@nestjs/observe 0.3.11 → 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
 
@@ -7,7 +7,8 @@
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
9
  *
10
- * The value after it is `false`, `true`, or `trimmed` - see `IngestMode`.
10
+ * The value after it is `false`, `true`, `trimmed` or `paced` - see
11
+ * `IngestMode`.
11
12
  */
12
13
  export declare const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
13
14
  /**
@@ -18,34 +19,48 @@ export declare const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
18
19
  * ingest - and only notable traces keep their spans.
19
20
  * - `trimmed`: a paying account past its threshold has its traces trimmed by
20
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.
21
25
  *
22
- * Both of the last two withhold exactly the same trees; they differ only in
23
- * why, which is what the operator is told and what they can do about it.
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.
24
38
  */
25
- export type IngestMode = "full" | "reduced" | "trimmed";
39
+ export type IngestMode = "full" | "reduced" | "trimmed" | "paced";
26
40
  /**
27
41
  * How long the main thread keeps withholding spans after the last batch that
28
42
  * reported degradation.
29
43
  *
30
44
  * The state is advisory and the collector never announces the end of it: an
31
- * upgrade or the turn of the billing period simply starts keeping spans
32
- * again. So it expires on its own, and the cost of it being briefly stale is
33
- * one flush of spans sent and discarded - against a restart being required to
34
- * 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.
35
50
  */
36
51
  export declare const DEGRADED_TTL_MS: number;
37
52
  /**
38
53
  * The worker's line for one batch, or null if this is not that line.
39
54
  *
40
55
  * `true` and `false` are what the line has always carried, and they mean what
41
- * they always did; `trimmed` is the one addition. Anything else reads as
42
- * `full`, as every value but `true` always has.
56
+ * they always did; `trimmed` and `paced` are the additions. Anything else
57
+ * reads as `full`, as every value but `true` always has.
43
58
  */
44
59
  export declare function parseDegradedMessage(msg: string): IngestMode | null;
45
60
  /**
46
61
  * How the detached worker tells the main thread it will send nothing until a
47
- * given time (epoch milliseconds): after a 429, until the pause lapses; after
48
- * rejected credentials, never.
62
+ * given time (epoch milliseconds): after a 429 or rejected credentials, until
63
+ * that pause lapses.
49
64
  *
50
65
  * Only the final flush reads it. A paused worker leaves the shared slot
51
66
  * untouched, so without this a shutdown would wait out its whole deadline for
@@ -7,7 +7,8 @@
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
9
  *
10
- * The value after it is `false`, `true`, or `trimmed` - see `IngestMode`.
10
+ * The value after it is `false`, `true`, `trimmed` or `paced` - see
11
+ * `IngestMode`.
11
12
  */
12
13
  export const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
13
14
  /**
@@ -15,18 +16,19 @@ export const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
15
16
  * reported degradation.
16
17
  *
17
18
  * The state is advisory and the collector never announces the end of it: an
18
- * upgrade or the turn of the billing period simply starts keeping spans
19
- * again. So it expires on its own, and the cost of it being briefly stale is
20
- * one flush of spans sent and discarded - against a restart being required to
21
- * 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.
22
24
  */
23
25
  export const DEGRADED_TTL_MS = 5 * 60 * 1000;
24
26
  /**
25
27
  * The worker's line for one batch, or null if this is not that line.
26
28
  *
27
29
  * `true` and `false` are what the line has always carried, and they mean what
28
- * they always did; `trimmed` is the one addition. Anything else reads as
29
- * `full`, as every value but `true` always has.
30
+ * they always did; `trimmed` and `paced` are the additions. Anything else
31
+ * reads as `full`, as every value but `true` always has.
30
32
  */
31
33
  export function parseDegradedMessage(msg) {
32
34
  if (!msg.startsWith(DEGRADED_MESSAGE_PREFIX)) {
@@ -37,14 +39,16 @@ export function parseDegradedMessage(msg) {
37
39
  return "reduced";
38
40
  case "trimmed":
39
41
  return "trimmed";
42
+ case "paced":
43
+ return "paced";
40
44
  default:
41
45
  return "full";
42
46
  }
43
47
  }
44
48
  /**
45
49
  * How the detached worker tells the main thread it will send nothing until a
46
- * given time (epoch milliseconds): after a 429, until the pause lapses; after
47
- * rejected credentials, never.
50
+ * given time (epoch milliseconds): after a 429 or rejected credentials, until
51
+ * that pause lapses.
48
52
  *
49
53
  * Only the final flush reads it. A paused worker leaves the shared slot
50
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,14 +500,17 @@ 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. 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.
470
514
  *
471
515
  * Read defensively and treated as absent on anything unexpected: an
472
516
  * older collector returns no body at all, and a parse failure here must
@@ -474,14 +518,21 @@ describeRefusal) => {
474
518
  */
475
519
  const accepted = await response.json().catch(() => undefined);
476
520
  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.
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.
480
529
  const verdict = reply.degraded !== true
481
530
  ? "false"
482
531
  : reply.trimmed === true
483
532
  ? "trimmed"
484
- : "true";
533
+ : reply.paced === true
534
+ ? "paced"
535
+ : "true";
485
536
  // A protocol line, not prose: the parent keys off the prefix and the
486
537
  // value, and is the side that decides what to do about it.
487
538
  parentPort.postMessage(`${degradedPrefix}${verdict}`);
@@ -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.
@@ -27,10 +27,15 @@ import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
27
27
  const DEFAULT_RUNTIME_METRICS_INTERVAL = 60000; // 60 seconds
28
28
  const MIN_RUNTIME_METRICS_INTERVAL = 30000; // 30 seconds
29
29
  const DEFAULT_FLUSH_INTERVAL = 5000; // 5 seconds
30
+ /**
31
+ * The hosted collector. Unlike a collector in placeholder mode, it accepts
32
+ * nothing without credentials.
33
+ */
34
+ const HOSTED_COLLECTOR_ENDPOINT = "https://observe-api.nestjs.com";
30
35
  /**
31
36
  * Where signals are posted when `endpoint` is not configured.
32
37
  */
33
- const DEFAULT_COLLECTOR_ENDPOINT = process.env.OBSERVE_ENDPOINT ?? "https://observe-api.nestjs.com";
38
+ const DEFAULT_COLLECTOR_ENDPOINT = process.env.OBSERVE_ENDPOINT ?? HOSTED_COLLECTOR_ENDPOINT;
34
39
  const MIN_FLUSH_INTERVAL = 1000; // 1 second
35
40
  /**
36
41
  * How long shutdown waits for buffered telemetry to reach the collector before
@@ -100,7 +105,8 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
100
105
  shutdownPromise = null;
101
106
  /**
102
107
  * Until when the worker has said it will send nothing (epoch ms) - after a
103
- * 429, or for good after rejected credentials. Read by the final flush only.
108
+ * 429 or rejected credentials, until that pause lapses. Read by the final
109
+ * flush only.
104
110
  */
105
111
  sendsPausedUntil = 0;
106
112
  constructor(observeAgentSharedBuffer, options, nodeRuntimeMetricsService, operationTraceRegistry) {
@@ -110,6 +116,17 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
110
116
  this.operationTraceRegistry = operationTraceRegistry;
111
117
  }
112
118
  onModuleInit() {
119
+ // Settled before the worker starts, which backs off from this interval
120
+ // after rejected credentials - as does a worker restarted later on.
121
+ let flushIntervalTime = this.options.flushInterval ?? DEFAULT_FLUSH_INTERVAL;
122
+ if (flushIntervalTime < MIN_FLUSH_INTERVAL) {
123
+ this.logger.warn(`Flush interval is too short (${flushIntervalTime}ms). Setting to minimum of ${MIN_FLUSH_INTERVAL}ms.`);
124
+ // Clamp the value the timer is armed with, not just the recorded option:
125
+ // the warning above used to be a lie, and a `flushInterval: 50` flushed
126
+ // twenty times a second while claiming it had been raised to 1s.
127
+ flushIntervalTime = MIN_FLUSH_INTERVAL;
128
+ this.options.flushInterval = MIN_FLUSH_INTERVAL;
129
+ }
113
130
  if (this.hasScaffoldCredentials) {
114
131
  // Nothing is sent, so there is no worker to start. The flush timer below
115
132
  // still runs and empties the buffer, which the instrumentation keeps
@@ -117,20 +134,22 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
117
134
  this.logger.log(`Observe is installed but not connected yet: appKey and appSecret are still the placeholders from nest new, so no telemetry is sent. ` +
118
135
  `See what this app will look like: ${DEMO_URL} - then create a free account at ${SIGN_UP_URL} for your own key and secret.`);
119
136
  }
137
+ else if (this.lacksHostedCredentials) {
138
+ // The same arrangement, said as a warning: this is a deployment missing
139
+ // its configuration, not a project fresh from the generator.
140
+ const unset = !this.options.appKey && !this.options.appSecret
141
+ ? "appKey and appSecret are"
142
+ : !this.options.appKey
143
+ ? "appKey is"
144
+ : "appSecret is";
145
+ this.logger.warn(`Observe is installed but sends nothing: ${unset} not set, and the hosted collector accepts no telemetry without a key and a secret. ` +
146
+ `If they come from the environment, check that both variables reach this process, then restart it. Create a key and secret at ${SIGN_UP_URL}.`);
147
+ }
120
148
  else {
121
149
  this.initializeWorker();
122
150
  }
123
- let flushIntervalTime = this.options.flushInterval ?? DEFAULT_FLUSH_INTERVAL;
124
- if (flushIntervalTime < MIN_FLUSH_INTERVAL) {
125
- this.logger.warn(`Flush interval is too short (${flushIntervalTime}ms). Setting to minimum of ${MIN_FLUSH_INTERVAL}ms.`);
126
- // Clamp the value the timer is armed with, not just the recorded option:
127
- // the warning above used to be a lie, and a `flushInterval: 50` flushed
128
- // twenty times a second while claiming it had been raised to 1s.
129
- flushIntervalTime = MIN_FLUSH_INTERVAL;
130
- this.options.flushInterval = MIN_FLUSH_INTERVAL;
131
- }
132
151
  this.flushInterval = setInterval(() => this.flush(), flushIntervalTime);
133
- if (!this.hasScaffoldCredentials) {
152
+ if (!this.sendsNothing) {
134
153
  this.startRuntimeMetrics();
135
154
  }
136
155
  // Continuous profiling is shelved: a flame graph asks more of a reader than
@@ -262,8 +281,9 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
262
281
  await this.cpuProfiler.stop();
263
282
  this.cpuProfiler = null;
264
283
  }
265
- // No worker - scaffold credentials, or never started - means nothing was
266
- // ever going to be sent, so there is nothing to flush either.
284
+ // No worker - placeholder or missing credentials, or never started -
285
+ // means nothing was ever going to be sent, so there is nothing to flush
286
+ // either.
267
287
  const worker = this.worker;
268
288
  if (!worker) {
269
289
  return;
@@ -420,6 +440,40 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
420
440
  return (this.options.appKey === SCAFFOLD_APP_KEY &&
421
441
  this.options.appSecret === SCAFFOLD_APP_SECRET);
422
442
  }
443
+ /**
444
+ * Whether credentials are missing and the collector is the hosted one,
445
+ * which answers every batch without them with a 401.
446
+ *
447
+ * The worker leaves both headers off when either half is unset, which a
448
+ * collector in placeholder mode accepts, so a collector of the user's own
449
+ * still gets those batches. The hosted collector refuses them for as long
450
+ * as the process runs: on 2026-10-15 that was 42% of the 1.87M batches it
451
+ * refused, from processes deployed without their environment variables,
452
+ * some of them posting every five seconds for weeks.
453
+ */
454
+ get lacksHostedCredentials() {
455
+ return ((!this.options.appKey || !this.options.appSecret) &&
456
+ this.isHostedCollector);
457
+ }
458
+ /**
459
+ * Whether `endpoint` - set, from `OBSERVE_ENDPOINT`, or the default - is the
460
+ * hosted collector. Compared by host, so a trailing slash or a capital
461
+ * letter cannot pass it off as a collector of the user's own.
462
+ */
463
+ get isHostedCollector() {
464
+ try {
465
+ return (new URL(this.endpoint).hostname ===
466
+ new URL(HOSTED_COLLECTOR_ENDPOINT).hostname);
467
+ }
468
+ catch {
469
+ // Not a URL at all; the worker says so when it tries to send.
470
+ return false;
471
+ }
472
+ }
473
+ /** Whether nothing will be sent, so there is no worker to feed. */
474
+ get sendsNothing() {
475
+ return this.hasScaffoldCredentials || this.lacksHostedCredentials;
476
+ }
423
477
  get endpoint() {
424
478
  return this.options.endpoint ?? DEFAULT_COLLECTOR_ENDPOINT;
425
479
  }
@@ -465,6 +519,8 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
465
519
  endpoint: this.endpoint,
466
520
  appKey: this.options.appKey,
467
521
  appSecret: this.options.appSecret,
522
+ // Clamped by `onModuleInit` before the first worker starts.
523
+ flushInterval: this.options.flushInterval ?? DEFAULT_FLUSH_INTERVAL,
468
524
  }),
469
525
  });
470
526
  this.watchWorker(this.worker);
@@ -526,7 +582,8 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
526
582
  * worth opening - server errors, slow requests, failed jobs - still are.
527
583
  */
528
584
  applyIngestMode(mode) {
529
- // Reduced and trimmed withhold the same trees; only the notice differs.
585
+ // Reduced, trimmed and paced withhold the same trees; only the notice
586
+ // differs.
530
587
  this.observeAgentSharedBuffer.setDegraded(mode !== "full");
531
588
  if (mode === this.reportedMode) {
532
589
  return;
@@ -541,6 +598,13 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
541
598
  "Requests, jobs and errors are still recorded, and server errors, slow requests and failed jobs keep their full traces. " +
542
599
  'To keep every trace, turn on "Keep full traces" at /dashboard/billing/usage.');
543
600
  }
601
+ else if (mode === "paced") {
602
+ // Not the reduced line: the allowance is not spent, and the spans come
603
+ // back at midnight UTC without the operator doing anything.
604
+ this.logger.warn("Observe: this account's day passed the Free plan's daily limit, so most traces arrive without their spans until 00:00 UTC. " +
605
+ "Requests, jobs and errors are still recorded, and server errors, slow requests and failed jobs keep their full traces. " +
606
+ "See /dashboard/billing/usage.");
607
+ }
544
608
  else {
545
609
  this.logger.log("Observe: spans are being recorded again.");
546
610
  }
@@ -555,7 +619,7 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
555
619
  // gone quiet, and an empty buffer would otherwise return here and strand
556
620
  // them until shutdown.
557
621
  this.observeAgentSharedBuffer.drainPendingLogs();
558
- if (this.hasScaffoldCredentials) {
622
+ if (this.sendsNothing) {
559
623
  this.observeAgentSharedBuffer.resetMainThreadBuffer();
560
624
  return;
561
625
  }
@@ -142,7 +142,10 @@ export interface ObserveOptions {
142
142
  *
143
143
  * Sent as `x-api-key` on every ingest request, alongside `appSecret`.
144
144
  * Without valid credentials the collector answers 401 and the batch is
145
- * dropped.
145
+ * dropped; the agent then backs off, to one attempt an hour, until a
146
+ * restart picks up fixed credentials. With this or `appSecret` unset,
147
+ * nothing is sent to the hosted collector at all - a warning at startup
148
+ * says so - while a collector of your own still receives the batches.
146
149
  */
147
150
  appKey: string;
148
151
  /**
@@ -1,14 +1,17 @@
1
1
  /**
2
2
  * Explains a 429 from the collector in the operator's terms.
3
3
  *
4
- * The collector refuses ingest for three different reasons, and until this
4
+ * The collector refuses ingest for several different reasons, and until this
5
5
  * existed the agent reported all of them as "the account may be out of
6
6
  * credits or over budget" - which sent an operator whose card had been
7
7
  * declined to the pricing page, and one whose rate cap had engaged to their
8
8
  * invoices. The body tells them apart: a quota refusal carries
9
9
  * `code: "USAGE_LIMIT_REACHED"` with the plan and the counts, and a quota
10
- * refusal caused by a declined payment adds `reason: "payment_failed"`. A
11
- * rate cap, and any older collector, sends neither and gets the old sentence.
10
+ * refusal caused by a declined payment adds `reason: "payment_failed"`.
11
+ * Credentials the collector has already rejected carry
12
+ * `code: "CREDENTIALS_REJECTED"` - a 429 rather than another 401, so that
13
+ * agents which pause only on a 429 stop retrying them. A rate cap, and any
14
+ * older collector, sends none of these and gets the old sentence.
12
15
  *
13
16
  * Written self-contained on purpose - no imports, no module-scope constants -
14
17
  * because the telemetry worker is a stringified function and this travels
@@ -1,14 +1,17 @@
1
1
  /**
2
2
  * Explains a 429 from the collector in the operator's terms.
3
3
  *
4
- * The collector refuses ingest for three different reasons, and until this
4
+ * The collector refuses ingest for several different reasons, and until this
5
5
  * existed the agent reported all of them as "the account may be out of
6
6
  * credits or over budget" - which sent an operator whose card had been
7
7
  * declined to the pricing page, and one whose rate cap had engaged to their
8
8
  * invoices. The body tells them apart: a quota refusal carries
9
9
  * `code: "USAGE_LIMIT_REACHED"` with the plan and the counts, and a quota
10
- * refusal caused by a declined payment adds `reason: "payment_failed"`. A
11
- * rate cap, and any older collector, sends neither and gets the old sentence.
10
+ * refusal caused by a declined payment adds `reason: "payment_failed"`.
11
+ * Credentials the collector has already rejected carry
12
+ * `code: "CREDENTIALS_REJECTED"` - a 429 rather than another 401, so that
13
+ * agents which pause only on a 429 stop retrying them. A rate cap, and any
14
+ * older collector, sends none of these and gets the old sentence.
12
15
  *
13
16
  * Written self-contained on purpose - no imports, no module-scope constants -
14
17
  * because the telemetry worker is a stringified function and this travels
@@ -22,6 +25,12 @@ export const describeIngestRefusal = (body) => {
22
25
  const detail = body !== null && typeof body === "object"
23
26
  ? body
24
27
  : {};
28
+ if (detail.code === "CREDENTIALS_REJECTED") {
29
+ // Nothing to do with the account's usage: the credentials are wrong and
30
+ // the process reads them once, so the fix is valid ones and a restart.
31
+ // The pause that follows only stops the agent asking in the meantime.
32
+ return "appKey and appSecret were rejected; check that both are valid for this application, then restart the process, which reads them once at start-up";
33
+ }
25
34
  if (detail.code !== "USAGE_LIMIT_REACHED") {
26
35
  return "the account may be out of credits or over budget";
27
36
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.3.11",
3
+ "version": "0.3.12",
4
4
  "description": "Observability and APM agent for NestJS - traces, runtime metrics and custom metrics",
5
5
  "author": "Kamil Mysliwiec",
6
6
  "homepage": "https://observe.nestjs.com",