@nestjs/observe 0.3.21 → 0.3.22

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 (34) hide show
  1. package/README.md +42 -13
  2. package/dist/agent/degraded-ingest.protocol.d.ts +20 -0
  3. package/dist/agent/degraded-ingest.protocol.js +25 -0
  4. package/dist/agent/detached-observe-worker.assembly.js +2 -1
  5. package/dist/agent/detached-observe-worker.d.ts +2 -0
  6. package/dist/agent/detached-observe-worker.js +7 -0
  7. package/dist/agent/observe-agent.shared-buffer.d.ts +36 -0
  8. package/dist/agent/observe-agent.shared-buffer.js +56 -1
  9. package/dist/agent/observe-agent.worker.d.ts +12 -0
  10. package/dist/agent/observe-agent.worker.js +55 -1
  11. package/dist/interfaces/observe-options.interface.d.ts +40 -2
  12. package/dist/observe.constants.d.ts +10 -0
  13. package/dist/observe.constants.js +10 -0
  14. package/dist/observe.module.js +3 -0
  15. package/dist/outgoing/http.integration.d.ts +34 -3
  16. package/dist/outgoing/http.integration.js +84 -17
  17. package/dist/outgoing/outgoing-observe-agent.service.d.ts +14 -1
  18. package/dist/outgoing/outgoing-observe-agent.service.js +24 -9
  19. package/dist/outgoing/outgoing-span.recorder.d.ts +11 -1
  20. package/dist/outgoing/outgoing-span.recorder.js +8 -2
  21. package/dist/protocols/http-observe-agent.service.js +25 -2
  22. package/dist/services/operation-trace.registry.d.ts +17 -2
  23. package/dist/services/operation-trace.registry.js +23 -8
  24. package/dist/services/tracer.service.d.ts +6 -0
  25. package/dist/services/tracer.service.js +11 -2
  26. package/dist/utils/default-trace-id-generator.util.d.ts +18 -0
  27. package/dist/utils/default-trace-id-generator.util.js +33 -0
  28. package/dist/utils/opentelemetry.util.d.ts +31 -0
  29. package/dist/utils/opentelemetry.util.js +52 -0
  30. package/dist/utils/trace-context.util.d.ts +91 -0
  31. package/dist/utils/trace-context.util.js +219 -0
  32. package/dist/utils/trace-id-generator-origin.util.d.ts +11 -0
  33. package/dist/utils/trace-id-generator-origin.util.js +26 -0
  34. package/package.json +14 -2
@@ -1,7 +1,12 @@
1
1
  import { subscribe, unsubscribe } from "diagnostics_channel";
2
+ import { openTelemetryWritesTraceparent } from "../utils/opentelemetry.util.js";
2
3
  import { redactUrlQuery } from "../utils/redact-url-query.js";
4
+ import { formatTraceparent, randomSpanId, w3cSpanIdOf, w3cTraceIdOf, } from "../utils/trace-context.util.js";
5
+ import { uuidv7 } from "../utils/uuid-v7.util.js";
3
6
  import { attachLlmSpan } from "./llm/llm-fetch.integration.js";
4
7
  const TRACE_HEADER = "x-request-id";
8
+ const TRACEPARENT_HEADER = "traceparent";
9
+ const TRACESTATE_HEADER = "tracestate";
5
10
  /**
6
11
  * Spans for outbound HTTP, from the diagnostics channels Node publishes on its
7
12
  * own: `undici` - which is also what the global `fetch` runs on - and the
@@ -14,13 +19,24 @@ const TRACE_HEADER = "x-request-id";
14
19
  *
15
20
  * Returns the function that removes every subscription.
16
21
  */
17
- export function subscribeOutgoingHttp(recorder, currentTraceId, options = {},
22
+ export function subscribeOutgoingHttp(recorder, currentTrace, options = {},
18
23
  /**
19
24
  * Read per request rather than passed once: the redactor is configured
20
25
  * after the module's options resolve, which can be after this subscribes.
21
26
  */
22
- getRedactor = () => null) {
27
+ getRedactor = () => null,
28
+ /**
29
+ * Whether calls carry W3C Trace Context now: with `openTelemetry` on and
30
+ * `traceContext` not off, while the collector takes this app's telemetry.
31
+ * Off unless given.
32
+ */
33
+ traceContextOn = () => false) {
23
34
  const spans = new WeakMap();
35
+ /**
36
+ * Span ids minted for a `node:http` request at `created`, where its
37
+ * `traceparent` has to be written, for the span `start` opens later.
38
+ */
39
+ const presetSpanIds = new WeakMap();
24
40
  const subscriptions = [];
25
41
  const on = (channel, handler) => {
26
42
  const guarded = (message) => {
@@ -39,14 +55,20 @@ getRedactor = () => null) {
39
55
  const shouldPropagate = (url) => typeof options.propagateTraceId === "function"
40
56
  ? options.propagateTraceId(url)
41
57
  : options.propagateTraceId !== false;
42
- const open = (request, method, url, host) => {
58
+ // Only while `traceContextOn` says so, and then left to an OpenTelemetry
59
+ // SDK in this process when it propagates W3C Trace Context - see
60
+ // `openTelemetryWritesTraceparent`. Both asked per call: interop pauses
61
+ // while the collector is not taking telemetry, and an SDK may be
62
+ // registered after the application starts.
63
+ const sendsTraceContext = () => traceContextOn() && !openTelemetryWritesTraceparent();
64
+ const open = (request, method, url, host, presetSpanId) => {
43
65
  if (options.ignore?.(url)) {
44
66
  return false;
45
67
  }
46
68
  const span = recorder.open("http", `${method} ${host}`, {
47
69
  "http.method": method,
48
70
  "http.url": redactUrlQuery(url, getRedactor()),
49
- });
71
+ }, presetSpanId);
50
72
  if (span) {
51
73
  spans.set(request, span);
52
74
  // A no-op unless this request is a model call the fetch observer is
@@ -68,12 +90,24 @@ getRedactor = () => null) {
68
90
  if (!open(request, method, url, host)) {
69
91
  return;
70
92
  }
71
- const traceId = currentTraceId();
72
- if (traceId &&
73
- shouldPropagate(url) &&
74
- typeof request.addHeader === "function" &&
75
- !hasUndiciHeader(request.headers, TRACE_HEADER)) {
76
- request.addHeader(TRACE_HEADER, traceId);
93
+ const trace = currentTrace();
94
+ if (!trace ||
95
+ !shouldPropagate(url) ||
96
+ typeof request.addHeader !== "function") {
97
+ return;
98
+ }
99
+ if (!hasUndiciHeader(request.headers, TRACE_HEADER)) {
100
+ request.addHeader(TRACE_HEADER, trace.traceId);
101
+ }
102
+ if (sendsTraceContext() &&
103
+ !hasUndiciHeader(request.headers, TRACEPARENT_HEADER)) {
104
+ const span = spans.get(request);
105
+ const headers = traceContextHeaders(trace, span?.spanId, span !== undefined);
106
+ request.addHeader(TRACEPARENT_HEADER, headers.traceparent);
107
+ if (headers.tracestate &&
108
+ !hasUndiciHeader(request.headers, TRACESTATE_HEADER)) {
109
+ request.addHeader(TRACESTATE_HEADER, headers.tracestate);
110
+ }
77
111
  }
78
112
  });
79
113
  on("undici:request:trailers", ({ request }) => close(request));
@@ -89,17 +123,33 @@ getRedactor = () => null) {
89
123
  // fires after the header block is already on its way.
90
124
  on("http.client.request.created", ({ request }) => {
91
125
  const { url } = describeNodeRequest(request);
92
- const traceId = currentTraceId();
93
- if (traceId &&
94
- !options.ignore?.(url) &&
95
- shouldPropagate(url) &&
96
- !request.getHeader?.(TRACE_HEADER)) {
97
- request.setHeader?.(TRACE_HEADER, traceId);
126
+ const trace = currentTrace();
127
+ if (!trace || options.ignore?.(url) || !shouldPropagate(url)) {
128
+ return;
129
+ }
130
+ if (!request.getHeader?.(TRACE_HEADER)) {
131
+ request.setHeader?.(TRACE_HEADER, trace.traceId);
132
+ }
133
+ if (sendsTraceContext() && !request.getHeader?.(TRACEPARENT_HEADER)) {
134
+ // The span only opens at `start`, by when the header has gone, so
135
+ // its id is minted here - and only for a call that will have one.
136
+ const recorded = recorder.isRecording();
137
+ const spanId = recorded ? uuidv7() : undefined;
138
+ if (spanId !== undefined) {
139
+ presetSpanIds.set(request, spanId);
140
+ }
141
+ const headers = traceContextHeaders(trace, spanId, recorded);
142
+ request.setHeader?.(TRACEPARENT_HEADER, headers.traceparent);
143
+ if (headers.tracestate && !request.getHeader?.(TRACESTATE_HEADER)) {
144
+ request.setHeader?.(TRACESTATE_HEADER, headers.tracestate);
145
+ }
98
146
  }
99
147
  });
100
148
  on("http.client.request.start", ({ request }) => {
101
149
  const { host, url, method } = describeNodeRequest(request);
102
- if (!open(request, method, url, host)) {
150
+ const presetSpanId = presetSpanIds.get(request);
151
+ presetSpanIds.delete(request);
152
+ if (!open(request, method, url, host, presetSpanId)) {
103
153
  return;
104
154
  }
105
155
  // `close` always fires, with or without a response. An `error` listener
@@ -117,6 +167,23 @@ getRedactor = () => null) {
117
167
  }
118
168
  };
119
169
  }
170
+ /**
171
+ * The W3C headers for one call: the trace the operation arrived in - else
172
+ * the one its trace id maps onto - with the call's own span as the parent the
173
+ * callee sees, so a server span there nests under this client span.
174
+ *
175
+ * `sampled` passes the caller's decision on, as the spec asks of a hop that
176
+ * does not make its own. With no caller, it says whether this operation is
177
+ * being recorded: a callee sampling by its parent then keeps exactly the
178
+ * traces that have a root.
179
+ */
180
+ function traceContextHeaders(trace, spanId, recorded) {
181
+ const received = trace.traceContext;
182
+ return {
183
+ traceparent: formatTraceparent(received?.traceId ?? w3cTraceIdOf(trace.traceId), spanId === undefined ? randomSpanId() : w3cSpanIdOf(spanId), received?.sampled ?? recorded),
184
+ tracestate: received?.traceState,
185
+ };
186
+ }
120
187
  /** undici keeps headers as a flat `[name, value, ...]` array or a raw string. */
121
188
  function hasUndiciHeader(headers, name) {
122
189
  if (Array.isArray(headers)) {
@@ -1,13 +1,26 @@
1
1
  import { OnApplicationShutdown } from "@nestjs/common";
2
2
  import { AsyncLocalStorage } from "async_hooks";
3
+ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
3
4
  import { ObserveModuleOptionsWithDefaults } from "../interfaces/index.js";
4
5
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
5
6
  export declare class OutgoingObserveAgentService implements OnApplicationShutdown {
6
7
  private readonly options;
8
+ /**
9
+ * Says whether the collector takes this app's telemetry, which W3C Trace
10
+ * Context waits on. Absent only where a test builds the service by hand,
11
+ * and interop then stays off.
12
+ */
13
+ private readonly observeAgentSharedBuffer?;
7
14
  private readonly logger;
8
15
  private unsubscribeHttp?;
9
16
  private deactivateLlm?;
10
- constructor(options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<any, any>>);
17
+ constructor(options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<any, any>>,
18
+ /**
19
+ * Says whether the collector takes this app's telemetry, which W3C Trace
20
+ * Context waits on. Absent only where a test builds the service by hand,
21
+ * and interop then stays off.
22
+ */
23
+ observeAgentSharedBuffer?: ObserveAgentSharedBuffer | undefined);
11
24
  onApplicationShutdown(): void;
12
25
  /**
13
26
  * Patches every copy of a driver the application can end up running on: the
@@ -11,9 +11,10 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
11
  return function (target, key) { decorator(target, key, paramIndex); }
12
12
  };
13
13
  var OutgoingObserveAgentService_1;
14
- import { Inject, Injectable, Logger, } from "@nestjs/common";
14
+ import { Inject, Injectable, Logger, Optional, } from "@nestjs/common";
15
15
  import { AsyncLocalStorage } from "async_hooks";
16
- import { OBSERVE_OPTIONS } from "../observe.constants.js";
16
+ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
17
+ import { OBSERVE_OPTIONS, TRACE_CONTEXT_KEY } from "../observe.constants.js";
17
18
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
18
19
  import { loadAsResolvedBy, loadOptionalPeer, } from "../utils/optional-peer.util.js";
19
20
  import { subscribeOutgoingHttp } from "./http.integration.js";
@@ -90,11 +91,13 @@ const DRIVER_DEPENDENTS = {
90
91
  };
91
92
  let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class OutgoingObserveAgentService {
92
93
  options;
94
+ observeAgentSharedBuffer;
93
95
  logger = new Logger(OutgoingObserveAgentService_1.name);
94
96
  unsubscribeHttp;
95
97
  deactivateLlm;
96
- constructor(options, operationTraceRegistry, asyncLocalStorage) {
98
+ constructor(options, operationTraceRegistry, asyncLocalStorage, observeAgentSharedBuffer) {
97
99
  this.options = options;
100
+ this.observeAgentSharedBuffer = observeAgentSharedBuffer;
98
101
  const outgoing = this.options.outgoing;
99
102
  // `forRoot` has given `fetch` back already; `forRootAsync` options are
100
103
  // only known from here.
@@ -112,12 +115,22 @@ let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class Outgoing
112
115
  this.patchDriver("mssql", "mssql", DRIVER_DEPENDENTS.mssql, (module) => patchMssql(module, recorder));
113
116
  }
114
117
  if (outgoing?.http !== false) {
118
+ const http = typeof outgoing?.http === "object" ? outgoing.http : {};
115
119
  this.unsubscribeHttp = subscribeOutgoingHttp(recorder, () => {
116
- const traceId = asyncLocalStorage
117
- .getStore()
118
- ?.get(this.options.traceIdKey);
119
- return typeof traceId === "string" ? traceId : undefined;
120
- }, typeof outgoing?.http === "object" ? outgoing.http : {}, () => operationTraceRegistry.getRedactor());
120
+ const store = asyncLocalStorage.getStore();
121
+ const traceId = store?.get(this.options.traceIdKey);
122
+ if (typeof traceId !== "string") {
123
+ return undefined;
124
+ }
125
+ const traceContext = store?.get(TRACE_CONTEXT_KEY);
126
+ return { traceId, traceContext };
127
+ }, http, () => operationTraceRegistry.getRedactor(),
128
+ // W3C Trace Context goes out only with `openTelemetry` on, and only
129
+ // while the collector takes this app's telemetry - see
130
+ // `ObserveAgentSharedBuffer.isIngesting`.
131
+ () => this.options.openTelemetry === true &&
132
+ http.traceContext !== false &&
133
+ this.observeAgentSharedBuffer?.isIngesting() === true);
121
134
  // Model calls are read off the spans above, so they go with them.
122
135
  if (outgoing?.llm !== false) {
123
136
  this.deactivateLlm = activateLlmFetchObserver(recorder, typeof outgoing?.llm === "object" ? outgoing.llm : {});
@@ -167,7 +180,9 @@ let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class Outgoing
167
180
  OutgoingObserveAgentService = OutgoingObserveAgentService_1 = __decorate([
168
181
  Injectable(),
169
182
  __param(0, Inject(OBSERVE_OPTIONS)),
183
+ __param(3, Optional()),
170
184
  __metadata("design:paramtypes", [Object, OperationTraceRegistry,
171
- AsyncLocalStorage])
185
+ AsyncLocalStorage,
186
+ ObserveAgentSharedBuffer])
172
187
  ], OutgoingObserveAgentService);
173
188
  export { OutgoingObserveAgentService };
@@ -3,6 +3,11 @@ import { OperationTraceRegistry } from "../services/operation-trace.registry.js"
3
3
  type Tags = Record<string, string | number | boolean>;
4
4
  /** A span that has been opened and is waiting to be told how the call went. */
5
5
  export interface OpenOutgoingSpan {
6
+ /**
7
+ * The span's id, for a call that names its span to the service it calls -
8
+ * the parent id of an outbound `traceparent`.
9
+ */
10
+ readonly spanId: string;
6
11
  end(error?: unknown): void;
7
12
  /** Adds tags to the span - what the response said, once it has been read. */
8
13
  tag?(tags: Tags): void;
@@ -44,7 +49,12 @@ export declare class OutgoingSpanRecorder {
44
49
  * to: no traced operation in this async context, one that was sampled out,
45
50
  * or a call an outer entry point already covers.
46
51
  */
47
- open(className: string, methodKey: string, tags: Tags): OpenOutgoingSpan | undefined;
52
+ open(className: string, methodKey: string, tags: Tags,
53
+ /**
54
+ * The id to open the span under, minted by a caller that had to name the
55
+ * span before it could open it. A fresh one otherwise.
56
+ */
57
+ presetSpanId?: string): OpenOutgoingSpan | undefined;
48
58
  /**
49
59
  * Whether `open` would attach a span here - asked first by an integration
50
60
  * whose description of a call costs more than the call's own bookkeeping
@@ -40,7 +40,12 @@ export class OutgoingSpanRecorder {
40
40
  * to: no traced operation in this async context, one that was sampled out,
41
41
  * or a call an outer entry point already covers.
42
42
  */
43
- open(className, methodKey, tags) {
43
+ open(className, methodKey, tags,
44
+ /**
45
+ * The id to open the span under, minted by a caller that had to name the
46
+ * span before it could open it. A fresh one otherwise.
47
+ */
48
+ presetSpanId) {
44
49
  if (this.covered.getStore()) {
45
50
  return undefined;
46
51
  }
@@ -50,7 +55,7 @@ export class OutgoingSpanRecorder {
50
55
  return undefined;
51
56
  }
52
57
  const callerId = store?.get(CALLER_METADATA_KEY);
53
- const spanId = this.operationTraceRegistry.internalStartTraceStep(registryKey, className, methodKey, callerId);
58
+ const spanId = this.operationTraceRegistry.internalStartTraceStep(registryKey, className, methodKey, callerId, presetSpanId);
54
59
  if (spanId === undefined) {
55
60
  return undefined;
56
61
  }
@@ -79,6 +84,7 @@ export class OutgoingSpanRecorder {
79
84
  }
80
85
  };
81
86
  return {
87
+ spanId,
82
88
  end: (error) => {
83
89
  if (ended || deferred) {
84
90
  return;
@@ -16,10 +16,13 @@ import { captureRequest, shouldCaptureRequest, } from "../utils/capture-request.
16
16
  import { HttpAdapterHost } from "@nestjs/core";
17
17
  import { AsyncLocalStorage } from "async_hooks";
18
18
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
19
- import { OBSERVE_OPTIONS, TRACE_REGISTRY_KEY } from "../observe.constants.js";
19
+ import { OBSERVE_OPTIONS, TRACE_CONTEXT_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
20
20
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
21
21
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
22
22
  import { redactUrlQuery } from "../utils/redact-url-query.js";
23
+ import { openTelemetryTraceIdGenerator } from "../utils/default-trace-id-generator.util.js";
24
+ import { usesDefaultTraceIdGenerator } from "../utils/trace-id-generator-origin.util.js";
25
+ import { inboundTraceContext } from "../utils/trace-context.util.js";
23
26
  import { uuidv7 } from "../utils/uuid-v7.util.js";
24
27
  import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
25
28
  /**
@@ -106,7 +109,14 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
106
109
  // identical object, one lookup fewer, and it is known to exist.
107
110
  const store = new Map();
108
111
  this.asyncLocalStorage.run(store, () => {
109
- const traceId = generateTraceIdSafely(this.options.traceIdGenerator, req, this.options, this.logger);
112
+ // OpenTelemetry interop runs only while the collector takes this app's
113
+ // telemetry - see `ObserveAgentSharedBuffer.isIngesting`. Asked once
114
+ // per request, so a request is named and carried on one way throughout.
115
+ const openTelemetry = this.options.openTelemetry === true &&
116
+ this.observeAgentSharedBuffer.isIngesting();
117
+ const traceId = generateTraceIdSafely(openTelemetry && usesDefaultTraceIdGenerator(this.options)
118
+ ? openTelemetryTraceIdGenerator
119
+ : this.options.traceIdGenerator, req, this.options, this.logger);
110
120
  store.set(this.options.traceIdKey, traceId);
111
121
  // An adopted `x-request-id` is not unique to this request: a caller that
112
122
  // fans out, or retries, sends the same id twice. Claim this execution
@@ -115,6 +125,19 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
115
125
  // lookups stay off a recorded request sharing its id.
116
126
  const registryKey = uuidv7();
117
127
  store.set(TRACE_REGISTRY_KEY, registryKey);
128
+ // With OpenTelemetry interop on, read whatever produced the trace id: a
129
+ // `traceIdGenerator` of the application's own decides what Observe
130
+ // calls the trace, not which OpenTelemetry trace the caller is in, and
131
+ // outbound calls carry that one on either way - for an unrecorded
132
+ // request too, so the trace does not break here. An OpenTelemetry SDK
133
+ // in this process has the say on which trace that is, when one runs -
134
+ // see `inboundTraceContext`.
135
+ if (openTelemetry) {
136
+ const traceContext = inboundTraceContext(req.headers);
137
+ if (traceContext) {
138
+ store.set(TRACE_CONTEXT_KEY, traceContext);
139
+ }
140
+ }
118
141
  setAttributesSafely(this.options.http?.setAttributes, [req], this.options.http, store, this.logger, "http");
119
142
  if (this.shouldIgnoreRequest(req) || this.isUntracedPreflight(req)) {
120
143
  return done();
@@ -135,7 +135,12 @@ export declare class OperationTraceRegistry {
135
135
  */
136
136
  private toErrorStatusCode;
137
137
  private setStatusCode;
138
- internalStartTraceStep(traceId: TraceId, className: string, methodKey: string, callerId: string | undefined): string | undefined;
138
+ internalStartTraceStep(traceId: TraceId, className: string, methodKey: string, callerId: string | undefined,
139
+ /**
140
+ * An id minted ahead of the span - by an outbound call that had to name
141
+ * its span in a `traceparent` before the span could be opened.
142
+ */
143
+ spanId?: string): string | undefined;
139
144
  /**
140
145
  * Nests a freshly opened node under its caller when that caller is still
141
146
  * live, and at the trace root otherwise.
@@ -192,7 +197,13 @@ export declare class OperationTraceRegistry {
192
197
  * async call) would otherwise lose its offset entirely.
193
198
  */
194
199
  private toStartOffset;
195
- captureError(traceId: string, callerId: string | undefined, error: Error | string, tags: Record<string, string | number | boolean>): void;
200
+ captureError(traceId: string, callerId: string | undefined, error: Error | string, tags: Record<string, string | number | boolean>,
201
+ /**
202
+ * The trace id the warnings below name, when it is not the registry key:
203
+ * the one the operation's logs carry. The key itself appears nowhere a
204
+ * reader could look it up.
205
+ */
206
+ reportedTraceId?: string): void;
196
207
  /**
197
208
  * Drops a trace that will never be plucked, freeing both maps.
198
209
  *
@@ -227,6 +238,10 @@ export declare class OperationTraceRegistry {
227
238
  * One line per trace `pluckSnapshot` ships without its open spans, naming
228
239
  * them. Their late ends are silent: one un-awaited call usually holds a
229
240
  * whole chain of spans open, and a line per span said the same thing N times.
241
+ *
242
+ * The line names the trace id the snapshot reports under, which the
243
+ * operation's logs and its trace carry too - not the registry key, which
244
+ * appears nowhere a reader could look it up.
230
245
  */
231
246
  private reportUnfinishedSpans;
232
247
  /**
@@ -372,13 +372,18 @@ export class OperationTraceRegistry {
372
372
  }
373
373
  requestSnapshot.attributes.statusCode = statusCode;
374
374
  }
375
- internalStartTraceStep(traceId, className, methodKey, callerId) {
375
+ internalStartTraceStep(traceId, className, methodKey, callerId,
376
+ /**
377
+ * An id minted ahead of the span - by an outbound call that had to name
378
+ * its span in a `traceparent` before the span could be opened.
379
+ */
380
+ spanId) {
376
381
  const snapshot = this.traceSnapshots.get(traceId);
377
382
  if (!snapshot) {
378
383
  return undefined;
379
384
  }
380
385
  snapshot.refsCounter += 1;
381
- const newNodeId = uuidv7();
386
+ const newNodeId = spanId ?? uuidv7();
382
387
  const startTime = performance.now();
383
388
  // Records which span owns the thread from here. A no-op unless continuous
384
389
  // profiling is on, and the only way profile samples can be attributed to a
@@ -571,20 +576,26 @@ export class OperationTraceRegistry {
571
576
  }
572
577
  return startTime - snapshot.startTimestamp;
573
578
  }
574
- captureError(traceId, callerId, error, tags) {
579
+ captureError(traceId, callerId, error, tags,
580
+ /**
581
+ * The trace id the warnings below name, when it is not the registry key:
582
+ * the one the operation's logs carry. The key itself appears nowhere a
583
+ * reader could look it up.
584
+ */
585
+ reportedTraceId = traceId) {
575
586
  const snapshot = this.traceSnapshots.get(traceId);
576
587
  if (!snapshot) {
577
- this.logger.warn(`No request snapshot found for traceId: "${traceId}". Cannot capture error.`);
588
+ this.logger.warn(`No request snapshot found for traceId: "${reportedTraceId}". Cannot capture error.`);
578
589
  return;
579
590
  }
580
591
  if (!snapshot.traces || snapshot.traces.length === 0) {
581
- this.logger.warn(`No traces found for traceId: "${traceId}". Cannot capture error.`);
592
+ this.logger.warn(`No traces found for traceId: "${reportedTraceId}". Cannot capture error.`);
582
593
  return;
583
594
  }
584
595
  const refsByCaller = this.callerIdsByTraceId.get(traceId);
585
596
  const targetSpan = refsByCaller?.get(callerId);
586
597
  if (!targetSpan) {
587
- this.logger.warn(`No active span found for traceId: "${traceId}". Cannot capture error.`);
598
+ this.logger.warn(`No active span found for traceId: "${reportedTraceId}". Cannot capture error.`);
588
599
  return;
589
600
  }
590
601
  if (!targetSpan.tags) {
@@ -714,6 +725,10 @@ export class OperationTraceRegistry {
714
725
  * One line per trace `pluckSnapshot` ships without its open spans, naming
715
726
  * them. Their late ends are silent: one un-awaited call usually holds a
716
727
  * whole chain of spans open, and a line per span said the same thing N times.
728
+ *
729
+ * The line names the trace id the snapshot reports under, which the
730
+ * operation's logs and its trace carry too - not the registry key, which
731
+ * appears nowhere a reader could look it up.
717
732
  */
718
733
  reportUnfinishedSpans(traceId, snapshot) {
719
734
  const open = [];
@@ -724,8 +739,8 @@ export class OperationTraceRegistry {
724
739
  }
725
740
  const operation = ("operationId" in snapshot && snapshot.operationId) ||
726
741
  ("name" in snapshot && snapshot.name) ||
727
- traceId;
728
- this.logger.warn(`Trace "${traceId}" (${operation}) was reported without ${open.join(", ") || "a span"}, which had not ended ${SNAPSHOT_COMPLETION_TIMEOUT_MS}ms after the operation did. Some of your async operations were not awaited and outlived the operation that started them. Ignore if this is the desired behavior.`);
742
+ snapshot.traceId;
743
+ this.logger.warn(`Trace "${snapshot.traceId}" (${operation}) was reported without ${open.join(", ") || "a span"}, which had not ended ${SNAPSHOT_COMPLETION_TIMEOUT_MS}ms after the operation did. Some of your async operations were not awaited and outlived the operation that started them. Ignore if this is the desired behavior.`);
729
744
  }
730
745
  /**
731
746
  * Whether `skipSpans` claims a finished operation. Only request snapshots
@@ -153,6 +153,12 @@ export declare class TracerService<Store extends object = Record<string | symbol
153
153
  * methods with no async context at all - and is reported the same way.
154
154
  */
155
155
  private requireTraceId;
156
+ /**
157
+ * The trace id a message names: the one the operation's logs and
158
+ * `currentTraceId()` carry, rather than the registry key its trace is kept
159
+ * under, which a reader has no way to look up.
160
+ */
161
+ private reportedTraceId;
156
162
  private registerCounterChangeHandler;
157
163
  private registerGaugeChangeHandler;
158
164
  private registerSummaryChangeHandler;
@@ -81,7 +81,7 @@ let TracerService = TracerService_1 = class TracerService {
81
81
  return new TraceSpanDelegate("", undefined, {});
82
82
  }
83
83
  if (!activeOngoingEvent) {
84
- throw new Error(`No active span found for traceId: ${traceId}. Ensure that a span is created before calling "activeSpan".`);
84
+ throw new Error(`No active span found for traceId: ${this.reportedTraceId(store, traceId)}. Ensure that a span is created before calling "activeSpan".`);
85
85
  }
86
86
  let tags = activeOngoingEvent.tags;
87
87
  if (!tags) {
@@ -116,7 +116,7 @@ let TracerService = TracerService_1 = class TracerService {
116
116
  return;
117
117
  }
118
118
  const callerId = store.get(CALLER_METADATA_KEY);
119
- this.operationTraceRegistry.captureError(traceId, callerId, error, tags ?? {});
119
+ this.operationTraceRegistry.captureError(traceId, callerId, error, tags ?? {}, this.reportedTraceId(store, traceId));
120
120
  }
121
121
  counter(name, attributes) {
122
122
  const existingRef = this.counters.get(name);
@@ -279,6 +279,15 @@ let TracerService = TracerService_1 = class TracerService {
279
279
  }
280
280
  return traceId;
281
281
  }
282
+ /**
283
+ * The trace id a message names: the one the operation's logs and
284
+ * `currentTraceId()` carry, rather than the registry key its trace is kept
285
+ * under, which a reader has no way to look up.
286
+ */
287
+ reportedTraceId(store, registryKey) {
288
+ const traceId = store.get(this.options.traceIdKey);
289
+ return typeof traceId === "string" ? traceId : registryKey;
290
+ }
282
291
  registerCounterChangeHandler(counter) {
283
292
  counter["_onChange"] = (self) => {
284
293
  this.observeAgentSharedBuffer.upsertCustomMetric(self);
@@ -11,3 +11,21 @@
11
11
  */
12
12
  export declare const REQUEST_ID_PATTERN: RegExp;
13
13
  export declare function defaultTraceIdGenerator(req: unknown): string;
14
+ /**
15
+ * The default `traceIdGenerator` with `openTelemetry` on.
16
+ *
17
+ * A request in a W3C trace is named after that trace, so it has the id the
18
+ * rest of the trace has in the caller's OpenTelemetry backend: the trace a
19
+ * caller's `traceparent` names - a service in another language, a mesh, a
20
+ * load balancer that starts traces - or, when an OpenTelemetry SDK runs in
21
+ * this process, the one it continued or started for the request (see
22
+ * `inboundTraceContext`). Anything else is named as `defaultTraceIdGenerator`
23
+ * names it.
24
+ *
25
+ * An `x-request-id` beside the trace names some other one when a mesh or a
26
+ * router stamped it (Envoy and Heroku's router stamp every request), and gives
27
+ * way. It stays only when it names this same trace: another service running
28
+ * this agent sends both, and its id may be one `traceparent` cannot carry - a
29
+ * custom id, or a UUIDv7 whose mint time the collector reads.
30
+ */
31
+ export declare function openTelemetryTraceIdGenerator(req: unknown): string;
@@ -1,3 +1,4 @@
1
+ import { inboundTraceId, w3cTraceIdOf } from "./trace-context.util.js";
1
2
  import { uuidv7 } from "./uuid-v7.util.js";
2
3
  /**
3
4
  * What an inbound `x-request-id` must look like to be adopted as the trace id.
@@ -32,3 +33,35 @@ export function defaultTraceIdGenerator(req) {
32
33
  // Minted here, so it can carry its time - see uuidv7.
33
34
  return uuidv7();
34
35
  }
36
+ /**
37
+ * The default `traceIdGenerator` with `openTelemetry` on.
38
+ *
39
+ * A request in a W3C trace is named after that trace, so it has the id the
40
+ * rest of the trace has in the caller's OpenTelemetry backend: the trace a
41
+ * caller's `traceparent` names - a service in another language, a mesh, a
42
+ * load balancer that starts traces - or, when an OpenTelemetry SDK runs in
43
+ * this process, the one it continued or started for the request (see
44
+ * `inboundTraceContext`). Anything else is named as `defaultTraceIdGenerator`
45
+ * names it.
46
+ *
47
+ * An `x-request-id` beside the trace names some other one when a mesh or a
48
+ * router stamped it (Envoy and Heroku's router stamp every request), and gives
49
+ * way. It stays only when it names this same trace: another service running
50
+ * this agent sends both, and its id may be one `traceparent` cannot carry - a
51
+ * custom id, or a UUIDv7 whose mint time the collector reads.
52
+ */
53
+ export function openTelemetryTraceIdGenerator(req) {
54
+ if (typeof req === "object" && req !== null && "headers" in req) {
55
+ const headers = req.headers;
56
+ const fromTraceContext = inboundTraceId(headers);
57
+ if (fromTraceContext) {
58
+ const requestId = headers?.["x-request-id"];
59
+ return typeof requestId === "string" &&
60
+ REQUEST_ID_PATTERN.test(requestId) &&
61
+ w3cTraceIdOf(requestId) === w3cTraceIdOf(fromTraceContext)
62
+ ? requestId
63
+ : fromTraceContext;
64
+ }
65
+ }
66
+ return defaultTraceIdGenerator(req);
67
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * A span's identity as `@opentelemetry/api` hands it out - the slice of
3
+ * `SpanContext` the agent reads.
4
+ */
5
+ export interface OpenTelemetrySpanContext {
6
+ traceId: string;
7
+ spanId: string;
8
+ traceFlags: number;
9
+ traceState?: {
10
+ serialize(): string;
11
+ };
12
+ }
13
+ /**
14
+ * The span an OpenTelemetry SDK in this process has open in the current
15
+ * context - for an incoming request, the server span its HTTP instrumentation
16
+ * opened - or `undefined` when none runs.
17
+ *
18
+ * Read so that a service running both reports to Observe under the trace id
19
+ * the SDK gave the request, including when the request started the trace.
20
+ * Never throws: an SDK this cannot read is treated as absent.
21
+ */
22
+ export declare function activeOpenTelemetrySpanContext(): OpenTelemetrySpanContext | undefined;
23
+ /**
24
+ * Whether an OpenTelemetry SDK in this process propagates W3C Trace Context,
25
+ * and so writes `traceparent` on the outbound calls it instruments.
26
+ *
27
+ * The agent then leaves the header to it, whichever of the two sees a call
28
+ * first: two `traceparent` headers on one request are not a valid one, and
29
+ * the SDK's names the span the rest of its trace nests under.
30
+ */
31
+ export declare function openTelemetryWritesTraceparent(): boolean;