@nestjs/observe 0.3.10 → 0.3.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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);
@@ -494,9 +550,9 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
494
550
  this.sendsPausedUntil = pausedUntil;
495
551
  return;
496
552
  }
497
- const degraded = parseDegradedMessage(msg);
498
- if (degraded !== null) {
499
- this.applyDegraded(degraded);
553
+ const mode = parseDegradedMessage(msg);
554
+ if (mode !== null) {
555
+ this.applyIngestMode(mode);
500
556
  return;
501
557
  }
502
558
  if (msg.includes("Error:")) {
@@ -508,33 +564,51 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
508
564
  }
509
565
  }
510
566
  /**
511
- * Whether the last reply said the collector is discarding spans.
567
+ * What the last reply said the collector does with spans.
512
568
  *
513
569
  * Kept beside the log rather than read from the buffer so the notice fires
514
570
  * once per transition: an account sits in this state for days, and a line
515
571
  * per flush would bury the one thing worth reading.
516
572
  */
517
- reportedDegraded = false;
573
+ reportedMode = "full";
518
574
  /**
519
575
  * Stops sending trace trees the collector has told us it is throwing away,
520
- * and says so once.
576
+ * and says so once - and again only when the reason changes.
521
577
  *
522
578
  * Said at `warn` rather than `debug`: the application is still being
523
- * observed, the waterfalls are not being kept, and a developer who finds
579
+ * observed, most waterfalls are not being kept, and a developer who finds
524
580
  * that out by opening a trace and seeing nothing has been let down by an
525
- * agent that knew.
581
+ * agent that knew. Each line says what is still kept, because the traces
582
+ * worth opening - server errors, slow requests, failed jobs - still are.
526
583
  */
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) {
584
+ applyIngestMode(mode) {
585
+ // Reduced, trimmed and paced withhold the same trees; only the notice
586
+ // differs.
587
+ this.observeAgentSharedBuffer.setDegraded(mode !== "full");
588
+ if (mode === this.reportedMode) {
589
+ return;
590
+ }
591
+ if (mode === "reduced") {
592
+ this.logger.warn("Observe: this account has used its monthly allowance, so most traces now arrive without their spans. " +
593
+ "Requests, jobs and errors are still recorded, and server errors, slow requests and failed jobs keep their full traces. " +
594
+ "See /dashboard/billing/usage.");
595
+ }
596
+ else if (mode === "trimmed") {
597
+ this.logger.warn("Observe: traces are now trimmed past this account's threshold to keep its bill down. " +
598
+ "Requests, jobs and errors are still recorded, and server errors, slow requests and failed jobs keep their full traces. " +
599
+ 'To keep every trace, turn on "Keep full traces" at /dashboard/billing/usage.');
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
+ }
608
+ else {
535
609
  this.logger.log("Observe: spans are being recorded again.");
536
610
  }
537
- this.reportedDegraded = degraded;
611
+ this.reportedMode = mode;
538
612
  }
539
613
  handleError(error) {
540
614
  this.logger.error(error);
@@ -545,7 +619,7 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
545
619
  // gone quiet, and an empty buffer would otherwise return here and strand
546
620
  // them until shutdown.
547
621
  this.observeAgentSharedBuffer.drainPendingLogs();
548
- if (this.hasScaffoldCredentials) {
622
+ if (this.sendsNothing) {
549
623
  this.observeAgentSharedBuffer.resetMainThreadBuffer();
550
624
  return;
551
625
  }
@@ -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
@@ -138,7 +142,10 @@ export interface ObserveOptions {
138
142
  *
139
143
  * Sent as `x-api-key` on every ingest request, alongside `appSecret`.
140
144
  * Without valid credentials the collector answers 401 and the batch is
141
- * 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.
142
149
  */
143
150
  appKey: string;
144
151
  /**
@@ -250,6 +257,8 @@ export interface ObserveOptions {
250
257
  /**
251
258
  * Maximum number of traces per batch that can be sent to the Agent.
252
259
  * This is useful for controlling the volume of traces sent, especially in high-traffic applications.
260
+ * At most 5000, the most the collector accepts in one batch - a larger value
261
+ * is read as 5000.
253
262
  * @default 1000
254
263
  */
255
264
  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
  }