@ultimat3/core 30.9.0 → 31.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +54 -58
- package/README.md +70 -27
- package/package.json +3 -2
- package/src/adapter-slot.ts +42 -0
- package/src/adapter.ts +24 -0
- package/src/audit.ts +31 -14
- package/src/aws-sigv4.ts +9 -3
- package/src/cache-vocabulary.ts +1 -1
- package/src/client-problem.ts +10 -3
- package/src/clock.ts +68 -14
- package/src/config-defaults.ts +4 -4
- package/src/config-keys.ts +1 -1
- package/src/config-removed.ts +11 -1
- package/src/config.ts +16 -20
- package/src/context.ts +2 -2
- package/src/cursor.ts +3 -11
- package/src/der.ts +65 -0
- package/src/error-render.ts +27 -1
- package/src/error-reporter-chain.ts +1 -1
- package/src/error-reporter-sentry-hooks.ts +85 -0
- package/src/error-reporter-sentry.ts +99 -7
- package/src/error-reporter.ts +39 -11
- package/src/errors.ts +3 -1
- package/src/exports/error-contract.ts +4 -14
- package/src/exports/observability.ts +57 -17
- package/src/exports/secrets.ts +4 -18
- package/src/failure-capture.ts +22 -13
- package/src/gate-shapes.ts +88 -0
- package/src/host-rules.ts +13 -1
- package/src/html-escape.ts +7 -1
- package/src/ids.ts +59 -10
- package/src/image/png-pixels.ts +14 -8
- package/src/index.ts +123 -136
- package/src/instrument-events.ts +272 -0
- package/src/instrument-semconv.ts +65 -0
- package/src/instrument-stacks.ts +38 -0
- package/src/instrument.ts +194 -0
- package/src/keyed-fingerprint.ts +7 -11
- package/src/lifecycle-signals.ts +5 -3
- package/src/lifecycle.ts +27 -0
- package/src/logger-record.ts +35 -0
- package/src/logger.ts +24 -16
- package/src/mcp-exposure.ts +17 -0
- package/src/metrics-semconv.ts +124 -0
- package/src/metrics.ts +19 -16
- package/src/otlp-batch.ts +78 -0
- package/src/otlp-log-exporter.ts +180 -0
- package/src/otlp-metric-exporter.ts +2 -1
- package/src/otlp-post.ts +22 -2
- package/src/otlp-span-exporter.ts +10 -59
- package/src/otlp.ts +27 -9
- package/src/outbound-instrument.ts +82 -0
- package/src/outbound.ts +5 -4
- package/src/page-meta.ts +6 -0
- package/src/page.ts +23 -5
- package/src/registrar.ts +269 -0
- package/src/route-vocabulary.ts +11 -2
- package/src/safe-url.ts +10 -8
- package/src/seal-errors.ts +14 -4
- package/src/seal-keys.ts +11 -7
- package/src/secret-source.ts +125 -0
- package/src/secrets-errors.ts +32 -12
- package/src/secrets-store.ts +30 -26
- package/src/sleep-clock.ts +70 -0
- package/src/telemetry.ts +90 -31
- package/src/type-pins.ts +19 -16
- package/src/log-tee.ts +0 -73
package/src/lifecycle.ts
CHANGED
|
@@ -69,6 +69,11 @@ let inflight = 0;
|
|
|
69
69
|
let lifetime = 0;
|
|
70
70
|
let registrations: Registration[] = [];
|
|
71
71
|
let drainPromise: Promise<void> | undefined;
|
|
72
|
+
/**
|
|
73
|
+
* Set when a drain gave up on work: at the deadline (`X_SHUTDOWN_TIMEOUT`), or when the drain itself
|
|
74
|
+
* threw and skipped the phases after it. A hook that THREW is not this: it ended, and said so.
|
|
75
|
+
*/
|
|
76
|
+
let abandoned = false;
|
|
72
77
|
let idleWaiters: (() => void)[] = [];
|
|
73
78
|
|
|
74
79
|
export function configureLifecycle(options: LifecycleOptions): void {
|
|
@@ -299,6 +304,7 @@ async function runPhase(phase: ShutdownPhase, reason: ShutdownReason): Promise<v
|
|
|
299
304
|
// SIGKILL this process — the every-deploy duplicate that draining exists to prevent — so
|
|
300
305
|
// the drain moves on and the hook is left running with nobody reading it. The cost of that
|
|
301
306
|
// choice is real and named in the cause: a write it had in flight may be half done.
|
|
307
|
+
abandoned = true;
|
|
302
308
|
report('warn', 'X_SHUTDOWN_TIMEOUT', {
|
|
303
309
|
code: 'X_SHUTDOWN_TIMEOUT',
|
|
304
310
|
cause: `the "${registration.name}" shutdown hook (phase: ${phase}) was still running at the ${deadlineMs}ms drain deadline and has been ABANDONED — the process exits without it, so anything it had in flight may be incomplete`,
|
|
@@ -331,6 +337,7 @@ async function runDrain(signal: string): Promise<void> {
|
|
|
331
337
|
const remaining = Math.max(0, reason.deadlineAt - systemClock.monotonic());
|
|
332
338
|
const idle = await waitForIdle(remaining);
|
|
333
339
|
if (!idle) {
|
|
340
|
+
abandoned = true;
|
|
334
341
|
report('warn', 'X_SHUTDOWN_TIMEOUT', {
|
|
335
342
|
code: 'X_SHUTDOWN_TIMEOUT',
|
|
336
343
|
cause: `${inflight} in-flight operations still running after ${deadlineMs}ms`,
|
|
@@ -345,6 +352,8 @@ async function runDrain(signal: string): Promise<void> {
|
|
|
345
352
|
// goes through `report`. If something does, the drain still ENDS: a rejected `drainPromise`
|
|
346
353
|
// is a memo that re-rejects for every later caller and an unhandled rejection that kills the
|
|
347
354
|
// process mid-drain, which is strictly worse than a drain that finished badly and said so.
|
|
355
|
+
// The phases after the throw never ran, so their work is abandoned as surely as a timeout's.
|
|
356
|
+
abandoned = true;
|
|
348
357
|
report('error', 'drain failed', { signal, error: thrown });
|
|
349
358
|
} finally {
|
|
350
359
|
state = 'stopped';
|
|
@@ -423,6 +432,23 @@ export function readyzPayload(options: { readonly deep?: boolean } = {}): Health
|
|
|
423
432
|
return { ok: body.ready, status: body.ready ? 200 : 503, body };
|
|
424
433
|
}
|
|
425
434
|
|
|
435
|
+
/**
|
|
436
|
+
* `EX_SOFTWARE` (sysexits.h): the drain ended, but work was abandoned at the deadline. Distinct from
|
|
437
|
+
* 0 so the platform's exit record, a crash-loop alert and a `docker ps` reader see what the warn
|
|
438
|
+
* line said; distinct from 1 so it is never mistaken for a boot that crashed.
|
|
439
|
+
*/
|
|
440
|
+
export const DRAIN_TIMEOUT_EXIT_CODE = 70;
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* What a process should exit with once `drain()` has settled: `DRAIN_TIMEOUT_EXIT_CODE` when any
|
|
444
|
+
* hook or in-flight operation was abandoned at the deadline (`X_SHUTDOWN_TIMEOUT`), or the drain
|
|
445
|
+
* threw before its last phase, else 0. The
|
|
446
|
+
* one answer for every exit after a drain — `installSignalHandlers` and the CLI's hold both read it.
|
|
447
|
+
*/
|
|
448
|
+
export function drainExitCode(): 0 | typeof DRAIN_TIMEOUT_EXIT_CODE {
|
|
449
|
+
return abandoned ? DRAIN_TIMEOUT_EXIT_CODE : 0;
|
|
450
|
+
}
|
|
451
|
+
|
|
426
452
|
/** Test-only: forget all hooks and return to `starting`. */
|
|
427
453
|
export function resetLifecycle(): void {
|
|
428
454
|
deadlineMs = DEFAULT_DEADLINE_MS;
|
|
@@ -437,6 +463,7 @@ export function resetLifecycle(): void {
|
|
|
437
463
|
lifetime += 1;
|
|
438
464
|
registrations = [];
|
|
439
465
|
drainPromise = undefined;
|
|
466
|
+
abandoned = false;
|
|
440
467
|
idleWaiters = [];
|
|
441
468
|
clearReadinessChecks();
|
|
442
469
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Single responsibility: publish one written process-logger line as `log.record` on the
|
|
2
|
+
// instrumentation bus — the feed the OTLP logs exporter and any app subscriber read. Total: a
|
|
3
|
+
// subscriber's throw never reaches the `log.*` call that wrote the line.
|
|
4
|
+
|
|
5
|
+
import type { Clock } from './clock';
|
|
6
|
+
import { instrument } from './instrument';
|
|
7
|
+
import type { LogLevel } from './logger';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* `log.record`, after the line is written. Swallowed, unlike every other event on the bus: a log
|
|
11
|
+
* call is TOTAL (see `serialiseValue`), and a subscriber that throws must not turn `log.error`
|
|
12
|
+
* inside some `catch` into a second failure replacing the first.
|
|
13
|
+
*/
|
|
14
|
+
export function publishRecord(
|
|
15
|
+
clock: Clock,
|
|
16
|
+
level: Exclude<LogLevel, 'silent'>,
|
|
17
|
+
message: string,
|
|
18
|
+
fields: Readonly<Record<string, unknown>>,
|
|
19
|
+
): void {
|
|
20
|
+
try {
|
|
21
|
+
instrument('log.record', { at: epochMs(clock), level, message, fields });
|
|
22
|
+
} catch {
|
|
23
|
+
// The line is already on the streams; the subscriber's failure is its own.
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The clock's reading in epoch ms, `0` for a clock that cannot be read — `timestamp`'s rule. */
|
|
28
|
+
function epochMs(clock: Clock): number {
|
|
29
|
+
try {
|
|
30
|
+
const at = clock.now().getTime();
|
|
31
|
+
return Number.isFinite(at) ? at : 0;
|
|
32
|
+
} catch {
|
|
33
|
+
return 0;
|
|
34
|
+
}
|
|
35
|
+
}
|
package/src/logger.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
// Single responsibility: structured JSON logging. One line per event, machine-readable by
|
|
2
|
-
// default because the primary reader is an agent tailing `x logs --json`.
|
|
2
|
+
// default because the primary reader is an agent tailing `x logs --json`. Every process-logger
|
|
3
|
+
// line is also published as `log.record` on the instrumentation bus — the OTLP logs exporter's feed.
|
|
3
4
|
|
|
5
|
+
import { adapterSlot } from './adapter-slot';
|
|
4
6
|
import { assert } from './assert';
|
|
5
|
-
import { type Clock,
|
|
7
|
+
import { type Clock, liveClock } from './clock';
|
|
6
8
|
import { renderCauseValue } from './error-render';
|
|
7
9
|
import { isUltimateError } from './errors';
|
|
8
|
-
import {
|
|
10
|
+
import { subscribed } from './instrument';
|
|
11
|
+
import { publishRecord } from './logger-record';
|
|
9
12
|
import { isSecret, REDACTED } from './secret';
|
|
10
13
|
|
|
11
14
|
// Re-exported, not redefined: `secret.ts` owns the placeholder because a `Secret` has to render
|
|
@@ -184,15 +187,18 @@ export function setLogStream(stream: 'stdout' | 'stderr'): void {
|
|
|
184
187
|
logStream = stream;
|
|
185
188
|
}
|
|
186
189
|
|
|
187
|
-
/** What `
|
|
190
|
+
/** What `installLogSink` installs: one complete JSON line, and the level it was written at. */
|
|
188
191
|
export type LogSink = (line: string, level: LogLevel) => void;
|
|
189
192
|
|
|
190
|
-
|
|
193
|
+
// `undefined` is a frame too: "the process's streams", so a test whose subject IS the streams can
|
|
194
|
+
// lift the preload's sink for its own span without knowing what the preload installed.
|
|
195
|
+
const logSinks = adapterSlot<LogSink | undefined>(() => undefined);
|
|
191
196
|
|
|
192
197
|
/**
|
|
193
|
-
* TEST SEAM. Every line with no explicit `writer` goes to `sink` INSTEAD of the process's streams
|
|
194
|
-
*
|
|
195
|
-
*
|
|
198
|
+
* TEST SEAM. Every line with no explicit `writer` goes to `sink` INSTEAD of the process's streams
|
|
199
|
+
* (`undefined`: to the streams), until the returned release runs. A stack of frames, each removed
|
|
200
|
+
* only by its own release — one `bun test` process is shared, so a test's `finally` hands back
|
|
201
|
+
* whatever an outer harness installed without ever having read it, in any order.
|
|
196
202
|
*
|
|
197
203
|
* It exists for two callers. A test preload installs a sink that drops every line, so a green run
|
|
198
204
|
* prints its reporter and nothing else; and a test that asserts on what the PROCESS logger wrote
|
|
@@ -200,10 +206,8 @@ let logSink: LogSink | undefined;
|
|
|
200
206
|
* `writer` never reaches it, and the level is untouched: this decides where a line goes, never
|
|
201
207
|
* whether it is written.
|
|
202
208
|
*/
|
|
203
|
-
export function
|
|
204
|
-
|
|
205
|
-
logSink = sink;
|
|
206
|
-
return previous;
|
|
209
|
+
export function installLogSink(sink: LogSink | undefined): () => void {
|
|
210
|
+
return logSinks.install(sink);
|
|
207
211
|
}
|
|
208
212
|
|
|
209
213
|
/**
|
|
@@ -221,12 +225,11 @@ export function setLogSink(sink: LogSink | undefined): LogSink | undefined {
|
|
|
221
225
|
*/
|
|
222
226
|
function defaultWriter(line: string, level: LogLevel): void {
|
|
223
227
|
streamWriter(line, level);
|
|
224
|
-
// After the streams, so a sink can never cost a line its stdout (`addLogSink`, `log-tee.ts`).
|
|
225
|
-
teeLogLine(line, level, streamWriter);
|
|
226
228
|
}
|
|
227
229
|
|
|
228
|
-
/** The process's streams, or the `
|
|
230
|
+
/** The process's streams, or the `installLogSink` seam standing in for them. */
|
|
229
231
|
function streamWriter(line: string, level: LogLevel): void {
|
|
232
|
+
const logSink = logSinks.current();
|
|
230
233
|
if (logSink !== undefined) {
|
|
231
234
|
logSink(line, level);
|
|
232
235
|
return;
|
|
@@ -433,7 +436,7 @@ function unreserved(fields: Record<string, unknown>): Record<string, unknown> {
|
|
|
433
436
|
export function structuredLogger(options?: LoggerOptions): Logger {
|
|
434
437
|
const level = options?.level === undefined ? envLevel() : resolveLevel(options.level);
|
|
435
438
|
const bound = options?.fields ?? {};
|
|
436
|
-
const clock = options?.clock ??
|
|
439
|
+
const clock = options?.clock ?? liveClock;
|
|
437
440
|
const writer = options?.writer ?? defaultWriter;
|
|
438
441
|
const threshold = LEVEL_WEIGHT[level];
|
|
439
442
|
|
|
@@ -451,6 +454,11 @@ export function structuredLogger(options?: LoggerOptions): Logger {
|
|
|
451
454
|
...unreserved(caller),
|
|
452
455
|
};
|
|
453
456
|
writer(renderLine(line, lineLevel, message, line.ts), lineLevel);
|
|
457
|
+
// `log.record`, after the streams, so a subscriber can never cost a line its stdout. The process
|
|
458
|
+
// logger's population only: a logger given its own `writer` is a test's or a command's answer.
|
|
459
|
+
if (writer === defaultWriter && subscribed('log.record')) {
|
|
460
|
+
publishRecord(clock, lineLevel as Exclude<LogLevel, 'silent'>, message, caller);
|
|
461
|
+
}
|
|
454
462
|
}
|
|
455
463
|
|
|
456
464
|
return {
|
package/src/mcp-exposure.ts
CHANGED
|
@@ -48,6 +48,12 @@ export interface McpListParams {
|
|
|
48
48
|
export interface McpExposureDeclaration {
|
|
49
49
|
/** Opt-in: only a literal `true` makes the primitive a tool. Silence exposes nothing. */
|
|
50
50
|
readonly expose: boolean;
|
|
51
|
+
/**
|
|
52
|
+
* Offered to this app's OWN `agent()`s without being published on its MCP surface. A literal
|
|
53
|
+
* `true` only. For a capability the app's agents may use and its `/mcp` must not re-serve — a
|
|
54
|
+
* remote server's tools through `mcpTools()`. `expose: true` already offers to both.
|
|
55
|
+
*/
|
|
56
|
+
readonly agents?: boolean;
|
|
51
57
|
/**
|
|
52
58
|
* Contract text, NOT UI text — deliberately outside `t()`. It becomes the OpenAPI operation
|
|
53
59
|
* `summary`, and `buildOpenApi`'s bytes are what `x verify` diffs for contract drift. Resolving
|
|
@@ -107,3 +113,14 @@ export function isMcpExposed(
|
|
|
107
113
|
): boolean {
|
|
108
114
|
return declared?.expose === true;
|
|
109
115
|
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Whether an in-app `agent()` may be offered the primitive: exposed (an in-app agent and an
|
|
119
|
+
* external one see the same catalogue of exposed actions), or declared `agents: true` — offered
|
|
120
|
+
* here and published nowhere. Literal `true` either way, for `isMcpExposed`'s reason.
|
|
121
|
+
*/
|
|
122
|
+
export function isAgentOffered(
|
|
123
|
+
declared: Partial<Pick<McpExposureDeclaration, 'expose' | 'agents'>> | undefined,
|
|
124
|
+
): boolean {
|
|
125
|
+
return isMcpExposed(declared) || declared?.agents === true;
|
|
126
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// Single responsibility: the semconv histograms the framework records from its own events —
|
|
2
|
+
// statement duration, job duration, LLM token usage — as ONE subscriber on the instrumentation bus.
|
|
3
|
+
// Nothing records them inline: `subscribeSemconvMetrics()` is installed at boot, like an exporter.
|
|
4
|
+
|
|
5
|
+
import { isUltimateError } from './errors';
|
|
6
|
+
import { subscribe } from './instrument';
|
|
7
|
+
import type { AiLlmEvent, DbStatementEvent, JobPerformEvent } from './instrument-events';
|
|
8
|
+
import { SEMCONV_METRICS, SEMCONV_VALUES } from './instrument-semconv';
|
|
9
|
+
import { histogram } from './metrics';
|
|
10
|
+
|
|
11
|
+
/** semconv's advisory boundaries for `db.client.operation.duration`, seconds. */
|
|
12
|
+
const DB_DURATION_BOUNDS = [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10] as const;
|
|
13
|
+
/** semconv's advisory boundaries for `gen_ai.client.token.usage`. */
|
|
14
|
+
const TOKEN_BOUNDS = [
|
|
15
|
+
1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216, 67108864,
|
|
16
|
+
] as const;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Declared on the first subscribe, never at import: a declared instrument is a `# TYPE` line on
|
|
20
|
+
* every `/metrics` scrape, and an app that never installs these must not advertise them.
|
|
21
|
+
*/
|
|
22
|
+
function instruments() {
|
|
23
|
+
return {
|
|
24
|
+
dbDuration: histogram(SEMCONV_METRICS.dbClientOperationDuration, {
|
|
25
|
+
unit: 's',
|
|
26
|
+
description: 'Duration of database client operations (semconv db.client.operation.duration)',
|
|
27
|
+
bounds: DB_DURATION_BOUNDS,
|
|
28
|
+
}),
|
|
29
|
+
jobDuration: histogram(SEMCONV_METRICS.jobDuration, {
|
|
30
|
+
unit: 's',
|
|
31
|
+
description: 'Background job perform duration, by queue and outcome',
|
|
32
|
+
}),
|
|
33
|
+
tokenUsage: histogram(SEMCONV_METRICS.genAiClientTokenUsage, {
|
|
34
|
+
unit: '{token}',
|
|
35
|
+
description: 'Tokens used per LLM call, by token type (semconv gen_ai.client.token.usage)',
|
|
36
|
+
bounds: TOKEN_BOUNDS,
|
|
37
|
+
}),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
type Instruments = ReturnType<typeof instruments>;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* A BOUNDED operation label: the statement's leading keyword when it is one of these, else
|
|
45
|
+
* `other`. The text itself never becomes a label — one series per distinct query is the
|
|
46
|
+
* cardinality ceiling reached by lunchtime.
|
|
47
|
+
*/
|
|
48
|
+
const OPERATIONS: ReadonlySet<string> = new Set([
|
|
49
|
+
'select',
|
|
50
|
+
'insert',
|
|
51
|
+
'update',
|
|
52
|
+
'delete',
|
|
53
|
+
'with',
|
|
54
|
+
'begin',
|
|
55
|
+
'commit',
|
|
56
|
+
'rollback',
|
|
57
|
+
'savepoint',
|
|
58
|
+
'release',
|
|
59
|
+
'set',
|
|
60
|
+
'lock',
|
|
61
|
+
'copy',
|
|
62
|
+
'listen',
|
|
63
|
+
'notify',
|
|
64
|
+
]);
|
|
65
|
+
|
|
66
|
+
export function dbOperationOf(text: string): string {
|
|
67
|
+
const verb = /^\s*([a-z]+)\b/i.exec(text)?.[1]?.toLowerCase() ?? '';
|
|
68
|
+
return OPERATIONS.has(verb) ? verb : 'other';
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** semconv `error.type`: the `X_*` code, else `_OTHER`. Absent on success. */
|
|
72
|
+
function errorType(error: unknown): string {
|
|
73
|
+
return isUltimateError(error) ? error.code : '_OTHER';
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function recordStatement({ dbDuration }: Instruments, event: DbStatementEvent): void {
|
|
77
|
+
dbDuration.record(event.durationMs / 1000, {
|
|
78
|
+
db_system_name: SEMCONV_VALUES.dbSystemPostgres,
|
|
79
|
+
db_operation_name: dbOperationOf(event.text),
|
|
80
|
+
...(event.error === undefined ? {} : { error_type: errorType(event.error) }),
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function recordJob({ jobDuration }: Instruments, event: JobPerformEvent): void {
|
|
85
|
+
jobDuration.record(event.durationMs / 1000, {
|
|
86
|
+
queue: event.queue,
|
|
87
|
+
outcome: event.error === undefined ? 'ok' : 'error',
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function recordTokens({ tokenUsage }: Instruments, event: AiLlmEvent): void {
|
|
92
|
+
// A cache hit called no model and used no tokens: recording its counts would bill them twice.
|
|
93
|
+
if (event.cacheHit) return;
|
|
94
|
+
const labels = {
|
|
95
|
+
gen_ai_operation_name: SEMCONV_VALUES.genAiOperationChat,
|
|
96
|
+
gen_ai_provider_name: event.provider,
|
|
97
|
+
gen_ai_request_model: event.model,
|
|
98
|
+
};
|
|
99
|
+
tokenUsage.record(event.inputTokens, {
|
|
100
|
+
...labels,
|
|
101
|
+
gen_ai_token_type: SEMCONV_VALUES.genAiTokenInput,
|
|
102
|
+
});
|
|
103
|
+
tokenUsage.record(event.outputTokens, {
|
|
104
|
+
...labels,
|
|
105
|
+
gen_ai_token_type: SEMCONV_VALUES.genAiTokenOutput,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Subscribe the semconv histograms. Returns the unsubscribe — wire it into the drain, or call it
|
|
111
|
+
* between tests. Called twice it subscribes twice and every point is recorded twice, so boot calls
|
|
112
|
+
* it ONCE.
|
|
113
|
+
*/
|
|
114
|
+
export function subscribeSemconvMetrics(): () => void {
|
|
115
|
+
const declared = instruments();
|
|
116
|
+
const offs = [
|
|
117
|
+
subscribe('db.statement', (event) => recordStatement(declared, event.payload)),
|
|
118
|
+
subscribe('job.perform', (event) => recordJob(declared, event.payload)),
|
|
119
|
+
subscribe('ai.llm', (event) => recordTokens(declared, event.payload)),
|
|
120
|
+
];
|
|
121
|
+
return () => {
|
|
122
|
+
for (const off of offs) off();
|
|
123
|
+
};
|
|
124
|
+
}
|
package/src/metrics.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
// Single responsibility: the OpenTelemetry-shaped metrics seam — counter, gauge and histogram
|
|
2
|
-
// aggregated in process, read through one `collectMetrics()
|
|
3
|
-
//
|
|
2
|
+
// aggregated in process, read through one `collectMetrics()`, and pushed as `metric.export` on the
|
|
3
|
+
// instrumentation bus. An exporter is a subscriber there, like the span and log exporters: always
|
|
4
|
+
// on, free until something subscribes, and the wire format supplied by a driver, never here.
|
|
4
5
|
|
|
5
6
|
import { assert } from './assert';
|
|
6
7
|
import { type Clock, systemClock } from './clock';
|
|
7
8
|
import { renderThrowable } from './error-render';
|
|
9
|
+
import { instrument, subscribed } from './instrument';
|
|
8
10
|
import { logger } from './logger';
|
|
9
11
|
import { finite, MetricValueInvalidError } from './metric-errors';
|
|
10
12
|
import { declare, type Instrument, instruments } from './metric-registry';
|
|
@@ -47,18 +49,15 @@ export type {
|
|
|
47
49
|
ReadableMetric,
|
|
48
50
|
} from './metrics-types';
|
|
49
51
|
|
|
50
|
-
export const noopMetricExporter: MetricExporter = Object.freeze({
|
|
51
|
-
export(): void {
|
|
52
|
-
// Intentionally empty: instruments are always live, and free until an exporter is configured.
|
|
53
|
-
},
|
|
54
|
-
});
|
|
55
|
-
|
|
56
52
|
export interface MemoryMetricExporter extends MetricExporter {
|
|
57
53
|
readonly collections: readonly MetricCollection[];
|
|
58
54
|
reset(): void;
|
|
59
55
|
}
|
|
60
56
|
|
|
61
|
-
/**
|
|
57
|
+
/**
|
|
58
|
+
* For tests: assert an export tick without a collector — `subscribe('metric.export', (event) =>
|
|
59
|
+
* memory.export(event.payload))`. `metricsText()` is the shipped read.
|
|
60
|
+
*/
|
|
62
61
|
export function memoryMetricExporter(): MemoryMetricExporter {
|
|
63
62
|
const collections: MetricCollection[] = [];
|
|
64
63
|
return {
|
|
@@ -72,18 +71,20 @@ export function memoryMetricExporter(): MemoryMetricExporter {
|
|
|
72
71
|
};
|
|
73
72
|
}
|
|
74
73
|
|
|
74
|
+
/**
|
|
75
|
+
* Configuration only. `exporter` left in 31.0.0: an exporter is a `metric.export` subscriber on the
|
|
76
|
+
* instrumentation bus, released by its own unsubscribe — never a slot one boot hands back under
|
|
77
|
+
* another's feet.
|
|
78
|
+
*/
|
|
75
79
|
export interface MetricsOptions {
|
|
76
|
-
readonly exporter?: MetricExporter | undefined;
|
|
77
80
|
readonly clock?: Clock | undefined;
|
|
78
81
|
readonly enabled?: boolean | undefined;
|
|
79
82
|
}
|
|
80
83
|
|
|
81
|
-
let exporter: MetricExporter = noopMetricExporter;
|
|
82
84
|
let clock: Clock = systemClock;
|
|
83
85
|
let enabled = true;
|
|
84
86
|
|
|
85
87
|
export function configureMetrics(options: MetricsOptions): void {
|
|
86
|
-
if (options.exporter !== undefined) exporter = options.exporter;
|
|
87
88
|
if (options.clock !== undefined) clock = options.clock;
|
|
88
89
|
if (options.enabled !== undefined) enabled = options.enabled;
|
|
89
90
|
}
|
|
@@ -94,7 +95,6 @@ export function configureMetrics(options: MetricsOptions): void {
|
|
|
94
95
|
* writing into a registry nothing reads.
|
|
95
96
|
*/
|
|
96
97
|
export function resetMetrics(): void {
|
|
97
|
-
exporter = noopMetricExporter;
|
|
98
98
|
clock = systemClock;
|
|
99
99
|
enabled = true;
|
|
100
100
|
for (const instrument of instruments.values()) {
|
|
@@ -229,10 +229,13 @@ export function collectMetrics(): MetricCollection {
|
|
|
229
229
|
};
|
|
230
230
|
}
|
|
231
231
|
|
|
232
|
-
/**
|
|
232
|
+
/**
|
|
233
|
+
* One push tick: the collection, published as `metric.export`. Nothing is collected while nobody
|
|
234
|
+
* subscribes. A driver decides when — `startMetricExport()` is the batteries-included when.
|
|
235
|
+
*/
|
|
233
236
|
export function exportMetrics(): void {
|
|
234
|
-
if (!enabled) return;
|
|
235
|
-
|
|
237
|
+
if (!enabled || !subscribed('metric.export')) return;
|
|
238
|
+
instrument('metric.export', collectMetrics());
|
|
236
239
|
}
|
|
237
240
|
|
|
238
241
|
/**
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Single responsibility: the bounded batch queue the per-item OTLP exporters (spans, logs) share —
|
|
2
|
+
// at most one POST in flight, drop-OLDEST past `maxQueueSize`, a full batch sent at once and the
|
|
3
|
+
// rest on an unref'd timer. One copy, because the span exporter's held 100k spans once.
|
|
4
|
+
|
|
5
|
+
export interface OtlpBatcherOptions<T> {
|
|
6
|
+
readonly maxBatchSize: number;
|
|
7
|
+
readonly maxQueueSize: number;
|
|
8
|
+
readonly flushIntervalMs: number;
|
|
9
|
+
/** Deliver one batch. Must not reject — `postOtlp` degrades to a log line, and so must this. */
|
|
10
|
+
readonly post: (batch: readonly T[]) => Promise<void>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface OtlpBatcher<T> {
|
|
14
|
+
push(item: T): void;
|
|
15
|
+
/** Send whatever is queued now. Resolves once the POSTs settle. */
|
|
16
|
+
flush(): Promise<void>;
|
|
17
|
+
/** Stop the timer and flush. */
|
|
18
|
+
shutdown(): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function otlpBatcher<T>(options: OtlpBatcherOptions<T>): OtlpBatcher<T> {
|
|
22
|
+
const { maxBatchSize, maxQueueSize, flushIntervalMs, post } = options;
|
|
23
|
+
const queue: T[] = [];
|
|
24
|
+
/** The ONE batch in flight, or `undefined`. Never a chain: see `pump`. */
|
|
25
|
+
let sending: Promise<void> | undefined;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* At most ONE batch in flight, and at most `maxBatchSize` items in it. Items WAIT IN the queue
|
|
29
|
+
* while a POST is unsettled, where drop-oldest applies, so what is held is `maxQueueSize` plus
|
|
30
|
+
* one batch — a stalled collector cannot grow memory. One at a time also keeps batches in
|
|
31
|
+
* order, so a parent span never arrives after its child.
|
|
32
|
+
*/
|
|
33
|
+
const pump = (): Promise<void> => {
|
|
34
|
+
if (sending !== undefined) return sending;
|
|
35
|
+
const batch = queue.splice(0, maxBatchSize);
|
|
36
|
+
if (batch.length === 0) return Promise.resolve();
|
|
37
|
+
const current = post(batch).then(
|
|
38
|
+
() => undefined,
|
|
39
|
+
() => undefined,
|
|
40
|
+
);
|
|
41
|
+
sending = current.then(() => {
|
|
42
|
+
sending = undefined;
|
|
43
|
+
// A full batch waiting behind a slow POST goes next without waiting for the timer.
|
|
44
|
+
if (queue.length >= maxBatchSize) void pump();
|
|
45
|
+
});
|
|
46
|
+
return sending;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** Everything queued NOW, batch by batch. Bounded, so a busy exporter cannot keep it looping. */
|
|
50
|
+
const drainQueue = async (): Promise<void> => {
|
|
51
|
+
let rounds = Math.ceil(queue.length / maxBatchSize) + 1;
|
|
52
|
+
while (rounds > 0) {
|
|
53
|
+
rounds -= 1;
|
|
54
|
+
await pump();
|
|
55
|
+
if (queue.length === 0 && sending === undefined) return;
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
// Unref'd, so a pending flush never holds a draining process open — `shutdown()` decides the
|
|
60
|
+
// last batch leaves. `pump`, never `drainQueue`: while a POST is stalled `pump` answers the send
|
|
61
|
+
// already in flight and allocates nothing.
|
|
62
|
+
const timer = setInterval(() => void pump(), flushIntervalMs);
|
|
63
|
+
timer.unref();
|
|
64
|
+
|
|
65
|
+
return {
|
|
66
|
+
push(item: T): void {
|
|
67
|
+
// Drop the OLDEST: the items an operator wants during an incident are the ones happening now.
|
|
68
|
+
if (queue.length >= maxQueueSize) queue.shift();
|
|
69
|
+
queue.push(item);
|
|
70
|
+
if (queue.length >= maxBatchSize) void pump();
|
|
71
|
+
},
|
|
72
|
+
flush: drainQueue,
|
|
73
|
+
async shutdown(): Promise<void> {
|
|
74
|
+
clearInterval(timer);
|
|
75
|
+
await drainQueue();
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
}
|