@nestjs/observe 0.3.9 → 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.
@@ -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 },
@@ -49,10 +63,24 @@ const REQUEST_ATTRIBUTES = {
49
63
  sc: { type: "number" },
50
64
  ou: { type: "string" },
51
65
  };
66
+ /**
67
+ * An operation's spans. Required - the API refuses an operation without the
68
+ * array, and the batch with it - but empty when there are none, including when
69
+ * the agent withheld them from a degraded account. Agents 0.2.1 to 0.3.9
70
+ * deleted the key instead, and every degraded batch carrying an ordinary
71
+ * request or job was refused whole.
72
+ */
73
+ const TRACES = {
74
+ type: "object",
75
+ array: true,
76
+ required: true,
77
+ fallback: [],
78
+ shape: TRACE_NODE,
79
+ };
52
80
  /** No `st`: see the note at the top of this file. */
53
81
  const REQUEST_SNAPSHOT = {
54
82
  ct: { type: "string" },
55
- ti: { type: "string", required: true },
83
+ ti: { type: "string", required: true, maxLength: 255 },
56
84
  d: { type: "number" },
57
85
  p: { type: "string" },
58
86
  op: { type: "string" },
@@ -61,12 +89,12 @@ const REQUEST_SNAPSHOT = {
61
89
  e: { type: "object" },
62
90
  rq: { type: "object" },
63
91
  a: { type: "object", shape: REQUEST_ATTRIBUTES },
64
- t: { type: "object", array: true, shape: TRACE_NODE },
92
+ t: TRACES,
65
93
  };
66
94
  /** No `st` here either, for the same reason. */
67
95
  const JOB_SNAPSHOT = {
68
96
  i: { type: "string", required: true },
69
- ti: { type: "string" },
97
+ ti: { type: "string", required: true, maxLength: 255 },
70
98
  n: { type: "string" },
71
99
  q: { type: "string" },
72
100
  s: { type: "string" },
@@ -78,7 +106,7 @@ const JOB_SNAPSHOT = {
78
106
  ma: { type: "number" },
79
107
  tg: { type: "object" },
80
108
  e: { type: "object" },
81
- t: { type: "object", array: true, shape: TRACE_NODE },
109
+ t: TRACES,
82
110
  };
83
111
  /**
84
112
  * One kind of collection in a runtime window. The encoder shortens the kind's
@@ -142,14 +170,14 @@ const RUNTIME_METRICS = {
142
170
  * can still be dropped on its own.
143
171
  */
144
172
  const CUSTOM_METRIC = {
145
- n: { type: "string", required: true },
146
- t: { type: "string" },
173
+ n: { type: "string", required: true, maxLength: 100 },
174
+ t: { type: "string", required: true, oneOf: ["counter", "gauge", "summary"] },
147
175
  v: { type: "object" },
148
176
  tg: { type: "object" },
149
- d: { type: "string" },
150
- l: { type: "string", array: true },
177
+ d: { type: "string", maxLength: 255 },
178
+ l: { type: "string", array: true, maxLength: 255, maxItems: 1000 },
151
179
  lu: { type: "number" },
152
- k: { type: "string" },
180
+ k: { type: "string", oneOf: ["additive", "ratio", "peak"] },
153
181
  iv: { type: "object" },
154
182
  q50: { type: "object" },
155
183
  q95: { type: "object" },
@@ -161,10 +189,10 @@ const CUSTOM_METRIC = {
161
189
  const LOG_ENTRY = {
162
190
  timestamp: { type: "number", required: true },
163
191
  text: { type: "string", required: true },
164
- traceId: { type: "string" },
165
- spanId: { type: "string" },
166
- level: { type: "string" },
167
- 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 },
168
196
  attributes: { type: "object" },
169
197
  };
170
198
  /** One `@Objective(...)` as a handler declares it. */
@@ -177,32 +205,66 @@ const DECLARED_OBJECTIVE = {
177
205
  target: { type: "number", required: true },
178
206
  },
179
207
  },
180
- windowDays: { type: "number" },
181
- name: { type: "string" },
208
+ windowDays: { type: "number", oneOf: [7, 14, 28, 30] },
209
+ name: { type: "string", maxLength: 120 },
182
210
  };
183
211
  /** A handler's objectives, with the route it was seen to serve. */
184
212
  const OBJECTIVE_DECLARATION = {
185
- handler: { type: "string", required: true },
186
- operationId: { type: "string", required: true },
187
- 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 },
188
216
  objectives: {
189
217
  type: "object",
190
218
  array: true,
191
219
  required: true,
220
+ maxItems: 10,
192
221
  shape: DECLARED_OBJECTIVE,
193
222
  },
194
223
  };
195
- /** 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
+ */
196
232
  export const TELEMETRY_BATCH = {
197
- serviceId: { type: "string", required: true },
198
- serviceVersion: { type: "string" },
233
+ serviceId: { type: "string", required: true, maxLength: 100 },
234
+ serviceVersion: { type: "string", maxLength: 50 },
235
+ truncatedSpans: { type: "number" },
199
236
  forwardLogs: { type: "boolean" },
200
- snapshots: { type: "object", array: true, shape: REQUEST_SNAPSHOT },
201
- 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
+ },
202
249
  runtime: { type: "object", shape: RUNTIME_METRICS },
203
- custom: { type: "object", array: true, shape: CUSTOM_METRIC },
204
- logs: { type: "object", array: true, shape: LOG_ENTRY },
205
- 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
+ },
206
268
  };
207
269
  /**
208
270
  * The sections of a batch whose entries are individually expendable. Maps each
@@ -255,6 +317,9 @@ function checkField(value, spec, parent, path, options, errors) {
255
317
  errors.push(`${path}: expected an array`);
256
318
  return;
257
319
  }
320
+ if (spec.maxItems !== undefined && value.length > spec.maxItems) {
321
+ errors.push(`${path}: more than ${spec.maxItems} items`);
322
+ }
258
323
  value.forEach((item, index) => {
259
324
  checkField(item, { ...spec, array: false }, parent, `${path}[${index}]`, options, errors);
260
325
  });
@@ -279,7 +344,30 @@ function checkField(value, spec, parent, path, options, errors) {
279
344
  }
280
345
  if (typeof value !== spec.type) {
281
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;
282
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;
283
371
  }
284
372
  /**
285
373
  * Builds the sanitizer that brings a rejected batch into contract.
@@ -290,13 +378,26 @@ function checkField(value, spec, parent, path, options, errors) {
290
378
  * would have rejected the whole batch over them (`forbidNonWhitelisted`).
291
379
  * A *required* field that is missing or unusable cannot be repaired by
292
380
  * removal, so the entry is dropped alone rather than the collector dropping
293
- * the batch.
381
+ * the batch - unless the contract names a fallback for a missing one, as it
382
+ * does for an operation's spans: an operation without its trace array is sent
383
+ * with an empty one, which is what the absence meant.
294
384
  *
295
385
  * Numbers must be finite: `NaN` and `Infinity` survive `typeof` but serialize
296
386
  * to `null` in JSON, which arrives at the API as a present-but-null field and
297
387
  * fails validation there. They are judged here as what they will be on the
298
388
  * wire, not as what they are in memory.
299
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
+ *
300
401
  * A factory rather than module-level functions, and deliberately
301
402
  * self-contained - it closes over nothing but its own parameter. The detached
302
403
  * worker runs as a stringified function with no module scope, so this
@@ -311,8 +412,19 @@ function checkField(value, spec, parent, path, options, errors) {
311
412
  * thread.
312
413
  */
313
414
  export function createTelemetrySanitizer(shapes) {
314
- // 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
315
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
+ };
316
428
  /** Returns whether the value is still usable once stripped. */
317
429
  const sanitizeShape = (value, shape, path, problems) => {
318
430
  if (!isPlainRecord(value)) {
@@ -330,7 +442,11 @@ export function createTelemetrySanitizer(shapes) {
330
442
  const fieldPath = `${path}.${key}`;
331
443
  const present = value[key] !== undefined && value[key] !== null;
332
444
  if (!present) {
333
- if (spec.required) {
445
+ if (spec.required && spec.fallback !== undefined) {
446
+ problems.push(`${fieldPath}: required, sent as ${JSON.stringify(spec.fallback)}`);
447
+ value[key] = structuredClone(spec.fallback);
448
+ }
449
+ else if (spec.required) {
334
450
  problems.push(`${fieldPath}: required`);
335
451
  usable = false;
336
452
  }
@@ -367,6 +483,10 @@ export function createTelemetrySanitizer(shapes) {
367
483
  value.splice(index, 1);
368
484
  }
369
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
+ }
370
490
  return true;
371
491
  }
372
492
  if (spec.alsoAccepts?.includes(typeof value)) {
@@ -392,6 +512,16 @@ export function createTelemetrySanitizer(shapes) {
392
512
  problems.push(`${path}: non-finite number`);
393
513
  return false;
394
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
+ }
395
525
  return true;
396
526
  };
397
527
  const sanitizeEntry = (section, entry) => {
@@ -20,7 +20,7 @@ declare const SNAPSHOT_KEY_MAP: {
20
20
  export type EncodedJobSnapshot = Omit<{
21
21
  [K in keyof JobSnapshot as K extends keyof typeof SNAPSHOT_KEY_MAP ? (typeof SNAPSHOT_KEY_MAP)[K] : never]: JobSnapshot[K];
22
22
  }, "t"> & {
23
- t?: Array<RecursiveEncodedTrace>;
23
+ t: Array<RecursiveEncodedTrace>;
24
24
  };
25
25
  export declare class JobSnapshotEncoder {
26
26
  static encode(snapshot: JobSnapshot): EncodedJobSnapshot;
@@ -20,9 +20,7 @@ const SNAPSHOT_KEY_MAP = {
20
20
  export class JobSnapshotEncoder {
21
21
  static encode(snapshot) {
22
22
  const encoded = remapKeys(snapshot, SNAPSHOT_KEY_MAP);
23
- if (snapshot.traces) {
24
- encoded.t = snapshot.traces.map((trace) => encodeTrace(trace));
25
- }
23
+ encoded.t = (snapshot.traces ?? []).map((trace) => encodeTrace(trace));
26
24
  return encoded;
27
25
  }
28
26
  }
@@ -25,7 +25,7 @@ export type EncodedAttributes = {
25
25
  export type EncodedRequestSnapshot = Omit<{
26
26
  [K in keyof RequestSnapshot as K extends keyof typeof SNAPSHOT_KEY_MAP ? (typeof SNAPSHOT_KEY_MAP)[K] : never]: RequestSnapshot[K];
27
27
  }, "t" | "a"> & {
28
- t?: Array<RecursiveEncodedTrace>;
28
+ t: Array<RecursiveEncodedTrace>;
29
29
  a?: EncodedAttributes;
30
30
  };
31
31
  export declare class RequestSnapshotEncoder {
@@ -22,9 +22,7 @@ const SNAPSHOT_KEY_MAP = {
22
22
  export class RequestSnapshotEncoder {
23
23
  static encode(snapshot) {
24
24
  const encoded = remapKeys(snapshot, SNAPSHOT_KEY_MAP);
25
- if (snapshot.traces) {
26
- encoded.t = snapshot.traces.map((trace) => encodeTrace(trace));
27
- }
25
+ encoded.t = (snapshot.traces ?? []).map((trace) => encodeTrace(trace));
28
26
  if (snapshot.attributes) {
29
27
  encoded.a = remapKeys(snapshot.attributes, ATTRIBUTES_KEY_MAP);
30
28
  }
@@ -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
@@ -195,6 +199,18 @@ export interface ObserveOptions {
195
199
  * @default 5000
196
200
  */
197
201
  flushInterval?: number;
202
+ /**
203
+ * How long, in milliseconds, closing the application waits for buffered
204
+ * telemetry to reach the collector before stopping the agent anyway. Runs
205
+ * on `app.close()`, and on a shutdown signal when the application called
206
+ * `app.enableShutdownHooks()`.
207
+ *
208
+ * `0` skips the final send - for test suites that boot the application
209
+ * with real credentials and should neither send their requests to the
210
+ * project nor wait on the collector at every `close()`.
211
+ * @default 2000
212
+ */
213
+ shutdownFlushTimeout?: number;
198
214
  /**
199
215
  * Whether to collect runtime metrics: memory, CPU load, GC and event loop
200
216
  * latency, sampled on an interval and drawn as gauges.
@@ -238,6 +254,8 @@ export interface ObserveOptions {
238
254
  /**
239
255
  * Maximum number of traces per batch that can be sent to the Agent.
240
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.
241
259
  * @default 1000
242
260
  */
243
261
  maxTracesPerBatch?: number;
@@ -176,6 +176,13 @@ export declare class OperationTraceRegistry {
176
176
  * no response has no status code to file it under.
177
177
  */
178
178
  abandonTrace(traceId: TraceId): void;
179
+ /**
180
+ * Plucks waiting out `SNAPSHOT_COMPLETION_TIMEOUT_MS` for spans that were
181
+ * still open when their operation ended. Their snapshots reach the buffer
182
+ * only once the wait is over, which a final flush has to wait for.
183
+ */
184
+ private awaitingCompletion;
185
+ hasSnapshotsAwaitingCompletion(): boolean;
179
186
  pluckSnapshot(traceId: string): Promise<RequestSnapshot | JobSnapshot | undefined>;
180
187
  /**
181
188
  * Whether `skipSpans` claims a finished operation. Only request snapshots
@@ -506,6 +506,15 @@ export class OperationTraceRegistry {
506
506
  this.callerIdsByTraceId.delete(traceId);
507
507
  this.traceSnapshots.delete(traceId);
508
508
  }
509
+ /**
510
+ * Plucks waiting out `SNAPSHOT_COMPLETION_TIMEOUT_MS` for spans that were
511
+ * still open when their operation ended. Their snapshots reach the buffer
512
+ * only once the wait is over, which a final flush has to wait for.
513
+ */
514
+ awaitingCompletion = 0;
515
+ hasSnapshotsAwaitingCompletion() {
516
+ return this.awaitingCompletion > 0;
517
+ }
509
518
  async pluckSnapshot(traceId) {
510
519
  const snapshot = this.traceSnapshots.get(traceId);
511
520
  if (snapshot) {
@@ -515,7 +524,13 @@ export class OperationTraceRegistry {
515
524
  };
516
525
  // Ensure snapshot is complete by checking refsCounter vs refsMarkedAsComplete
517
526
  if (snapshot.refsCounter > snapshot.refsMarkedAsComplete) {
518
- await new Promise((resolve) => setTimeout(resolve, SNAPSHOT_COMPLETION_TIMEOUT_MS));
527
+ this.awaitingCompletion += 1;
528
+ try {
529
+ await new Promise((resolve) => setTimeout(resolve, SNAPSHOT_COMPLETION_TIMEOUT_MS));
530
+ }
531
+ finally {
532
+ this.awaitingCompletion -= 1;
533
+ }
519
534
  if (snapshot.refsCounter > snapshot.refsMarkedAsComplete) {
520
535
  cleanup();
521
536
  return undefined;
@@ -27,6 +27,14 @@ export declare class StdoutForwarderService implements OnModuleInit, OnModuleDes
27
27
  private readonly redactor;
28
28
  constructor(options: ObserveModuleOptionsWithDefaults, observeAgentSharedBuffer: ObserveAgentSharedBuffer, als: AsyncLocalStorage<Map<string, any>>);
29
29
  onModuleInit(): void;
30
+ /**
31
+ * Stops forwarding at the first close phase - before in-flight requests
32
+ * finish and before the final flush. Lines written after this point, a
33
+ * draining request's included, are not sent; its snapshot still is. Moving
34
+ * this later needs care: forwarding during the final flush would feed the
35
+ * agent's own "could not reach the collector" lines back into the batches
36
+ * it is trying to send.
37
+ */
30
38
  onModuleDestroy(): void;
31
39
  /**
32
40
  * Patches both stdout and stderr. Nest's `ConsoleLogger` writes `error` to
@@ -47,4 +55,12 @@ export declare class StdoutForwarderService implements OnModuleInit, OnModuleDes
47
55
  private consume;
48
56
  private flushPartial;
49
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;
50
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;
@@ -86,6 +95,14 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
86
95
  this.logger.debug("Forwarding log lines written to stdout and stderr to Observe.");
87
96
  }
88
97
  }
98
+ /**
99
+ * Stops forwarding at the first close phase - before in-flight requests
100
+ * finish and before the final flush. Lines written after this point, a
101
+ * draining request's included, are not sent; its snapshot still is. Moving
102
+ * this later needs care: forwarding during the final flush would feed the
103
+ * agent's own "could not reach the collector" lines back into the batches
104
+ * it is trying to send.
105
+ */
89
106
  onModuleDestroy() {
90
107
  this.restore();
91
108
  }
@@ -179,7 +196,15 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
179
196
  const contextTraceId = store?.get(this.options.traceIdKey);
180
197
  // The line's own trace id wins: it was captured when the log was written,
181
198
  // whereas the async store is read now and may already have moved on.
182
- 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;
183
208
  return {
184
209
  timestamp: Date.now(),
185
210
  traceId,
@@ -191,7 +216,9 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
191
216
  ? store?.get(CALLER_METADATA_KEY)
192
217
  : undefined,
193
218
  level: parsed.level,
194
- context: parsed.context,
219
+ context: parsed.context === undefined
220
+ ? undefined
221
+ : this.toContext(parsed.context),
195
222
  // Redaction happens here, before the entry reaches the shared buffer -
196
223
  // which is also before the buffer truncates oversized lines. That order is
197
224
  // deliberate: truncating first would cut a long secret in half and ship
@@ -204,6 +231,19 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
204
231
  : parsed.message,
205
232
  };
206
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
+ }
207
247
  };
208
248
  StdoutForwarderService = StdoutForwarderService_1 = __decorate([
209
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;