@nestjs/observe 0.3.22 → 0.3.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +71 -14
  2. package/dist/agent/degraded-ingest.protocol.d.ts +2 -8
  3. package/dist/agent/degraded-ingest.protocol.js +2 -8
  4. package/dist/agent/detached-observe-worker.assembly.d.ts +2 -0
  5. package/dist/agent/detached-observe-worker.assembly.js +3 -0
  6. package/dist/agent/detached-observe-worker.d.ts +8 -0
  7. package/dist/agent/detached-observe-worker.js +20 -2
  8. package/dist/agent/observe-agent.shared-buffer.d.ts +48 -22
  9. package/dist/agent/observe-agent.shared-buffer.js +94 -34
  10. package/dist/agent/observe-agent.worker.d.ts +16 -21
  11. package/dist/agent/observe-agent.worker.js +67 -74
  12. package/dist/agent/observe-reporting.util.d.ts +35 -0
  13. package/dist/agent/observe-reporting.util.js +69 -0
  14. package/dist/interfaces/observe-options.interface.d.ts +67 -13
  15. package/dist/observe.constants.d.ts +7 -0
  16. package/dist/observe.constants.js +7 -0
  17. package/dist/observe.module.js +50 -4
  18. package/dist/otlp/otlp-encoders.d.ts +26 -0
  19. package/dist/otlp/otlp-encoders.js +296 -0
  20. package/dist/otlp/otlp-export-grant.d.ts +34 -0
  21. package/dist/otlp/otlp-export-grant.js +22 -0
  22. package/dist/otlp/otlp-options.interface.d.ts +59 -0
  23. package/dist/otlp/otlp-options.interface.js +1 -0
  24. package/dist/otlp/otlp-settings.util.d.ts +38 -0
  25. package/dist/otlp/otlp-settings.util.js +154 -0
  26. package/dist/otlp/otlp-span.mapper.d.ts +73 -0
  27. package/dist/otlp/otlp-span.mapper.js +345 -0
  28. package/dist/otlp/otlp-trace-exporter.service.d.ts +130 -0
  29. package/dist/otlp/otlp-trace-exporter.service.js +497 -0
  30. package/dist/outgoing/http.integration.d.ts +6 -4
  31. package/dist/outgoing/http.integration.js +3 -3
  32. package/dist/outgoing/outgoing-observe-agent.service.d.ts +2 -2
  33. package/dist/outgoing/outgoing-observe-agent.service.js +1 -1
  34. package/dist/outgoing/sql-statement.util.js +2 -2
  35. package/dist/protocols/http-observe-agent.service.d.ts +1 -8
  36. package/dist/protocols/http-observe-agent.service.js +28 -21
  37. package/dist/protocols/job-trace-runner.d.ts +11 -0
  38. package/dist/protocols/job-trace-runner.js +42 -8
  39. package/dist/protocols/rpc-observe-agent.service.d.ts +5 -0
  40. package/dist/protocols/rpc-observe-agent.service.js +43 -3
  41. package/dist/services/operation-trace.registry.d.ts +29 -1
  42. package/dist/services/operation-trace.registry.js +46 -5
  43. package/dist/utils/default-trace-id-generator.util.js +6 -2
  44. package/dist/utils/opentelemetry.util.d.ts +26 -0
  45. package/dist/utils/opentelemetry.util.js +48 -0
  46. package/dist/utils/trace-handoff.util.d.ts +45 -0
  47. package/dist/utils/trace-handoff.util.js +90 -0
  48. package/package.json +13 -12
package/README.md CHANGED
@@ -61,18 +61,24 @@ starts the OpenTelemetry Node SDK, it reports each request under the trace id
61
61
  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
- 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.
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
70
+ 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.
69
74
 
70
75
  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
+ 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.
76
82
 
77
83
  ```typescript
78
84
  ObserveModule.forRoot({
@@ -81,6 +87,12 @@ ObserveModule.forRoot({
81
87
  });
82
88
  ```
83
89
 
90
+ With `otlp` set as well, the agent exports the spans it records to the
91
+ OpenTelemetry backend you already run - a collector, Jaeger, Tempo or any
92
+ vendor - on the same trace ids, so the Nest service's spans sit in the same
93
+ waterfall as the rest of the trace. See
94
+ [Exporting to OpenTelemetry](#exporting-to-opentelemetry).
95
+
84
96
  ## Seeing it before installing
85
97
 
86
98
  **[observe-demo.nestjs.com](https://www.observe-demo.nestjs.com/dashboard)** is the whole
@@ -403,7 +415,7 @@ Once the module and the instrument are in place, the agent reports, with no furt
403
415
  - **Requests, GraphQL operations, RPC messages, WebSocket gateway messages, queue jobs and scheduled jobs**, each with its tree of provider method calls.
404
416
  - **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.
405
417
  - **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.
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.
407
419
  - **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.
408
420
  - **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.
409
421
  - **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.
@@ -513,6 +525,49 @@ Declarations are checked when the application starts, and whatever fails is logg
513
525
 
514
526
  SLOs need a plan that has them - Scale or Enterprise. On any other plan, declarations are sent and ignored. The [documentation](https://www.observe.nestjs.com/documentation/sdk#declaring-objectives-in-code) has the rest.
515
527
 
528
+ ## Exporting to OpenTelemetry
529
+
530
+ With `openTelemetry: true`, `otlp` exports the traces the agent records as OpenTelemetry spans, over OTLP/HTTP, to a receiver of your own - an OpenTelemetry Collector, Jaeger, Grafana Tempo, Honeycomb, Datadog's agent, or any vendor that takes OTLP. A request that arrived with a `traceparent` goes under the caller's span, and each call it makes is the parent of what the service it calls exports, so the Nest service's spans land in the same trace, in the same waterfall, as the rest of your system.
531
+
532
+ ```typescript
533
+ ObserveModule.forRoot({
534
+ serviceId: "orders-api",
535
+ openTelemetry: true,
536
+ otlp: {
537
+ endpoint: "https://api.honeycomb.io",
538
+ headers: { "x-honeycomb-team": process.env.HONEYCOMB_API_KEY! },
539
+ },
540
+ });
541
+ ```
542
+
543
+ Export runs beside what the agent sends to NestJS Observe, never instead of it, and every plan includes it:
544
+
545
+ - **Paid plans** export every trace the agent records, ahead of anything NestJS Observe does with its own copy: an overage trim or a paused overage changes what the dashboard keeps, not what is exported.
546
+ - **Free** exports what NestJS Observe keeps. Once your apps send 30,000 events in one UTC day, or the month's allowance is used, most waterfalls are paused, and the requests and jobs behind them are exported as their own spans, without the spans under them; server errors, failed jobs and anything over 1 s keep their full traces in both places. While the collector can't be reached, what NestJS Observe keeps can't be known, so Free's export pauses a few minutes into the outage and resumes with the next batch the collector accepts.
547
+
548
+ Which applies is the collector's to say: its reply to every batch the agent sends carries what the app's plan includes - the plan of the account that pays for the project. Export starts with the first batch the collector accepts and pauses whenever OpenTelemetry interop does, and the log says when it turns on and how. Without `openTelemetry: true`, without the `appKey` and `appSecret` the hosted collector needs, or with `enabled: false`, nothing is exported, and the agent says why at start-up. A proxy at `endpoint` that adds the credentials on the way to NestJS Observe counts as reporting to it.
549
+
550
+ `otlp: true` takes everything from the standard variables instead, as an OpenTelemetry SDK would: `OTEL_EXPORTER_OTLP_ENDPOINT` (or `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`), `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_EXPORTER_OTLP_PROTOCOL`, `OTEL_EXPORTER_OTLP_COMPRESSION`, `OTEL_EXPORTER_OTLP_TIMEOUT`, `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES`, with their `_TRACES_` forms. Options set in code win over them. The variables never turn export on by themselves: an application that also runs an OpenTelemetry SDK has them set for that SDK, and would export every trace twice.
551
+
552
+ | Option | Default | What it does |
553
+ | -------------------- | -------------------------------- | --------------------------------------------------------------------------------------------------------- |
554
+ | `endpoint` | `http://localhost:4318` | The receiver's base URL; `/v1/traces` is appended unless it is already there. |
555
+ | `headers` | none | Sent with every export - a vendor's API key, usually. |
556
+ | `protocol` | `'http/protobuf'` | Or `'http/json'`. gRPC is not supported: point at the receiver's HTTP port. |
557
+ | `compression` | `'gzip'` | Or `'none'`. |
558
+ | `timeoutMillis` | `10000` | How long one export may take before it is abandoned and retried. |
559
+ | `serviceName` | `serviceId` | The `service.name` spans are reported under. |
560
+ | `resourceAttributes` | none | Added to the agent's own (`service.version`, `service.instance.id`, `host.name`, `process.pid`, ...). |
561
+
562
+ What a backend receives, for each operation:
563
+
564
+ - **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
+ - **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.
567
+ - **Errors** as span status and an `exception` event, with the class, message and stack the dashboard shows - redacted the same way.
568
+
569
+ 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.
570
+
516
571
  ## Configuration
517
572
 
518
573
  Every option, with its default. The [documentation](https://www.observe.nestjs.com/documentation/sdk) covers each in more depth.
@@ -526,6 +581,7 @@ Every option, with its default. The [documentation](https://www.observe.nestjs.c
526
581
  | `serviceId` | required | Names the service in the dashboard, in at most 100 characters - a longer one is cut to fit, with a warning at startup. |
527
582
  | `serviceVersion` | inferred | The release the process runs, at most 50 characters - see [What it records without any code](#what-it-records-without-any-code). `false` reports none. |
528
583
  | `endpoint` | `https://observe-api.nestjs.com` | The collector's base URL - NestJS Observe, or a proxy that forwards to it. `OBSERVE_ENDPOINT` in the environment changes the default without touching the config. |
584
+ | `otlp` | `false` | Exports traces as OpenTelemetry spans to a receiver of your own, with `openTelemetry: true` - see [Exporting to OpenTelemetry](#exporting-to-opentelemetry). `true` reads the `OTEL_EXPORTER_OTLP_*` variables. |
529
585
  | `flushInterval` | `5000` | Milliseconds between sends of buffered telemetry; at least `1000`. |
530
586
  | `shutdownFlushTimeout` | `2000` | Milliseconds closing the app waits for buffered telemetry to reach the collector before stopping the agent. `0` skips the final send - for test suites that boot the app with real credentials. |
531
587
  | `maxTracesPerBatch` | `1000` | The most traces one send carries. |
@@ -537,7 +593,7 @@ Every option, with its default. The [documentation](https://www.observe.nestjs.c
537
593
  | `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). |
538
594
  | `redaction` | on | How log lines, error messages and captured requests are scrubbed before they leave the process: `enabled`, `useDefaultPatterns`, `patterns`, `keys` and `replacement`. |
539
595
  | `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. |
596
+ | `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 beside reporting to NestJS Observe, and stays on through collector outages. Off, the agent reads and sends `x-request-id` alone. |
541
597
  | `http` | | `ignore`, `tags`, `setAttributes`, `getUserId`, `queryParamsObfuscateRegex`, `tracePreflights` and `capture` - see [Capturing failed and slow requests](#capturing-failed-and-slow-requests). |
542
598
  | `rpc`, `grpc` | | `ignore`, `tags`, `setAttributes` and `getUserId` for microservice and gRPC handlers. |
543
599
  | `graphql` | | The same four, once per GraphQL operation. |
@@ -585,16 +641,17 @@ $ npm run typecheck
585
641
  $ npm run test:int
586
642
  ```
587
643
 
588
- The MSSQL unit suite uses the real driver's public request APIs with stubbed transport methods and needs no SQL Server. The queue suites need a Redis, and the query-span integration suites a PostgreSQL, MySQL and MongoDB. Each integration suite skips itself when its server does not answer, so without them `test:int` passes having tested less. CI starts them with these ports and credentials, which the suites default to:
644
+ The MSSQL unit suite uses the real driver's public request APIs with stubbed transport methods and needs no SQL Server. The queue suites need a Redis, the query-span integration suites a PostgreSQL, MySQL and MongoDB, and the OTLP export suite's Jaeger case a Jaeger. Each integration suite skips itself when its server does not answer, so without them `test:int` passes having tested less. CI starts them with these ports and credentials, which the suites default to:
589
645
 
590
646
  ```bash
591
647
  $ docker run -d -p 6379:6379 redis:7-alpine
592
648
  $ docker run -d -p 54321:5432 -e POSTGRES_PASSWORD=postgres-whisprr postgres:16-alpine
593
649
  $ docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=test mysql:8
594
650
  $ docker run -d -p 27027:27017 mongo:7
651
+ $ docker run -d -p 4318:4318 -p 16686:16686 jaegertracing/jaeger:2.22.0
595
652
  ```
596
653
 
597
- To point them elsewhere, set `REDIS_HOST`/`REDIS_PORT`, `PGHOST`/`PGPORT`/`PGUSER`/`PGPASSWORD`/`PGDATABASE`, `MYSQL_HOST`/`MYSQL_PORT`/`MYSQL_USER`/`MYSQL_PASSWORD`/`MYSQL_DATABASE` or `MONGO_HOST`/`MONGO_PORT`.
654
+ 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.
598
655
 
599
656
  ## Module format
600
657
 
@@ -111,19 +111,13 @@ export declare function parsePausedMessage(msg: string): number | null;
111
111
  * collector, any other status, a fault in the worker. A batch that got in
112
112
  * says so with its degraded verdict instead.
113
113
  *
114
- * Read for OpenTelemetry interop, which runs only while the collector takes
115
- * this app's telemetry - see `ObserveAgentSharedBuffer.isIngesting`.
114
+ * Read for OpenTelemetry interop, which a refusal pauses and any other failure
115
+ * leaves as it is - see `ObserveAgentSharedBuffer.isIngesting`.
116
116
  */
117
117
  export declare const NOT_INGESTED_MESSAGE_PREFIX = "observe:not-ingested=";
118
118
  export type NotIngestedReason = "refused" | "failed";
119
119
  /** Why a batch did not get in, or null if this is not that line. */
120
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;
127
121
  /**
128
122
  * Duration past which the collector treats an execution as notable, in
129
123
  * milliseconds.
@@ -93,8 +93,8 @@ export function parsePausedMessage(msg) {
93
93
  * collector, any other status, a fault in the worker. A batch that got in
94
94
  * says so with its degraded verdict instead.
95
95
  *
96
- * Read for OpenTelemetry interop, which runs only while the collector takes
97
- * this app's telemetry - see `ObserveAgentSharedBuffer.isIngesting`.
96
+ * Read for OpenTelemetry interop, which a refusal pauses and any other failure
97
+ * leaves as it is - see `ObserveAgentSharedBuffer.isIngesting`.
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. */
@@ -105,12 +105,6 @@ export function parseNotIngestedMessage(msg) {
105
105
  const reason = msg.slice(NOT_INGESTED_MESSAGE_PREFIX.length);
106
106
  return reason === "refused" || reason === "failed" ? reason : null;
107
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;
114
108
  /**
115
109
  * Duration past which the collector treats an execution as notable, in
116
110
  * milliseconds.
@@ -16,4 +16,6 @@ export declare function detachedWorkerData(input: {
16
16
  appKey?: string;
17
17
  appSecret?: string;
18
18
  flushInterval: number;
19
+ /** Whether `otlp` is set up to export - see `asksForOtlpExport`. */
20
+ asksForOtlpExport?: boolean;
19
21
  }): DetachedWorkerData;
@@ -1,6 +1,7 @@
1
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
+ import { OTLP_EXPORT_MESSAGE_PREFIX } from "../otlp/otlp-export-grant.js";
4
5
  import { describeIngestRefusal } from "../utils/ingest-refusal.util.js";
5
6
  import { readSdkVersion } from "../utils/sdk-version.util.js";
6
7
  /**
@@ -28,6 +29,8 @@ export function detachedWorkerData(input) {
28
29
  degradedPrefix: DEGRADED_MESSAGE_PREFIX,
29
30
  pausedPrefix: PAUSED_MESSAGE_PREFIX,
30
31
  notIngestedPrefix: NOT_INGESTED_MESSAGE_PREFIX,
32
+ otlpExportPrefix: OTLP_EXPORT_MESSAGE_PREFIX,
33
+ asksForOtlpExport: input.asksForOtlpExport === true,
31
34
  sdkVersion: readSdkVersion(),
32
35
  };
33
36
  return { sharedBuffer: input.sharedBuffer, config };
@@ -25,6 +25,14 @@ export interface DetachedWorkerConfig {
25
25
  pausedPrefix: string;
26
26
  /** `NOT_INGESTED_MESSAGE_PREFIX`, as data, for the same reason. */
27
27
  notIngestedPrefix: string;
28
+ /** `OTLP_EXPORT_MESSAGE_PREFIX`, as data, for the same reason. */
29
+ otlpExportPrefix: string;
30
+ /**
31
+ * Whether `otlp` is set up to export, so batches ask the collector what
32
+ * the app's plan allows it (`OTLP_EXPORT_INGEST_MODE`) and the answer is
33
+ * posted back. False leaves every batch and every line as they were.
34
+ */
35
+ asksForOtlpExport: boolean;
28
36
  /**
29
37
  * This package's version (`readSdkVersion`), read on the main thread: the
30
38
  * worker runs as eval'd source and cannot resolve a manifest of its own.
@@ -52,6 +52,9 @@ describeRefusal) => {
52
52
  const degradedPrefix = config.degradedPrefix;
53
53
  const pausedPrefix = config.pausedPrefix;
54
54
  const notIngestedPrefix = config.notIngestedPrefix;
55
+ const otlpExportPrefix = config.otlpExportPrefix;
56
+ // Read as truthy, so a config without it asks nothing and posts no line.
57
+ const asksForOtlpExport = config.asksForOtlpExport;
55
58
  /**
56
59
  * Built here, used only when the collector answers 400. The shapes travel
57
60
  * through `workerData` (they are plain JSON); the factory travels as source.
@@ -67,8 +70,11 @@ describeRefusal) => {
67
70
  // degraded-ingest.protocol.ts. A literal rather than data from `config`
68
71
  // like the prefixes: nothing in the agent reads it back, and a missing
69
72
  // config key would put a broken header on every batch. The value is
70
- // pinned by worker-degraded-reply.spec.ts.
71
- "x-observe-ingest-modes": "reduced, trimmed, paced, errors-only",
73
+ // pinned by worker-degraded-reply.spec.ts. `otlp-export`
74
+ // (`OTLP_EXPORT_INGEST_MODE`) asks what the app's plan allows `otlp` to
75
+ // export, and is listed only by an agent set up to export.
76
+ "x-observe-ingest-modes": "reduced, trimmed, paced, errors-only" +
77
+ (asksForOtlpExport ? ", otlp-export" : ""),
72
78
  // Which agent sent the batch, so the collector can tell an application
73
79
  // still on an old release that a newer one exists.
74
80
  "x-observe-sdk-version": config.sdkVersion,
@@ -529,6 +535,18 @@ describeRefusal) => {
529
535
  */
530
536
  const accepted = await response.json().catch(() => undefined);
531
537
  const reply = (typeof accepted === "object" && accepted !== null ? accepted : {});
538
+ // What the app's plan allows `otlp` to export - see `OtlpExportGrant`.
539
+ // Every accepted reply says it again, and a reply that says nothing
540
+ // grants nothing: a collector that predates export, or a plan without
541
+ // it. Ahead of the verdict below, which the main thread reads as the
542
+ // collector taking the app's telemetry - by then it knows what export
543
+ // may do with it.
544
+ if (asksForOtlpExport) {
545
+ const grant = reply.otlpExport === "full" || reply.otlpExport === "capped"
546
+ ? reply.otlpExport
547
+ : "off";
548
+ parentPort.postMessage(`${otlpExportPrefix}${grant}`);
549
+ }
532
550
  // `false`, `true`, `trimmed`, `paced` or `errors-only`. `trimmed`,
533
551
  // `paced` and `errorsOnly` say only why or how the spans are discarded,
534
552
  // so they count only beside `degraded`; a collector that sends none of
@@ -5,6 +5,8 @@ import { JobSnapshot } from "../interfaces/job-snapshot.interface.js";
5
5
  import { NodeRuntimeMetrics } from "../interfaces/node-runtime-metrics.interface.js";
6
6
  import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.interface.js";
7
7
  import { RequestSnapshot } from "../interfaces/request-snapshot.interface.js";
8
+ import type { OtlpExportGrant } from "../otlp/otlp-export-grant.js";
9
+ import { OtlpTraceExporter } from "../otlp/otlp-trace-exporter.service.js";
8
10
  /**
9
11
  * A log line waiting to be shipped.
10
12
  *
@@ -47,6 +49,7 @@ interface BufferedLogEntry {
47
49
  export declare class ObserveAgentSharedBuffer {
48
50
  private readonly options;
49
51
  private readonly objectivesRegistry?;
52
+ private readonly otlpTraceExporter?;
50
53
  private readonly _sharedBuffer;
51
54
  private readonly lock;
52
55
  private readonly sharedBytes;
@@ -66,7 +69,7 @@ export declare class ObserveAgentSharedBuffer {
66
69
  */
67
70
  private readonly _awaitingFlushAck;
68
71
  get sharedBuffer(): SharedArrayBuffer;
69
- constructor(options: ObserveModuleOptionsWithDefaults, objectivesRegistry?: ObjectivesRegistry | undefined);
72
+ constructor(options: ObserveModuleOptionsWithDefaults, objectivesRegistry?: ObjectivesRegistry | undefined, otlpTraceExporter?: OtlpTraceExporter | undefined);
70
73
  insertRequestSnapshot(snapshot: RequestSnapshot): void;
71
74
  insertJobSnapshot(jobSnapshot: JobSnapshot): void;
72
75
  /**
@@ -85,16 +88,11 @@ export declare class ObserveAgentSharedBuffer {
85
88
  */
86
89
  private errorsOnly;
87
90
  /**
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
+ * 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
94
  */
92
95
  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;
98
96
  /**
99
97
  * Requests and jobs that errors-only ingest withheld from the batch being
100
98
  * built, cleared with it.
@@ -127,30 +125,58 @@ export declare class ObserveAgentSharedBuffer {
127
125
  /** Whether only server errors are being sent, until the same window lapses. */
128
126
  isErrorsOnly(): boolean;
129
127
  /**
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.
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
+ *
132
+ * A batch that fails to get in for any other reason - a collector that is
133
+ * down or slow to answer, a 5xx, a 429 pause, however long - leaves it as
134
+ * it is: that is an outage at NestJS Observe, and the traces running through
135
+ * the services around this one must not break over it. Refused credentials
136
+ * are a verdict on this app, and a stopped worker sends nothing until a new
137
+ * one gets a batch in.
134
138
  *
135
139
  * OpenTelemetry interop runs on it (see `openTelemetry`): the agent reads
136
140
  * 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.
141
+ * 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.
140
144
  */
141
145
  isIngesting(): boolean;
142
146
  /** The collector accepted a batch, whatever it then kept of it. */
143
147
  recordAccepted(): void;
144
148
  /** The collector refused the app's credentials. */
145
149
  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
150
  /** The worker stopped; a restarted one has to get a batch in again. */
153
151
  recordStopped(): void;
152
+ /**
153
+ * What the collector's last accepted reply granted `otlp` - see
154
+ * `OtlpExportGrant`. Nothing until one says otherwise: what this agent may
155
+ * export is the collector's to say, for the plan the app's account is on.
156
+ */
157
+ private otlpExport;
158
+ /**
159
+ * Until when a `capped` grant holds (epoch ms), refreshed by every reply
160
+ * that repeats it.
161
+ *
162
+ * A capped export is what NestJS Observe keeps, and the agent learns what
163
+ * that is only from replies. With none coming - an account the collector
164
+ * refuses at its limit, an outage - it would fall back on exporting every
165
+ * span once `isDegraded` lapsed. So the grant lapses first: it is set just
166
+ * before the verdict for the same reply, on the same TTL. A `full` grant
167
+ * holds until a reply says otherwise, and export then runs for as long as
168
+ * `isIngesting` does.
169
+ */
170
+ private otlpExportCappedUntil;
171
+ /** Records what the collector's last accepted reply granted `otlp`. */
172
+ setOtlpExport(grant: OtlpExportGrant, now?: number): void;
173
+ /**
174
+ * What `otlp` may export right now: the collector's grant, while the
175
+ * collector takes this app's telemetry (`isIngesting`) - export runs beside
176
+ * reporting to NestJS Observe, never instead of it - and `off` otherwise.
177
+ * Asked once per operation, as it is handed over.
178
+ */
179
+ otlpExportGrant(now?: number): OtlpExportGrant;
154
180
  /**
155
181
  * What errors-only ingest makes of one execution: whether it is sent.
156
182
  *