@macss/modular-api 0.6.0 → 0.7.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.
@@ -43,12 +43,50 @@ export type WriteFn = (line: string) => void;
43
43
  * Accepts an optional `writeFn` for output — defaults to `console.log`.
44
44
  * In tests, pass a capturing function to inspect output without side-effects.
45
45
  */
46
+ /**
47
+ * Builds platform-specific correlation fields from the ids the framework resolved.
48
+ *
49
+ * The framework emits open formats and nothing vendor-specific (roadmap invariant 7), so
50
+ * a field like Google's `logging.googleapis.com/trace` — which needs a project id the
51
+ * framework has no business knowing — is produced by the application.
52
+ */
53
+ export type TraceFieldFormatter = (traceId: string, spanId: string | undefined) => Record<string, unknown>;
46
54
  export declare class RequestScopedLogger implements ModularLogger {
47
55
  readonly traceId: string;
48
56
  readonly logLevel: LogLevel;
49
57
  readonly serviceName: string;
50
58
  private readonly writeFn;
51
- constructor(traceId: string, logLevel: LogLevel, serviceName: string, writeFn?: WriteFn);
59
+ /**
60
+ * The caller's `X-Request-ID`, when it sent one. Preserved beside {@link traceId}
61
+ * rather than promoted into it (runbook D6).
62
+ */
63
+ readonly requestId?: string | undefined;
64
+ /**
65
+ * The active server span's id, when tracing is configured.
66
+ *
67
+ * Known at construction because the tracing middleware is **outermost** (runbook D12
68
+ * as reversed): the span already exists when `loggingMiddleware` creates this logger,
69
+ * so nothing needs mutating afterwards.
70
+ */
71
+ readonly spanId?: string | undefined;
72
+ /** Builds platform correlation fields. Undefined means none are emitted. */
73
+ private readonly traceFieldFormatter?;
74
+ constructor(traceId: string, logLevel: LogLevel, serviceName: string, writeFn?: WriteFn,
75
+ /**
76
+ * The caller's `X-Request-ID`, when it sent one. Preserved beside {@link traceId}
77
+ * rather than promoted into it (runbook D6).
78
+ */
79
+ requestId?: string | undefined,
80
+ /**
81
+ * The active server span's id, when tracing is configured.
82
+ *
83
+ * Known at construction because the tracing middleware is **outermost** (runbook D12
84
+ * as reversed): the span already exists when `loggingMiddleware` creates this logger,
85
+ * so nothing needs mutating afterwards.
86
+ */
87
+ spanId?: string | undefined,
88
+ /** Builds platform correlation fields. Undefined means none are emitted. */
89
+ traceFieldFormatter?: TraceFieldFormatter | undefined);
52
90
  emergency(msg: string, fields?: Record<string, unknown>): void;
53
91
  alert(msg: string, fields?: Record<string, unknown>): void;
54
92
  critical(msg: string, fields?: Record<string, unknown>): void;
@@ -34,25 +34,37 @@ const LEVEL_NAME = {
34
34
  [LogLevel.info]: 'info',
35
35
  [LogLevel.debug]: 'debug',
36
36
  };
37
- /**
38
- * Per-request logger that carries `traceId` and respects `logLevel` filtering.
39
- *
40
- * Created by `loggingMiddleware` for each incoming HTTP request and injected
41
- * into the UseCase via the `logger` property.
42
- *
43
- * Accepts an optional `writeFn` for output — defaults to `console.log`.
44
- * In tests, pass a capturing function to inspect output without side-effects.
45
- */
46
37
  class RequestScopedLogger {
47
38
  traceId;
48
39
  logLevel;
49
40
  serviceName;
50
41
  writeFn;
51
- constructor(traceId, logLevel, serviceName, writeFn = (line) => process.stdout.write(line + '\n')) {
42
+ requestId;
43
+ spanId;
44
+ traceFieldFormatter;
45
+ constructor(traceId, logLevel, serviceName, writeFn = (line) => process.stdout.write(line + '\n'),
46
+ /**
47
+ * The caller's `X-Request-ID`, when it sent one. Preserved beside {@link traceId}
48
+ * rather than promoted into it (runbook D6).
49
+ */
50
+ requestId,
51
+ /**
52
+ * The active server span's id, when tracing is configured.
53
+ *
54
+ * Known at construction because the tracing middleware is **outermost** (runbook D12
55
+ * as reversed): the span already exists when `loggingMiddleware` creates this logger,
56
+ * so nothing needs mutating afterwards.
57
+ */
58
+ spanId,
59
+ /** Builds platform correlation fields. Undefined means none are emitted. */
60
+ traceFieldFormatter) {
52
61
  this.traceId = traceId;
53
62
  this.logLevel = logLevel;
54
63
  this.serviceName = serviceName;
55
64
  this.writeFn = writeFn;
65
+ this.requestId = requestId;
66
+ this.spanId = spanId;
67
+ this.traceFieldFormatter = traceFieldFormatter;
56
68
  }
57
69
  // ─── Public API (8 RFC 5424 levels) ──────────────────────────────
58
70
  emergency(msg, fields) {
@@ -116,7 +128,14 @@ class RequestScopedLogger {
116
128
  msg,
117
129
  service: this.serviceName,
118
130
  trace_id: this.traceId,
131
+ ...(this.spanId === undefined ? {} : { span_id: this.spanId }),
132
+ ...(this.requestId === undefined ? {} : { request_id: this.requestId }),
119
133
  };
134
+ // Only when there is trace context to point at. A platform field naming a trace
135
+ // that does not exist is worse than no field.
136
+ if (this.traceFieldFormatter !== undefined && this.spanId !== undefined) {
137
+ Object.assign(entry, this.traceFieldFormatter(this.traceId, this.spanId));
138
+ }
120
139
  if (opts.extra)
121
140
  Object.assign(entry, opts.extra);
122
141
  if (opts.fields)
@@ -1,5 +1,5 @@
1
1
  import type { RequestHandler } from 'express';
2
- import { LogLevel } from './logger';
2
+ import { LogLevel, type TraceFieldFormatter } from './logger';
3
3
  import type { WriteFn } from './logger';
4
4
  /** Key used in `res.locals` to propagate the logger to downstream handlers. */
5
5
  export declare const LOGGER_LOCALS_KEY = "modularLogger";
@@ -9,6 +9,8 @@ export interface LoggingMiddlewareOptions {
9
9
  excludedRoutes?: string[];
10
10
  /** Override output for testing. Defaults to stdout. */
11
11
  writeFn?: WriteFn;
12
+ /** Builds platform correlation fields. Undefined means none are emitted. */
13
+ traceFieldFormatter?: TraceFieldFormatter;
12
14
  }
13
15
  /**
14
16
  * Creates an Express middleware that:
@@ -8,6 +8,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.LOGGER_LOCALS_KEY = void 0;
9
9
  exports.loggingMiddleware = loggingMiddleware;
10
10
  const node_crypto_1 = require("node:crypto");
11
+ const api_1 = require("@opentelemetry/api");
11
12
  const logger_1 = require("./logger");
12
13
  const request_pipeline_audit_1 = require("../request_pipeline_audit");
13
14
  /** Key used in `res.locals` to propagate the logger to downstream handlers. */
@@ -32,11 +33,28 @@ function loggingMiddleware(opts) {
32
33
  if (excludedSet.has(path)) {
33
34
  return next();
34
35
  }
35
- // 1. Resolve trace_id
36
+ // 1. Resolve the ids from the ambient span.
37
+ //
38
+ // The tracing middleware is outermost (D12 as reversed), so when tracing is
39
+ // configured a recording span is already active here — and it stays active for
40
+ // `request completed` too. That is what lets both lines carry the same ids with
41
+ // nothing mutated afterwards.
42
+ //
43
+ // With no recording span this is byte-for-byte the behaviour it always had: the
44
+ // caller's X-Request-ID or a fresh UUID. D5b's compatibility guarantee is therefore
45
+ // structural rather than conditional — there is no tracing flag to consult, only
46
+ // whether a span exists.
47
+ const activeSpan = api_1.trace.getSpan(api_1.context.active());
48
+ const activeSpanContext = activeSpan?.spanContext();
49
+ const tracingActive = activeSpanContext !== undefined && api_1.trace.isSpanContextValid(activeSpanContext);
36
50
  const headerValue = req.headers['x-request-id'];
37
- const traceId = typeof headerValue === 'string' && headerValue.length > 0 ? headerValue : (0, node_crypto_1.randomUUID)();
51
+ const callerRequestId = typeof headerValue === 'string' && headerValue.length > 0 ? headerValue : undefined;
52
+ const traceId = tracingActive ? activeSpanContext.traceId : (callerRequestId ?? (0, node_crypto_1.randomUUID)());
53
+ const spanId = tracingActive ? activeSpanContext.spanId : undefined;
54
+ // Preserved beside the trace id rather than promoted into it (D6).
55
+ const requestId = tracingActive ? callerRequestId : undefined;
38
56
  // 2. Create per-request logger
39
- const logger = new logger_1.RequestScopedLogger(traceId, opts.logLevel, opts.serviceName, opts.writeFn);
57
+ const logger = new logger_1.RequestScopedLogger(traceId, opts.logLevel, opts.serviceName, opts.writeFn, requestId, spanId, opts.traceFieldFormatter);
40
58
  const method = req.method.toUpperCase();
41
59
  const route = path;
42
60
  // 3. "request received"
@@ -2,6 +2,7 @@ import { type RequestHandler } from 'express';
2
2
  import { ModuleBuilder } from './module_builder';
3
3
  import type { HealthCheck } from './health/health_check';
4
4
  import { MetricsRegistrar } from './metrics/metric_registry';
5
+ import { TracingOptions } from './tracing/tracingOptions';
5
6
  import { LogLevel } from './logger/logger';
6
7
  import { type Plugin } from './plugin';
7
8
  import type { GraphqlOptions } from '../graphql/runtime/graphql_runtime_options';
@@ -28,6 +29,12 @@ export interface ModularApiOptions {
28
29
  * Default: LogLevel.info (emits emergency..info, suppresses debug).
29
30
  */
30
31
  logLevel?: LogLevel;
32
+ /**
33
+ * Opt-in distributed tracing. Absent means off and costs nothing: no tracing
34
+ * middleware is installed and no span is ever created. The application supplies
35
+ * the tracer provider; the framework depends on `@opentelemetry/api` only.
36
+ */
37
+ tracing?: TracingOptions;
31
38
  /**
32
39
  * OpenAPI `servers` list. Each entry has a `url` and optional `description`.
33
40
  * When omitted, `serve()` generates `[{url: 'http://localhost:{port}'}]`.
@@ -78,6 +85,8 @@ export declare class ModularApi {
78
85
  private readonly httpRequestsInFlight?;
79
86
  private readonly httpRequestDuration?;
80
87
  private readonly logLevel;
88
+ /** Distributed tracing options, or undefined when tracing is off (ADR-0005). */
89
+ private readonly tracing?;
81
90
  private readonly servers?;
82
91
  private readonly graphql?;
83
92
  /** Public accessor for custom-metric registration. Undefined when metrics are disabled. */
@@ -14,6 +14,9 @@ const module_builder_1 = require("./module_builder");
14
14
  const health_service_1 = require("./health/health_service");
15
15
  const metric_registry_1 = require("./metrics/metric_registry");
16
16
  const logging_middleware_1 = require("./logger/logging_middleware");
17
+ const api_1 = require("@opentelemetry/api");
18
+ const compositePropagator_1 = require("./tracing/compositePropagator");
19
+ const tracingMiddleware_1 = require("./tracing/tracingMiddleware");
17
20
  const logger_1 = require("./logger/logger");
18
21
  const body_parser_error_handler_1 = require("./body_parser_error_handler");
19
22
  const unhandled_request_error_handler_1 = require("./unhandled_request_error_handler");
@@ -60,6 +63,8 @@ class ModularApi {
60
63
  httpRequestDuration;
61
64
  // Logging
62
65
  logLevel;
66
+ /** Distributed tracing options, or undefined when tracing is off (ADR-0005). */
67
+ tracing;
63
68
  // OpenAPI
64
69
  servers;
65
70
  graphql;
@@ -81,6 +86,7 @@ class ModularApi {
81
86
  this.excludedMetricsRoutes = options.excludedMetricsRoutes ?? ['/metrics', '/health', '/docs'];
82
87
  // Logging
83
88
  this.logLevel = options.logLevel ?? logger_1.LogLevel.info;
89
+ this.tracing = options.tracing;
84
90
  // OpenAPI servers
85
91
  this.servers = options.servers;
86
92
  this.graphql = options.graphql;
@@ -234,10 +240,43 @@ class ModularApi {
234
240
  operationalPaths.openApiYamlPath,
235
241
  ...(operationalPaths.metricsPath ? [operationalPaths.metricsPath] : []),
236
242
  ];
243
+ // Tracing is the OUTERMOST middleware, with logging inside it (runbook D12 as
244
+ // reversed). The logger then runs within the span's active scope and reads
245
+ // `trace_id` and `span_id` from the ambient span on every line. An earlier design
246
+ // had this after logging, which forced the logger to own the trace id and the span
247
+ // to adopt it — and here that meant seeding a parent, whose trace flags made the
248
+ // default ParentBased sampler drop the span entirely.
249
+ //
250
+ // Absent options install nothing, which is what makes tracing free when it is off
251
+ // (gate G3).
252
+ const tracing = this.tracing;
253
+ if (tracing !== undefined) {
254
+ // Publish the chain as the global propagator, which is how satellite packages
255
+ // inject it. @macss/modular-api-rest-client does not depend on this package (D21),
256
+ // so it cannot reach our W3C propagator — and per the OpenTelemetry API's guidance
257
+ // it should not: instrumentation libraries read the global, the host sets it.
258
+ //
259
+ // That indirection also means whatever chain the application configured is honoured
260
+ // on outbound calls, including a Cloud Trace propagator it appended.
261
+ const propagators = tracing.policy.propagators;
262
+ if (propagators.length > 0) {
263
+ api_1.propagation.setGlobalPropagator(propagators.length === 1
264
+ ? propagators[0]
265
+ : new compositePropagator_1.CompositeTextMapPropagator(propagators));
266
+ }
267
+ this.app.use((0, tracingMiddleware_1.tracingMiddleware)({
268
+ tracer: tracing.tracer,
269
+ policy: tracing.policy,
270
+ excludedRoutes: excludedLogRoutes,
271
+ }));
272
+ }
237
273
  this.app.use((0, logging_middleware_1.loggingMiddleware)({
238
274
  logLevel: this.logLevel,
239
275
  serviceName: this.title,
240
276
  excludedRoutes: excludedLogRoutes,
277
+ ...(this.tracing?.traceFieldFormatter === undefined
278
+ ? {}
279
+ : { traceFieldFormatter: this.tracing.traceFieldFormatter }),
241
280
  }));
242
281
  // Body parsing AFTER loggingMiddleware — SyntaxErrors now have trace_id.
243
282
  this.app.use(express_1.default.json());
@@ -266,7 +305,25 @@ class ModularApi {
266
305
  resolve(server);
267
306
  });
268
307
  server.on('close', () => {
269
- void pluginHost.shutdown();
308
+ // Tracing's shutdown callback runs alongside the plugin host's, not as a plugin.
309
+ // There is deliberately no tracing plugin: every responsibility ADR-0005 decision
310
+ // 4 gave one was reassigned by a later decision, and what remained was a plugin
311
+ // whose setup() did nothing (see ADR-0005 A7).
312
+ //
313
+ // The framework owns the timing; the application owns the provider. A callback
314
+ // that rejects is swallowed — losing telemetry is bad, failing to stop is worse.
315
+ const onShutdown = this.tracing?.onShutdown;
316
+ void (async () => {
317
+ if (onShutdown !== undefined) {
318
+ try {
319
+ await onShutdown();
320
+ }
321
+ catch {
322
+ // Intentionally ignored.
323
+ }
324
+ }
325
+ await pluginHost.shutdown();
326
+ })();
270
327
  });
271
328
  });
272
329
  }
@@ -11,9 +11,9 @@ export interface UseCaseOptions {
11
11
  /** Override output schema for OpenAPI (if fromJson fails with empty data) */
12
12
  outputSchema?: Record<string, unknown>;
13
13
  /** Input class for pre-validation and schema extraction (enables strict fromJson). */
14
- inputClass: abstract new (...args: unknown[]) => Input;
14
+ inputClass: abstract new (...args: never[]) => Input;
15
15
  /** Output class for schema extraction. */
16
- outputClass: abstract new (...args: unknown[]) => Output;
16
+ outputClass: abstract new (...args: never[]) => Output;
17
17
  }
18
18
  /**
19
19
  * Fluent builder that registers use cases on a module-scoped Express Router.
@@ -57,5 +57,5 @@ export declare const Field: {
57
57
  * Retrieves the `@Field` metadata registered on a class.
58
58
  * Returns an empty array if the class has no decorated fields.
59
59
  */
60
- export declare function getFieldMetadata(target: abstract new (...args: unknown[]) => unknown): FieldMeta[];
60
+ export declare function getFieldMetadata(target: abstract new (...args: never[]) => unknown): FieldMeta[];
61
61
  export {};
@@ -0,0 +1,33 @@
1
+ import { type Context, type TextMapGetter, type TextMapPropagator, type TextMapSetter } from '@opentelemetry/api';
2
+ /** The carrier key this propagator reads and writes. */
3
+ export declare const CLOUD_TRACE_CONTEXT_HEADER = "x-cloud-trace-context";
4
+ /**
5
+ * Propagates Google Cloud's legacy `X-Cloud-Trace-Context` header.
6
+ *
7
+ * The OTel API ships W3C `traceparent` and Baggage propagators but no Google
8
+ * Cloud propagator, so this one is ours. Cloud Run injects both headers; W3C is
9
+ * preferred and this is the documented fallback, which is why the precedence
10
+ * policy consults it second.
11
+ *
12
+ * Format: `TRACE_ID/SPAN_ID;o=OPTIONS`, where
13
+ *
14
+ * - `TRACE_ID` is 32 hex characters, case-insensitive per Google's docs;
15
+ * - **`SPAN_ID` is the decimal representation of an unsigned 64-bit integer** —
16
+ * not hex. Reading it as hex yields a wrong parent and a silently broken
17
+ * waterfall, which is the most likely defect in this file. JavaScript's Number
18
+ * cannot hold 2^64-1 either, so the conversion goes through BigInt.
19
+ * - `OPTIONS` carries `o=1` (parent sampled) or `o=0` (not sampled).
20
+ *
21
+ * Header-name casing is deliberately not this class's concern. HTTP header
22
+ * semantics belong to the carrier, so {@link fields} returns the lowercase
23
+ * canonical name and lookup goes through the supplied getter.
24
+ *
25
+ * The Dart counterpart is `lib/src/core/tracing/cloud_trace_propagator.dart`.
26
+ * Same behaviour; this version leans on `isValidTraceId` / `isValidSpanId`, which
27
+ * the JavaScript API provides and the Dart API does not.
28
+ */
29
+ export declare class CloudTraceContextPropagator implements TextMapPropagator<unknown> {
30
+ fields(): string[];
31
+ inject(context: Context, carrier: unknown, setter: TextMapSetter<unknown>): void;
32
+ extract(context: Context, carrier: unknown, getter: TextMapGetter<unknown>): Context;
33
+ }
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CloudTraceContextPropagator = exports.CLOUD_TRACE_CONTEXT_HEADER = void 0;
4
+ const api_1 = require("@opentelemetry/api");
5
+ /** The carrier key this propagator reads and writes. */
6
+ exports.CLOUD_TRACE_CONTEXT_HEADER = 'x-cloud-trace-context';
7
+ const TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;
8
+ const DECIMAL_PATTERN = /^[0-9]+$/;
9
+ /** 2^64-1 — the span id is an unsigned 64-bit integer, so the bound is a BigInt. */
10
+ const MAX_UNSIGNED_64 = BigInt('0xffffffffffffffff');
11
+ /**
12
+ * Propagates Google Cloud's legacy `X-Cloud-Trace-Context` header.
13
+ *
14
+ * The OTel API ships W3C `traceparent` and Baggage propagators but no Google
15
+ * Cloud propagator, so this one is ours. Cloud Run injects both headers; W3C is
16
+ * preferred and this is the documented fallback, which is why the precedence
17
+ * policy consults it second.
18
+ *
19
+ * Format: `TRACE_ID/SPAN_ID;o=OPTIONS`, where
20
+ *
21
+ * - `TRACE_ID` is 32 hex characters, case-insensitive per Google's docs;
22
+ * - **`SPAN_ID` is the decimal representation of an unsigned 64-bit integer** —
23
+ * not hex. Reading it as hex yields a wrong parent and a silently broken
24
+ * waterfall, which is the most likely defect in this file. JavaScript's Number
25
+ * cannot hold 2^64-1 either, so the conversion goes through BigInt.
26
+ * - `OPTIONS` carries `o=1` (parent sampled) or `o=0` (not sampled).
27
+ *
28
+ * Header-name casing is deliberately not this class's concern. HTTP header
29
+ * semantics belong to the carrier, so {@link fields} returns the lowercase
30
+ * canonical name and lookup goes through the supplied getter.
31
+ *
32
+ * The Dart counterpart is `lib/src/core/tracing/cloud_trace_propagator.dart`.
33
+ * Same behaviour; this version leans on `isValidTraceId` / `isValidSpanId`, which
34
+ * the JavaScript API provides and the Dart API does not.
35
+ */
36
+ class CloudTraceContextPropagator {
37
+ fields() {
38
+ return [exports.CLOUD_TRACE_CONTEXT_HEADER];
39
+ }
40
+ inject(context, carrier, setter) {
41
+ const spanContext = api_1.trace.getSpanContext(context);
42
+ if (spanContext === undefined)
43
+ return;
44
+ if (!(0, api_1.isValidTraceId)(spanContext.traceId) || !(0, api_1.isValidSpanId)(spanContext.spanId))
45
+ return;
46
+ // Back to decimal, which is what makes this header Google's and not W3C's.
47
+ const spanId = BigInt(`0x${spanContext.spanId}`).toString();
48
+ const option = (spanContext.traceFlags & api_1.TraceFlags.SAMPLED) === api_1.TraceFlags.SAMPLED ? '1' : '0';
49
+ setter.set(carrier, exports.CLOUD_TRACE_CONTEXT_HEADER, `${spanContext.traceId}/${spanId};o=${option}`);
50
+ }
51
+ extract(context, carrier, getter) {
52
+ // A malformed upstream header must never fail a request, so every exit
53
+ // returns the untouched context and the whole body is guarded.
54
+ try {
55
+ const raw = getter.get(carrier, exports.CLOUD_TRACE_CONTEXT_HEADER);
56
+ const value = Array.isArray(raw) ? raw[0] : raw;
57
+ if (typeof value !== 'string' || value.length === 0)
58
+ return context;
59
+ const separator = value.indexOf('/');
60
+ if (separator <= 0)
61
+ return context;
62
+ // Google documents the trace id as case-insensitive hex; W3C requires
63
+ // lowercase. Normalising here is the deliberate asymmetry.
64
+ const traceId = value.slice(0, separator).toLowerCase();
65
+ if (!TRACE_ID_PATTERN.test(traceId) || !(0, api_1.isValidTraceId)(traceId))
66
+ return context;
67
+ let remainder = value.slice(separator + 1);
68
+ let sampled = false;
69
+ const optionsAt = remainder.indexOf(';');
70
+ if (optionsAt >= 0) {
71
+ sampled = isSampled(remainder.slice(optionsAt + 1));
72
+ remainder = remainder.slice(0, optionsAt);
73
+ }
74
+ if (!DECIMAL_PATTERN.test(remainder))
75
+ return context;
76
+ const spanIdValue = BigInt(remainder);
77
+ if (spanIdValue <= 0n || spanIdValue > MAX_UNSIGNED_64)
78
+ return context;
79
+ const spanId = spanIdValue.toString(16).padStart(16, '0');
80
+ if (!(0, api_1.isValidSpanId)(spanId))
81
+ return context;
82
+ return api_1.trace.setSpanContext(context, {
83
+ traceId,
84
+ spanId,
85
+ traceFlags: sampled ? api_1.TraceFlags.SAMPLED : api_1.TraceFlags.NONE,
86
+ isRemote: true,
87
+ });
88
+ }
89
+ catch {
90
+ return context;
91
+ }
92
+ }
93
+ }
94
+ exports.CloudTraceContextPropagator = CloudTraceContextPropagator;
95
+ /** Reads the `o=` option, tolerating other options alongside it. */
96
+ function isSampled(options) {
97
+ for (const option of options.split(';')) {
98
+ const trimmed = option.trim();
99
+ if (trimmed.startsWith('o='))
100
+ return trimmed.slice(2) === '1';
101
+ }
102
+ return false;
103
+ }
@@ -0,0 +1,23 @@
1
+ import type { Context, TextMapGetter, TextMapPropagator, TextMapSetter } from '@opentelemetry/api';
2
+ /**
3
+ * Combines several propagators into one, for publishing as the global propagator.
4
+ *
5
+ * `@opentelemetry/core` ships a `CompositePropagator`, and this exists because core may not
6
+ * depend on it: that package is past the API boundary ADR-0005 A2 draws, and the Stage 1b
7
+ * dependency guard names it explicitly. Dart needs no equivalent — its OpenTelemetry API
8
+ * provides `OTelAPI.compositePropagator` directly, one of several places where the Dart API
9
+ * is the richer of the three.
10
+ *
11
+ * Injection runs every propagator, so an outbound call can carry both `traceparent` and a
12
+ * vendor header when the application asked for that. Extraction stops at the first
13
+ * propagator that yields a valid span context, which is the precedence
14
+ * {@link PropagationPolicy} defines — and why extraction here is a fallback rather than the
15
+ * main path: the host resolves inbound context through the policy, not through this.
16
+ */
17
+ export declare class CompositeTextMapPropagator implements TextMapPropagator<unknown> {
18
+ private readonly propagators;
19
+ constructor(propagators: readonly TextMapPropagator<unknown>[]);
20
+ fields(): string[];
21
+ inject(context: Context, carrier: unknown, setter: TextMapSetter<unknown>): void;
22
+ extract(context: Context, carrier: unknown, getter: TextMapGetter<unknown>): Context;
23
+ }
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CompositeTextMapPropagator = void 0;
4
+ /**
5
+ * Combines several propagators into one, for publishing as the global propagator.
6
+ *
7
+ * `@opentelemetry/core` ships a `CompositePropagator`, and this exists because core may not
8
+ * depend on it: that package is past the API boundary ADR-0005 A2 draws, and the Stage 1b
9
+ * dependency guard names it explicitly. Dart needs no equivalent — its OpenTelemetry API
10
+ * provides `OTelAPI.compositePropagator` directly, one of several places where the Dart API
11
+ * is the richer of the three.
12
+ *
13
+ * Injection runs every propagator, so an outbound call can carry both `traceparent` and a
14
+ * vendor header when the application asked for that. Extraction stops at the first
15
+ * propagator that yields a valid span context, which is the precedence
16
+ * {@link PropagationPolicy} defines — and why extraction here is a fallback rather than the
17
+ * main path: the host resolves inbound context through the policy, not through this.
18
+ */
19
+ class CompositeTextMapPropagator {
20
+ propagators;
21
+ constructor(propagators) {
22
+ this.propagators = propagators;
23
+ }
24
+ fields() {
25
+ return [...new Set(this.propagators.flatMap((propagator) => propagator.fields()))];
26
+ }
27
+ inject(context, carrier, setter) {
28
+ for (const propagator of this.propagators) {
29
+ try {
30
+ propagator.inject(context, carrier, setter);
31
+ }
32
+ catch {
33
+ // A third-party propagator is not our code. One misbehaving entry must not fail an
34
+ // outbound request; the rest still get their headers on.
35
+ }
36
+ }
37
+ }
38
+ extract(context, carrier, getter) {
39
+ for (const propagator of this.propagators) {
40
+ try {
41
+ const extracted = propagator.extract(context, carrier, getter);
42
+ if (extracted !== context)
43
+ return extracted;
44
+ }
45
+ catch {
46
+ continue;
47
+ }
48
+ }
49
+ return context;
50
+ }
51
+ }
52
+ exports.CompositeTextMapPropagator = CompositeTextMapPropagator;
@@ -0,0 +1,65 @@
1
+ import { type Context, type TextMapPropagator } from '@opentelemetry/api';
2
+ /**
3
+ * The header carrying a caller-supplied correlation id.
4
+ *
5
+ * Read and preserved, **never** adopted as the trace id — see {@link PropagationPolicy}.
6
+ */
7
+ export declare const REQUEST_ID_HEADER = "x-request-id";
8
+ /** What resolving the incoming headers produced. */
9
+ export interface PropagationResult {
10
+ /**
11
+ * The context to continue with. Carries a remote parent when one was accepted,
12
+ * and otherwise carries none — trace and span id generation belongs to the
13
+ * tracer, not here.
14
+ */
15
+ readonly context: Context;
16
+ /**
17
+ * The caller's `X-Request-ID`, when it sent one. Preserved for log correlation
18
+ * and for forwarding on outbound calls; it is not identity.
19
+ */
20
+ readonly requestId?: string;
21
+ /** Whether a remote parent was accepted from the incoming headers. */
22
+ readonly hasRemoteParent: boolean;
23
+ }
24
+ export interface PropagationPolicyOptions {
25
+ /** The ordered chain. First valid span context wins. Defaults to W3C alone. */
26
+ readonly propagators?: readonly TextMapPropagator<unknown>[];
27
+ /** Whether an incoming trace context is honoured at all. Defaults to `true`. */
28
+ readonly trustIncomingTraceContext?: boolean;
29
+ }
30
+ /**
31
+ * Resolves incoming request headers into a tracing context.
32
+ *
33
+ * **Composable rather than hardcoded** (runbook D24). The chain is an ordered list
34
+ * of propagators and the first to yield a valid span context wins. The default is
35
+ * W3C Trace Context only: a service on Google Cloud appends a Cloud Trace
36
+ * propagator, which keeps anything vendor-specific out of the framework. A service
37
+ * behind a B3-speaking mesh appends a B3 propagator the same way, instead of forking.
38
+ *
39
+ * **`X-Request-ID` is never the trace id** (runbook D6). It is read and preserved
40
+ * beside the trace id, never promoted into it: callers reuse it deliberately on
41
+ * retries, so adopting it would merge unrelated retries into one trace; any client
42
+ * could then collide traces on purpose; and `trace_id` would have ambiguous
43
+ * provenance, sometimes caller-supplied and sometimes generated.
44
+ *
45
+ * **Nothing is generated here.** When no propagator matches, the returned context
46
+ * simply carries no span context and the tracer starts a fresh trace with ids of its
47
+ * own (runbook D7, gate G3).
48
+ *
49
+ * The Dart counterpart is `lib/src/core/tracing/propagation_policy.dart`.
50
+ */
51
+ export declare class PropagationPolicy {
52
+ /** The ordered chain. First valid span context wins. */
53
+ readonly propagators: readonly TextMapPropagator<unknown>[];
54
+ /**
55
+ * Whether an incoming trace context is honoured at all (D25).
56
+ *
57
+ * Defaults to `true`, matching every official OpenTelemetry SDK. Set it to
58
+ * `false` on a service that receives internet traffic directly, where a caller
59
+ * could otherwise choose its trace ids.
60
+ */
61
+ readonly trustIncomingTraceContext: boolean;
62
+ constructor(options?: PropagationPolicyOptions);
63
+ /** Resolves `headers` into a context plus the preserved request id. */
64
+ resolve(headers: Record<string, string>): PropagationResult;
65
+ }