@nestjs/observe 0.3.25 → 0.3.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +17 -0
  2. package/dist/agent/detached-observe-worker.js +50 -6
  3. package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
  4. package/dist/agent/observe-agent.shared-buffer.js +196 -19
  5. package/dist/agent/observe-agent.worker.d.ts +22 -2
  6. package/dist/agent/observe-agent.worker.js +43 -7
  7. package/dist/agent/telemetry-wire-contract.js +7 -1
  8. package/dist/cli/agent-notes.js +16 -4
  9. package/dist/cli/link.js +28 -3
  10. package/dist/cli/observe-cli.js +1 -19
  11. package/dist/cli/open-url.d.ts +27 -0
  12. package/dist/cli/open-url.js +63 -0
  13. package/dist/cli/project-files.d.ts +42 -1
  14. package/dist/cli/project-files.js +146 -7
  15. package/dist/cli/project-setup.d.ts +6 -0
  16. package/dist/cli/project-setup.js +14 -1
  17. package/dist/cli/wire-application.js +6 -0
  18. package/dist/custom-metrics/counter.d.ts +13 -2
  19. package/dist/custom-metrics/counter.js +33 -16
  20. package/dist/custom-metrics/finite-value.util.d.ts +14 -0
  21. package/dist/custom-metrics/finite-value.util.js +33 -1
  22. package/dist/custom-metrics/gauge.d.ts +2 -0
  23. package/dist/custom-metrics/gauge.js +41 -17
  24. package/dist/custom-metrics/label-values.util.d.ts +37 -0
  25. package/dist/custom-metrics/label-values.util.js +51 -0
  26. package/dist/custom-metrics/summary.d.ts +23 -0
  27. package/dist/custom-metrics/summary.js +73 -2
  28. package/dist/instrument/create-instance-decorator.instrument.js +158 -96
  29. package/dist/interfaces/observe-options.interface.d.ts +3 -1
  30. package/dist/objectives/objectives.registry.js +12 -0
  31. package/dist/observe.module.js +119 -3
  32. package/dist/otlp/otlp-encoders.js +22 -5
  33. package/dist/otlp/otlp-span.mapper.js +7 -3
  34. package/dist/otlp/otlp-trace-exporter.service.js +63 -5
  35. package/dist/outgoing/http.integration.d.ts +8 -4
  36. package/dist/outgoing/http.integration.js +13 -6
  37. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  38. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  39. package/dist/outgoing/llm/llm-providers.js +72 -22
  40. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  41. package/dist/outgoing/llm/llm-usage.js +72 -25
  42. package/dist/outgoing/mssql.integration.js +16 -2
  43. package/dist/outgoing/mysql2.integration.js +17 -1
  44. package/dist/outgoing/outgoing-observe-agent.service.js +15 -3
  45. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  46. package/dist/outgoing/pg.integration.d.ts +3 -2
  47. package/dist/outgoing/pg.integration.js +39 -11
  48. package/dist/outgoing/sql-statement.util.js +106 -14
  49. package/dist/outgoing/undici.integration.d.ts +13 -0
  50. package/dist/outgoing/undici.integration.js +68 -0
  51. package/dist/protocols/bull-observe-agent.service.js +2 -12
  52. package/dist/protocols/deferred-trace-completion.d.ts +9 -1
  53. package/dist/protocols/deferred-trace-completion.js +36 -6
  54. package/dist/protocols/graphql-observe-agent.service.d.ts +36 -5
  55. package/dist/protocols/graphql-observe-agent.service.js +166 -5
  56. package/dist/protocols/graphql-operation-parser.js +72 -18
  57. package/dist/protocols/http-observe-agent.service.d.ts +43 -9
  58. package/dist/protocols/http-observe-agent.service.js +177 -59
  59. package/dist/protocols/job-trace-runner.d.ts +35 -3
  60. package/dist/protocols/job-trace-runner.js +126 -29
  61. package/dist/protocols/queue-observe-agent.service.js +44 -20
  62. package/dist/protocols/rpc-observe-agent.service.d.ts +50 -8
  63. package/dist/protocols/rpc-observe-agent.service.js +187 -47
  64. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  65. package/dist/protocols/ws-observe-agent.service.js +226 -20
  66. package/dist/services/index.d.ts +1 -1
  67. package/dist/services/index.js +1 -1
  68. package/dist/services/logger-patcher.service.js +3 -4
  69. package/dist/services/operation-trace.registry.d.ts +45 -1
  70. package/dist/services/operation-trace.registry.js +418 -35
  71. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  72. package/dist/services/stdout-forwarder.service.js +288 -51
  73. package/dist/services/tracer.service.d.ts +23 -0
  74. package/dist/services/tracer.service.js +91 -5
  75. package/dist/utils/capture-request.util.d.ts +3 -1
  76. package/dist/utils/capture-request.util.js +100 -12
  77. package/dist/utils/fit-to-length.util.js +33 -10
  78. package/dist/utils/log-line.parser.d.ts +14 -0
  79. package/dist/utils/log-line.parser.js +7 -3
  80. package/dist/utils/log-redactor.d.ts +14 -0
  81. package/dist/utils/log-redactor.js +512 -61
  82. package/dist/utils/operation-state.util.d.ts +39 -0
  83. package/dist/utils/operation-state.util.js +50 -0
  84. package/dist/utils/redact-url-query.d.ts +26 -4
  85. package/dist/utils/redact-url-query.js +184 -32
  86. package/dist/utils/sensitive-keys.d.ts +4 -1
  87. package/dist/utils/sensitive-keys.js +48 -10
  88. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  89. package/dist/utils/shared-hook-slot.util.js +103 -0
  90. package/dist/utils/source-context.util.d.ts +8 -0
  91. package/dist/utils/source-context.util.js +88 -24
  92. package/dist/utils/source-map-resolver.util.js +8 -2
  93. package/dist/utils/trace-context.util.js +21 -6
  94. package/package.json +2 -2
@@ -4,10 +4,24 @@ import { uuidv7 } from "../utils/uuid-v7.util.js";
4
4
  import { TraceSpanDelegate } from "../trace-span.delegate.js";
5
5
  import { collectCodeFrames } from "../utils/source-context.util.js";
6
6
  import { fallbackOperationId } from "../utils/fallback-operation-id.util.js";
7
+ import { fitToLength } from "../utils/fit-to-length.util.js";
7
8
  import { LogRedactor } from "../utils/log-redactor.js";
8
9
  import { CALLER_METADATA_KEY } from "../observe.constants.js";
9
10
  import { collapseRepeatedSpans, DEFAULT_SPAN_COLLAPSE, } from "./collapse-repeated-spans.util.js";
10
11
  const SNAPSHOT_COMPLETION_TIMEOUT_MS = 1000;
12
+ /**
13
+ * Deepest a span is nested in the tree that is shipped, root span included.
14
+ *
15
+ * Far past any call chain written by hand, and about a ninth of the depth at
16
+ * which the first walk of a tree - building it for shipping, collapsing it,
17
+ * encoding it, serialising the batch it rides in - runs out of stack. Async
18
+ * recursion is traced level by level (the instance decorator only keeps a
19
+ * synchronous call out of the tree), so a method that awaits and then calls
20
+ * itself once per level of a client's JSON body nested its spans as deep as
21
+ * the body was, and the batch's `JSON.stringify` threw away every other
22
+ * operation of the flush window with it.
23
+ */
24
+ const MAX_SPAN_DEPTH = 256;
11
25
  /**
12
26
  * Tag under which a snapshot records how many spans were left out of its tree
13
27
  * because they had not ended when it was shipped - the spans still open and
@@ -18,6 +32,38 @@ const SNAPSHOT_COMPLETION_TIMEOUT_MS = 1000;
18
32
  * collector release has to come first. Absent on a snapshot shipped whole.
19
33
  */
20
34
  export const UNFINISHED_SPANS_TAG = "observe.unfinishedSpans";
35
+ /**
36
+ * Tag under which a snapshot records how many spans were never opened because
37
+ * it had already opened `MAX_SPANS_PER_TRACE`. A tag for the reason
38
+ * `UNFINISHED_SPANS_TAG` is one. Absent on a snapshot that stayed under it.
39
+ */
40
+ export const UNRECORDED_SPANS_TAG = "observe.unrecordedSpans";
41
+ /**
42
+ * Most spans one operation opens, manual ones included. Past it a traced
43
+ * call runs as it would untraced, and is counted under `UNRECORDED_SPANS_TAG`.
44
+ *
45
+ * Every span is a node, an id and a map entry the registry holds until the
46
+ * operation ends - about 300 bytes - and `spanCollapse` bounds only what is
47
+ * shipped, once it has ended. So a handler that calls a provider once per
48
+ * element of a list it was sent let the sender decide how much the agent
49
+ * held: one 12 MB WebSocket message ran a process out of heap, and an HTTP
50
+ * body within the default limit stalled the event loop for seconds as its
51
+ * spans were collapsed. Ten thousand is far past what a request makes and
52
+ * what the collapsed tree shows, and about 3 MB per open operation.
53
+ */
54
+ const MAX_SPANS_PER_TRACE = 10_000;
55
+ /**
56
+ * Most errors `captureError` records in full for one operation, as many as
57
+ * repeated siblings it takes to collapse a group (`spanCollapse.threshold`).
58
+ *
59
+ * Building a payload redacts the whole message and the whole stack, which
60
+ * repeats the message, so a handler reporting each rejected row of a client's
61
+ * list paid rows x message length on the request thread - seconds for one
62
+ * 100 kB body - and, captured on a span per row, kept every payload until the
63
+ * flush. Past the limit a span is still marked as failed and its tags still
64
+ * merge; it only goes without the details.
65
+ */
66
+ const MAX_CAPTURED_ERRORS_PER_TRACE = 20;
21
67
  /**
22
68
  * An error the business logic did not model. `IntrinsicException` is what Nest
23
69
  * itself uses to tell a deliberately raised failure from a leaked one.
@@ -28,6 +74,170 @@ const UNHANDLED_ERROR_STATUS_CODE = 500;
28
74
  * count as handled; the exact code only matters when the exception carries one.
29
75
  */
30
76
  const HANDLED_ERROR_STATUS_CODE = 400;
77
+ /**
78
+ * The most of an error's message, and of its stack, that is recorded.
79
+ *
80
+ * Both are as long as whoever threw made them, and a message that quotes the
81
+ * request - `No product with sku ${sku}` - is as long as a client made it. V8
82
+ * repeats the message at the head of the stack, and a failed operation carries
83
+ * the error on its root span and on itself, so uncut, each such request held
84
+ * its text four times over until the flush - and the flush, which writes the
85
+ * batch to a 16 MB slot, threw the whole batch away over a few of them.
86
+ */
87
+ const MAX_ERROR_MESSAGE_LENGTH = 4 * 1024;
88
+ const MAX_ERROR_STACK_LENGTH = 8 * 1024;
89
+ /**
90
+ * How much of a cut stack's head is kept - the error's name and the start of
91
+ * its message. The rest of the limit goes to its tail, the frames.
92
+ */
93
+ const ERROR_STACK_HEAD_LENGTH = 2 * 1024;
94
+ const ERROR_TEXT_CUT = "... [truncated by observe]";
95
+ /** The first `length` characters, not ending in half a surrogate pair. */
96
+ function headOf(text, length) {
97
+ const last = text.charCodeAt(length - 1);
98
+ return text.slice(0, last >= 0xd800 && last <= 0xdbff ? length - 1 : length);
99
+ }
100
+ /**
101
+ * Its own copy of a cut: a slice keeps the whole of the text it was taken
102
+ * from alive for as long as the slice itself is.
103
+ */
104
+ function copyOf(text) {
105
+ return Buffer.from(text, "utf8").toString("utf8");
106
+ }
107
+ /** An error's message, cut to the most of it that is recorded. */
108
+ function fitErrorMessage(message) {
109
+ if (typeof message !== "string" ||
110
+ message.length <= MAX_ERROR_MESSAGE_LENGTH) {
111
+ return message;
112
+ }
113
+ return copyOf(headOf(message, MAX_ERROR_MESSAGE_LENGTH - ERROR_TEXT_CUT.length) +
114
+ ERROR_TEXT_CUT);
115
+ }
116
+ /**
117
+ * An error's stack, cut to the most of it that is recorded: its head and its
118
+ * tail, since a stack opens with the message and closes with the frames,
119
+ * which a cut message would otherwise push out of it altogether. The tail
120
+ * starts on a line of its own where it can.
121
+ */
122
+ function fitErrorStack(stack) {
123
+ if (typeof stack !== "string" || stack.length <= MAX_ERROR_STACK_LENGTH) {
124
+ return stack;
125
+ }
126
+ const tailLength = MAX_ERROR_STACK_LENGTH - ERROR_STACK_HEAD_LENGTH - ERROR_TEXT_CUT.length;
127
+ let tailStart = stack.length - tailLength;
128
+ const line = stack.indexOf("\n", tailStart);
129
+ if (line !== -1) {
130
+ tailStart = line;
131
+ }
132
+ else {
133
+ const first = stack.charCodeAt(tailStart);
134
+ if (first >= 0xdc00 && first <= 0xdfff) {
135
+ tailStart += 1;
136
+ }
137
+ }
138
+ return copyOf(headOf(stack, ERROR_STACK_HEAD_LENGTH) +
139
+ ERROR_TEXT_CUT +
140
+ stack.slice(tailStart));
141
+ }
142
+ /**
143
+ * Longest span name the collector takes - the encoder's own limit, which it
144
+ * cuts every name to on the way out.
145
+ */
146
+ const MAX_SPAN_NAME_LENGTH = 255;
147
+ /**
148
+ * Longest manual span name that is read to be cut. A name is as long as the
149
+ * code that opened the span made it, often from a string of a client's, and
150
+ * a name built by concatenation is written out whole the first time any of
151
+ * it is read - so a span per row of a client's list, each named after a long
152
+ * string, cost rows x length on the request thread, however little of each
153
+ * name was kept. A longer one is recorded by its length alone.
154
+ */
155
+ const MAX_READ_SPAN_NAME_LENGTH = 4 * 1024;
156
+ /** A manual span's name, as its node holds it until the trace ships. */
157
+ function fitManualSpanName(name) {
158
+ // Typed, but passed from code nothing checks at run time; left as it is.
159
+ if (typeof name !== "string" || name.length <= MAX_SPAN_NAME_LENGTH) {
160
+ return name;
161
+ }
162
+ if (name.length > MAX_READ_SPAN_NAME_LENGTH) {
163
+ return `[span name of ${name.length} characters]`;
164
+ }
165
+ return fitToLength(name, MAX_SPAN_NAME_LENGTH);
166
+ }
167
+ /**
168
+ * A thrown value, or an error's message, as text - whatever it is.
169
+ *
170
+ * Neither is what its type says for certain. A microservice client rejects
171
+ * with the JSON object the remote service sent as its error, and a driver
172
+ * copies a server reply's fields onto the error it throws; `String()` throws
173
+ * on `{"toString": 1}`, and that was thrown back at the code recording the
174
+ * failure - a handler that reported it and answered with a fallback
175
+ * answered 500 instead.
176
+ */
177
+ function toErrorText(value) {
178
+ if (typeof value === "string") {
179
+ return value;
180
+ }
181
+ try {
182
+ // oxlint-disable-next-line typescript/no-base-to-string -- recorded as `String()` always recorded it
183
+ return String(value);
184
+ }
185
+ catch {
186
+ try {
187
+ return Object.prototype.toString.call(value);
188
+ }
189
+ catch {
190
+ return "[unprintable value]";
191
+ }
192
+ }
193
+ }
194
+ /** An error's stack, when it has one that is text. */
195
+ function stackOf(error) {
196
+ try {
197
+ const stack = error.stack;
198
+ return typeof stack === "string" ? stack : undefined;
199
+ }
200
+ catch {
201
+ return undefined;
202
+ }
203
+ }
204
+ /** The name of a thrown value's class, when it can be read. */
205
+ function classNameOf(error) {
206
+ try {
207
+ const constructor = error
208
+ ?.constructor;
209
+ if (typeof constructor !== "function") {
210
+ return undefined;
211
+ }
212
+ const name = constructor.name;
213
+ return typeof name === "string" ? name : undefined;
214
+ }
215
+ catch {
216
+ return undefined;
217
+ }
218
+ }
219
+ /** An absolute-form request target: `http://api.example.com/graphql?query=`. */
220
+ const ABSOLUTE_URL = /^[a-z][a-z\d+.-]*:\/\//i;
221
+ /**
222
+ * The URL of a request that nothing named - no route, no GraphQL resolver -
223
+ * without its query string.
224
+ *
225
+ * Its query string is masked by parameter name only, and nothing says what
226
+ * it holds: over GET, a GraphQL endpoint's is the operation itself, string
227
+ * literals and `variables` included, which the GraphQL agent's request hook
228
+ * blanks - and the hook did not run for a request that is still unnamed: a
229
+ * middleware refused it, it is a persisted query sent by its hash, or the
230
+ * endpoint is one the hook is not registered for. Anything that is not a
231
+ * request target - a GraphQL document - is left as it is.
232
+ */
233
+ function withoutQueryString(originalUrl) {
234
+ if (typeof originalUrl !== "string" ||
235
+ !(originalUrl.startsWith("/") || ABSOLUTE_URL.test(originalUrl))) {
236
+ return originalUrl;
237
+ }
238
+ const queryAt = originalUrl.indexOf("?");
239
+ return queryAt === -1 ? originalUrl : originalUrl.slice(0, queryAt);
240
+ }
31
241
  /** A node and everything below it. */
32
242
  function countNodes(node) {
33
243
  let count = 1;
@@ -100,6 +310,17 @@ export class OperationTraceRegistry {
100
310
  * would bury everything else in the log. Full text once, one line after.
101
311
  */
102
312
  hasReportedMissingInstrumentation = false;
313
+ /** See `reportSpanDepthLimit`. */
314
+ hasReportedSpanDepthLimit = false;
315
+ /** See `reportCapturedErrorLimit`. */
316
+ hasReportedCapturedErrorLimit = false;
317
+ /** See `countUnrecordedSpan`. */
318
+ hasReportedSpanLimit = false;
319
+ /**
320
+ * Root spans of outgoing calls - a query, an HTTP call - that ended with
321
+ * an error. See `endTrace` for what they decide.
322
+ */
323
+ failedOutgoingRoots = new WeakSet();
103
324
  /**
104
325
  * Applied to every tree as it is plucked. Defaults are live from
105
326
  * construction rather than waiting for `configureSpanCollapse`, so a
@@ -178,10 +399,10 @@ export class OperationTraceRegistry {
178
399
  */
179
400
  toErrorPayload(error) {
180
401
  const raw = error instanceof Error
181
- ? { message: error.message, stack: error.stack }
182
- : { message: String(error), stack: undefined };
402
+ ? { message: toErrorText(error.message), stack: stackOf(error) }
403
+ : { message: toErrorText(error), stack: undefined };
183
404
  // Redacted here, at the one point every error payload passes through.
184
- const payload = this.redactor
405
+ const redacted = this.redactor
185
406
  ? {
186
407
  message: this.redactor.redactMessage(raw.message),
187
408
  stack: raw.stack === undefined
@@ -189,29 +410,30 @@ export class OperationTraceRegistry {
189
410
  : this.redactor.redactMessage(raw.stack),
190
411
  }
191
412
  : raw;
413
+ // Cut once redacted, so no rule is handed half of what it matches.
414
+ const payload = {
415
+ message: fitErrorMessage(redacted.message),
416
+ stack: fitErrorStack(redacted.stack),
417
+ };
192
418
  const result = payload;
193
- if (typeof error?.constructor === "function") {
194
- result.cls = error.constructor.name;
419
+ const cls = classNameOf(error);
420
+ if (cls !== undefined) {
421
+ result.cls = cls;
195
422
  }
196
423
  if (this.sourceContext !== false) {
197
424
  const settings = this.sourceContext === true ? {} : this.sourceContext;
198
425
  // Read off the raw stack with the raw message: the message is what marks
199
426
  // where the frames start, and it only matches the stack it came from.
200
427
  // Nothing of either is shipped from here - just the file positions.
428
+ // Source is as likely to hold a literal secret as a message is, and
429
+ // goes to the same place.
201
430
  const codeFrames = collectCodeFrames(raw.stack, {
202
431
  ...settings,
203
432
  message: raw.message,
433
+ redactor: this.redactor ?? undefined,
204
434
  });
205
435
  if (codeFrames) {
206
- // Source is as likely to hold a literal secret as a message is, and
207
- // goes to the same place.
208
- const redactor = this.redactor;
209
- result.codeFrames = redactor
210
- ? codeFrames.map((frame) => ({
211
- ...frame,
212
- lines: redactor.redactSource(frame.lines),
213
- }))
214
- : codeFrames;
436
+ result.codeFrames = codeFrames;
215
437
  }
216
438
  }
217
439
  return result;
@@ -279,15 +501,21 @@ export class OperationTraceRegistry {
279
501
  // recorded a span for it. Both at once has one cause: the instance
280
502
  // decorator never wrapped the providers, because `instrument` never
281
503
  // reached NestFactory.
504
+ //
505
+ // Dropped before the line is written, not after: a logger taken from
506
+ // the container is wrapped like any provider and writes inside this
507
+ // operation's async store, so with the trace still registered every
508
+ // call it makes on itself opened a span here - in a span map nothing
509
+ // would ever free again.
510
+ this.abandonTrace(traceId);
282
511
  this.reportMissingInstrumentation(snapshot);
283
- this.traceSnapshots.delete(traceId);
284
512
  return;
285
513
  }
286
514
  // Ignore snapshots that have no traces as that means
287
515
  // the request didnt even have a handler in the first place - unless
288
516
  // the transport said the operation is complete without one.
289
517
  if (!snapshot.keptWithoutSpans) {
290
- this.traceSnapshots.delete(traceId);
518
+ this.abandonTrace(traceId);
291
519
  return;
292
520
  }
293
521
  }
@@ -299,7 +527,17 @@ export class OperationTraceRegistry {
299
527
  const reportedStatusCode = "statusCode" in opts && typeof opts.statusCode === "number"
300
528
  ? opts.statusCode
301
529
  : undefined;
302
- const errorStatusCode = "protocol" in snapshot ? snapshot.errorStatusCode : undefined;
530
+ // An outgoing call's error at the root (see `internalEndTraceStep`) may
531
+ // have been caught and answered: a duplicate key turned into a 409, a
532
+ // failed lookup into a 200 with a fallback. A transport that reports a
533
+ // status code says how the operation ended, so there it does not stand in
534
+ // for one; on one that reports none, it is all there is to go on.
535
+ const errorStatusCode = "protocol" in snapshot
536
+ ? snapshot.errorStatusCode ??
537
+ (reportedStatusCode === undefined
538
+ ? snapshot.outgoingErrorStatusCode
539
+ : undefined)
540
+ : undefined;
303
541
  // A root span that threw outranks a success status code reported by the
304
542
  // transport. Two cases need this. Transports that carry no status code of
305
543
  // their own (RPC, gRPC) end their trace without one at all, and the backend
@@ -321,20 +559,51 @@ export class OperationTraceRegistry {
321
559
  jobSnapshot.status = opts.status;
322
560
  }
323
561
  if ("userId" in opts && typeof opts.userId !== "undefined") {
324
- const requestSnapshot = snapshot;
325
- requestSnapshot.userId = String(opts.userId);
562
+ // Typed as a string, but a transport passes on what `getUserId`
563
+ // returned, and `String()` throws on `{"toString": 1}`. Thrown here,
564
+ // between ending the trace and plucking it, it left the trace
565
+ // registered for good; the trace goes without a user id instead.
566
+ let userId;
567
+ try {
568
+ // oxlint-disable-next-line typescript/no-unnecessary-type-conversion -- typed a string, but whatever `getUserId` returned
569
+ userId = String(opts.userId);
570
+ }
571
+ catch {
572
+ userId = undefined;
573
+ }
574
+ if (userId !== undefined) {
575
+ snapshot.userId = userId;
576
+ }
326
577
  }
327
578
  delete snapshot.startTimestamp; // Clean up to avoid confusion
328
579
  if (snapshot.traces && snapshot.traces.length > 0) {
329
- // Iterate through root traces to check if any have errors
580
+ // The first root span that failed gives the operation its error. An
581
+ // outgoing call's counts only where nothing else did and the operation
582
+ // failed by its status - or reported none: otherwise its error was
583
+ // caught and answered, and recording it as the operation's put the
584
+ // driver's message, bound values and all, in place of what the
585
+ // application returned.
586
+ let outgoing;
587
+ let found = false;
330
588
  for (const trace of snapshot.traces) {
331
- if ("error" in trace && trace.error) {
332
- // If any root trace has an error, we mark the entire snapshot as having an error
333
- if (typeof trace.error === "object") {
334
- snapshot.error = trace.error;
335
- }
336
- break; // No need to check further once an error is found
589
+ if (!("error" in trace) || !trace.error) {
590
+ continue;
337
591
  }
592
+ if (this.failedOutgoingRoots.has(trace)) {
593
+ outgoing ??= trace;
594
+ continue;
595
+ }
596
+ if (typeof trace.error === "object") {
597
+ snapshot.error = trace.error;
598
+ }
599
+ found = true;
600
+ break;
601
+ }
602
+ if (!found &&
603
+ typeof outgoing?.error === "object" &&
604
+ (reportedStatusCode === undefined ||
605
+ (typeof statusCode === "number" && statusCode >= 500))) {
606
+ snapshot.error = outgoing.error;
338
607
  }
339
608
  }
340
609
  }
@@ -407,6 +676,12 @@ export class OperationTraceRegistry {
407
676
  if (!snapshot) {
408
677
  return undefined;
409
678
  }
679
+ // No step, as for an operation that is not recorded: every caller then
680
+ // runs the call untraced and closes nothing.
681
+ if (snapshot.refsCounter >= MAX_SPANS_PER_TRACE) {
682
+ this.countUnrecordedSpan(snapshot);
683
+ return undefined;
684
+ }
410
685
  snapshot.refsCounter += 1;
411
686
  const newNodeId = spanId ?? uuidv7();
412
687
  const startTime = performance.now();
@@ -429,6 +704,9 @@ export class OperationTraceRegistry {
429
704
  // store (CALLER_METADATA_KEY), so the two sides agree by construction
430
705
  // instead of by a timing heuristic. It costs a uuid per span on the wire.
431
706
  spanId: newNodeId,
707
+ // Set where the node is attached; in the literal so every node has the
708
+ // same shape from the start.
709
+ depth: 1,
432
710
  };
433
711
  let refsByCaller = this.callerIdsByTraceId.get(traceId);
434
712
  this.attachToCaller(snapshot, refsByCaller, callerId, newNode);
@@ -452,18 +730,45 @@ export class OperationTraceRegistry {
452
730
  * ending after its caller did, is already tolerated in
453
731
  * `internalEndTraceStep`. Auto and manual spans both attach through here, so
454
732
  * they share the tolerance.
733
+ *
734
+ * A node past `MAX_SPAN_DEPTH` is kept out of its caller's children, and so
735
+ * out of the shipped tree, and everything opened under it goes the same
736
+ * way. Nothing else about it changes: it still has its parent, so an error
737
+ * it ends with is not taken for the operation's own, and it is still
738
+ * registered and counted, so the calls under it find their caller and the
739
+ * trace completes when it would have.
455
740
  */
456
741
  attachToCaller(snapshot, refsByCaller, callerId, newNode) {
457
- const caller = callerId ? refsByCaller?.get(callerId) : undefined;
742
+ // Every node in the map was opened by this registry, with its depth.
743
+ const caller = (callerId ? refsByCaller?.get(callerId) : undefined);
458
744
  if (caller?.type === "start") {
459
- caller.children.push(newNode);
460
745
  newNode.parent = caller;
746
+ newNode.depth = caller.depth + 1;
747
+ if (newNode.depth <= MAX_SPAN_DEPTH) {
748
+ caller.children.push(newNode);
749
+ }
750
+ else {
751
+ this.reportSpanDepthLimit(snapshot, newNode);
752
+ }
461
753
  }
462
754
  else {
463
755
  // No (live) caller means insert trace at the root level
464
756
  snapshot.traces.push(newNode);
465
757
  }
466
758
  }
759
+ /**
760
+ * Once for the process: a chain that deep comes from one recursive method,
761
+ * which recurses that deep on every request it is given the same input.
762
+ * Flagged before the line is written, which an instrumented logger records
763
+ * as one more span of the same chain.
764
+ */
765
+ reportSpanDepthLimit(snapshot, node) {
766
+ if (this.hasReportedSpanDepthLimit) {
767
+ return;
768
+ }
769
+ this.hasReportedSpanDepthLimit = true;
770
+ this.logger.warn(`Trace "${snapshot.traceId}" is reported without the spans nested more than ${MAX_SPAN_DEPTH} levels deep, from "${node.className}#${node.methodKey}" down. A method that calls itself once per level of its input traces each level. Later traces this deep are not reported.`);
771
+ }
467
772
  internalEndTraceStep(traceId,
468
773
  /**
469
774
  * Diagnostic label only - it names the span in the two warnings below and
@@ -474,7 +779,9 @@ export class OperationTraceRegistry {
474
779
  // Undefined when `internalStartTraceStep` found no snapshot to open the
475
780
  // step against; the lookup below then misses and warns, as it does for any
476
781
  // other unknown caller.
477
- callerId, error) {
782
+ callerId, error,
783
+ /** The span is an outgoing call's, opened by `OutgoingSpanRecorder`. */
784
+ outgoing = false) {
478
785
  const snapshot = this.traceSnapshots.get(traceId);
479
786
  if (!snapshot) {
480
787
  // The trace was handed off while this span was still open -
@@ -509,13 +816,24 @@ export class OperationTraceRegistry {
509
816
  activeTrace.duration = duration;
510
817
  if (error && !activeTrace.error) {
511
818
  const isRootSpan = !parent;
512
- if (isRootSpan) {
819
+ if (isRootSpan && outgoing) {
820
+ // An outgoing call at the root ran outside every traced call of the
821
+ // operation - most often a query in a cold Observable, run when Nest
822
+ // subscribed, after the provider that built it had returned. Whoever
823
+ // handles its error is not traced, so the error says nothing yet of
824
+ // how the operation ended: `endTrace` decides what it counts for.
825
+ snapshot.outgoingErrorStatusCode = this.toErrorStatusCode(error);
826
+ this.failedOutgoingRoots.add(activeTrace);
827
+ }
828
+ else if (isRootSpan) {
513
829
  // Only a root span decides this: an error thrown deeper down may well
514
830
  // have been caught and handled by its caller, in which case the
515
831
  // operation did not fail at all.
516
832
  snapshot.errorStatusCode = this.toErrorStatusCode(error);
517
- // If this is the root span, we can directly set the error on the snapshot
518
- // if it's a non-intrinsic error
833
+ }
834
+ if (isRootSpan) {
835
+ // A root span keeps the error's details: it may become the
836
+ // operation's own.
519
837
  if (typeof error === "object") {
520
838
  activeTrace.error = this.toErrorPayload(error);
521
839
  }
@@ -628,8 +946,40 @@ export class OperationTraceRegistry {
628
946
  }
629
947
  // Merge tags
630
948
  Object.assign(targetSpan.tags, tags);
949
+ const captured = snapshot.capturedErrors ?? 0;
950
+ if (captured >= MAX_CAPTURED_ERRORS_PER_TRACE) {
951
+ // A span that already holds the details of one keeps them.
952
+ targetSpan.error ??= true;
953
+ this.reportCapturedErrorLimit(reportedTraceId);
954
+ return;
955
+ }
956
+ snapshot.capturedErrors = captured + 1;
631
957
  targetSpan.error = this.toErrorPayload(error);
632
958
  }
959
+ /**
960
+ * Once for the process: the operation that gets here does so on every
961
+ * request it is given the same input.
962
+ */
963
+ reportCapturedErrorLimit(reportedTraceId) {
964
+ if (this.hasReportedCapturedErrorLimit) {
965
+ return;
966
+ }
967
+ this.hasReportedCapturedErrorLimit = true;
968
+ this.logger.warn(`Trace "${reportedTraceId}" captured more than ${MAX_CAPTURED_ERRORS_PER_TRACE} errors; the spans of later ones are marked as failed, without the error's details. Later traces past this limit are not reported.`);
969
+ }
970
+ /**
971
+ * Counts a span left unopened by `MAX_SPANS_PER_TRACE`. Warned once for
972
+ * the process: an operation that gets there does so on every request it is
973
+ * given the same input.
974
+ */
975
+ countUnrecordedSpan(snapshot) {
976
+ snapshot.unrecordedSpans = (snapshot.unrecordedSpans ?? 0) + 1;
977
+ if (this.hasReportedSpanLimit) {
978
+ return;
979
+ }
980
+ this.hasReportedSpanLimit = true;
981
+ this.logger.warn(`Trace "${snapshot.traceId}" opened ${MAX_SPANS_PER_TRACE} spans; the calls it makes after that run untraced, and the snapshot counts them under the "${UNRECORDED_SPANS_TAG}" tag. Later traces past this limit are not reported.`);
982
+ }
633
983
  /**
634
984
  * Reports the trace even if it ends with no span recorded under it.
635
985
  *
@@ -693,15 +1043,41 @@ export class OperationTraceRegistry {
693
1043
  }
694
1044
  }
695
1045
  cleanup();
696
- // These five are what distinguish the registry's working copy from the
1046
+ // These are what distinguish the registry's working copy from the
697
1047
  // snapshot the API receives, so removing them is the hand-off.
698
1048
  const bookkeeping = snapshot;
699
1049
  const customOperationId = bookkeeping.customOperationId;
1050
+ const unrecordedSpans = bookkeeping.unrecordedSpans;
1051
+ if (unrecordedSpans !== undefined) {
1052
+ // A copy: the object `startTrace` was given is the transport's `tags`
1053
+ // option, shared by every operation it reports.
1054
+ snapshot.tags = {
1055
+ ...snapshot.tags,
1056
+ [UNRECORDED_SPANS_TAG]: unrecordedSpans,
1057
+ };
1058
+ }
1059
+ delete bookkeeping.unrecordedSpans;
700
1060
  delete bookkeeping.refsCounter;
701
1061
  delete bookkeeping.refsMarkedAsComplete;
702
1062
  delete bookkeeping.errorStatusCode;
1063
+ delete bookkeeping.outgoingErrorStatusCode;
703
1064
  delete bookkeeping.customOperationId;
704
1065
  delete bookkeeping.keptWithoutSpans;
1066
+ delete bookkeeping.capturedErrors;
1067
+ // Before a custom name is applied: a request is named after its URL
1068
+ // when nothing else named it - by the buffer, or below as the name a
1069
+ // custom one replaces - and that URL is then sent without its query
1070
+ // string. Here, at the one point every request snapshot is handed on,
1071
+ // ahead of the buffer and of the OTLP export that reads it too.
1072
+ if ("protocol" in snapshot &&
1073
+ snapshot.operationId == null &&
1074
+ snapshot.attributes?.originalUrl !== undefined) {
1075
+ const originalUrl = withoutQueryString(snapshot.attributes.originalUrl);
1076
+ if (originalUrl !== snapshot.attributes.originalUrl) {
1077
+ // A copy: the transport may share the object it was given.
1078
+ snapshot.attributes = { ...snapshot.attributes, originalUrl };
1079
+ }
1080
+ }
705
1081
  // Before `skipSpans`, which judges the operation by the name it is
706
1082
  // reported under.
707
1083
  if (customOperationId !== undefined && "protocol" in snapshot) {
@@ -831,6 +1207,10 @@ export class OperationTraceRegistry {
831
1207
  if (!activeSpan || !snapshot) {
832
1208
  return spanFunction(new TraceSpanDelegate("", name, {}));
833
1209
  }
1210
+ if (snapshot.refsCounter >= MAX_SPANS_PER_TRACE) {
1211
+ this.countUnrecordedSpan(snapshot);
1212
+ return spanFunction(new TraceSpanDelegate("", name, {}));
1213
+ }
834
1214
  // Book the span in the same ledger auto spans use. Completion goes through
835
1215
  // internalEndTraceStep, which increments refsMarkedAsComplete - without
836
1216
  // the matching increment here, every completed manual span pushed the
@@ -850,7 +1230,9 @@ export class OperationTraceRegistry {
850
1230
  // registered under, so a log line written inside this span carries an id
851
1231
  // that resolves back to this node.
852
1232
  spanId: newNodeId,
853
- name,
1233
+ // Cut as the span opens, so the tree never holds a long name; the
1234
+ // callback's delegate keeps the one it was given.
1235
+ name: fitManualSpanName(name),
854
1236
  origin: "manual",
855
1237
  type: "start",
856
1238
  className: activeSpan.className,
@@ -858,6 +1240,7 @@ export class OperationTraceRegistry {
858
1240
  startTime,
859
1241
  startOffset: this.toStartOffset(snapshot, startTime),
860
1242
  children: [],
1243
+ depth: 1,
861
1244
  };
862
1245
  const refsByCaller = this.callerIdsByTraceId.get(traceId);
863
1246
  this.attachToCaller(snapshot, refsByCaller, callerId, manualSpan);
@@ -872,7 +1255,7 @@ export class OperationTraceRegistry {
872
1255
  throw err;
873
1256
  };
874
1257
  const tags = {};
875
- const delegate = new TraceSpanDelegate(newNodeId, manualSpan.name, tags);
1258
+ const delegate = new TraceSpanDelegate(newNodeId, name, tags);
876
1259
  manualSpan.tags = tags;
877
1260
  const store = this.als.getStore();
878
1261
  return this.als.run(new Map([...(store?.entries() ?? []), [CALLER_METADATA_KEY, newNodeId]]), () => {