import type * as api from '@opentelemetry/api'; import type { Span, SpanKind, SpanOptions } from '@opentelemetry/api'; import { globalSingleton, once } from '@workflow/utils'; import { WorkflowSuspension } from './global.js'; import { runtimeLogger } from './logger.js'; import * as Attr from './telemetry/semantic-conventions.js'; // ============================================================ // Trace Context Propagation Utilities // ============================================================ /** * Controls how workflow/step queue-handler spans relate to the run-origin * trace context carried in queue messages: * * - `'linked'` (default): each invocation starts a NEW root trace; the * run-origin context (and the incoming delivery context) are attached as * span links. This keeps traces bounded per invocation instead of * stitching a long-lived run into one giant trace. * - `'continuous'`: the restored run-origin context becomes the parent of * the invocation span (legacy behavior), producing a single trace that * spans the entire run. */ export type WorkflowTraceMode = 'linked' | 'continuous'; /** * Unrecognized `WORKFLOW_TRACE_MODE` values we already warned about. On * `globalThis` (see `globalSingleton`) so the warning stays once per process * rather than once per bundler layer. */ const traceModeWarnings = globalSingleton( '@workflow/core//traceModeWarnings', 1, () => ({ unrecognized: new Set() }) ); /** * Resolves the active trace mode from the `WORKFLOW_TRACE_MODE` env var. * Defaults to `'linked'`; any value other than `'continuous'` selects it. * Unrecognized non-empty values (e.g. typos like `continous`) emit a * one-time warning so silent fallback to `linked` is at least visible. */ export function getWorkflowTraceMode(): WorkflowTraceMode { const value = process.env.WORKFLOW_TRACE_MODE; if (value === 'continuous') return 'continuous'; if ( value && value !== 'linked' && !traceModeWarnings.unrecognized.has(value) ) { traceModeWarnings.unrecognized.add(value); runtimeLogger.warn( `Unrecognized WORKFLOW_TRACE_MODE value "${value}"; expected "linked" or "continuous". Falling back to "linked".` ); } return 'linked'; } /** * Returns whether a serialized trace carrier is usable, i.e. present and * non-empty. `serializeTraceCarrier()` returns `{}` when no OTEL SDK is * registered or no span is active, and `start()` always attaches the * carrier to the first queue message, so an empty carrier must be treated * the same as an absent one wherever the trace-mode logic branches. */ export function isUsableTraceCarrier( carrier: Record | undefined ): carrier is Record { return carrier !== undefined && Object.keys(carrier).length > 0; } /** * Returns the trace carrier to attach to messages the current invocation * enqueues. In `linked` mode the ORIGINAL run-origin carrier is forwarded * unchanged (when usable) so every future invocation links back to the same * origin; otherwise (`continuous` mode, or no usable incoming carrier) * the current (active) context is serialized, so the trace keeps chaining * (continuous) or the first instrumented invocation becomes the de-facto * origin (linked). */ export function getNextTraceCarrier( traceMode: WorkflowTraceMode, incomingCarrier: Record | undefined ): Promise> { return traceMode === 'linked' && isUsableTraceCarrier(incomingCarrier) ? Promise.resolve(incomingCarrier) : serializeTraceCarrier(); } /** * Builds the span links for a queue-delivered invocation span * (`workflow.execute` / `step.execute`): * * - In `linked` mode the invocation span is a CHILD of the local delivery * (flow-route) context, so the only link is to the run-origin context * from the message's trace carrier, connecting this bounded per-invocation * trace back to where the run was started. The run-origin context is a * link, never a parent, and re-enqueues forward the original carrier * unchanged, so the whole run is never stitched into one giant trace. * The link is skipped when the carrier is absent, empty, or invalid. * - In `continuous` mode the run-origin context is restored as the parent * instead, and the link points at the incoming delivery context. */ export async function buildInvocationSpanLinks( traceMode: WorkflowTraceMode, incomingCarrier: Record | undefined ): Promise { if (traceMode !== 'linked') return linkToCurrentContext(); const originLink = await linkToTraceCarrier( isUsableTraceCarrier(incomingCarrier) ? incomingCarrier : undefined ); return originLink ? [originLink] : undefined; } /** * Serializes the current trace context into a format that can be passed through queues * @returns A record of strings representing the trace context */ export async function serializeTraceCarrier(): Promise> { const otel = await OtelApi.value; if (!otel) return {}; const carrier: Record = {}; // Inject the current context into the carrier otel.propagation.inject(otel.context.active(), carrier); return carrier; } /** * Deserializes trace context and returns a context that can be used to continue the trace * @param traceCarrier The serialized trace context * @returns OpenTelemetry context with the restored trace */ export async function deserializeTraceCarrier( traceCarrier: Record ) { const otel = await OtelApi.value; if (!otel) return; // Extract the context from the carrier return otel.propagation.extract(otel.context.active(), traceCarrier); } /** * Runs a function within the context of a deserialized trace * @param traceCarrier The serialized trace carrier (optional) * @param fn The function to run within the trace context * @returns The result of the function */ export async function withTraceContext( traceCarrier: Record | undefined, fn: () => Promise ): Promise { if (!traceCarrier) { return fn(); } const otel = await OtelApi.value; if (!otel) return fn(); const extractedContext = await deserializeTraceCarrier(traceCarrier); if (!extractedContext) { return fn(); } return otel.context.with(extractedContext, async () => await fn()); } const OtelApi = once(async () => { // `@opentelemetry/api` is an optional peer dependency. The static specifier // is intentional: esbuild-bundled targets (the CLI's // `vercel-build-output-api` build, Nitro, Astro) ship a self-contained // bundle with no node_modules, so the package must be *inlined* at build // time for spans to work at runtime; a runtime-built specifier is opaque to // esbuild and would silently disable tracing there. Bundlers that reject an // unresolvable static `import()` when the peer isn't installed (Rollup/Vite, // e.g. SvelteKit) instead externalize `@opentelemetry/api` in the workflow // framework integration, which keeps the build green and still loads real // OTel when the peer is present. Runtime semantics: present → loaded, absent // → caught and tracing disabled. try { return await import('@opentelemetry/api'); } catch { runtimeLogger.info('OpenTelemetry not available, tracing will be disabled'); return null; } }); const Tracer = once(async () => { const api = await OtelApi.value; if (!api) return null; const tracer = api.trace.getTracer('workflow'); logOtelDiagnosticOnce(api, tracer); return tracer; }); const StepExecutionDurationHistogram = once(async () => { const otel = await OtelApi.value; if (!otel) return null; // service.name is a resource attribute, applied by the configured provider. return otel.metrics .getMeter('workflow') .createHistogram('workflow.step.execute.duration', { description: 'Duration of user step execution', unit: 'ms', }); }); const QueueDeliveryRefusedCounter = once(async () => { const otel = await OtelApi.value; if (!otel) return null; return otel.metrics .getMeter('workflow') .createCounter('workflow.queue.delivery.refused', { description: 'Queue deliveries a route refused because they did not carry the process queue key', unit: '{delivery}', }); }); /** * One-shot runtime diagnostic (DEBUG=workflow:* only), same shape as the one * world-vercel emits tagged `world-vercel`: prints how this module instance * of `@opentelemetry/api` sees the global registration, so a deployment's * logs show the two packages' views side by side. */ // per-copy-ok: this diagnostic reports how THIS module instance sees the global // OTel registration, which is the whole point of the log. With several copies // in a process, each one's view is what is worth seeing. let otelDiagLogged = false; function describeThrownValue(value: unknown): string { try { if ( typeof value === 'object' && value !== null && 'message' in value && typeof value.message === 'string' ) { return value.message; } return String(value); } catch { return 'Unknown error'; } } function logOtelDiagnosticOnce(otel: typeof api, tracer: api.Tracer): void { const debugEnabled = typeof process !== 'undefined' && typeof process.env.DEBUG === 'string' && (process.env.DEBUG.includes('workflow:') || process.env.DEBUG === '*'); if (otelDiagLogged || !debugEnabled) return; otelDiagLogged = true; try { const g = (globalThis as Record)[ Symbol.for('opentelemetry.js.api.1') ] as { version?: string } | undefined; const provider = otel.trace.getTracerProvider(); const delegate = (provider as { getDelegate?: () => unknown }).getDelegate?.() ?? provider; const probe = tracer.startSpan('workflow.otel.probe.core'); console.warn( '[workflow:otel-diag] core', JSON.stringify({ globalRegistrationVersion: g?.version ?? null, providerCtor: provider?.constructor?.name ?? null, delegateCtor: (delegate as object | null)?.constructor?.name ?? null, tracerCtor: tracer?.constructor?.name ?? null, probeCtor: probe?.constructor?.name ?? null, probeRecording: probe.isRecording(), }) ); probe.end(); } catch (error) { console.warn( '[workflow:otel-diag] core failed:', error instanceof Error ? error.message : error ); } } export async function trace( spanName: string, ...args: | [fn: (span?: Span) => Promise] | [opts: SpanOptions, fn: (span?: Span) => Promise] ): Promise { const [tracer, otel] = await Promise.all([Tracer.value, OtelApi.value]); const { fn, opts } = typeof args[0] === 'function' ? { fn: args[0], opts: {} } : { fn: args[1], opts: args[0] }; if (!fn) throw new Error('Function to trace must be provided'); if (!tracer || !otel) { return await fn(); } return tracer.startActiveSpan(spanName, opts, async (span) => { try { const result = await fn(span); span.setStatus({ code: otel.SpanStatusCode.OK }); return result; } catch (e) { if (WorkflowSuspension.is(e)) { span.setStatus({ code: otel.SpanStatusCode.OK }); applyWorkflowSuspensionToSpan(e, span); } else { span.setStatus({ code: otel.SpanStatusCode.ERROR, message: describeThrownValue(e), }); } throw e; } finally { span.end(); } }); } /** Starts a child span without installing it as the active context. */ export async function startTraceSpan(spanName: string) { const [tracer, otel] = await Promise.all([Tracer.value, OtelApi.value]); if (!tracer || !otel) return { end() {}, fail() {} }; const span = tracer.startSpan(spanName); let ended = false; const finish = (status: api.SpanStatus) => { if (ended) return; ended = true; span.setStatus(status); span.end(); }; return { end: () => finish({ code: otel.SpanStatusCode.OK }), fail: (error: unknown) => finish({ code: otel.SpanStatusCode.ERROR, message: describeThrownValue(error), }), }; } /** Bind work to the currently active span even when it starts from a child. */ export async function bindActiveTraceContext( fn: (...args: Args) => Result ): Promise<(...args: Args) => Result> { const otel = await OtelApi.value; return otel ? otel.context.bind(otel.context.active(), fn) : fn; } /** Keeps a parked workflow's ambient trace context aligned with each resume. */ export async function createRefreshableTraceContext() { const otel = await OtelApi.value; if (!otel) { return { refresh() {}, run: (fn: () => T): T => fn() }; } let current = otel.context.active(); const context: api.Context = { getValue: (key) => current.getValue(key), setValue: (key, value) => current.setValue(key, value), deleteValue: (key) => current.deleteValue(key), }; return { refresh: () => { current = otel.context.active(); }, run: (fn: () => T): T => otel.context.with(context, fn), }; } /** * Emit a span whose start is back-dated to `startEpochMs` and whose end is now, * so its duration reflects an interval only measurable at its end (e.g. * time-to-first-chunk, known when the first chunk arrives). Unlike `trace()`, * this records an already-elapsed span in one shot rather than wrapping a * callback. No-op when OpenTelemetry is not available. */ export async function recordElapsedSpan( spanName: string, startEpochMs: number, opts?: SpanOptions ): Promise { const tracer = await Tracer.value; if (!tracer) return; tracer.startSpan(spanName, { ...opts, startTime: startEpochMs }).end(); } /** * Records the same user-code interval as the inner `step.execute` span. The * configured OpenTelemetry meter provider attaches resource dimensions such as * service.name, so this avoids accepting a caller-controlled service tag. */ export async function recordStepExecutionDuration( durationMs: number, status: 'ok' | 'error' ): Promise { const histogram = await StepExecutionDurationHistogram.value; histogram?.record(durationMs, { 'workflow.step.status': status }); } /** * Counts one delivery a queue route refused with a 401 (see * `authorizeQueueDelivery`): the operator's signal for a forgery storm or a * mass refusal from a misconfigured sender. Every refusal is counted, unlike * the rate-limited log. Dimensions are bounded: the World target, the route's * path (fixed by the app), and whether the request carried a key at all. */ export async function recordQueueDeliveryRefused(attributes: { world: string; route: string; reason: 'no-key' | 'wrong-key'; }): Promise { const counter = await QueueDeliveryRefusedCounter.value; counter?.add(1, { 'workflow.world': attributes.world, 'http.route': attributes.route, 'workflow.queue.refusal_reason': attributes.reason, }); } /** * Applies the workflow suspension algebraic effect to an active span. */ export function applyWorkflowSuspensionToSpan( error: WorkflowSuspension, span: api.Span ): void { span.setAttributes({ ...Attr.WorkflowSuspensionState('suspended'), ...Attr.WorkflowSuspensionStepCount(error.stepCount), ...Attr.WorkflowSuspensionHookCount(error.hookCount), ...Attr.WorkflowSuspensionWaitCount(error.waitCount), }); } export async function getSpanContextForTraceCarrier( carrier: Record ) { const [deserialized, otel] = await Promise.all([ deserializeTraceCarrier(carrier), OtelApi.value, ]); if (!deserialized || !otel) return; return otel.trace.getSpanContext(deserialized); } export async function getActiveSpan() { return await withOtel((otel) => otel.trace.getActiveSpan()); } /** * Wraps all methods of an object with tracing spans. * @param prefix - Prefix for span names (e.g., "WORLD.runs") * @param o - Object with methods to instrument * @returns Instrumented object with same interface */ export function instrumentObject(prefix: string, o: T): T { const handlers = {} as T; for (const key of Object.keys(o) as (keyof T)[]) { if (typeof o[key] !== 'function') { handlers[key] = o[key]; } else { const f = o[key]; // @ts-expect-error handlers[key] = async (...args: any[]) => trace(`${prefix}.${String(key)}`, {}, () => f(...args)); } } return handlers; } export async function getSpanKind(field: keyof typeof SpanKind) { return withOtel((x) => x.SpanKind[field]); } export async function withOtel( fn: (otel: typeof api) => T ): Promise | undefined> { const otel = await OtelApi.value; if (!otel) return undefined; return await fn(otel); } export function linkToCurrentContext(): Promise<[api.Link] | undefined> { return withOtel((otel): [api.Link] | undefined => { const context = otel.trace.getActiveSpan()?.spanContext(); if (!context) return; return [{ context }]; }); } /** * Builds a span link pointing at the span context embedded in a serialized * trace carrier (e.g. the run-origin context flowing through queue * messages). Returns `undefined` when OTEL is unavailable, the carrier is * absent, or it does not contain a valid span context. */ export async function linkToTraceCarrier( carrier: Record | undefined ): Promise { if (!carrier) return; const [context, otel] = await Promise.all([ getSpanContextForTraceCarrier(carrier), OtelApi.value, ]); if (!context || !otel) return; if (!otel.trace.isSpanContextValid(context)) return; return { context }; } // ============================================================ // Baggage Propagation Utilities // ============================================================ /** * Workflow context to propagate via baggage */ export interface WorkflowBaggageContext { workflowRunId: string; workflowName: string; } /** * Sets workflow context as OTEL baggage for automatic propagation. * Baggage is propagated across service boundaries via HTTP headers. * @param context - Workflow context to set as baggage * @returns A function to run within the baggage context */ export async function withWorkflowBaggage( context: WorkflowBaggageContext, fn: () => Promise ): Promise { const otel = await OtelApi.value; if (!otel) return fn(); // Create baggage with workflow context const baggage = otel.propagation.createBaggage({ 'workflow.run_id': { value: context.workflowRunId }, 'workflow.name': { value: context.workflowName }, }); // Set baggage in context and run function const contextWithBaggage = otel.propagation.setBaggage( otel.context.active(), baggage ); return otel.context.with(contextWithBaggage, () => fn()); } /** * Retrieves workflow context from OTEL baggage. * @returns Workflow context if present in baggage, undefined otherwise */ export async function getWorkflowBaggage(): Promise< WorkflowBaggageContext | undefined > { const otel = await OtelApi.value; if (!otel) return undefined; const baggage = otel.propagation.getBaggage(otel.context.active()); if (!baggage) return undefined; const runId = baggage.getEntry('workflow.run_id')?.value; const name = baggage.getEntry('workflow.name')?.value; if (!runId || !name) return undefined; return { workflowRunId: runId, workflowName: name, }; }