@nestjs/observe 0.3.12 → 0.3.14

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 (36) hide show
  1. package/README.md +65 -2
  2. package/dist/agent/degraded-ingest.protocol.d.ts +82 -26
  3. package/dist/agent/degraded-ingest.protocol.js +60 -19
  4. package/dist/agent/detached-observe-worker.js +31 -16
  5. package/dist/agent/observe-agent.shared-buffer.d.ts +54 -1
  6. package/dist/agent/observe-agent.shared-buffer.js +127 -22
  7. package/dist/agent/observe-agent.worker.d.ts +29 -0
  8. package/dist/agent/observe-agent.worker.js +80 -10
  9. package/dist/agent/telemetry-wire-contract.js +11 -1
  10. package/dist/encoders/request-snapshot.encoder.d.ts +1 -0
  11. package/dist/encoders/request-snapshot.encoder.js +1 -0
  12. package/dist/interfaces/observe-options.interface.d.ts +13 -1
  13. package/dist/interfaces/request-snapshot.interface.d.ts +13 -0
  14. package/dist/objectives/objectives.registry.d.ts +1 -0
  15. package/dist/objectives/objectives.registry.js +12 -0
  16. package/dist/outgoing/mssql.integration.d.ts +12 -0
  17. package/dist/outgoing/mssql.integration.js +248 -0
  18. package/dist/outgoing/mysql2.integration.js +1 -1
  19. package/dist/outgoing/outgoing-observe-agent.service.js +46 -8
  20. package/dist/outgoing/outgoing-span.recorder.d.ts +7 -0
  21. package/dist/outgoing/outgoing-span.recorder.js +15 -0
  22. package/dist/outgoing/pg.integration.js +1 -1
  23. package/dist/outgoing/sql-statement.util.d.ts +5 -1
  24. package/dist/outgoing/sql-statement.util.js +83 -10
  25. package/dist/protocols/http-observe-agent.service.js +9 -2
  26. package/dist/protocols/job-trace-runner.js +5 -0
  27. package/dist/services/node-runtime-metrics.service.js +1 -1
  28. package/dist/services/operation-trace.registry.d.ts +11 -0
  29. package/dist/services/operation-trace.registry.js +37 -1
  30. package/dist/services/stdout-forwarder.service.js +1 -1
  31. package/dist/services/trace-sampler.service.js +5 -0
  32. package/dist/services/tracer.service.d.ts +19 -0
  33. package/dist/services/tracer.service.js +61 -3
  34. package/dist/utils/ingest-refusal.util.d.ts +7 -5
  35. package/dist/utils/ingest-refusal.util.js +17 -5
  36. package/package.json +9 -4
package/README.md CHANGED
@@ -87,6 +87,22 @@ and nothing is sent to the hosted collector at all, with a warning at startup
87
87
  instead; a collector of your own at `endpoint` still receives batches without
88
88
  them.
89
89
 
90
+ To keep an environment from reporting - local development, say - switch the
91
+ agent off rather than supplying fake credentials, which are sent and refused:
92
+
93
+ ```ts
94
+ ObserveModule.forRoot({
95
+ enabled: process.env.NODE_ENV === "production",
96
+ appKey: process.env.OBSERVE_APP_KEY ?? "",
97
+ appSecret: process.env.OBSERVE_APP_SECRET ?? "",
98
+ serviceId: "my-service",
99
+ });
100
+ ```
101
+
102
+ With `enabled: false` the module stays imported - `TracerService` still
103
+ resolves, and calling it is harmless - but nothing is recorded or sent, and the
104
+ only trace of it is one line at startup.
105
+
90
106
  ## Quick start
91
107
 
92
108
  `createObserveModule()` returns both the dynamic module and the instrumentation
@@ -254,7 +270,7 @@ is told `protocol`, `operationId`, `method`, `statusCode`, `duration` and
254
270
  Once the module and the instrument are in place, the agent reports, with no further changes to your application:
255
271
 
256
272
  - **Requests, GraphQL operations, RPC messages, WebSocket gateway messages, queue jobs and scheduled jobs**, each with its tree of provider method calls.
257
- - **Database queries**, as a span under the method that ran them, for `pg`, `mysql2` and `mongodb`. Anything built on those drivers is covered without being known by name: TypeORM, Drizzle, MikroORM and Mongoose are tested in this repository, and others (Knex, Sequelize) go through the same driver calls. The statement is recorded with every value removed (`SELECT "o"."id" FROM "orders" "o" WHERE "o"."customer_id" = $1`). Prisma's Rust query engine does not go through these drivers and is not covered yet.
273
+ - **Database queries**, as a span under the method that ran them, for `pg`, `mysql2`, `mssql` and `mongodb`. Anything built on those drivers is covered without being known by name: TypeORM, Drizzle, MikroORM and Mongoose are tested in this repository, and others (Knex, Sequelize) go through the same driver calls. SQL Server is the exception: `mssql` is what TypeORM and Prisma's SQL Server adapter run on, but Knex, Sequelize and MikroORM talk to SQL Server through `tedious` directly, which is not covered yet (nor is `mssql/msnodesqlv8`). The statement is recorded with every value removed (`SELECT "o"."id" FROM "orders" "o" WHERE "o"."customer_id" = $1`). Prisma's Rust query engine does not go through these drivers and is not covered yet.
258
274
  - **Outbound HTTP calls** made with `fetch`/`undici` or `node:http`/`https` (so Axios too), as `POST api.stripe.com`. The current trace id is forwarded as `x-request-id` - by `fetch` on every supported Node version, by `node:http`/`https` from Node 22.12, the first to let a request's headers still be set at that point - so a service that also runs the agent continues the same trace; a header you set yourself is never overwritten.
259
275
  - **Trace ids across queues**: a BullMQ (Pro included) or Bull job enqueued while handling a request carries that request's trace id, so the request and its job show up as one trace. Repeatable (cron) jobs start their own.
260
276
  - **The code around an error's throw site**: for each in-app frame of a captured error, a few lines of source either side, read from the running process, so the dashboard shows the failing code next to the stack. This sends fragments of your application's source to Observe, stored with the error. Frames in `node_modules` and Node internals are never read. `createObserveModule({ sourceContext: false })` turns it off; the [documentation](https://www.observe.nestjs.com/documentation/sdk#error-source-context) covers tuning it instead.
@@ -287,6 +303,52 @@ ObserveModule.forRoot({
287
303
 
288
304
  A failed request is always captured (headers only, unless `body` is on); `capture: false` turns the feature off. Everything captured goes through the same redaction as error messages and logs before it leaves the process - sensitive keys by name, secrets by pattern - so naming `authorization` in `headers` records `[REDACTED]`.
289
305
 
306
+ ## Custom request operation IDs
307
+
308
+ HTTP requests are grouped by their route path by default. If you want to report
309
+ a different operation name for a request, inject `TracerService` and call
310
+ `setOperationId()` while the request is in flight - from the handler, or from a
311
+ guard, interceptor or middleware:
312
+
313
+ ```ts
314
+ import { TracerService } from "@nestjs/observe";
315
+
316
+ // Inject TracerService in your controller's constructor:
317
+ constructor(private readonly tracerService: TracerService) {}
318
+
319
+ // Choose any naming scheme that suits your application. `body.method` comes
320
+ // from the client, so name only the methods you serve:
321
+ const RPC_METHODS = new Set(["orders.list", "orders.create", "customers.get"]);
322
+
323
+ this.tracerService.setOperationId(
324
+ RPC_METHODS.has(body.method) ? `/rpc/${body.method}` : "/rpc/unknown",
325
+ );
326
+ ```
327
+
328
+ For example, an RPC handler could distinguish `orders.list` from `orders.create`,
329
+ even when both requests use the same route. This changes only the operation ID,
330
+ not the URL, HTTP method, tags, or spans. The name replaces the route or GraphQL
331
+ name; a later call replaces an earlier one.
332
+
333
+ The operation ID is an application-defined name; choose any scheme that fits
334
+ your use case. Use stable, bounded names rather than per-request values such as
335
+ user IDs or request IDs to avoid high-cardinality groups, and don't pass a
336
+ client-supplied value through unchecked: that lets any caller create new groups.
337
+ Names are trimmed and cut to 255 characters, and anything other than a non-blank
338
+ string is ignored. The method is a no-op outside an active trace and for ignored
339
+ or sampled-out requests.
340
+
341
+ Observe keeps up to 100 custom names per project in any 30 days. A request
342
+ renamed to a name past that is reported under the route it replaced, and a name
343
+ gives its place up once no request has used it for 30 days.
344
+
345
+ Everything keyed on the operation ID sees the new name: a drop filter on
346
+ `http.route` (one on `http.url` still matches the URL),
347
+ [`skipSpans`](#skipping-spans-for-expected-outcomes), alerts and SLOs. Rules
348
+ and history recorded under the old name don't carry over to the new one.
349
+ `@Objective()` is not declared for renamed requests: an SLO watches one route,
350
+ and each name is a route of its own.
351
+
290
352
  ## Declaring objectives in code
291
353
 
292
354
  `@Objective()` states what a route promises, next to the handler that has to keep it, and Observe turns each promise into an [SLO](https://www.observe.nestjs.com/documentation/slos). The objective is written, reviewed and versioned with the route it covers:
@@ -326,6 +388,7 @@ Every option, with its default. The [documentation](https://www.observe.nestjs.c
326
388
 
327
389
  | Option | Default | What it does |
328
390
  | ------------------------ | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
391
+ | `enabled` | `true` | `false` records and sends nothing, and needs no credentials - see [Getting credentials](#getting-credentials). |
329
392
  | `appKey`, `appSecret` | required | The credentials the dashboard issues - see [Getting credentials](#getting-credentials). |
330
393
  | `serviceId` | required | Names the service in the dashboard, in at most 100 characters - a longer one is cut to fit, with a warning at startup. |
331
394
  | `serviceVersion` | inferred | The release the process runs, at most 50 characters - see [What it records without any code](#what-it-records-without-any-code). `false` reports none. |
@@ -388,7 +451,7 @@ $ npm run typecheck
388
451
  $ npm run test:int
389
452
  ```
390
453
 
391
- The queue suites need a Redis, and the query-span suites a PostgreSQL, MySQL and MongoDB. Each suite skips itself when its server does not answer, so without them `test:int` passes having tested less. CI starts them with these ports and credentials, which the suites default to:
454
+ The MSSQL unit suite uses the real driver's public request APIs with stubbed transport methods and needs no SQL Server. The queue suites need a Redis, and the query-span integration suites a PostgreSQL, MySQL and MongoDB. Each integration suite skips itself when its server does not answer, so without them `test:int` passes having tested less. CI starts them with these ports and credentials, which the suites default to:
392
455
 
393
456
  ```bash
394
457
  $ docker run -d -p 6379:6379 redis:7-alpine
@@ -7,8 +7,10 @@
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`, `trimmed` or `paced` - see
11
- * `IngestMode`.
10
+ * The value after it is `false`, `true`, `trimmed`, `paced` or `errors-only` -
11
+ * see `IngestMode` - and an `errors-only` value carries the pause's reason
12
+ * after a colon when the collector gave one this agent can word:
13
+ * `errors-only:spike` or `errors-only:budget` (see `OveragePauseReason`).
12
14
  */
13
15
  export declare const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
14
16
  /**
@@ -22,41 +24,74 @@ export declare const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
22
24
  * - `paced`: a Free account still inside its allowance whose UTC day passed a
23
25
  * tenth of it has its traces held back by the same rule until 00:00 UTC, so
24
26
  * one busy day cannot spend the month.
27
+ * - `errors-only`: a paying account's overage is paused - by spike protection,
28
+ * or because its monthly overage budget is spent - and the collector keeps
29
+ * its server errors (`isServerErrorSnapshot`) and nothing else: not their
30
+ * trees, no other request or job, no log record. Runtime and custom metrics
31
+ * and objectives are kept as ever.
25
32
  *
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.
33
+ * `reduced`, `trimmed` and `paced` withhold exactly the same trees; they
34
+ * differ only in why, which is what the operator is told and what they can do
35
+ * about it. `errors-only` withholds far more, and only the dashboard or the
36
+ * turn of the month ends it.
28
37
  *
29
38
  * 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.
39
+ * header `x-observe-ingest-modes: reduced, trimmed, paced, errors-only` (set
40
+ * where the worker builds its headers, credentials or not). The collector
41
+ * reads only `paced` and `errors-only`. Agents up to 0.3.11 send no header and
42
+ * take any `degraded: true` for a spent allowance, so a paced account's
43
+ * batches from them are answered `{ degraded: false }` and the collector trims
44
+ * the trees itself: the waterfalls are still held back, and nobody is told
45
+ * their month is gone. Only an agent that lists `paced` is answered
46
+ * `{ degraded: true, paced: true }`, and can stop sending those trees in the
47
+ * first place.
48
+ *
49
+ * A paused account's batches are answered `{ degraded: true }` when the agent
50
+ * does not list `errors-only`, as no agent up to 0.3.12 does, and the
51
+ * collector keeps only the server errors of whatever arrives. Only an agent
52
+ * that lists it is answered `{ degraded: true, errorsOnly: true, reason }`,
53
+ * and can stop sending the rest - and say why.
54
+ */
55
+ export type IngestMode = "full" | "reduced" | "trimmed" | "paced" | "errors-only";
56
+ /**
57
+ * Why a paying account's overage is paused, as an `errors-only` reply says
58
+ * it: `spike` when spike protection paused it - a day far past the account's
59
+ * usual volume, while it was already in overage - and `budget` when its
60
+ * monthly overage budget is spent.
61
+ *
62
+ * Only the operator's notice reads it. What is withheld is the same either
63
+ * way, and so is a reason this agent has no words for, or none at all.
38
64
  */
39
- export type IngestMode = "full" | "reduced" | "trimmed" | "paced";
65
+ export type OveragePauseReason = "spike" | "budget";
40
66
  /**
41
67
  * How long the main thread keeps withholding spans after the last batch that
42
68
  * reported degradation.
43
69
  *
44
70
  * The state is advisory and the collector never announces the end of it: an
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.
71
+ * upgrade, the turn of the billing period, an overage pause resumed in the
72
+ * dashboard or, for a paced day, 00:00 UTC simply starts keeping spans again.
73
+ * So it expires on its own, and the cost of it being briefly stale is one
74
+ * flush of spans sent and discarded - against a restart being required to
75
+ * recover, which is what a sticky flag would have cost.
50
76
  */
51
77
  export declare const DEGRADED_TTL_MS: number;
52
78
  /**
53
79
  * The worker's line for one batch, or null if this is not that line.
54
80
  *
55
81
  * `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.
82
+ * they always did; `trimmed`, `paced` and `errors-only` are the additions. An
83
+ * `errors-only` line reads as one whatever follows its colon: the reason only
84
+ * words the notice (`parseOveragePauseReason`), and one this agent cannot word
85
+ * must not send a paused account's every request. Anything else reads as
86
+ * `full`, as every value but `true` always has.
58
87
  */
59
88
  export declare function parseDegradedMessage(msg: string): IngestMode | null;
89
+ /**
90
+ * Why the worker's line says the account's overage is paused, or null when it
91
+ * is not an `errors-only` line, or gives no reason, or one this agent has no
92
+ * words for - read beside `parseDegradedMessage`, from the same line.
93
+ */
94
+ export declare function parseOveragePauseReason(msg: string): OveragePauseReason | null;
60
95
  /**
61
96
  * How the detached worker tells the main thread it will send nothing until a
62
97
  * given time (epoch milliseconds): after a 429 or rejected credentials, until
@@ -87,12 +122,8 @@ export declare const NOTABLE_DURATION_MS = 1000;
87
122
  * anything, or an account past its allowance loses exactly the waterfalls the
88
123
  * collector was still willing to store - and loses them silently.
89
124
  *
90
- * The rule mirrors the collector's, including the part that looks wrong:
91
- * where there is a status code it decides alone, and the error object is not
92
- * consulted beside it. An expected 401 carries an error exactly like a 500
93
- * does, and on that platform 401s and 429s are most of the daily error count -
94
- * so consulting the error first would send a tree for every unauthenticated
95
- * probe, which is the traffic this exists to stop sending.
125
+ * A server error (`isServerErrorSnapshot`, whose rule this shares), or
126
+ * anything slow.
96
127
  */
97
128
  export declare function isNotableSnapshot(snapshot: {
98
129
  d?: number;
@@ -101,6 +132,31 @@ export declare function isNotableSnapshot(snapshot: {
101
132
  sc?: number;
102
133
  };
103
134
  }): boolean;
135
+ /**
136
+ * Whether an execution is a server error: what the collector still keeps of
137
+ * an account whose overage is paused (`errors-only`), and half of what makes
138
+ * an execution notable.
139
+ *
140
+ * Mirrors the collector's `isServerErrorExecution` - its notable rule without
141
+ * the duration half - for the reason `isNotableSnapshot` mirrors the rest: an
142
+ * agent that withholds what the collector would have kept loses a paused
143
+ * account the one stream it was promised, and loses it silently. A slow
144
+ * success is notable and still not one of these.
145
+ *
146
+ * The rule includes the part that looks wrong: where there is a status code
147
+ * it decides alone, and the error object is not consulted beside it. An
148
+ * expected 401 carries an error exactly like a 500 does, and on that platform
149
+ * 401s and 429s are most of the daily error count - so consulting the error
150
+ * first would send a tree for every unauthenticated probe, which is the
151
+ * traffic degraded ingest exists to stop sending, and would keep every one of
152
+ * them through a pause, when a 4xx flood is a common cause of the spike.
153
+ */
154
+ export declare function isServerErrorSnapshot(snapshot: {
155
+ e?: unknown;
156
+ a?: {
157
+ sc?: number;
158
+ };
159
+ }): boolean;
104
160
  /**
105
161
  * Nodes in an encoded trace tree, counted the way the collector counts them.
106
162
  *
@@ -7,8 +7,10 @@
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`, `trimmed` or `paced` - see
11
- * `IngestMode`.
10
+ * The value after it is `false`, `true`, `trimmed`, `paced` or `errors-only` -
11
+ * see `IngestMode` - and an `errors-only` value carries the pause's reason
12
+ * after a colon when the collector gave one this agent can word:
13
+ * `errors-only:spike` or `errors-only:budget` (see `OveragePauseReason`).
12
14
  */
13
15
  export const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
14
16
  /**
@@ -16,33 +18,54 @@ export const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
16
18
  * reported degradation.
17
19
  *
18
20
  * The state is advisory and the collector never announces the end of it: an
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.
21
+ * upgrade, the turn of the billing period, an overage pause resumed in the
22
+ * dashboard or, for a paced day, 00:00 UTC simply starts keeping spans again.
23
+ * So it expires on its own, and the cost of it being briefly stale is one
24
+ * flush of spans sent and discarded - against a restart being required to
25
+ * recover, which is what a sticky flag would have cost.
24
26
  */
25
27
  export const DEGRADED_TTL_MS = 5 * 60 * 1000;
26
28
  /**
27
29
  * The worker's line for one batch, or null if this is not that line.
28
30
  *
29
31
  * `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
+ * they always did; `trimmed`, `paced` and `errors-only` are the additions. An
33
+ * `errors-only` line reads as one whatever follows its colon: the reason only
34
+ * words the notice (`parseOveragePauseReason`), and one this agent cannot word
35
+ * must not send a paused account's every request. Anything else reads as
36
+ * `full`, as every value but `true` always has.
32
37
  */
33
38
  export function parseDegradedMessage(msg) {
34
39
  if (!msg.startsWith(DEGRADED_MESSAGE_PREFIX)) {
35
40
  return null;
36
41
  }
37
- switch (msg.slice(DEGRADED_MESSAGE_PREFIX.length)) {
42
+ const value = msg.slice(DEGRADED_MESSAGE_PREFIX.length);
43
+ switch (value) {
38
44
  case "true":
39
45
  return "reduced";
40
46
  case "trimmed":
41
47
  return "trimmed";
42
48
  case "paced":
43
49
  return "paced";
50
+ case "errors-only":
51
+ return "errors-only";
44
52
  default:
45
- return "full";
53
+ return value.startsWith("errors-only:") ? "errors-only" : "full";
54
+ }
55
+ }
56
+ /**
57
+ * Why the worker's line says the account's overage is paused, or null when it
58
+ * is not an `errors-only` line, or gives no reason, or one this agent has no
59
+ * words for - read beside `parseDegradedMessage`, from the same line.
60
+ */
61
+ export function parseOveragePauseReason(msg) {
62
+ switch (msg) {
63
+ case `${DEGRADED_MESSAGE_PREFIX}errors-only:spike`:
64
+ return "spike";
65
+ case `${DEGRADED_MESSAGE_PREFIX}errors-only:budget`:
66
+ return "budget";
67
+ default:
68
+ return null;
46
69
  }
47
70
  }
48
71
  /**
@@ -82,22 +105,40 @@ const SERVER_ERROR_FLOOR = 500;
82
105
  * anything, or an account past its allowance loses exactly the waterfalls the
83
106
  * collector was still willing to store - and loses them silently.
84
107
  *
85
- * The rule mirrors the collector's, including the part that looks wrong:
86
- * where there is a status code it decides alone, and the error object is not
87
- * consulted beside it. An expected 401 carries an error exactly like a 500
88
- * does, and on that platform 401s and 429s are most of the daily error count -
89
- * so consulting the error first would send a tree for every unauthenticated
90
- * probe, which is the traffic this exists to stop sending.
108
+ * A server error (`isServerErrorSnapshot`, whose rule this shares), or
109
+ * anything slow.
91
110
  */
92
111
  export function isNotableSnapshot(snapshot) {
93
112
  const slow = typeof snapshot.d === "number" && snapshot.d > NOTABLE_DURATION_MS;
113
+ return slow || isServerErrorSnapshot(snapshot);
114
+ }
115
+ /**
116
+ * Whether an execution is a server error: what the collector still keeps of
117
+ * an account whose overage is paused (`errors-only`), and half of what makes
118
+ * an execution notable.
119
+ *
120
+ * Mirrors the collector's `isServerErrorExecution` - its notable rule without
121
+ * the duration half - for the reason `isNotableSnapshot` mirrors the rest: an
122
+ * agent that withholds what the collector would have kept loses a paused
123
+ * account the one stream it was promised, and loses it silently. A slow
124
+ * success is notable and still not one of these.
125
+ *
126
+ * The rule includes the part that looks wrong: where there is a status code
127
+ * it decides alone, and the error object is not consulted beside it. An
128
+ * expected 401 carries an error exactly like a 500 does, and on that platform
129
+ * 401s and 429s are most of the daily error count - so consulting the error
130
+ * first would send a tree for every unauthenticated probe, which is the
131
+ * traffic degraded ingest exists to stop sending, and would keep every one of
132
+ * them through a pause, when a 4xx flood is a common cause of the spike.
133
+ */
134
+ export function isServerErrorSnapshot(snapshot) {
94
135
  const statusCode = snapshot.a?.sc;
95
136
  if (typeof statusCode === "number") {
96
- return statusCode >= SERVER_ERROR_FLOOR || slow;
137
+ return statusCode >= SERVER_ERROR_FLOOR;
97
138
  }
98
139
  // No status code: a job, or a non-HTTP entry point. Nothing grades these but
99
140
  // the error, so here it is the signal rather than the noise.
100
- return Boolean(snapshot.e) || slow;
141
+ return Boolean(snapshot.e);
101
142
  }
102
143
  /**
103
144
  * Nodes in an encoded trace tree, counted the way the collector counts them.
@@ -67,7 +67,7 @@ describeRefusal) => {
67
67
  // like the prefixes: nothing in the agent reads it back, and a missing
68
68
  // config key would put a broken header on every batch. The value is
69
69
  // pinned by worker-degraded-reply.spec.ts.
70
- "x-observe-ingest-modes": "reduced, trimmed, paced",
70
+ "x-observe-ingest-modes": "reduced, trimmed, paced, errors-only",
71
71
  };
72
72
  // Omitted rather than sent empty when unconfigured: a collector in
73
73
  // placeholder mode accepts an unauthenticated batch, and blank credentials
@@ -508,9 +508,11 @@ describeRefusal) => {
508
508
  * batch - an account past its plan's allowance, a paying one past its
509
509
  * trim threshold, or a Free one whose day passed its daily limit, keeps
510
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.
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.
514
516
  *
515
517
  * Read defensively and treated as absent on anything unexpected: an
516
518
  * older collector returns no body at all, and a parse failure here must
@@ -518,21 +520,34 @@ describeRefusal) => {
518
520
  */
519
521
  const accepted = await response.json().catch(() => undefined);
520
522
  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.
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.
524
527
  //
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.
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
+ : "";
529
542
  const verdict = reply.degraded !== true
530
543
  ? "false"
531
- : reply.trimmed === true
532
- ? "trimmed"
533
- : reply.paced === true
534
- ? "paced"
535
- : "true";
544
+ : reply.errorsOnly === true
545
+ ? `errors-only${pauseReason}`
546
+ : reply.trimmed === true
547
+ ? "trimmed"
548
+ : reply.paced === true
549
+ ? "paced"
550
+ : "true";
536
551
  // A protocol line, not prose: the parent keys off the prefix and the
537
552
  // value, and is the side that decides what to do about it.
538
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