@nestjs/observe 0.3.10 → 0.3.12

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.
package/README.md CHANGED
@@ -80,6 +80,12 @@ OBSERVE_APP_SECRET=...
80
80
  ```
81
81
 
82
82
  Without valid credentials the collector answers `401` and telemetry is dropped.
83
+ The agent says so once, then backs off - one flush interval, then two, then
84
+ four, up to one attempt an hour - until the credentials are fixed. They are
85
+ read at startup, so that takes a restart. Leave `appKey` or `appSecret` unset
86
+ and nothing is sent to the hosted collector at all, with a warning at startup
87
+ instead; a collector of your own at `endpoint` still receives batches without
88
+ them.
83
89
 
84
90
  ## Quick start
85
91
 
@@ -352,7 +358,7 @@ Every option, with its default. The [documentation](https://www.observe.nestjs.c
352
358
  | `traceIdGenerator` | the `x-request-id` header, else a UUIDv7 | Gives each request its trace id. |
353
359
  | `traceIdKey` | `'traceId'` | The key the trace id is stored under in the request context. |
354
360
  | `attachTraceIdToLogs` | `true` | Adds the trace id to the `ConsoleLogger`'s own output, on Nest 11.2 and later. Sending lines to the dashboard is `forwardLogs`. |
355
- | `skipInstrumentation` | `() => false` | Returns `true` for a provider instance that must not be instrumented. |
361
+ | `skipInstrumentation` | `() => false` | Returns `true` for a provider instance that must not be instrumented. Nest's `Reflector` never is, whatever this returns. |
356
362
 
357
363
  ## Optional peer dependencies
358
364
 
@@ -6,25 +6,61 @@
6
6
  * is already strings - every other line it posts is human-readable prose the
7
7
  * parent logs - and a second message shape would have to be threaded through
8
8
  * the same handler anyway. Parsed in exactly one place on each side.
9
+ *
10
+ * The value after it is `false`, `true`, `trimmed` or `paced` - see
11
+ * `IngestMode`.
9
12
  */
10
13
  export declare const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
14
+ /**
15
+ * What the collector said it does with a batch's spans.
16
+ *
17
+ * - `full`: keeps them all.
18
+ * - `reduced`: the account has used its monthly allowance - Free's reduced
19
+ * ingest - and only notable traces keep their spans.
20
+ * - `trimmed`: a paying account past its threshold has its traces trimmed by
21
+ * the same rule, to keep its bill down.
22
+ * - `paced`: a Free account still inside its allowance whose UTC day passed a
23
+ * tenth of it has its traces held back by the same rule until 00:00 UTC, so
24
+ * one busy day cannot spend the month.
25
+ *
26
+ * The last three withhold exactly the same trees; they differ only in why,
27
+ * which is what the operator is told and what they can do about it.
28
+ *
29
+ * Every batch says which of them this agent can tell apart, in the request
30
+ * header `x-observe-ingest-modes: reduced, trimmed, paced` (set where the
31
+ * worker builds its headers, credentials or not). The collector reads only
32
+ * `paced`. Agents up to 0.3.11 send no header and take any `degraded: true`
33
+ * for a spent allowance, so a paced account's batches from them are answered
34
+ * `{ degraded: false }` and the collector trims the trees itself: the
35
+ * waterfalls are still held back, and nobody is told their month is gone. Only
36
+ * an agent that lists `paced` is answered `{ degraded: true, paced: true }`,
37
+ * and can stop sending those trees in the first place.
38
+ */
39
+ export type IngestMode = "full" | "reduced" | "trimmed" | "paced";
11
40
  /**
12
41
  * How long the main thread keeps withholding spans after the last batch that
13
42
  * reported degradation.
14
43
  *
15
44
  * The state is advisory and the collector never announces the end of it: an
16
- * upgrade or the turn of the billing period simply starts keeping spans
17
- * again. So it expires on its own, and the cost of it being briefly stale is
18
- * one flush of spans sent and discarded - against a restart being required to
19
- * recover, which is what a sticky flag would have cost.
45
+ * upgrade, the turn of the billing period or, for a paced day, 00:00 UTC
46
+ * simply starts keeping spans again. So it expires on its own, and the cost
47
+ * of it being briefly stale is one flush of spans sent and discarded - against
48
+ * a restart being required to recover, which is what a sticky flag would have
49
+ * cost.
20
50
  */
21
51
  export declare const DEGRADED_TTL_MS: number;
22
- /** The worker's line for one batch, or null if this is not that line. */
23
- export declare function parseDegradedMessage(msg: string): boolean | null;
52
+ /**
53
+ * The worker's line for one batch, or null if this is not that line.
54
+ *
55
+ * `true` and `false` are what the line has always carried, and they mean what
56
+ * they always did; `trimmed` and `paced` are the additions. Anything else
57
+ * reads as `full`, as every value but `true` always has.
58
+ */
59
+ export declare function parseDegradedMessage(msg: string): IngestMode | null;
24
60
  /**
25
61
  * How the detached worker tells the main thread it will send nothing until a
26
- * given time (epoch milliseconds): after a 429, until the pause lapses; after
27
- * rejected credentials, never.
62
+ * given time (epoch milliseconds): after a 429 or rejected credentials, until
63
+ * that pause lapses.
28
64
  *
29
65
  * Only the final flush reads it. A paused worker leaves the shared slot
30
66
  * untouched, so without this a shutdown would wait out its whole deadline for
@@ -6,6 +6,9 @@
6
6
  * is already strings - every other line it posts is human-readable prose the
7
7
  * parent logs - and a second message shape would have to be threaded through
8
8
  * the same handler anyway. Parsed in exactly one place on each side.
9
+ *
10
+ * The value after it is `false`, `true`, `trimmed` or `paced` - see
11
+ * `IngestMode`.
9
12
  */
10
13
  export const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
11
14
  /**
@@ -13,23 +16,39 @@ export const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
13
16
  * reported degradation.
14
17
  *
15
18
  * The state is advisory and the collector never announces the end of it: an
16
- * upgrade or the turn of the billing period simply starts keeping spans
17
- * again. So it expires on its own, and the cost of it being briefly stale is
18
- * one flush of spans sent and discarded - against a restart being required to
19
- * recover, which is what a sticky flag would have cost.
19
+ * upgrade, the turn of the billing period or, for a paced day, 00:00 UTC
20
+ * simply starts keeping spans again. So it expires on its own, and the cost
21
+ * of it being briefly stale is one flush of spans sent and discarded - against
22
+ * a restart being required to recover, which is what a sticky flag would have
23
+ * cost.
20
24
  */
21
25
  export const DEGRADED_TTL_MS = 5 * 60 * 1000;
22
- /** The worker's line for one batch, or null if this is not that line. */
26
+ /**
27
+ * The worker's line for one batch, or null if this is not that line.
28
+ *
29
+ * `true` and `false` are what the line has always carried, and they mean what
30
+ * they always did; `trimmed` and `paced` are the additions. Anything else
31
+ * reads as `full`, as every value but `true` always has.
32
+ */
23
33
  export function parseDegradedMessage(msg) {
24
34
  if (!msg.startsWith(DEGRADED_MESSAGE_PREFIX)) {
25
35
  return null;
26
36
  }
27
- return msg.slice(DEGRADED_MESSAGE_PREFIX.length) === "true";
37
+ switch (msg.slice(DEGRADED_MESSAGE_PREFIX.length)) {
38
+ case "true":
39
+ return "reduced";
40
+ case "trimmed":
41
+ return "trimmed";
42
+ case "paced":
43
+ return "paced";
44
+ default:
45
+ return "full";
46
+ }
28
47
  }
29
48
  /**
30
49
  * How the detached worker tells the main thread it will send nothing until a
31
- * given time (epoch milliseconds): after a 429, until the pause lapses; after
32
- * rejected credentials, never.
50
+ * given time (epoch milliseconds): after a 429 or rejected credentials, until
51
+ * that pause lapses.
33
52
  *
34
53
  * Only the final flush reads it. A paused worker leaves the shared slot
35
54
  * untouched, so without this a shutdown would wait out its whole deadline for
@@ -15,4 +15,5 @@ export declare function detachedWorkerData(input: {
15
15
  endpoint: string;
16
16
  appKey?: string;
17
17
  appSecret?: string;
18
+ flushInterval: number;
18
19
  }): DetachedWorkerData;
@@ -22,6 +22,7 @@ export function detachedWorkerData(input) {
22
22
  endpoint: input.endpoint,
23
23
  appKey: input.appKey,
24
24
  appSecret: input.appSecret,
25
+ flushInterval: input.flushInterval,
25
26
  wireShapes: SECTION_SHAPES,
26
27
  degradedPrefix: DEGRADED_MESSAGE_PREFIX,
27
28
  pausedPrefix: PAUSED_MESSAGE_PREFIX,
@@ -12,6 +12,11 @@ export interface DetachedWorkerConfig {
12
12
  endpoint: string;
13
13
  appKey?: string;
14
14
  appSecret?: string;
15
+ /**
16
+ * Milliseconds between the main thread's flushes, as clamped there: the
17
+ * first pause after rejected credentials, which then doubles.
18
+ */
19
+ flushInterval: number;
15
20
  /** Plain JSON, so it travels as data; the sanitizer that reads it travels as source. */
16
21
  wireShapes: Parameters<typeof createTelemetrySanitizer>[0];
17
22
  /** `DEGRADED_MESSAGE_PREFIX`, as data - see where it is read below. */
@@ -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",
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,25 +500,42 @@ 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 keeps its requests, jobs
465
- * and errors and loses the trace trees underneath them. Nothing in the
466
- * status says so, so the body is the only way to learn it, and an agent
467
- * that does not look keeps building, serializing and gzipping trees
468
- * that die on 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. Nothing in the status says so, so the body is the
512
+ * only way to learn it, and an agent that does not look keeps building,
513
+ * serializing and gzipping trees that die on arrival.
469
514
  *
470
515
  * Read defensively and treated as absent on anything unexpected: an
471
516
  * older collector returns no body at all, and a parse failure here must
472
517
  * never turn a successful send into a reported failure.
473
518
  */
474
519
  const accepted = await response.json().catch(() => undefined);
475
- const degraded = typeof accepted === "object" &&
476
- accepted !== null &&
477
- accepted.degraded === true;
520
+ const reply = (typeof accepted === "object" && accepted !== null ? accepted : {});
521
+ // `false`, `true`, `trimmed` or `paced`. `trimmed` and `paced` say only
522
+ // why the spans are discarded, so they count only beside `degraded`; a
523
+ // collector that sends neither gets exactly the line it always did.
524
+ //
525
+ // The collector never sends both - trimming is a paying account's, pacing
526
+ // a Free one's. Should a reply carry both, `trimmed` wins, in the order
527
+ // the collector itself checks them: it is the paying account's reading,
528
+ // and the one that promises nothing about 00:00 UTC.
529
+ const verdict = reply.degraded !== true
530
+ ? "false"
531
+ : reply.trimmed === true
532
+ ? "trimmed"
533
+ : reply.paced === true
534
+ ? "paced"
535
+ : "true";
478
536
  // A protocol line, not prose: the parent keys off the prefix and the
479
537
  // value, and is the side that decides what to do about it.
480
- parentPort.postMessage(`${degradedPrefix}${degraded}`);
538
+ parentPort.postMessage(`${degradedPrefix}${verdict}`);
481
539
  parentPort.postMessage("Tracing and instrumentation data sent successfully");
482
540
  return true;
483
541
  }
@@ -96,6 +96,12 @@ export declare class ObserveAgentSharedBuffer {
96
96
  * actually produced.
97
97
  */
98
98
  private countTruncated;
99
+ /**
100
+ * `maxTracesPerBatch`, held to the most the collector accepts in one section
101
+ * of a batch. It refuses a batch holding more whole, so a setting above that
102
+ * would cost a busy window every operation in it rather than the overflow.
103
+ */
104
+ private get maxOperationsPerBatch();
99
105
  isBufferLocked(): boolean;
100
106
  isBufferEmpty(): boolean;
101
107
  /** Whether log lines are held back for a later batch. */
@@ -12,6 +12,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
12
  };
13
13
  var ObserveAgentSharedBuffer_1;
14
14
  import { countTraceNodes, DEGRADED_TTL_MS, isNotableSnapshot, } from "./degraded-ingest.protocol.js";
15
+ import { MAX_BATCH_ITEMS } from "./telemetry-wire-contract.js";
15
16
  import { Inject, Injectable, Logger, Optional } from "@nestjs/common";
16
17
  import { Counter, Summary } from "../custom-metrics/index.js";
17
18
  import { ObjectivesRegistry, } from "../objectives/objectives.registry.js";
@@ -104,7 +105,7 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
104
105
  if (!this._mainThreadBuffer) {
105
106
  this._mainThreadBuffer = this.createEmptyPayload();
106
107
  }
107
- const maxPerBatch = this.options.maxTracesPerBatch ?? DEFAULT_MAX_SNAPSHOTS_PER_TRANSACTION;
108
+ const maxPerBatch = this.maxOperationsPerBatch;
108
109
  if (this._mainThreadBuffer.snapshots.length >= maxPerBatch) {
109
110
  if (this.options.debug) {
110
111
  this.logger.debug(`Max snapshots per transaction reached: ${maxPerBatch}. Ignoring snapshot.`);
@@ -149,7 +150,7 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
149
150
  // empties when a flush succeeds, so without a ceiling a stalled flush on
150
151
  // the worker service - the process that sees every queue job - grows this
151
152
  // array for as long as the stall lasts.
152
- const maxPerBatch = this.options.maxTracesPerBatch ?? DEFAULT_MAX_SNAPSHOTS_PER_TRANSACTION;
153
+ const maxPerBatch = this.maxOperationsPerBatch;
153
154
  if (this._mainThreadBuffer.jobs.length >= maxPerBatch) {
154
155
  if (this.options.debug) {
155
156
  this.logger.debug(`Max job snapshots per transaction reached: ${maxPerBatch}. Ignoring snapshot.`);
@@ -203,6 +204,14 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
203
204
  this._mainThreadBuffer.truncatedSpans =
204
205
  (this._mainThreadBuffer.truncatedSpans ?? 0) + countTraceNodes(traces);
205
206
  }
207
+ /**
208
+ * `maxTracesPerBatch`, held to the most the collector accepts in one section
209
+ * of a batch. It refuses a batch holding more whole, so a setting above that
210
+ * would cost a busy window every operation in it rather than the overflow.
211
+ */
212
+ get maxOperationsPerBatch() {
213
+ return Math.min(this.options.maxTracesPerBatch ?? DEFAULT_MAX_SNAPSHOTS_PER_TRANSACTION, MAX_BATCH_ITEMS);
214
+ }
206
215
  isBufferLocked() {
207
216
  return Atomics.load(this.lock, 0) !== 0;
208
217
  }
@@ -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,26 @@ 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
+ /** Whether nothing will be sent, so there is no worker to feed. */
145
+ private get sendsNothing();
125
146
  private get endpoint();
126
147
  /**
127
148
  * Says out loud when credentials are about to cross the network unencrypted.
@@ -139,23 +160,24 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
139
160
  private watchWorker;
140
161
  handleMessage(msg: string): void;
141
162
  /**
142
- * Whether the last reply said the collector is discarding spans.
163
+ * What the last reply said the collector does with spans.
143
164
  *
144
165
  * Kept beside the log rather than read from the buffer so the notice fires
145
166
  * once per transition: an account sits in this state for days, and a line
146
167
  * per flush would bury the one thing worth reading.
147
168
  */
148
- private reportedDegraded;
169
+ private reportedMode;
149
170
  /**
150
171
  * Stops sending trace trees the collector has told us it is throwing away,
151
- * and says so once.
172
+ * and says so once - and again only when the reason changes.
152
173
  *
153
174
  * Said at `warn` rather than `debug`: the application is still being
154
- * observed, the waterfalls are not being kept, and a developer who finds
175
+ * observed, most waterfalls are not being kept, and a developer who finds
155
176
  * that out by opening a trace and seeing nothing has been let down by an
156
- * agent that knew.
177
+ * agent that knew. Each line says what is still kept, because the traces
178
+ * worth opening - server errors, slow requests, failed jobs - still are.
157
179
  */
158
- private applyDegraded;
180
+ private applyIngestMode;
159
181
  handleError(error: Error): void;
160
182
  flush(): void;
161
183
  }