@nestjs/observe 0.3.22 → 0.3.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +79 -16
  2. package/dist/agent/degraded-ingest.protocol.d.ts +2 -8
  3. package/dist/agent/degraded-ingest.protocol.js +2 -8
  4. package/dist/agent/detached-observe-worker.assembly.d.ts +2 -0
  5. package/dist/agent/detached-observe-worker.assembly.js +3 -0
  6. package/dist/agent/detached-observe-worker.d.ts +8 -0
  7. package/dist/agent/detached-observe-worker.js +20 -2
  8. package/dist/agent/observe-agent.shared-buffer.d.ts +71 -23
  9. package/dist/agent/observe-agent.shared-buffer.js +126 -38
  10. package/dist/agent/observe-agent.worker.d.ts +19 -23
  11. package/dist/agent/observe-agent.worker.js +79 -78
  12. package/dist/agent/observe-reporting.util.d.ts +35 -0
  13. package/dist/agent/observe-reporting.util.js +69 -0
  14. package/dist/instrument/create-instance-decorator.instrument.js +34 -2
  15. package/dist/interfaces/observe-options.interface.d.ts +71 -13
  16. package/dist/observe.constants.d.ts +7 -0
  17. package/dist/observe.constants.js +7 -0
  18. package/dist/observe.module.js +50 -4
  19. package/dist/otlp/otlp-encoders.d.ts +26 -0
  20. package/dist/otlp/otlp-encoders.js +296 -0
  21. package/dist/otlp/otlp-export-grant.d.ts +34 -0
  22. package/dist/otlp/otlp-export-grant.js +22 -0
  23. package/dist/otlp/otlp-options.interface.d.ts +59 -0
  24. package/dist/otlp/otlp-options.interface.js +1 -0
  25. package/dist/otlp/otlp-settings.util.d.ts +38 -0
  26. package/dist/otlp/otlp-settings.util.js +154 -0
  27. package/dist/otlp/otlp-span.mapper.d.ts +73 -0
  28. package/dist/otlp/otlp-span.mapper.js +345 -0
  29. package/dist/otlp/otlp-trace-exporter.service.d.ts +130 -0
  30. package/dist/otlp/otlp-trace-exporter.service.js +497 -0
  31. package/dist/outgoing/http.integration.d.ts +5 -4
  32. package/dist/outgoing/http.integration.js +3 -3
  33. package/dist/outgoing/outgoing-observe-agent.service.d.ts +2 -2
  34. package/dist/outgoing/outgoing-observe-agent.service.js +3 -3
  35. package/dist/outgoing/sql-statement.util.js +2 -2
  36. package/dist/protocols/http-observe-agent.service.d.ts +1 -8
  37. package/dist/protocols/http-observe-agent.service.js +29 -22
  38. package/dist/protocols/job-trace-runner.d.ts +11 -0
  39. package/dist/protocols/job-trace-runner.js +42 -8
  40. package/dist/protocols/rpc-observe-agent.service.d.ts +5 -0
  41. package/dist/protocols/rpc-observe-agent.service.js +43 -3
  42. package/dist/services/operation-trace.registry.d.ts +29 -1
  43. package/dist/services/operation-trace.registry.js +46 -5
  44. package/dist/utils/default-trace-id-generator.util.js +6 -2
  45. package/dist/utils/opentelemetry.util.d.ts +26 -0
  46. package/dist/utils/opentelemetry.util.js +48 -0
  47. package/dist/utils/trace-handoff.util.d.ts +51 -0
  48. package/dist/utils/trace-handoff.util.js +98 -0
  49. package/package.json +14 -12
@@ -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, NOT_INGESTED_GRACE_MS, } from "./degraded-ingest.protocol.js";
14
+ import { countTraceNodes, DEGRADED_TTL_MS, isNotableSnapshot, isServerErrorSnapshot, } 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";
@@ -21,6 +21,7 @@ import { JobSnapshotEncoder, } from "../encoders/job-snapshot.encoder.js";
21
21
  import { RequestSnapshotEncoder, } from "../encoders/request-snapshot.encoder.js";
22
22
  import { RuntimeMetricsEncoder, } from "../encoders/runtime-metrics.encoder.js";
23
23
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
24
+ import { OtlpTraceExporter } from "../otlp/otlp-trace-exporter.service.js";
24
25
  import { fallbackOperationId } from "../utils/fallback-operation-id.util.js";
25
26
  const SHARED_BUFFER_SIZE = 1024 * 1024 * 16; // 16 MB
26
27
  const DEFAULT_MAX_SNAPSHOTS_PER_TRANSACTION = 1000;
@@ -61,6 +62,7 @@ const MAX_OBJECTIVES_PER_BATCH = 100;
61
62
  let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSharedBuffer {
62
63
  options;
63
64
  objectivesRegistry;
65
+ otlpTraceExporter;
64
66
  _sharedBuffer = new SharedArrayBuffer(SHARED_BUFFER_SIZE);
65
67
  lock = new Int32Array(this._sharedBuffer, 0, 1);
66
68
  sharedBytes = new Uint8Array(this._sharedBuffer);
@@ -82,9 +84,10 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
82
84
  get sharedBuffer() {
83
85
  return this._sharedBuffer;
84
86
  }
85
- constructor(options, objectivesRegistry) {
87
+ constructor(options, objectivesRegistry, otlpTraceExporter) {
86
88
  this.options = options;
87
89
  this.objectivesRegistry = objectivesRegistry;
90
+ this.otlpTraceExporter = otlpTraceExporter;
88
91
  }
89
92
  insertRequestSnapshot(snapshot) {
90
93
  // A request can end before its route metadata is ever captured - an auth
@@ -96,6 +99,15 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
96
99
  // ride in. The URL is folded to a route-like path first, or every query
97
100
  // string and id would be a route of its own; `originalUrl` keeps it whole.
98
101
  snapshot.operationId ??= fallbackOperationId(snapshot.attributes?.originalUrl);
102
+ // A full grant exports ahead of everything below that can leave the
103
+ // snapshot out: the collector's limits and its answers about this
104
+ // account decide what reaches Observe, not what an OTLP receiver of the
105
+ // application's own is sent. The raw snapshot, which the encoder below
106
+ // only copies. A capped grant exports what the batch keeps, further down.
107
+ const otlpExport = this.otlpExportGrant();
108
+ if (otlpExport === "full") {
109
+ this.otlpTraceExporter?.exportRequestSnapshot(snapshot);
110
+ }
99
111
  if (!snapshot.operationId) {
100
112
  if (this.options.debug) {
101
113
  this.logger.debug(`Snapshot for traceId "${snapshot.traceId}" has no operation id nor URL to fall back on. Ignoring snapshot.`);
@@ -121,12 +133,17 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
121
133
  // further down - they are not telemetry.
122
134
  if (this.sendsWhileErrorsOnly(encodedSnapshot)) {
123
135
  this._mainThreadBuffer.snapshots.push(encodedSnapshot);
136
+ if (otlpExport === "capped") {
137
+ // Sent, and never with its tree.
138
+ this.otlpTraceExporter?.exportRequestSnapshot(snapshot, false);
139
+ }
124
140
  }
125
141
  else {
126
142
  this.withheldSnapshots += 1;
127
143
  }
128
144
  }
129
145
  else {
146
+ let keepsTree = true;
130
147
  if (this.isDegraded() && !isNotableSnapshot(encodedSnapshot)) {
131
148
  // The collector is discarding these on arrival; shipping them costs
132
149
  // the application its own CPU and bandwidth for nothing. The snapshot
@@ -135,8 +152,12 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
135
152
  // count goes with it, because it is the only record these existed.
136
153
  this.countTruncated(encodedSnapshot.t);
137
154
  encodedSnapshot.t = [];
155
+ keepsTree = false;
138
156
  }
139
157
  this._mainThreadBuffer.snapshots.push(encodedSnapshot);
158
+ if (otlpExport === "capped") {
159
+ this.otlpTraceExporter?.exportRequestSnapshot(snapshot, keepsTree);
160
+ }
140
161
  }
141
162
  // Read off the raw snapshot: the handler's span carries `Class.method`,
142
163
  // which is what `@Objective` declarations are keyed by. Declarations are
@@ -155,6 +176,12 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
155
176
  }
156
177
  }
157
178
  insertJobSnapshot(jobSnapshot) {
179
+ // A full grant exports before the cap below, as for a request; a capped
180
+ // one what the batch keeps.
181
+ const otlpExport = this.otlpExportGrant();
182
+ if (otlpExport === "full") {
183
+ this.otlpTraceExporter?.exportJobSnapshot(jobSnapshot);
184
+ }
158
185
  if (!this._mainThreadBuffer) {
159
186
  this._mainThreadBuffer = this.createEmptyPayload();
160
187
  }
@@ -178,20 +205,28 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
178
205
  // makes it a server error - which is what the collector keeps of it too.
179
206
  if (this.sendsWhileErrorsOnly(encodedJobSnapshot)) {
180
207
  this._mainThreadBuffer.jobs.push(encodedJobSnapshot);
208
+ if (otlpExport === "capped") {
209
+ this.otlpTraceExporter?.exportJobSnapshot(jobSnapshot, false);
210
+ }
181
211
  }
182
212
  else {
183
213
  this.withheldJobs += 1;
184
214
  }
185
215
  }
186
216
  else {
217
+ let keepsTree = true;
187
218
  if (this.isDegraded() && !isNotableSnapshot(encodedJobSnapshot)) {
188
219
  // A job carries no status code, so the same rule grades it on its
189
220
  // error and its duration - which is what the collector does with it
190
221
  // too.
191
222
  this.countTruncated(encodedJobSnapshot.t);
192
223
  encodedJobSnapshot.t = [];
224
+ keepsTree = false;
193
225
  }
194
226
  this._mainThreadBuffer.jobs.push(encodedJobSnapshot);
227
+ if (otlpExport === "capped") {
228
+ this.otlpTraceExporter?.exportJobSnapshot(jobSnapshot, keepsTree);
229
+ }
195
230
  }
196
231
  }
197
232
  /**
@@ -210,16 +245,14 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
210
245
  */
211
246
  errorsOnly = false;
212
247
  /**
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.
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.
216
254
  */
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;
255
+ reporting = "off";
223
256
  /**
224
257
  * Requests and jobs that errors-only ingest withheld from the batch being
225
258
  * built, cleared with it.
@@ -259,48 +292,101 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
259
292
  return this.errorsOnly && this.isDegraded();
260
293
  }
261
294
  /**
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.
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.
305
+ *
306
+ * A batch that fails to get in for any other reason - a collector that is
307
+ * down or slow to answer, a 5xx, a 429 pause, however long - leaves it as
308
+ * it is: that is an outage at NestJS Observe, and the traces running through
309
+ * the services around this one must not break over it. Refused credentials
310
+ * are a verdict on this app, and a stopped worker sends nothing until a new
311
+ * one gets a batch in.
266
312
  *
267
313
  * OpenTelemetry interop runs on it (see `openTelemetry`): the agent reads
268
314
  * 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.
315
+ * only beside reporting to NestJS Observe. So an agent that sends Observe
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.
272
326
  */
273
327
  isIngesting() {
274
- 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
+ }
275
339
  }
276
340
  /** The collector accepted a batch, whatever it then kept of it. */
277
341
  recordAccepted() {
278
- this.ingesting = true;
279
- this.failingSince = 0;
342
+ this.reporting = "ingesting";
280
343
  }
281
344
  /** The collector refused the app's credentials. */
282
345
  recordRefused() {
283
- this.ingesting = false;
284
- this.failingSince = 0;
346
+ this.reporting = "off";
347
+ }
348
+ /** The worker stopped; a restarted one has to get a batch in again. */
349
+ recordStopped() {
350
+ this.reporting = "off";
285
351
  }
286
352
  /**
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.
353
+ * What the collector's last accepted reply granted `otlp` - see
354
+ * `OtlpExportGrant`. Nothing until one says otherwise: what this agent may
355
+ * export is the collector's to say, for the plan the app's account is on.
356
+ */
357
+ otlpExport = "off";
358
+ /**
359
+ * Until when a `capped` grant holds (epoch ms), refreshed by every reply
360
+ * that repeats it.
361
+ *
362
+ * A capped export is what NestJS Observe keeps, and the agent learns what
363
+ * that is only from replies. With none coming - an account the collector
364
+ * refuses at its limit, an outage - it would fall back on exporting every
365
+ * span once `isDegraded` lapsed. So the grant lapses first: it is set just
366
+ * before the verdict for the same reply, on the same TTL. A `full` grant
367
+ * holds until a reply says otherwise, and export then runs for as long as
368
+ * `isIngesting` does.
290
369
  */
291
- recordFailed(pausedUntil = 0, now = Date.now()) {
292
- if (this.failingSince === 0) {
293
- this.failingSince = now;
370
+ otlpExportCappedUntil = 0;
371
+ /** Records what the collector's last accepted reply granted `otlp`. */
372
+ setOtlpExport(grant, now = Date.now()) {
373
+ this.otlpExport = grant;
374
+ this.otlpExportCappedUntil = grant === "capped" ? now + DEGRADED_TTL_MS : 0;
375
+ }
376
+ /**
377
+ * What `otlp` may export right now: the collector's grant, while the
378
+ * collector takes this app's telemetry (`isIngesting`) - export runs beside
379
+ * reporting to NestJS Observe, never instead of it - and `off` otherwise.
380
+ * Asked once per operation, as it is handed over.
381
+ */
382
+ otlpExportGrant(now = Date.now()) {
383
+ if (!this.otlpTraceExporter?.enabled || !this.isIngesting()) {
384
+ return "off";
294
385
  }
295
- if (Math.max(now, pausedUntil) - this.failingSince >=
296
- NOT_INGESTED_GRACE_MS) {
297
- this.ingesting = false;
386
+ if (this.otlpExport === "capped" && now >= this.otlpExportCappedUntil) {
387
+ return "off";
298
388
  }
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;
389
+ return this.otlpExport;
304
390
  }
305
391
  /**
306
392
  * What errors-only ingest makes of one execution: whether it is sent.
@@ -593,6 +679,8 @@ ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = __decorate([
593
679
  Injectable(),
594
680
  __param(0, Inject(OBSERVE_OPTIONS)),
595
681
  __param(1, Optional()),
596
- __metadata("design:paramtypes", [Object, ObjectivesRegistry])
682
+ __param(2, Optional()),
683
+ __metadata("design:paramtypes", [Object, ObjectivesRegistry,
684
+ OtlpTraceExporter])
597
685
  ], ObserveAgentSharedBuffer);
598
686
  export { ObserveAgentSharedBuffer };
@@ -3,11 +3,13 @@ import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.
3
3
  import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.service.js";
4
4
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
5
5
  import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
6
+ import { OtlpTraceExporter } from "../otlp/otlp-trace-exporter.service.js";
6
7
  export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationShutdown {
7
8
  private readonly observeAgentSharedBuffer;
8
9
  private readonly options;
9
10
  private readonly nodeRuntimeMetricsService;
10
11
  private readonly operationTraceRegistry?;
12
+ private readonly otlpTraceExporter?;
11
13
  private readonly logger;
12
14
  private worker;
13
15
  /**
@@ -33,7 +35,7 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
33
35
  * flush only.
34
36
  */
35
37
  private sendsPausedUntil;
36
- constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, nodeRuntimeMetricsService: NodeRuntimeMetricsService, operationTraceRegistry?: OperationTraceRegistry | undefined);
38
+ constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, nodeRuntimeMetricsService: NodeRuntimeMetricsService, operationTraceRegistry?: OperationTraceRegistry | undefined, otlpTraceExporter?: OtlpTraceExporter | undefined);
37
39
  onModuleInit(): void;
38
40
  /**
39
41
  * Starts the runtime-metrics collector: memory, CPU, GC, event loop.
@@ -122,25 +124,6 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
122
124
  * The runtime-metrics window between the last scheduled sample and now.
123
125
  */
124
126
  private addFinalRuntimeMetrics;
125
- private get hasScaffoldCredentials();
126
- /**
127
- * Whether credentials are missing and the collector is the hosted one,
128
- * which answers every batch without them with a 401.
129
- *
130
- * The worker leaves both headers off when either half is unset, which a
131
- * collector in placeholder mode accepts, so a collector of the user's own
132
- * still gets those batches. The hosted collector refuses them for as long
133
- * as the process runs: on 2026-10-15 that was 42% of the 1.87M batches it
134
- * refused, from processes deployed without their environment variables,
135
- * some of them posting every five seconds for weeks.
136
- */
137
- private get lacksHostedCredentials();
138
- /**
139
- * Whether `endpoint` - set, from `OBSERVE_ENDPOINT`, or the default - is the
140
- * hosted collector. Compared by host, so a trailing slash or a capital
141
- * letter cannot pass it off as a collector of the user's own.
142
- */
143
- private get isHostedCollector();
144
127
  /**
145
128
  * Whether `enabled: false` switched the agent off - whatever the
146
129
  * credentials, and whichever collector `endpoint` names.
@@ -171,11 +154,24 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
171
154
  private reportedOpenTelemetry;
172
155
  /**
173
156
  * 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.
157
+ * it runs only beside reporting to NestJS Observe (see
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.
177
161
  */
178
162
  private reportOpenTelemetryInterop;
163
+ /**
164
+ * The OTLP export grant last said, or null before the first. Kept beside
165
+ * the log so each change is said once: every accepted batch repeats it.
166
+ */
167
+ private reportedOtlpExport;
168
+ /**
169
+ * Says what the collector granted `otlp` when it changes, the first answer
170
+ * included - an export that stays silent would read as a broken receiver.
171
+ * Only the plan's answer: a pause while the collector is not taking the
172
+ * app's telemetry is said by the interop line above.
173
+ */
174
+ private reportOtlpExport;
179
175
  /** Whether this process has said the collector accepted its first batch. */
180
176
  private reportedConnection;
181
177
  /**
@@ -21,22 +21,16 @@ 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 { NOT_INGESTED_GRACE_MS, parseDegradedMessage, parseNotIngestedMessage, parseOveragePauseReason, parsePausedMessage, } from "./degraded-ingest.protocol.js";
24
+ import { 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";
28
+ import { parseOtlpExportMessage, } from "../otlp/otlp-export-grant.js";
29
+ import { OtlpTraceExporter } from "../otlp/otlp-trace-exporter.service.js";
30
+ import { collectorEndpointOf, hasScaffoldCredentials, isHostedCollector, lacksHostedCredentials, sendsToObserve, } from "./observe-reporting.util.js";
28
31
  const DEFAULT_RUNTIME_METRICS_INTERVAL = 60000; // 60 seconds
29
32
  const MIN_RUNTIME_METRICS_INTERVAL = 30000; // 30 seconds
30
33
  const DEFAULT_FLUSH_INTERVAL = 5000; // 5 seconds
31
- /**
32
- * The hosted collector. Unlike a collector in placeholder mode, it accepts
33
- * nothing without credentials.
34
- */
35
- const HOSTED_COLLECTOR_ENDPOINT = "https://observe-api.nestjs.com";
36
- /**
37
- * Where signals are posted when `endpoint` is not configured.
38
- */
39
- const DEFAULT_COLLECTOR_ENDPOINT = process.env.OBSERVE_ENDPOINT ?? HOSTED_COLLECTOR_ENDPOINT;
40
34
  const MIN_FLUSH_INTERVAL = 1000; // 1 second
41
35
  /**
42
36
  * How long shutdown waits for buffered telemetry to reach the collector before
@@ -67,21 +61,13 @@ const FINAL_FLUSH_POLL_MS = 10;
67
61
  * a pegged CPU and a saturated loop, and mean nothing.
68
62
  */
69
63
  const MIN_FINAL_RUNTIME_WINDOW_MS = 10_000;
70
- /**
71
- * The credentials `nest new --observe` writes into `AppModule`.
72
- *
73
- * A project fresh from the generator has these until someone signs up, so
74
- * they mean "not connected yet", not "wrong": sending them only buys a 401
75
- * and an `Error:` line on the very first `npm run start`.
76
- */
77
- const SCAFFOLD_APP_KEY = "YOUR_APP_KEY";
78
- const SCAFFOLD_APP_SECRET = "YOUR_APP_SECRET";
79
64
  const DASHBOARD_URL = `${SIGN_UP_URL}/dashboard`;
80
65
  let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
81
66
  observeAgentSharedBuffer;
82
67
  options;
83
68
  nodeRuntimeMetricsService;
84
69
  operationTraceRegistry;
70
+ otlpTraceExporter;
85
71
  logger = new Logger(ObserveAgentWorker_1.name);
86
72
  // Null before `initializeWorker` and again after termination, which is what
87
73
  // the shutdown path below checks for.
@@ -109,11 +95,12 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
109
95
  * flush only.
110
96
  */
111
97
  sendsPausedUntil = 0;
112
- constructor(observeAgentSharedBuffer, options, nodeRuntimeMetricsService, operationTraceRegistry) {
98
+ constructor(observeAgentSharedBuffer, options, nodeRuntimeMetricsService, operationTraceRegistry, otlpTraceExporter) {
113
99
  this.observeAgentSharedBuffer = observeAgentSharedBuffer;
114
100
  this.options = options;
115
101
  this.nodeRuntimeMetricsService = nodeRuntimeMetricsService;
116
102
  this.operationTraceRegistry = operationTraceRegistry;
103
+ this.otlpTraceExporter = otlpTraceExporter;
117
104
  }
118
105
  onModuleInit() {
119
106
  // Settled before the worker starts, which backs off from this interval
@@ -132,12 +119,13 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
132
119
  // needs no key or secret, so a missing one is not worth a warning.
133
120
  this.logger.log("Observe is disabled (enabled: false): nothing is recorded or sent.");
134
121
  }
135
- else if (this.hasScaffoldCredentials || this.lacksHostedCredentials) {
122
+ else if (hasScaffoldCredentials(this.options) ||
123
+ lacksHostedCredentials(this.options)) {
136
124
  // Nothing is sent, so there is no worker to start. The flush timer below
137
125
  // still runs and empties the buffer, which the instrumentation keeps
138
126
  // writing into either way.
139
127
  const notice = describeMissingCredentials({
140
- scaffold: this.hasScaffoldCredentials,
128
+ scaffold: hasScaffoldCredentials(this.options),
141
129
  unset: !this.options.appKey && !this.options.appSecret
142
130
  ? "both"
143
131
  : !this.options.appKey
@@ -154,6 +142,10 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
154
142
  }
155
143
  else {
156
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");
157
149
  }
158
150
  if (this.options.openTelemetry === true && this.sendsNothing) {
159
151
  this.logger.warn("openTelemetry is on, but this agent reports nothing to NestJS Observe, so OpenTelemetry interop stays off: " +
@@ -448,40 +440,6 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
448
440
  }
449
441
  }
450
442
  }
451
- get hasScaffoldCredentials() {
452
- return (this.options.appKey === SCAFFOLD_APP_KEY &&
453
- this.options.appSecret === SCAFFOLD_APP_SECRET);
454
- }
455
- /**
456
- * Whether credentials are missing and the collector is the hosted one,
457
- * which answers every batch without them with a 401.
458
- *
459
- * The worker leaves both headers off when either half is unset, which a
460
- * collector in placeholder mode accepts, so a collector of the user's own
461
- * still gets those batches. The hosted collector refuses them for as long
462
- * as the process runs: on 2026-10-15 that was 42% of the 1.87M batches it
463
- * refused, from processes deployed without their environment variables,
464
- * some of them posting every five seconds for weeks.
465
- */
466
- get lacksHostedCredentials() {
467
- return ((!this.options.appKey || !this.options.appSecret) &&
468
- this.isHostedCollector);
469
- }
470
- /**
471
- * Whether `endpoint` - set, from `OBSERVE_ENDPOINT`, or the default - is the
472
- * hosted collector. Compared by host, so a trailing slash or a capital
473
- * letter cannot pass it off as a collector of the user's own.
474
- */
475
- get isHostedCollector() {
476
- try {
477
- return (new URL(this.endpoint).hostname ===
478
- new URL(HOSTED_COLLECTOR_ENDPOINT).hostname);
479
- }
480
- catch {
481
- // Not a URL at all; the worker says so when it tries to send.
482
- return false;
483
- }
484
- }
485
443
  /**
486
444
  * Whether `enabled: false` switched the agent off - whatever the
487
445
  * credentials, and whichever collector `endpoint` names.
@@ -491,12 +449,10 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
491
449
  }
492
450
  /** Whether nothing will be sent, so there is no worker to feed. */
493
451
  get sendsNothing() {
494
- return (this.isDisabled ||
495
- this.hasScaffoldCredentials ||
496
- this.lacksHostedCredentials);
452
+ return !sendsToObserve(this.options);
497
453
  }
498
454
  get endpoint() {
499
- return this.options.endpoint ?? DEFAULT_COLLECTOR_ENDPOINT;
455
+ return collectorEndpointOf(this.options);
500
456
  }
501
457
  /**
502
458
  * Says out loud when credentials are about to cross the network unencrypted.
@@ -542,6 +498,9 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
542
498
  appSecret: this.options.appSecret,
543
499
  // Clamped by `onModuleInit` before the first worker starts.
544
500
  flushInterval: this.options.flushInterval ?? DEFAULT_FLUSH_INTERVAL,
501
+ // Batches ask what the app's plan allows `otlp` to export only when
502
+ // it is set up to export at all.
503
+ asksForOtlpExport: this.otlpTraceExporter?.enabled === true,
545
504
  }),
546
505
  });
547
506
  this.watchWorker(this.worker);
@@ -577,20 +536,29 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
577
536
  }
578
537
  const notIngested = parseNotIngestedMessage(msg);
579
538
  if (notIngested !== null) {
539
+ // Only a refusal of the credentials pauses OpenTelemetry interop. A
540
+ // batch that failed to get in otherwise - the collector down, a 5xx, a
541
+ // timeout, a 429 pause - is an outage at NestJS Observe, and the
542
+ // traces running through the services around this one stay whole
543
+ // through it.
580
544
  if (notIngested === "refused") {
581
545
  this.observeAgentSharedBuffer.recordRefused();
546
+ this.reportOpenTelemetryInterop("refused");
582
547
  }
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);
548
+ return;
549
+ }
550
+ // Ahead of the verdict for the same batch, which the worker posts after
551
+ // it - see `OtlpExportGrant`.
552
+ const otlpExport = parseOtlpExportMessage(msg);
553
+ if (otlpExport !== null) {
554
+ this.observeAgentSharedBuffer.setOtlpExport(otlpExport);
555
+ this.reportOtlpExport(otlpExport);
588
556
  return;
589
557
  }
590
558
  const mode = parseDegradedMessage(msg);
591
559
  if (mode !== null) {
592
560
  this.observeAgentSharedBuffer.recordAccepted();
593
- this.reportOpenTelemetryInterop();
561
+ this.reportOpenTelemetryInterop("accepted");
594
562
  this.reportFirstAcceptedBatch();
595
563
  this.applyIngestMode(mode, parseOveragePauseReason(msg));
596
564
  return;
@@ -610,30 +578,61 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
610
578
  reportedOpenTelemetry = false;
611
579
  /**
612
580
  * 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.
581
+ * it runs only beside reporting to NestJS Observe (see
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.
616
585
  */
617
586
  reportOpenTelemetryInterop(why) {
618
587
  if (this.options.openTelemetry !== true) {
619
588
  return;
620
589
  }
621
- const on = this.observeAgentSharedBuffer.isIngesting();
590
+ const on = this.observeAgentSharedBuffer.isReporting();
622
591
  if (on === this.reportedOpenTelemetry) {
623
592
  return;
624
593
  }
625
594
  this.reportedOpenTelemetry = on;
626
595
  if (on) {
627
- this.logger.log("OpenTelemetry interop is on: the collector is taking this app's telemetry, so traceparent is read and sent.");
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.");
628
602
  return;
629
603
  }
630
604
  const reason = why === "refused"
631
605
  ? "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.`);
606
+ : "the telemetry worker stopped";
607
+ this.logger.warn(`OpenTelemetry interop is paused: ${reason}. It resumes with the next batch the collector accepts.`);
608
+ }
609
+ /**
610
+ * The OTLP export grant last said, or null before the first. Kept beside
611
+ * the log so each change is said once: every accepted batch repeats it.
612
+ */
613
+ reportedOtlpExport = null;
614
+ /**
615
+ * Says what the collector granted `otlp` when it changes, the first answer
616
+ * included - an export that stays silent would read as a broken receiver.
617
+ * Only the plan's answer: a pause while the collector is not taking the
618
+ * app's telemetry is said by the interop line above.
619
+ */
620
+ reportOtlpExport(grant) {
621
+ if (grant === this.reportedOtlpExport) {
622
+ return;
623
+ }
624
+ this.reportedOtlpExport = grant;
625
+ const url = this.otlpTraceExporter?.url ?? "the OTLP receiver";
626
+ if (grant === "full") {
627
+ this.logger.log(`OTLP export is on: every trace this app records goes to ${url}.`);
628
+ }
629
+ else if (grant === "capped") {
630
+ this.logger.log(`OTLP export is on, capped by this app's plan: traces go to ${url} as NestJS Observe keeps them, ` +
631
+ "so an operation it keeps without its spans - past the plan's daily pacing or monthly allowance - is exported without them too.");
632
+ }
633
+ else {
634
+ this.logger.warn(`OTLP export is off: the collector did not grant it for this app's plan, so nothing goes to ${url}.`);
635
+ }
637
636
  }
638
637
  /** Whether this process has said the collector accepted its first batch. */
639
638
  reportedConnection = false;
@@ -652,7 +651,7 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
652
651
  return;
653
652
  }
654
653
  this.reportedConnection = true;
655
- this.logger.log(this.isHostedCollector
654
+ this.logger.log(isHostedCollector(this.endpoint)
656
655
  ? `Observe is connected: the collector accepted this app's first batch. Requests and jobs appear at ${DASHBOARD_URL} as soon as the app serves them.`
657
656
  : `Observe is connected: ${this.endpoint} accepted this app's first batch.`);
658
657
  }
@@ -780,7 +779,9 @@ ObserveAgentWorker = ObserveAgentWorker_1 = __decorate([
780
779
  Injectable(),
781
780
  __param(1, Inject(OBSERVE_OPTIONS)),
782
781
  __param(3, Optional()),
782
+ __param(4, Optional()),
783
783
  __metadata("design:paramtypes", [ObserveAgentSharedBuffer, Object, NodeRuntimeMetricsService,
784
- OperationTraceRegistry])
784
+ OperationTraceRegistry,
785
+ OtlpTraceExporter])
785
786
  ], ObserveAgentWorker);
786
787
  export { ObserveAgentWorker };