@nestjs/observe 0.3.23 → 0.3.25

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 (29) hide show
  1. package/README.md +32 -18
  2. package/dist/agent/degraded-ingest.protocol.d.ts +1 -1
  3. package/dist/agent/degraded-ingest.protocol.js +1 -1
  4. package/dist/agent/observe-agent.shared-buffer.d.ts +31 -9
  5. package/dist/agent/observe-agent.shared-buffer.js +41 -13
  6. package/dist/agent/observe-agent.worker.d.ts +3 -2
  7. package/dist/agent/observe-agent.worker.js +15 -7
  8. package/dist/custom-metrics/gauge.js +2 -4
  9. package/dist/instrument/create-instance-decorator.instrument.js +120 -3
  10. package/dist/interfaces/observe-options.interface.d.ts +16 -12
  11. package/dist/otlp/otlp-span.mapper.d.ts +4 -3
  12. package/dist/otlp/otlp-span.mapper.js +9 -5
  13. package/dist/otlp/otlp-trace-exporter.service.d.ts +3 -0
  14. package/dist/otlp/otlp-trace-exporter.service.js +8 -1
  15. package/dist/outgoing/http.integration.d.ts +3 -4
  16. package/dist/outgoing/http.integration.js +1 -1
  17. package/dist/outgoing/outgoing-observe-agent.service.js +2 -2
  18. package/dist/protocols/http-observe-agent.service.js +2 -2
  19. package/dist/protocols/job-trace-runner.d.ts +1 -1
  20. package/dist/protocols/job-trace-runner.js +12 -4
  21. package/dist/protocols/rpc-observe-agent.service.d.ts +1 -1
  22. package/dist/protocols/rpc-observe-agent.service.js +41 -5
  23. package/dist/services/tracer.service.js +8 -2
  24. package/dist/utils/source-context.util.js +9 -4
  25. package/dist/utils/trace-context.util.d.ts +20 -0
  26. package/dist/utils/trace-context.util.js +29 -0
  27. package/dist/utils/trace-handoff.util.d.ts +8 -2
  28. package/dist/utils/trace-handoff.util.js +11 -3
  29. package/package.json +5 -1
package/README.md CHANGED
@@ -62,23 +62,29 @@ the SDK gave it - also when the request started the trace - and leaves
62
62
  `traceparent` to the SDK on calls out of the service, so a request has one
63
63
  trace id in both tools and every call carries one `traceparent`. The SDK keeps
64
64
  its own spans, the agent adds the class-level ones. Queue jobs and microservice
65
- messages stay in the request's trace in both tools too: a BullMQ (Pro included)
66
- or Bull job, or a message over the TCP or Redis transport (`@nestjs/microservices`
67
- 12.0.4 and later), carries W3C trace context beside its trace id, and the agent
68
- that runs it hands that context to the SDK there, which has no instrumentation
69
- of its own for either hop. This is tested against the SDK with its
65
+ messages stay in the request's trace in both tools too. A BullMQ (Pro included)
66
+ or Bull job, and a message over a built-in transport - TCP and Redis on
67
+ `@nestjs/microservices` 12.0.4 and later, NATS, Kafka, RabbitMQ, MQTT 5 and
68
+ gRPC on 12.3.3 and later - carries W3C trace context beside its trace id: as
69
+ call metadata over gRPC, as a header or user property over the others, so a
70
+ consumer in another language instrumented with OpenTelemetry continues the
71
+ trace. In a Nest service, the agent that runs the job or handles the message
72
+ hands that context to the SDK there, which has no instrumentation for BullMQ or
73
+ for Nest's TCP and Redis transports. Where an instrumentation does carry it -
74
+ BullMQ's own `bullmq-otel` add-on, the SDK's gRPC instrumentation - the work's
75
+ spans nest under the span it opens. This is tested against the SDK with its
70
76
  auto-instrumentations, on Express and Fastify, over `fetch`, `node:http`, `pg`,
71
- BullMQ, TCP microservices and Nest's own instrumentation. Without the option,
72
- the agent speaks `x-request-id` alone and leaves any OpenTelemetry SDK in the
73
- process alone.
74
-
75
- It works only beside reporting to NestJS Observe. It turns on with the first
76
- batch the collector accepts, and stays on through collector outages and rate
77
- limits, so traces through the services around yours stay whole while NestJS
78
- Observe is down. It pauses - saying so in the log - only while the collector
79
- refuses the app's credentials or the agent's worker is down, resuming with the
80
- next batch the collector accepts. With `enabled: false`, or without credentials
81
- for the hosted collector, it never turns on.
77
+ BullMQ with and without `bullmq-otel`, TCP and gRPC microservices and Nest's
78
+ own instrumentation. Without the option, the agent speaks `x-request-id` alone
79
+ and leaves any OpenTelemetry SDK in the process alone.
80
+
81
+ It works only beside reporting to NestJS Observe. It is on from start-up, so a
82
+ new instance's first requests stay in the traces around it, and stays on
83
+ through collector outages and rate limits, so those traces stay whole while
84
+ NestJS Observe is down. It pauses - saying so in the log - only while the
85
+ collector refuses the app's credentials or the agent's worker is down, resuming
86
+ with the next batch the collector accepts. With `enabled: false`, or without
87
+ credentials for the hosted collector, it never turns on.
82
88
 
83
89
  ```typescript
84
90
  ObserveModule.forRoot({
@@ -415,7 +421,7 @@ Once the module and the instrument are in place, the agent reports, with no furt
415
421
  - **Requests, GraphQL operations, RPC messages, WebSocket gateway messages, queue jobs and scheduled jobs**, each with its tree of provider method calls.
416
422
  - **Database queries**, as a span under the method that ran them, for `pg`, `mysql2`, `mssql` and `mongodb`. Anything built on those drivers is covered without being known by name: TypeORM, Drizzle, MikroORM and Mongoose are tested in this repository, and others (Knex, Sequelize) go through the same driver calls. SQL Server is the exception: `mssql` is what TypeORM and Prisma's SQL Server adapter run on, but Knex, Sequelize and MikroORM talk to SQL Server through `tedious` directly, which is not covered yet (nor is `mssql/msnodesqlv8`). The statement is recorded with every value removed (`SELECT "o"."id" FROM "orders" "o" WHERE "o"."customer_id" = $1`). Prisma's Rust query engine does not go through these drivers and is not covered yet.
417
423
  - **Outbound HTTP calls** made with `fetch`/`undici` or `node:http`/`https` (so Axios too), as `POST api.stripe.com`. The current trace id is forwarded as `x-request-id` - by `fetch` on every supported Node version, by `node:http`/`https` from Node 22.12, the first to let a request's headers still be set at that point - so a service that also runs the agent continues the same trace; a header you set yourself is never overwritten. With `openTelemetry: true`, a W3C `traceparent` goes with it, naming the trace and the call's span, so a service instrumented with OpenTelemetry - in Go, Python, Java or anything else - continues it too, as does a service running the agent behind it. When an OpenTelemetry SDK that propagates W3C Trace Context runs in the same process, `traceparent` is left to it: its instrumentations write the header on the calls they cover, and a request takes only one. `outgoing: { http: { traceContext: false } }` sends `x-request-id` alone even then, and `propagateTraceId: (url) => boolean` keeps both headers away from the URLs you name.
418
- - **Trace context from OpenTelemetry**, with `openTelemetry: true`: a request arriving with a W3C `traceparent` - from a service instrumented with OpenTelemetry, a mesh, or a load balancer that starts traces - is reported under that trace id, written as a UUID (`4bf92f35-77b3-4da6-a3ce-929d0e0e4736`), so the same id finds it in both tools. With an OpenTelemetry SDK in the same process - or another tracer registered with the OpenTelemetry API, as dd-trace is once its `TracerProvider` is registered - the trace is the one the SDK's server span is in, so a request that starts a trace gets the SDK's id too. That holds when a mesh or router stamped an `x-request-id` of its own on the request too, as Envoy and Heroku's router do: an `x-request-id` is kept only when it names the same trace, which is what another service running the agent sends, so custom ids still carry from one such service to the next. BullMQ (Pro included) and Bull jobs, and messages over the TCP and Redis transports (`@nestjs/microservices` 12.0.4 and later), carry W3C trace context beside the trace id, so an OpenTelemetry SDK in the process that runs the job or handles the message continues the request's trace; gRPC and the other transports carry the trace id as before. Without the option, a request is named by its `x-request-id`, else by a UUIDv7 of its own, and no `traceparent` is read or sent.
424
+ - **Trace context from OpenTelemetry**, with `openTelemetry: true`: a request arriving with a W3C `traceparent` - from a service instrumented with OpenTelemetry, a mesh, or a load balancer that starts traces - is reported under that trace id, written as a UUID (`4bf92f35-77b3-4da6-a3ce-929d0e0e4736`), so the same id finds it in both tools. With an OpenTelemetry SDK in the same process - or another tracer registered with the OpenTelemetry API, as dd-trace is once its `TracerProvider` is registered - the trace is the one the SDK's server span is in, so a request that starts a trace gets the SDK's id too. That holds when a mesh or router stamped an `x-request-id` of its own on the request too, as Envoy and Heroku's router do: an `x-request-id` is kept only when it names the same trace, which is what another service running the agent sends, so custom ids still carry from one such service to the next. BullMQ (Pro included) and Bull jobs, and messages over the built-in transports (TCP and Redis on `@nestjs/microservices` 12.0.4 and later; NATS, Kafka, RabbitMQ, MQTT 5 and gRPC on 12.3.3 and later), carry W3C trace context beside the trace id, so whatever runs the job or handles the message continues the request's trace in OpenTelemetry too - an SDK in a Nest service, or a consumer in another language. Without the option, a request is named by its `x-request-id`, else by a UUIDv7 of its own, and no `traceparent` is read or sent.
419
425
  - **Model calls**: a `fetch` to OpenAI, Azure OpenAI, Anthropic, Gemini or Vertex, Bedrock, Mistral, Groq, OpenRouter, Together, DeepSeek, xAI, Cohere or Perplexity also reports the model and the input, output and cached tokens its response states - read as the response passes through to your code, streams included, so it arrives exactly as it would have and a stream you cancel is cancelled at the provider too. That covers the official SDKs, the Vercel AI SDK and LangChain, which all use `fetch`; calls made through `node:http` (axios, the AWS SDK) keep their plain span. Prompts and completions are never reported. A gateway in front of the providers is added with `outgoing: { llm: { hosts: ['llm-gateway.internal:4000'] } }`, and `outgoing: { llm: false }` turns this off and leaves the global `fetch` as it was.
420
426
  - **Trace ids across queues**: a BullMQ (Pro included) or Bull job enqueued while handling a request carries that request's trace id, so the request and its job show up as one trace. Repeatable (cron) jobs start their own.
421
427
  - **The code around an error's throw site**: for each in-app frame of a captured error, a few lines of source either side, read from the running process, so the dashboard shows the failing code next to the stack. This sends fragments of your application's source to Observe, stored with the error. Frames in `node_modules` and Node internals are never read. `createObserveModule({ sourceContext: false })` turns it off; the [documentation](https://www.observe.nestjs.com/documentation/sdk#error-source-context) covers tuning it instead.
@@ -563,7 +569,7 @@ What a backend receives, for each operation:
563
569
 
564
570
  - **A SERVER span** for every request, GraphQL operation, RPC message and gateway message, named like the dashboard names it (`GET /orders/:id`), with the HTTP semantic conventions - `http.request.method`, `http.route`, `http.response.status_code`, `url.path` - plus `enduser.id`, your `tags`, and the headers `http.capture` recorded. A queue job is a CONSUMER span, a scheduled run an INTERNAL one.
565
571
  - **INTERNAL spans** for the provider methods and manual spans under it, named `OrdersService.findOne`, and **CLIENT spans** for queries and outbound HTTP calls, named for what they did (`SELECT orders`, `GET api.stripe.com`).
566
- - **The same trace ids `traceparent` carries.** A request that arrived with a `traceparent` goes under the caller's span, and a call this service makes names its CLIENT span as the parent the callee sees - so services instrumented with OpenTelemetry, and other services running the agent, assemble into one trace in the backend.
572
+ - **The same trace ids `traceparent` carries.** A request that arrived with a `traceparent` goes under the caller's span, a queue job or microservice message under the span that handed it on, and a call this service makes names its CLIENT span as the parent the callee sees - so services instrumented with OpenTelemetry, and other services running the agent, assemble into one trace in the backend.
567
573
  - **Errors** as span status and an `exception` event, with the class, message and stack the dashboard shows - redacted the same way.
568
574
 
569
575
  What is exported is what is recorded: after `tracesSampleRate`, `skipSpans` and `spanCollapse`, and on Free after what NestJS Observe holds back. A request whose caller sampled its trace out (`traceparent` flags `00`) is not exported, as an OpenTelemetry SDK sampling by its parent would leave it out. Spans wait in a queue of at most 10,000 while an export is retried (429, 502, 503 and 504, honouring `Retry-After`); past that, whole operations are dropped and counted. Exports run on the application's thread, outside its traces, and whatever is queued is exported when the application closes, within `shutdownFlushTimeout`. Traces only, for now: runtime metrics, custom metrics and logs are not exported.
@@ -653,6 +659,14 @@ $ docker run -d -p 4318:4318 -p 16686:16686 jaegertracing/jaeger:2.22.0
653
659
 
654
660
  To point them elsewhere, set `REDIS_HOST`/`REDIS_PORT`, `PGHOST`/`PGPORT`/`PGUSER`/`PGPASSWORD`/`PGDATABASE`, `MYSQL_HOST`/`MYSQL_PORT`/`MYSQL_USER`/`MYSQL_PASSWORD`/`MYSQL_DATABASE`, `MONGO_HOST`/`MONGO_PORT`, or `JAEGER_OTLP_ENDPOINT`/`JAEGER_QUERY_URL` for the suite that exports traces into Jaeger.
655
661
 
662
+ The suites run on the Nest the devDependencies pin. CI also runs them on Nest 12.0.1 and 11.2.8; to do the same locally, swap the dev tree first. The script rewrites `package.json` and the lockfile, so restore both afterwards:
663
+
664
+ ```bash
665
+ $ node scripts/use-nest.cjs 11.2.8
666
+ $ npm test && npm run test:int
667
+ $ git checkout -- package.json package-lock.json && npm ci --legacy-peer-deps
668
+ ```
669
+
656
670
  ## Module format
657
671
 
658
672
  The package ships as ESM only. CommonJS consumers can still `require()` it
@@ -112,7 +112,7 @@ export declare function parsePausedMessage(msg: string): number | null;
112
112
  * says so with its degraded verdict instead.
113
113
  *
114
114
  * Read for OpenTelemetry interop, which a refusal pauses and any other failure
115
- * leaves as it is - see `ObserveAgentSharedBuffer.isIngesting`.
115
+ * leaves as it is - see `ObserveAgentSharedBuffer.isReporting`.
116
116
  */
117
117
  export declare const NOT_INGESTED_MESSAGE_PREFIX = "observe:not-ingested=";
118
118
  export type NotIngestedReason = "refused" | "failed";
@@ -94,7 +94,7 @@ export function parsePausedMessage(msg) {
94
94
  * says so with its degraded verdict instead.
95
95
  *
96
96
  * Read for OpenTelemetry interop, which a refusal pauses and any other failure
97
- * leaves as it is - see `ObserveAgentSharedBuffer.isIngesting`.
97
+ * leaves as it is - see `ObserveAgentSharedBuffer.isReporting`.
98
98
  */
99
99
  export const NOT_INGESTED_MESSAGE_PREFIX = "observe:not-ingested=";
100
100
  /** Why a batch did not get in, or null if this is not that line. */
@@ -88,11 +88,14 @@ export declare class ObserveAgentSharedBuffer {
88
88
  */
89
89
  private errorsOnly;
90
90
  /**
91
- * Whether this app reports to NestJS Observe - see `isIngesting`. False
92
- * until the collector accepts a first batch: what has not been shown to
93
- * reach NestJS Observe does not count as reaching it.
91
+ * How far this app's reporting to NestJS Observe has got - see
92
+ * `isReporting` and `isIngesting`. `off` until the worker starts with the
93
+ * application, `started` from then until the collector accepts a batch,
94
+ * and `ingesting` from that batch on. Refused credentials and a stopped
95
+ * worker set it back to `off`, and only an accepted batch moves it on
96
+ * from there.
94
97
  */
95
- private ingesting;
98
+ private reporting;
96
99
  /**
97
100
  * Requests and jobs that errors-only ingest withheld from the batch being
98
101
  * built, cleared with it.
@@ -125,9 +128,16 @@ export declare class ObserveAgentSharedBuffer {
125
128
  /** Whether only server errors are being sent, until the same window lapses. */
126
129
  isErrorsOnly(): boolean;
127
130
  /**
128
- * Whether this app reports to NestJS Observe: from the first batch the
129
- * collector accepts, until the collector refuses the app's credentials or
130
- * the worker stops - and again from the next batch it accepts.
131
+ * Whether this app reports to NestJS Observe, as far as the agent can tell:
132
+ * from start-up, once its worker is running, until the collector refuses
133
+ * the app's credentials or the worker stops - and again from the next batch
134
+ * the collector accepts.
135
+ *
136
+ * Nothing has to get in first. A service's first requests are when a new
137
+ * instance joins the traces around it, and an agent set up to report -
138
+ * enabled, with credentials - almost always does. Credentials the collector
139
+ * refuses are learned from the first batch the worker sends, a flush
140
+ * interval into the app's traffic; until then they count as reporting.
131
141
  *
132
142
  * A batch that fails to get in for any other reason - a collector that is
133
143
  * down or slow to answer, a 5xx, a 429 pause, however long - leaves it as
@@ -139,10 +149,22 @@ export declare class ObserveAgentSharedBuffer {
139
149
  * OpenTelemetry interop runs on it (see `openTelemetry`): the agent reads
140
150
  * and sends `traceparent`, and follows an OpenTelemetry SDK in the process,
141
151
  * only beside reporting to NestJS Observe. So an agent that sends Observe
142
- * nothing - `enabled: false`, no credentials, credentials the collector
143
- * refuses - never turns it on.
152
+ * nothing - `enabled: false`, no credentials - never turns it on.
153
+ */
154
+ isReporting(): boolean;
155
+ /**
156
+ * Whether the collector takes this app's telemetry: from the first batch
157
+ * it accepts, until it refuses the app's credentials or the worker stops -
158
+ * and again from the next batch it accepts. What its replies grant, an
159
+ * OTLP export say, holds only while it does.
144
160
  */
145
161
  isIngesting(): boolean;
162
+ /**
163
+ * The worker started with the application, set up to report: see
164
+ * `isReporting`. A worker restarted after a stop is not this - it has to
165
+ * get a batch in first - and a batch already taken stays taken.
166
+ */
167
+ recordStarted(): void;
146
168
  /** The collector accepted a batch, whatever it then kept of it. */
147
169
  recordAccepted(): void;
148
170
  /** The collector refused the app's credentials. */
@@ -245,11 +245,14 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
245
245
  */
246
246
  errorsOnly = false;
247
247
  /**
248
- * Whether this app reports to NestJS Observe - see `isIngesting`. False
249
- * until the collector accepts a first batch: what has not been shown to
250
- * reach NestJS Observe does not count as reaching it.
248
+ * How far this app's reporting to NestJS Observe has got - see
249
+ * `isReporting` and `isIngesting`. `off` until the worker starts with the
250
+ * application, `started` from then until the collector accepts a batch,
251
+ * and `ingesting` from that batch on. Refused credentials and a stopped
252
+ * worker set it back to `off`, and only an accepted batch moves it on
253
+ * from there.
251
254
  */
252
- ingesting = false;
255
+ reporting = "off";
253
256
  /**
254
257
  * Requests and jobs that errors-only ingest withheld from the batch being
255
258
  * built, cleared with it.
@@ -289,9 +292,16 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
289
292
  return this.errorsOnly && this.isDegraded();
290
293
  }
291
294
  /**
292
- * Whether this app reports to NestJS Observe: from the first batch the
293
- * collector accepts, until the collector refuses the app's credentials or
294
- * the worker stops - and again from the next batch it accepts.
295
+ * Whether this app reports to NestJS Observe, as far as the agent can tell:
296
+ * from start-up, once its worker is running, until the collector refuses
297
+ * the app's credentials or the worker stops - and again from the next batch
298
+ * the collector accepts.
299
+ *
300
+ * Nothing has to get in first. A service's first requests are when a new
301
+ * instance joins the traces around it, and an agent set up to report -
302
+ * enabled, with credentials - almost always does. Credentials the collector
303
+ * refuses are learned from the first batch the worker sends, a flush
304
+ * interval into the app's traffic; until then they count as reporting.
295
305
  *
296
306
  * A batch that fails to get in for any other reason - a collector that is
297
307
  * down or slow to answer, a 5xx, a 429 pause, however long - leaves it as
@@ -303,23 +313,41 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
303
313
  * OpenTelemetry interop runs on it (see `openTelemetry`): the agent reads
304
314
  * and sends `traceparent`, and follows an OpenTelemetry SDK in the process,
305
315
  * only beside reporting to NestJS Observe. So an agent that sends Observe
306
- * nothing - `enabled: false`, no credentials, credentials the collector
307
- * refuses - never turns it on.
316
+ * nothing - `enabled: false`, no credentials - never turns it on.
317
+ */
318
+ isReporting() {
319
+ return this.reporting !== "off";
320
+ }
321
+ /**
322
+ * Whether the collector takes this app's telemetry: from the first batch
323
+ * it accepts, until it refuses the app's credentials or the worker stops -
324
+ * and again from the next batch it accepts. What its replies grant, an
325
+ * OTLP export say, holds only while it does.
308
326
  */
309
327
  isIngesting() {
310
- return this.ingesting;
328
+ return this.reporting === "ingesting";
329
+ }
330
+ /**
331
+ * The worker started with the application, set up to report: see
332
+ * `isReporting`. A worker restarted after a stop is not this - it has to
333
+ * get a batch in first - and a batch already taken stays taken.
334
+ */
335
+ recordStarted() {
336
+ if (this.reporting === "off") {
337
+ this.reporting = "started";
338
+ }
311
339
  }
312
340
  /** The collector accepted a batch, whatever it then kept of it. */
313
341
  recordAccepted() {
314
- this.ingesting = true;
342
+ this.reporting = "ingesting";
315
343
  }
316
344
  /** The collector refused the app's credentials. */
317
345
  recordRefused() {
318
- this.ingesting = false;
346
+ this.reporting = "off";
319
347
  }
320
348
  /** The worker stopped; a restarted one has to get a batch in again. */
321
349
  recordStopped() {
322
- this.ingesting = false;
350
+ this.reporting = "off";
323
351
  }
324
352
  /**
325
353
  * What the collector's last accepted reply granted `otlp` - see
@@ -155,8 +155,9 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
155
155
  /**
156
156
  * Says when OpenTelemetry interop turns on or off, with `openTelemetry` on:
157
157
  * it runs only beside reporting to NestJS Observe (see
158
- * `ObserveAgentSharedBuffer.isIngesting`), and a `traceparent` that stops
159
- * going out with no word would read as a bug in the agent.
158
+ * `ObserveAgentSharedBuffer.isReporting`), and a `traceparent` that stops
159
+ * going out with no word would read as a bug in the agent. `why` is what
160
+ * just happened, which the line gives as the reason.
160
161
  */
161
162
  private reportOpenTelemetryInterop;
162
163
  /**
@@ -142,6 +142,10 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
142
142
  }
143
143
  else {
144
144
  this.initializeWorker();
145
+ // Not in `initializeWorker`, which restarts a stopped worker too: that
146
+ // one has to get a batch in first.
147
+ this.observeAgentSharedBuffer.recordStarted();
148
+ this.reportOpenTelemetryInterop("started");
145
149
  }
146
150
  if (this.options.openTelemetry === true && this.sendsNothing) {
147
151
  this.logger.warn("openTelemetry is on, but this agent reports nothing to NestJS Observe, so OpenTelemetry interop stays off: " +
@@ -554,7 +558,7 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
554
558
  const mode = parseDegradedMessage(msg);
555
559
  if (mode !== null) {
556
560
  this.observeAgentSharedBuffer.recordAccepted();
557
- this.reportOpenTelemetryInterop();
561
+ this.reportOpenTelemetryInterop("accepted");
558
562
  this.reportFirstAcceptedBatch();
559
563
  this.applyIngestMode(mode, parseOveragePauseReason(msg));
560
564
  return;
@@ -575,22 +579,26 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
575
579
  /**
576
580
  * Says when OpenTelemetry interop turns on or off, with `openTelemetry` on:
577
581
  * it runs only beside reporting to NestJS Observe (see
578
- * `ObserveAgentSharedBuffer.isIngesting`), and a `traceparent` that stops
579
- * going out with no word would read as a bug in the agent.
582
+ * `ObserveAgentSharedBuffer.isReporting`), and a `traceparent` that stops
583
+ * going out with no word would read as a bug in the agent. `why` is what
584
+ * just happened, which the line gives as the reason.
580
585
  */
581
586
  reportOpenTelemetryInterop(why) {
582
587
  if (this.options.openTelemetry !== true) {
583
588
  return;
584
589
  }
585
- const on = this.observeAgentSharedBuffer.isIngesting();
590
+ const on = this.observeAgentSharedBuffer.isReporting();
586
591
  if (on === this.reportedOpenTelemetry) {
587
592
  return;
588
593
  }
589
594
  this.reportedOpenTelemetry = on;
590
595
  if (on) {
591
- this.logger.log("OpenTelemetry interop is on: the collector accepted this app's telemetry, so traceparent is read and sent. " +
592
- "It stays on through collector outages and rate limits, and pauses only if the collector refuses the app's " +
593
- "credentials or the telemetry worker stops.");
596
+ this.logger.log(why === "started"
597
+ ? "OpenTelemetry interop is on: traceparent is read and sent beside reporting to NestJS Observe. " +
598
+ "It stays on through collector outages and rate limits, and pauses only if the collector refuses the " +
599
+ "app's credentials or the telemetry worker stops."
600
+ : "OpenTelemetry interop is on again: the collector accepted this app's telemetry, so traceparent is read " +
601
+ "and sent.");
594
602
  return;
595
603
  }
596
604
  const reason = why === "refused"
@@ -174,11 +174,9 @@ export class Gauge {
174
174
  else if (typeof labelOrValue === "object") {
175
175
  this.validateLabels(labelOrValue);
176
176
  const stringifiedLabel = stringifyLabel(labelOrValue);
177
- if (!(stringifiedLabel in this.value)) {
178
- throw new Error(`Label "${stringifiedLabel}" does not exist in the gauge. Available labels: ${Object.keys(this.value).join(", ")}.`);
179
- }
180
177
  const newValue = value ?? this._initialValue;
181
- if (!admitsFinite(this.name, newValue, this.nonFinite)) {
178
+ if (!admitsFinite(this.name, newValue, this.nonFinite) ||
179
+ !admitsSeries(this.name, this.value, stringifiedLabel, this.seriesLimit)) {
182
180
  return;
183
181
  }
184
182
  this.value[stringifiedLabel] = newValue;
@@ -64,6 +64,86 @@ function isMongoDriverHandle(instance) {
64
64
  return false;
65
65
  }
66
66
  }
67
+ /**
68
+ * Library classes traced only in part, each with a method only it has, which
69
+ * tells it from an application's own class of the same name - `ValidationPipe`
70
+ * is what Nest's documentation calls the pipe it has readers write themselves,
71
+ * and plenty of applications have a `ConfigService` of their own.
72
+ *
73
+ * - Nest's validating pipes keep only `validate`. `ValidationPipe` runs once
74
+ * per handler argument, and for each one `transform`, `toValidate` and
75
+ * `transformPrimitive` were spans, usually of a few microseconds and each
76
+ * one billed, on runs that mostly validate nothing: 82% of runs across the
77
+ * hosted platform on 2026-11-06, which made it the busiest class after
78
+ * `pg`, and 404,552 of 404,652 on one REST app.
79
+ * - `@nestjs/config`'s `ConfigService` keeps what an application calls. Each
80
+ * `get` made four or five more spans of its private helpers - 2.7M of its
81
+ * 4.6M a day, in 220 projects.
82
+ *
83
+ * Folding cannot reach any of them (`collapseRepeatedSpans`), because each
84
+ * repeats only a few times under its parent.
85
+ *
86
+ * By name, because `StandardSchemaValidationPipe` is not in every supported
87
+ * `@nestjs/common` and an application may carry a second copy of a package.
88
+ * A class that stops matching is simply traced like any other.
89
+ */
90
+ const PARTLY_TRACED_CLASSES = new Map([
91
+ [
92
+ "ValidationPipe",
93
+ { marker: "flattenValidationErrors", traced: new Set(["validate"]) },
94
+ ],
95
+ [
96
+ "StandardSchemaValidationPipe",
97
+ { marker: "formatIssueMessages", traced: new Set(["validate"]) },
98
+ ],
99
+ [
100
+ "ParseFilePipe",
101
+ { marker: "validateFilesOrFile", traced: new Set(["validate"]) },
102
+ ],
103
+ [
104
+ "ConfigService",
105
+ {
106
+ marker: "getFromValidatedEnv",
107
+ traced: new Set(["get", "getOrThrow", "set", "setEnvFilePaths"]),
108
+ },
109
+ ],
110
+ ]);
111
+ /** The methods a prototype's class keeps traced, if it is one of those. */
112
+ function partlyTracedMethodsOf(proto) {
113
+ const candidate = proto;
114
+ const entry = PARTLY_TRACED_CLASSES.get(candidate.constructor?.name ?? "");
115
+ return entry !== undefined && typeof candidate[entry.marker] === "function"
116
+ ? entry.traced
117
+ : null;
118
+ }
119
+ /** Whether an instance is one of those classes, or extends one. */
120
+ function extendsPartlyTracedClass(instance) {
121
+ for (let proto = Object.getPrototypeOf(instance); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
122
+ if (partlyTracedMethodsOf(proto) !== null) {
123
+ return true;
124
+ }
125
+ }
126
+ return false;
127
+ }
128
+ /**
129
+ * Whether a method is one of those classes' internals, and so makes no span.
130
+ *
131
+ * Asked of the class that holds the method, so what an application adds to or
132
+ * overrides in a subclass is still traced. An instance's own function - the
133
+ * `exceptionFactory` a constructor assigns - goes by the instance's class.
134
+ */
135
+ function isLibraryInternal(target, methodName) {
136
+ let holder = target;
137
+ while (holder !== null && !Object.hasOwn(holder, methodName)) {
138
+ holder = Object.getPrototypeOf(holder);
139
+ }
140
+ if (holder === null) {
141
+ return false;
142
+ }
143
+ const traced = partlyTracedMethodsOf(holder === target ? Object.getPrototypeOf(target) : holder);
144
+ return (traced !== null &&
145
+ !(typeof methodName === "string" && traced.has(methodName)));
146
+ }
67
147
  export function createInstanceDecorator(als, operationTraceRegistry, options) {
68
148
  /**
69
149
  * Builds the tracing wrapper shared by methods and standalone functions.
@@ -220,6 +300,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
220
300
  let hasPrivateMembers;
221
301
  let slotBacked;
222
302
  let bareBuiltIn;
303
+ let partlyTraced;
223
304
  try {
224
305
  // Inspected here, inside the guard, for the same reason as the checks
225
306
  // below: reading a provider's constructor can run a trap that throws.
@@ -229,6 +310,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
229
310
  hasPrivateMembers = usesNativePrivateMembers(instance);
230
311
  slotBacked = isSlotBackedBuiltIn(instance);
231
312
  bareBuiltIn = slotBacked && isNativeFunction(instance.constructor);
313
+ partlyTraced = extendsPartlyTracedClass(instance);
232
314
  }
233
315
  catch {
234
316
  // Reading the prototype ran a trap that threw (nestjs-cls proxy
@@ -283,7 +365,10 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
283
365
  // mid-trace). This subsumes the Axios special case that used to sit
284
366
  // here: an Axios instance is a bound `request` carrying its API as
285
367
  // own properties.
286
- !isCallableObject(attributeValue);
368
+ !isCallableObject(attributeValue) &&
369
+ // Handed out as it is, so it still runs against the proxy: the
370
+ // `this.validate()` inside `transform` comes back through here.
371
+ !(partlyTraced && isLibraryInternal(target, prop));
287
372
  if (!shouldProxy) {
288
373
  // Remembered, as a wrapped method is: telling them apart reads the
289
374
  // function's source and its prototype's keys, which a Mongoose
@@ -572,11 +657,43 @@ function declaresPrivateMembers(ctor) {
572
657
  /**
573
658
  * The class name that labels an instance's spans. A null-prototype object or
574
659
  * an ES module namespace has no `constructor`, and some objects hold a
575
- * non-function there. Both fall back to `Object`.
660
+ * non-function there. Both fall back to `Object`. An `ioredis` client is
661
+ * named for what it is - see `ioredisClassNameOf`.
576
662
  */
577
663
  function classNameOf(instance) {
578
664
  const ctor = Reflect.get(instance, "constructor");
579
- return typeof ctor === "function" ? ctor.name : FALLBACK_CLASS_NAME;
665
+ if (typeof ctor !== "function") {
666
+ return FALLBACK_CLASS_NAME;
667
+ }
668
+ return ((ctor.name === "EventEmitter" && ioredisClassNameOf(instance)) || ctor.name);
669
+ }
670
+ /**
671
+ * `Redis` or `Cluster` for an `ioredis` client, null for anything else.
672
+ *
673
+ * Both classes take `EventEmitter`'s methods by copying the own properties of
674
+ * its prototype onto theirs, `constructor` included, so a client's
675
+ * `constructor` is `EventEmitter` and every command would be labelled
676
+ * `EventEmitter.get`. Both extend ioredis's `Commander`, whose prototype keeps
677
+ * its own `constructor`, and a client has `sendCommand`.
678
+ *
679
+ * Matched by name and shape only, as `isMongoDriverHandle` is: ioredis is an
680
+ * application's dependency, never imported here, and an application may carry
681
+ * more than one copy of it - BullMQ and Bull bring their own.
682
+ */
683
+ function ioredisClassNameOf(instance) {
684
+ try {
685
+ const candidate = instance;
686
+ const base = Object.getPrototypeOf(Object.getPrototypeOf(instance));
687
+ if (base?.constructor?.name !== "Commander" ||
688
+ typeof candidate.sendCommand !== "function") {
689
+ return null;
690
+ }
691
+ return candidate.isCluster === true ? "Cluster" : "Redis";
692
+ }
693
+ catch {
694
+ // A prototype or a property that cannot be read names nothing.
695
+ return null;
696
+ }
580
697
  }
581
698
  function generateSpanId(instance, methodKey) {
582
699
  return `${classNameOf(instance)}#${methodKey}`;
@@ -663,22 +663,26 @@ export interface ObserveOptions {
663
663
  * reported under the trace of the server span the SDK opened for it, the
664
664
  * request that starts a trace included, and `traceparent` on outbound
665
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.
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.
670
674
  *
671
675
  * A `traceIdGenerator` passed to `createObserveModule()` still names the
672
676
  * trace; the W3C one is carried on beside it.
673
677
  *
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.
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.
682
686
  * @default false
683
687
  */
684
688
  openTelemetry?: boolean;
@@ -59,10 +59,11 @@ export declare function requestSnapshotSpans(snapshot: RequestSnapshot, context:
59
59
  * A queue job or a scheduled run as OTLP spans: a CONSUMER span for the run
60
60
  * - INTERNAL for a scheduled one, which nothing sent - and its tree under
61
61
  * it. A job reports under the trace id of the operation that enqueued it,
62
- * so it lands in that trace; nothing records which span enqueued it, so it
63
- * has no parent there. Without `withTree`, the run's span alone.
62
+ * so it lands in that trace, and under the span that enqueued it when it was
63
+ * handed on with a `traceparent` - see `handedOnTraceContext`. Without
64
+ * `withTree`, the run's span alone.
64
65
  */
65
- export declare function jobSnapshotSpans(snapshot: JobSnapshot, withTree?: boolean): OtlpSpan[];
66
+ export declare function jobSnapshotSpans(snapshot: JobSnapshot, context: TraceContext | undefined, withTree?: boolean): OtlpSpan[];
66
67
  /**
67
68
  * Attributes from a flat record, in its order, without the keys that hold
68
69
  * nothing - and at most `MAX_ATTRIBUTES_PER_SPAN` of them, the rest counted.
@@ -115,11 +115,12 @@ export function requestSnapshotSpans(snapshot, context, withTree = true) {
115
115
  * A queue job or a scheduled run as OTLP spans: a CONSUMER span for the run
116
116
  * - INTERNAL for a scheduled one, which nothing sent - and its tree under
117
117
  * it. A job reports under the trace id of the operation that enqueued it,
118
- * so it lands in that trace; nothing records which span enqueued it, so it
119
- * has no parent there. Without `withTree`, the run's span alone.
118
+ * so it lands in that trace, and under the span that enqueued it when it was
119
+ * handed on with a `traceparent` - see `handedOnTraceContext`. Without
120
+ * `withTree`, the run's span alone.
120
121
  */
121
- export function jobSnapshotSpans(snapshot, withTree = true) {
122
- const traceId = w3cTraceIdOf(snapshot.traceId);
122
+ export function jobSnapshotSpans(snapshot, context, withTree = true) {
123
+ const traceId = context?.traceId ?? w3cTraceIdOf(snapshot.traceId);
123
124
  const startNs = epochNanos(snapshot.calledAt);
124
125
  const scheduled = SCHEDULER_QUEUES.has(snapshot.queueName);
125
126
  const tags = {
@@ -141,6 +142,9 @@ export function jobSnapshotSpans(snapshot, withTree = true) {
141
142
  const run = {
142
143
  traceId,
143
144
  spanId: randomSpanId(),
145
+ ...(context
146
+ ? { parentSpanId: context.parentSpanId, traceState: context.traceState }
147
+ : {}),
144
148
  name: `${snapshot.queueName} ${snapshot.name}`,
145
149
  kind: scheduled ? SpanKind.INTERNAL : SpanKind.CONSUMER,
146
150
  startTimeUnixNano: startNs,
@@ -148,7 +152,7 @@ export function jobSnapshotSpans(snapshot, withTree = true) {
148
152
  ...toAttributes(tags),
149
153
  events: [],
150
154
  ...(failed ? { status: errorStatus(snapshot.error) } : {}),
151
- flags: LOCAL_PARENT_FLAGS,
155
+ flags: context ? REMOTE_PARENT_FLAGS : LOCAL_PARENT_FLAGS,
152
156
  };
153
157
  const spans = [run];
154
158
  for (const node of withTree ? snapshot.traces ?? [] : []) {
@@ -86,6 +86,9 @@ export declare class OtlpTraceExporter implements OnModuleInit, OnApplicationShu
86
86
  /**
87
87
  * Queues a finished job's spans - its own span, and with `withTree` the
88
88
  * spans under it. Never throws into the caller.
89
+ *
90
+ * Left out, as a request is, when the trace it was handed on in is one an
91
+ * OpenTelemetry SDK in this process sampled out.
89
92
  */
90
93
  exportJobSnapshot(snapshot: JobSnapshot, withTree?: boolean): void;
91
94
  /**
@@ -210,13 +210,20 @@ let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
210
210
  /**
211
211
  * Queues a finished job's spans - its own span, and with `withTree` the
212
212
  * spans under it. Never throws into the caller.
213
+ *
214
+ * Left out, as a request is, when the trace it was handed on in is one an
215
+ * OpenTelemetry SDK in this process sampled out.
213
216
  */
214
217
  exportJobSnapshot(snapshot, withTree = true) {
215
218
  if (!this.settings) {
216
219
  return;
217
220
  }
218
221
  try {
219
- this.enqueue(jobSnapshotSpans(snapshot, withTree));
222
+ const context = this.operationTraceRegistry.traceContextOf(snapshot);
223
+ if (context && !context.sampled) {
224
+ return;
225
+ }
226
+ this.enqueue(jobSnapshotSpans(snapshot, context, withTree));
220
227
  }
221
228
  catch (error) {
222
229
  this.reportMappingFailure(error);
@@ -29,9 +29,8 @@ export interface OutgoingHttpOptions {
29
29
  * cover, and a request takes only one.
30
30
  *
31
31
  * Only with `openTelemetry` on, and only beside reporting to NestJS
32
- * Observe - from the first batch the collector accepts, through outages,
33
- * until it refuses the app's credentials; otherwise no `traceparent` is
34
- * sent.
32
+ * Observe - from start-up, through outages, until the collector refuses
33
+ * the app's credentials; otherwise no `traceparent` is sent.
35
34
  * @default true, with `openTelemetry` on
36
35
  */
37
36
  traceContext?: boolean;
@@ -64,6 +63,6 @@ getRedactor?: () => LogRedactor | null,
64
63
  /**
65
64
  * Whether calls carry W3C Trace Context now: with `openTelemetry` on and
66
65
  * `traceContext` not off, while the agent reports to NestJS Observe (see
67
- * `ObserveAgentSharedBuffer.isIngesting`). Off unless given.
66
+ * `ObserveAgentSharedBuffer.isReporting`). Off unless given.
68
67
  */
69
68
  traceContextOn?: () => boolean): () => void;
@@ -28,7 +28,7 @@ getRedactor = () => null,
28
28
  /**
29
29
  * Whether calls carry W3C Trace Context now: with `openTelemetry` on and
30
30
  * `traceContext` not off, while the agent reports to NestJS Observe (see
31
- * `ObserveAgentSharedBuffer.isIngesting`). Off unless given.
31
+ * `ObserveAgentSharedBuffer.isReporting`). Off unless given.
32
32
  */
33
33
  traceContextOn = () => false) {
34
34
  const spans = new WeakMap();
@@ -127,10 +127,10 @@ let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class Outgoing
127
127
  }, http, () => operationTraceRegistry.getRedactor(),
128
128
  // W3C Trace Context goes out only with `openTelemetry` on, and only
129
129
  // while the agent reports to NestJS Observe - see
130
- // `ObserveAgentSharedBuffer.isIngesting`.
130
+ // `ObserveAgentSharedBuffer.isReporting`.
131
131
  () => this.options.openTelemetry === true &&
132
132
  http.traceContext !== false &&
133
- this.observeAgentSharedBuffer?.isIngesting() === true);
133
+ this.observeAgentSharedBuffer?.isReporting() === true);
134
134
  // Model calls are read off the spans above, so they go with them.
135
135
  if (outgoing?.llm !== false) {
136
136
  this.deactivateLlm = activateLlmFetchObserver(recorder, typeof outgoing?.llm === "object" ? outgoing.llm : {});
@@ -110,10 +110,10 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
110
110
  const store = new Map();
111
111
  this.asyncLocalStorage.run(store, () => {
112
112
  // OpenTelemetry interop runs only beside reporting to NestJS Observe -
113
- // see `ObserveAgentSharedBuffer.isIngesting`. Asked once per request,
113
+ // see `ObserveAgentSharedBuffer.isReporting`. Asked once per request,
114
114
  // so a request is named and carried on one way throughout.
115
115
  const openTelemetry = this.options.openTelemetry === true &&
116
- this.observeAgentSharedBuffer.isIngesting();
116
+ this.observeAgentSharedBuffer.isReporting();
117
117
  const traceId = generateTraceIdSafely(openTelemetry && usesDefaultTraceIdGenerator(this.options)
118
118
  ? openTelemetryTraceIdGenerator
119
119
  : this.options.traceIdGenerator, req, this.options, this.logger);
@@ -61,7 +61,7 @@ export declare class JobTraceRunner<Store extends Record<string, unknown>> {
61
61
  private stampTraceId;
62
62
  /**
63
63
  * Whether OpenTelemetry interop runs now: `openTelemetry` on, beside
64
- * reporting to NestJS Observe - see `ObserveAgentSharedBuffer.isIngesting`.
64
+ * reporting to NestJS Observe - see `ObserveAgentSharedBuffer.isReporting`.
65
65
  * Asked as a job is enqueued and again as it starts, by each side for
66
66
  * itself.
67
67
  */
@@ -1,5 +1,6 @@
1
- import { JOB_TRACE_CONTEXT_OPTION_KEY, JOB_TRACE_OPTION_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
1
+ import { JOB_TRACE_CONTEXT_OPTION_KEY, JOB_TRACE_OPTION_KEY, TRACE_CONTEXT_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
2
2
  import { REQUEST_ID_PATTERN } from "../utils/default-trace-id-generator.util.js";
3
+ import { handedOnTraceContext } from "../utils/trace-context.util.js";
3
4
  import { continueHandedOnTrace, traceparentToHandOn, } from "../utils/trace-handoff.util.js";
4
5
  import { uuidv7 } from "../utils/uuid-v7.util.js";
5
6
  import { deferTraceCompletion, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
@@ -122,13 +123,13 @@ export class JobTraceRunner {
122
123
  }
123
124
  /**
124
125
  * Whether OpenTelemetry interop runs now: `openTelemetry` on, beside
125
- * reporting to NestJS Observe - see `ObserveAgentSharedBuffer.isIngesting`.
126
+ * reporting to NestJS Observe - see `ObserveAgentSharedBuffer.isReporting`.
126
127
  * Asked as a job is enqueued and again as it starts, by each side for
127
128
  * itself.
128
129
  */
129
130
  openTelemetryInteropOn() {
130
131
  return (this.options.openTelemetry === true &&
131
- this.observeAgentSharedBuffer.isIngesting());
132
+ this.observeAgentSharedBuffer.isReporting());
132
133
  }
133
134
  /**
134
135
  * The id stamped at enqueue time, if it is one this agent would have minted
@@ -217,6 +218,13 @@ export class JobTraceRunner {
217
218
  const handedOn = inheritedTraceId !== undefined && this.openTelemetryInteropOn()
218
219
  ? job.opts?.[JOB_TRACE_CONTEXT_OPTION_KEY]
219
220
  : undefined;
221
+ // And the job's span goes under the span that handed it on, for `otlp`,
222
+ // while the calls it makes carry the caller's decision on - as a
223
+ // request's do with the `traceparent` it arrived with.
224
+ const traceContext = handedOnTraceContext(handedOn, traceId);
225
+ if (traceContext) {
226
+ store.set(TRACE_CONTEXT_KEY, traceContext);
227
+ }
220
228
  const context = {
221
229
  queueName: job.queueName,
222
230
  name: job.name,
@@ -235,7 +243,7 @@ export class JobTraceRunner {
235
243
  tags: this.options.jobs?.tags,
236
244
  ...context,
237
245
  ...job.metadata,
238
- }, traceId);
246
+ }, traceId, traceContext);
239
247
  let settled = false;
240
248
  const settle = (status) => {
241
249
  if (settled) {
@@ -50,7 +50,7 @@ export declare class RpcObserveAgentService<Store extends Record<string, unknown
50
50
  startRpcRequestTracing(transportId: Transport | symbol, ctx: BaseRpcContext, done: () => Promise<any>): Promise<unknown>;
51
51
  /**
52
52
  * Whether OpenTelemetry interop runs now: `openTelemetry` on, beside
53
- * reporting to NestJS Observe - see `ObserveAgentSharedBuffer.isIngesting`.
53
+ * reporting to NestJS Observe - see `ObserveAgentSharedBuffer.isReporting`.
54
54
  */
55
55
  private openTelemetryInteropOn;
56
56
  startGrpcRequestTracing(transportId: Transport | symbol, call: GrpcCall, done: () => Promise<any>): Promise<unknown>;
@@ -17,7 +17,8 @@ import { AsyncLocalStorage } from "async_hooks";
17
17
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
18
18
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
19
19
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
20
- import { OBSERVE_OPTIONS, TRACE_REGISTRY_KEY } from "../observe.constants.js";
20
+ import { OBSERVE_OPTIONS, TRACE_CONTEXT_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
21
+ import { handedOnTraceContext } from "../utils/trace-context.util.js";
21
22
  import { continueHandedOnTrace } from "../utils/trace-handoff.util.js";
22
23
  import { uuidv7 } from "../utils/uuid-v7.util.js";
23
24
  import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
@@ -129,6 +130,13 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
129
130
  const handle = handedOn === undefined
130
131
  ? done
131
132
  : () => continueHandedOnTrace(handedOn, traceId, done);
133
+ // And the handler's span goes under the span that sent the message, for
134
+ // `otlp`, while the calls it makes carry the caller's decision on - as
135
+ // a request's do with the `traceparent` it arrived with.
136
+ const traceContext = handedOnTraceContext(handedOn, traceId);
137
+ if (traceContext) {
138
+ store.set(TRACE_CONTEXT_KEY, traceContext);
139
+ }
132
140
  setAttributesSafely(this.options.rpc?.setAttributes, [transportId, ctx], this.options.rpc, store, this.logger, "rpc");
133
141
  if (shouldIgnoreSafely(this.options.rpc?.ignore, [transportId, ctx], this.options.rpc, this.logger, "rpc")) {
134
142
  return handle();
@@ -144,17 +152,17 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
144
152
  protocol: this.toProtocolName(transportId),
145
153
  operationId: this.getOperationIdFromContext(ctx),
146
154
  tags: this.options.rpc?.tags,
147
- }, traceId);
155
+ }, traceId, traceContext);
148
156
  return handle();
149
157
  });
150
158
  }
151
159
  /**
152
160
  * Whether OpenTelemetry interop runs now: `openTelemetry` on, beside
153
- * reporting to NestJS Observe - see `ObserveAgentSharedBuffer.isIngesting`.
161
+ * reporting to NestJS Observe - see `ObserveAgentSharedBuffer.isReporting`.
154
162
  */
155
163
  openTelemetryInteropOn() {
156
164
  return (this.options.openTelemetry === true &&
157
- this.observeAgentSharedBuffer.isIngesting());
165
+ this.observeAgentSharedBuffer.isReporting());
158
166
  }
159
167
  startGrpcRequestTracing(transportId, call, done) {
160
168
  // As above: the map `run` is given, not looked back up.
@@ -165,6 +173,17 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
165
173
  // The key must precede callbacks here too, before the deferred startup.
166
174
  const registryKey = uuidv7();
167
175
  store.set(TRACE_REGISTRY_KEY, registryKey);
176
+ // As for a message: the call's span goes under the caller's for `otlp`,
177
+ // and the calls the handler makes carry its decision on. Read now, while
178
+ // the span a gRPC instrumentation opened for the call is the active one.
179
+ // Unlike a message's, the handler is not run in the caller's trace: the
180
+ // SDK's gRPC instrumentation carries it there.
181
+ const traceContext = this.openTelemetryInteropOn()
182
+ ? handedOnTraceContext(grpcTraceparent(call), traceId)
183
+ : undefined;
184
+ if (traceContext) {
185
+ store.set(TRACE_CONTEXT_KEY, traceContext);
186
+ }
168
187
  setAttributesSafely(this.options.grpc?.setAttributes, [call], this.options.grpc, store, this.logger, "grpc");
169
188
  return new Promise((resolve) => {
170
189
  // A throw in this timer escapes the promise: `done()` never runs, and
@@ -183,7 +202,7 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
183
202
  protocol: this.toProtocolName(transportId),
184
203
  operationId: call.operationId,
185
204
  tags: this.options.grpc?.tags,
186
- }, traceId);
205
+ }, traceId, traceContext);
187
206
  resolve(done());
188
207
  }, 0);
189
208
  });
@@ -272,3 +291,20 @@ function handedOnTraceparent(ctx) {
272
291
  return undefined;
273
292
  }
274
293
  }
294
+ /**
295
+ * The `traceparent` a gRPC call's metadata carries - a caller instrumented
296
+ * with OpenTelemetry sends one, and so does one running the agent with
297
+ * `openTelemetry` on - read off grpc-js's `Metadata`, whichever Nest release
298
+ * handed the call over.
299
+ */
300
+ function grpcTraceparent(call) {
301
+ try {
302
+ const metadata = call.metadata;
303
+ const value = metadata?.get?.("traceparent")?.[0];
304
+ return typeof value === "string" ? value : undefined;
305
+ }
306
+ catch {
307
+ // Metadata that cannot be read carries nothing to continue.
308
+ return undefined;
309
+ }
310
+ }
@@ -128,9 +128,12 @@ let TracerService = TracerService_1 = class TracerService {
128
128
  if (attributes?.labels) {
129
129
  overridableRef.labels = attributes.labels;
130
130
  }
131
+ // `value` holds one reading per label, so the seed goes to the default
132
+ // one; a labelled metric has no unlabelled reading to seed.
131
133
  if (attributes?.initialValue !== undefined &&
134
+ !existingRef.labels &&
132
135
  existingRef.getValue() === 0) {
133
- overridableRef["value"] = attributes.initialValue;
136
+ overridableRef.value.default = attributes.initialValue;
134
137
  }
135
138
  return existingRef;
136
139
  }
@@ -149,9 +152,12 @@ let TracerService = TracerService_1 = class TracerService {
149
152
  if (attributes?.labels) {
150
153
  overridableRef.labels = attributes.labels;
151
154
  }
155
+ // `value` holds one reading per label, so the seed goes to the default
156
+ // one; a labelled metric has no unlabelled reading to seed.
152
157
  if (attributes?.initialValue !== undefined &&
158
+ !existingRef.labels &&
153
159
  existingRef.getValue() === 0) {
154
- overridableRef["value"] = attributes.initialValue;
160
+ overridableRef.value.default = attributes.initialValue;
155
161
  }
156
162
  if (attributes?.kind) {
157
163
  overridableRef.kind = attributes.kind;
@@ -91,11 +91,16 @@ function frameLines(stack, message) {
91
91
  headerEnd = stack.indexOf("\n");
92
92
  }
93
93
  else {
94
- const at = stack.indexOf(message);
95
- if (at === -1 || stack.lastIndexOf("\n", at) !== -1) {
96
- return [];
94
+ // The last match on the first line that runs to the end of a line: an
95
+ // earlier one can sit inside the name - `UnauthorizedException:
96
+ // Unauthorized` - and a later one ends past the real message, so whatever
97
+ // follows it is still what V8 wrote.
98
+ headerEnd = -1;
99
+ for (let at = stack.indexOf(message); at !== -1 && stack.lastIndexOf("\n", at) === -1; at = stack.indexOf(message, at + 1)) {
100
+ if (stack[at + message.length] === "\n") {
101
+ headerEnd = at + message.length;
102
+ }
97
103
  }
98
- headerEnd = at + message.length;
99
104
  }
100
105
  if (headerEnd === -1 || stack[headerEnd] !== "\n") {
101
106
  return [];
@@ -62,6 +62,26 @@ export declare function inboundTraceContext(headers: Record<string, unknown> | u
62
62
  * `traceIdFromTraceparent` writes it.
63
63
  */
64
64
  export declare function inboundTraceId(headers: Record<string, unknown> | undefined): string | undefined;
65
+ /**
66
+ * The W3C trace context a queue job or a microservice message runs in -
67
+ * `inboundTraceContext`'s counterpart for work handed on with a `traceparent`
68
+ * (see `traceparentToHandOn`), whose span the exporter puts under it. That is
69
+ * the span an OpenTelemetry SDK in this process has open for the work, when
70
+ * it is in that trace - an instrumentation that covers the hop opens one:
71
+ * `bullmq-otel` for a job, the SDK's gRPC, Kafka or RabbitMQ instrumentation
72
+ * for a message - else the `traceparent` itself.
73
+ *
74
+ * Only a `traceparent` in the trace `traceId` - the Observe trace id the work
75
+ * runs under - maps onto, as `continueHandedOnTrace` takes it: job options and
76
+ * packet metadata are writable by anything that reaches Redis or the socket.
77
+ *
78
+ * And only a sampled one, which a request's `traceparent` need not be. The
79
+ * agent hands work on unsampled when the operation that sent it was not
80
+ * recorded, naming a span that exists nowhere; or its caller sampled the
81
+ * trace out, and nothing upstream exports it. Either way there is no parent
82
+ * to put the work's span under, so it stays as it was without one.
83
+ */
84
+ export declare function handedOnTraceContext(traceparent: unknown, traceId: string): TraceContext | undefined;
65
85
  /**
66
86
  * The W3C trace id an Observe trace id goes out under.
67
87
  *
@@ -126,6 +126,35 @@ export function inboundTraceId(headers) {
126
126
  const traceId = inboundTraceContext(headers)?.traceId;
127
127
  return traceId === undefined ? undefined : toUuid(traceId);
128
128
  }
129
+ /**
130
+ * The W3C trace context a queue job or a microservice message runs in -
131
+ * `inboundTraceContext`'s counterpart for work handed on with a `traceparent`
132
+ * (see `traceparentToHandOn`), whose span the exporter puts under it. That is
133
+ * the span an OpenTelemetry SDK in this process has open for the work, when
134
+ * it is in that trace - an instrumentation that covers the hop opens one:
135
+ * `bullmq-otel` for a job, the SDK's gRPC, Kafka or RabbitMQ instrumentation
136
+ * for a message - else the `traceparent` itself.
137
+ *
138
+ * Only a `traceparent` in the trace `traceId` - the Observe trace id the work
139
+ * runs under - maps onto, as `continueHandedOnTrace` takes it: job options and
140
+ * packet metadata are writable by anything that reaches Redis or the socket.
141
+ *
142
+ * And only a sampled one, which a request's `traceparent` need not be. The
143
+ * agent hands work on unsampled when the operation that sent it was not
144
+ * recorded, naming a span that exists nowhere; or its caller sampled the
145
+ * trace out, and nothing upstream exports it. Either way there is no parent
146
+ * to put the work's span under, so it stays as it was without one.
147
+ */
148
+ export function handedOnTraceContext(traceparent, traceId) {
149
+ const handedOn = typeof traceparent === "string"
150
+ ? readTraceContext({ traceparent })
151
+ : undefined;
152
+ if (!handedOn?.sampled || handedOn.traceId !== w3cTraceIdOf(traceId)) {
153
+ return undefined;
154
+ }
155
+ const active = traceContextOfSpan(activeOpenTelemetrySpanContext());
156
+ return active?.traceId === handedOn.traceId ? active : handedOn;
157
+ }
129
158
  /**
130
159
  * An OpenTelemetry span context as the trace context an operation runs in,
131
160
  * the span becoming the operation's parent - or `undefined` for one the spec
@@ -24,11 +24,17 @@ export declare function traceparentToHandOn(store: ReadonlyMap<unknown, unknown>
24
24
  * packet metadata are writable by anything that reaches Redis or the
25
25
  * socket, and a span from another trace would put the work under one it
26
26
  * never ran beside. Anything else runs `run` as it is.
27
+ *
28
+ * So does work an OpenTelemetry instrumentation has already taken up, with
29
+ * a span of that trace open for it - BullMQ's `bullmq-otel` opens one for
30
+ * each job, and OpenTelemetry's Kafka and RabbitMQ instrumentations one for
31
+ * each message they deliver. The work's spans belong under that span, which
32
+ * the handed-on parent would put them beside.
27
33
  */
28
34
  export declare function continueHandedOnTrace<T>(traceparent: unknown, traceId: string, run: () => T): T;
29
35
  /**
30
36
  * Whether OpenTelemetry interop runs now - `openTelemetry` on, beside
31
- * reporting to NestJS Observe (see `ObserveAgentSharedBuffer.isIngesting`) -
37
+ * reporting to NestJS Observe (see `ObserveAgentSharedBuffer.isReporting`) -
32
38
  * for what is set up before the module's options resolve: the microservice
33
39
  * dispatch hook, which a client is handed as it is instantiated. Off until
34
40
  * the module configures it.
@@ -39,7 +45,7 @@ export declare class OpenTelemetryInteropGate {
39
45
  configure(options: {
40
46
  openTelemetry?: boolean;
41
47
  } | undefined, buffer: {
42
- isIngesting(): boolean;
48
+ isReporting(): boolean;
43
49
  } | undefined): this;
44
50
  isOn(): boolean;
45
51
  }
@@ -54,12 +54,20 @@ export function traceparentToHandOn(store, traceId) {
54
54
  * packet metadata are writable by anything that reaches Redis or the
55
55
  * socket, and a span from another trace would put the work under one it
56
56
  * never ran beside. Anything else runs `run` as it is.
57
+ *
58
+ * So does work an OpenTelemetry instrumentation has already taken up, with
59
+ * a span of that trace open for it - BullMQ's `bullmq-otel` opens one for
60
+ * each job, and OpenTelemetry's Kafka and RabbitMQ instrumentations one for
61
+ * each message they deliver. The work's spans belong under that span, which
62
+ * the handed-on parent would put them beside.
57
63
  */
58
64
  export function continueHandedOnTrace(traceparent, traceId, run) {
59
65
  const parent = typeof traceparent === "string"
60
66
  ? readTraceContext({ traceparent })
61
67
  : undefined;
62
- if (!parent || parent.traceId !== w3cTraceIdOf(traceId)) {
68
+ if (!parent ||
69
+ parent.traceId !== w3cTraceIdOf(traceId) ||
70
+ activeOpenTelemetrySpanContext()?.traceId === parent.traceId) {
63
71
  return run();
64
72
  }
65
73
  return withRemoteOpenTelemetryParent({
@@ -70,7 +78,7 @@ export function continueHandedOnTrace(traceparent, traceId, run) {
70
78
  }
71
79
  /**
72
80
  * Whether OpenTelemetry interop runs now - `openTelemetry` on, beside
73
- * reporting to NestJS Observe (see `ObserveAgentSharedBuffer.isIngesting`) -
81
+ * reporting to NestJS Observe (see `ObserveAgentSharedBuffer.isReporting`) -
74
82
  * for what is set up before the module's options resolve: the microservice
75
83
  * dispatch hook, which a client is handed as it is instantiated. Off until
76
84
  * the module configures it.
@@ -85,6 +93,6 @@ export class OpenTelemetryInteropGate {
85
93
  }
86
94
  isOn() {
87
95
  return (this.options?.openTelemetry === true &&
88
- this.buffer?.isIngesting() === true);
96
+ this.buffer?.isReporting() === true);
89
97
  }
90
98
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.3.23",
3
+ "version": "0.3.25",
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",
@@ -163,14 +163,18 @@
163
163
  "@types/supertest": "7.2.1",
164
164
  "@types/ws": "8.18.1",
165
165
  "@vitest/coverage-v8": "4.1.11",
166
+ "amqp-connection-manager": "5.0.0",
167
+ "amqplib": "2.2.0",
166
168
  "bull": "4.16.5",
167
169
  "bullmq": "6.2.0",
170
+ "bullmq-otel": "2.0.1",
168
171
  "dd-trace": "6.23.0",
169
172
  "drizzle-orm": "0.45.4",
170
173
  "express": "5.2.1",
171
174
  "graphql": "16.14.2",
172
175
  "husky": "9.1.7",
173
176
  "ioredis": "6.0.0",
177
+ "kafkajs": "2.2.4",
174
178
  "lint-staged": "17.6.0",
175
179
  "mongodb": "7.6.0",
176
180
  "mongoose": "9.10.1",