@nestjs/observe 0.3.11 → 0.3.13

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 (39) hide show
  1. package/README.md +71 -2
  2. package/dist/agent/degraded-ingest.protocol.d.ts +87 -16
  3. package/dist/agent/degraded-ingest.protocol.js +62 -17
  4. package/dist/agent/detached-observe-worker.assembly.d.ts +1 -0
  5. package/dist/agent/detached-observe-worker.assembly.js +1 -0
  6. package/dist/agent/detached-observe-worker.d.ts +5 -0
  7. package/dist/agent/detached-observe-worker.js +129 -63
  8. package/dist/agent/observe-agent.shared-buffer.d.ts +54 -1
  9. package/dist/agent/observe-agent.shared-buffer.js +127 -22
  10. package/dist/agent/observe-agent.worker.d.ts +38 -1
  11. package/dist/agent/observe-agent.worker.js +134 -23
  12. package/dist/agent/telemetry-wire-contract.js +11 -1
  13. package/dist/encoders/request-snapshot.encoder.d.ts +1 -0
  14. package/dist/encoders/request-snapshot.encoder.js +1 -0
  15. package/dist/interfaces/observe-options.interface.d.ts +17 -2
  16. package/dist/interfaces/request-snapshot.interface.d.ts +13 -0
  17. package/dist/objectives/objectives.registry.d.ts +1 -0
  18. package/dist/objectives/objectives.registry.js +12 -0
  19. package/dist/outgoing/mssql.integration.d.ts +12 -0
  20. package/dist/outgoing/mssql.integration.js +248 -0
  21. package/dist/outgoing/mysql2.integration.js +1 -1
  22. package/dist/outgoing/outgoing-observe-agent.service.js +46 -8
  23. package/dist/outgoing/outgoing-span.recorder.d.ts +7 -0
  24. package/dist/outgoing/outgoing-span.recorder.js +15 -0
  25. package/dist/outgoing/pg.integration.js +1 -1
  26. package/dist/outgoing/sql-statement.util.d.ts +5 -1
  27. package/dist/outgoing/sql-statement.util.js +83 -10
  28. package/dist/protocols/http-observe-agent.service.js +9 -2
  29. package/dist/protocols/job-trace-runner.js +5 -0
  30. package/dist/services/node-runtime-metrics.service.js +1 -1
  31. package/dist/services/operation-trace.registry.d.ts +11 -0
  32. package/dist/services/operation-trace.registry.js +37 -1
  33. package/dist/services/stdout-forwarder.service.js +1 -1
  34. package/dist/services/trace-sampler.service.js +5 -0
  35. package/dist/services/tracer.service.d.ts +19 -0
  36. package/dist/services/tracer.service.js +61 -3
  37. package/dist/utils/ingest-refusal.util.d.ts +8 -3
  38. package/dist/utils/ingest-refusal.util.js +24 -3
  39. package/package.json +9 -4
@@ -62,6 +62,12 @@ describeRefusal) => {
62
62
  const headers = {
63
63
  "Content-Type": "application/json",
64
64
  "Content-Encoding": "gzip",
65
+ // The degraded replies this agent can tell apart - see `IngestMode` in
66
+ // degraded-ingest.protocol.ts. A literal rather than data from `config`
67
+ // like the prefixes: nothing in the agent reads it back, and a missing
68
+ // config key would put a broken header on every batch. The value is
69
+ // pinned by worker-degraded-reply.spec.ts.
70
+ "x-observe-ingest-modes": "reduced, trimmed, paced, errors-only",
65
71
  };
66
72
  // Omitted rather than sent empty when unconfigured: a collector in
67
73
  // placeholder mode accepts an unauthenticated batch, and blank credentials
@@ -71,62 +77,87 @@ describeRefusal) => {
71
77
  headers["x-api-secret"] = config.appSecret;
72
78
  }
73
79
  /**
74
- * Whether the collector has already refused these credentials.
80
+ * How many times the collector has refused these credentials since
81
+ * start-up.
75
82
  *
76
- * Rejected credentials do not recover on their own: the values arrive in the
77
- * environment and are read once at start-up, so nothing short of a restart
78
- * can change the answer. Reporting it on every flush therefore adds no
79
- * information and costs a line every few seconds - 535 identical errors in
80
- * half an hour, in the run that prompted this - which buries whatever else
81
- * the service was trying to say.
82
- *
83
- * Said once, in full, and then only counted. Flushing continues either way:
84
- * the batch is dropped rather than queued, so a fixed deployment starts
85
- * reporting again without anything to drain.
83
+ * Reporting every rejection adds no information and once cost a line every
84
+ * few seconds - 535 identical errors in half an hour, in the run that
85
+ * prompted this - which buries whatever else the service was trying to
86
+ * say. So the first is said in full and the rest are only counted.
86
87
  */
87
88
  let authRejections = 0;
88
89
  /**
89
- * How many rejected batches between reminders. At the default five-second
90
- * flush this is roughly hourly - often enough that a long-running process
91
- * silently dropping telemetry is still visible in a day's logs, rare enough
92
- * that it never competes with anything.
90
+ * How many rejections between reminders.
91
+ *
92
+ * Chosen when every flush was sent into the rejection, which made it
93
+ * roughly hourly at the default five-second flush. Sends now back off (see
94
+ * `authBackoffMs`) to one an hour, so at that flush the same count comes
95
+ * round after about a month: a reminder for a process that has been failing
96
+ * for that long, not the hourly line it used to be.
93
97
  */
94
98
  const AUTH_REJECTION_REPORT_EVERY = 720;
95
99
  /**
96
- * When sending may resume after the collector answered 429.
100
+ * When sending may resume after the collector refused a batch: a 429, or
101
+ * rejected credentials (401/403).
97
102
  *
98
- * A 429 means the account is out of credits or over budget, and that does
99
- * not change batch to batch: retrying at the flush cadence is sixty more
100
- * refusals in five minutes, each costing the collector a request and this
101
- * process a log line. So sends pause outright. The main thread keeps
102
- * overwriting the shared buffer with newer batches in the meantime - the
103
- * buffer holds exactly one, so pausing drops data by replacement rather
104
- * than growing a queue - and once the pause lapses the next flush goes out
105
- * normally. If the collector is still refusing, it answers 429 again and
106
- * the pause restarts.
103
+ * Neither changes batch to batch - an account out of credits stays out for
104
+ * minutes at least, and credentials are read once at start-up - so
105
+ * retrying at the flush cadence only buys more refusals, each costing the
106
+ * collector a request and this process a log line. So sends pause
107
+ * outright. The main thread keeps overwriting the shared buffer with newer
108
+ * batches in the meantime - the buffer holds exactly one, so pausing drops
109
+ * data by replacement rather than growing a queue - and once the pause
110
+ * lapses the next flush goes out normally. If the collector is still
111
+ * refusing, it answers the same again and the pause restarts.
107
112
  */
108
- let rateLimitedUntil = 0;
113
+ let pausedUntil = 0;
109
114
  /**
110
- * How long to pause when the 429 carries no usable Retry-After. Long enough
115
+ * How long to pause when a 429 carries no usable Retry-After. Long enough
111
116
  * that a depleted account is not being polled, short enough that a topped-up
112
117
  * one resumes within minutes.
113
118
  */
114
119
  const RATE_LIMIT_PAUSE_MS = 5 * 60 * 1000;
115
- /** Ceiling on a server-sent Retry-After, so a bad header cannot park the
116
- * worker for a day. */
117
- const RATE_LIMIT_PAUSE_MAX_MS = 60 * 60 * 1000;
118
120
  /**
119
- * How long to pause for, from the response's Retry-After when it carries
120
- * one. Only the delta-seconds form is parsed - the HTTP-date form is rare
121
- * on rate limits and mis-parsing it risks an enormous pause - and anything
122
- * absent, malformed, or out of range falls back to the default.
121
+ * The longest any pause lasts: the ceiling on a server-sent Retry-After, so
122
+ * a bad header cannot park the worker for a day, and where the backoff after
123
+ * rejected credentials stops doubling.
124
+ */
125
+ const PAUSE_MAX_MS = 60 * 60 * 1000;
126
+ /**
127
+ * The pause after the latest of a run of rejected credentials, before any
128
+ * Retry-After: one flush interval after the first, doubling with each one
129
+ * after it up to `PAUSE_MAX_MS`, then one probe an hour. 0 until the first,
130
+ * and again once the collector accepts a batch.
131
+ *
132
+ * Every flush used to be sent into the rejection, and at the hosted
133
+ * collector that added up: on 2026-10-15 it refused 1.87M batches - 38% of
134
+ * every request it served - from about 2,000 addresses presenting a deleted
135
+ * key, a wrong secret or none at all, many of them every five seconds for
136
+ * weeks. Nothing changes for such a process until someone fixes its
137
+ * credentials and restarts it. The quick first retries cover a collector
138
+ * that refused a good key by mistake; the hourly probe picks up a fix on
139
+ * its side within the hour.
123
140
  */
124
- const rateLimitPauseMs = (response) => {
141
+ let authBackoffMs = 0;
142
+ /**
143
+ * Where the backoff starts. Falls back to the default flush when the config
144
+ * carries no usable interval, rather than not backing off at all.
145
+ */
146
+ const AUTH_BACKOFF_BASE_MS = Number.isFinite(config.flushInterval) && config.flushInterval > 0
147
+ ? config.flushInterval
148
+ : 5000;
149
+ /**
150
+ * The pause a response's Retry-After asks for, or null when it carries
151
+ * none. Only the delta-seconds form is parsed - the HTTP-date form is rare
152
+ * on refusals and mis-parsing it risks an enormous pause - and anything
153
+ * absent, malformed, or out of range counts as none.
154
+ */
155
+ const retryAfterMs = (response) => {
125
156
  const retryAfter = Number(response.headers.get("retry-after"));
126
157
  if (Number.isFinite(retryAfter) && retryAfter > 0) {
127
- return Math.min(retryAfter * 1000, RATE_LIMIT_PAUSE_MAX_MS);
158
+ return Math.min(retryAfter * 1000, PAUSE_MAX_MS);
128
159
  }
129
- return RATE_LIMIT_PAUSE_MS;
160
+ return null;
130
161
  };
131
162
  /**
132
163
  * How long to block waiting for the main thread to release the lock, and how
@@ -349,10 +380,10 @@ describeRefusal) => {
349
380
  * immediately or to sleep first.
350
381
  */
351
382
  const sendInstrumentationJsonData = async () => {
352
- if (Date.now() < rateLimitedUntil) {
353
- // Rate-limited: not even worth taking the lock. Returning false routes
354
- // through the idle sleep, and the main thread goes on replacing the
355
- // buffered batch with fresher ones.
383
+ if (Date.now() < pausedUntil) {
384
+ // Paused after a refusal: not even worth taking the lock. Returning
385
+ // false routes through the idle sleep, and the main thread goes on
386
+ // replacing the buffered batch with fresher ones.
356
387
  return false;
357
388
  }
358
389
  waitWhileLocked();
@@ -406,32 +437,42 @@ describeRefusal) => {
406
437
  if (!response.ok) {
407
438
  if (response.status === 401 || response.status === 403) {
408
439
  authRejections += 1;
409
- // Nothing will be accepted until a restart, so a final flush has
410
- // nothing to wait for.
411
- parentPort.postMessage(`${pausedPrefix}${Number.MAX_SAFE_INTEGER}`);
440
+ authBackoffMs =
441
+ authBackoffMs === 0
442
+ ? Math.min(AUTH_BACKOFF_BASE_MS, PAUSE_MAX_MS)
443
+ : Math.min(authBackoffMs * 2, PAUSE_MAX_MS);
444
+ // The collector's own word on when to come back wins. The backoff
445
+ // still advances under it, so a collector that sends one only
446
+ // some of the time cannot hold the retries at the flush cadence.
447
+ pausedUntil = Date.now() + (retryAfterMs(response) ?? authBackoffMs);
448
+ // The slot is left alone until then, which a final flush would
449
+ // otherwise read as a send still in progress.
450
+ parentPort.postMessage(`${pausedPrefix}${pausedUntil}`);
412
451
  // Said plainly, and once. The batch is well-formed and the
413
452
  // credentials are not accepted for this application; left as a
414
453
  // generic transport failure this reads as a network problem, and the
415
454
  // fix - appKey and appSecret - is nowhere in the message.
416
455
  if (authRejections === 1) {
417
456
  parentPort.postMessage(`Error: Telemetry rejected (${response.status}). Check that appKey and appSecret are valid; ` +
418
- `the application is taken from the key. Credentials are read once at start-up, so this ` +
419
- `will not recover without a restart - further rejections are counted, not logged.`);
457
+ `the application is taken from the key. Credentials are read once at start-up, so fixing them ` +
458
+ `takes a restart. Until then sends back off to one attempt an hour and batches in between are ` +
459
+ `dropped - further rejections are counted, not logged.`);
420
460
  }
421
461
  else if (authRejections % AUTH_REJECTION_REPORT_EVERY === 0) {
422
462
  // A periodic reminder, rare enough not to bury anything. Without
423
- // it a process that has been dropping telemetry for a day looks
463
+ // it a process that has been dropping telemetry for weeks looks
424
464
  // exactly like one that is healthy.
425
- parentPort.postMessage(`Error: Telemetry still rejected (${response.status}); ${authRejections} batches dropped since start-up.`);
465
+ parentPort.postMessage(`Error: Telemetry still rejected (${response.status}); ${authRejections} attempts refused since ` +
466
+ `start-up, and every batch in between was dropped.`);
426
467
  }
427
468
  return true;
428
469
  }
429
470
  if (response.status === 429) {
430
- const pauseMs = rateLimitPauseMs(response);
431
- rateLimitedUntil = Date.now() + pauseMs;
471
+ const pauseMs = retryAfterMs(response) ?? RATE_LIMIT_PAUSE_MS;
472
+ pausedUntil = Date.now() + pauseMs;
432
473
  // The slot is left alone until then, which a final flush would
433
474
  // otherwise read as a send still in progress.
434
- parentPort.postMessage(`${pausedPrefix}${rateLimitedUntil}`);
475
+ parentPort.postMessage(`${pausedPrefix}${pausedUntil}`);
435
476
  // The body says which refusal this is - a quota, a quota frozen by
436
477
  // a declined payment, or a rate cap - and each needs a different
437
478
  // fix from the operator. Parsed defensively: a rate-cap body is
@@ -459,14 +500,19 @@ describeRefusal) => {
459
500
  (errorBody ? ` - ${errorBody.slice(0, 500)}` : ""));
460
501
  return true;
461
502
  }
503
+ // Accepted, so whatever refused these credentials no longer does: a
504
+ // later rejection starts the backoff over from the flush interval.
505
+ authBackoffMs = 0;
462
506
  /*
463
507
  * The collector answers 200 while it is discarding the spans in the
464
- * batch - an account past its plan's allowance, or a paying one past
465
- * its trim threshold, keeps its requests, jobs and errors and loses the
466
- * trace trees of all but its notable traces. Nothing in the status says
467
- * so, so the body is the only way to learn it, and an agent that does
468
- * not look keeps building, serializing and gzipping trees that die on
469
- * arrival.
508
+ * batch - an account past its plan's allowance, a paying one past its
509
+ * trim threshold, or a Free one whose day passed its daily limit, keeps
510
+ * its requests, jobs and errors and loses the trace trees of all but
511
+ * its notable traces. A paying account whose overage is paused keeps
512
+ * less again: its server errors, without their trees. Nothing in the
513
+ * status says so, so the body is the only way to learn it, and an agent
514
+ * that does not look keeps building, serializing and gzipping trees
515
+ * that die on arrival.
470
516
  *
471
517
  * Read defensively and treated as absent on anything unexpected: an
472
518
  * older collector returns no body at all, and a parse failure here must
@@ -474,14 +520,34 @@ describeRefusal) => {
474
520
  */
475
521
  const accepted = await response.json().catch(() => undefined);
476
522
  const reply = (typeof accepted === "object" && accepted !== null ? accepted : {});
477
- // `false`, `true` or `trimmed`. `trimmed` says only why the spans are
478
- // discarded, so it counts only beside `degraded`; a collector that never
479
- // sends it gets exactly the line it always did.
523
+ // `false`, `true`, `trimmed`, `paced` or `errors-only`. `trimmed`,
524
+ // `paced` and `errorsOnly` say only why or how the spans are discarded,
525
+ // so they count only beside `degraded`; a collector that sends none of
526
+ // them gets exactly the line it always did.
527
+ //
528
+ // The collector never sends `trimmed` and `paced` together - trimming
529
+ // is a paying account's, pacing a Free one's. Should a reply carry both,
530
+ // `trimmed` wins, in the order the collector itself checks them: it is
531
+ // the paying account's reading, and the one that promises nothing about
532
+ // 00:00 UTC. `errorsOnly` wins over both, in the same order: a paused
533
+ // account is answered errors-only whatever else holds for it.
534
+ //
535
+ // The pause's reason rides after a colon, for the notice - but only a
536
+ // reason the main thread has words for. The value is the collector's;
537
+ // anything else leaves the bare `errors-only`, which withholds just the
538
+ // same and words the notice without a reason.
539
+ const pauseReason = reply.reason === "spike" || reply.reason === "budget"
540
+ ? `:${reply.reason}`
541
+ : "";
480
542
  const verdict = reply.degraded !== true
481
543
  ? "false"
482
- : reply.trimmed === true
483
- ? "trimmed"
484
- : "true";
544
+ : reply.errorsOnly === true
545
+ ? `errors-only${pauseReason}`
546
+ : reply.trimmed === true
547
+ ? "trimmed"
548
+ : reply.paced === true
549
+ ? "paced"
550
+ : "true";
485
551
  // A protocol line, not prose: the parent keys off the prefix and the
486
552
  // value, and is the side that decides what to do about it.
487
553
  parentPort.postMessage(`${degradedPrefix}${verdict}`);
@@ -1,3 +1,4 @@
1
+ import { IngestMode } from "./degraded-ingest.protocol.js";
1
2
  import { Counter, Gauge, Summary } from "../custom-metrics/index.js";
2
3
  import { ObjectivesRegistry } from "../objectives/objectives.registry.js";
3
4
  import { JobSnapshot } from "../interfaces/job-snapshot.interface.js";
@@ -77,6 +78,24 @@ export declare class ObserveAgentSharedBuffer {
77
78
  * persisting a guess across restarts.
78
79
  */
79
80
  private degradedUntil;
81
+ /**
82
+ * Whether that answer was errors-only: the account's overage is paused, and
83
+ * only its server errors are kept. It holds as long as the window above and
84
+ * not a moment longer.
85
+ */
86
+ private errorsOnly;
87
+ /**
88
+ * Requests and jobs that errors-only ingest withheld from the batch being
89
+ * built, cleared with it.
90
+ *
91
+ * Counted against `maxTracesPerBatch` as though they had been sent, so a
92
+ * pause grades the same executions a batch would carry outside one: what
93
+ * is reported withheld is what the collector would have been sent and
94
+ * billed, and a busy service encodes no more per batch than it does
95
+ * outside a pause. A server error past the cap is lost, as it would be.
96
+ */
97
+ private withheldSnapshots;
98
+ private withheldJobs;
80
99
  /**
81
100
  * Records what the collector said about the last batch.
82
101
  *
@@ -84,9 +103,29 @@ export declare class ObserveAgentSharedBuffer {
84
103
  * the account stays over its allowance and lapses on its own once it does
85
104
  * not - the collector has no way to announce the end of it, and an upgrade
86
105
  * must not need a restart to take effect.
106
+ *
107
+ * Each reply replaces the last whole: one that is not errors-only ends
108
+ * errors-only ingest at once, whatever it says instead.
109
+ */
110
+ setIngestMode(mode: IngestMode): void;
111
+ /**
112
+ * Whether trees the collector discards are being withheld: in every mode
113
+ * but `full`, until the window lapses.
87
114
  */
88
- setDegraded(degraded: boolean): void;
89
115
  isDegraded(): boolean;
116
+ /** Whether only server errors are being sent, until the same window lapses. */
117
+ isErrorsOnly(): boolean;
118
+ /**
119
+ * What errors-only ingest makes of one execution: whether it is sent.
120
+ *
121
+ * Its tree never is, server error or not - the collector stores no tree of
122
+ * a paused account's, and a 5xx storm would otherwise ship every failure's
123
+ * whole waterfall - so its nodes are counted and the array emptied, as
124
+ * degraded ingest empties it. One that is not a server error is not sent at
125
+ * all, and counts itself and the error it carried on top: the same events,
126
+ * in the same units, as the collector counts when it filters a batch itself.
127
+ */
128
+ private sendsWhileErrorsOnly;
90
129
  /**
91
130
  * Adds a withheld tree to the batch's reported truncation.
92
131
  *
@@ -96,6 +135,20 @@ export declare class ObserveAgentSharedBuffer {
96
135
  * actually produced.
97
136
  */
98
137
  private countTruncated;
138
+ /** Adds withheld events, in billed units, to the batch's `truncatedSpans`. */
139
+ private countWithheld;
140
+ /**
141
+ * Takes the log records out of the outgoing batch while errors-only ingest
142
+ * holds, one withheld event each - error-level records too: a crash loop
143
+ * logs faster than it fails requests.
144
+ *
145
+ * Done as the batch is written rather than as lines arrive, so a batch
146
+ * counts exactly the records it would have carried - its share of the
147
+ * per-batch cap and of the backlog, as outside a pause - which is what the
148
+ * collector counts when it drops a batch's logs itself. Counted at the door,
149
+ * a chatty service would report lines the cap was always going to drop.
150
+ */
151
+ private withholdLogs;
99
152
  /**
100
153
  * `maxTracesPerBatch`, held to the most the collector accepts in one section
101
154
  * of a batch. It refuses a batch holding more whole, so a setting above that
@@ -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, } 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";
@@ -106,23 +106,38 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
106
106
  this._mainThreadBuffer = this.createEmptyPayload();
107
107
  }
108
108
  const maxPerBatch = this.maxOperationsPerBatch;
109
- if (this._mainThreadBuffer.snapshots.length >= maxPerBatch) {
109
+ if (this._mainThreadBuffer.snapshots.length + this.withheldSnapshots >=
110
+ maxPerBatch) {
110
111
  if (this.options.debug) {
111
112
  this.logger.debug(`Max snapshots per transaction reached: ${maxPerBatch}. Ignoring snapshot.`);
112
113
  }
113
114
  return;
114
115
  }
115
116
  const encodedSnapshot = RequestSnapshotEncoder.encode(snapshot);
116
- if (this.isDegraded() && !isNotableSnapshot(encodedSnapshot)) {
117
- // The collector is discarding these on arrival; shipping them costs the
118
- // application its own CPU and bandwidth for nothing. The snapshot still
119
- // goes - the request, its duration and its error are what the charts
120
- // are built from, and those are still being kept - and the count goes
121
- // with it, because it is the only record these existed.
122
- this.countTruncated(encodedSnapshot.t);
123
- encodedSnapshot.t = [];
124
- }
125
- this._mainThreadBuffer.snapshots.push(encodedSnapshot);
117
+ if (this.isErrorsOnly()) {
118
+ // Decided ahead of the rule below, which keeps more than a paused
119
+ // account does: a slow success is notable, and not a server error.
120
+ // Sent or not, the request still brings its handler's objectives due
121
+ // further down - they are not telemetry.
122
+ if (this.sendsWhileErrorsOnly(encodedSnapshot)) {
123
+ this._mainThreadBuffer.snapshots.push(encodedSnapshot);
124
+ }
125
+ else {
126
+ this.withheldSnapshots += 1;
127
+ }
128
+ }
129
+ else {
130
+ if (this.isDegraded() && !isNotableSnapshot(encodedSnapshot)) {
131
+ // The collector is discarding these on arrival; shipping them costs
132
+ // the application its own CPU and bandwidth for nothing. The snapshot
133
+ // still goes - the request, its duration and its error are what the
134
+ // charts are built from, and those are still being kept - and the
135
+ // count goes with it, because it is the only record these existed.
136
+ this.countTruncated(encodedSnapshot.t);
137
+ encodedSnapshot.t = [];
138
+ }
139
+ this._mainThreadBuffer.snapshots.push(encodedSnapshot);
140
+ }
126
141
  // Read off the raw snapshot: the handler's span carries `Class.method`,
127
142
  // which is what `@Objective` declarations are keyed by. Declarations are
128
143
  // not telemetry, so they ride even a degraded batch - but a batch holds
@@ -151,20 +166,33 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
151
166
  // the worker service - the process that sees every queue job - grows this
152
167
  // array for as long as the stall lasts.
153
168
  const maxPerBatch = this.maxOperationsPerBatch;
154
- if (this._mainThreadBuffer.jobs.length >= maxPerBatch) {
169
+ if (this._mainThreadBuffer.jobs.length + this.withheldJobs >= maxPerBatch) {
155
170
  if (this.options.debug) {
156
171
  this.logger.debug(`Max job snapshots per transaction reached: ${maxPerBatch}. Ignoring snapshot.`);
157
172
  }
158
173
  return;
159
174
  }
160
175
  const encodedJobSnapshot = JobSnapshotEncoder.encode(jobSnapshot);
161
- if (this.isDegraded() && !isNotableSnapshot(encodedJobSnapshot)) {
162
- // A job carries no status code, so the same rule grades it on its error
163
- // and its duration - which is what the collector does with it too.
164
- this.countTruncated(encodedJobSnapshot.t);
165
- encodedJobSnapshot.t = [];
176
+ if (this.isErrorsOnly()) {
177
+ // A job carries no status code, so the error it failed with is what
178
+ // makes it a server error - which is what the collector keeps of it too.
179
+ if (this.sendsWhileErrorsOnly(encodedJobSnapshot)) {
180
+ this._mainThreadBuffer.jobs.push(encodedJobSnapshot);
181
+ }
182
+ else {
183
+ this.withheldJobs += 1;
184
+ }
185
+ }
186
+ else {
187
+ if (this.isDegraded() && !isNotableSnapshot(encodedJobSnapshot)) {
188
+ // A job carries no status code, so the same rule grades it on its
189
+ // error and its duration - which is what the collector does with it
190
+ // too.
191
+ this.countTruncated(encodedJobSnapshot.t);
192
+ encodedJobSnapshot.t = [];
193
+ }
194
+ this._mainThreadBuffer.jobs.push(encodedJobSnapshot);
166
195
  }
167
- this._mainThreadBuffer.jobs.push(encodedJobSnapshot);
168
196
  }
169
197
  /**
170
198
  * Until when the collector's last answer says spans are being discarded.
@@ -175,6 +203,24 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
175
203
  * persisting a guess across restarts.
176
204
  */
177
205
  degradedUntil = 0;
206
+ /**
207
+ * Whether that answer was errors-only: the account's overage is paused, and
208
+ * only its server errors are kept. It holds as long as the window above and
209
+ * not a moment longer.
210
+ */
211
+ errorsOnly = false;
212
+ /**
213
+ * Requests and jobs that errors-only ingest withheld from the batch being
214
+ * built, cleared with it.
215
+ *
216
+ * Counted against `maxTracesPerBatch` as though they had been sent, so a
217
+ * pause grades the same executions a batch would carry outside one: what
218
+ * is reported withheld is what the collector would have been sent and
219
+ * billed, and a busy service encodes no more per batch than it does
220
+ * outside a pause. A server error past the cap is lost, as it would be.
221
+ */
222
+ withheldSnapshots = 0;
223
+ withheldJobs = 0;
178
224
  /**
179
225
  * Records what the collector said about the last batch.
180
226
  *
@@ -182,13 +228,44 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
182
228
  * the account stays over its allowance and lapses on its own once it does
183
229
  * not - the collector has no way to announce the end of it, and an upgrade
184
230
  * must not need a restart to take effect.
231
+ *
232
+ * Each reply replaces the last whole: one that is not errors-only ends
233
+ * errors-only ingest at once, whatever it says instead.
185
234
  */
186
- setDegraded(degraded) {
187
- this.degradedUntil = degraded ? Date.now() + DEGRADED_TTL_MS : 0;
235
+ setIngestMode(mode) {
236
+ this.degradedUntil = mode === "full" ? 0 : Date.now() + DEGRADED_TTL_MS;
237
+ this.errorsOnly = mode === "errors-only";
188
238
  }
239
+ /**
240
+ * Whether trees the collector discards are being withheld: in every mode
241
+ * but `full`, until the window lapses.
242
+ */
189
243
  isDegraded() {
190
244
  return this.degradedUntil > Date.now();
191
245
  }
246
+ /** Whether only server errors are being sent, until the same window lapses. */
247
+ isErrorsOnly() {
248
+ return this.errorsOnly && this.isDegraded();
249
+ }
250
+ /**
251
+ * What errors-only ingest makes of one execution: whether it is sent.
252
+ *
253
+ * Its tree never is, server error or not - the collector stores no tree of
254
+ * a paused account's, and a 5xx storm would otherwise ship every failure's
255
+ * whole waterfall - so its nodes are counted and the array emptied, as
256
+ * degraded ingest empties it. One that is not a server error is not sent at
257
+ * all, and counts itself and the error it carried on top: the same events,
258
+ * in the same units, as the collector counts when it filters a batch itself.
259
+ */
260
+ sendsWhileErrorsOnly(execution) {
261
+ this.countTruncated(execution.t);
262
+ execution.t = [];
263
+ if (isServerErrorSnapshot(execution)) {
264
+ return true;
265
+ }
266
+ this.countWithheld(execution.e ? 2 : 1);
267
+ return false;
268
+ }
192
269
  /**
193
270
  * Adds a withheld tree to the batch's reported truncation.
194
271
  *
@@ -198,11 +275,36 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
198
275
  * actually produced.
199
276
  */
200
277
  countTruncated(traces) {
278
+ this.countWithheld(countTraceNodes(traces));
279
+ }
280
+ /** Adds withheld events, in billed units, to the batch's `truncatedSpans`. */
281
+ countWithheld(events) {
201
282
  if (!this._mainThreadBuffer) {
202
283
  return;
203
284
  }
204
285
  this._mainThreadBuffer.truncatedSpans =
205
- (this._mainThreadBuffer.truncatedSpans ?? 0) + countTraceNodes(traces);
286
+ (this._mainThreadBuffer.truncatedSpans ?? 0) + events;
287
+ }
288
+ /**
289
+ * Takes the log records out of the outgoing batch while errors-only ingest
290
+ * holds, one withheld event each - error-level records too: a crash loop
291
+ * logs faster than it fails requests.
292
+ *
293
+ * Done as the batch is written rather than as lines arrive, so a batch
294
+ * counts exactly the records it would have carried - its share of the
295
+ * per-batch cap and of the backlog, as outside a pause - which is what the
296
+ * collector counts when it drops a batch's logs itself. Counted at the door,
297
+ * a chatty service would report lines the cap was always going to drop.
298
+ */
299
+ withholdLogs() {
300
+ const batch = this._mainThreadBuffer;
301
+ if (!batch?.logs || !this.isErrorsOnly()) {
302
+ return;
303
+ }
304
+ if (batch.logs.length > 0) {
305
+ this.countWithheld(batch.logs.length);
306
+ }
307
+ delete batch.logs;
206
308
  }
207
309
  /**
208
310
  * `maxTracesPerBatch`, held to the most the collector accepts in one section
@@ -385,6 +487,7 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
385
487
  TRUNCATION_SUFFIX);
386
488
  }
387
489
  encodeAndWrite() {
490
+ this.withholdLogs();
388
491
  if (this.options.debug) {
389
492
  if (this._mainThreadBuffer?.snapshots) {
390
493
  this.logger.debug(`Encoding and writing ${this._mainThreadBuffer.snapshots.length} snapshots to shared buffer.`);
@@ -416,6 +519,8 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
416
519
  }
417
520
  resetMainThreadBuffer() {
418
521
  this._mainThreadBuffer = null;
522
+ this.withheldSnapshots = 0;
523
+ this.withheldJobs = 0;
419
524
  }
420
525
  createEmptyPayload() {
421
526
  const payload = {
@@ -29,7 +29,8 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
29
29
  private shutdownPromise;
30
30
  /**
31
31
  * Until when the worker has said it will send nothing (epoch ms) - after a
32
- * 429, or for good after rejected credentials. Read by the final flush only.
32
+ * 429 or rejected credentials, until that pause lapses. Read by the final
33
+ * flush only.
33
34
  */
34
35
  private sendsPausedUntil;
35
36
  constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, nodeRuntimeMetricsService: NodeRuntimeMetricsService, operationTraceRegistry?: OperationTraceRegistry | undefined);
@@ -122,6 +123,31 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
122
123
  */
123
124
  private addFinalRuntimeMetrics;
124
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
+ /**
145
+ * Whether `enabled: false` switched the agent off - whatever the
146
+ * credentials, and whichever collector `endpoint` names.
147
+ */
148
+ private get isDisabled();
149
+ /** Whether nothing will be sent, so there is no worker to feed. */
150
+ private get sendsNothing();
125
151
  private get endpoint();
126
152
  /**
127
153
  * Says out loud when credentials are about to cross the network unencrypted.
@@ -146,6 +172,13 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
146
172
  * per flush would bury the one thing worth reading.
147
173
  */
148
174
  private reportedMode;
175
+ /**
176
+ * Why the account's overage is paused, when the last reply was errors-only
177
+ * and gave a reason this agent can word; null otherwise. Kept beside
178
+ * `reportedMode` for the same reason, and a pause whose reason changes -
179
+ * spike protection's, then a spent budget's - is said again.
180
+ */
181
+ private reportedPauseReason;
149
182
  /**
150
183
  * Stops sending trace trees the collector has told us it is throwing away,
151
184
  * and says so once - and again only when the reason changes.
@@ -155,6 +188,10 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
155
188
  * that out by opening a trace and seeing nothing has been let down by an
156
189
  * agent that knew. Each line says what is still kept, because the traces
157
190
  * worth opening - server errors, slow requests, failed jobs - still are.
191
+ *
192
+ * Except while the account's overage is paused, when next to nothing is
193
+ * kept and nothing comes back on its own before the month ends: that line
194
+ * says so, and who can change it.
158
195
  */
159
196
  private applyIngestMode;
160
197
  handleError(error: Error): void;