@nestjs/observe 0.3.20 → 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 (46) hide show
  1. package/LICENSE +105 -22
  2. package/NOTICE +31 -0
  3. package/README.md +138 -21
  4. package/dist/agent/degraded-ingest.protocol.d.ts +20 -0
  5. package/dist/agent/degraded-ingest.protocol.js +25 -0
  6. package/dist/agent/detached-observe-worker.assembly.js +2 -1
  7. package/dist/agent/detached-observe-worker.d.ts +2 -0
  8. package/dist/agent/detached-observe-worker.js +7 -0
  9. package/dist/agent/observe-agent.shared-buffer.d.ts +36 -0
  10. package/dist/agent/observe-agent.shared-buffer.js +56 -1
  11. package/dist/agent/observe-agent.worker.d.ts +12 -0
  12. package/dist/agent/observe-agent.worker.js +63 -8
  13. package/dist/instrument/create-instance-decorator.instrument.js +99 -86
  14. package/dist/interfaces/observe-options.interface.d.ts +42 -3
  15. package/dist/interfaces/trace-events.interfaces.d.ts +11 -5
  16. package/dist/observe.constants.d.ts +15 -5
  17. package/dist/observe.constants.js +15 -5
  18. package/dist/observe.module.js +3 -0
  19. package/dist/outgoing/http.integration.d.ts +34 -3
  20. package/dist/outgoing/http.integration.js +84 -17
  21. package/dist/outgoing/outgoing-observe-agent.service.d.ts +14 -1
  22. package/dist/outgoing/outgoing-observe-agent.service.js +24 -9
  23. package/dist/outgoing/outgoing-span.recorder.d.ts +11 -1
  24. package/dist/outgoing/outgoing-span.recorder.js +8 -2
  25. package/dist/protocols/deferred-trace-completion.d.ts +13 -2
  26. package/dist/protocols/deferred-trace-completion.js +27 -4
  27. package/dist/protocols/graphql-observe-agent.service.js +1 -1
  28. package/dist/protocols/http-observe-agent.service.js +45 -30
  29. package/dist/protocols/job-trace-runner.js +2 -2
  30. package/dist/protocols/rpc-observe-agent.service.js +19 -10
  31. package/dist/protocols/ws-observe-agent.service.js +1 -1
  32. package/dist/services/collapse-repeated-spans.util.js +41 -37
  33. package/dist/services/operation-trace.registry.d.ts +32 -11
  34. package/dist/services/operation-trace.registry.js +102 -33
  35. package/dist/services/tracer.service.d.ts +6 -0
  36. package/dist/services/tracer.service.js +11 -2
  37. package/dist/utils/default-trace-id-generator.util.d.ts +18 -0
  38. package/dist/utils/default-trace-id-generator.util.js +33 -0
  39. package/dist/utils/opentelemetry.util.d.ts +31 -0
  40. package/dist/utils/opentelemetry.util.js +52 -0
  41. package/dist/utils/trace-context.util.d.ts +91 -0
  42. package/dist/utils/trace-context.util.js +219 -0
  43. package/dist/utils/trace-id-generator-origin.util.d.ts +11 -0
  44. package/dist/utils/trace-id-generator-origin.util.js +26 -0
  45. package/dist/utils/uuid-v7.util.js +53 -15
  46. package/package.json +18 -4
@@ -1,4 +1,5 @@
1
1
  import { LogRedactor } from "../utils/log-redactor.js";
2
+ import { TraceContext } from "../utils/trace-context.util.js";
2
3
  import { OutgoingSpanRecorder } from "./outgoing-span.recorder.js";
3
4
  export interface OutgoingHttpOptions {
4
5
  /**
@@ -11,10 +12,34 @@ export interface OutgoingHttpOptions {
11
12
  * carries one. It is what a downstream service running `@nestjs/observe`
12
13
  * adopts as its own trace id, which makes HTTP-to-HTTP calls one trace with
13
14
  * no application code. A function narrows it to the URLs it returns true
14
- * for - your own services, say, and not third parties.
15
+ * for - your own services, say, and not third parties. It narrows
16
+ * `traceContext` too.
15
17
  * @default true
16
18
  */
17
19
  propagateTraceId?: boolean | ((url: string) => boolean);
20
+ /**
21
+ * Send W3C Trace Context beside `x-request-id`: a `traceparent` naming the
22
+ * trace and this call's span, and the `tracestate` the operation arrived
23
+ * with, if any. It is what a service instrumented with OpenTelemetry - in
24
+ * any language - reads, so the call stays one trace through it. The trace
25
+ * is the one the operation's own `traceparent` named, when it arrived with
26
+ * one. Never added to a request that already carries a `traceparent`, nor
27
+ * while an OpenTelemetry SDK that propagates W3C Trace Context runs in the
28
+ * same process: its instrumentations write the header on the calls they
29
+ * cover, and a request takes only one.
30
+ *
31
+ * Only with `openTelemetry` on, and only while the agent is reporting to
32
+ * NestJS Observe; otherwise no `traceparent` is sent.
33
+ * @default true, with `openTelemetry` on
34
+ */
35
+ traceContext?: boolean;
36
+ }
37
+ /** What an outbound call is told about the operation making it. */
38
+ export interface OutgoingTrace {
39
+ /** The operation's trace id, as `x-request-id` carries it. */
40
+ traceId: string;
41
+ /** The `traceparent` the operation arrived with, when it had one. */
42
+ traceContext?: TraceContext;
18
43
  }
19
44
  /**
20
45
  * Spans for outbound HTTP, from the diagnostics channels Node publishes on its
@@ -28,9 +53,15 @@ export interface OutgoingHttpOptions {
28
53
  *
29
54
  * Returns the function that removes every subscription.
30
55
  */
31
- export declare function subscribeOutgoingHttp(recorder: OutgoingSpanRecorder, currentTraceId: () => string | undefined, options?: OutgoingHttpOptions,
56
+ export declare function subscribeOutgoingHttp(recorder: OutgoingSpanRecorder, currentTrace: () => OutgoingTrace | undefined, options?: OutgoingHttpOptions,
32
57
  /**
33
58
  * Read per request rather than passed once: the redactor is configured
34
59
  * after the module's options resolve, which can be after this subscribes.
35
60
  */
36
- getRedactor?: () => LogRedactor | null): () => void;
61
+ getRedactor?: () => LogRedactor | null,
62
+ /**
63
+ * Whether calls carry W3C Trace Context now: with `openTelemetry` on and
64
+ * `traceContext` not off, while the collector takes this app's telemetry.
65
+ * Off unless given.
66
+ */
67
+ traceContextOn?: () => boolean): () => void;
@@ -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;
@@ -23,5 +23,16 @@ export declare function setAttributesSafely<TArgs extends unknown[]>(callback: (
23
23
  export declare function shouldIgnoreSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => boolean) | undefined, args: TArgs, receiver: unknown, logger: Logger, transport: string): boolean;
24
24
  /** A bad identity callback must not prevent the trace from being closed. */
25
25
  export declare function getUserIdSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => string | undefined) | undefined, args: TArgs, receiver: unknown, logger: Logger, transport: string): string | undefined;
26
- /** Run deferred completion without ever leaking a rejection from its timer. */
27
- export declare function deferTraceCompletion(completion: () => Promise<void>, logger: Logger, transport: string): void;
26
+ /**
27
+ * Completes a trace once its operation has ended, without ever leaking a
28
+ * rejection from the completion.
29
+ *
30
+ * Right away - in a microtask, once the rest of the listeners of the event
31
+ * that ended the operation have run - when `hasOpenSpans` says every span of
32
+ * the trace has closed, which is the usual case: spans close as the handler's
33
+ * calls return. Otherwise on a timer, so that a span still closing has that
34
+ * moment to end before the trace is plucked. A timer for every operation cost
35
+ * a lightly loaded process a wake-up of its event loop per request, about
36
+ * 35 µs of CPU each on a laptop, and a busy one nothing it would notice.
37
+ */
38
+ export declare function deferTraceCompletion(completion: () => Promise<void>, logger: Logger, transport: string, hasOpenSpans?: () => boolean): void;
@@ -76,9 +76,20 @@ export function getUserIdSafely(callback, args, receiver, logger, transport) {
76
76
  }
77
77
  return invokeUserCallbackSafely(callback, args, receiver, () => undefined, logger, `${transport}.getUserId`, "completing the trace without a user id");
78
78
  }
79
- /** Run deferred completion without ever leaking a rejection from its timer. */
80
- export function deferTraceCompletion(completion, logger, transport) {
81
- setTimeout(() => {
79
+ /**
80
+ * Completes a trace once its operation has ended, without ever leaking a
81
+ * rejection from the completion.
82
+ *
83
+ * Right away - in a microtask, once the rest of the listeners of the event
84
+ * that ended the operation have run - when `hasOpenSpans` says every span of
85
+ * the trace has closed, which is the usual case: spans close as the handler's
86
+ * calls return. Otherwise on a timer, so that a span still closing has that
87
+ * moment to end before the trace is plucked. A timer for every operation cost
88
+ * a lightly loaded process a wake-up of its event loop per request, about
89
+ * 35 µs of CPU each on a laptop, and a busy one nothing it would notice.
90
+ */
91
+ export function deferTraceCompletion(completion, logger, transport, hasOpenSpans) {
92
+ const complete = () => {
82
93
  void Promise.resolve()
83
94
  .then(completion)
84
95
  .catch((error) => {
@@ -87,5 +98,17 @@ export function deferTraceCompletion(completion, logger, transport) {
87
98
  warnSafely(logger, `Deferred ${transport} trace completion failed; later failures are not reported: ${describeFailure(error)}`);
88
99
  }
89
100
  });
90
- }, 0);
101
+ };
102
+ if (!hasOpenSpans) {
103
+ setTimeout(complete, 0);
104
+ return;
105
+ }
106
+ queueMicrotask(() => {
107
+ if (hasOpenSpans()) {
108
+ setTimeout(complete, 0);
109
+ }
110
+ else {
111
+ complete();
112
+ }
113
+ });
91
114
  }
@@ -338,7 +338,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
338
338
  return;
339
339
  }
340
340
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
341
- }, this.logger, "graphql");
341
+ }, this.logger, "graphql", () => this.operationTraceRegistry.hasOpenSpans(traceId));
342
342
  }
343
343
  /**
344
344
  * Picks the error a failed operation is recorded with.
@@ -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
  /**
@@ -71,12 +74,11 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
71
74
  if (!store) {
72
75
  return;
73
76
  }
74
- const traceId = store.get(TRACE_REGISTRY_KEY) ??
75
- store.get(this.options.traceIdKey);
76
- if (!traceId) {
77
+ const registryKey = store.get(TRACE_REGISTRY_KEY);
78
+ if (typeof registryKey !== "string") {
77
79
  return;
78
80
  }
79
- this.operationTraceRegistry.addRouteMetadataToTrace(traceId, requestMethod, path);
81
+ this.operationTraceRegistry.addRouteMetadataToTrace(registryKey, requestMethod, path);
80
82
  });
81
83
  }
82
84
  onModuleInit() {
@@ -107,25 +109,45 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
107
109
  // identical object, one lookup fewer, and it is known to exist.
108
110
  const store = new Map();
109
111
  this.asyncLocalStorage.run(store, () => {
110
- 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);
111
120
  store.set(this.options.traceIdKey, traceId);
121
+ // An adopted `x-request-id` is not unique to this request: a caller that
122
+ // fans out, or retries, sends the same id twice. Claim this execution
123
+ // before option callbacks can reach another request's trace. A request
124
+ // that is not recorded keeps the key too, never registered, so its
125
+ // lookups stay off a recorded request sharing its id.
126
+ const registryKey = uuidv7();
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
+ }
112
141
  setAttributesSafely(this.options.http?.setAttributes, [req], this.options.http, store, this.logger, "http");
113
- // A request that is not recorded still carries its trace id, which an
114
- // adopted `x-request-id` can share with a recorded request. A registry
115
- // key of its own, never registered, keeps its lookups off that trace.
116
- const skip = () => {
117
- store.set(TRACE_REGISTRY_KEY, uuidv7());
118
- done();
119
- };
120
142
  if (this.shouldIgnoreRequest(req) || this.isUntracedPreflight(req)) {
121
- return skip();
143
+ return done();
122
144
  }
123
145
  const shouldCapture = this.traceSamplerService.shouldCapture("http", {
124
146
  url: req.url,
125
147
  method: req.method,
126
148
  });
127
149
  if (!shouldCapture) {
128
- return skip();
150
+ return done();
129
151
  }
130
152
  // Sensitive query parameters are masked whether or not the deployment
131
153
  // configured anything: an opt-in redactor protects only those who
@@ -137,15 +159,6 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
137
159
  const originalUrl = this.queryParamsObfuscateRegex
138
160
  ? redactedUrl.replaceAll(this.queryParamsObfuscateRegex, "[REDACTED]")
139
161
  : redactedUrl;
140
- // An adopted `x-request-id` is not unique to this request: a caller
141
- // that fans out, or retries, sends the same id twice, and both requests
142
- // can be open here at once. The second gets a registry key of its own -
143
- // only the second, so the ordinary request is still keyed by its id.
144
- let registryKey = traceId;
145
- if (this.operationTraceRegistry.hasTrace(traceId)) {
146
- registryKey = uuidv7();
147
- store.set(TRACE_REGISTRY_KEY, registryKey);
148
- }
149
162
  this.operationTraceRegistry.startTrace(registryKey, {
150
163
  protocol: req.protocol,
151
164
  tags: this.options.http?.tags,
@@ -163,18 +176,20 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
163
176
  if (!store) {
164
177
  return;
165
178
  }
166
- const traceId = store.get(TRACE_REGISTRY_KEY) ??
167
- store.get(this.options.traceIdKey);
168
- if (!traceId) {
179
+ // Only this execution's own key: a stale store left by a finished request
180
+ // must not complete a later one that reuses its id.
181
+ const registryKey = store.get(TRACE_REGISTRY_KEY);
182
+ if (typeof registryKey !== "string" ||
183
+ !this.operationTraceRegistry.hasTrace(registryKey)) {
169
184
  return;
170
185
  }
171
186
  deferTraceCompletion(async () => {
172
187
  const userId = getUserIdSafely(this.options.http?.getUserId, [req], this.options.http, this.logger, "http");
173
- this.operationTraceRegistry.endTrace(traceId, {
188
+ this.operationTraceRegistry.endTrace(registryKey, {
174
189
  statusCode: res.statusCode,
175
190
  userId,
176
191
  });
177
- const snapshot = await this.operationTraceRegistry.pluckSnapshot(traceId);
192
+ const snapshot = await this.operationTraceRegistry.pluckSnapshot(registryKey);
178
193
  if (!snapshot) {
179
194
  return;
180
195
  }
@@ -185,7 +200,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
185
200
  }
186
201
  }
187
202
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
188
- }, this.logger, "http");
203
+ }, this.logger, "http", () => this.operationTraceRegistry.hasOpenSpans(registryKey));
189
204
  }
190
205
  /**
191
206
  * Frees the trace when the client goes away before the response finishes.
@@ -215,7 +215,7 @@ export class JobTraceRunner {
215
215
  const snapshot = (await this.operationTraceRegistry.pluckSnapshot(registryKey));
216
216
  // `pluckSnapshot` deletes what it returns, so a trace already
217
217
  // plucked answers undefined, and the encoder would dereference it
218
- // inside a `setTimeout`, where no try/catch can reach: an
218
+ // in this deferred completion, where no try/catch can reach: an
219
219
  // unhandled TypeError that took the whole process down.
220
220
  //
221
221
  // Dropped rather than reported: there is no snapshot, so there is
@@ -225,7 +225,7 @@ export class JobTraceRunner {
225
225
  return;
226
226
  }
227
227
  this.observeAgentSharedBuffer.insertJobSnapshot(snapshot);
228
- }, this.logger, "job");
228
+ }, this.logger, "job", () => this.operationTraceRegistry.hasOpenSpans(registryKey));
229
229
  };
230
230
  try {
231
231
  const returnValue = invoke(settle);