@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.
@@ -11,15 +11,17 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
11
  return function (target, key) { decorator(target, key, paramIndex); }
12
12
  };
13
13
  var ObserveAgentWorker_1;
14
- import { Inject, Injectable, Logger, } from "@nestjs/common";
14
+ import { Inject, Injectable, Logger, Optional, } from "@nestjs/common";
15
15
  import { hostname } from "node:os";
16
+ import { setTimeout as sleep } from "node:timers/promises";
16
17
  import { Worker } from "worker_threads";
17
18
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
18
19
  import { CpuProfilerService } from "../profiling/cpu-profiler.service.js";
19
20
  import { ProfileUploader } from "../profiling/profile-uploader.js";
20
21
  import { setActiveSliceRecorder, SpanSliceRecorder, } from "../profiling/span-slice-recorder.js";
21
22
  import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.service.js";
22
- import { parseDegradedMessage } from "./degraded-ingest.protocol.js";
23
+ import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
24
+ import { parseDegradedMessage, parsePausedMessage, } from "./degraded-ingest.protocol.js";
23
25
  import { detachedWorkerData, detachedWorkerSource, } from "./detached-observe-worker.assembly.js";
24
26
  import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
25
27
  const DEFAULT_RUNTIME_METRICS_INTERVAL = 60000; // 60 seconds
@@ -30,6 +32,35 @@ const DEFAULT_FLUSH_INTERVAL = 5000; // 5 seconds
30
32
  */
31
33
  const DEFAULT_COLLECTOR_ENDPOINT = process.env.OBSERVE_ENDPOINT ?? "https://observe-api.nestjs.com";
32
34
  const MIN_FLUSH_INTERVAL = 1000; // 1 second
35
+ /**
36
+ * How long shutdown waits for buffered telemetry to reach the collector before
37
+ * terminating the worker anyway, unless `shutdownFlushTimeout` says otherwise.
38
+ *
39
+ * Several times a healthy round trip to the hosted collector - gzip, a POST,
40
+ * a few-hundred-byte reply, a fresh TLS handshake if the kept-alive socket has
41
+ * gone - and well inside the grace period an orchestrator gives a process
42
+ * after SIGTERM (30 s on ECS and Kubernetes by default), which also has to
43
+ * cover the application's own shutdown hooks. The worker gives up on a silent
44
+ * collector only after its own, much longer, request timeout, so this is what
45
+ * keeps such a collector from holding shutdown open.
46
+ */
47
+ const FINAL_FLUSH_TIMEOUT_MS = 2000;
48
+ /**
49
+ * How often the final flush looks at the shared slot while the worker is
50
+ * sending. Not what bounds the drain: every batch also waits out the worker's
51
+ * 50 ms idle sleep before it is picked up, which is why the final flush sends
52
+ * the log backlog as one batch rather than 250 lines per round trip.
53
+ */
54
+ const FINAL_FLUSH_POLL_MS = 10;
55
+ /**
56
+ * The shortest window a last runtime sample is taken over at shutdown.
57
+ *
58
+ * A sample's CPU and event-loop figures are rates over the time since the
59
+ * previous one. Over a few milliseconds - a process that has only just
60
+ * started, or one stopped straight after a scheduled sample - they read as
61
+ * a pegged CPU and a saturated loop, and mean nothing.
62
+ */
63
+ const MIN_FINAL_RUNTIME_WINDOW_MS = 10_000;
33
64
  /**
34
65
  * The credentials `nest new --observe` writes into `AppModule`.
35
66
  *
@@ -45,6 +76,7 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
45
76
  observeAgentSharedBuffer;
46
77
  options;
47
78
  nodeRuntimeMetricsService;
79
+ operationTraceRegistry;
48
80
  logger = new Logger(ObserveAgentWorker_1.name);
49
81
  // Null before `initializeWorker` and again after termination, which is what
50
82
  // the shutdown path below checks for.
@@ -61,11 +93,21 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
61
93
  isTerminating = false;
62
94
  flushInterval;
63
95
  runtimeMetricsInterval = null;
96
+ /** When the last runtime sample was taken, or sampling started. */
97
+ lastRuntimeSampleAt = 0;
64
98
  cpuProfiler = null;
65
- constructor(observeAgentSharedBuffer, options, nodeRuntimeMetricsService) {
99
+ /** The one shutdown, however many times Nest asks for it. */
100
+ shutdownPromise = null;
101
+ /**
102
+ * 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.
104
+ */
105
+ sendsPausedUntil = 0;
106
+ constructor(observeAgentSharedBuffer, options, nodeRuntimeMetricsService, operationTraceRegistry) {
66
107
  this.observeAgentSharedBuffer = observeAgentSharedBuffer;
67
108
  this.options = options;
68
109
  this.nodeRuntimeMetricsService = nodeRuntimeMetricsService;
110
+ this.operationTraceRegistry = operationTraceRegistry;
69
111
  }
70
112
  onModuleInit() {
71
113
  if (this.hasScaffoldCredentials) {
@@ -110,7 +152,9 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
110
152
  this.logger.warn(`Runtime metrics interval is too short (${interval}ms). Setting to minimum of ${MIN_RUNTIME_METRICS_INTERVAL}ms.`);
111
153
  interval = MIN_RUNTIME_METRICS_INTERVAL;
112
154
  }
155
+ this.lastRuntimeSampleAt = Date.now();
113
156
  this.runtimeMetricsInterval = setInterval(() => {
157
+ this.lastRuntimeSampleAt = Date.now();
114
158
  this.observeAgentSharedBuffer.addNodeRuntimeMetrics(this.nodeRuntimeMetricsService.collectNodeRuntimeMetrics());
115
159
  }, interval);
116
160
  if (this.options.debug) {
@@ -170,10 +214,46 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
170
214
  });
171
215
  this.logger.log("Continuous profiling enabled.");
172
216
  }
173
- async onApplicationShutdown() {
217
+ /**
218
+ * Sends what is still buffered, then stops the worker.
219
+ *
220
+ * Runs in `onApplicationShutdown` rather than `beforeApplicationShutdown`
221
+ * on purpose. Nest closes an application as destroy hooks, then
222
+ * before-shutdown hooks, then the HTTP server (letting in-flight requests
223
+ * finish, and record their snapshots), then shutdown hooks - so this is the
224
+ * last point at which requests are still being recorded. Forwarded log
225
+ * lines stop earlier, in the destroy phase (see StdoutForwarderService).
226
+ *
227
+ * Shutdown hooks run module by module, the root module first and global
228
+ * modules last - but global modules among themselves in reverse order of
229
+ * registration. One registered before ObserveModule shuts down after this
230
+ * hook, and what it records then stays in the main-thread buffer, unsent:
231
+ * BullModule, whose workers let their active jobs finish in their own
232
+ * shutdown hook, is the common case. Hence "import ObserveModule first" in
233
+ * the README; with `forRootAsync({ global: false })` this runs before every
234
+ * global module.
235
+ *
236
+ * On a signal, none of this runs unless the application called
237
+ * `app.enableShutdownHooks()` - without it Node ends the process at once.
238
+ *
239
+ * Called once however many times it is asked: `enableShutdownHooks()` plus
240
+ * an application's own signal handler calling `close()` both get here, and a
241
+ * second run would otherwise race the first for the worker.
242
+ */
243
+ onApplicationShutdown() {
244
+ this.shutdownPromise ??= this.shutDown();
245
+ return this.shutdownPromise;
246
+ }
247
+ async shutDown() {
174
248
  if (this.flushInterval) {
175
249
  clearInterval(this.flushInterval);
176
250
  }
251
+ const timeoutMs = this.options.shutdownFlushTimeout ?? FINAL_FLUSH_TIMEOUT_MS;
252
+ // Before the first `await`: on Nest 11 every shutdown hook in this module
253
+ // starts at once, and NodeRuntimeMetricsService stops its monitors as soon
254
+ // as this one yields. Nest 12 runs this hook first, as this class depends
255
+ // on that service.
256
+ const sampleRuntimeMetricsLast = timeoutMs > 0 && this.worker !== null && this.takeFinalRuntimeSample();
177
257
  if (this.runtimeMetricsInterval) {
178
258
  clearInterval(this.runtimeMetricsInterval);
179
259
  }
@@ -182,16 +262,160 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
182
262
  await this.cpuProfiler.stop();
183
263
  this.cpuProfiler = null;
184
264
  }
185
- if (!this.worker) {
265
+ // No worker - scaffold credentials, or never started - means nothing was
266
+ // ever going to be sent, so there is nothing to flush either.
267
+ const worker = this.worker;
268
+ if (!worker) {
186
269
  return;
187
270
  }
271
+ // Set before the final flush rather than just before `terminate`: a worker
272
+ // that dies while draining must not be replaced by one nothing will stop.
188
273
  this.isTerminating = true;
189
- await this.worker.terminate();
274
+ if (timeoutMs > 0) {
275
+ try {
276
+ await this.flushBeforeShutdown(worker, timeoutMs, sampleRuntimeMetricsLast);
277
+ }
278
+ catch (error) {
279
+ // `flush` reports its own failures; this is anything else, and a
280
+ // shutdown hook that throws would only trade lost telemetry for a
281
+ // shutdown that does not finish cleanly.
282
+ if (this.options.debug) {
283
+ this.logger.debug(`Final flush before shutdown failed: ${String(error)}`);
284
+ }
285
+ }
286
+ }
287
+ await worker.terminate();
190
288
  if (this.options.debug) {
191
289
  this.logger.debug("Worker terminated successfully.");
192
290
  }
193
291
  this.worker = null;
194
292
  }
293
+ /**
294
+ * Hands everything still buffered to the worker and waits for it to be
295
+ * sent, for at most `timeoutMs`.
296
+ *
297
+ * Telemetry sits in up to three places at shutdown: the main-thread batch
298
+ * (plus log lines held back for later batches), the shared slot, and the
299
+ * worker's in-flight request - the worker keeps the slot locked and filled
300
+ * until the collector has answered. The slot holds one batch, and a plain
301
+ * `flush()` skips while the worker holds it, so this is a loop: wait for the
302
+ * slot to empty, write the next batch, repeat until there is nothing left to
303
+ * write and the worker is done with the last one. Waiting for an empty slot
304
+ * before each write is also what stops the final flush overwriting a batch
305
+ * the worker has not read yet.
306
+ *
307
+ * Timed with `node:timers` and `process.uptime()` rather than the global
308
+ * `setTimeout` and `Date.now()`, which test suites' fake timers replace - a
309
+ * shutdown waiting on those would never finish.
310
+ *
311
+ * Never throws for a send: a refused or failed batch is reported by the
312
+ * worker as it always is, and clears the slot like a sent one. A worker
313
+ * paused after a 429, or refused for its credentials, says so and is not
314
+ * waited for.
315
+ */
316
+ async flushBeforeShutdown(worker, timeoutMs, sampleRuntimeMetrics) {
317
+ const buffer = this.observeAgentSharedBuffer;
318
+ const deadline = process.uptime() * 1000 + timeoutMs;
319
+ // A worker that dies mid-drain will never empty the slot; there is no
320
+ // point waiting out the deadline for it.
321
+ let exited = false;
322
+ const onExit = () => {
323
+ exited = true;
324
+ };
325
+ worker.once("exit", onExit);
326
+ try {
327
+ // Every protocol records its snapshot from a `setTimeout(0)` after the
328
+ // response or job has finished, so the last requests a process served
329
+ // may not be in the buffer yet - and an empty buffer would end this
330
+ // before they land. A zero timer set now fires after the ones already
331
+ // queued, and the microtasks each of those starts run before it does.
332
+ // A trace whose spans were still open waits a further second in the
333
+ // registry; the loop below waits for those too.
334
+ await sleep(0);
335
+ for (;;) {
336
+ if (exited) {
337
+ if (this.options.debug) {
338
+ this.logger.debug("Worker exited before the final flush completed. Telemetry still buffered was not sent.");
339
+ }
340
+ return;
341
+ }
342
+ if (Date.now() < this.sendsPausedUntil) {
343
+ if (this.options.debug) {
344
+ this.logger.debug("The collector refused the last batch and sends are paused. Telemetry still buffered was not sent.");
345
+ }
346
+ return;
347
+ }
348
+ if (!buffer.hasBatchAwaitingWorker()) {
349
+ // The whole backlog in one batch once the batch before it has gone,
350
+ // not 250 lines per round trip: each batch also waits out the
351
+ // worker's idle sleep, and a full backlog would outlast the deadline.
352
+ if (buffer.isBufferEmpty()) {
353
+ buffer.drainPendingLogs(Number.POSITIVE_INFINITY);
354
+ }
355
+ this.flush();
356
+ if (!buffer.hasBatchAwaitingWorker() &&
357
+ buffer.isBufferEmpty() &&
358
+ !buffer.hasPendingLogs() &&
359
+ !this.operationTraceRegistry?.hasSnapshotsAwaitingCompletion()) {
360
+ if (!sampleRuntimeMetrics) {
361
+ return;
362
+ }
363
+ // Taken only now that whatever was already buffered has gone: a
364
+ // batch carries a single runtime sample, and each sample covers the
365
+ // window since the previous one, so taking this earlier could
366
+ // replace an unsent sample and lose its window.
367
+ sampleRuntimeMetrics = false;
368
+ this.addFinalRuntimeMetrics();
369
+ continue;
370
+ }
371
+ }
372
+ if (process.uptime() * 1000 >= deadline) {
373
+ if (this.options.debug) {
374
+ this.logger.debug(`Final flush did not complete within ${timeoutMs}ms. Telemetry still buffered was not sent.`);
375
+ }
376
+ return;
377
+ }
378
+ await sleep(FINAL_FLUSH_POLL_MS);
379
+ }
380
+ }
381
+ finally {
382
+ worker.off("exit", onExit);
383
+ }
384
+ }
385
+ /**
386
+ * Adds the last runtime sample to the outgoing batch, or says it must wait
387
+ * until that batch has gone.
388
+ *
389
+ * Skipped when its window would be shorter than
390
+ * `MIN_FINAL_RUNTIME_WINDOW_MS`. Otherwise it rides the first batch the
391
+ * final flush sends - unless that batch already carries a sample, which it
392
+ * would replace; then it is taken last (returns `true`), when on Nest 11
393
+ * the monitors may already have stopped.
394
+ */
395
+ takeFinalRuntimeSample() {
396
+ if (!this.runtimeMetricsInterval ||
397
+ Date.now() - this.lastRuntimeSampleAt < MIN_FINAL_RUNTIME_WINDOW_MS) {
398
+ return false;
399
+ }
400
+ if (this.observeAgentSharedBuffer.hasRuntimeMetrics()) {
401
+ return true;
402
+ }
403
+ this.addFinalRuntimeMetrics();
404
+ return false;
405
+ }
406
+ /**
407
+ * The runtime-metrics window between the last scheduled sample and now.
408
+ */
409
+ addFinalRuntimeMetrics() {
410
+ try {
411
+ this.observeAgentSharedBuffer.addNodeRuntimeMetrics(this.nodeRuntimeMetricsService.collectNodeRuntimeMetrics());
412
+ }
413
+ catch (error) {
414
+ if (this.options.debug) {
415
+ this.logger.debug(`Could not collect final runtime metrics: ${String(error)}`);
416
+ }
417
+ }
418
+ }
195
419
  get hasScaffoldCredentials() {
196
420
  return (this.options.appKey === SCAFFOLD_APP_KEY &&
197
421
  this.options.appSecret === SCAFFOLD_APP_SECRET);
@@ -243,9 +467,14 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
243
467
  appSecret: this.options.appSecret,
244
468
  }),
245
469
  });
246
- this.worker.on("message", (msg) => this.handleMessage(msg));
247
- this.worker.on("error", (error) => this.handleError(error));
248
- this.worker.on("exit", (code) => {
470
+ this.watchWorker(this.worker);
471
+ this.logger.log("Observe agent worker initialized.");
472
+ }
473
+ /** The worker's messages, errors, and the restart when it dies. */
474
+ watchWorker(worker) {
475
+ worker.on("message", (msg) => this.handleMessage(msg));
476
+ worker.on("error", (error) => this.handleError(error));
477
+ worker.on("exit", (code) => {
249
478
  if (this.isTerminating) {
250
479
  this.logger.debug("Worker exited on shutdown.");
251
480
  return;
@@ -258,12 +487,16 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
258
487
  this.logger.debug("Worker exited gracefully.");
259
488
  }
260
489
  });
261
- this.logger.log("Observe agent worker initialized.");
262
490
  }
263
491
  handleMessage(msg) {
264
- const degraded = parseDegradedMessage(msg);
265
- if (degraded !== null) {
266
- this.applyDegraded(degraded);
492
+ const pausedUntil = parsePausedMessage(msg);
493
+ if (pausedUntil !== null) {
494
+ this.sendsPausedUntil = pausedUntil;
495
+ return;
496
+ }
497
+ const mode = parseDegradedMessage(msg);
498
+ if (mode !== null) {
499
+ this.applyIngestMode(mode);
267
500
  return;
268
501
  }
269
502
  if (msg.includes("Error:")) {
@@ -275,33 +508,43 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
275
508
  }
276
509
  }
277
510
  /**
278
- * Whether the last reply said the collector is discarding spans.
511
+ * What the last reply said the collector does with spans.
279
512
  *
280
513
  * Kept beside the log rather than read from the buffer so the notice fires
281
514
  * once per transition: an account sits in this state for days, and a line
282
515
  * per flush would bury the one thing worth reading.
283
516
  */
284
- reportedDegraded = false;
517
+ reportedMode = "full";
285
518
  /**
286
519
  * Stops sending trace trees the collector has told us it is throwing away,
287
- * and says so once.
520
+ * and says so once - and again only when the reason changes.
288
521
  *
289
522
  * Said at `warn` rather than `debug`: the application is still being
290
- * 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
291
524
  * that out by opening a trace and seeing nothing has been let down by an
292
- * 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.
293
527
  */
294
- applyDegraded(degraded) {
295
- this.observeAgentSharedBuffer.setDegraded(degraded);
296
- if (degraded && !this.reportedDegraded) {
297
- this.logger.warn("Observe: this account has spent its monthly event allowance. Requests, jobs " +
298
- "and errors are still being recorded; spans are not, so traces will show no " +
299
- "waterfall. The agent has stopped sending them. See /dashboard/billing.");
300
- }
301
- 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 {
302
545
  this.logger.log("Observe: spans are being recorded again.");
303
546
  }
304
- this.reportedDegraded = degraded;
547
+ this.reportedMode = mode;
305
548
  }
306
549
  handleError(error) {
307
550
  this.logger.error(error);
@@ -346,6 +589,8 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
346
589
  ObserveAgentWorker = ObserveAgentWorker_1 = __decorate([
347
590
  Injectable(),
348
591
  __param(1, Inject(OBSERVE_OPTIONS)),
349
- __metadata("design:paramtypes", [ObserveAgentSharedBuffer, Object, NodeRuntimeMetricsService])
592
+ __param(3, Optional()),
593
+ __metadata("design:paramtypes", [ObserveAgentSharedBuffer, Object, NodeRuntimeMetricsService,
594
+ OperationTraceRegistry])
350
595
  ], ObserveAgentWorker);
351
596
  export { ObserveAgentWorker };
@@ -39,15 +39,43 @@ export interface FieldSpec {
39
39
  readonly alsoAccepts?: readonly FieldType[];
40
40
  /** The field must be present and non-null. */
41
41
  readonly required?: boolean;
42
+ /**
43
+ * For a required field whose absence has a meaning: what the sanitizer
44
+ * sends in its place, instead of dropping the entry over it. Plain JSON, as
45
+ * it travels to the worker with the shapes.
46
+ */
47
+ readonly fallback?: unknown;
42
48
  /** The field is an array of `type`. */
43
49
  readonly array?: boolean;
44
50
  /** Nested contract, for object fields the API models rather than passes through. */
45
51
  readonly shape?: Shape;
46
52
  /** The nested contract is this shape itself - trace nodes nest arbitrarily deep. */
47
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;
48
64
  }
49
65
  export type Shape = Readonly<Record<string, FieldSpec>>;
50
- /** 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
+ */
51
79
  export declare const TELEMETRY_BATCH: Shape;
52
80
  /**
53
81
  * The sections of a batch whose entries are individually expendable. Maps each
@@ -101,13 +129,26 @@ export interface TelemetrySanitizer {
101
129
  * would have rejected the whole batch over them (`forbidNonWhitelisted`).
102
130
  * A *required* field that is missing or unusable cannot be repaired by
103
131
  * removal, so the entry is dropped alone rather than the collector dropping
104
- * the batch.
132
+ * the batch - unless the contract names a fallback for a missing one, as it
133
+ * does for an operation's spans: an operation without its trace array is sent
134
+ * with an empty one, which is what the absence meant.
105
135
  *
106
136
  * Numbers must be finite: `NaN` and `Infinity` survive `typeof` but serialize
107
137
  * to `null` in JSON, which arrives at the API as a present-but-null field and
108
138
  * fails validation there. They are judged here as what they will be on the
109
139
  * wire, not as what they are in memory.
110
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
+ *
111
152
  * A factory rather than module-level functions, and deliberately
112
153
  * self-contained - it closes over nothing but its own parameter. The detached
113
154
  * worker runs as a stringified function with no module scope, so this