// W3C TRACE CONTEXT across a World (https://www.w3.org/TR/trace-context/): one cause followed across // vendors by the tracing standard, never an id of our own. An app instrumented with OpenTelemetry // sends `traceparent` on its outgoing calls; a real vendor ignores it, so the vendor wire is // unchanged. The kernel serve seams (twin-fetch.ts, derived.ts) run a handler inside the request's // valid traceparent; every entry appended while handling it records that value (actions.ts // `traceparent`, authoring metadata excluded from replay identity like `correlationId`); and a // pack's outbound delivery the write caused (a webhook to the app) carries a CHILD of it — the // same trace-id, a new parent-id — so the app's handler continues the same trace. // // Nothing here is vendor knowledge, and nothing runs at import: the async-context store is made on // first use (a browser bundle carrying the kernel and has no AsyncLocalStorage). import { AsyncLocalStorage } from 'node:async_hooks'; export const TRACEPARENT_HEADER = 'traceparent'; // version-traceid-parentid-flags, lowercase hex only (the spec's HEXDIGLC). Version ff is invalid; // a future version is read by its version-00 prefix only when nothing else follows, which keeps the // accepted form exactly the one this module emits. const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/; const ZERO_TRACE = '0'.repeat(32); const ZERO_SPAN = '0'.repeat(16); export type Traceparent = { version: string; traceId: string; parentId: string; flags: string }; /** A `traceparent` header value parsed strictly, or null: malformed, version `ff`, or an all-zero * trace-id or parent-id is no trace at all (the spec: such a header is ignored). */ export function parseTraceparent(value: unknown): Traceparent | null { if (typeof value !== 'string') return null; const m = TRACEPARENT.exec(value.trim()); if (!m) return null; const [, version, traceId, parentId, flags] = m as unknown as [string, string, string, string, string]; if (version === 'ff' || traceId === ZERO_TRACE || parentId === ZERO_SPAN) return null; return { version, traceId, parentId, flags }; } /** The value itself when it is a valid traceparent (normalized: trimmed), else undefined. */ export function validTraceparent(value: unknown): string | undefined { const parsed = parseTraceparent(value); return parsed ? `${parsed.version}-${parsed.traceId}-${parsed.parentId}-${parsed.flags}` : undefined; } // created on first use, never at import (see the header) let traceStore: AsyncLocalStorage | undefined; const traceScope = (): AsyncLocalStorage => (traceStore ??= new AsyncLocalStorage()); /** Run `fn` with `traceparent` as the request's trace context; an invalid value runs `fn` outside any. */ export function runWithTraceparent(traceparent: string | undefined, fn: () => T): T { const valid = validTraceparent(traceparent); return valid ? traceScope().run(valid, fn) : fn(); } /** The trace context of the request being handled, when it carried a valid traceparent. */ export function currentTraceparent(): string | undefined { return traceStore?.getStore(); } /** Run `fn` inside the trace context `request` carries (its `traceparent` header), if any. */ export function runWithRequestTrace(request: Request, fn: () => T): T { return runWithTraceparent(request.headers.get(TRACEPARENT_HEADER) ?? undefined, fn); } /** A new trace's `traceparent` (version 00, a fresh trace-id and parent-id, sampled): for a request that carried none, * so what it causes can be told apart and joined to it. */ export function newTraceparent(): string { const bytes = new Uint8Array(16); let trace = ''; do { globalThis.crypto.getRandomValues(bytes); trace = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''); } while (/^0+$/.test(trace)); return `00-${trace}-${newSpanId()}-01`; } function newSpanId(): string { const bytes = new Uint8Array(8); for (;;) { globalThis.crypto.getRandomValues(bytes); const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''); if (hex !== ZERO_SPAN) return hex; } } /** * The `traceparent` an outbound delivery carries: a CHILD of its cause — the same trace-id and * flags, a new parent-id — so the receiving handler continues the cause's trace. The cause is the * given traceparent, or an entry's recorded one, or (omitted) the trace context of the request * being handled. No valid cause, no traceparent: a delivery never invents a trace. */ export function traceparentForDelivery(cause?: string | { traceparent?: unknown } | null): string | undefined { const source = cause === undefined ? currentTraceparent() : typeof cause === 'string' ? cause : cause?.traceparent; const parent = parseTraceparent(source); return parent ? `00-${parent.traceId}-${newSpanId()}-${parent.flags}` : undefined; } /** `traceparentForDelivery` as headers to spread into a delivery's own: `{ traceparent }` or `{}`. */ export function deliveryTraceHeaders(cause?: string | { traceparent?: unknown } | null): Record { const traceparent = traceparentForDelivery(cause); return traceparent ? { [TRACEPARENT_HEADER]: traceparent } : {}; }