@ultimat3/core 30.9.0 → 31.1.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.
Files changed (67) hide show
  1. package/CLAUDE.md +54 -58
  2. package/README.md +70 -27
  3. package/package.json +3 -2
  4. package/src/adapter-slot.ts +42 -0
  5. package/src/adapter.ts +24 -0
  6. package/src/audit.ts +31 -14
  7. package/src/aws-sigv4.ts +9 -3
  8. package/src/cache-vocabulary.ts +1 -1
  9. package/src/client-problem.ts +10 -3
  10. package/src/clock.ts +68 -14
  11. package/src/config-defaults.ts +4 -4
  12. package/src/config-keys.ts +1 -1
  13. package/src/config-removed.ts +11 -1
  14. package/src/config.ts +16 -20
  15. package/src/context.ts +2 -2
  16. package/src/cursor.ts +3 -11
  17. package/src/der.ts +65 -0
  18. package/src/error-render.ts +27 -1
  19. package/src/error-reporter-chain.ts +1 -1
  20. package/src/error-reporter-sentry-hooks.ts +85 -0
  21. package/src/error-reporter-sentry.ts +99 -7
  22. package/src/error-reporter.ts +39 -11
  23. package/src/errors.ts +3 -1
  24. package/src/exports/error-contract.ts +4 -14
  25. package/src/exports/observability.ts +57 -17
  26. package/src/exports/secrets.ts +4 -18
  27. package/src/failure-capture.ts +22 -13
  28. package/src/gate-shapes.ts +88 -0
  29. package/src/host-rules.ts +13 -1
  30. package/src/html-escape.ts +7 -1
  31. package/src/ids.ts +59 -10
  32. package/src/image/png-pixels.ts +14 -8
  33. package/src/index.ts +123 -136
  34. package/src/instrument-events.ts +272 -0
  35. package/src/instrument-semconv.ts +65 -0
  36. package/src/instrument-stacks.ts +38 -0
  37. package/src/instrument.ts +194 -0
  38. package/src/keyed-fingerprint.ts +7 -11
  39. package/src/lifecycle-signals.ts +5 -3
  40. package/src/lifecycle.ts +27 -0
  41. package/src/logger-record.ts +35 -0
  42. package/src/logger.ts +24 -16
  43. package/src/mcp-exposure.ts +17 -0
  44. package/src/metrics-semconv.ts +124 -0
  45. package/src/metrics.ts +19 -16
  46. package/src/otlp-batch.ts +78 -0
  47. package/src/otlp-log-exporter.ts +180 -0
  48. package/src/otlp-metric-exporter.ts +2 -1
  49. package/src/otlp-post.ts +22 -2
  50. package/src/otlp-span-exporter.ts +10 -59
  51. package/src/otlp.ts +27 -9
  52. package/src/outbound-instrument.ts +82 -0
  53. package/src/outbound.ts +5 -4
  54. package/src/page-meta.ts +6 -0
  55. package/src/page.ts +23 -5
  56. package/src/registrar.ts +269 -0
  57. package/src/route-vocabulary.ts +11 -2
  58. package/src/safe-url.ts +10 -8
  59. package/src/seal-errors.ts +14 -4
  60. package/src/seal-keys.ts +11 -7
  61. package/src/secret-source.ts +125 -0
  62. package/src/secrets-errors.ts +32 -12
  63. package/src/secrets-store.ts +30 -26
  64. package/src/sleep-clock.ts +70 -0
  65. package/src/telemetry.ts +90 -31
  66. package/src/type-pins.ts +19 -16
  67. package/src/log-tee.ts +0 -73
@@ -0,0 +1,272 @@
1
+ // Single responsibility: the framework's instrumentation vocabulary — every event name the bus
2
+ // carries, the payload each one delivers, and the span kind its emitter opens. Payloads are
3
+ // declared HERE, structurally, because core is tier 0: the emitting package re-exports the type,
4
+ // it never owns a second shape. An app adds its own names by augmenting `InstrumentEventMap`.
5
+
6
+ import type { LogLevel } from './logger';
7
+ import type { MetricCollection } from './metrics-types';
8
+ import type { ReadableSpan, SpanKind } from './telemetry';
9
+
10
+ /** What every timed event carries: wall time from start to settle, and the failure, if any. */
11
+ export interface TimedEvent {
12
+ readonly durationMs: number;
13
+ /** What the work threw, as the caller is about to receive it. Absent on success. */
14
+ readonly error?: unknown;
15
+ }
16
+
17
+ export interface HttpRequestEvent extends TimedEvent {
18
+ readonly method: string;
19
+ /** The matched route PATTERN (`/r/:token`), never the URL — `undefined` when nothing matched. */
20
+ readonly route: string | undefined;
21
+ readonly status: number;
22
+ }
23
+
24
+ /** Who compiled a statement — `@ultimat3/entity` knows it, hand-written SQL does not. */
25
+ export interface StatementAttribution {
26
+ readonly entity: string;
27
+ readonly op: string;
28
+ }
29
+
30
+ export interface DbStatementEvent extends TimedEvent {
31
+ /** Parameterised (`$1..$n`) — safe to log. */
32
+ readonly text: string;
33
+ /** Bound values, in order. May carry user data: a subscriber that logs them must redact. */
34
+ readonly values: readonly unknown[];
35
+ /** Rows returned or affected; `0` when the statement threw. */
36
+ readonly rows: number;
37
+ readonly attribution?: StatementAttribution | undefined;
38
+ /** The innermost `expectedQueryLoop()` reason this statement ran inside. */
39
+ readonly expected?: string | undefined;
40
+ /**
41
+ * The stack the statement was SENT from, captured before the driver's first `await` — present
42
+ * only while a holder has `captureStatementStacks()` on (the `statements` test fixture); never in
43
+ * production, where a stack per statement is cost nobody reads.
44
+ */
45
+ readonly callerStack?: string | undefined;
46
+ }
47
+
48
+ export type EntityRowOp = 'insert' | 'update' | 'delete';
49
+
50
+ export interface EntityRowEvent {
51
+ /** Entity name as declared, never a table name. */
52
+ readonly entity: string;
53
+ readonly op: EntityRowOp;
54
+ readonly before: Readonly<Record<string, unknown>> | null;
55
+ readonly after: Readonly<Record<string, unknown>> | null;
56
+ /** `currentWriteOrigin()` at the write — the digest of the request's idempotency key. */
57
+ readonly write?: string | undefined;
58
+ }
59
+
60
+ export interface EntityBulkEvent {
61
+ readonly entity: string;
62
+ readonly op: 'delete' | 'update';
63
+ readonly rows: number;
64
+ }
65
+
66
+ export interface EntityCrossTenantEvent {
67
+ readonly reason: string;
68
+ }
69
+
70
+ export interface PolicyDecisionEvent {
71
+ readonly label: string;
72
+ readonly allowed: boolean;
73
+ readonly code: string | null;
74
+ readonly reason: string | null;
75
+ readonly actorId: string | null;
76
+ readonly actorKind: string | null;
77
+ readonly orgId: string | null;
78
+ readonly surface: string | null;
79
+ readonly deciding: string | null;
80
+ }
81
+
82
+ export interface ActionInvokeEvent extends TimedEvent {
83
+ readonly action: string;
84
+ }
85
+
86
+ export interface QueryReadEvent extends TimedEvent {
87
+ readonly query: string;
88
+ }
89
+
90
+ export interface JobEnqueueEvent {
91
+ readonly job: string;
92
+ readonly queue: string;
93
+ readonly id: string;
94
+ }
95
+
96
+ export interface JobPerformEvent extends TimedEvent {
97
+ readonly job: string;
98
+ readonly queue: string;
99
+ readonly id: string;
100
+ /** 1-based. */
101
+ readonly attempt: number;
102
+ }
103
+
104
+ export interface AiLlmEvent extends TimedEvent {
105
+ readonly provider: string;
106
+ readonly model: string;
107
+ readonly inputTokens: number;
108
+ readonly outputTokens: number;
109
+ readonly cacheHit: boolean;
110
+ }
111
+
112
+ export interface RenderPageEvent extends TimedEvent {
113
+ readonly route: string;
114
+ }
115
+
116
+ export interface RenderIsrRegenerateEvent extends TimedEvent {
117
+ readonly route: string;
118
+ readonly path: string;
119
+ }
120
+
121
+ export interface RenderHoleEvent extends TimedEvent {
122
+ readonly route: string;
123
+ readonly hole: string;
124
+ }
125
+
126
+ export interface OutboundRequestEvent extends TimedEvent {
127
+ /** The bounded label the call was made with (`'resend'`). */
128
+ readonly vendor: string;
129
+ readonly method: string;
130
+ readonly host: string;
131
+ /** The last answer's status; absent when no answer arrived. */
132
+ readonly status?: number | undefined;
133
+ }
134
+
135
+ export interface MailDeliverEvent extends TimedEvent {
136
+ readonly transport: string;
137
+ /** A count — addresses are personal data and never ride an event. */
138
+ readonly recipients: number;
139
+ }
140
+
141
+ export interface StorageEvent extends TimedEvent {
142
+ readonly disk: string;
143
+ readonly key: string;
144
+ readonly bytes?: number | undefined;
145
+ }
146
+
147
+ export interface CacheLookupEvent {
148
+ readonly tier: string;
149
+ readonly key: string;
150
+ }
151
+
152
+ export interface CacheInvalidateEvent extends TimedEvent {
153
+ readonly tags: readonly string[];
154
+ /**
155
+ * What triggered the bust: the name of the span active when `invalidateTags` was called, else
156
+ * `'invalidateTags'`. Read at the call, because a subscriber runs after that span has moved on.
157
+ */
158
+ readonly source?: string | undefined;
159
+ /** Everything the fan-out actually cleared: tier keys, ISR paths, live queries. */
160
+ readonly busted: readonly string[];
161
+ /** Tier failures, verbatim — a partial bust must not read as a clean one. */
162
+ readonly errors: readonly { readonly tier: string; readonly message: string }[];
163
+ }
164
+
165
+ export interface CacheTierFailureEvent {
166
+ readonly tier: string;
167
+ readonly op: 'get' | 'set' | 'del';
168
+ readonly key: string;
169
+ readonly code?: string | undefined;
170
+ readonly message: string;
171
+ }
172
+
173
+ /**
174
+ * One line the process logger wrote — after redaction, so a subscriber never sees a secret. The
175
+ * active span is the emitter's: a subscriber reads `currentSpanContext()` for trace correlation.
176
+ */
177
+ export interface LogRecordEvent {
178
+ /** Epoch milliseconds. */
179
+ readonly at: number;
180
+ readonly level: Exclude<LogLevel, 'silent'>;
181
+ readonly message: string;
182
+ /** The line's fields, redacted, the context's `requestId`/`traceId` included. */
183
+ readonly fields: Readonly<Record<string, unknown>>;
184
+ }
185
+
186
+ /** Every event the framework emits, name → payload. Closed: `INSTRUMENT_EVENTS` must list each. */
187
+ export interface FrameworkEventMap {
188
+ 'http.request': HttpRequestEvent;
189
+ 'db.statement': DbStatementEvent;
190
+ 'entity.row': EntityRowEvent;
191
+ 'entity.bulk': EntityBulkEvent;
192
+ 'entity.cross_tenant': EntityCrossTenantEvent;
193
+ 'policy.decision': PolicyDecisionEvent;
194
+ 'action.invoke': ActionInvokeEvent;
195
+ 'query.read': QueryReadEvent;
196
+ 'job.enqueue': JobEnqueueEvent;
197
+ 'job.perform': JobPerformEvent;
198
+ 'ai.llm': AiLlmEvent;
199
+ 'render.page': RenderPageEvent;
200
+ 'render.isr.regenerate': RenderIsrRegenerateEvent;
201
+ 'render.hole': RenderHoleEvent;
202
+ 'outbound.request': OutboundRequestEvent;
203
+ 'mail.deliver': MailDeliverEvent;
204
+ 'storage.put': StorageEvent;
205
+ 'storage.get': StorageEvent;
206
+ 'storage.stat': StorageEvent;
207
+ 'storage.copy': StorageEvent;
208
+ 'storage.delete': StorageEvent;
209
+ 'storage.list': StorageEvent;
210
+ 'cache.hit': CacheLookupEvent;
211
+ 'cache.miss': CacheLookupEvent;
212
+ 'cache.invalidate': CacheInvalidateEvent;
213
+ 'cache.tier_failure': CacheTierFailureEvent;
214
+ /** A SAMPLED span, ended — the trace export stream. Unsampled spans never reach it. */
215
+ 'span.end': ReadableSpan;
216
+ 'log.record': LogRecordEvent;
217
+ /** One push tick's cumulative collection (`exportMetrics()`) — the metric export stream. */
218
+ 'metric.export': MetricCollection;
219
+ }
220
+
221
+ /**
222
+ * Every event the bus carries. AUGMENTABLE — an app declares its own names with
223
+ * `declare module '@ultimat3/core' { interface InstrumentEventMap { 'billing.charged': … } }` and
224
+ * emits them with the same `instrument()`. A name is lowercase dot-segments; the framework's first
225
+ * segments (`INSTRUMENT_EVENTS`) are taken.
226
+ */
227
+ export interface InstrumentEventMap extends FrameworkEventMap {}
228
+
229
+ /** `'event'`: a point fact, no span. Otherwise the OTel kind of the span its emitter opens. */
230
+ export type InstrumentSpan = SpanKind | 'event';
231
+
232
+ export interface InstrumentEventSpec {
233
+ readonly span: InstrumentSpan;
234
+ /** The package that emits it — the ONE place `instrument(name, …)` is called from. */
235
+ readonly owner: string;
236
+ }
237
+
238
+ /** The framework's names, as a value: the docs, `x dev`'s panels and the tests read this. */
239
+ export const INSTRUMENT_EVENTS = Object.freeze({
240
+ 'http.request': { span: 'server', owner: '@ultimat3/http' },
241
+ 'db.statement': { span: 'client', owner: '@ultimat3/db' },
242
+ 'entity.row': { span: 'event', owner: '@ultimat3/entity' },
243
+ 'entity.bulk': { span: 'event', owner: '@ultimat3/entity' },
244
+ 'entity.cross_tenant': { span: 'event', owner: '@ultimat3/entity' },
245
+ 'policy.decision': { span: 'event', owner: '@ultimat3/policy' },
246
+ 'action.invoke': { span: 'internal', owner: '@ultimat3/action' },
247
+ 'query.read': { span: 'internal', owner: '@ultimat3/query' },
248
+ 'job.enqueue': { span: 'producer', owner: '@ultimat3/jobs' },
249
+ 'job.perform': { span: 'consumer', owner: '@ultimat3/jobs' },
250
+ 'ai.llm': { span: 'client', owner: '@ultimat3/ai' },
251
+ 'render.page': { span: 'internal', owner: '@ultimat3/render' },
252
+ 'render.isr.regenerate': { span: 'internal', owner: '@ultimat3/render' },
253
+ 'render.hole': { span: 'internal', owner: '@ultimat3/render' },
254
+ 'outbound.request': { span: 'client', owner: '@ultimat3/core' },
255
+ 'mail.deliver': { span: 'client', owner: '@ultimat3/mail' },
256
+ 'storage.put': { span: 'client', owner: '@ultimat3/storage' },
257
+ 'storage.get': { span: 'client', owner: '@ultimat3/storage' },
258
+ 'storage.stat': { span: 'client', owner: '@ultimat3/storage' },
259
+ 'storage.copy': { span: 'client', owner: '@ultimat3/storage' },
260
+ 'storage.delete': { span: 'client', owner: '@ultimat3/storage' },
261
+ 'storage.list': { span: 'client', owner: '@ultimat3/storage' },
262
+ 'cache.hit': { span: 'event', owner: '@ultimat3/cache' },
263
+ 'cache.miss': { span: 'event', owner: '@ultimat3/cache' },
264
+ 'cache.invalidate': { span: 'internal', owner: '@ultimat3/cache' },
265
+ 'cache.tier_failure': { span: 'event', owner: '@ultimat3/cache' },
266
+ 'span.end': { span: 'event', owner: '@ultimat3/core' },
267
+ 'log.record': { span: 'event', owner: '@ultimat3/core' },
268
+ 'metric.export': { span: 'event', owner: '@ultimat3/core' },
269
+ } as const satisfies Record<keyof FrameworkEventMap, InstrumentEventSpec>);
270
+
271
+ /** A framework event name — the closed half of `InstrumentName`. */
272
+ export type FrameworkEventName = keyof typeof INSTRUMENT_EVENTS;
@@ -0,0 +1,65 @@
1
+ // Single responsibility: the OpenTelemetry semantic-convention names the framework's spans and
2
+ // metrics carry — STABLE names (http, db, messaging, gen_ai), one declaration each, so an emitter
3
+ // writes `SEMCONV.httpRequestMethod` and a typo is a type error, never a dashboard that is empty.
4
+
5
+ /** Span attribute keys. The legacy `http.method` / `db.statement` / `llm.*` spellings are gone. */
6
+ export const SEMCONV = Object.freeze({
7
+ // HTTP server — https://opentelemetry.io/docs/specs/semconv/http/http-spans/
8
+ httpRequestMethod: 'http.request.method',
9
+ httpResponseStatusCode: 'http.response.status_code',
10
+ httpRoute: 'http.route',
11
+ urlPath: 'url.path',
12
+ urlScheme: 'url.scheme',
13
+ serverAddress: 'server.address',
14
+ serverPort: 'server.port',
15
+ errorType: 'error.type',
16
+ // Database client — https://opentelemetry.io/docs/specs/semconv/database/database-spans/
17
+ dbSystemName: 'db.system.name',
18
+ dbNamespace: 'db.namespace',
19
+ dbQueryText: 'db.query.text',
20
+ dbOperationName: 'db.operation.name',
21
+ dbCollectionName: 'db.collection.name',
22
+ dbResponseReturnedRows: 'db.response.returned_rows',
23
+ // Messaging (jobs) — https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/
24
+ messagingSystem: 'messaging.system',
25
+ messagingOperationType: 'messaging.operation.type',
26
+ messagingOperationName: 'messaging.operation.name',
27
+ messagingDestinationName: 'messaging.destination.name',
28
+ messagingMessageId: 'messaging.message.id',
29
+ // Generative AI — https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/
30
+ genAiProviderName: 'gen_ai.provider.name',
31
+ genAiOperationName: 'gen_ai.operation.name',
32
+ genAiRequestModel: 'gen_ai.request.model',
33
+ genAiResponseModel: 'gen_ai.response.model',
34
+ genAiUsageInputTokens: 'gen_ai.usage.input_tokens',
35
+ genAiUsageOutputTokens: 'gen_ai.usage.output_tokens',
36
+ genAiTokenType: 'gen_ai.token.type',
37
+ } as const);
38
+
39
+ /** The values semconv fixes for the framework's own systems. */
40
+ export const SEMCONV_VALUES = Object.freeze({
41
+ dbSystemPostgres: 'postgresql',
42
+ messagingSystemUltimate: 'ultimate',
43
+ messagingOperationCreate: 'create',
44
+ /** One message handed to the queue — a producer; `create` is for one built for a later batch. */
45
+ messagingOperationSend: 'send',
46
+ messagingOperationProcess: 'process',
47
+ /** `llm()` is a chat call: every `ai.llm` event is this operation. */
48
+ genAiOperationChat: 'chat',
49
+ genAiTokenInput: 'input',
50
+ genAiTokenOutput: 'output',
51
+ } as const);
52
+
53
+ /**
54
+ * Metric names: semconv's, in the Prometheus form an OTel → Prometheus bridge produces (dots to
55
+ * underscores, the unit as a suffix) — the registry is snake_case (`metric-names.ts`), and one
56
+ * spelling on both `/metrics` and OTLP is what keeps a dashboard joinable.
57
+ */
58
+ export const SEMCONV_METRICS = Object.freeze({
59
+ /** semconv `db.client.operation.duration`, seconds. */
60
+ dbClientOperationDuration: 'db_client_operation_duration_seconds',
61
+ /** semconv `gen_ai.client.token.usage`, `{token}`, by `gen_ai.token.type`. */
62
+ genAiClientTokenUsage: 'gen_ai_client_token_usage',
63
+ /** `job.duration`, seconds, by queue and outcome — semconv `messaging.process.duration`'s role. */
64
+ jobDuration: 'job_duration_seconds',
65
+ } as const);
@@ -0,0 +1,38 @@
1
+ // Single responsibility: the opt-in that makes a `db.statement` event carry the stack it was SENT
2
+ // from. Off by default and never turned on by production — a stack per statement is real cost —
3
+ // so only a holder that needs to name a loop's line (`@ultimat3/testing`'s `statements` fixture)
4
+ // pays for it, and only for as long as it holds it. Ref-counted: nested holders compose.
5
+
6
+ let holders = 0;
7
+
8
+ /** Turn stack capture on until the returned release is called. Releasing twice is a no-op. */
9
+ export function captureStatementStacks(): () => void {
10
+ holders += 1;
11
+ let released = false;
12
+ return () => {
13
+ if (released) return;
14
+ released = true;
15
+ holders -= 1;
16
+ };
17
+ }
18
+
19
+ /** Whether any holder has stack capture on. One integer read: the emitter's whole cost when off. */
20
+ export function statementStacksCaptured(): boolean {
21
+ return holders > 0;
22
+ }
23
+
24
+ /**
25
+ * The caller's stack NOW — read by an emitter BEFORE its first `await`, because an awaited
26
+ * continuation keeps no caller frames. `undefined` while capture is off: nothing is built.
27
+ */
28
+ export function callerStack(): string | undefined {
29
+ if (holders === 0) return undefined;
30
+ const site: { stack?: string } = {};
31
+ Error.captureStackTrace(site, callerStack);
32
+ return site.stack;
33
+ }
34
+
35
+ /** TEST SEAM: every holder dropped. */
36
+ export function resetStatementStacks(): void {
37
+ holders = 0;
38
+ }
@@ -0,0 +1,194 @@
1
+ // Single responsibility: the ONE instrumentation bus — `instrument()` publishes a named event,
2
+ // `subscribe()` hears it, `subscribed()` lets an emitter skip building a payload nobody reads.
3
+ // Every observer the framework has (OTLP spans and logs, metrics, `x dev`'s recorder, the `/_x`
4
+ // panels, app code) is a subscriber here; no package keeps a `set*Observer` slot of its own.
5
+
6
+ import { renderThrowable } from './error-render';
7
+ import type { InstrumentEventMap } from './instrument-events';
8
+ import { logger } from './logger';
9
+
10
+ /** Every event name the bus carries — the framework's (`INSTRUMENT_EVENTS`) and the app's own. */
11
+ export type InstrumentName = keyof InstrumentEventMap & string;
12
+
13
+ /** `entity` for `entity.row`, `render` and `render.isr` for `render.isr.regenerate`. */
14
+ type PrefixesOf<N extends string> = N extends `${infer Head}.${infer Rest}`
15
+ ? Head | `${Head}.${PrefixesOf<Rest>}`
16
+ : never;
17
+
18
+ /**
19
+ * What `subscribe()` accepts: an exact name, a dot-segment prefix of one (`'entity'` hears
20
+ * `entity.row`, `entity.bulk` and `entity.cross_tenant`; `'ent'` hears nothing and does not
21
+ * compile), or `'*'` for everything.
22
+ */
23
+ export type InstrumentPattern = InstrumentName | PrefixesOf<InstrumentName> | '*';
24
+
25
+ /** The names a pattern hears. */
26
+ export type MatchedName<P extends InstrumentPattern> = P extends '*'
27
+ ? InstrumentName
28
+ : Extract<InstrumentName, P | `${P}.${string}`>;
29
+
30
+ /** One delivered event: discriminated on `name`, so a prefix subscriber narrows with a switch. */
31
+ export type InstrumentEvent<N extends InstrumentName = InstrumentName> = {
32
+ readonly [K in N]: { readonly name: K; readonly payload: InstrumentEventMap[K] };
33
+ }[N];
34
+
35
+ export type InstrumentHandler<P extends InstrumentPattern> = (
36
+ event: InstrumentEvent<MatchedName<P>>,
37
+ ) => void;
38
+
39
+ type AnyHandler = (event: { readonly name: string; readonly payload: unknown }) => void;
40
+
41
+ interface Subscription {
42
+ readonly pattern: string;
43
+ readonly handler: AnyHandler;
44
+ /** Cleared by the unsubscribe, read per call: a dispatch in flight skips it from then on. */
45
+ live: boolean;
46
+ }
47
+
48
+ /** Replaced, never mutated: a dispatch in flight keeps the list it started with. */
49
+ let subscriptions: readonly Subscription[] = [];
50
+ /** name → the subscriptions it reaches, in order. Dropped whole on every (un)subscribe. */
51
+ let routes = new Map<string, readonly Subscription[]>();
52
+ /** Names being dispatched on this stack — a handler re-emitting one is not re-delivered to it. */
53
+ const dispatching = new Set<string>();
54
+
55
+ const NONE: readonly Subscription[] = Object.freeze([]);
56
+
57
+ /** Failures contained since the last reset — `subscriberFailures()`. */
58
+ let failures = 0;
59
+ /** handler → the event names it has already been reported failing on: one line per pair. */
60
+ let reported = new WeakMap<AnyHandler, Set<string>>();
61
+
62
+ function matches(pattern: string, name: string): boolean {
63
+ return pattern === '*' || pattern === name || name.startsWith(`${pattern}.`);
64
+ }
65
+
66
+ function routeOf(name: string): readonly Subscription[] {
67
+ if (subscriptions.length === 0) return NONE;
68
+ const known = routes.get(name);
69
+ if (known !== undefined) return known;
70
+ const found = subscriptions.filter((sub) => matches(sub.pattern, name));
71
+ const route = found.length === 0 ? NONE : Object.freeze(found);
72
+ routes.set(name, route);
73
+ return route;
74
+ }
75
+
76
+ /**
77
+ * Hear every event `pattern` matches. Handlers run synchronously, on the emitter's stack, in the
78
+ * order they subscribed — so `tryUseContext()` and `currentSpanContext()` inside one answer for
79
+ * the code that emitted. Returns the unsubscribe; calling it twice is a no-op.
80
+ *
81
+ * A subscriber can never break the work it observes: a handler that throws — or returns a promise
82
+ * that rejects — is CONTAINED. The other handlers still run, the emitter never sees the failure,
83
+ * and it is logged once per handler and event name as `instrument.subscriber_failed`. An observer
84
+ * is not an input: a `policy.decision` subscriber cannot deny, a `mail.deliver` one cannot make a
85
+ * delivered message look failed and get it sent twice.
86
+ */
87
+ export function subscribe<P extends InstrumentPattern>(
88
+ pattern: P,
89
+ handler: InstrumentHandler<P>,
90
+ ): () => void {
91
+ const subscription: Subscription = { pattern, handler: handler as AnyHandler, live: true };
92
+ subscriptions = [...subscriptions, subscription];
93
+ routes = new Map();
94
+ return () => {
95
+ if (!subscription.live) return;
96
+ subscription.live = false;
97
+ subscriptions = subscriptions.filter((candidate) => candidate !== subscription);
98
+ routes = new Map();
99
+ };
100
+ }
101
+
102
+ /**
103
+ * Whether anything hears `name`. An emitter asks BEFORE it builds a payload that costs something —
104
+ * reading a row's before-image, copying bound values — so an app with no subscriber pays one map
105
+ * read per event and allocates nothing (axiom 6).
106
+ */
107
+ export function subscribed(name: InstrumentName): boolean {
108
+ return routeOf(name).length > 0;
109
+ }
110
+
111
+ /**
112
+ * Publish one event. Fired for EVERY occurrence — before, and regardless of, trace sampling — so a
113
+ * subscriber counting statements or decisions sees unsampled traffic too.
114
+ *
115
+ * Re-entrancy: a handler may emit other events (a subscriber that logs emits `log.record`), but an
116
+ * event emitted from inside a handler of the SAME name is not delivered again — that is the loop a
117
+ * `'*'` subscriber that logs would otherwise spin forever.
118
+ */
119
+ export function instrument<N extends InstrumentName>(
120
+ name: N,
121
+ payload: InstrumentEventMap[N],
122
+ ): void {
123
+ const route = routeOf(name);
124
+ if (route.length === 0 || dispatching.has(name)) return;
125
+ const event = { name, payload };
126
+ dispatching.add(name);
127
+ try {
128
+ for (const subscription of route) {
129
+ // Unsubscribed by an earlier handler of this same dispatch: not called again.
130
+ if (subscription.live) deliver(subscription.handler, event);
131
+ }
132
+ } finally {
133
+ dispatching.delete(name);
134
+ }
135
+ }
136
+
137
+ function deliver(
138
+ handler: AnyHandler,
139
+ event: { readonly name: string; readonly payload: unknown },
140
+ ): void {
141
+ let returned: unknown;
142
+ try {
143
+ returned = handler(event);
144
+ } catch (thrown) {
145
+ contain(handler, event.name, thrown);
146
+ return;
147
+ }
148
+ // The handler type says `void`, and an `async` handler still satisfies it: a rejection left
149
+ // unhandled would take the process down from a subscriber nobody awaited.
150
+ if (isThenable(returned)) {
151
+ returned.then(undefined, (rejected: unknown) => contain(handler, event.name, rejected));
152
+ }
153
+ }
154
+
155
+ function isThenable(value: unknown): value is PromiseLike<unknown> {
156
+ return (
157
+ typeof value === 'object' &&
158
+ value !== null &&
159
+ typeof (value as { then?: unknown }).then === 'function'
160
+ );
161
+ }
162
+
163
+ function contain(handler: AnyHandler, name: string, error: unknown): void {
164
+ failures += 1;
165
+ const names = reported.get(handler) ?? new Set<string>();
166
+ if (names.has(name)) return;
167
+ names.add(name);
168
+ reported.set(handler, names);
169
+ try {
170
+ logger.error('instrument.subscriber_failed', { event: name, error: renderThrowable(error) });
171
+ } catch {
172
+ // The logger is total; this is the belt to its braces — containment must not throw either.
173
+ }
174
+ }
175
+
176
+ /** How many subscriber failures were contained since the last reset — every one, not only the logged. */
177
+ export function subscriberFailures(): number {
178
+ return failures;
179
+ }
180
+
181
+ /** How many subscriptions are live — a count that climbs across a test is an unsubscribe missed. */
182
+ export function subscriberCount(): number {
183
+ return subscriptions.length;
184
+ }
185
+
186
+ /** TEST SEAM: drop every subscription. A suite that subscribes unsubscribes; this is the backstop. */
187
+ export function resetInstrumentation(): void {
188
+ for (const subscription of subscriptions) subscription.live = false;
189
+ subscriptions = [];
190
+ routes = new Map();
191
+ dispatching.clear();
192
+ failures = 0;
193
+ reported = new WeakMap();
194
+ }
@@ -4,24 +4,22 @@
4
4
  // known, is brute-forced from a database read. Keyed with HMAC-SHA-256, the stored value proves
5
5
  // nothing to anyone without the app's signing secret.
6
6
 
7
- import { canonicalJson, fingerprint } from './canonical-json';
7
+ import { canonicalJson } from './canonical-json';
8
8
  import { currentSigningSecret } from './cursor';
9
9
  import { hmac } from './hmac';
10
10
  import { timingSafeEqual } from './timing-safe-equal';
11
11
 
12
- /** The format tag. A stored value without it predates keying (see `compareFingerprint`). */
12
+ /** The format tag. A stored value without it is no format this build reads (`unverifiable`). */
13
13
  export const KEYED_FINGERPRINT_VERSION = 'h1';
14
14
 
15
15
  /**
16
16
  * What a stored fingerprint says about an input:
17
- * - `match` / `mismatch` — computed under the key in force now (or the legacy unkeyed form);
17
+ * - `match` / `mismatch` — computed under the key in force now;
18
18
  * - `unverifiable` — keyed under a secret this process does not hold (a rotation), or a format this
19
- * build does not know. The input can be neither confirmed nor refused.
19
+ * build does not know (a bare pre-v24 hash among them). Neither confirmed nor refused.
20
20
  */
21
21
  export type FingerprintMatch = 'match' | 'mismatch' | 'unverifiable';
22
22
 
23
- const LEGACY = /^[0-9a-f]{16}$/;
24
-
25
23
  /** One key per purpose, derived from the signing secret, so no two uses share a MAC key. */
26
24
  function derivedKey(purpose: string): string {
27
25
  return hmac('sha256', currentSigningSecret(), `ultimate:keyed-fingerprint:${purpose}`, 'hex');
@@ -47,17 +45,15 @@ export function keyedFingerprint(value: unknown, purpose: string): string {
47
45
  }
48
46
 
49
47
  /**
50
- * Compare a STORED fingerprint with an input. A legacy unkeyed value (16 hex characters, written by
51
- * a build before keying) is checked against `fingerprint()` computed here and never stored, so rows
52
- * written across an upgrade keep their exact semantics until they age out.
48
+ * Compare a STORED fingerprint with an input. Only the keyed form is read: the unkeyed one (v23
49
+ * and before) aged out of every store long ago, and one still lying around is `unverifiable` —
50
+ * each caller already answers that safely (a rotation reads the same).
53
51
  */
54
52
  export function compareFingerprint(
55
53
  stored: string,
56
54
  value: unknown,
57
55
  purpose: string,
58
56
  ): FingerprintMatch {
59
- if (LEGACY.test(stored))
60
- return timingSafeEqual(stored, fingerprint(value)) ? 'match' : 'mismatch';
61
57
  const current = keyedFingerprint(value, purpose);
62
58
  const prefix = current.slice(0, current.lastIndexOf(':') + 1);
63
59
  if (!stored.startsWith(prefix)) return 'unverifiable';
@@ -1,11 +1,11 @@
1
1
  // Single responsibility: wiring process signals to the one drain. Split from `lifecycle.ts`, which
2
2
  // owns the state machine and the phases, when the readiness grace took it past its line ceiling.
3
3
 
4
- import { drain, type ProcessSignal } from './lifecycle';
4
+ import { drain, drainExitCode, type ProcessSignal } from './lifecycle';
5
5
 
6
6
  export interface SignalHandlerOptions {
7
7
  readonly signals?: readonly ProcessSignal[] | undefined;
8
- /** Call `process.exit()` once drained. Off in tests. */
8
+ /** Call `process.exit(drainExitCode())` once drained: 0, or 70 when work was abandoned. Off in tests. */
9
9
  readonly exit?: boolean | undefined;
10
10
  /** Whose default signal set to install — `process.platform` unless a test names one. */
11
11
  readonly platform?: string | undefined;
@@ -46,7 +46,9 @@ export function installSignalHandlers(options?: SignalHandlerOptions): () => voi
46
46
  // `drain()` cannot reject today — that is `runDrain`'s `try/finally` in `lifecycle.ts`, not luck — and this is
47
47
  // the one line that keeps it true when someone changes the body.
48
48
  const done = (): void => {
49
- if (options?.exit === true) process.exit(0);
49
+ // 70, not 0, when the drain abandoned work at its deadline: the exit code is the
50
+ // platform's only record of whether a write may be half done (`drainExitCode`).
51
+ if (options?.exit === true) process.exit(drainExitCode());
50
52
  };
51
53
  void drain(signal).then(done, done);
52
54
  };