@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.
- 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/secrets-store.ts
CHANGED
|
@@ -10,6 +10,14 @@ import { existsSync, readFileSync } from 'node:fs';
|
|
|
10
10
|
// Bun exposes no path-join primitive.
|
|
11
11
|
import { join } from 'node:path';
|
|
12
12
|
import { isUltimateError } from './errors';
|
|
13
|
+
import type { MasterKeyRef } from './secret-source';
|
|
14
|
+
import {
|
|
15
|
+
builtInMasterKey,
|
|
16
|
+
masterKeyPath,
|
|
17
|
+
resolveMasterKey,
|
|
18
|
+
SECRETS_KEY_ENV,
|
|
19
|
+
secretSource,
|
|
20
|
+
} from './secret-source';
|
|
13
21
|
import type { SecretValues } from './secrets';
|
|
14
22
|
import { masterKeyId, openSecrets, parseMasterKey, sealSecrets } from './secrets';
|
|
15
23
|
import { SecretsFileMissingError, SecretsKeyMissingError } from './secrets-errors';
|
|
@@ -17,29 +25,15 @@ import { OWNER_ONLY_MODE, renameOver, writeOwnerOnlyFile } from './secrets-key-f
|
|
|
17
25
|
|
|
18
26
|
/** Committed. Encrypted at rest, diffable, and the only file `x secrets` writes into the repo. */
|
|
19
27
|
export const SECRETS_FILE = 'secrets.enc.json';
|
|
20
|
-
/** Never committed — `x secrets init` writes the ignore rule before it writes this. */
|
|
21
|
-
export const SECRETS_KEY_FILE = '.secrets.key';
|
|
22
|
-
/** Read first, so a container gets its key from the platform's secret store and never from a file. */
|
|
23
|
-
export const SECRETS_KEY_ENV = 'ULTIMATE_SECRETS_KEY';
|
|
24
28
|
/**
|
|
25
29
|
* Owner read/write. A key file the rest of the box can read is a key file that has leaked. On
|
|
26
30
|
* Windows the mode is not what keeps other accounts out — the ACL is, and the writers set it.
|
|
27
31
|
*/
|
|
28
32
|
export const SECRETS_KEY_MODE = OWNER_ONLY_MODE;
|
|
29
33
|
|
|
30
|
-
export type MasterKeySource = 'env' | 'file';
|
|
31
|
-
|
|
32
|
-
export interface MasterKeyRef {
|
|
33
|
-
readonly hex: string;
|
|
34
|
-
readonly source: MasterKeySource;
|
|
35
|
-
/** The env var name or the file path, for an error's `cause` — never the key itself. */
|
|
36
|
-
readonly at: string;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
34
|
type EnvRecord = Record<string, string | undefined>;
|
|
40
35
|
|
|
41
36
|
export const secretsPath = (root: string): string => join(root, SECRETS_FILE);
|
|
42
|
-
export const masterKeyPath = (root: string): string => join(root, SECRETS_KEY_FILE);
|
|
43
37
|
export const secretsFileExists = (root: string): boolean => existsSync(secretsPath(root));
|
|
44
38
|
/**
|
|
45
39
|
* Where `x secrets rotate` STAGES a new key before sealing the committed file with it; the rename
|
|
@@ -75,21 +69,15 @@ async function openWithStaged(
|
|
|
75
69
|
}
|
|
76
70
|
|
|
77
71
|
/**
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
72
|
+
* The BUILT-IN lookup — env var first, key file second — synchronously, for the tools that manage
|
|
73
|
+
* those two (`x secrets`, `x doctor`). A booting process asks the installed `SecretSource` instead
|
|
74
|
+
* (`requireInstalledMasterKey`), so a KMS source is the answer there and only there.
|
|
81
75
|
*/
|
|
82
76
|
export function findMasterKey(
|
|
83
77
|
root: string,
|
|
84
78
|
env: EnvRecord = process.env,
|
|
85
79
|
): MasterKeyRef | undefined {
|
|
86
|
-
|
|
87
|
-
if (fromEnv !== undefined && fromEnv.trim().length > 0) {
|
|
88
|
-
return { hex: fromEnv.trim(), source: 'env', at: SECRETS_KEY_ENV };
|
|
89
|
-
}
|
|
90
|
-
const path = masterKeyPath(root);
|
|
91
|
-
if (!existsSync(path)) return undefined;
|
|
92
|
-
return { hex: readFileSync(path, 'utf-8').trim(), source: 'file', at: path };
|
|
80
|
+
return builtInMasterKey({ root, env });
|
|
93
81
|
}
|
|
94
82
|
|
|
95
83
|
export function requireMasterKey(root: string, env: EnvRecord = process.env): MasterKeyRef {
|
|
@@ -98,6 +86,21 @@ export function requireMasterKey(root: string, env: EnvRecord = process.env): Ma
|
|
|
98
86
|
throw new SecretsKeyMissingError({ envVar: SECRETS_KEY_ENV, keyPath: masterKeyPath(root) });
|
|
99
87
|
}
|
|
100
88
|
|
|
89
|
+
/** The installed source's key, or `X_SECRETS_KEY_MISSING` naming that source. */
|
|
90
|
+
export async function requireInstalledMasterKey(
|
|
91
|
+
root: string,
|
|
92
|
+
env: EnvRecord = process.env,
|
|
93
|
+
): Promise<MasterKeyRef> {
|
|
94
|
+
const found = await resolveMasterKey(root, env);
|
|
95
|
+
if (found !== undefined) return found;
|
|
96
|
+
const source = secretSource().name;
|
|
97
|
+
throw new SecretsKeyMissingError({
|
|
98
|
+
envVar: SECRETS_KEY_ENV,
|
|
99
|
+
keyPath: masterKeyPath(root),
|
|
100
|
+
...(source === 'default' ? {} : { source }),
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
101
104
|
/** The key's public id. Safe to print, safe to commit — it is what names a rotation in a diff. */
|
|
102
105
|
export const masterKeyIdOf = (key: MasterKeyRef): Promise<string> =>
|
|
103
106
|
masterKeyId(parseMasterKey(key.hex, key.at));
|
|
@@ -164,7 +167,8 @@ export interface SecretsInstallOptions {
|
|
|
164
167
|
export interface SecretsInstallReport {
|
|
165
168
|
readonly present: boolean;
|
|
166
169
|
readonly path: string;
|
|
167
|
-
|
|
170
|
+
/** The `name` of the source that found the key. */
|
|
171
|
+
readonly keySource: string | undefined;
|
|
168
172
|
readonly keyId: string | undefined;
|
|
169
173
|
/** Variables this call set. */
|
|
170
174
|
readonly installed: readonly string[];
|
|
@@ -212,7 +216,7 @@ export async function installSecrets(
|
|
|
212
216
|
skipped: [],
|
|
213
217
|
};
|
|
214
218
|
}
|
|
215
|
-
const { values, key } = await openWithStaged(root,
|
|
219
|
+
const { values, key } = await openWithStaged(root, await requireInstalledMasterKey(root, env));
|
|
216
220
|
const installed: string[] = [];
|
|
217
221
|
const skipped: string[] = [];
|
|
218
222
|
for (const [name, value] of Object.entries(values)) {
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Single responsibility: the clock that WAITS — the server's `systemClock` with `sleep`, the test
|
|
2
|
+
// clock that waits one loop turn, and `ambientClock()`/`installClock` over the `clock` port's
|
|
3
|
+
// frames (`clock.ts`). Server-only: `./page` never imports this module, so no route pays for a timer
|
|
4
|
+
// nothing in the browser arms.
|
|
5
|
+
|
|
6
|
+
import type { SleepClock } from './clock';
|
|
7
|
+
import { installedClocks, systemClock as wallClock } from './clock';
|
|
8
|
+
import { finiteOption } from './finite-option';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A timer raced against the signal, never `Bun.sleep(ms).then(check)`: a watchdog aborts a wedged
|
|
12
|
+
* run precisely so nothing waits out the rest of its budget. An already-aborted signal throws inside
|
|
13
|
+
* the executor, which rejects with its reason without arming a timer.
|
|
14
|
+
*
|
|
15
|
+
* Screened once, here, as `frozenClock.sleep` screens it: `setTimeout(fn, NaN)` fires at once, so an
|
|
16
|
+
* unscreened broken delay turned a retry loop into a spin. A negative wait is zero on both clocks.
|
|
17
|
+
*/
|
|
18
|
+
function sleepFor(ms: number, signal: AbortSignal | undefined): Promise<void> {
|
|
19
|
+
return new Promise<void>((resolve, reject) => {
|
|
20
|
+
// Inside the executor: a refusal is a rejection, never a synchronous throw from `sleep()`.
|
|
21
|
+
finiteOption('systemClock.sleep', 'ms', ms);
|
|
22
|
+
signal?.throwIfAborted();
|
|
23
|
+
const onAbort = (): void => {
|
|
24
|
+
clearTimeout(timer);
|
|
25
|
+
reject(signal?.reason);
|
|
26
|
+
};
|
|
27
|
+
const timer = setTimeout(() => {
|
|
28
|
+
signal?.removeEventListener('abort', onAbort);
|
|
29
|
+
resolve();
|
|
30
|
+
}, ms);
|
|
31
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The system clock that can wait — `clock.ts`'s `now`/`monotonic`, plus `sleep`. `ambientClock()`'s
|
|
37
|
+
* default and `./adapter`'s `systemClock`. The barrel and `./page` export `clock.ts`'s, which has no
|
|
38
|
+
* `sleep`: `time`, `money` and `realtime` read it in the browser, where no caller waits (axiom 6).
|
|
39
|
+
*/
|
|
40
|
+
export const systemClock: SleepClock = /* @__PURE__ */ Object.freeze({
|
|
41
|
+
now: wallClock.now,
|
|
42
|
+
monotonic: wallClock.monotonic,
|
|
43
|
+
sleep: sleepFor,
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The system clock with the waiting taken out: `now()` and `monotonic()` are real, every `sleep` is
|
|
48
|
+
* ONE turn of the event loop. For a test whose wait ends on something that really happens in the
|
|
49
|
+
* same process, where a frozen clock's "sleeping is advancing" would run a deadline out in microtasks.
|
|
50
|
+
*/
|
|
51
|
+
export const noWaitClock: SleepClock = /* @__PURE__ */ Object.freeze({
|
|
52
|
+
now: () => systemClock.now(),
|
|
53
|
+
monotonic: () => systemClock.monotonic(),
|
|
54
|
+
// Screened like every `SleepClock` (a rejection, as `async`), then one loop turn: a broken delay
|
|
55
|
+
// is refused, never skipped.
|
|
56
|
+
sleep: async (ms: number, signal?: AbortSignal): Promise<void> => {
|
|
57
|
+
finiteOption('noWaitClock.sleep', 'ms', ms);
|
|
58
|
+
await sleepFor(0, signal);
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
export const ambientClock = (): SleepClock => installedClocks.current() ?? systemClock;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The installer behind `ambientClock()`. Returns the RELEASE, which removes this install alone —
|
|
66
|
+
* any stop order, idempotent (`adapter-slot.ts`). The shape every port installer takes.
|
|
67
|
+
*/
|
|
68
|
+
export function installClock(next: SleepClock): () => void {
|
|
69
|
+
return installedClocks.install(next);
|
|
70
|
+
}
|
package/src/telemetry.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
// Single responsibility: OpenTelemetry-shaped tracing that is always on.
|
|
2
|
-
// is
|
|
3
|
-
//
|
|
1
|
+
// Single responsibility: OpenTelemetry-shaped tracing that is always on. An ended, sampled span
|
|
2
|
+
// is published on the instrumentation bus as `span.end` — every exporter is a subscriber, so an
|
|
3
|
+
// app with none pays nothing — and trace context is serialised explicitly (`traceparent`) so a
|
|
4
|
+
// trace survives HTTP -> job -> live query.
|
|
4
5
|
|
|
5
6
|
import { asyncContext } from './async-context';
|
|
6
7
|
import { type Clock, systemClock } from './clock';
|
|
@@ -8,6 +9,7 @@ import { tryUseContext } from './context';
|
|
|
8
9
|
import { renderThrowable } from './error-render';
|
|
9
10
|
import { isUltimateError } from './errors';
|
|
10
11
|
import { isSpanId, isTraceId, spanId as newSpanId, traceId as newTraceId } from './ids';
|
|
12
|
+
import { instrument, subscribed } from './instrument';
|
|
11
13
|
import { installTraceHeaders } from './outbound-headers';
|
|
12
14
|
import { defaultSampler, resetDefaultSampler, type Sampler } from './sampler';
|
|
13
15
|
|
|
@@ -50,6 +52,8 @@ export interface ReadableSpan {
|
|
|
50
52
|
readonly durationMs: number;
|
|
51
53
|
readonly attributes: SpanAttributes;
|
|
52
54
|
readonly events: readonly SpanEvent[];
|
|
55
|
+
/** Events past `MAX_SPAN_EVENTS`, counted and not kept — OTLP's `droppedEventsCount`. */
|
|
56
|
+
readonly droppedEventsCount: number;
|
|
53
57
|
readonly status: SpanStatus;
|
|
54
58
|
readonly links: readonly SpanContext[];
|
|
55
59
|
readonly resource: SpanResource;
|
|
@@ -78,10 +82,21 @@ export interface Span {
|
|
|
78
82
|
end(): void;
|
|
79
83
|
}
|
|
80
84
|
|
|
85
|
+
/**
|
|
86
|
+
* What an exporter does with one span. Installed by SUBSCRIBING, never configured:
|
|
87
|
+
* `subscribe('span.end', (event) => exporter.export(event.payload))`.
|
|
88
|
+
*/
|
|
81
89
|
export interface SpanExporter {
|
|
82
90
|
export(span: ReadableSpan): void;
|
|
83
91
|
}
|
|
84
92
|
|
|
93
|
+
/**
|
|
94
|
+
* The most events one span keeps. A span is held until it ends, and a loop that records an event
|
|
95
|
+
* per row grew it without bound; past this the events are counted, not kept — the OTel SDK's own
|
|
96
|
+
* default (`OTEL_SPAN_EVENT_COUNT_LIMIT=128`), and OTLP carries the count as `droppedEventsCount`.
|
|
97
|
+
*/
|
|
98
|
+
export const MAX_SPAN_EVENTS = 128;
|
|
99
|
+
|
|
85
100
|
export interface StartSpanOptions {
|
|
86
101
|
readonly kind?: SpanKind | undefined;
|
|
87
102
|
readonly attributes?: SpanAttributes | undefined;
|
|
@@ -91,7 +106,6 @@ export interface StartSpanOptions {
|
|
|
91
106
|
}
|
|
92
107
|
|
|
93
108
|
export interface TelemetryOptions {
|
|
94
|
-
readonly exporter?: SpanExporter | undefined;
|
|
95
109
|
readonly clock?: Clock | undefined;
|
|
96
110
|
readonly serviceName?: string | undefined;
|
|
97
111
|
readonly serviceVersion?: string | undefined;
|
|
@@ -100,18 +114,15 @@ export interface TelemetryOptions {
|
|
|
100
114
|
readonly sampler?: Sampler | undefined;
|
|
101
115
|
}
|
|
102
116
|
|
|
103
|
-
export const noopExporter: SpanExporter = Object.freeze({
|
|
104
|
-
export(): void {
|
|
105
|
-
// Intentionally empty: tracing is always on, and free until an exporter is configured.
|
|
106
|
-
},
|
|
107
|
-
});
|
|
108
|
-
|
|
109
117
|
export interface MemoryExporter extends SpanExporter {
|
|
110
118
|
readonly spans: readonly ReadableSpan[];
|
|
111
119
|
reset(): void;
|
|
112
120
|
}
|
|
113
121
|
|
|
114
|
-
/**
|
|
122
|
+
/**
|
|
123
|
+
* For tests, and for reading back what a run traced with no collector on the box. Subscribe it:
|
|
124
|
+
* `const off = subscribe('span.end', (event) => spans.export(event.payload))`.
|
|
125
|
+
*/
|
|
115
126
|
export function memoryExporter(): MemoryExporter {
|
|
116
127
|
const spans: ReadableSpan[] = [];
|
|
117
128
|
return {
|
|
@@ -130,14 +141,12 @@ export function memoryExporter(): MemoryExporter {
|
|
|
130
141
|
// `@ultimat3/core` down with it. `async-context.ts` owns the argument.
|
|
131
142
|
const activeSpan = asyncContext<Span>('the active span');
|
|
132
143
|
|
|
133
|
-
let exporter: SpanExporter = noopExporter;
|
|
134
144
|
let clock: Clock = systemClock;
|
|
135
145
|
let enabled = true;
|
|
136
146
|
let sampler: Sampler | undefined;
|
|
137
147
|
let resource: SpanResource = Object.freeze({ serviceName: 'ultimate', serviceVersion: '0.0.1' });
|
|
138
148
|
|
|
139
149
|
export function configureTelemetry(options: TelemetryOptions): void {
|
|
140
|
-
if (options.exporter !== undefined) exporter = options.exporter;
|
|
141
150
|
if (options.clock !== undefined) clock = options.clock;
|
|
142
151
|
if (options.enabled !== undefined) enabled = options.enabled;
|
|
143
152
|
if (options.sampler !== undefined) sampler = options.sampler;
|
|
@@ -150,7 +159,6 @@ export function configureTelemetry(options: TelemetryOptions): void {
|
|
|
150
159
|
}
|
|
151
160
|
|
|
152
161
|
export function resetTelemetry(): void {
|
|
153
|
-
exporter = noopExporter;
|
|
154
162
|
clock = systemClock;
|
|
155
163
|
enabled = true;
|
|
156
164
|
sampler = undefined;
|
|
@@ -197,7 +205,45 @@ export function currentSpanContext(): SpanContext | undefined {
|
|
|
197
205
|
* exact pair — and the one lever between "tracing is on" and "the collector melts" did nothing.
|
|
198
206
|
*/
|
|
199
207
|
function inboundParent(parent: SpanContext | undefined): SpanContext | undefined {
|
|
200
|
-
|
|
208
|
+
if (parent === undefined) return undefined;
|
|
209
|
+
// A span this process started IS a real parent — asked first, because reading its `spanId`
|
|
210
|
+
// would mint the id an unsampled span deliberately left unminted.
|
|
211
|
+
if (parent instanceof LazySpanContext || parent instanceof SampledSpanContext) return parent;
|
|
212
|
+
return parent.spanId === '' ? undefined : parent;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* A SAMPLED span's context: three own, enumerable fields, so a spread, `JSON.stringify` and
|
|
217
|
+
* `structuredClone` carry all of them. A class, so `inboundParent` brands it with `instanceof`
|
|
218
|
+
* instead of reading `spanId` (measured: an object literal with a getter and a symbol brand cost
|
|
219
|
+
* ten times a class to build).
|
|
220
|
+
*/
|
|
221
|
+
class SampledSpanContext implements SpanContext {
|
|
222
|
+
readonly spanId: string;
|
|
223
|
+
readonly traceFlags = 1;
|
|
224
|
+
constructor(readonly traceId: string) {
|
|
225
|
+
this.spanId = newSpanId();
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* An UNSAMPLED span's context: its id is minted only when something reads it — a `traceparent`
|
|
231
|
+
* sent onward, a sampled child's `parentSpanId` — because nothing else ever does, and the draw was
|
|
232
|
+
* most of what an unsampled span cost (plan 101 slice 20: ≤ 1 µs). The getter lives on the
|
|
233
|
+
* prototype, which a spread and `structuredClone` skip; `toJSON` keeps `JSON.stringify` whole, and
|
|
234
|
+
* a caller copying a context reads `spanId` by name, as `SpanContext` declares it.
|
|
235
|
+
*/
|
|
236
|
+
class LazySpanContext implements SpanContext {
|
|
237
|
+
readonly traceFlags = 0;
|
|
238
|
+
#spanId: string | undefined;
|
|
239
|
+
constructor(readonly traceId: string) {}
|
|
240
|
+
get spanId(): string {
|
|
241
|
+
this.#spanId ??= newSpanId();
|
|
242
|
+
return this.#spanId;
|
|
243
|
+
}
|
|
244
|
+
toJSON(): SpanContext {
|
|
245
|
+
return { traceId: this.traceId, spanId: this.spanId, traceFlags: this.traceFlags };
|
|
246
|
+
}
|
|
201
247
|
}
|
|
202
248
|
|
|
203
249
|
export function startSpan(initialName: string, options?: StartSpanOptions): Span {
|
|
@@ -206,7 +252,8 @@ export function startSpan(initialName: string, options?: StartSpanOptions): Span
|
|
|
206
252
|
installTraceHeaders();
|
|
207
253
|
const parent = options?.parent ?? currentSpanContext();
|
|
208
254
|
const inbound = inboundParent(parent);
|
|
209
|
-
const
|
|
255
|
+
const given = options?.attributes;
|
|
256
|
+
const attributes: Record<string, AttributeValue> = given === undefined ? {} : { ...given };
|
|
210
257
|
// The bit is decided ONCE, here, and every child of this span inherits it through `parent` —
|
|
211
258
|
// so one trace is sampled or not sampled as a whole. Before this, `traceFlags` was hardcoded to
|
|
212
259
|
// 1 for a root and `end()` exported regardless, which made the bit a value the framework
|
|
@@ -214,14 +261,19 @@ export function startSpan(initialName: string, options?: StartSpanOptions): Span
|
|
|
214
261
|
// The id is resolved BEFORE the decision, because the decision may be a function of it: a
|
|
215
262
|
// `traceidratio` sampler hashes the trace id, and a root's id exists nowhere else to hash.
|
|
216
263
|
const traceId = parent?.traceId ?? newTraceId();
|
|
217
|
-
const
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
};
|
|
264
|
+
const sampled = currentSampler().shouldSample(name, inbound, attributes, traceId);
|
|
265
|
+
const context: SpanContext = sampled
|
|
266
|
+
? new SampledSpanContext(traceId)
|
|
267
|
+
: new LazySpanContext(traceId);
|
|
222
268
|
const events: SpanEvent[] = [];
|
|
223
|
-
|
|
224
|
-
const
|
|
269
|
+
let droppedEventsCount = 0;
|
|
270
|
+
const pushEvent = (event: SpanEvent): void => {
|
|
271
|
+
if (events.length < MAX_SPAN_EVENTS) events.push(event);
|
|
272
|
+
else droppedEventsCount += 1;
|
|
273
|
+
};
|
|
274
|
+
// Read only for a span that can be exported: an unsampled one never reports a time.
|
|
275
|
+
const startedAt = sampled ? clock.now().getTime() : 0;
|
|
276
|
+
const startedMono = sampled ? clock.monotonic() : 0;
|
|
225
277
|
let status: SpanStatus = { code: 'unset' };
|
|
226
278
|
let ended = false;
|
|
227
279
|
|
|
@@ -242,7 +294,8 @@ export function startSpan(initialName: string, options?: StartSpanOptions): Span
|
|
|
242
294
|
return span;
|
|
243
295
|
},
|
|
244
296
|
addEvent(eventName, eventAttributes) {
|
|
245
|
-
|
|
297
|
+
if (!sampled) return span;
|
|
298
|
+
pushEvent({
|
|
246
299
|
name: eventName,
|
|
247
300
|
at: clock.now().getTime(),
|
|
248
301
|
attributes: eventAttributes ?? {},
|
|
@@ -257,11 +310,13 @@ export function startSpan(initialName: string, options?: StartSpanOptions): Span
|
|
|
257
310
|
// A throw here substitutes the tracer's own TypeError for the caller's real failure and
|
|
258
311
|
// leaves the span it was annotating unended.
|
|
259
312
|
const message = renderThrowable(error);
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
313
|
+
if (sampled) {
|
|
314
|
+
pushEvent({
|
|
315
|
+
name: 'exception',
|
|
316
|
+
at: clock.now().getTime(),
|
|
317
|
+
attributes: { 'error.code': code, 'error.message': message },
|
|
318
|
+
});
|
|
319
|
+
}
|
|
265
320
|
status = { code: 'error', message };
|
|
266
321
|
return span;
|
|
267
322
|
},
|
|
@@ -280,10 +335,13 @@ export function startSpan(initialName: string, options?: StartSpanOptions): Span
|
|
|
280
335
|
// The whole point of propagating a sampling bit is that somebody obeys it. A span still
|
|
281
336
|
// exists, still parents its children and still carries the decision onward in
|
|
282
337
|
// `traceparent`; it is simply not exported.
|
|
283
|
-
if (
|
|
338
|
+
if (!sampled) return;
|
|
339
|
+
// Nobody exporting: no record is built. Checked after the sampling bit, so `span.end` is
|
|
340
|
+
// the export stream — a subscriber that wants every occurrence hears the domain event.
|
|
341
|
+
if (!subscribed('span.end')) return;
|
|
284
342
|
const endedAt = clock.now().getTime();
|
|
285
343
|
const parentSpanId = inbound?.spanId;
|
|
286
|
-
|
|
344
|
+
instrument('span.end', {
|
|
287
345
|
name,
|
|
288
346
|
kind: options?.kind ?? 'internal',
|
|
289
347
|
context,
|
|
@@ -293,6 +351,7 @@ export function startSpan(initialName: string, options?: StartSpanOptions): Span
|
|
|
293
351
|
durationMs: clock.monotonic() - startedMono,
|
|
294
352
|
attributes,
|
|
295
353
|
events,
|
|
354
|
+
droppedEventsCount,
|
|
296
355
|
status,
|
|
297
356
|
links: options?.links ?? [],
|
|
298
357
|
resource,
|
package/src/type-pins.ts
CHANGED
|
@@ -16,7 +16,8 @@ import type {
|
|
|
16
16
|
} from './config';
|
|
17
17
|
import type { CtxPatch } from './context';
|
|
18
18
|
import type { Page } from './cursor-page';
|
|
19
|
-
import type {
|
|
19
|
+
import type { ErrorReporter, ErrorReportingOptions } from './error-reporter';
|
|
20
|
+
import type { HydrateStrategy, OfflineStrategy, RenderMode, Surface } from './route-vocabulary';
|
|
20
21
|
|
|
21
22
|
/** Fails to compile when `T` is anything but `true`. The whole mechanism. */
|
|
22
23
|
type Assert<T extends true> = T;
|
|
@@ -151,27 +152,18 @@ type _CacheInputCarriesNoDeadField = Assert<
|
|
|
151
152
|
>;
|
|
152
153
|
|
|
153
154
|
/**
|
|
154
|
-
* The
|
|
155
|
-
*
|
|
156
|
-
*
|
|
157
|
-
*
|
|
158
|
-
*
|
|
155
|
+
* The `config.realtime` fields deleted for the same rule — `heartbeatMs` (2026-08-19), `tier`
|
|
156
|
+
* (2026-08-23), and `transport`/`urlEnv` (31.0.0). `tier` accepted three values with three
|
|
157
|
+
* documented meanings that were one behaviour; `transport` was a closed two-bus union in front of an
|
|
158
|
+
* adapter port, and `@ultimat3/realtime` stopped reading both it and `urlEnv` when `NATS_URL` became
|
|
159
|
+
* the env default and `runtime.ts`'s `transport` the override. Re-adding either is a second selector.
|
|
159
160
|
*/
|
|
160
|
-
type DeadRealtimeField = 'tier' | 'heartbeatMs';
|
|
161
|
+
type DeadRealtimeField = 'tier' | 'heartbeatMs' | 'transport' | 'urlEnv';
|
|
161
162
|
|
|
162
163
|
type _RealtimeConfigCarriesNoDeadField = Assert<
|
|
163
164
|
Extract<keyof RealtimeConfig, DeadRealtimeField> extends never ? true : false
|
|
164
165
|
>;
|
|
165
166
|
|
|
166
|
-
/**
|
|
167
|
-
* `'redis'` accepted, built by nothing, and booted whichever bus `NATS_URL` chose — removed in
|
|
168
|
-
* 22.0.0 when `selectTransport` began building what `transport` says. Re-adding it to the union is
|
|
169
|
-
* a type that promises a bus the framework does not have.
|
|
170
|
-
*/
|
|
171
|
-
type _RealtimeTransportHasNoRedis = Assert<
|
|
172
|
-
'redis' extends RealtimeConfig['transport'] ? false : true
|
|
173
|
-
>;
|
|
174
|
-
|
|
175
167
|
/** And the input side with it — `Input<RealtimeConfig>` is what an `app.config.ts` writes. */
|
|
176
168
|
type _RealtimeInputCarriesNoDeadField = Assert<
|
|
177
169
|
Extract<keyof NonNullable<AppConfigInput['realtime']>, DeadRealtimeField> extends never
|
|
@@ -221,6 +213,9 @@ type _HydrateStrategyIsItsArray = Assert<
|
|
|
221
213
|
Exact<HydrateStrategy, 'idle' | 'visible' | 'interaction' | 'never'>
|
|
222
214
|
>;
|
|
223
215
|
|
|
216
|
+
/** Render's boundary table, seo's route records and cli's filters all read this one (D7). */
|
|
217
|
+
type _SurfaceIsItsArray = Assert<Exact<Surface, 'site' | 'app' | 'api' | 'shared'>>;
|
|
218
|
+
|
|
224
219
|
/**
|
|
225
220
|
* The cache ladder's rungs, same rule as the three above and for a defect that shipped: 8.0.0's
|
|
226
221
|
* `CacheTier` was a hand-written union in `config.ts` — `memo | lru | shared | isr | cdn` — while
|
|
@@ -269,3 +264,11 @@ export type _HasMoreNarrowsCursor = Assert<
|
|
|
269
264
|
export type _LastPageHasNoCursor = Assert<
|
|
270
265
|
Extract<Page<number>, { readonly hasMore: false }>['nextCursor'] extends null ? true : false
|
|
271
266
|
>;
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* `configureErrorReporting` takes no reporter (31.0.0): the reporter is the `errorReporter` port's,
|
|
270
|
+
* installed by the boot through `installErrorReporter`. A second door would be a second answer.
|
|
271
|
+
*/
|
|
272
|
+
type _NoReporterOption = Assert<
|
|
273
|
+
{ readonly reporter: ErrorReporter } extends ErrorReportingOptions ? false : true
|
|
274
|
+
>;
|
package/src/log-tee.ts
DELETED
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
// Single responsibility: `addLogSink` — the supported tee of every default-writer log line, beside
|
|
2
|
-
// the process's streams and never instead of them (`setLogSink` is the test seam that replaces).
|
|
3
|
-
// Total: a sink that throws or logs cannot cost the line, the other sinks, or the process.
|
|
4
|
-
|
|
5
|
-
import { systemClock } from './clock';
|
|
6
|
-
import { renderThrowable } from './error-render';
|
|
7
|
-
import type { LogLevel, LogSink } from './logger';
|
|
8
|
-
|
|
9
|
-
let sinks: readonly LogSink[] = [];
|
|
10
|
-
/** Set while sinks run: a line a sink logs reaches the streams, never the tee it came from. */
|
|
11
|
-
let teeing = false;
|
|
12
|
-
/** Each sink says it failed ONCE — a sink that throws on every line would double the log. */
|
|
13
|
-
const reported = new WeakSet<LogSink>();
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Tee every line the process logger writes — the complete JSON line, AFTER redaction, and its
|
|
17
|
-
* level — to `sink`, in addition to stdout/stderr (or a `setLogSink` test sink). Returns the
|
|
18
|
-
* unsubscribe; calling it twice is a no-op.
|
|
19
|
-
*
|
|
20
|
-
* The population is `setLogSink`'s: every logger without its own `writer` — `logger`, every
|
|
21
|
-
* `child()` of it, `ctx.logger`. Sinks run synchronously, in the order added, after the line is
|
|
22
|
-
* written; one added while a line is being teed sees the next line, not that one. A sink that
|
|
23
|
-
* throws is skipped for that line and reported once as `log.sink_failed` on the streams; a line a
|
|
24
|
-
* sink logs itself is written but not teed back into the sinks.
|
|
25
|
-
*/
|
|
26
|
-
export function addLogSink(sink: LogSink): () => void {
|
|
27
|
-
sinks = [...sinks, sink];
|
|
28
|
-
return () => {
|
|
29
|
-
sinks = sinks.filter((candidate) => candidate !== sink);
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/** How many sinks are teeing now — a count that climbs across a test is an unsubscribe missed. */
|
|
34
|
-
export function logTeeCount(): number {
|
|
35
|
-
return sinks.length;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/** Called by the logger's default writer after `write` has put the line on the streams. */
|
|
39
|
-
export function teeLogLine(line: string, level: LogLevel, write: LogSink): void {
|
|
40
|
-
if (teeing || sinks.length === 0) return;
|
|
41
|
-
teeing = true;
|
|
42
|
-
try {
|
|
43
|
-
for (const sink of sinks) {
|
|
44
|
-
try {
|
|
45
|
-
sink(line, level);
|
|
46
|
-
} catch (thrown) {
|
|
47
|
-
reportOnce(sink, thrown, write);
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
} finally {
|
|
51
|
-
teeing = false;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/** Straight to the streams, never through the logger: the logger is what called the sink. */
|
|
56
|
-
function reportOnce(sink: LogSink, thrown: unknown, write: LogSink): void {
|
|
57
|
-
if (reported.has(sink)) return;
|
|
58
|
-
reported.add(sink);
|
|
59
|
-
try {
|
|
60
|
-
write(
|
|
61
|
-
JSON.stringify({
|
|
62
|
-
ts: systemClock.now().toISOString(),
|
|
63
|
-
level: 'warn',
|
|
64
|
-
msg: 'log.sink_failed',
|
|
65
|
-
cause: `a log sink added with addLogSink threw ${renderThrowable(thrown)}; it is skipped for that line and still called for the next — this is reported once per sink`,
|
|
66
|
-
fix: 'addLogSink((line, level) => { try { store(line, level); } catch { /* drop it: a sink must not throw */ } })',
|
|
67
|
-
}),
|
|
68
|
-
'warn',
|
|
69
|
-
);
|
|
70
|
-
} catch {
|
|
71
|
-
// The streams themselves are gone; there is nowhere left to say it.
|
|
72
|
-
}
|
|
73
|
-
}
|