@nestjs/observe 0.3.10 → 0.3.11

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
@@ -352,7 +352,7 @@ Every option, with its default. The [documentation](https://www.observe.nestjs.c
352
352
  | `traceIdGenerator` | the `x-request-id` header, else a UUIDv7 | Gives each request its trace id. |
353
353
  | `traceIdKey` | `'traceId'` | The key the trace id is stored under in the request context. |
354
354
  | `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. |
355
+ | `skipInstrumentation` | `() => false` | Returns `true` for a provider instance that must not be instrumented. Nest's `Reflector` never is, whatever this returns. |
356
356
 
357
357
  ## Optional peer dependencies
358
358
 
@@ -6,8 +6,23 @@
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`, or `trimmed` - see `IngestMode`.
9
11
  */
10
12
  export declare const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
13
+ /**
14
+ * What the collector said it does with a batch's spans.
15
+ *
16
+ * - `full`: keeps them all.
17
+ * - `reduced`: the account has used its monthly allowance - Free's reduced
18
+ * ingest - and only notable traces keep their spans.
19
+ * - `trimmed`: a paying account past its threshold has its traces trimmed by
20
+ * the same rule, to keep its bill down.
21
+ *
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.
24
+ */
25
+ export type IngestMode = "full" | "reduced" | "trimmed";
11
26
  /**
12
27
  * How long the main thread keeps withholding spans after the last batch that
13
28
  * reported degradation.
@@ -19,8 +34,14 @@ export declare const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
19
34
  * recover, which is what a sticky flag would have cost.
20
35
  */
21
36
  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;
37
+ /**
38
+ * The worker's line for one batch, or null if this is not that line.
39
+ *
40
+ * `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.
43
+ */
44
+ export declare function parseDegradedMessage(msg: string): IngestMode | null;
24
45
  /**
25
46
  * How the detached worker tells the main thread it will send nothing until a
26
47
  * given time (epoch milliseconds): after a 429, until the pause lapses; after
@@ -6,6 +6,8 @@
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`, or `trimmed` - see `IngestMode`.
9
11
  */
10
12
  export const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
11
13
  /**
@@ -19,12 +21,25 @@ export const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
19
21
  * recover, which is what a sticky flag would have cost.
20
22
  */
21
23
  export const DEGRADED_TTL_MS = 5 * 60 * 1000;
22
- /** The worker's line for one batch, or null if this is not that line. */
24
+ /**
25
+ * The worker's line for one batch, or null if this is not that line.
26
+ *
27
+ * `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
+ */
23
31
  export function parseDegradedMessage(msg) {
24
32
  if (!msg.startsWith(DEGRADED_MESSAGE_PREFIX)) {
25
33
  return null;
26
34
  }
27
- return msg.slice(DEGRADED_MESSAGE_PREFIX.length) === "true";
35
+ switch (msg.slice(DEGRADED_MESSAGE_PREFIX.length)) {
36
+ case "true":
37
+ return "reduced";
38
+ case "trimmed":
39
+ return "trimmed";
40
+ default:
41
+ return "full";
42
+ }
28
43
  }
29
44
  /**
30
45
  * How the detached worker tells the main thread it will send nothing until a
@@ -461,23 +461,30 @@ describeRefusal) => {
461
461
  }
462
462
  /*
463
463
  * 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.
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.
469
470
  *
470
471
  * Read defensively and treated as absent on anything unexpected: an
471
472
  * older collector returns no body at all, and a parse failure here must
472
473
  * never turn a successful send into a reported failure.
473
474
  */
474
475
  const accepted = await response.json().catch(() => undefined);
475
- const degraded = typeof accepted === "object" &&
476
- accepted !== null &&
477
- accepted.degraded === true;
476
+ 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.
480
+ const verdict = reply.degraded !== true
481
+ ? "false"
482
+ : reply.trimmed === true
483
+ ? "trimmed"
484
+ : "true";
478
485
  // A protocol line, not prose: the parent keys off the prefix and the
479
486
  // value, and is the side that decides what to do about it.
480
- parentPort.postMessage(`${degradedPrefix}${degraded}`);
487
+ parentPort.postMessage(`${degradedPrefix}${verdict}`);
481
488
  parentPort.postMessage("Tracing and instrumentation data sent successfully");
482
489
  return true;
483
490
  }
@@ -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
  }
@@ -139,23 +139,24 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
139
139
  private watchWorker;
140
140
  handleMessage(msg: string): void;
141
141
  /**
142
- * Whether the last reply said the collector is discarding spans.
142
+ * What the last reply said the collector does with spans.
143
143
  *
144
144
  * Kept beside the log rather than read from the buffer so the notice fires
145
145
  * once per transition: an account sits in this state for days, and a line
146
146
  * per flush would bury the one thing worth reading.
147
147
  */
148
- private reportedDegraded;
148
+ private reportedMode;
149
149
  /**
150
150
  * Stops sending trace trees the collector has told us it is throwing away,
151
- * and says so once.
151
+ * and says so once - and again only when the reason changes.
152
152
  *
153
153
  * Said at `warn` rather than `debug`: the application is still being
154
- * observed, the waterfalls are not being kept, and a developer who finds
154
+ * observed, most waterfalls are not being kept, and a developer who finds
155
155
  * that out by opening a trace and seeing nothing has been let down by an
156
- * agent that knew.
156
+ * agent that knew. Each line says what is still kept, because the traces
157
+ * worth opening - server errors, slow requests, failed jobs - still are.
157
158
  */
158
- private applyDegraded;
159
+ private applyIngestMode;
159
160
  handleError(error: Error): void;
160
161
  flush(): void;
161
162
  }
@@ -494,9 +494,9 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
494
494
  this.sendsPausedUntil = pausedUntil;
495
495
  return;
496
496
  }
497
- const degraded = parseDegradedMessage(msg);
498
- if (degraded !== null) {
499
- this.applyDegraded(degraded);
497
+ const mode = parseDegradedMessage(msg);
498
+ if (mode !== null) {
499
+ this.applyIngestMode(mode);
500
500
  return;
501
501
  }
502
502
  if (msg.includes("Error:")) {
@@ -508,33 +508,43 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
508
508
  }
509
509
  }
510
510
  /**
511
- * Whether the last reply said the collector is discarding spans.
511
+ * What the last reply said the collector does with spans.
512
512
  *
513
513
  * Kept beside the log rather than read from the buffer so the notice fires
514
514
  * once per transition: an account sits in this state for days, and a line
515
515
  * per flush would bury the one thing worth reading.
516
516
  */
517
- reportedDegraded = false;
517
+ reportedMode = "full";
518
518
  /**
519
519
  * Stops sending trace trees the collector has told us it is throwing away,
520
- * and says so once.
520
+ * and says so once - and again only when the reason changes.
521
521
  *
522
522
  * Said at `warn` rather than `debug`: the application is still being
523
- * observed, the waterfalls are not being kept, and a developer who finds
523
+ * observed, most waterfalls are not being kept, and a developer who finds
524
524
  * that out by opening a trace and seeing nothing has been let down by an
525
- * agent that knew.
525
+ * agent that knew. Each line says what is still kept, because the traces
526
+ * worth opening - server errors, slow requests, failed jobs - still are.
526
527
  */
527
- applyDegraded(degraded) {
528
- this.observeAgentSharedBuffer.setDegraded(degraded);
529
- if (degraded && !this.reportedDegraded) {
530
- this.logger.warn("Observe: this account has spent its monthly event allowance. Requests, jobs " +
531
- "and errors are still being recorded; spans are not, so traces will show no " +
532
- "waterfall. The agent has stopped sending them. See /dashboard/billing.");
533
- }
534
- else if (!degraded && this.reportedDegraded) {
528
+ applyIngestMode(mode) {
529
+ // Reduced and trimmed withhold the same trees; only the notice differs.
530
+ this.observeAgentSharedBuffer.setDegraded(mode !== "full");
531
+ if (mode === this.reportedMode) {
532
+ return;
533
+ }
534
+ if (mode === "reduced") {
535
+ this.logger.warn("Observe: this account has used its monthly allowance, so most traces now arrive without their spans. " +
536
+ "Requests, jobs and errors are still recorded, and server errors, slow requests and failed jobs keep their full traces. " +
537
+ "See /dashboard/billing/usage.");
538
+ }
539
+ else if (mode === "trimmed") {
540
+ this.logger.warn("Observe: traces are now trimmed past this account's threshold to keep its bill down. " +
541
+ "Requests, jobs and errors are still recorded, and server errors, slow requests and failed jobs keep their full traces. " +
542
+ 'To keep every trace, turn on "Keep full traces" at /dashboard/billing/usage.');
543
+ }
544
+ else {
535
545
  this.logger.log("Observe: spans are being recorded again.");
536
546
  }
537
- this.reportedDegraded = degraded;
547
+ this.reportedMode = mode;
538
548
  }
539
549
  handleError(error) {
540
550
  this.logger.error(error);
@@ -51,9 +51,31 @@ export interface FieldSpec {
51
51
  readonly shape?: Shape;
52
52
  /** The nested contract is this shape itself - trace nodes nest arbitrarily deep. */
53
53
  readonly recursive?: boolean;
54
+ /**
55
+ * Longest string the API accepts (`@MaxLength`), counted the way it counts:
56
+ * a surrogate pair or a variation selector is not a character of its own.
57
+ * For an array of strings, the limit on each element.
58
+ */
59
+ readonly maxLength?: number;
60
+ /** The only values the API accepts (`@IsIn`, `@IsEnum`). */
61
+ readonly oneOf?: readonly (string | number)[];
62
+ /** Most elements the API accepts in an array field (`@ArrayMaxSize`). */
63
+ readonly maxItems?: number;
54
64
  }
55
65
  export type Shape = Readonly<Record<string, FieldSpec>>;
56
- /** The batch body the agent POSTs to the collector. */
66
+ /**
67
+ * Most entries the API accepts in one section of a batch. It refuses a batch
68
+ * with more whole, so every producer has to stay under it.
69
+ */
70
+ export declare const MAX_BATCH_ITEMS = 5000;
71
+ /**
72
+ * The batch body the agent POSTs to the collector.
73
+ *
74
+ * Only the sections' entries are repaired on a 400 - see `SECTION_SHAPES`. The
75
+ * limits on the batch itself (the service id, how many entries a section
76
+ * holds) are kept where the batch is built, and are declared here so a test
77
+ * that sends one over them fails.
78
+ */
57
79
  export declare const TELEMETRY_BATCH: Shape;
58
80
  /**
59
81
  * The sections of a batch whose entries are individually expendable. Maps each
@@ -116,6 +138,17 @@ export interface TelemetrySanitizer {
116
138
  * fails validation there. They are judged here as what they will be on the
117
139
  * wire, not as what they are in memory.
118
140
  *
141
+ * Limits are judged like types: an optional field longer than the API takes,
142
+ * or holding a value it does not accept, is removed, and a required one costs
143
+ * its entry. A string is removed rather than cut on purpose. Everything that
144
+ * can legitimately run long is already cut where it is produced, with a hash
145
+ * that keeps two cut values apart (`fitToLength`), so a value still over its
146
+ * limit when the API refuses the batch is a bug upstream - the worker's report
147
+ * names it, where a cut would hide it behind a plausible value. And most
148
+ * bounded fields are identifiers, trace and span ids and metric names, which a
149
+ * cut turns into the name of something else. An array over its size is the
150
+ * exception: it keeps its head, since each element is a value on its own.
151
+ *
119
152
  * A factory rather than module-level functions, and deliberately
120
153
  * self-contained - it closes over nothing but its own parameter. The detached
121
154
  * worker runs as a stringified function with no module scope, so this
@@ -27,10 +27,24 @@
27
27
  * dropping individual unsalvageable entries - then re-sends once, so one bad
28
28
  * entry cannot cost the batch. Healthy batches are never touched.
29
29
  */
30
- /** One span. Nests through `ch` to whatever depth the operation produced. */
30
+ /**
31
+ * Most entries the API accepts in one section of a batch. It refuses a batch
32
+ * with more whole, so every producer has to stay under it.
33
+ */
34
+ export const MAX_BATCH_ITEMS = 5000;
35
+ /** The levels a forwarded log line may carry - Nest's own. */
36
+ const LOG_LEVELS = ["fatal", "error", "warn", "log", "debug", "verbose"];
37
+ /**
38
+ * One span. Nests through `ch` to whatever depth the operation produced.
39
+ *
40
+ * The API checks spans by hand rather than through a DTO, and requires `o`,
41
+ * `c` and `m` of every one - so a span missing any of them, or carrying one
42
+ * the API refuses, is dropped from its tree on repair rather than stripped of
43
+ * the field and refused again.
44
+ */
31
45
  const TRACE_NODE = {
32
- n: { type: "string" },
33
- o: { type: "string" },
46
+ n: { type: "string", maxLength: 255 },
47
+ o: { type: "string", required: true, oneOf: ["manual", "auto"] },
34
48
  t: { type: "object" },
35
49
  d: { type: "number" },
36
50
  // Boolean is the "an error occurred but was handled, details not captured"
@@ -38,8 +52,8 @@ const TRACE_NODE = {
38
52
  // primitive, reports `e: true` rather than an error object. See
39
53
  // `TraceSpan.error`.
40
54
  e: { type: "object", alsoAccepts: ["boolean"] },
41
- c: { type: "string" },
42
- m: { type: "string" },
55
+ c: { type: "string", required: true, maxLength: 255 },
56
+ m: { type: "string", required: true, maxLength: 255 },
43
57
  s: { type: "string" },
44
58
  so: { type: "number" },
45
59
  ch: { type: "object", array: true, recursive: true },
@@ -66,7 +80,7 @@ const TRACES = {
66
80
  /** No `st`: see the note at the top of this file. */
67
81
  const REQUEST_SNAPSHOT = {
68
82
  ct: { type: "string" },
69
- ti: { type: "string", required: true },
83
+ ti: { type: "string", required: true, maxLength: 255 },
70
84
  d: { type: "number" },
71
85
  p: { type: "string" },
72
86
  op: { type: "string" },
@@ -80,7 +94,7 @@ const REQUEST_SNAPSHOT = {
80
94
  /** No `st` here either, for the same reason. */
81
95
  const JOB_SNAPSHOT = {
82
96
  i: { type: "string", required: true },
83
- ti: { type: "string" },
97
+ ti: { type: "string", required: true, maxLength: 255 },
84
98
  n: { type: "string" },
85
99
  q: { type: "string" },
86
100
  s: { type: "string" },
@@ -156,14 +170,14 @@ const RUNTIME_METRICS = {
156
170
  * can still be dropped on its own.
157
171
  */
158
172
  const CUSTOM_METRIC = {
159
- n: { type: "string", required: true },
160
- t: { type: "string" },
173
+ n: { type: "string", required: true, maxLength: 100 },
174
+ t: { type: "string", required: true, oneOf: ["counter", "gauge", "summary"] },
161
175
  v: { type: "object" },
162
176
  tg: { type: "object" },
163
- d: { type: "string" },
164
- l: { type: "string", array: true },
177
+ d: { type: "string", maxLength: 255 },
178
+ l: { type: "string", array: true, maxLength: 255, maxItems: 1000 },
165
179
  lu: { type: "number" },
166
- k: { type: "string" },
180
+ k: { type: "string", oneOf: ["additive", "ratio", "peak"] },
167
181
  iv: { type: "object" },
168
182
  q50: { type: "object" },
169
183
  q95: { type: "object" },
@@ -175,10 +189,10 @@ const CUSTOM_METRIC = {
175
189
  const LOG_ENTRY = {
176
190
  timestamp: { type: "number", required: true },
177
191
  text: { type: "string", required: true },
178
- traceId: { type: "string" },
179
- spanId: { type: "string" },
180
- level: { type: "string" },
181
- context: { type: "string" },
192
+ traceId: { type: "string", maxLength: 255 },
193
+ spanId: { type: "string", maxLength: 255 },
194
+ level: { type: "string", oneOf: LOG_LEVELS },
195
+ context: { type: "string", maxLength: 255 },
182
196
  attributes: { type: "object" },
183
197
  };
184
198
  /** One `@Objective(...)` as a handler declares it. */
@@ -191,33 +205,66 @@ const DECLARED_OBJECTIVE = {
191
205
  target: { type: "number", required: true },
192
206
  },
193
207
  },
194
- windowDays: { type: "number" },
195
- name: { type: "string" },
208
+ windowDays: { type: "number", oneOf: [7, 14, 28, 30] },
209
+ name: { type: "string", maxLength: 120 },
196
210
  };
197
211
  /** A handler's objectives, with the route it was seen to serve. */
198
212
  const OBJECTIVE_DECLARATION = {
199
- handler: { type: "string", required: true },
200
- operationId: { type: "string", required: true },
201
- method: { type: "string" },
213
+ handler: { type: "string", required: true, maxLength: 255 },
214
+ operationId: { type: "string", required: true, maxLength: 255 },
215
+ method: { type: "string", maxLength: 10 },
202
216
  objectives: {
203
217
  type: "object",
204
218
  array: true,
205
219
  required: true,
220
+ maxItems: 10,
206
221
  shape: DECLARED_OBJECTIVE,
207
222
  },
208
223
  };
209
- /** The batch body the agent POSTs to the collector. */
224
+ /**
225
+ * The batch body the agent POSTs to the collector.
226
+ *
227
+ * Only the sections' entries are repaired on a 400 - see `SECTION_SHAPES`. The
228
+ * limits on the batch itself (the service id, how many entries a section
229
+ * holds) are kept where the batch is built, and are declared here so a test
230
+ * that sends one over them fails.
231
+ */
210
232
  export const TELEMETRY_BATCH = {
211
- serviceId: { type: "string", required: true },
212
- serviceVersion: { type: "string" },
233
+ serviceId: { type: "string", required: true, maxLength: 100 },
234
+ serviceVersion: { type: "string", maxLength: 50 },
213
235
  truncatedSpans: { type: "number" },
214
236
  forwardLogs: { type: "boolean" },
215
- snapshots: { type: "object", array: true, shape: REQUEST_SNAPSHOT },
216
- jobs: { type: "object", array: true, shape: JOB_SNAPSHOT },
237
+ snapshots: {
238
+ type: "object",
239
+ array: true,
240
+ maxItems: MAX_BATCH_ITEMS,
241
+ shape: REQUEST_SNAPSHOT,
242
+ },
243
+ jobs: {
244
+ type: "object",
245
+ array: true,
246
+ maxItems: MAX_BATCH_ITEMS,
247
+ shape: JOB_SNAPSHOT,
248
+ },
217
249
  runtime: { type: "object", shape: RUNTIME_METRICS },
218
- custom: { type: "object", array: true, shape: CUSTOM_METRIC },
219
- logs: { type: "object", array: true, shape: LOG_ENTRY },
220
- objectives: { type: "object", array: true, shape: OBJECTIVE_DECLARATION },
250
+ custom: {
251
+ type: "object",
252
+ array: true,
253
+ maxItems: MAX_BATCH_ITEMS,
254
+ shape: CUSTOM_METRIC,
255
+ },
256
+ logs: {
257
+ type: "object",
258
+ array: true,
259
+ maxItems: MAX_BATCH_ITEMS,
260
+ shape: LOG_ENTRY,
261
+ },
262
+ objectives: {
263
+ type: "object",
264
+ array: true,
265
+ maxItems: 100,
266
+ shape: OBJECTIVE_DECLARATION,
267
+ },
221
268
  };
222
269
  /**
223
270
  * The sections of a batch whose entries are individually expendable. Maps each
@@ -270,6 +317,9 @@ function checkField(value, spec, parent, path, options, errors) {
270
317
  errors.push(`${path}: expected an array`);
271
318
  return;
272
319
  }
320
+ if (spec.maxItems !== undefined && value.length > spec.maxItems) {
321
+ errors.push(`${path}: more than ${spec.maxItems} items`);
322
+ }
273
323
  value.forEach((item, index) => {
274
324
  checkField(item, { ...spec, array: false }, parent, `${path}[${index}]`, options, errors);
275
325
  });
@@ -294,7 +344,30 @@ function checkField(value, spec, parent, path, options, errors) {
294
344
  }
295
345
  if (typeof value !== spec.type) {
296
346
  errors.push(`${path}: expected a ${spec.type}, got ${typeof value}`);
347
+ return;
348
+ }
349
+ if (spec.oneOf && !spec.oneOf.includes(value)) {
350
+ errors.push(`${path}: not one of ${spec.oneOf.join(", ")}`);
351
+ }
352
+ if (spec.maxLength !== undefined &&
353
+ typeof value === "string" &&
354
+ exceedsMaxLength(value, spec.maxLength)) {
355
+ errors.push(`${path}: longer than ${spec.maxLength} characters`);
356
+ }
357
+ }
358
+ /**
359
+ * Whether a string is longer than the API's `@MaxLength` allows. It counts the
360
+ * way validator.js's `isLength` does - the second half of a surrogate pair and
361
+ * a variation selector are not characters - so the exact count is taken only
362
+ * once `.length`, which can only overcount, says the string might be over.
363
+ */
364
+ function exceedsMaxLength(value, maxLength) {
365
+ if (value.length <= maxLength) {
366
+ return false;
297
367
  }
368
+ const pairs = value.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g)?.length ?? 0;
369
+ const selectors = value.match(/[\uFE0E\uFE0F]/g)?.length ?? 0;
370
+ return value.length - pairs - selectors > maxLength;
298
371
  }
299
372
  /**
300
373
  * Builds the sanitizer that brings a rejected batch into contract.
@@ -314,6 +387,17 @@ function checkField(value, spec, parent, path, options, errors) {
314
387
  * fails validation there. They are judged here as what they will be on the
315
388
  * wire, not as what they are in memory.
316
389
  *
390
+ * Limits are judged like types: an optional field longer than the API takes,
391
+ * or holding a value it does not accept, is removed, and a required one costs
392
+ * its entry. A string is removed rather than cut on purpose. Everything that
393
+ * can legitimately run long is already cut where it is produced, with a hash
394
+ * that keeps two cut values apart (`fitToLength`), so a value still over its
395
+ * limit when the API refuses the batch is a bug upstream - the worker's report
396
+ * names it, where a cut would hide it behind a plausible value. And most
397
+ * bounded fields are identifiers, trace and span ids and metric names, which a
398
+ * cut turns into the name of something else. An array over its size is the
399
+ * exception: it keeps its head, since each element is a value on its own.
400
+ *
317
401
  * A factory rather than module-level functions, and deliberately
318
402
  * self-contained - it closes over nothing but its own parameter. The detached
319
403
  * worker runs as a stringified function with no module scope, so this
@@ -328,8 +412,19 @@ function checkField(value, spec, parent, path, options, errors) {
328
412
  * thread.
329
413
  */
330
414
  export function createTelemetrySanitizer(shapes) {
331
- // Local copy of the module-level helper, for the self-containment above.
415
+ // Local copies of the module-level helpers, for the self-containment above
416
+ // - moving them out, as the linter asks, is exactly what would break it.
417
+ // oxlint-disable-next-line unicorn/consistent-function-scoping
332
418
  const isPlainRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
419
+ // oxlint-disable-next-line unicorn/consistent-function-scoping
420
+ const isTooLong = (value, maxLength) => {
421
+ if (value.length <= maxLength) {
422
+ return false;
423
+ }
424
+ const pairs = value.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g)?.length ?? 0;
425
+ const selectors = value.match(/[\uFE0E\uFE0F]/g)?.length ?? 0;
426
+ return value.length - pairs - selectors > maxLength;
427
+ };
333
428
  /** Returns whether the value is still usable once stripped. */
334
429
  const sanitizeShape = (value, shape, path, problems) => {
335
430
  if (!isPlainRecord(value)) {
@@ -388,6 +483,10 @@ export function createTelemetrySanitizer(shapes) {
388
483
  value.splice(index, 1);
389
484
  }
390
485
  }
486
+ if (spec.maxItems !== undefined && value.length > spec.maxItems) {
487
+ problems.push(`${path}: more than ${spec.maxItems} items, ${value.length - spec.maxItems} removed`);
488
+ value.length = spec.maxItems;
489
+ }
391
490
  return true;
392
491
  }
393
492
  if (spec.alsoAccepts?.includes(typeof value)) {
@@ -413,6 +512,16 @@ export function createTelemetrySanitizer(shapes) {
413
512
  problems.push(`${path}: non-finite number`);
414
513
  return false;
415
514
  }
515
+ if (spec.oneOf && !spec.oneOf.includes(value)) {
516
+ problems.push(`${path}: not one of ${spec.oneOf.join(", ")}`);
517
+ return false;
518
+ }
519
+ if (spec.maxLength !== undefined &&
520
+ typeof value === "string" &&
521
+ isTooLong(value, spec.maxLength)) {
522
+ problems.push(`${path}: longer than ${spec.maxLength} characters`);
523
+ return false;
524
+ }
416
525
  return true;
417
526
  };
418
527
  const sanitizeEntry = (section, entry) => {
@@ -1,3 +1,4 @@
1
+ import { Reflector } from "@nestjs/core";
1
2
  import { CALLER_METADATA_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
2
3
  /**
3
4
  * Stand-in "class name" for instrumented standalone functions. Unlike methods,
@@ -7,6 +8,29 @@ import { CALLER_METADATA_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.j
7
8
  const STANDALONE_FUNCTION_LABEL = "Function";
8
9
  /** Class name for an instance that has no constructor function. */
9
10
  const FALLBACK_CLASS_NAME = "Object";
11
+ /**
12
+ * Whether an instance is a framework provider that is never instrumented,
13
+ * whatever `skipInstrumentation` says.
14
+ *
15
+ * Nest's `Reflector` is the one: guards, interceptors and pipes ask it whether
16
+ * a route is public, throttled or role-gated several times a request, each
17
+ * answer a hundredth of a millisecond, and a waterfall full of those answers
18
+ * explains nothing - while every one of them is a billed span. On one app it
19
+ * was 18 spans in every request, 29% of all it sent. The collector drops what
20
+ * older agents still send; this stops them being made.
21
+ *
22
+ * Matched by shape as well as by class: an application with a second copy of
23
+ * `@nestjs/core` in its tree has a second `Reflector` class, which the
24
+ * `instanceof` alone would miss.
25
+ */
26
+ function isFrameworkNoise(instance) {
27
+ if (instance instanceof Reflector) {
28
+ return true;
29
+ }
30
+ const candidate = instance;
31
+ return (candidate.constructor?.name === "Reflector" &&
32
+ typeof candidate.getAllAndOverride === "function");
33
+ }
10
34
  export function createInstanceDecorator(als, operationTraceRegistry, options) {
11
35
  /**
12
36
  * Builds the tracing wrapper shared by methods and standalone functions.
@@ -162,6 +186,11 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
162
186
  let slotBacked;
163
187
  let bareBuiltIn;
164
188
  try {
189
+ // Inspected here, inside the guard, for the same reason as the checks
190
+ // below: reading a provider's constructor can run a trap that throws.
191
+ if (isFrameworkNoise(instance)) {
192
+ return instance;
193
+ }
165
194
  hasPrivateMembers = usesNativePrivateMembers(instance);
166
195
  slotBacked = isSlotBackedBuiltIn(instance);
167
196
  bareBuiltIn = slotBacked && isNativeFunction(instance.constructor);
@@ -77,6 +77,10 @@ export interface CreateObserveModuleOptions {
77
77
  * should stay untouched - no proxy is placed around it and none of its
78
78
  * methods produce spans.
79
79
  *
80
+ * Nest's own `Reflector` is never instrumented, whatever this returns: its
81
+ * metadata lookups run several times a request and say nothing a
82
+ * waterfall is for.
83
+ *
80
84
  * Runs before the built-in checks, so it also shields providers that
81
85
  * cannot even be inspected safely: some libraries (nestjs-cls proxy
82
86
  * providers, for instance) register proxies that throw on any property
@@ -250,6 +254,8 @@ export interface ObserveOptions {
250
254
  /**
251
255
  * Maximum number of traces per batch that can be sent to the Agent.
252
256
  * This is useful for controlling the volume of traces sent, especially in high-traffic applications.
257
+ * At most 5000, the most the collector accepts in one batch - a larger value
258
+ * is read as 5000.
253
259
  * @default 1000
254
260
  */
255
261
  maxTracesPerBatch?: number;
@@ -55,4 +55,12 @@ export declare class StdoutForwarderService implements OnModuleInit, OnModuleDes
55
55
  private consume;
56
56
  private flushPartial;
57
57
  private toLogEntry;
58
+ /**
59
+ * A context is normally a class name, but it is read off the line like the
60
+ * message, so it holds whatever was written there - a secret passed where a
61
+ * context was expected (`logger.log("login", "token=" + token)`) included.
62
+ * Redacted as the message is, and before the cut for the same reason, then
63
+ * cut to what the collector accepts.
64
+ */
65
+ private toContext;
58
66
  }
@@ -14,6 +14,8 @@ var StdoutForwarderService_1;
14
14
  import { Inject, Injectable, Logger, } from "@nestjs/common";
15
15
  import { AsyncLocalStorage } from "async_hooks";
16
16
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
17
+ import { REQUEST_ID_PATTERN } from "../utils/default-trace-id-generator.util.js";
18
+ import { fitToLength } from "../utils/fit-to-length.util.js";
17
19
  import { parseLogLine } from "../utils/log-line.parser.js";
18
20
  import { LogRedactor } from "../utils/log-redactor.js";
19
21
  import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "../observe.constants.js";
@@ -34,7 +36,9 @@ const MAX_PARTIAL_LINE_LENGTH = 8 * 1024;
34
36
  * is a set of regular expressions whose cost grows with input length. A single
35
37
  * multi-megabyte line - a dumped payload, and payloads can carry content an
36
38
  * outside caller chose - must not be able to hold the event loop while every
37
- * rule walks it.
39
+ * rule walks it. A bound only helps while that cost stays linear: a pattern
40
+ * that backtracks super-linearly holds the loop for minutes inside 16 KB, which
41
+ * is why the parser's patterns are written to be linear.
38
42
  *
39
43
  * The bound is safe because it is four times what can ship: the shared buffer
40
44
  * truncates entries to 4 KB, so bytes beyond this window were never going to
@@ -42,6 +46,11 @@ const MAX_PARTIAL_LINE_LENGTH = 8 * 1024;
42
46
  * inside this window, so it is redacted before the cut can split it.
43
47
  */
44
48
  const MAX_PARSED_LINE_LENGTH = 16 * 1024;
49
+ /**
50
+ * Longest `context` the collector accepts. It does not cut a longer one down:
51
+ * it refuses the whole batch the line rides in, traces and metrics included.
52
+ */
53
+ const MAX_CONTEXT_LENGTH = 255;
45
54
  const FORWARDED_STREAMS = ["stdout", "stderr"];
46
55
  let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderService {
47
56
  options;
@@ -187,7 +196,15 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
187
196
  const contextTraceId = store?.get(this.options.traceIdKey);
188
197
  // The line's own trace id wins: it was captured when the log was written,
189
198
  // whereas the async store is read now and may already have moved on.
190
- const traceId = parsed.traceId ?? contextTraceId;
199
+ //
200
+ // Only an id shaped like one, though. It is read off text, and anyone who
201
+ // gets a newline into a logged value can end a line with whatever
202
+ // `Trace ID:` they like - so it is held to the rule a client-supplied
203
+ // `x-request-id` is. An over-long one would get the whole batch refused.
204
+ const lineTraceId = parsed.traceId !== undefined && REQUEST_ID_PATTERN.test(parsed.traceId)
205
+ ? parsed.traceId
206
+ : undefined;
207
+ const traceId = lineTraceId ?? contextTraceId;
191
208
  return {
192
209
  timestamp: Date.now(),
193
210
  traceId,
@@ -199,7 +216,9 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
199
216
  ? store?.get(CALLER_METADATA_KEY)
200
217
  : undefined,
201
218
  level: parsed.level,
202
- context: parsed.context,
219
+ context: parsed.context === undefined
220
+ ? undefined
221
+ : this.toContext(parsed.context),
203
222
  // Redaction happens here, before the entry reaches the shared buffer -
204
223
  // which is also before the buffer truncates oversized lines. That order is
205
224
  // deliberate: truncating first would cut a long secret in half and ship
@@ -212,6 +231,19 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
212
231
  : parsed.message,
213
232
  };
214
233
  }
234
+ /**
235
+ * A context is normally a class name, but it is read off the line like the
236
+ * message, so it holds whatever was written there - a secret passed where a
237
+ * context was expected (`logger.log("login", "token=" + token)`) included.
238
+ * Redacted as the message is, and before the cut for the same reason, then
239
+ * cut to what the collector accepts.
240
+ */
241
+ toContext(context) {
242
+ const redacted = this.redactor
243
+ ? this.redactor.redactMessage(context)
244
+ : context;
245
+ return fitToLength(redacted, MAX_CONTEXT_LENGTH);
246
+ }
215
247
  };
216
248
  StdoutForwarderService = StdoutForwarderService_1 = __decorate([
217
249
  Injectable(),
@@ -12,8 +12,9 @@
12
12
  * Nothing is ever dropped for being unparseable. A log the agent does not
13
13
  * understand is still the log the user is looking for.
14
14
  */
15
+ import type { LogLevel } from "@nestjs/common";
15
16
  export interface ParsedLogLine {
16
- level?: string;
17
+ level?: LogLevel;
17
18
  context?: string;
18
19
  message: string;
19
20
  traceId?: string;
@@ -23,14 +23,46 @@ const ANSI_PATTERN = /\x1B\[[0-9;]*[A-Za-z]/g;
23
23
  * Nest's default ConsoleLogger line:
24
24
  * [Nest] 1234 - 07/29/2026, 10:42:18 AM LOG [AppController] message
25
25
  * The context bracket is optional - `logger.log()` without a context omits it.
26
+ * The level is right-aligned in seven columns, so `VERBOSE` follows the
27
+ * timestamp after a single space and every other level after several.
28
+ *
29
+ * Must stay linear in the length of the line: it runs on every line the
30
+ * process writes, synchronously inside `process.stdout.write`, on text a caller
31
+ * can shape. The pattern this replaced read `.+?\s{2,}` here - two quantifiers
32
+ * that could both take the same run of whitespace - and backtracked cubically
33
+ * on a `[Nest]` line that never reached a level: seconds for a few thousand
34
+ * spaces. Here no two neighbouring quantifiers can take the same character.
35
+ * The timestamp opens with a non-space, exactly one whitespace character
36
+ * precedes the level, and nothing after the level can fail.
26
37
  */
27
- const NEST_TEXT_PATTERN = /^\[Nest\]\s+\d+\s+-\s+.+?\s{2,}(FATAL|ERROR|WARN|LOG|DEBUG|VERBOSE)\s+(?:\[([^\]]+)\]\s*)?([\s\S]*)$/;
38
+ const NEST_TEXT_PATTERN = /^\[Nest\]\s+\d+\s+-\s+\S.*?\s(FATAL|ERROR|WARN|LOG|DEBUG|VERBOSE)\s+(?:\[([^\]]+)\]\s*)?([\s\S]*)$/;
28
39
  /**
29
- * Suffix appended by LoggerPatcherService when a trace is in scope. Parsing it
30
- * back off recovers the trace id even for lines whose async context is gone by
31
- * the time the forwarder sees them.
40
+ * Marker LoggerPatcherService puts before the trace id it appends when a trace
41
+ * is in scope. Parsing the id back off recovers it even for lines whose async
42
+ * context is gone by the time the forwarder sees them.
32
43
  */
33
- const TRACE_ID_SUFFIX_PATTERN = /\s*Trace ID:\s*(\S+)\s*$/;
44
+ const TRACE_ID_MARKER = "Trace ID:";
45
+ /** What may follow the marker: one token, and nothing after it. */
46
+ const TRACE_ID_VALUE_PATTERN = /^\s*(\S+)\s*$/;
47
+ /**
48
+ * The levels the collector accepts, which are Nest's own. It refuses a batch
49
+ * carrying any other value whole - every trace and metric in it lost over one
50
+ * log line - so nothing else is ever put in `level`.
51
+ */
52
+ const LOG_LEVELS = new Set([
53
+ "fatal",
54
+ "error",
55
+ "warn",
56
+ "log",
57
+ "debug",
58
+ "verbose",
59
+ ]);
60
+ /** Other loggers' names for a level the collector models. */
61
+ const LEVEL_ALIASES = new Map([
62
+ ["info", "log"],
63
+ ["warning", "warn"],
64
+ ["trace", "verbose"],
65
+ ]);
34
66
  /**
35
67
  * Keys the JSON logger sets that map onto modelled columns; anything else a
36
68
  * service attaches is preserved under `attributes`.
@@ -71,9 +103,13 @@ function parseStructured(line) {
71
103
  if (typeof record.message !== "string") {
72
104
  return null;
73
105
  }
74
- const attributes = Object.fromEntries(Object.entries(record).filter(([key]) => !STRUCTURED_KEYS.has(key)));
106
+ const level = toLogLevel(record.level);
107
+ const attributes = Object.fromEntries(Object.entries(record).filter(
108
+ // A level the collector does not model - pino's numeric ones, a logger's
109
+ // own `notice` - stays an attribute rather than being dropped.
110
+ ([key]) => !STRUCTURED_KEYS.has(key) || (key === "level" && level === undefined)));
75
111
  return {
76
- level: typeof record.level === "string" ? record.level : undefined,
112
+ level,
77
113
  context: typeof record.context === "string" ? record.context : undefined,
78
114
  traceId: typeof record.traceId === "string" ? record.traceId : undefined,
79
115
  message: record.message,
@@ -86,11 +122,38 @@ function parseNestText(line) {
86
122
  return null;
87
123
  }
88
124
  const [, level, context, rest] = match;
89
- const traceIdMatch = TRACE_ID_SUFFIX_PATTERN.exec(rest);
125
+ const { message, traceId } = splitTraceIdSuffix(rest);
90
126
  return {
91
- level: level.toLowerCase(),
127
+ level: toLogLevel(level),
92
128
  context: context || undefined,
93
- traceId: traceIdMatch?.[1],
94
- message: traceIdMatch ? rest.slice(0, traceIdMatch.index).trimEnd() : rest,
129
+ traceId,
130
+ message,
95
131
  };
96
132
  }
133
+ /**
134
+ * Splits the trace id suffix off the end of a message, when there is one.
135
+ *
136
+ * Found with `lastIndexOf` rather than an unanchored `\s*Trace ID:...$`
137
+ * pattern, which retried its leading `\s*` from every offset - quadratic in a
138
+ * long run of whitespace, and that whitespace can come from a caller. Only the
139
+ * last marker can be the suffix anyway: the marker itself contains a space, so
140
+ * an earlier one is always followed by more than one token.
141
+ */
142
+ function splitTraceIdSuffix(rest) {
143
+ const markerIndex = rest.lastIndexOf(TRACE_ID_MARKER);
144
+ if (markerIndex === -1) {
145
+ return { message: rest };
146
+ }
147
+ const value = TRACE_ID_VALUE_PATTERN.exec(rest.slice(markerIndex + TRACE_ID_MARKER.length));
148
+ if (!value) {
149
+ return { message: rest };
150
+ }
151
+ return { message: rest.slice(0, markerIndex).trimEnd(), traceId: value[1] };
152
+ }
153
+ function toLogLevel(value) {
154
+ if (typeof value !== "string") {
155
+ return undefined;
156
+ }
157
+ const lower = value.toLowerCase();
158
+ return LOG_LEVELS.has(lower) ? lower : LEVEL_ALIASES.get(lower);
159
+ }
@@ -84,8 +84,13 @@ function buildDefaultRules(literalValuesOnly = false) {
84
84
  replace: (replacement, prefix) => `${prefix}${replacement}`,
85
85
  },
86
86
  // Bare JWTs - they show up outside any header often enough to matter.
87
+ //
88
+ // Must not follow a token character, rather than `\b`: a hyphen is a word
89
+ // boundary but also a token character, so under `\b` every `eyJ` in a run
90
+ // like `eyJ-eyJ-eyJ-...` started a match that rescanned the rest of the
91
+ // run - quadratic, on a line a caller can fill.
87
92
  {
88
- pattern: /\beyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]*/g,
93
+ pattern: /(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]*/g,
89
94
  replace: (replacement) => replacement,
90
95
  },
91
96
  // AWS access key ids. Distinctive enough to match on sight; the matching
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.3.10",
3
+ "version": "0.3.11",
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",