@nestjs/observe 0.3.21 → 0.3.23

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 (57) hide show
  1. package/README.md +100 -14
  2. package/dist/agent/degraded-ingest.protocol.d.ts +14 -0
  3. package/dist/agent/degraded-ingest.protocol.js +19 -0
  4. package/dist/agent/detached-observe-worker.assembly.d.ts +2 -0
  5. package/dist/agent/detached-observe-worker.assembly.js +5 -1
  6. package/dist/agent/detached-observe-worker.d.ts +10 -0
  7. package/dist/agent/detached-observe-worker.js +27 -2
  8. package/dist/agent/observe-agent.shared-buffer.d.ts +63 -1
  9. package/dist/agent/observe-agent.shared-buffer.js +117 -2
  10. package/dist/agent/observe-agent.worker.d.ts +27 -20
  11. package/dist/agent/observe-agent.worker.js +109 -62
  12. package/dist/agent/observe-reporting.util.d.ts +35 -0
  13. package/dist/agent/observe-reporting.util.js +69 -0
  14. package/dist/interfaces/observe-options.interface.d.ts +100 -8
  15. package/dist/observe.constants.d.ts +17 -0
  16. package/dist/observe.constants.js +17 -0
  17. package/dist/observe.module.js +53 -4
  18. package/dist/otlp/otlp-encoders.d.ts +26 -0
  19. package/dist/otlp/otlp-encoders.js +296 -0
  20. package/dist/otlp/otlp-export-grant.d.ts +34 -0
  21. package/dist/otlp/otlp-export-grant.js +22 -0
  22. package/dist/otlp/otlp-options.interface.d.ts +59 -0
  23. package/dist/otlp/otlp-options.interface.js +1 -0
  24. package/dist/otlp/otlp-settings.util.d.ts +38 -0
  25. package/dist/otlp/otlp-settings.util.js +154 -0
  26. package/dist/otlp/otlp-span.mapper.d.ts +73 -0
  27. package/dist/otlp/otlp-span.mapper.js +345 -0
  28. package/dist/otlp/otlp-trace-exporter.service.d.ts +130 -0
  29. package/dist/otlp/otlp-trace-exporter.service.js +497 -0
  30. package/dist/outgoing/http.integration.d.ts +36 -3
  31. package/dist/outgoing/http.integration.js +84 -17
  32. package/dist/outgoing/outgoing-observe-agent.service.d.ts +14 -1
  33. package/dist/outgoing/outgoing-observe-agent.service.js +24 -9
  34. package/dist/outgoing/outgoing-span.recorder.d.ts +11 -1
  35. package/dist/outgoing/outgoing-span.recorder.js +8 -2
  36. package/dist/outgoing/sql-statement.util.js +2 -2
  37. package/dist/protocols/http-observe-agent.service.d.ts +1 -8
  38. package/dist/protocols/http-observe-agent.service.js +44 -14
  39. package/dist/protocols/job-trace-runner.d.ts +11 -0
  40. package/dist/protocols/job-trace-runner.js +42 -8
  41. package/dist/protocols/rpc-observe-agent.service.d.ts +5 -0
  42. package/dist/protocols/rpc-observe-agent.service.js +43 -3
  43. package/dist/services/operation-trace.registry.d.ts +46 -3
  44. package/dist/services/operation-trace.registry.js +69 -13
  45. package/dist/services/tracer.service.d.ts +6 -0
  46. package/dist/services/tracer.service.js +11 -2
  47. package/dist/utils/default-trace-id-generator.util.d.ts +18 -0
  48. package/dist/utils/default-trace-id-generator.util.js +39 -2
  49. package/dist/utils/opentelemetry.util.d.ts +57 -0
  50. package/dist/utils/opentelemetry.util.js +100 -0
  51. package/dist/utils/trace-context.util.d.ts +91 -0
  52. package/dist/utils/trace-context.util.js +219 -0
  53. package/dist/utils/trace-handoff.util.d.ts +45 -0
  54. package/dist/utils/trace-handoff.util.js +90 -0
  55. package/dist/utils/trace-id-generator-origin.util.d.ts +11 -0
  56. package/dist/utils/trace-id-generator-origin.util.js +26 -0
  57. package/package.json +26 -13
@@ -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 agent reports to NestJS Observe (see
31
+ * `ObserveAgentSharedBuffer.isIngesting`). 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 refuses the app's credentials, 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 agent reports to NestJS Observe, 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 agent reports to NestJS Observe, 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 agent reports to NestJS Observe - 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;
@@ -5,8 +5,8 @@ const MAX_IDENTIFIER_LENGTH = 64;
5
5
  * falls through to the verb alone - a wrong table is worse than none.
6
6
  */
7
7
  const TABLE_AFTER = {
8
- SELECT: /\bFROM\s+([\w."`[\]]+)/i,
9
- DELETE: /\bFROM\s+([\w."`[\]]+)/i,
8
+ SELECT: /\bFROM\s+(?:ONLY\s+)?([\w."`[\]]+)/i,
9
+ DELETE: /\bFROM\s+(?:ONLY\s+)?([\w."`[\]]+)/i,
10
10
  INSERT: /\bINTO\s+([\w."`[\]]+)/i,
11
11
  REPLACE: /\bINTO\s+([\w."`[\]]+)/i,
12
12
  UPDATE: /^\s*UPDATE\s+(?:ONLY\s+)?([\w."`[\]]+)/i,
@@ -69,14 +69,7 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
69
69
  * to, so the HTTP side stands aside and everything else is still reported.
70
70
  */
71
71
  private hasRequestHooks;
72
- /**
73
- * A CORS preflight, when `http.tracePreflights` has not asked for them.
74
- *
75
- * Recognised by what the CORS spec defines a preflight to be - `OPTIONS`
76
- * with an `Access-Control-Request-Method` header - rather than by the
77
- * method alone, so an application's own `OPTIONS` handler is still traced.
78
- * Every adapter lower-cases header names.
79
- */
72
+ /** A CORS preflight, when `http.tracePreflights` has not asked for them. */
80
73
  private isUntracedPreflight;
81
74
  private shouldIgnoreRequest;
82
75
  }
@@ -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 beside reporting to NestJS Observe -
113
+ // see `ObserveAgentSharedBuffer.isIngesting`. Asked once per request,
114
+ // 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,20 @@ 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`. The registry keeps it beside the
135
+ // snapshot too, for `otlp`, which puts the operation's span under it.
136
+ const traceContext = openTelemetry
137
+ ? inboundTraceContext(req.headers)
138
+ : undefined;
139
+ if (traceContext) {
140
+ store.set(TRACE_CONTEXT_KEY, traceContext);
141
+ }
118
142
  setAttributesSafely(this.options.http?.setAttributes, [req], this.options.http, store, this.logger, "http");
119
143
  if (this.shouldIgnoreRequest(req) || this.isUntracedPreflight(req)) {
120
144
  return done();
@@ -143,7 +167,12 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
143
167
  method: req.method,
144
168
  originalUrl,
145
169
  },
146
- }, traceId);
170
+ }, traceId, traceContext);
171
+ // Answered by the CORS layer before any route, and on Fastify before
172
+ // any middleware too: a preflight asked for has no span to keep it.
173
+ if (isPreflight(req)) {
174
+ this.operationTraceRegistry.keepWithoutSpans(registryKey);
175
+ }
147
176
  this.evictTraceOnClientAbort(res, registryKey);
148
177
  done();
149
178
  });
@@ -230,18 +259,9 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
230
259
  }
231
260
  return false;
232
261
  }
233
- /**
234
- * A CORS preflight, when `http.tracePreflights` has not asked for them.
235
- *
236
- * Recognised by what the CORS spec defines a preflight to be - `OPTIONS`
237
- * with an `Access-Control-Request-Method` header - rather than by the
238
- * method alone, so an application's own `OPTIONS` handler is still traced.
239
- * Every adapter lower-cases header names.
240
- */
262
+ /** A CORS preflight, when `http.tracePreflights` has not asked for them. */
241
263
  isUntracedPreflight(req) {
242
- return (!this.options.http?.tracePreflights &&
243
- req.method === "OPTIONS" &&
244
- req.headers?.["access-control-request-method"] !== undefined);
264
+ return !this.options.http?.tracePreflights && isPreflight(req);
245
265
  }
246
266
  shouldIgnoreRequest(req) {
247
267
  if (typeof this.options.http?.ignore === "function") {
@@ -299,3 +319,13 @@ function toGlobalRegExp(pattern) {
299
319
  }
300
320
  return new RegExp(pattern.source, pattern.flags + "g");
301
321
  }
322
+ /**
323
+ * A CORS preflight: what the CORS spec defines one to be - `OPTIONS` with an
324
+ * `Access-Control-Request-Method` header - rather than the method alone, so
325
+ * an application's own `OPTIONS` handler is still traced as a request. Every
326
+ * adapter lower-cases header names.
327
+ */
328
+ function isPreflight(req) {
329
+ return (req.method === "OPTIONS" &&
330
+ req.headers?.["access-control-request-method"] !== undefined);
331
+ }
@@ -53,8 +53,19 @@ export declare class JobTraceRunner<Store extends Record<string, unknown>> {
53
53
  * under the one request that happened to register the schedule, for as long
54
54
  * as the schedule lives. Those runs are cron firings, and each mints its own
55
55
  * id like any other.
56
+ *
57
+ * With OpenTelemetry interop on, a W3C `traceparent` goes beside the id, for
58
+ * an OpenTelemetry SDK in the worker's process to continue - see
59
+ * `traceparentToHandOn`.
56
60
  */
57
61
  private stampTraceId;
62
+ /**
63
+ * Whether OpenTelemetry interop runs now: `openTelemetry` on, beside
64
+ * reporting to NestJS Observe - see `ObserveAgentSharedBuffer.isIngesting`.
65
+ * Asked as a job is enqueued and again as it starts, by each side for
66
+ * itself.
67
+ */
68
+ private openTelemetryInteropOn;
58
69
  /**
59
70
  * The id stamped at enqueue time, if it is one this agent would have minted
60
71
  * or adopted itself. Job options are readable and writable by anything with
@@ -1,5 +1,6 @@
1
- import { JOB_TRACE_OPTION_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
1
+ import { JOB_TRACE_CONTEXT_OPTION_KEY, JOB_TRACE_OPTION_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
2
2
  import { REQUEST_ID_PATTERN } from "../utils/default-trace-id-generator.util.js";
3
+ import { continueHandedOnTrace, traceparentToHandOn, } from "../utils/trace-handoff.util.js";
3
4
  import { uuidv7 } from "../utils/uuid-v7.util.js";
4
5
  import { deferTraceCompletion, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
5
6
  const ORIGINAL_ADD = Symbol.for("nestjs.observe.queue.add");
@@ -91,11 +92,14 @@ export class JobTraceRunner {
91
92
  * under the one request that happened to register the schedule, for as long
92
93
  * as the schedule lives. Those runs are cron firings, and each mints its own
93
94
  * id like any other.
95
+ *
96
+ * With OpenTelemetry interop on, a W3C `traceparent` goes beside the id, for
97
+ * an OpenTelemetry SDK in the worker's process to continue - see
98
+ * `traceparentToHandOn`.
94
99
  */
95
100
  stampTraceId(opts) {
96
- const traceId = this.asyncLocalStorage
97
- .getStore()
98
- ?.get(this.options.traceIdKey);
101
+ const store = this.asyncLocalStorage.getStore();
102
+ const traceId = store?.get(this.options.traceIdKey);
99
103
  if (typeof traceId !== "string") {
100
104
  return undefined;
101
105
  }
@@ -106,7 +110,25 @@ export class JobTraceRunner {
106
110
  if (current["repeat"] || current[JOB_TRACE_OPTION_KEY] !== undefined) {
107
111
  return undefined;
108
112
  }
109
- return { ...current, [JOB_TRACE_OPTION_KEY]: traceId };
113
+ const stamped = {
114
+ ...current,
115
+ [JOB_TRACE_OPTION_KEY]: traceId,
116
+ };
117
+ if (this.openTelemetryInteropOn() &&
118
+ current[JOB_TRACE_CONTEXT_OPTION_KEY] === undefined) {
119
+ stamped[JOB_TRACE_CONTEXT_OPTION_KEY] = traceparentToHandOn(store, traceId);
120
+ }
121
+ return stamped;
122
+ }
123
+ /**
124
+ * Whether OpenTelemetry interop runs now: `openTelemetry` on, beside
125
+ * reporting to NestJS Observe - see `ObserveAgentSharedBuffer.isIngesting`.
126
+ * Asked as a job is enqueued and again as it starts, by each side for
127
+ * itself.
128
+ */
129
+ openTelemetryInteropOn() {
130
+ return (this.options.openTelemetry === true &&
131
+ this.observeAgentSharedBuffer.isIngesting());
110
132
  }
111
133
  /**
112
134
  * The id stamped at enqueue time, if it is one this agent would have minted
@@ -184,9 +206,17 @@ export class JobTraceRunner {
184
206
  // The registry key is always this run's own. The inherited id may belong
185
207
  // to a request still open in this process, and a retry reuses it.
186
208
  const registryKey = uuidv7();
187
- const traceId = this.readInheritedTraceId(job.opts) ?? registryKey;
209
+ const inheritedTraceId = this.readInheritedTraceId(job.opts);
210
+ const traceId = inheritedTraceId ?? registryKey;
188
211
  store.set(this.options.traceIdKey, traceId);
189
212
  store.set(TRACE_REGISTRY_KEY, registryKey);
213
+ // With OpenTelemetry interop on, the job runs in the W3C trace context
214
+ // it was enqueued in, for an OpenTelemetry SDK in this process - see
215
+ // `continueHandedOnTrace`. Recorded or not, as an outbound call carries
216
+ // the trace on for an unrecorded request.
217
+ const handedOn = inheritedTraceId !== undefined && this.openTelemetryInteropOn()
218
+ ? job.opts?.[JOB_TRACE_CONTEXT_OPTION_KEY]
219
+ : undefined;
190
220
  const context = {
191
221
  queueName: job.queueName,
192
222
  name: job.name,
@@ -197,7 +227,9 @@ export class JobTraceRunner {
197
227
  // The trace id stays in the store so logs and jobs enqueued from here
198
228
  // still correlate; nothing is registered under the registry key, so
199
229
  // its spans have no trace to join.
200
- return invoke(() => undefined);
230
+ return handedOn === undefined
231
+ ? invoke(() => undefined)
232
+ : continueHandedOnTrace(handedOn, traceId, () => invoke(() => undefined));
201
233
  }
202
234
  this.operationTraceRegistry.startTrace(registryKey, {
203
235
  tags: this.options.jobs?.tags,
@@ -228,7 +260,9 @@ export class JobTraceRunner {
228
260
  }, this.logger, "job", () => this.operationTraceRegistry.hasOpenSpans(registryKey));
229
261
  };
230
262
  try {
231
- const returnValue = invoke(settle);
263
+ const returnValue = handedOn === undefined
264
+ ? invoke(settle)
265
+ : continueHandedOnTrace(handedOn, traceId, () => invoke(settle));
232
266
  if (returnValue instanceof Promise) {
233
267
  return returnValue
234
268
  .then((ret) => {
@@ -48,6 +48,11 @@ export declare class RpcObserveAgentService<Store extends Record<string, unknown
48
48
  */
49
49
  private toProtocolName;
50
50
  startRpcRequestTracing(transportId: Transport | symbol, ctx: BaseRpcContext, done: () => Promise<any>): Promise<unknown>;
51
+ /**
52
+ * Whether OpenTelemetry interop runs now: `openTelemetry` on, beside
53
+ * reporting to NestJS Observe - see `ObserveAgentSharedBuffer.isIngesting`.
54
+ */
55
+ private openTelemetryInteropOn;
51
56
  startGrpcRequestTracing(transportId: Transport | symbol, call: GrpcCall, done: () => Promise<any>): Promise<unknown>;
52
57
  endRpcRequestTracing(transportId: Transport | symbol, ctx: BaseRpcContext | GrpcCall): void;
53
58
  private getOperationIdFromContext;
@@ -18,6 +18,7 @@ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.j
18
18
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
19
19
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
20
20
  import { OBSERVE_OPTIONS, TRACE_REGISTRY_KEY } from "../observe.constants.js";
21
+ import { continueHandedOnTrace } from "../utils/trace-handoff.util.js";
21
22
  import { uuidv7 } from "../utils/uuid-v7.util.js";
22
23
  import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
23
24
  import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
@@ -118,25 +119,43 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
118
119
  // execution before option callbacks can reach another operation's trace.
119
120
  const registryKey = uuidv7();
120
121
  store.set(TRACE_REGISTRY_KEY, registryKey);
122
+ // With OpenTelemetry interop on, the handler runs in the W3C trace
123
+ // context the message was sent in, for an OpenTelemetry SDK in this
124
+ // process - see `continueHandedOnTrace`. Recorded or not, as an
125
+ // outbound call carries the trace on for an unrecorded request.
126
+ const handedOn = this.openTelemetryInteropOn()
127
+ ? handedOnTraceparent(ctx)
128
+ : undefined;
129
+ const handle = handedOn === undefined
130
+ ? done
131
+ : () => continueHandedOnTrace(handedOn, traceId, done);
121
132
  setAttributesSafely(this.options.rpc?.setAttributes, [transportId, ctx], this.options.rpc, store, this.logger, "rpc");
122
133
  if (shouldIgnoreSafely(this.options.rpc?.ignore, [transportId, ctx], this.options.rpc, this.logger, "rpc")) {
123
- return done();
134
+ return handle();
124
135
  }
125
136
  const shouldCapture = this.traceSamplerService.shouldCapture("rpc", {
126
137
  transport: transportId.toString(),
127
138
  ctx: ctx,
128
139
  });
129
140
  if (!shouldCapture) {
130
- return done();
141
+ return handle();
131
142
  }
132
143
  this.operationTraceRegistry.startTrace(registryKey, {
133
144
  protocol: this.toProtocolName(transportId),
134
145
  operationId: this.getOperationIdFromContext(ctx),
135
146
  tags: this.options.rpc?.tags,
136
147
  }, traceId);
137
- return done();
148
+ return handle();
138
149
  });
139
150
  }
151
+ /**
152
+ * Whether OpenTelemetry interop runs now: `openTelemetry` on, beside
153
+ * reporting to NestJS Observe - see `ObserveAgentSharedBuffer.isIngesting`.
154
+ */
155
+ openTelemetryInteropOn() {
156
+ return (this.options.openTelemetry === true &&
157
+ this.observeAgentSharedBuffer.isIngesting());
158
+ }
140
159
  startGrpcRequestTracing(transportId, call, done) {
141
160
  // As above: the map `run` is given, not looked back up.
142
161
  const store = new Map();
@@ -232,3 +251,24 @@ RpcObserveAgentService = RpcObserveAgentService_1 = __decorate([
232
251
  TraceSamplerService])
233
252
  ], RpcObserveAgentService);
234
253
  export { RpcObserveAgentService };
254
+ /**
255
+ * The `traceparent` the sending service's agent put in the packet's metadata
256
+ * beside `x-request-id` - see `traceparentToHandOn` - on a transport whose
257
+ * packets carry metadata: TCP and Redis, from `@nestjs/microservices` 12.0.4.
258
+ * Read as `defaultTraceIdGenerator` reads the id, and held to the spec by
259
+ * `continueHandedOnTrace`.
260
+ */
261
+ function handedOnTraceparent(ctx) {
262
+ try {
263
+ const getMetadata = ctx?.getMetadata;
264
+ if (typeof getMetadata !== "function") {
265
+ return undefined;
266
+ }
267
+ const metadata = getMetadata.call(ctx);
268
+ return metadata?.["traceparent"];
269
+ }
270
+ catch {
271
+ // A context that cannot be read carries nothing to continue.
272
+ return undefined;
273
+ }
274
+ }