@nestjs/observe 0.3.22 → 0.3.24

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 (49) hide show
  1. package/README.md +79 -16
  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 +71 -23
  9. package/dist/agent/observe-agent.shared-buffer.js +126 -38
  10. package/dist/agent/observe-agent.worker.d.ts +19 -23
  11. package/dist/agent/observe-agent.worker.js +79 -78
  12. package/dist/agent/observe-reporting.util.d.ts +35 -0
  13. package/dist/agent/observe-reporting.util.js +69 -0
  14. package/dist/instrument/create-instance-decorator.instrument.js +34 -2
  15. package/dist/interfaces/observe-options.interface.d.ts +71 -13
  16. package/dist/observe.constants.d.ts +7 -0
  17. package/dist/observe.constants.js +7 -0
  18. package/dist/observe.module.js +50 -4
  19. package/dist/otlp/otlp-encoders.d.ts +26 -0
  20. package/dist/otlp/otlp-encoders.js +296 -0
  21. package/dist/otlp/otlp-export-grant.d.ts +34 -0
  22. package/dist/otlp/otlp-export-grant.js +22 -0
  23. package/dist/otlp/otlp-options.interface.d.ts +59 -0
  24. package/dist/otlp/otlp-options.interface.js +1 -0
  25. package/dist/otlp/otlp-settings.util.d.ts +38 -0
  26. package/dist/otlp/otlp-settings.util.js +154 -0
  27. package/dist/otlp/otlp-span.mapper.d.ts +73 -0
  28. package/dist/otlp/otlp-span.mapper.js +345 -0
  29. package/dist/otlp/otlp-trace-exporter.service.d.ts +130 -0
  30. package/dist/otlp/otlp-trace-exporter.service.js +497 -0
  31. package/dist/outgoing/http.integration.d.ts +5 -4
  32. package/dist/outgoing/http.integration.js +3 -3
  33. package/dist/outgoing/outgoing-observe-agent.service.d.ts +2 -2
  34. package/dist/outgoing/outgoing-observe-agent.service.js +3 -3
  35. package/dist/outgoing/sql-statement.util.js +2 -2
  36. package/dist/protocols/http-observe-agent.service.d.ts +1 -8
  37. package/dist/protocols/http-observe-agent.service.js +29 -22
  38. package/dist/protocols/job-trace-runner.d.ts +11 -0
  39. package/dist/protocols/job-trace-runner.js +42 -8
  40. package/dist/protocols/rpc-observe-agent.service.d.ts +5 -0
  41. package/dist/protocols/rpc-observe-agent.service.js +43 -3
  42. package/dist/services/operation-trace.registry.d.ts +29 -1
  43. package/dist/services/operation-trace.registry.js +46 -5
  44. package/dist/utils/default-trace-id-generator.util.js +6 -2
  45. package/dist/utils/opentelemetry.util.d.ts +26 -0
  46. package/dist/utils/opentelemetry.util.js +48 -0
  47. package/dist/utils/trace-handoff.util.d.ts +51 -0
  48. package/dist/utils/trace-handoff.util.js +98 -0
  49. package/package.json +14 -12
@@ -0,0 +1,35 @@
1
+ import type { ObserveOptions } from "../interfaces/observe-options.interface.js";
2
+ /** The options that decide whether, and where, the agent reports. */
3
+ type ReportingOptions = Pick<ObserveOptions, "enabled" | "appKey" | "appSecret" | "endpoint">;
4
+ /** The collector the agent posts to: `endpoint`, else the default. */
5
+ export declare function collectorEndpointOf(options: ReportingOptions): string;
6
+ export declare function hasScaffoldCredentials(options: ReportingOptions): boolean;
7
+ /**
8
+ * Whether `endpoint` - set, from `OBSERVE_ENDPOINT`, or the default - is the
9
+ * hosted collector. Compared by host, so a trailing slash or a capital
10
+ * letter cannot pass it off as a collector of the user's own.
11
+ */
12
+ export declare function isHostedCollector(endpoint: string): boolean;
13
+ /**
14
+ * Whether credentials are missing and the collector is the hosted one,
15
+ * which answers every batch without them with a 401.
16
+ *
17
+ * The worker leaves both headers off when either half is unset, which a
18
+ * collector in placeholder mode accepts, so a collector of the user's own
19
+ * still gets those batches. The hosted collector refuses them for as long
20
+ * as the process runs: on 2026-10-15 that was 42% of the 1.87M batches it
21
+ * refused, from processes deployed without their environment variables,
22
+ * some of them posting every five seconds for weeks.
23
+ */
24
+ export declare function lacksHostedCredentials(options: ReportingOptions): boolean;
25
+ /**
26
+ * Whether the agent sends NestJS Observe anything: not with `enabled:
27
+ * false`, not with `nest new`'s placeholders, and not without both
28
+ * credentials when `endpoint` is the hosted collector. Another `endpoint` - a
29
+ * proxy that adds them on the way - is sent to either way.
30
+ *
31
+ * The worker starts only when this holds. So does OTLP export, which runs
32
+ * beside reporting to Observe, never instead of it.
33
+ */
34
+ export declare function sendsToObserve(options: ReportingOptions): boolean;
35
+ export {};
@@ -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
+ }
@@ -572,11 +572,43 @@ function declaresPrivateMembers(ctor) {
572
572
  /**
573
573
  * The class name that labels an instance's spans. A null-prototype object or
574
574
  * an ES module namespace has no `constructor`, and some objects hold a
575
- * non-function there. Both fall back to `Object`.
575
+ * non-function there. Both fall back to `Object`. An `ioredis` client is
576
+ * named for what it is - see `ioredisClassNameOf`.
576
577
  */
577
578
  function classNameOf(instance) {
578
579
  const ctor = Reflect.get(instance, "constructor");
579
- return typeof ctor === "function" ? ctor.name : FALLBACK_CLASS_NAME;
580
+ if (typeof ctor !== "function") {
581
+ return FALLBACK_CLASS_NAME;
582
+ }
583
+ return ((ctor.name === "EventEmitter" && ioredisClassNameOf(instance)) || ctor.name);
584
+ }
585
+ /**
586
+ * `Redis` or `Cluster` for an `ioredis` client, null for anything else.
587
+ *
588
+ * Both classes take `EventEmitter`'s methods by copying the own properties of
589
+ * its prototype onto theirs, `constructor` included, so a client's
590
+ * `constructor` is `EventEmitter` and every command would be labelled
591
+ * `EventEmitter.get`. Both extend ioredis's `Commander`, whose prototype keeps
592
+ * its own `constructor`, and a client has `sendCommand`.
593
+ *
594
+ * Matched by name and shape only, as `isMongoDriverHandle` is: ioredis is an
595
+ * application's dependency, never imported here, and an application may carry
596
+ * more than one copy of it - BullMQ and Bull bring their own.
597
+ */
598
+ function ioredisClassNameOf(instance) {
599
+ try {
600
+ const candidate = instance;
601
+ const base = Object.getPrototypeOf(Object.getPrototypeOf(instance));
602
+ if (base?.constructor?.name !== "Commander" ||
603
+ typeof candidate.sendCommand !== "function") {
604
+ return null;
605
+ }
606
+ return candidate.isCluster === true ? "Cluster" : "Redis";
607
+ }
608
+ catch {
609
+ // A prototype or a property that cannot be read names nothing.
610
+ return null;
611
+ }
580
612
  }
581
613
  function generateSpanId(instance, methodKey) {
582
614
  return `${classNameOf(instance)}#${methodKey}`;
@@ -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,7 +61,8 @@ 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
+ * The default implementation uses the 'x-request-id' header if available
65
+ * (for a microservice message, the 'x-request-id' in its packet metadata),
64
66
  * or mints a time-ordered UUID (version 7) if not - an id the collector can
65
67
  * locate in time without a scan.
66
68
  *
@@ -197,6 +199,49 @@ export interface ObserveOptions {
197
199
  * @default 'https://observe-api.nestjs.com'
198
200
  */
199
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;
200
245
  /**
201
246
  * Unique identifier for the service.
202
247
  * If you anticipate running multiple instances of the same service,
@@ -410,11 +455,13 @@ export interface ObserveOptions {
410
455
  * sends ahead of a cross-origin call.
411
456
  *
412
457
  * Off by default. A preflight is answered by the CORS middleware before
413
- * any route matches, so it has no route to be grouped under. Whenever
414
- * middleware registered ahead of CORS (helmet, compression) records a
415
- * span for it, it is reported under its URL instead - one "route" per
416
- * distinct URL, ids included, for every call a browser client makes. An
417
- * `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.
418
465
  * @default false
419
466
  */
420
467
  tracePreflights?: boolean;
@@ -600,7 +647,8 @@ export interface ObserveOptions {
600
647
  };
601
648
  /**
602
649
  * Interoperates with OpenTelemetry. Off by default, and off, the agent
603
- * reads and sends `x-request-id` alone, as it always has.
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.
604
652
  *
605
653
  * On:
606
654
  * - A request that arrives in a W3C trace (`traceparent`) is reported under
@@ -615,16 +663,26 @@ export interface ObserveOptions {
615
663
  * reported under the trace of the server span the SDK opened for it, the
616
664
  * request that starts a trace included, and `traceparent` on outbound
617
665
  * calls is left to the SDK.
666
+ * - A BullMQ or Bull job, and a message over a built-in transport - TCP and
667
+ * Redis on `@nestjs/microservices` 12.0.4 and later, NATS, Kafka,
668
+ * RabbitMQ, MQTT 5 and gRPC on 12.3.3 and later - carry a W3C
669
+ * `traceparent` beside their trace id, for whatever runs them to
670
+ * continue: an OpenTelemetry SDK in the Nest process that runs one does,
671
+ * in the span an instrumentation such as `bullmq-otel` opens for the
672
+ * work, else in the trace handed on - so its spans there, and the calls
673
+ * they make, stay in the trace that handed the work on.
618
674
  *
619
675
  * A `traceIdGenerator` passed to `createObserveModule()` still names the
620
676
  * trace; the W3C one is carried on beside it.
621
677
  *
622
- * It works only beside reporting to NestJS Observe: from the first batch
623
- * the collector accepts, and paused - each time with a line in the log -
624
- * while the collector refuses the app's credentials, once batches have
625
- * failed to get in for a minute, or while the agent's worker is down. It
626
- * resumes with the next batch the collector accepts. With `enabled: false`,
627
- * or without credentials for the hosted collector, it never turns on.
678
+ * It works only beside reporting to NestJS Observe. It is on from
679
+ * start-up, and stays on through collector outages and rate limits, so
680
+ * traces through the services around this one stay whole from an
681
+ * instance's first request, and while NestJS Observe is down. It pauses -
682
+ * each time with a line in the log - only while the collector refuses the
683
+ * app's credentials or the agent's worker is down, and resumes with the
684
+ * next batch the collector accepts. With `enabled: false`, or without
685
+ * credentials for the hosted collector, it never turns on.
628
686
  * @default false
629
687
  */
630
688
  openTelemetry?: boolean;
@@ -26,3 +26,10 @@ export declare const TRACE_CONTEXT_KEY = "#traceContext";
26
26
  * through Redis without touching the job's data.
27
27
  */
28
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";
@@ -26,3 +26,10 @@ export const TRACE_CONTEXT_KEY = "#traceContext";
26
26
  * through Redis without touching the job's data.
27
27
  */
28
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";
@@ -38,6 +39,7 @@ 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";
40
41
  import { recordTraceIdGeneratorOrigin } from "./utils/trace-id-generator-origin.util.js";
42
+ import { OpenTelemetryInteropGate, traceparentToHandOn, } from "./utils/trace-handoff.util.js";
41
43
  import { fitServiceVersion, MAX_SERVICE_VERSION_LENGTH, } from "./utils/fit-service-version.util.js";
42
44
  import { fitToLength } from "./utils/fit-to-length.util.js";
43
45
  import { inferServiceVersion } from "./utils/infer-service-version.util.js";
@@ -134,6 +136,9 @@ export function createObserveModule(options = {}) {
134
136
  installLlmFetchObserver();
135
137
  const asyncLocalStorage = new AsyncLocalStorage();
136
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();
137
142
  let ObserveModule = ObserveModule_1 = class ObserveModule {
138
143
  httpAdapterHost;
139
144
  asyncLocalStorage;
@@ -232,6 +237,14 @@ export function createObserveModule(options = {}) {
232
237
  useFactory: assertModuleOptions,
233
238
  inject: [{ token: OBSERVE_OPTIONS, optional: true }],
234
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
+ },
235
248
  {
236
249
  provide: AsyncLocalStorage,
237
250
  useValue: asyncLocalStorage,
@@ -280,6 +293,8 @@ export function createObserveModule(options = {}) {
280
293
  // A no-op unless @nestjs/websockets is installed.
281
294
  WsObserveAgentService,
282
295
  OutgoingObserveAgentService,
296
+ // A no-op unless `otlp` asks for export.
297
+ OtlpTraceExporter,
283
298
  ],
284
299
  exports: [AsyncLocalStorage, TracerService],
285
300
  }),
@@ -294,7 +309,11 @@ export function createObserveModule(options = {}) {
294
309
  // inspection throws before the structural checks below ever touch
295
310
  // them.
296
311
  options.skipInstrumentation(instance) ||
297
- [asyncLocalStorage, operationTraceRegistry].includes(instance) ||
312
+ [
313
+ asyncLocalStorage,
314
+ operationTraceRegistry,
315
+ openTelemetryInterop,
316
+ ].includes(instance) ||
298
317
  instance instanceof TraceSamplerService ||
299
318
  instance instanceof TracerService ||
300
319
  instance instanceof ObserveAgentSharedBuffer ||
@@ -309,6 +328,9 @@ export function createObserveModule(options = {}) {
309
328
  instance instanceof ScheduleObserveAgentService ||
310
329
  instance instanceof WsObserveAgentService ||
311
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 ||
312
334
  // Nest's discovery machinery, which the GraphQL agent walks to map
313
335
  // root fields back to their resolver classes. It has to stay
314
336
  // unproxied: ModulesContainer extends Map, and a Map method invoked
@@ -349,7 +371,9 @@ export function createObserveModule(options = {}) {
349
371
  skipInstrumentation,
350
372
  });
351
373
  return (instance) => {
352
- 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);
353
377
  return decorate(instance);
354
378
  };
355
379
  })(),
@@ -360,13 +384,23 @@ export function createObserveModule(options = {}) {
360
384
  /**
361
385
  * Makes a microservice client send the current trace id with every packet.
362
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
+ *
363
393
  * `setOnDispatchHook` is the client-side counterpart of the server's
364
394
  * processing hooks, and only exists on `@nestjs/microservices` versions that
365
395
  * carry packet metadata - so this is a feature test, and a no-op on every
366
396
  * version before. The id goes out under the same name an HTTP hop uses, and
367
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`.
368
402
  */
369
- function propagateTraceIdThrough(instance, currentTraceId) {
403
+ function propagateTraceIdThrough(instance, currentTraceId, traceparentFor) {
370
404
  const client = instance;
371
405
  try {
372
406
  if (typeof client?.setOnDispatchHook !== "function") {
@@ -380,9 +414,21 @@ function propagateTraceIdThrough(instance, currentTraceId) {
380
414
  }
381
415
  client.setOnDispatchHook((packet) => {
382
416
  const traceId = currentTraceId();
383
- if (typeof traceId === "string" && !packet.metadata?.["x-request-id"]) {
417
+ if (typeof traceId !== "string") {
418
+ return;
419
+ }
420
+ if (!packet.metadata?.["x-request-id"]) {
384
421
  packet.metadata = { ...packet.metadata, "x-request-id": traceId };
385
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
+ }
386
432
  });
387
433
  }
388
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;