@nestjs/observe 0.3.21 → 0.3.22

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 (34) hide show
  1. package/README.md +42 -13
  2. package/dist/agent/degraded-ingest.protocol.d.ts +20 -0
  3. package/dist/agent/degraded-ingest.protocol.js +25 -0
  4. package/dist/agent/detached-observe-worker.assembly.js +2 -1
  5. package/dist/agent/detached-observe-worker.d.ts +2 -0
  6. package/dist/agent/detached-observe-worker.js +7 -0
  7. package/dist/agent/observe-agent.shared-buffer.d.ts +36 -0
  8. package/dist/agent/observe-agent.shared-buffer.js +56 -1
  9. package/dist/agent/observe-agent.worker.d.ts +12 -0
  10. package/dist/agent/observe-agent.worker.js +55 -1
  11. package/dist/interfaces/observe-options.interface.d.ts +40 -2
  12. package/dist/observe.constants.d.ts +10 -0
  13. package/dist/observe.constants.js +10 -0
  14. package/dist/observe.module.js +3 -0
  15. package/dist/outgoing/http.integration.d.ts +34 -3
  16. package/dist/outgoing/http.integration.js +84 -17
  17. package/dist/outgoing/outgoing-observe-agent.service.d.ts +14 -1
  18. package/dist/outgoing/outgoing-observe-agent.service.js +24 -9
  19. package/dist/outgoing/outgoing-span.recorder.d.ts +11 -1
  20. package/dist/outgoing/outgoing-span.recorder.js +8 -2
  21. package/dist/protocols/http-observe-agent.service.js +25 -2
  22. package/dist/services/operation-trace.registry.d.ts +17 -2
  23. package/dist/services/operation-trace.registry.js +23 -8
  24. package/dist/services/tracer.service.d.ts +6 -0
  25. package/dist/services/tracer.service.js +11 -2
  26. package/dist/utils/default-trace-id-generator.util.d.ts +18 -0
  27. package/dist/utils/default-trace-id-generator.util.js +33 -0
  28. package/dist/utils/opentelemetry.util.d.ts +31 -0
  29. package/dist/utils/opentelemetry.util.js +52 -0
  30. package/dist/utils/trace-context.util.d.ts +91 -0
  31. package/dist/utils/trace-context.util.js +219 -0
  32. package/dist/utils/trace-id-generator-origin.util.d.ts +11 -0
  33. package/dist/utils/trace-id-generator-origin.util.js +26 -0
  34. package/package.json +14 -2
package/README.md CHANGED
@@ -43,16 +43,43 @@ unreachable collector never holds a request up. Recording it does cost the
43
43
  request path a microsecond or two per traced call - [Overhead](#overhead) has
44
44
  the numbers.
45
45
 
46
- ### Why not just OpenTelemetry?
47
-
48
- OpenTelemetry is the right answer when you need vendor neutrality across a
49
- polyglot estate, and this agent is not a replacement for it. It is a different
50
- trade: no collector to run, no exporter pipeline to configure, no manual
51
- instrumentation for the framework's own lifecycle — and spans named after your
52
- Nest classes and methods, which generic Node.js instrumentation cannot produce
53
- because it cannot see them. If you would otherwise spend a week wiring a
54
- collector and still not know which provider spent the time, this is the
55
- shortcut.
46
+ ### Observe and OpenTelemetry
47
+
48
+ OpenTelemetry is the vendor-neutral standard across a polyglot estate, and
49
+ this agent isn't a replacement for it: it works on its own, or beside the
50
+ OpenTelemetry you already have. What it brings to a Nest service is no
51
+ collector to run, no exporter pipeline to configure, no manual instrumentation
52
+ for the framework's own lifecycle — and spans named after your Nest classes
53
+ and methods, which generic Node.js instrumentation cannot produce because it
54
+ cannot see them. If you would otherwise spend a week wiring a collector and
55
+ still not know which provider spent the time, this is the shortcut.
56
+
57
+ It also runs beside OpenTelemetry, with `openTelemetry: true`. The agent then
58
+ continues and sends W3C `traceparent`, so a trace that runs through services
59
+ instrumented with OpenTelemetry stays one trace. In a Nest service that already
60
+ starts the OpenTelemetry Node SDK, it reports each request under the trace id
61
+ the SDK gave it - also when the request started the trace - and leaves
62
+ `traceparent` to the SDK on calls out of the service, so a request has one
63
+ trace id in both tools and every call carries one `traceparent`. The SDK keeps
64
+ its own spans, the agent adds the class-level ones. This is tested against the
65
+ SDK with its auto-instrumentations, on Express and Fastify, over `fetch`,
66
+ `node:http`, `pg` and Nest's own instrumentation. Without the option, the agent
67
+ speaks `x-request-id` alone and leaves any OpenTelemetry SDK in the process
68
+ alone.
69
+
70
+ It works only beside reporting to NestJS Observe. It turns on with the first
71
+ batch the collector accepts, and pauses - saying so in the log - while the
72
+ collector refuses the app's credentials, once batches have failed to get in
73
+ for a minute, or while the agent's worker is down, resuming with the next batch
74
+ the collector accepts. With `enabled: false`, or without credentials for the
75
+ hosted collector, it never turns on.
76
+
77
+ ```typescript
78
+ ObserveModule.forRoot({
79
+ serviceId: "orders-api",
80
+ openTelemetry: true,
81
+ });
82
+ ```
56
83
 
57
84
  ## Seeing it before installing
58
85
 
@@ -375,7 +402,8 @@ Once the module and the instrument are in place, the agent reports, with no furt
375
402
 
376
403
  - **Requests, GraphQL operations, RPC messages, WebSocket gateway messages, queue jobs and scheduled jobs**, each with its tree of provider method calls.
377
404
  - **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.
378
- - **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.
405
+ - **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.
406
+ - **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. Over HTTP only: microservice, gRPC and queue hops pass the trace id as `x-request-id` and job options, 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.
379
407
  - **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.
380
408
  - **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.
381
409
  - **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.
@@ -508,7 +536,8 @@ Every option, with its default. The [documentation](https://www.observe.nestjs.c
508
536
  | `runtimeMetricsInterval` | `60000` | Milliseconds between runtime samples; at least `30000`. |
509
537
  | `forwardLogs` | `false` | Sends the application's log lines, each correlated to the trace it was written in - see [Logs](https://www.observe.nestjs.com/documentation/sdk#logs). |
510
538
  | `redaction` | on | How log lines, error messages and captured requests are scrubbed before they leave the process: `enabled`, `useDefaultPatterns`, `patterns`, `keys` and `replacement`. |
511
- | `outgoing` | on | Query and outbound-HTTP spans. `false` turns both off; `{ database: false }` or `{ http: false }` one of them. |
539
+ | `outgoing` | on | Query and outbound-HTTP spans. `false` turns both off; `{ database: false }` or `{ http: false }` one of them. `{ http: { propagateTraceId, traceContext } }` tunes the `x-request-id` and `traceparent` headers outbound calls carry - `traceparent` only with `openTelemetry`. |
540
+ | `openTelemetry` | `false` | Continues and sends W3C `traceparent`, names a request after the W3C trace it is in, and follows an OpenTelemetry SDK running in the same process - see [Observe and OpenTelemetry](#observe-and-opentelemetry). Works only while the agent is reporting to NestJS Observe. Off, the agent reads and sends `x-request-id` alone. |
512
541
  | `http` | | `ignore`, `tags`, `setAttributes`, `getUserId`, `queryParamsObfuscateRegex`, `tracePreflights` and `capture` - see [Capturing failed and slow requests](#capturing-failed-and-slow-requests). |
513
542
  | `rpc`, `grpc` | | `ignore`, `tags`, `setAttributes` and `getUserId` for microservice and gRPC handlers. |
514
543
  | `graphql` | | The same four, once per GraphQL operation. |
@@ -523,7 +552,7 @@ Every option, with its default. The [documentation](https://www.observe.nestjs.c
523
552
  | Option | Default | What it does |
524
553
  | --------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
525
554
  | `sourceContext` | `true` | Attaches the source around each in-app frame of a captured error - see [What it records without any code](#what-it-records-without-any-code). `{ linesOfContext, maxFrames, sourceMaps }` tunes it. |
526
- | `traceIdGenerator` | the `x-request-id` header, else a UUIDv7 | Gives each request its trace id. |
555
+ | `traceIdGenerator` | the `x-request-id` header, else a UUIDv7 | Gives each request its trace id. With `openTelemetry` on, the default takes the W3C trace id first and keeps an `x-request-id` that names the same trace, and the W3C trace is still read beside whatever this returns, so outbound calls stay in the caller's trace. |
527
556
  | `traceIdKey` | `'traceId'` | The key the trace id is stored under in the request context. |
528
557
  | `attachTraceIdToLogs` | `true` | Adds the trace id to the `ConsoleLogger`'s own output, on Nest 11.2 and later. Sending lines to the dashboard is `forwardLogs`. |
529
558
  | `skipInstrumentation` | `() => false` | Returns `true` for a provider instance that must not be instrumented. Nest's `Reflector` and the `mongodb` driver's `MongoClient` and `Db` never are, whatever this returns. |
@@ -104,6 +104,26 @@ export declare function parseOveragePauseReason(msg: string): OveragePauseReason
104
104
  export declare const PAUSED_MESSAGE_PREFIX = "observe:paused-until=";
105
105
  /** The time sends are paused until, or null if this is not that line. */
106
106
  export declare function parsePausedMessage(msg: string): number | null;
107
+ /**
108
+ * How the detached worker tells the main thread a batch did not get in:
109
+ * `refused` when the collector turned the credentials away (401 or 403), and
110
+ * `failed` for anything else that kept a batch out - a 429, an unreachable
111
+ * collector, any other status, a fault in the worker. A batch that got in
112
+ * says so with its degraded verdict instead.
113
+ *
114
+ * Read for OpenTelemetry interop, which runs only while the collector takes
115
+ * this app's telemetry - see `ObserveAgentSharedBuffer.isIngesting`.
116
+ */
117
+ export declare const NOT_INGESTED_MESSAGE_PREFIX = "observe:not-ingested=";
118
+ export type NotIngestedReason = "refused" | "failed";
119
+ /** Why a batch did not get in, or null if this is not that line. */
120
+ export declare function parseNotIngestedMessage(msg: string): NotIngestedReason | null;
121
+ /**
122
+ * How long batches may keep failing to get in before the collector counts as
123
+ * no longer taking this app's telemetry - a collector restarting, a network
124
+ * blip, a short rate-limit pause. Refused credentials end it at once.
125
+ */
126
+ export declare const NOT_INGESTED_GRACE_MS: number;
107
127
  /**
108
128
  * Duration past which the collector treats an execution as notable, in
109
129
  * milliseconds.
@@ -86,6 +86,31 @@ export function parsePausedMessage(msg) {
86
86
  const until = Number(msg.slice(PAUSED_MESSAGE_PREFIX.length));
87
87
  return Number.isFinite(until) ? until : null;
88
88
  }
89
+ /**
90
+ * How the detached worker tells the main thread a batch did not get in:
91
+ * `refused` when the collector turned the credentials away (401 or 403), and
92
+ * `failed` for anything else that kept a batch out - a 429, an unreachable
93
+ * collector, any other status, a fault in the worker. A batch that got in
94
+ * says so with its degraded verdict instead.
95
+ *
96
+ * Read for OpenTelemetry interop, which runs only while the collector takes
97
+ * this app's telemetry - see `ObserveAgentSharedBuffer.isIngesting`.
98
+ */
99
+ export const NOT_INGESTED_MESSAGE_PREFIX = "observe:not-ingested=";
100
+ /** Why a batch did not get in, or null if this is not that line. */
101
+ export function parseNotIngestedMessage(msg) {
102
+ if (!msg.startsWith(NOT_INGESTED_MESSAGE_PREFIX)) {
103
+ return null;
104
+ }
105
+ const reason = msg.slice(NOT_INGESTED_MESSAGE_PREFIX.length);
106
+ return reason === "refused" || reason === "failed" ? reason : null;
107
+ }
108
+ /**
109
+ * How long batches may keep failing to get in before the collector counts as
110
+ * no longer taking this app's telemetry - a collector restarting, a network
111
+ * blip, a short rate-limit pause. Refused credentials end it at once.
112
+ */
113
+ export const NOT_INGESTED_GRACE_MS = 60 * 1000;
89
114
  /**
90
115
  * Duration past which the collector treats an execution as notable, in
91
116
  * milliseconds.
@@ -1,4 +1,4 @@
1
- import { DEGRADED_MESSAGE_PREFIX, PAUSED_MESSAGE_PREFIX, } from "./degraded-ingest.protocol.js";
1
+ import { DEGRADED_MESSAGE_PREFIX, NOT_INGESTED_MESSAGE_PREFIX, PAUSED_MESSAGE_PREFIX, } from "./degraded-ingest.protocol.js";
2
2
  import { detachedObserveWorker } from "./detached-observe-worker.js";
3
3
  import { createTelemetrySanitizer, SECTION_SHAPES, } from "./telemetry-wire-contract.js";
4
4
  import { describeIngestRefusal } from "../utils/ingest-refusal.util.js";
@@ -27,6 +27,7 @@ export function detachedWorkerData(input) {
27
27
  wireShapes: SECTION_SHAPES,
28
28
  degradedPrefix: DEGRADED_MESSAGE_PREFIX,
29
29
  pausedPrefix: PAUSED_MESSAGE_PREFIX,
30
+ notIngestedPrefix: NOT_INGESTED_MESSAGE_PREFIX,
30
31
  sdkVersion: readSdkVersion(),
31
32
  };
32
33
  return { sharedBuffer: input.sharedBuffer, config };
@@ -23,6 +23,8 @@ export interface DetachedWorkerConfig {
23
23
  degradedPrefix: string;
24
24
  /** `PAUSED_MESSAGE_PREFIX`, as data, for the same reason. */
25
25
  pausedPrefix: string;
26
+ /** `NOT_INGESTED_MESSAGE_PREFIX`, as data, for the same reason. */
27
+ notIngestedPrefix: string;
26
28
  /**
27
29
  * This package's version (`readSdkVersion`), read on the main thread: the
28
30
  * worker runs as eval'd source and cannot resolve a manifest of its own.
@@ -51,6 +51,7 @@ describeRefusal) => {
51
51
  // that `parseDegradedMessage` still matches.
52
52
  const degradedPrefix = config.degradedPrefix;
53
53
  const pausedPrefix = config.pausedPrefix;
54
+ const notIngestedPrefix = config.notIngestedPrefix;
54
55
  /**
55
56
  * Built here, used only when the collector answers 400. The shapes travel
56
57
  * through `workerData` (they are plain JSON); the factory travels as source.
@@ -367,6 +368,7 @@ describeRefusal) => {
367
368
  const retryBody = await retry.text().catch(() => "");
368
369
  parentPort.postMessage(`Error: Telemetry batch was rejected (400), repaired (${summary}), and rejected again ` +
369
370
  `(${retry.status})${retryBody ? ` - ${retryBody.slice(0, 500)}` : ""}. The batch was dropped.`);
371
+ parentPort.postMessage(`${notIngestedPrefix}failed`);
370
372
  }
371
373
  return true;
372
374
  }
@@ -431,6 +433,7 @@ describeRefusal) => {
431
433
  : `Error: Could not reach the collector at ${telemetryUrl}` +
432
434
  (reason ? ` (${reason})` : "") +
433
435
  `. Check that it is running and that \`endpoint\` points at it.`);
436
+ parentPort.postMessage(`${notIngestedPrefix}failed`);
434
437
  // Discarded rather than retried - `clearBuffer` in `finally` - which
435
438
  // is the right call for a fixed-size buffer the application is still
436
439
  // writing into: holding it for a retry would block every batch behind
@@ -451,6 +454,7 @@ describeRefusal) => {
451
454
  // The slot is left alone until then, which a final flush would
452
455
  // otherwise read as a send still in progress.
453
456
  parentPort.postMessage(`${pausedPrefix}${pausedUntil}`);
457
+ parentPort.postMessage(`${notIngestedPrefix}refused`);
454
458
  // Said plainly, and once. The batch is well-formed and the
455
459
  // credentials are not accepted for this application; left as a
456
460
  // generic transport failure this reads as a network problem, and the
@@ -476,6 +480,7 @@ describeRefusal) => {
476
480
  // The slot is left alone until then, which a final flush would
477
481
  // otherwise read as a send still in progress.
478
482
  parentPort.postMessage(`${pausedPrefix}${pausedUntil}`);
483
+ parentPort.postMessage(`${notIngestedPrefix}failed`);
479
484
  // The body says which refusal this is - a quota, a quota frozen by
480
485
  // a declined payment, or a rate cap - and each needs a different
481
486
  // fix from the operator. Parsed defensively: a rate-cap body is
@@ -501,6 +506,7 @@ describeRefusal) => {
501
506
  const errorBody = await response.text().catch(() => "");
502
507
  parentPort.postMessage(`Error: Failed to send data. ${response.statusText} (${response.status})` +
503
508
  (errorBody ? ` - ${errorBody.slice(0, 500)}` : ""));
509
+ parentPort.postMessage(`${notIngestedPrefix}failed`);
504
510
  return true;
505
511
  }
506
512
  // Accepted, so whatever refused these credentials no longer does: a
@@ -572,6 +578,7 @@ describeRefusal) => {
572
578
  (causeText === undefined ? "" : ` (cause: ${causeText})`) +
573
579
  `. This is most likely a fault in the observe agent rather than a ` +
574
580
  `connectivity problem; please report it.`);
581
+ parentPort.postMessage(`${notIngestedPrefix}failed`);
575
582
  return true;
576
583
  }
577
584
  finally {
@@ -84,6 +84,17 @@ export declare class ObserveAgentSharedBuffer {
84
84
  * not a moment longer.
85
85
  */
86
86
  private errorsOnly;
87
+ /**
88
+ * Whether the collector is taking this app's telemetry - see `isIngesting`.
89
+ * False until it accepts a first batch: what has not been shown to reach
90
+ * NestJS Observe does not count as reaching it.
91
+ */
92
+ private ingesting;
93
+ /**
94
+ * When batches began failing to get in, since the last one that did; zero
95
+ * while they get in.
96
+ */
97
+ private failingSince;
87
98
  /**
88
99
  * Requests and jobs that errors-only ingest withheld from the batch being
89
100
  * built, cleared with it.
@@ -115,6 +126,31 @@ export declare class ObserveAgentSharedBuffer {
115
126
  isDegraded(): boolean;
116
127
  /** Whether only server errors are being sent, until the same window lapses. */
117
128
  isErrorsOnly(): boolean;
129
+ /**
130
+ * Whether the collector is taking this app's telemetry: from the first
131
+ * batch it accepts, until it refuses the app's credentials, the worker
132
+ * stops, or batches have kept failing to get in for
133
+ * `NOT_INGESTED_GRACE_MS` - and again from the next batch it accepts.
134
+ *
135
+ * OpenTelemetry interop runs on it (see `openTelemetry`): the agent reads
136
+ * and sends `traceparent`, and follows an OpenTelemetry SDK in the process,
137
+ * only while it is also reporting to NestJS Observe. So an agent that sends
138
+ * Observe nothing - `enabled: false`, no credentials, credentials the
139
+ * collector refuses - never turns it on.
140
+ */
141
+ isIngesting(): boolean;
142
+ /** The collector accepted a batch, whatever it then kept of it. */
143
+ recordAccepted(): void;
144
+ /** The collector refused the app's credentials. */
145
+ recordRefused(): void;
146
+ /**
147
+ * A batch did not get in - see `NotIngestedReason`. `pausedUntil` is when a
148
+ * paused worker sends again: nothing gets in before then, so a pause longer
149
+ * than the grace ends ingesting at once rather than after it.
150
+ */
151
+ recordFailed(pausedUntil?: number, now?: number): void;
152
+ /** The worker stopped; a restarted one has to get a batch in again. */
153
+ recordStopped(): void;
118
154
  /**
119
155
  * What errors-only ingest makes of one execution: whether it is sent.
120
156
  *
@@ -11,7 +11,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
11
  return function (target, key) { decorator(target, key, paramIndex); }
12
12
  };
13
13
  var ObserveAgentSharedBuffer_1;
14
- import { countTraceNodes, DEGRADED_TTL_MS, isNotableSnapshot, isServerErrorSnapshot, } from "./degraded-ingest.protocol.js";
14
+ import { countTraceNodes, DEGRADED_TTL_MS, isNotableSnapshot, isServerErrorSnapshot, NOT_INGESTED_GRACE_MS, } from "./degraded-ingest.protocol.js";
15
15
  import { MAX_BATCH_ITEMS } from "./telemetry-wire-contract.js";
16
16
  import { Inject, Injectable, Logger, Optional } from "@nestjs/common";
17
17
  import { Counter, Summary } from "../custom-metrics/index.js";
@@ -209,6 +209,17 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
209
209
  * not a moment longer.
210
210
  */
211
211
  errorsOnly = false;
212
+ /**
213
+ * Whether the collector is taking this app's telemetry - see `isIngesting`.
214
+ * False until it accepts a first batch: what has not been shown to reach
215
+ * NestJS Observe does not count as reaching it.
216
+ */
217
+ ingesting = false;
218
+ /**
219
+ * When batches began failing to get in, since the last one that did; zero
220
+ * while they get in.
221
+ */
222
+ failingSince = 0;
212
223
  /**
213
224
  * Requests and jobs that errors-only ingest withheld from the batch being
214
225
  * built, cleared with it.
@@ -247,6 +258,50 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
247
258
  isErrorsOnly() {
248
259
  return this.errorsOnly && this.isDegraded();
249
260
  }
261
+ /**
262
+ * Whether the collector is taking this app's telemetry: from the first
263
+ * batch it accepts, until it refuses the app's credentials, the worker
264
+ * stops, or batches have kept failing to get in for
265
+ * `NOT_INGESTED_GRACE_MS` - and again from the next batch it accepts.
266
+ *
267
+ * OpenTelemetry interop runs on it (see `openTelemetry`): the agent reads
268
+ * and sends `traceparent`, and follows an OpenTelemetry SDK in the process,
269
+ * only while it is also reporting to NestJS Observe. So an agent that sends
270
+ * Observe nothing - `enabled: false`, no credentials, credentials the
271
+ * collector refuses - never turns it on.
272
+ */
273
+ isIngesting() {
274
+ return this.ingesting;
275
+ }
276
+ /** The collector accepted a batch, whatever it then kept of it. */
277
+ recordAccepted() {
278
+ this.ingesting = true;
279
+ this.failingSince = 0;
280
+ }
281
+ /** The collector refused the app's credentials. */
282
+ recordRefused() {
283
+ this.ingesting = false;
284
+ this.failingSince = 0;
285
+ }
286
+ /**
287
+ * A batch did not get in - see `NotIngestedReason`. `pausedUntil` is when a
288
+ * paused worker sends again: nothing gets in before then, so a pause longer
289
+ * than the grace ends ingesting at once rather than after it.
290
+ */
291
+ recordFailed(pausedUntil = 0, now = Date.now()) {
292
+ if (this.failingSince === 0) {
293
+ this.failingSince = now;
294
+ }
295
+ if (Math.max(now, pausedUntil) - this.failingSince >=
296
+ NOT_INGESTED_GRACE_MS) {
297
+ this.ingesting = false;
298
+ }
299
+ }
300
+ /** The worker stopped; a restarted one has to get a batch in again. */
301
+ recordStopped() {
302
+ this.ingesting = false;
303
+ this.failingSince = 0;
304
+ }
250
305
  /**
251
306
  * What errors-only ingest makes of one execution: whether it is sent.
252
307
  *
@@ -164,6 +164,18 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
164
164
  /** The worker's messages, errors, and the restart when it dies. */
165
165
  private watchWorker;
166
166
  handleMessage(msg: string): void;
167
+ /**
168
+ * Whether OpenTelemetry interop was last said to be on - see
169
+ * `reportOpenTelemetryInterop`. It starts off, as the buffer's state does.
170
+ */
171
+ private reportedOpenTelemetry;
172
+ /**
173
+ * Says when OpenTelemetry interop turns on or off, with `openTelemetry` on:
174
+ * it runs only while the collector takes this app's telemetry (see
175
+ * `ObserveAgentSharedBuffer.isIngesting`), and a `traceparent` that stops
176
+ * going out with no word would read as a bug in the agent.
177
+ */
178
+ private reportOpenTelemetryInterop;
167
179
  /** Whether this process has said the collector accepted its first batch. */
168
180
  private reportedConnection;
169
181
  /**
@@ -21,7 +21,7 @@ import { ProfileUploader } from "../profiling/profile-uploader.js";
21
21
  import { setActiveSliceRecorder, SpanSliceRecorder, } from "../profiling/span-slice-recorder.js";
22
22
  import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.service.js";
23
23
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
24
- import { parseDegradedMessage, parseOveragePauseReason, parsePausedMessage, } from "./degraded-ingest.protocol.js";
24
+ import { NOT_INGESTED_GRACE_MS, parseDegradedMessage, parseNotIngestedMessage, parseOveragePauseReason, parsePausedMessage, } from "./degraded-ingest.protocol.js";
25
25
  import { detachedWorkerData, detachedWorkerSource, } from "./detached-observe-worker.assembly.js";
26
26
  import { describeMissingCredentials, SIGN_UP_URL, } from "./credentials-notice.js";
27
27
  import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
@@ -155,6 +155,10 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
155
155
  else {
156
156
  this.initializeWorker();
157
157
  }
158
+ if (this.options.openTelemetry === true && this.sendsNothing) {
159
+ this.logger.warn("openTelemetry is on, but this agent reports nothing to NestJS Observe, so OpenTelemetry interop stays off: " +
160
+ "it runs only beside reporting to Observe.");
161
+ }
158
162
  this.flushInterval = setInterval(() => this.flush(), flushIntervalTime);
159
163
  if (!this.sendsNothing) {
160
164
  this.startRuntimeMetrics();
@@ -552,6 +556,10 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
552
556
  this.logger.debug("Worker exited on shutdown.");
553
557
  return;
554
558
  }
559
+ // Whatever comes next, this worker gets nothing in any more: a
560
+ // restarted one has to get a batch in again first.
561
+ this.observeAgentSharedBuffer.recordStopped();
562
+ this.reportOpenTelemetryInterop("stopped");
555
563
  if (code !== 0) {
556
564
  this.logger.error(`Worker stopped with exit code ${code}. Restarting worker...`);
557
565
  this.initializeWorker(); // Restart the worker
@@ -567,8 +575,22 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
567
575
  this.sendsPausedUntil = pausedUntil;
568
576
  return;
569
577
  }
578
+ const notIngested = parseNotIngestedMessage(msg);
579
+ if (notIngested !== null) {
580
+ if (notIngested === "refused") {
581
+ this.observeAgentSharedBuffer.recordRefused();
582
+ }
583
+ else {
584
+ // After the paused line, when the worker pauses: it posts that first.
585
+ this.observeAgentSharedBuffer.recordFailed(this.sendsPausedUntil);
586
+ }
587
+ this.reportOpenTelemetryInterop(notIngested);
588
+ return;
589
+ }
570
590
  const mode = parseDegradedMessage(msg);
571
591
  if (mode !== null) {
592
+ this.observeAgentSharedBuffer.recordAccepted();
593
+ this.reportOpenTelemetryInterop();
572
594
  this.reportFirstAcceptedBatch();
573
595
  this.applyIngestMode(mode, parseOveragePauseReason(msg));
574
596
  return;
@@ -581,6 +603,38 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
581
603
  this.logger.debug(msg);
582
604
  }
583
605
  }
606
+ /**
607
+ * Whether OpenTelemetry interop was last said to be on - see
608
+ * `reportOpenTelemetryInterop`. It starts off, as the buffer's state does.
609
+ */
610
+ reportedOpenTelemetry = false;
611
+ /**
612
+ * Says when OpenTelemetry interop turns on or off, with `openTelemetry` on:
613
+ * it runs only while the collector takes this app's telemetry (see
614
+ * `ObserveAgentSharedBuffer.isIngesting`), and a `traceparent` that stops
615
+ * going out with no word would read as a bug in the agent.
616
+ */
617
+ reportOpenTelemetryInterop(why) {
618
+ if (this.options.openTelemetry !== true) {
619
+ return;
620
+ }
621
+ const on = this.observeAgentSharedBuffer.isIngesting();
622
+ if (on === this.reportedOpenTelemetry) {
623
+ return;
624
+ }
625
+ this.reportedOpenTelemetry = on;
626
+ if (on) {
627
+ this.logger.log("OpenTelemetry interop is on: the collector is taking this app's telemetry, so traceparent is read and sent.");
628
+ return;
629
+ }
630
+ const reason = why === "refused"
631
+ ? "the collector refused this app's credentials"
632
+ : why === "stopped"
633
+ ? "the telemetry worker stopped"
634
+ : `no batch has reached the collector for ${NOT_INGESTED_GRACE_MS / 1000} seconds`;
635
+ this.logger.warn(`OpenTelemetry interop is paused: ${reason}. It runs only while the agent is reporting to NestJS Observe, ` +
636
+ `and resumes with the next batch the collector accepts.`);
637
+ }
584
638
  /** Whether this process has said the collector accepted its first batch. */
585
639
  reportedConnection = false;
586
640
  /**
@@ -61,8 +61,16 @@ export interface CreateObserveModuleOptions {
61
61
  * For HTTP protocols, the request object is passed to the function.
62
62
  * For non-HTTP protocols, the request object will be contextual and may not be available.
63
63
  * The default implementation uses the 'x-request-id' header if available,
64
- * or mints a time-ordered UUID (version 7) if the header is not present -
65
- * an id the collector can locate in time without a scan.
64
+ * or mints a time-ordered UUID (version 7) if not - an id the collector can
65
+ * locate in time without a scan.
66
+ *
67
+ * With `openTelemetry` on, the default names a request in a W3C trace after
68
+ * that trace instead: the trace id of its `traceparent`, written as a UUID,
69
+ * or of the span an OpenTelemetry SDK in the same process opened for it.
70
+ * An 'x-request-id' that names the same trace is kept. Whatever this
71
+ * returns, the W3C trace is then still read alongside it: outbound calls
72
+ * carry it on, so the request stays in the OpenTelemetry trace its caller
73
+ * is in.
66
74
  * @default (req) => req.headers['x-request-id'] || uuidv7()
67
75
  */
68
76
  traceIdGenerator?: (req: unknown) => string;
@@ -590,6 +598,36 @@ export interface ObserveOptions {
590
598
  */
591
599
  getUserId?: (call: any) => string;
592
600
  };
601
+ /**
602
+ * Interoperates with OpenTelemetry. Off by default, and off, the agent
603
+ * reads and sends `x-request-id` alone, as it always has.
604
+ *
605
+ * On:
606
+ * - A request that arrives in a W3C trace (`traceparent`) is reported under
607
+ * that trace's id, written as a UUID, so it has the id the rest of the
608
+ * trace has in the caller's OpenTelemetry backend. An `x-request-id` is
609
+ * kept when it names the same trace, which is what another service
610
+ * running the agent sends.
611
+ * - Outbound `fetch` and `node:http` calls carry a `traceparent` beside
612
+ * `x-request-id` - see `outgoing.http.traceContext`.
613
+ * - With an OpenTelemetry SDK running in the same process - or an SDK
614
+ * built on it, as Sentry's Node SDK is from version 8 - a request is
615
+ * reported under the trace of the server span the SDK opened for it, the
616
+ * request that starts a trace included, and `traceparent` on outbound
617
+ * calls is left to the SDK.
618
+ *
619
+ * A `traceIdGenerator` passed to `createObserveModule()` still names the
620
+ * trace; the W3C one is carried on beside it.
621
+ *
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.
628
+ * @default false
629
+ */
630
+ openTelemetry?: boolean;
593
631
  /**
594
632
  * Spans for what leaves the process: database queries (`pg`, `mysql2`, `mssql`,
595
633
  * `mongodb` - and so every ORM built on them) and outbound HTTP requests
@@ -10,6 +10,16 @@ export declare const CALLER_METADATA_KEY = "#caller";
10
10
  * snapshot.
11
11
  */
12
12
  export declare const TRACE_REGISTRY_KEY = "#registryKey";
13
+ /**
14
+ * Where a store keeps the W3C trace context its operation arrived with - see
15
+ * `readTraceContext`. Absent when none came in; outbound calls then derive
16
+ * their `traceparent` from the trace id instead.
17
+ *
18
+ * Apart from `traceIdKey` because the two can disagree: an `x-request-id`
19
+ * from a proxy names the Observe trace, while the `traceparent` beside it
20
+ * names the OpenTelemetry trace the caller is in, and both are passed on.
21
+ */
22
+ export declare const TRACE_CONTEXT_KEY = "#traceContext";
13
23
  /**
14
24
  * The job option the enqueuing side stamps the active trace id into. Both
15
25
  * BullMQ and Bull persist unknown options verbatim, so it survives the trip
@@ -10,6 +10,16 @@ export const CALLER_METADATA_KEY = "#caller";
10
10
  * snapshot.
11
11
  */
12
12
  export const TRACE_REGISTRY_KEY = "#registryKey";
13
+ /**
14
+ * Where a store keeps the W3C trace context its operation arrived with - see
15
+ * `readTraceContext`. Absent when none came in; outbound calls then derive
16
+ * their `traceparent` from the trace id instead.
17
+ *
18
+ * Apart from `traceIdKey` because the two can disagree: an `x-request-id`
19
+ * from a proxy names the Observe trace, while the `traceparent` beside it
20
+ * names the OpenTelemetry trace the caller is in, and both are passed on.
21
+ */
22
+ export const TRACE_CONTEXT_KEY = "#traceContext";
13
23
  /**
14
24
  * The job option the enqueuing side stamps the active trace id into. Both
15
25
  * BullMQ and Bull persist unknown options verbatim, so it survives the trip
@@ -37,6 +37,7 @@ import { TraceSamplerService } from "./services/trace-sampler.service.js";
37
37
  import { TracerService } from "./services/tracer.service.js";
38
38
  import { assertModuleOptions } from "./utils/assert-module-options.util.js";
39
39
  import { defaultTraceIdGenerator } from "./utils/default-trace-id-generator.util.js";
40
+ import { recordTraceIdGeneratorOrigin } from "./utils/trace-id-generator-origin.util.js";
40
41
  import { fitServiceVersion, MAX_SERVICE_VERSION_LENGTH, } from "./utils/fit-service-version.util.js";
41
42
  import { fitToLength } from "./utils/fit-to-length.util.js";
42
43
  import { inferServiceVersion } from "./utils/infer-service-version.util.js";
@@ -125,6 +126,8 @@ export function createObserveModule(options = {}) {
125
126
  options.traceIdKey ??= "traceId";
126
127
  options.attachTraceIdToLogs ??= true;
127
128
  options.traceIdGenerator ??= defaultTraceIdGenerator;
129
+ // While the options are a plain object - see the function.
130
+ recordTraceIdGeneratorOrigin(options);
128
131
  options.skipInstrumentation ??= () => false;
129
132
  // Inert until the agent starts with `outgoing.llm` on - see the function.
130
133
  // `forRoot` puts the original back if its options turn model calls off.
@@ -1,4 +1,5 @@
1
1
  import { LogRedactor } from "../utils/log-redactor.js";
2
+ import { TraceContext } from "../utils/trace-context.util.js";
2
3
  import { OutgoingSpanRecorder } from "./outgoing-span.recorder.js";
3
4
  export interface OutgoingHttpOptions {
4
5
  /**
@@ -11,10 +12,34 @@ export interface OutgoingHttpOptions {
11
12
  * carries one. It is what a downstream service running `@nestjs/observe`
12
13
  * adopts as its own trace id, which makes HTTP-to-HTTP calls one trace with
13
14
  * no application code. A function narrows it to the URLs it returns true
14
- * for - your own services, say, and not third parties.
15
+ * for - your own services, say, and not third parties. It narrows
16
+ * `traceContext` too.
15
17
  * @default true
16
18
  */
17
19
  propagateTraceId?: boolean | ((url: string) => boolean);
20
+ /**
21
+ * Send W3C Trace Context beside `x-request-id`: a `traceparent` naming the
22
+ * trace and this call's span, and the `tracestate` the operation arrived
23
+ * with, if any. It is what a service instrumented with OpenTelemetry - in
24
+ * any language - reads, so the call stays one trace through it. The trace
25
+ * is the one the operation's own `traceparent` named, when it arrived with
26
+ * one. Never added to a request that already carries a `traceparent`, nor
27
+ * while an OpenTelemetry SDK that propagates W3C Trace Context runs in the
28
+ * same process: its instrumentations write the header on the calls they
29
+ * cover, and a request takes only one.
30
+ *
31
+ * Only with `openTelemetry` on, and only while the agent is reporting to
32
+ * NestJS Observe; otherwise no `traceparent` is sent.
33
+ * @default true, with `openTelemetry` on
34
+ */
35
+ traceContext?: boolean;
36
+ }
37
+ /** What an outbound call is told about the operation making it. */
38
+ export interface OutgoingTrace {
39
+ /** The operation's trace id, as `x-request-id` carries it. */
40
+ traceId: string;
41
+ /** The `traceparent` the operation arrived with, when it had one. */
42
+ traceContext?: TraceContext;
18
43
  }
19
44
  /**
20
45
  * Spans for outbound HTTP, from the diagnostics channels Node publishes on its
@@ -28,9 +53,15 @@ export interface OutgoingHttpOptions {
28
53
  *
29
54
  * Returns the function that removes every subscription.
30
55
  */
31
- export declare function subscribeOutgoingHttp(recorder: OutgoingSpanRecorder, currentTraceId: () => string | undefined, options?: OutgoingHttpOptions,
56
+ export declare function subscribeOutgoingHttp(recorder: OutgoingSpanRecorder, currentTrace: () => OutgoingTrace | undefined, options?: OutgoingHttpOptions,
32
57
  /**
33
58
  * Read per request rather than passed once: the redactor is configured
34
59
  * after the module's options resolve, which can be after this subscribes.
35
60
  */
36
- getRedactor?: () => LogRedactor | null): () => void;
61
+ getRedactor?: () => LogRedactor | null,
62
+ /**
63
+ * Whether calls carry W3C Trace Context now: with `openTelemetry` on and
64
+ * `traceContext` not off, while the collector takes this app's telemetry.
65
+ * Off unless given.
66
+ */
67
+ traceContextOn?: () => boolean): () => void;