@nestjs/observe 0.3.22 → 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 (48) hide show
  1. package/README.md +71 -14
  2. package/dist/agent/degraded-ingest.protocol.d.ts +2 -8
  3. package/dist/agent/degraded-ingest.protocol.js +2 -8
  4. package/dist/agent/detached-observe-worker.assembly.d.ts +2 -0
  5. package/dist/agent/detached-observe-worker.assembly.js +3 -0
  6. package/dist/agent/detached-observe-worker.d.ts +8 -0
  7. package/dist/agent/detached-observe-worker.js +20 -2
  8. package/dist/agent/observe-agent.shared-buffer.d.ts +48 -22
  9. package/dist/agent/observe-agent.shared-buffer.js +94 -34
  10. package/dist/agent/observe-agent.worker.d.ts +16 -21
  11. package/dist/agent/observe-agent.worker.js +67 -74
  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 +67 -13
  15. package/dist/observe.constants.d.ts +7 -0
  16. package/dist/observe.constants.js +7 -0
  17. package/dist/observe.module.js +50 -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 +6 -4
  31. package/dist/outgoing/http.integration.js +3 -3
  32. package/dist/outgoing/outgoing-observe-agent.service.d.ts +2 -2
  33. package/dist/outgoing/outgoing-observe-agent.service.js +1 -1
  34. package/dist/outgoing/sql-statement.util.js +2 -2
  35. package/dist/protocols/http-observe-agent.service.d.ts +1 -8
  36. package/dist/protocols/http-observe-agent.service.js +28 -21
  37. package/dist/protocols/job-trace-runner.d.ts +11 -0
  38. package/dist/protocols/job-trace-runner.js +42 -8
  39. package/dist/protocols/rpc-observe-agent.service.d.ts +5 -0
  40. package/dist/protocols/rpc-observe-agent.service.js +43 -3
  41. package/dist/services/operation-trace.registry.d.ts +29 -1
  42. package/dist/services/operation-trace.registry.js +46 -5
  43. package/dist/utils/default-trace-id-generator.util.js +6 -2
  44. package/dist/utils/opentelemetry.util.d.ts +26 -0
  45. package/dist/utils/opentelemetry.util.js +48 -0
  46. package/dist/utils/trace-handoff.util.d.ts +45 -0
  47. package/dist/utils/trace-handoff.util.js +90 -0
  48. package/package.json +13 -12
@@ -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
+ }
@@ -7,6 +7,7 @@ import { OngoingTraceEventNode } from "../interfaces/trace-events.interfaces.js"
7
7
  import { TraceSpanDelegate } from "../trace-span.delegate.js";
8
8
  import { KeyOf } from "../types/key-of.type.js";
9
9
  import { LogRedactor } from "../utils/log-redactor.js";
10
+ import type { TraceContext } from "../utils/trace-context.util.js";
10
11
  import { CALLER_METADATA_KEY } from "../observe.constants.js";
11
12
  import { SpanCollapseSettings } from "./collapse-repeated-spans.util.js";
12
13
  import { SkipSpansPredicate } from "./skip-spans.util.js";
@@ -59,6 +60,16 @@ export declare class OperationTraceRegistry {
59
60
  * switched off explicitly.
60
61
  */
61
62
  private redactor;
63
+ /**
64
+ * The W3C trace context each operation arrived with, by snapshot.
65
+ *
66
+ * Beside the snapshot rather than on it: both encoders map every key a
67
+ * snapshot has onto the wire, and the collector refuses a batch carrying a
68
+ * key it does not know. The snapshot object `startTrace` builds is the one
69
+ * `pluckSnapshot` hands out, so whoever receives it can still look its
70
+ * context up - and the entry goes when the snapshot does.
71
+ */
72
+ private readonly traceContexts;
62
73
  constructor(als: AsyncLocalStorage<Map<KeyOf<{
63
74
  [CALLER_METADATA_KEY]: string;
64
75
  }>, unknown>>, sourceContext?: CreateObserveModuleOptions["sourceContext"]);
@@ -108,7 +119,14 @@ export declare class OperationTraceRegistry {
108
119
  * The trace id the snapshot reports under, when it is not the registry
109
120
  * key - a job inheriting the id of the operation that enqueued it.
110
121
  */
111
- reportedTraceId?: string): void;
122
+ reportedTraceId?: string,
123
+ /** The `traceparent` the operation arrived with, when it had one. */
124
+ traceContext?: TraceContext): void;
125
+ /**
126
+ * The `traceparent` a snapshot's operation arrived with, if it had one -
127
+ * for the exporter, which puts the operation under the caller's span.
128
+ */
129
+ traceContextOf(snapshot: object): TraceContext | undefined;
112
130
  endTrace(traceId: string): void;
113
131
  endTrace(traceId: string, opts?: {
114
132
  statusCode?: number;
@@ -204,6 +222,16 @@ export declare class OperationTraceRegistry {
204
222
  * reader could look it up.
205
223
  */
206
224
  reportedTraceId?: string): void;
225
+ /**
226
+ * Reports the trace even if it ends with no span recorded under it.
227
+ *
228
+ * `endTrace` drops such a trace, as a request no handler ran for. A CORS
229
+ * preflight that `http.tracePreflights` asked for is the one operation that
230
+ * is complete without a handler: the CORS layer answers it before any
231
+ * route, and - on Fastify from `@nestjs/platform-fastify` 12.1.3 - before
232
+ * any middleware that could record a span for it.
233
+ */
234
+ keepWithoutSpans(traceId: TraceId): void;
207
235
  /**
208
236
  * Drops a trace that will never be plucked, freeing both maps.
209
237
  *
@@ -126,6 +126,16 @@ export class OperationTraceRegistry {
126
126
  * switched off explicitly.
127
127
  */
128
128
  redactor = new LogRedactor();
129
+ /**
130
+ * The W3C trace context each operation arrived with, by snapshot.
131
+ *
132
+ * Beside the snapshot rather than on it: both encoders map every key a
133
+ * snapshot has onto the wire, and the collector refuses a batch carrying a
134
+ * key it does not know. The snapshot object `startTrace` builds is the one
135
+ * `pluckSnapshot` hands out, so whoever receives it can still look its
136
+ * context up - and the entry goes when the snapshot does.
137
+ */
138
+ traceContexts = new WeakMap();
129
139
  constructor(als, sourceContext = true) {
130
140
  this.als = als;
131
141
  this.sourceContext = sourceContext;
@@ -229,7 +239,9 @@ export class OperationTraceRegistry {
229
239
  * The trace id the snapshot reports under, when it is not the registry
230
240
  * key - a job inheriting the id of the operation that enqueued it.
231
241
  */
232
- reportedTraceId = traceId) {
242
+ reportedTraceId = traceId,
243
+ /** The `traceparent` the operation arrived with, when it had one. */
244
+ traceContext) {
233
245
  if (this.traceSnapshots.has(traceId)) {
234
246
  this.logger.warn(`Trace already started for traceId: "${traceId}". Overwriting existing trace.`);
235
247
  this.traceSnapshots.delete(traceId);
@@ -245,6 +257,16 @@ export class OperationTraceRegistry {
245
257
  refsMarkedAsComplete: 0,
246
258
  };
247
259
  this.traceSnapshots.set(traceId, snapshot);
260
+ if (traceContext) {
261
+ this.traceContexts.set(snapshot, traceContext);
262
+ }
263
+ }
264
+ /**
265
+ * The `traceparent` a snapshot's operation arrived with, if it had one -
266
+ * for the exporter, which puts the operation under the caller's span.
267
+ */
268
+ traceContextOf(snapshot) {
269
+ return this.traceContexts.get(snapshot);
248
270
  }
249
271
  endTrace(traceId, opts = {}) {
250
272
  const snapshot = this.traceSnapshots.get(traceId);
@@ -262,9 +284,12 @@ export class OperationTraceRegistry {
262
284
  return;
263
285
  }
264
286
  // Ignore snapshots that have no traces as that means
265
- // the request didnt even have a handler in the first place
266
- this.traceSnapshots.delete(traceId);
267
- return;
287
+ // the request didnt even have a handler in the first place - unless
288
+ // the transport said the operation is complete without one.
289
+ if (!snapshot.keptWithoutSpans) {
290
+ this.traceSnapshots.delete(traceId);
291
+ return;
292
+ }
268
293
  }
269
294
  // Set by `startTrace` and deleted a few lines below, so it is always there
270
295
  // for a snapshot still in the registry. The fallback keeps a duration of 0
@@ -605,6 +630,21 @@ export class OperationTraceRegistry {
605
630
  Object.assign(targetSpan.tags, tags);
606
631
  targetSpan.error = this.toErrorPayload(error);
607
632
  }
633
+ /**
634
+ * Reports the trace even if it ends with no span recorded under it.
635
+ *
636
+ * `endTrace` drops such a trace, as a request no handler ran for. A CORS
637
+ * preflight that `http.tracePreflights` asked for is the one operation that
638
+ * is complete without a handler: the CORS layer answers it before any
639
+ * route, and - on Fastify from `@nestjs/platform-fastify` 12.1.3 - before
640
+ * any middleware that could record a span for it.
641
+ */
642
+ keepWithoutSpans(traceId) {
643
+ const snapshot = this.traceSnapshots.get(traceId);
644
+ if (snapshot) {
645
+ snapshot.keptWithoutSpans = true;
646
+ }
647
+ }
608
648
  /**
609
649
  * Drops a trace that will never be plucked, freeing both maps.
610
650
  *
@@ -653,7 +693,7 @@ export class OperationTraceRegistry {
653
693
  }
654
694
  }
655
695
  cleanup();
656
- // These four are what distinguish the registry's working copy from the
696
+ // These five are what distinguish the registry's working copy from the
657
697
  // snapshot the API receives, so removing them is the hand-off.
658
698
  const bookkeeping = snapshot;
659
699
  const customOperationId = bookkeeping.customOperationId;
@@ -661,6 +701,7 @@ export class OperationTraceRegistry {
661
701
  delete bookkeeping.refsMarkedAsComplete;
662
702
  delete bookkeeping.errorStatusCode;
663
703
  delete bookkeeping.customOperationId;
704
+ delete bookkeeping.keptWithoutSpans;
664
705
  // Before `skipSpans`, which judges the operation by the name it is
665
706
  // reported under.
666
707
  if (customOperationId !== undefined && "protocol" in snapshot) {
@@ -20,8 +20,12 @@ export function defaultTraceIdGenerator(req) {
20
20
  }
21
21
  }
22
22
  // A microservice context, on a transport whose packets carry metadata: the
23
- // id the calling service's client attached. Held to the same shape as the
24
- // header - a packet is no more trustworthy than a request.
23
+ // id the calling service's client attached. TCP and Redis carry it inside
24
+ // the packet, from @nestjs/microservices 12.0.4. NATS, Kafka, RabbitMQ,
25
+ // MQTT 5 and gRPC carry it as a header, from 12.3.3 (nestjs/nest#18386),
26
+ // which gave their contexts - and the context gRPC hands the processing
27
+ // hooks - the same `getMetadata()`. Held to the same shape as the header - a
28
+ // packet is no more trustworthy than a request.
25
29
  const getMetadata = req?.getMetadata;
26
30
  if (typeof getMetadata === "function") {
27
31
  const metadata = getMetadata.call(req);
@@ -10,6 +10,18 @@ export interface OpenTelemetrySpanContext {
10
10
  serialize(): string;
11
11
  };
12
12
  }
13
+ /**
14
+ * A span in another process, or in the operation that handed this work on,
15
+ * for an OpenTelemetry SDK here to continue - what its propagator reads off
16
+ * a `traceparent`.
17
+ */
18
+ export interface RemoteParent {
19
+ /** 32 lowercase hex digits. */
20
+ traceId: string;
21
+ /** 16 lowercase hex digits. */
22
+ spanId: string;
23
+ sampled: boolean;
24
+ }
13
25
  /**
14
26
  * The span an OpenTelemetry SDK in this process has open in the current
15
27
  * context - for an incoming request, the server span its HTTP instrumentation
@@ -29,3 +41,17 @@ export declare function activeOpenTelemetrySpanContext(): OpenTelemetrySpanConte
29
41
  * the SDK's names the span the rest of its trace nests under.
30
42
  */
31
43
  export declare function openTelemetryWritesTraceparent(): boolean;
44
+ /**
45
+ * Runs `run` with `parent` as the span an OpenTelemetry SDK in this process
46
+ * continues, as its propagator continues a `traceparent` read off an
47
+ * incoming request: the spans its instrumentations open inside `run` join
48
+ * `parent`'s trace, under it, and the calls they cover carry that trace on.
49
+ *
50
+ * For work that reaches this process by a way no OpenTelemetry
51
+ * instrumentation covers - a queue job, a microservice message - and that
52
+ * would otherwise run in no trace at all. Without `@opentelemetry/api`, or
53
+ * with no SDK registered on it, `run` just runs. Never the reason `run`
54
+ * fails: an API this cannot use is treated as absent, and what `run` itself
55
+ * throws is thrown as it is.
56
+ */
57
+ export declare function withRemoteOpenTelemetryParent<T>(parent: RemoteParent, run: () => T): T;
@@ -50,3 +50,51 @@ export function openTelemetryWritesTraceparent() {
50
50
  return false;
51
51
  }
52
52
  }
53
+ /**
54
+ * Runs `run` with `parent` as the span an OpenTelemetry SDK in this process
55
+ * continues, as its propagator continues a `traceparent` read off an
56
+ * incoming request: the spans its instrumentations open inside `run` join
57
+ * `parent`'s trace, under it, and the calls they cover carry that trace on.
58
+ *
59
+ * For work that reaches this process by a way no OpenTelemetry
60
+ * instrumentation covers - a queue job, a microservice message - and that
61
+ * would otherwise run in no trace at all. Without `@opentelemetry/api`, or
62
+ * with no SDK registered on it, `run` just runs. Never the reason `run`
63
+ * fails: an API this cannot use is treated as absent, and what `run` itself
64
+ * throws is thrown as it is.
65
+ */
66
+ export function withRemoteOpenTelemetryParent(parent, run) {
67
+ let enter;
68
+ try {
69
+ const otel = openTelemetryApi();
70
+ if (otel) {
71
+ const parentContext = otel.trace.setSpanContext(otel.context.active(), {
72
+ traceId: parent.traceId,
73
+ spanId: parent.spanId,
74
+ traceFlags: parent.sampled ? 0x01 : 0x00,
75
+ isRemote: true,
76
+ });
77
+ enter = (fn) => otel.context.with(parentContext, fn);
78
+ }
79
+ }
80
+ catch {
81
+ enter = undefined;
82
+ }
83
+ if (!enter) {
84
+ return run();
85
+ }
86
+ let entered = false;
87
+ try {
88
+ return enter(() => {
89
+ entered = true;
90
+ return run();
91
+ });
92
+ }
93
+ catch (error) {
94
+ if (entered) {
95
+ throw error;
96
+ }
97
+ // The SDK's context manager failed before `run` started.
98
+ return run();
99
+ }
100
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The `traceparent` an operation hands on with work it starts elsewhere,
3
+ * beside the Observe trace id `traceId` that the work inherits.
4
+ *
5
+ * Its trace is the W3C form of `traceId`, so the work has one trace id in
6
+ * both tools whatever side runs it. Its parent is the span an OpenTelemetry
7
+ * SDK in this process has open, when that span is in the same trace - so
8
+ * the SDK's spans for the work nest under the request's in its backend -
9
+ * and its sampled flag is that span's. Otherwise it is the span Observe has
10
+ * open, as on an outbound HTTP call, with the sampled flag the operation
11
+ * arrived with, else whether Observe is recording it.
12
+ *
13
+ * `store` is the operation's async store.
14
+ */
15
+ export declare function traceparentToHandOn(store: ReadonlyMap<unknown, unknown> | undefined, traceId: string): string;
16
+ /**
17
+ * Runs `run` in the trace a `traceparent` handed on with the work names -
18
+ * see `traceparentToHandOn` - for an OpenTelemetry SDK in this process: the
19
+ * spans it opens inside `run` join that trace, under the span that handed
20
+ * the work on, and the calls they cover carry the trace on.
21
+ *
22
+ * Only a `traceparent` the spec accepts, and only in the trace `traceId` -
23
+ * the Observe trace id the work runs under - maps onto: job options and
24
+ * packet metadata are writable by anything that reaches Redis or the
25
+ * socket, and a span from another trace would put the work under one it
26
+ * never ran beside. Anything else runs `run` as it is.
27
+ */
28
+ export declare function continueHandedOnTrace<T>(traceparent: unknown, traceId: string, run: () => T): T;
29
+ /**
30
+ * Whether OpenTelemetry interop runs now - `openTelemetry` on, beside
31
+ * reporting to NestJS Observe (see `ObserveAgentSharedBuffer.isIngesting`) -
32
+ * for what is set up before the module's options resolve: the microservice
33
+ * dispatch hook, which a client is handed as it is instantiated. Off until
34
+ * the module configures it.
35
+ */
36
+ export declare class OpenTelemetryInteropGate {
37
+ private options?;
38
+ private buffer?;
39
+ configure(options: {
40
+ openTelemetry?: boolean;
41
+ } | undefined, buffer: {
42
+ isIngesting(): boolean;
43
+ } | undefined): this;
44
+ isOn(): boolean;
45
+ }
@@ -0,0 +1,90 @@
1
+ import { CALLER_METADATA_KEY, TRACE_CONTEXT_KEY, } from "../observe.constants.js";
2
+ import { activeOpenTelemetrySpanContext, withRemoteOpenTelemetryParent, } from "./opentelemetry.util.js";
3
+ import { formatTraceparent, randomSpanId, readTraceContext, w3cSpanIdOf, w3cTraceIdOf, } from "./trace-context.util.js";
4
+ /**
5
+ * W3C Trace Context for work an operation hands on where no OpenTelemetry
6
+ * instrumentation carries it - a queue job it enqueues, a microservice
7
+ * message it sends - with `openTelemetry` on.
8
+ *
9
+ * Observe carries its own trace id across those hops already: in a job's
10
+ * options (`observeTraceId`) and in a message's `x-request-id` metadata. An
11
+ * OpenTelemetry SDK in the process that runs the job or handles the message
12
+ * has nothing to go on, though, so the spans it opens there - and the
13
+ * `traceparent` on every call they make - would start a trace of their own,
14
+ * which every service further down then follows. So the hop carries a
15
+ * `traceparent` too, and the other side hands it to the SDK.
16
+ */
17
+ /** A span id the spec accepts: 16 lowercase hex digits, not all zeros. */
18
+ const SPAN_ID_PATTERN = /^(?![0]{16})[0-9a-f]{16}$/;
19
+ /**
20
+ * The `traceparent` an operation hands on with work it starts elsewhere,
21
+ * beside the Observe trace id `traceId` that the work inherits.
22
+ *
23
+ * Its trace is the W3C form of `traceId`, so the work has one trace id in
24
+ * both tools whatever side runs it. Its parent is the span an OpenTelemetry
25
+ * SDK in this process has open, when that span is in the same trace - so
26
+ * the SDK's spans for the work nest under the request's in its backend -
27
+ * and its sampled flag is that span's. Otherwise it is the span Observe has
28
+ * open, as on an outbound HTTP call, with the sampled flag the operation
29
+ * arrived with, else whether Observe is recording it.
30
+ *
31
+ * `store` is the operation's async store.
32
+ */
33
+ export function traceparentToHandOn(store, traceId) {
34
+ const w3cTraceId = w3cTraceIdOf(traceId);
35
+ const active = activeOpenTelemetrySpanContext();
36
+ if (active?.traceId === w3cTraceId &&
37
+ typeof active.spanId === "string" &&
38
+ SPAN_ID_PATTERN.test(active.spanId)) {
39
+ return formatTraceparent(w3cTraceId, active.spanId, (active.traceFlags & 0x01) === 0x01);
40
+ }
41
+ const caller = store?.get(CALLER_METADATA_KEY);
42
+ const received = store?.get(TRACE_CONTEXT_KEY);
43
+ const recorded = typeof caller === "string";
44
+ return formatTraceparent(w3cTraceId, recorded ? w3cSpanIdOf(caller) : randomSpanId(), received?.traceId === w3cTraceId ? received.sampled : recorded);
45
+ }
46
+ /**
47
+ * Runs `run` in the trace a `traceparent` handed on with the work names -
48
+ * see `traceparentToHandOn` - for an OpenTelemetry SDK in this process: the
49
+ * spans it opens inside `run` join that trace, under the span that handed
50
+ * the work on, and the calls they cover carry the trace on.
51
+ *
52
+ * Only a `traceparent` the spec accepts, and only in the trace `traceId` -
53
+ * the Observe trace id the work runs under - maps onto: job options and
54
+ * packet metadata are writable by anything that reaches Redis or the
55
+ * socket, and a span from another trace would put the work under one it
56
+ * never ran beside. Anything else runs `run` as it is.
57
+ */
58
+ export function continueHandedOnTrace(traceparent, traceId, run) {
59
+ const parent = typeof traceparent === "string"
60
+ ? readTraceContext({ traceparent })
61
+ : undefined;
62
+ if (!parent || parent.traceId !== w3cTraceIdOf(traceId)) {
63
+ return run();
64
+ }
65
+ return withRemoteOpenTelemetryParent({
66
+ traceId: parent.traceId,
67
+ spanId: parent.parentSpanId,
68
+ sampled: parent.sampled,
69
+ }, run);
70
+ }
71
+ /**
72
+ * Whether OpenTelemetry interop runs now - `openTelemetry` on, beside
73
+ * reporting to NestJS Observe (see `ObserveAgentSharedBuffer.isIngesting`) -
74
+ * for what is set up before the module's options resolve: the microservice
75
+ * dispatch hook, which a client is handed as it is instantiated. Off until
76
+ * the module configures it.
77
+ */
78
+ export class OpenTelemetryInteropGate {
79
+ options;
80
+ buffer;
81
+ configure(options, buffer) {
82
+ this.options = options;
83
+ this.buffer = buffer;
84
+ return this;
85
+ }
86
+ isOn() {
87
+ return (this.options?.openTelemetry === true &&
88
+ this.buffer?.isIngesting() === true);
89
+ }
90
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.3.22",
3
+ "version": "0.3.23",
4
4
  "description": "Observability and APM agent for NestJS - traces, runtime metrics and custom metrics",
5
5
  "author": "Kamil Mysliwiec",
6
6
  "homepage": "https://observe.nestjs.com",
@@ -137,18 +137,18 @@
137
137
  "@nestjs/apollo": "14.1.1",
138
138
  "@nestjs/bull": "12.0.0",
139
139
  "@nestjs/bullmq": "12.0.0",
140
- "@nestjs/common": "12.0.1",
141
- "@nestjs/core": "12.0.1",
140
+ "@nestjs/common": "12.3.3",
141
+ "@nestjs/core": "12.3.3",
142
142
  "@nestjs/graphql": "14.0.0",
143
- "@nestjs/microservices": "12.0.1",
144
- "@nestjs/platform-express": "12.0.1",
145
- "@nestjs/platform-fastify": "12.0.3",
146
- "@nestjs/platform-node": "12.3.2",
147
- "@nestjs/platform-socket.io": "12.0.3",
148
- "@nestjs/platform-ws": "12.0.3",
143
+ "@nestjs/microservices": "12.3.3",
144
+ "@nestjs/platform-express": "12.3.3",
145
+ "@nestjs/platform-fastify": "12.3.3",
146
+ "@nestjs/platform-node": "12.3.3",
147
+ "@nestjs/platform-socket.io": "12.3.3",
148
+ "@nestjs/platform-ws": "12.3.3",
149
149
  "@nestjs/schedule": "12.0.1",
150
- "@nestjs/testing": "12.0.1",
151
- "@nestjs/websockets": "12.0.3",
150
+ "@nestjs/testing": "12.3.3",
151
+ "@nestjs/websockets": "12.3.3",
152
152
  "@opentelemetry/api": "1.9.1",
153
153
  "@opentelemetry/auto-instrumentations-node": "0.81.0",
154
154
  "@opentelemetry/context-async-hooks": "2.12.0",
@@ -174,13 +174,14 @@
174
174
  "lint-staged": "17.6.0",
175
175
  "mongodb": "7.6.0",
176
176
  "mongoose": "9.10.1",
177
- "mssql": "12.7.11",
177
+ "mssql": "12.7.13",
178
178
  "mysql2": "3.24.6",
179
179
  "nestjs-cls": "6.2.1",
180
180
  "oxlint": "1.79.0",
181
181
  "oxlint-tsgolint": "7.0.2001",
182
182
  "pg": "8.23.0",
183
183
  "prettier": "3.2.5",
184
+ "protobufjs": "7.6.5",
184
185
  "reflect-metadata": "0.2.2",
185
186
  "release-it": "21.0.2",
186
187
  "rimraf": "6.1.3",