@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
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The hosted collector. Unlike a collector in placeholder mode, it accepts
3
+ * nothing without credentials.
4
+ */
5
+ const HOSTED_COLLECTOR_ENDPOINT = "https://observe-api.nestjs.com";
6
+ /**
7
+ * Where signals are posted when `endpoint` is not configured.
8
+ */
9
+ const DEFAULT_COLLECTOR_ENDPOINT = process.env.OBSERVE_ENDPOINT ?? HOSTED_COLLECTOR_ENDPOINT;
10
+ /**
11
+ * The credentials `nest new --observe` writes into `AppModule`.
12
+ *
13
+ * A project fresh from the generator has these until someone signs up, so
14
+ * they mean "not connected yet", not "wrong": sending them only buys a 401
15
+ * and an `Error:` line on the very first `npm run start`.
16
+ */
17
+ const SCAFFOLD_APP_KEY = "YOUR_APP_KEY";
18
+ const SCAFFOLD_APP_SECRET = "YOUR_APP_SECRET";
19
+ /** The collector the agent posts to: `endpoint`, else the default. */
20
+ export function collectorEndpointOf(options) {
21
+ return options.endpoint ?? DEFAULT_COLLECTOR_ENDPOINT;
22
+ }
23
+ export function hasScaffoldCredentials(options) {
24
+ return (options.appKey === SCAFFOLD_APP_KEY &&
25
+ options.appSecret === SCAFFOLD_APP_SECRET);
26
+ }
27
+ /**
28
+ * Whether `endpoint` - set, from `OBSERVE_ENDPOINT`, or the default - is the
29
+ * hosted collector. Compared by host, so a trailing slash or a capital
30
+ * letter cannot pass it off as a collector of the user's own.
31
+ */
32
+ export function isHostedCollector(endpoint) {
33
+ try {
34
+ return (new URL(endpoint).hostname === new URL(HOSTED_COLLECTOR_ENDPOINT).hostname);
35
+ }
36
+ catch {
37
+ // Not a URL at all; the worker says so when it tries to send.
38
+ return false;
39
+ }
40
+ }
41
+ /**
42
+ * Whether credentials are missing and the collector is the hosted one,
43
+ * which answers every batch without them with a 401.
44
+ *
45
+ * The worker leaves both headers off when either half is unset, which a
46
+ * collector in placeholder mode accepts, so a collector of the user's own
47
+ * still gets those batches. The hosted collector refuses them for as long
48
+ * as the process runs: on 2026-10-15 that was 42% of the 1.87M batches it
49
+ * refused, from processes deployed without their environment variables,
50
+ * some of them posting every five seconds for weeks.
51
+ */
52
+ export function lacksHostedCredentials(options) {
53
+ return ((!options.appKey || !options.appSecret) &&
54
+ isHostedCollector(collectorEndpointOf(options)));
55
+ }
56
+ /**
57
+ * Whether the agent sends NestJS Observe anything: not with `enabled:
58
+ * false`, not with `nest new`'s placeholders, and not without both
59
+ * credentials when `endpoint` is the hosted collector. Another `endpoint` - a
60
+ * proxy that adds them on the way - is sent to either way.
61
+ *
62
+ * The worker starts only when this holds. So does OTLP export, which runs
63
+ * beside reporting to Observe, never instead of it.
64
+ */
65
+ export function sendsToObserve(options) {
66
+ return !(options.enabled === false ||
67
+ hasScaffoldCredentials(options) ||
68
+ lacksHostedCredentials(options));
69
+ }
@@ -1,5 +1,6 @@
1
1
  import type { OutgoingHttpOptions } from "../outgoing/http.integration.js";
2
2
  import type { OutgoingLlmOptions } from "../outgoing/llm/llm-fetch.integration.js";
3
+ import type { OtlpExportOptions } from "../otlp/otlp-options.interface.js";
3
4
  import type { HttpCaptureOptions } from "../utils/capture-request.util.js";
4
5
  import { FactoryProvider, ModuleMetadata, Provider, Type } from "@nestjs/common";
5
6
  import { BaseRpcContext, Transport } from "@nestjs/microservices";
@@ -60,9 +61,18 @@ export interface CreateObserveModuleOptions {
60
61
  * If not provided, a default trace ID generator will be used.
61
62
  * For HTTP protocols, the request object is passed to the function.
62
63
  * For non-HTTP protocols, the request object will be contextual and may not be available.
63
- * The default implementation uses the 'x-request-id' header if available,
64
- * or mints a time-ordered UUID (version 7) if the header is not present -
65
- * an id the collector can locate in time without a scan.
64
+ * The default implementation uses the 'x-request-id' header if available
65
+ * (for a microservice message, the 'x-request-id' in its packet metadata),
66
+ * or mints a time-ordered UUID (version 7) if not - an id the collector can
67
+ * locate in time without a scan.
68
+ *
69
+ * With `openTelemetry` on, the default names a request in a W3C trace after
70
+ * that trace instead: the trace id of its `traceparent`, written as a UUID,
71
+ * or of the span an OpenTelemetry SDK in the same process opened for it.
72
+ * An 'x-request-id' that names the same trace is kept. Whatever this
73
+ * returns, the W3C trace is then still read alongside it: outbound calls
74
+ * carry it on, so the request stays in the OpenTelemetry trace its caller
75
+ * is in.
66
76
  * @default (req) => req.headers['x-request-id'] || uuidv7()
67
77
  */
68
78
  traceIdGenerator?: (req: unknown) => string;
@@ -189,6 +199,49 @@ export interface ObserveOptions {
189
199
  * @default 'https://observe-api.nestjs.com'
190
200
  */
191
201
  endpoint?: string;
202
+ /**
203
+ * Exports traces as OpenTelemetry spans, over OTLP/HTTP, to a receiver of
204
+ * your own - an OpenTelemetry Collector, Jaeger, Grafana Tempo, Honeycomb,
205
+ * or any vendor that takes OTLP - beside what is sent to Observe.
206
+ *
207
+ * Every operation becomes a SERVER span (CONSUMER for a queue job) with its
208
+ * provider method calls as INTERNAL spans and its queries and outbound
209
+ * calls as CLIENT spans, on the same trace ids the W3C `traceparent`
210
+ * headers carry - so services instrumented with OpenTelemetry land in the
211
+ * same traces, the operation's span under the caller's. What is exported
212
+ * is what is recorded, after `tracesSampleRate`, `skipSpans`,
213
+ * `spanCollapse` and redaction; a request whose caller sampled its trace
214
+ * out (`traceparent` flags 00) is not exported.
215
+ *
216
+ * Part of OpenTelemetry interop, so it takes `openTelemetry: true` too,
217
+ * which reads the `traceparent` the spans nest under. Without it, `otlp`
218
+ * stays off and says so at start-up.
219
+ *
220
+ * What the app's plan includes is the collector's to say, in its reply to
221
+ * the agent's batches: every plan exports, a paid one every trace it
222
+ * records - whatever the collector then keeps of its own copy - and Free
223
+ * what NestJS Observe keeps: past Free's daily pacing or its monthly
224
+ * allowance, an operation it keeps without spans is exported without them
225
+ * too - and nothing a few minutes into an outage, when no reply says what
226
+ * that is. Export starts with the first batch the collector accepts, and a
227
+ * collector that grants nothing - one released before export was - leaves
228
+ * it off, with a line in the log.
229
+ *
230
+ * `true` takes everything from the standard `OTEL_EXPORTER_OTLP_*`,
231
+ * `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES` variables, as an
232
+ * OpenTelemetry SDK would; an object sets any of it in code. Those
233
+ * variables never turn export on by themselves - an application that also
234
+ * runs an OpenTelemetry SDK has them set for that SDK, and would send
235
+ * every trace twice.
236
+ *
237
+ * Runs beside reporting to NestJS Observe, never instead of it, and only
238
+ * while `openTelemetry` interop is on: off with `enabled: false`, and off
239
+ * without the credentials the hosted collector needs - a proxy at
240
+ * `endpoint` that adds them on the way still counts. Traces only: metrics
241
+ * and logs are not exported.
242
+ * @default false
243
+ */
244
+ otlp?: boolean | OtlpExportOptions;
192
245
  /**
193
246
  * Unique identifier for the service.
194
247
  * If you anticipate running multiple instances of the same service,
@@ -402,11 +455,13 @@ export interface ObserveOptions {
402
455
  * sends ahead of a cross-origin call.
403
456
  *
404
457
  * Off by default. A preflight is answered by the CORS middleware before
405
- * any route matches, so it has no route to be grouped under. Whenever
406
- * middleware registered ahead of CORS (helmet, compression) records a
407
- * span for it, it is reported under its URL instead - one "route" per
408
- * distinct URL, ids included, for every call a browser client makes. An
409
- * `OPTIONS` request without that header is traced either way.
458
+ * any route matches, so it has no route to be grouped under: on, each one
459
+ * is reported under its URL - one "route" per distinct URL, ids included,
460
+ * for every call a browser client makes. That holds whether or not
461
+ * middleware registered ahead of CORS (helmet, compression) ran for it,
462
+ * and on Fastify from `@nestjs/platform-fastify` 12.1.3 none does: Nest
463
+ * answers a preflight there before its middleware. An `OPTIONS` request
464
+ * without that header is traced either way.
410
465
  * @default false
411
466
  */
412
467
  tracePreflights?: boolean;
@@ -590,6 +645,43 @@ export interface ObserveOptions {
590
645
  */
591
646
  getUserId?: (call: any) => string;
592
647
  };
648
+ /**
649
+ * Interoperates with OpenTelemetry. Off by default, and off, the agent
650
+ * reads and sends `x-request-id` alone, as it always has. To export the
651
+ * agent's spans over OTLP as well, set `otlp` beside it.
652
+ *
653
+ * On:
654
+ * - A request that arrives in a W3C trace (`traceparent`) is reported under
655
+ * that trace's id, written as a UUID, so it has the id the rest of the
656
+ * trace has in the caller's OpenTelemetry backend. An `x-request-id` is
657
+ * kept when it names the same trace, which is what another service
658
+ * running the agent sends.
659
+ * - Outbound `fetch` and `node:http` calls carry a `traceparent` beside
660
+ * `x-request-id` - see `outgoing.http.traceContext`.
661
+ * - With an OpenTelemetry SDK running in the same process - or an SDK
662
+ * built on it, as Sentry's Node SDK is from version 8 - a request is
663
+ * reported under the trace of the server span the SDK opened for it, the
664
+ * request that starts a trace included, and `traceparent` on outbound
665
+ * calls is left to the SDK.
666
+ * - A BullMQ or Bull job, and a message over the TCP or Redis transport,
667
+ * carry a W3C `traceparent` beside their trace id, and run in it for an
668
+ * OpenTelemetry SDK in the process that runs them - so its spans there,
669
+ * and the calls they make, stay in the trace that handed the work on.
670
+ *
671
+ * A `traceIdGenerator` passed to `createObserveModule()` still names the
672
+ * trace; the W3C one is carried on beside it.
673
+ *
674
+ * It works only beside reporting to NestJS Observe: it turns on with the
675
+ * first batch the collector accepts, and stays on through collector outages
676
+ * and rate limits, so traces through the services around this one stay
677
+ * whole while NestJS Observe is down. It pauses - each time with a line in
678
+ * the log - only while the collector refuses the app's credentials or the
679
+ * agent's worker is down, and resumes with the next batch the collector
680
+ * accepts. With `enabled: false`, or without credentials for the hosted
681
+ * collector, it never turns on.
682
+ * @default false
683
+ */
684
+ openTelemetry?: boolean;
593
685
  /**
594
686
  * Spans for what leaves the process: database queries (`pg`, `mysql2`, `mssql`,
595
687
  * `mongodb` - and so every ORM built on them) and outbound HTTP requests
@@ -10,9 +10,26 @@ export declare const CALLER_METADATA_KEY = "#caller";
10
10
  * snapshot.
11
11
  */
12
12
  export declare const TRACE_REGISTRY_KEY = "#registryKey";
13
+ /**
14
+ * Where a store keeps the W3C trace context its operation arrived with - see
15
+ * `readTraceContext`. Absent when none came in; outbound calls then derive
16
+ * their `traceparent` from the trace id instead.
17
+ *
18
+ * Apart from `traceIdKey` because the two can disagree: an `x-request-id`
19
+ * from a proxy names the Observe trace, while the `traceparent` beside it
20
+ * names the OpenTelemetry trace the caller is in, and both are passed on.
21
+ */
22
+ export declare const TRACE_CONTEXT_KEY = "#traceContext";
13
23
  /**
14
24
  * The job option the enqueuing side stamps the active trace id into. Both
15
25
  * BullMQ and Bull persist unknown options verbatim, so it survives the trip
16
26
  * through Redis without touching the job's data.
17
27
  */
18
28
  export declare const JOB_TRACE_OPTION_KEY = "observeTraceId";
29
+ /**
30
+ * The job option the enqueuing side stamps a W3C `traceparent` into, beside
31
+ * `JOB_TRACE_OPTION_KEY`, with `openTelemetry` on: the trace the job runs in
32
+ * for an OpenTelemetry SDK in the worker's process, and the span it nests
33
+ * under there - see `traceparentToHandOn`.
34
+ */
35
+ export declare const JOB_TRACE_CONTEXT_OPTION_KEY = "observeTraceparent";
@@ -10,9 +10,26 @@ export const CALLER_METADATA_KEY = "#caller";
10
10
  * snapshot.
11
11
  */
12
12
  export const TRACE_REGISTRY_KEY = "#registryKey";
13
+ /**
14
+ * Where a store keeps the W3C trace context its operation arrived with - see
15
+ * `readTraceContext`. Absent when none came in; outbound calls then derive
16
+ * their `traceparent` from the trace id instead.
17
+ *
18
+ * Apart from `traceIdKey` because the two can disagree: an `x-request-id`
19
+ * from a proxy names the Observe trace, while the `traceparent` beside it
20
+ * names the OpenTelemetry trace the caller is in, and both are passed on.
21
+ */
22
+ export const TRACE_CONTEXT_KEY = "#traceContext";
13
23
  /**
14
24
  * The job option the enqueuing side stamps the active trace id into. Both
15
25
  * BullMQ and Bull persist unknown options verbatim, so it survives the trip
16
26
  * through Redis without touching the job's data.
17
27
  */
18
28
  export const JOB_TRACE_OPTION_KEY = "observeTraceId";
29
+ /**
30
+ * The job option the enqueuing side stamps a W3C `traceparent` into, beside
31
+ * `JOB_TRACE_OPTION_KEY`, with `openTelemetry` on: the trace the job runs in
32
+ * for an OpenTelemetry SDK in the worker's process, and the span it nests
33
+ * under there - see `traceparentToHandOn`.
34
+ */
35
+ export const JOB_TRACE_CONTEXT_OPTION_KEY = "observeTraceparent";
@@ -21,6 +21,7 @@ import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "./observe.constants.js";
21
21
  import { GraphQLObserveAgentService } from "./protocols/graphql-observe-agent.service.js";
22
22
  import { HttpObserveAgentService } from "./protocols/http-observe-agent.service.js";
23
23
  import { OutgoingObserveAgentService } from "./outgoing/outgoing-observe-agent.service.js";
24
+ import { OtlpTraceExporter } from "./otlp/otlp-trace-exporter.service.js";
24
25
  import { installLlmFetchObserver, llmCallsOff, uninstallLlmFetchObserver, } from "./outgoing/llm/llm-fetch.integration.js";
25
26
  import { BullObserveAgentService } from "./protocols/bull-observe-agent.service.js";
26
27
  import { QueueObserveAgentService } from "./protocols/queue-observe-agent.service.js";
@@ -37,6 +38,8 @@ import { TraceSamplerService } from "./services/trace-sampler.service.js";
37
38
  import { TracerService } from "./services/tracer.service.js";
38
39
  import { assertModuleOptions } from "./utils/assert-module-options.util.js";
39
40
  import { defaultTraceIdGenerator } from "./utils/default-trace-id-generator.util.js";
41
+ import { recordTraceIdGeneratorOrigin } from "./utils/trace-id-generator-origin.util.js";
42
+ import { OpenTelemetryInteropGate, traceparentToHandOn, } from "./utils/trace-handoff.util.js";
40
43
  import { fitServiceVersion, MAX_SERVICE_VERSION_LENGTH, } from "./utils/fit-service-version.util.js";
41
44
  import { fitToLength } from "./utils/fit-to-length.util.js";
42
45
  import { inferServiceVersion } from "./utils/infer-service-version.util.js";
@@ -125,12 +128,17 @@ export function createObserveModule(options = {}) {
125
128
  options.traceIdKey ??= "traceId";
126
129
  options.attachTraceIdToLogs ??= true;
127
130
  options.traceIdGenerator ??= defaultTraceIdGenerator;
131
+ // While the options are a plain object - see the function.
132
+ recordTraceIdGeneratorOrigin(options);
128
133
  options.skipInstrumentation ??= () => false;
129
134
  // Inert until the agent starts with `outgoing.llm` on - see the function.
130
135
  // `forRoot` puts the original back if its options turn model calls off.
131
136
  installLlmFetchObserver();
132
137
  const asyncLocalStorage = new AsyncLocalStorage();
133
138
  const operationTraceRegistry = new OperationTraceRegistry(asyncLocalStorage, options.sourceContext);
139
+ // Read by the microservice dispatch hook, which a client is handed as it is
140
+ // instantiated - before the module's options resolve. Configured below.
141
+ const openTelemetryInterop = new OpenTelemetryInteropGate();
134
142
  let ObserveModule = ObserveModule_1 = class ObserveModule {
135
143
  httpAdapterHost;
136
144
  asyncLocalStorage;
@@ -229,6 +237,14 @@ export function createObserveModule(options = {}) {
229
237
  useFactory: assertModuleOptions,
230
238
  inject: [{ token: OBSERVE_OPTIONS, optional: true }],
231
239
  },
240
+ {
241
+ provide: OpenTelemetryInteropGate,
242
+ useFactory: (observeOptions, observeAgentSharedBuffer) => openTelemetryInterop.configure(observeOptions, observeAgentSharedBuffer),
243
+ inject: [
244
+ { token: OBSERVE_OPTIONS, optional: true },
245
+ ObserveAgentSharedBuffer,
246
+ ],
247
+ },
232
248
  {
233
249
  provide: AsyncLocalStorage,
234
250
  useValue: asyncLocalStorage,
@@ -277,6 +293,8 @@ export function createObserveModule(options = {}) {
277
293
  // A no-op unless @nestjs/websockets is installed.
278
294
  WsObserveAgentService,
279
295
  OutgoingObserveAgentService,
296
+ // A no-op unless `otlp` asks for export.
297
+ OtlpTraceExporter,
280
298
  ],
281
299
  exports: [AsyncLocalStorage, TracerService],
282
300
  }),
@@ -291,7 +309,11 @@ export function createObserveModule(options = {}) {
291
309
  // inspection throws before the structural checks below ever touch
292
310
  // them.
293
311
  options.skipInstrumentation(instance) ||
294
- [asyncLocalStorage, operationTraceRegistry].includes(instance) ||
312
+ [
313
+ asyncLocalStorage,
314
+ operationTraceRegistry,
315
+ openTelemetryInterop,
316
+ ].includes(instance) ||
295
317
  instance instanceof TraceSamplerService ||
296
318
  instance instanceof TracerService ||
297
319
  instance instanceof ObserveAgentSharedBuffer ||
@@ -306,6 +328,9 @@ export function createObserveModule(options = {}) {
306
328
  instance instanceof ScheduleObserveAgentService ||
307
329
  instance instanceof WsObserveAgentService ||
308
330
  instance instanceof OutgoingObserveAgentService ||
331
+ // Handed every finished operation from inside its completion: agent
332
+ // bookkeeping, like the buffer that hands them over.
333
+ instance instanceof OtlpTraceExporter ||
309
334
  // Nest's discovery machinery, which the GraphQL agent walks to map
310
335
  // root fields back to their resolver classes. It has to stay
311
336
  // unproxied: ModulesContainer extends Map, and a Map method invoked
@@ -346,7 +371,9 @@ export function createObserveModule(options = {}) {
346
371
  skipInstrumentation,
347
372
  });
348
373
  return (instance) => {
349
- propagateTraceIdThrough(instance, () => asyncLocalStorage.getStore()?.get(options.traceIdKey));
374
+ propagateTraceIdThrough(instance, () => asyncLocalStorage.getStore()?.get(options.traceIdKey), (traceId) => openTelemetryInterop.isOn()
375
+ ? traceparentToHandOn(asyncLocalStorage.getStore(), traceId)
376
+ : undefined);
350
377
  return decorate(instance);
351
378
  };
352
379
  })(),
@@ -357,13 +384,23 @@ export function createObserveModule(options = {}) {
357
384
  /**
358
385
  * Makes a microservice client send the current trace id with every packet.
359
386
  *
387
+ * TCP and Redis clients carry it from `@nestjs/microservices` 12.0.4, and
388
+ * the NATS, Kafka, RabbitMQ, MQTT 5 and gRPC clients - as a header - from
389
+ * 12.3.3 (nestjs/nest#18386). Every client has had the method since 12.0.4,
390
+ * but those others call the hook only from 12.3.3, so on the versions
391
+ * between, registering it there changes nothing.
392
+ *
360
393
  * `setOnDispatchHook` is the client-side counterpart of the server's
361
394
  * processing hooks, and only exists on `@nestjs/microservices` versions that
362
395
  * carry packet metadata - so this is a feature test, and a no-op on every
363
396
  * version before. The id goes out under the same name an HTTP hop uses, and
364
397
  * `defaultTraceIdGenerator` reads it back from the receiving context.
398
+ *
399
+ * With OpenTelemetry interop on, `traceparentFor` names a W3C `traceparent`
400
+ * to send beside it, which the receiving agent hands to an OpenTelemetry SDK
401
+ * in its process - see `traceparentToHandOn`.
365
402
  */
366
- function propagateTraceIdThrough(instance, currentTraceId) {
403
+ function propagateTraceIdThrough(instance, currentTraceId, traceparentFor) {
367
404
  const client = instance;
368
405
  try {
369
406
  if (typeof client?.setOnDispatchHook !== "function") {
@@ -377,9 +414,21 @@ function propagateTraceIdThrough(instance, currentTraceId) {
377
414
  }
378
415
  client.setOnDispatchHook((packet) => {
379
416
  const traceId = currentTraceId();
380
- if (typeof traceId === "string" && !packet.metadata?.["x-request-id"]) {
417
+ if (typeof traceId !== "string") {
418
+ return;
419
+ }
420
+ if (!packet.metadata?.["x-request-id"]) {
381
421
  packet.metadata = { ...packet.metadata, "x-request-id": traceId };
382
422
  }
423
+ // Only beside the id this operation sends: an id the application chose
424
+ // names a trace of its own, and the packet is left as it made it.
425
+ if (packet.metadata?.["x-request-id"] === traceId &&
426
+ !packet.metadata["traceparent"]) {
427
+ const traceparent = traceparentFor(traceId);
428
+ if (traceparent) {
429
+ packet.metadata = { ...packet.metadata, traceparent };
430
+ }
431
+ }
383
432
  });
384
433
  }
385
434
  /**
@@ -0,0 +1,26 @@
1
+ import type { OtlpAttribute, OtlpSpan } from "./otlp-span.mapper.js";
2
+ /** What every exported span names as the code that produced it. */
3
+ export interface OtlpScope {
4
+ name: string;
5
+ version: string;
6
+ }
7
+ /**
8
+ * One `ExportTraceServiceRequest` - a resource, this agent's scope, and the
9
+ * spans - in OTLP's JSON encoding.
10
+ *
11
+ * Not quite the standard protobuf-to-JSON mapping, as the OTLP spec says:
12
+ * trace and span ids are hex rather than base64, and enums are numbers. The
13
+ * 64-bit fields are decimal strings, as the mapping has them - a JSON number
14
+ * cannot hold a nanosecond timestamp exactly.
15
+ */
16
+ export declare function encodeOtlpJson(resource: OtlpAttribute[], scope: OtlpScope, spans: OtlpSpan[]): string;
17
+ /**
18
+ * One `ExportTraceServiceRequest` in OTLP's protobuf encoding, field numbers
19
+ * as `opentelemetry/proto/collector/trace/v1/trace_service.proto` and the
20
+ * messages it uses define them.
21
+ *
22
+ * Fields holding their default value are left out, as a protobuf encoder
23
+ * leaves them out - except inside `AnyValue`, a `oneof`, where a zero, a
24
+ * `false` or an empty string is the value and has to be written.
25
+ */
26
+ export declare function encodeOtlpProtobuf(resource: OtlpAttribute[], scope: OtlpScope, spans: OtlpSpan[]): Buffer;