@nestjs/observe 0.3.25 → 0.3.27

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 (109) hide show
  1. package/README.md +55 -2
  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 +201 -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 +10 -4
  8. package/dist/cli/agent-notes.js +16 -4
  9. package/dist/cli/link.js +51 -4
  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/package-manager.d.ts +6 -0
  14. package/dist/cli/package-manager.js +60 -3
  15. package/dist/cli/project-files.d.ts +62 -1
  16. package/dist/cli/project-files.js +229 -7
  17. package/dist/cli/project-setup.d.ts +6 -0
  18. package/dist/cli/project-setup.js +14 -1
  19. package/dist/cli/wire-application.js +6 -0
  20. package/dist/custom-metrics/counter.d.ts +13 -2
  21. package/dist/custom-metrics/counter.js +33 -16
  22. package/dist/custom-metrics/finite-value.util.d.ts +14 -0
  23. package/dist/custom-metrics/finite-value.util.js +33 -1
  24. package/dist/custom-metrics/gauge.d.ts +2 -0
  25. package/dist/custom-metrics/gauge.js +41 -17
  26. package/dist/custom-metrics/label-values.util.d.ts +37 -0
  27. package/dist/custom-metrics/label-values.util.js +51 -0
  28. package/dist/custom-metrics/summary.d.ts +23 -0
  29. package/dist/custom-metrics/summary.js +90 -12
  30. package/dist/instrument/create-instance-decorator.instrument.js +504 -116
  31. package/dist/instrument/raw-receiver.d.ts +6 -0
  32. package/dist/instrument/raw-receiver.js +32 -0
  33. package/dist/interfaces/observe-options.interface.d.ts +17 -6
  34. package/dist/objectives/objectives.registry.js +12 -0
  35. package/dist/observe.module.js +119 -3
  36. package/dist/otlp/otlp-encoders.js +22 -5
  37. package/dist/otlp/otlp-span.mapper.d.ts +2 -0
  38. package/dist/otlp/otlp-span.mapper.js +26 -4
  39. package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
  40. package/dist/otlp/otlp-trace-exporter.service.js +295 -43
  41. package/dist/outgoing/http.integration.d.ts +8 -4
  42. package/dist/outgoing/http.integration.js +49 -17
  43. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  44. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  45. package/dist/outgoing/llm/llm-providers.js +72 -22
  46. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  47. package/dist/outgoing/llm/llm-usage.js +72 -25
  48. package/dist/outgoing/mongodb.integration.d.ts +3 -1
  49. package/dist/outgoing/mongodb.integration.js +93 -18
  50. package/dist/outgoing/mssql.integration.js +25 -6
  51. package/dist/outgoing/mysql2.integration.js +17 -1
  52. package/dist/outgoing/outgoing-observe-agent.service.js +20 -4
  53. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  54. package/dist/outgoing/pg.integration.d.ts +3 -2
  55. package/dist/outgoing/pg.integration.js +39 -11
  56. package/dist/outgoing/sql-statement.util.js +139 -21
  57. package/dist/outgoing/undici.integration.d.ts +13 -0
  58. package/dist/outgoing/undici.integration.js +68 -0
  59. package/dist/protocols/bull-observe-agent.service.js +23 -12
  60. package/dist/protocols/deferred-trace-completion.d.ts +17 -3
  61. package/dist/protocols/deferred-trace-completion.js +76 -9
  62. package/dist/protocols/graphql-observe-agent.service.d.ts +97 -6
  63. package/dist/protocols/graphql-observe-agent.service.js +354 -19
  64. package/dist/protocols/graphql-operation-parser.js +111 -26
  65. package/dist/protocols/http-observe-agent.service.d.ts +50 -9
  66. package/dist/protocols/http-observe-agent.service.js +220 -59
  67. package/dist/protocols/job-trace-runner.d.ts +42 -3
  68. package/dist/protocols/job-trace-runner.js +197 -36
  69. package/dist/protocols/queue-observe-agent.service.js +44 -20
  70. package/dist/protocols/rpc-observe-agent.service.d.ts +111 -8
  71. package/dist/protocols/rpc-observe-agent.service.js +332 -56
  72. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  73. package/dist/protocols/ws-observe-agent.service.js +227 -21
  74. package/dist/services/index.d.ts +1 -1
  75. package/dist/services/index.js +1 -1
  76. package/dist/services/logger-patcher.service.js +16 -7
  77. package/dist/services/operation-trace.registry.d.ts +58 -1
  78. package/dist/services/operation-trace.registry.js +576 -63
  79. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  80. package/dist/services/stdout-forwarder.service.js +308 -51
  81. package/dist/services/tracer.service.d.ts +39 -11
  82. package/dist/services/tracer.service.js +145 -36
  83. package/dist/utils/capture-request.util.d.ts +3 -1
  84. package/dist/utils/capture-request.util.js +128 -12
  85. package/dist/utils/context-accessor.util.d.ts +16 -0
  86. package/dist/utils/context-accessor.util.js +28 -0
  87. package/dist/utils/default-trace-id-generator.util.js +5 -7
  88. package/dist/utils/error-stack.util.d.ts +13 -0
  89. package/dist/utils/error-stack.util.js +166 -0
  90. package/dist/utils/fit-to-length.util.js +33 -10
  91. package/dist/utils/log-line.parser.d.ts +22 -0
  92. package/dist/utils/log-line.parser.js +20 -7
  93. package/dist/utils/log-redactor.d.ts +14 -0
  94. package/dist/utils/log-redactor.js +690 -65
  95. package/dist/utils/operation-state.util.d.ts +39 -0
  96. package/dist/utils/operation-state.util.js +50 -0
  97. package/dist/utils/redact-url-query.d.ts +37 -4
  98. package/dist/utils/redact-url-query.js +197 -32
  99. package/dist/utils/sensitive-keys.d.ts +4 -1
  100. package/dist/utils/sensitive-keys.js +48 -10
  101. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  102. package/dist/utils/shared-hook-slot.util.js +103 -0
  103. package/dist/utils/source-context.util.d.ts +14 -0
  104. package/dist/utils/source-context.util.js +142 -43
  105. package/dist/utils/source-map-resolver.util.js +33 -6
  106. package/dist/utils/store-copy.util.d.ts +10 -0
  107. package/dist/utils/store-copy.util.js +43 -0
  108. package/dist/utils/trace-context.util.js +21 -6
  109. package/package.json +2 -2
@@ -3,11 +3,27 @@ import { activeSliceRecorder } from "../profiling/span-slice-recorder.js";
3
3
  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
+ import { readStack } from "../utils/error-stack.util.js";
6
7
  import { fallbackOperationId } from "../utils/fallback-operation-id.util.js";
8
+ import { fitToLength } from "../utils/fit-to-length.util.js";
7
9
  import { LogRedactor } from "../utils/log-redactor.js";
8
10
  import { CALLER_METADATA_KEY } from "../observe.constants.js";
11
+ import { copyStore } from "../utils/store-copy.util.js";
9
12
  import { collapseRepeatedSpans, DEFAULT_SPAN_COLLAPSE, } from "./collapse-repeated-spans.util.js";
10
13
  const SNAPSHOT_COMPLETION_TIMEOUT_MS = 1000;
14
+ /**
15
+ * Deepest a span is nested in the tree that is shipped, root span included.
16
+ *
17
+ * Far past any call chain written by hand, and about a ninth of the depth at
18
+ * which the first walk of a tree - building it for shipping, collapsing it,
19
+ * encoding it, serialising the batch it rides in - runs out of stack. Async
20
+ * recursion is traced level by level (the instance decorator only keeps a
21
+ * synchronous call out of the tree), so a method that awaits and then calls
22
+ * itself once per level of a client's JSON body nested its spans as deep as
23
+ * the body was, and the batch's `JSON.stringify` threw away every other
24
+ * operation of the flush window with it.
25
+ */
26
+ const MAX_SPAN_DEPTH = 256;
11
27
  /**
12
28
  * Tag under which a snapshot records how many spans were left out of its tree
13
29
  * because they had not ended when it was shipped - the spans still open and
@@ -18,6 +34,43 @@ const SNAPSHOT_COMPLETION_TIMEOUT_MS = 1000;
18
34
  * collector release has to come first. Absent on a snapshot shipped whole.
19
35
  */
20
36
  export const UNFINISHED_SPANS_TAG = "observe.unfinishedSpans";
37
+ /**
38
+ * Tag under which a snapshot records how many spans were never opened because
39
+ * it had already opened `MAX_SPANS_PER_TRACE`. A tag for the reason
40
+ * `UNFINISHED_SPANS_TAG` is one. Absent on a snapshot that stayed under it.
41
+ */
42
+ export const UNRECORDED_SPANS_TAG = "observe.unrecordedSpans";
43
+ /**
44
+ * Most spans one operation opens, manual ones included. Past it a traced
45
+ * call runs as it would untraced, and is counted under `UNRECORDED_SPANS_TAG`.
46
+ *
47
+ * Every span is a node, an id and a map entry the registry holds until the
48
+ * operation ends - about 300 bytes - and `spanCollapse` bounds only what is
49
+ * shipped, once it has ended. So a handler that calls a provider once per
50
+ * element of a list it was sent let the sender decide how much the agent
51
+ * held: one 12 MB WebSocket message ran a process out of heap, and an HTTP
52
+ * body within the default limit stalled the event loop for seconds as its
53
+ * spans were collapsed. Ten thousand is far past what a request makes and
54
+ * what the collapsed tree shows, and about 3 MB per open operation.
55
+ */
56
+ const MAX_SPANS_PER_TRACE = 10_000;
57
+ /**
58
+ * Most errors one operation records in full, as many as repeated siblings it
59
+ * takes to collapse a group (`spanCollapse.threshold`) - through
60
+ * `captureError` and on failed root spans alike, from one budget.
61
+ *
62
+ * Building a payload redacts the message and the stack, which repeats the
63
+ * message, so a handler reporting each rejected row of a client's list paid
64
+ * rows x message length on the request thread - seconds for one 100 kB body -
65
+ * and, captured on a span per row, kept every payload until the flush. A
66
+ * failed root span builds one too, and a trace has as many root spans as
67
+ * calls made outside a live caller: from an Observable a handler returned,
68
+ * from the resolvers of a GraphQL document that opens with a fragment. A
69
+ * call per element of the client's list, each failure caught, held hundreds
70
+ * of megabytes for one request. Past the limit a span is still marked as
71
+ * failed and its tags still merge; it only goes without the details.
72
+ */
73
+ const MAX_CAPTURED_ERRORS_PER_TRACE = 20;
21
74
  /**
22
75
  * An error the business logic did not model. `IntrinsicException` is what Nest
23
76
  * itself uses to tell a deliberately raised failure from a leaked one.
@@ -28,6 +81,247 @@ const UNHANDLED_ERROR_STATUS_CODE = 500;
28
81
  * count as handled; the exact code only matters when the exception carries one.
29
82
  */
30
83
  const HANDLED_ERROR_STATUS_CODE = 400;
84
+ /**
85
+ * The most of an error's message, and of its stack, that is recorded.
86
+ *
87
+ * Both are as long as whoever threw made them, and a message that quotes the
88
+ * request - `No product with sku ${sku}` - is as long as a client made it. V8
89
+ * repeats the message at the head of the stack, and a failed operation carries
90
+ * the error on its root span and on itself, so uncut, each such request held
91
+ * its text four times over until the flush - and the flush, which writes the
92
+ * batch to a 16 MB slot, threw the whole batch away over a few of them.
93
+ */
94
+ const MAX_ERROR_MESSAGE_LENGTH = 4 * 1024;
95
+ const MAX_ERROR_STACK_LENGTH = 8 * 1024;
96
+ /**
97
+ * How much of a cut stack's head is kept - the error's name and the start of
98
+ * its message. The rest of the limit goes to its tail, the frames.
99
+ */
100
+ const ERROR_STACK_HEAD_LENGTH = 2 * 1024;
101
+ const ERROR_TEXT_CUT = "... [truncated by observe]";
102
+ /** How much of a cut stack's tail is kept: what its head leaves. */
103
+ const ERROR_STACK_TAIL_LENGTH = MAX_ERROR_STACK_LENGTH - ERROR_STACK_HEAD_LENGTH - ERROR_TEXT_CUT.length;
104
+ /** The first `length` characters, not ending in half a surrogate pair. */
105
+ function headOf(text, length) {
106
+ const last = text.charCodeAt(length - 1);
107
+ return text.slice(0, last >= 0xd800 && last <= 0xdbff ? length - 1 : length);
108
+ }
109
+ /**
110
+ * Its own copy of a cut: a slice keeps the whole of the text it was taken
111
+ * from alive for as long as the slice itself is.
112
+ */
113
+ function copyOf(text) {
114
+ return Buffer.from(text, "utf8").toString("utf8");
115
+ }
116
+ /** An error's message, cut to the most of it that is recorded. */
117
+ function fitErrorMessage(message) {
118
+ if (typeof message !== "string" ||
119
+ message.length <= MAX_ERROR_MESSAGE_LENGTH) {
120
+ return message;
121
+ }
122
+ return copyOf(headOf(message, MAX_ERROR_MESSAGE_LENGTH - ERROR_TEXT_CUT.length) +
123
+ ERROR_TEXT_CUT);
124
+ }
125
+ /**
126
+ * An error's stack, cut to the most of it that is recorded: its head and its
127
+ * tail, since a stack opens with the message and closes with the frames,
128
+ * which a cut message would otherwise push out of it altogether. The tail
129
+ * starts on a line of its own where it can.
130
+ */
131
+ function fitErrorStack(stack) {
132
+ if (typeof stack !== "string" || stack.length <= MAX_ERROR_STACK_LENGTH) {
133
+ return stack;
134
+ }
135
+ return copyOf(headOf(stack, ERROR_STACK_HEAD_LENGTH) +
136
+ ERROR_TEXT_CUT +
137
+ stack.slice(tailStartOf(stack, stack.length - ERROR_STACK_TAIL_LENGTH)));
138
+ }
139
+ /**
140
+ * Where the kept tail of a stack starts, at or after `from`: on a line of its
141
+ * own where it can, and never on the second half of a surrogate pair.
142
+ */
143
+ function tailStartOf(stack, from) {
144
+ const line = stack.indexOf("\n", from);
145
+ if (line !== -1) {
146
+ return line;
147
+ }
148
+ const first = stack.charCodeAt(from);
149
+ return first >= 0xdc00 && first <= 0xdfff ? from + 1 : from;
150
+ }
151
+ /**
152
+ * How much more of an error's text the redactor is shown than is recorded,
153
+ * on each side of a cut made before it redacts.
154
+ *
155
+ * Redacting a whole message and stack cost as much as they were long - a
156
+ * message quoting a 100 kB request field, and the stack that repeats it -
157
+ * for a payload that keeps 4 kB and 8 kB of them. So text this much longer
158
+ * than what is kept is cut first, and redacted cut. A cut through a secret
159
+ * leaves pieces no rule recognises, though, and masking shortens the text in
160
+ * front of the cut - a long `token=AAAA…` becomes `token=[REDACTED]` - which
161
+ * can bring a piece into what is kept. The piece sits on the edge of the cut,
162
+ * so this much of the redacted text along that edge is dropped as well. A
163
+ * secret longer than this that a cut splits can still leave its start
164
+ * behind, as with the log forwarder's `REDACTION_LOOKAHEAD`.
165
+ */
166
+ const ERROR_TEXT_LOOKAHEAD = 4 * 1024;
167
+ /** An error's message, redacted and cut to the most of it that is recorded. */
168
+ function redactErrorMessage(message, redact) {
169
+ const shown = MAX_ERROR_MESSAGE_LENGTH + ERROR_TEXT_LOOKAHEAD;
170
+ if (message.length <= shown) {
171
+ // Cut once redacted, so no rule is handed half of what it matches.
172
+ return fitErrorMessage(redact(message));
173
+ }
174
+ const redacted = redact(headOf(message, shown));
175
+ const kept = Math.min(MAX_ERROR_MESSAGE_LENGTH - ERROR_TEXT_CUT.length, redacted.length - ERROR_TEXT_LOOKAHEAD);
176
+ return copyOf(headOf(redacted, Math.max(0, kept)) + ERROR_TEXT_CUT);
177
+ }
178
+ /**
179
+ * An error's stack, redacted and cut to the most of it that is recorded - as
180
+ * `fitErrorStack` cuts it, from a head and a tail redacted apart when the
181
+ * stack is long enough to cut before redacting.
182
+ */
183
+ function redactErrorStack(stack, redact) {
184
+ if (stack === undefined) {
185
+ return undefined;
186
+ }
187
+ if (stack.length <= MAX_ERROR_STACK_LENGTH + 2 * ERROR_TEXT_LOOKAHEAD) {
188
+ return fitErrorStack(redact(stack));
189
+ }
190
+ const head = redact(headOf(stack, ERROR_STACK_HEAD_LENGTH + ERROR_TEXT_LOOKAHEAD));
191
+ let tailFrom = stack.length - ERROR_STACK_TAIL_LENGTH - ERROR_TEXT_LOOKAHEAD;
192
+ const first = stack.charCodeAt(tailFrom);
193
+ if (first >= 0xdc00 && first <= 0xdfff) {
194
+ tailFrom += 1;
195
+ }
196
+ const tail = redact(stack.slice(tailFrom));
197
+ const keptHead = Math.min(ERROR_STACK_HEAD_LENGTH, head.length - ERROR_TEXT_LOOKAHEAD);
198
+ const keptTail = tailStartOf(tail, Math.max(ERROR_TEXT_LOOKAHEAD, tail.length - ERROR_STACK_TAIL_LENGTH));
199
+ return copyOf(headOf(head, Math.max(0, keptHead)) + ERROR_TEXT_CUT + tail.slice(keptTail));
200
+ }
201
+ /**
202
+ * Longest span name the collector takes - the encoder's own limit, which it
203
+ * cuts every name to on the way out.
204
+ */
205
+ const MAX_SPAN_NAME_LENGTH = 255;
206
+ /**
207
+ * Longest manual span name that is read to be cut. A name is as long as the
208
+ * code that opened the span made it, often from a string of a client's, and
209
+ * a name built by concatenation is written out whole the first time any of
210
+ * it is read - so a span per row of a client's list, each named after a long
211
+ * string, cost rows x length on the request thread, however little of each
212
+ * name was kept. A longer one is recorded by its length alone.
213
+ */
214
+ const MAX_READ_SPAN_NAME_LENGTH = 4 * 1024;
215
+ /** A manual span's name, as its node holds it until the trace ships. */
216
+ function fitManualSpanName(name) {
217
+ // Typed, but passed from code nothing checks at run time; left as it is.
218
+ if (typeof name !== "string" || name.length <= MAX_SPAN_NAME_LENGTH) {
219
+ return name;
220
+ }
221
+ if (name.length > MAX_READ_SPAN_NAME_LENGTH) {
222
+ return `[span name of ${name.length} characters]`;
223
+ }
224
+ return fitToLength(name, MAX_SPAN_NAME_LENGTH);
225
+ }
226
+ /**
227
+ * A thrown value, or an error's message, as text - whatever it is.
228
+ *
229
+ * Neither is what its type says for certain. A microservice client rejects
230
+ * with the JSON object the remote service sent as its error, and a driver
231
+ * copies a server reply's fields onto the error it throws; `String()` throws
232
+ * on `{"toString": 1}`, and that was thrown back at the code recording the
233
+ * failure - a handler that reported it and answered with a fallback
234
+ * answered 500 instead.
235
+ */
236
+ function toErrorText(value) {
237
+ if (typeof value === "string") {
238
+ return value;
239
+ }
240
+ try {
241
+ // oxlint-disable-next-line typescript/no-base-to-string -- recorded as `String()` always recorded it
242
+ return String(value);
243
+ }
244
+ catch {
245
+ try {
246
+ return Object.prototype.toString.call(value);
247
+ }
248
+ catch {
249
+ return "[unprintable value]";
250
+ }
251
+ }
252
+ }
253
+ /**
254
+ * An error's stack, when it has one that is text - read without fixing the
255
+ * message in it, for an exception filter still to run (`readStack`).
256
+ */
257
+ function stackOf(error) {
258
+ try {
259
+ const stack = readStack(error);
260
+ return typeof stack === "string" ? stack : undefined;
261
+ }
262
+ catch {
263
+ return undefined;
264
+ }
265
+ }
266
+ /**
267
+ * An error's `name` and `code`, when they can be read and are text - what,
268
+ * with its message, opens its stack (see `collectCodeFrames`). A driver
269
+ * error copies a server reply's fields onto itself, so either may be
270
+ * anything, or a getter that throws.
271
+ */
272
+ function stackHeaderOf(error) {
273
+ const header = {};
274
+ try {
275
+ const { name, code } = error;
276
+ if (typeof name === "string") {
277
+ header.name = name;
278
+ }
279
+ if (typeof code === "string") {
280
+ header.code = code;
281
+ }
282
+ }
283
+ catch {
284
+ // Read as far as it could be; the stack is then unlikely to match.
285
+ }
286
+ return header;
287
+ }
288
+ /** The name of a thrown value's class, when it can be read. */
289
+ function classNameOf(error) {
290
+ try {
291
+ const constructor = error
292
+ ?.constructor;
293
+ if (typeof constructor !== "function") {
294
+ return undefined;
295
+ }
296
+ const name = constructor.name;
297
+ return typeof name === "string" ? name : undefined;
298
+ }
299
+ catch {
300
+ return undefined;
301
+ }
302
+ }
303
+ /** An absolute-form request target: `http://api.example.com/graphql?query=`. */
304
+ const ABSOLUTE_URL = /^[a-z][a-z\d+.-]*:\/\//i;
305
+ /**
306
+ * The URL of a request that nothing named - no route, no GraphQL resolver -
307
+ * without its query string.
308
+ *
309
+ * Its query string is masked by parameter name only, and nothing says what
310
+ * it holds: over GET, a GraphQL endpoint's is the operation itself, string
311
+ * literals and `variables` included, which the GraphQL agent's request hook
312
+ * blanks - and the hook did not run for a request that is still unnamed: a
313
+ * middleware refused it, it is a persisted query sent by its hash, or the
314
+ * endpoint is one the hook is not registered for. Anything that is not a
315
+ * request target - a GraphQL document - is left as it is.
316
+ */
317
+ function withoutQueryString(originalUrl) {
318
+ if (typeof originalUrl !== "string" ||
319
+ !(originalUrl.startsWith("/") || ABSOLUTE_URL.test(originalUrl))) {
320
+ return originalUrl;
321
+ }
322
+ const queryAt = originalUrl.indexOf("?");
323
+ return queryAt === -1 ? originalUrl : originalUrl.slice(0, queryAt);
324
+ }
31
325
  /** A node and everything below it. */
32
326
  function countNodes(node) {
33
327
  let count = 1;
@@ -100,6 +394,24 @@ export class OperationTraceRegistry {
100
394
  * would bury everything else in the log. Full text once, one line after.
101
395
  */
102
396
  hasReportedMissingInstrumentation = false;
397
+ /** See `reportSpanDepthLimit`. */
398
+ hasReportedSpanDepthLimit = false;
399
+ /** See `reportCapturedErrorLimit`. */
400
+ hasReportedCapturedErrorLimit = false;
401
+ /** See `countUnrecordedSpan`. */
402
+ hasReportedSpanLimit = false;
403
+ /**
404
+ * Root spans of outgoing calls - a query, an HTTP call - that ended with
405
+ * an error. See `endTrace` for what they decide.
406
+ */
407
+ failedOutgoingRoots = new WeakSet();
408
+ /**
409
+ * The status code each root span that threw stands for. An operation with
410
+ * several - the operations of a batched GraphQL request, side by side - is
411
+ * reported with the error of the first, and so with its status: the one
412
+ * the last to end set left a 500's error filed as a 401.
413
+ */
414
+ rootErrorStatusCodes = new WeakMap();
103
415
  /**
104
416
  * Applied to every tree as it is plucked. Defaults are live from
105
417
  * construction rather than waiting for `configureSpanCollapse`, so a
@@ -178,40 +490,38 @@ export class OperationTraceRegistry {
178
490
  */
179
491
  toErrorPayload(error) {
180
492
  const raw = error instanceof Error
181
- ? { message: error.message, stack: error.stack }
182
- : { message: String(error), stack: undefined };
493
+ ? { message: toErrorText(error.message), stack: stackOf(error) }
494
+ : { message: toErrorText(error), stack: undefined };
183
495
  // Redacted here, at the one point every error payload passes through.
184
- const payload = this.redactor
185
- ? {
186
- message: this.redactor.redactMessage(raw.message),
187
- stack: raw.stack === undefined
188
- ? undefined
189
- : this.redactor.redactMessage(raw.stack),
190
- }
191
- : raw;
496
+ const redactor = this.redactor;
497
+ const redact = redactor
498
+ ? (text) => redactor.redactMessage(text)
499
+ : (text) => text;
500
+ const payload = {
501
+ message: redactErrorMessage(raw.message, redact),
502
+ stack: redactErrorStack(raw.stack, redact),
503
+ };
192
504
  const result = payload;
193
- if (typeof error?.constructor === "function") {
194
- result.cls = error.constructor.name;
505
+ const cls = classNameOf(error);
506
+ if (cls !== undefined) {
507
+ result.cls = cls;
195
508
  }
196
509
  if (this.sourceContext !== false) {
197
510
  const settings = this.sourceContext === true ? {} : this.sourceContext;
198
- // Read off the raw stack with the raw message: the message is what marks
199
- // where the frames start, and it only matches the stack it came from.
200
- // Nothing of either is shipped from here - just the file positions.
511
+ // Read off the raw stack with the raw message, and the error's name and
512
+ // code: together they are the header that marks where the frames
513
+ // start, and it only matches the stack it was written into. Nothing of
514
+ // them is shipped from here - just the file positions. Source is as
515
+ // likely to hold a literal secret as a message is, and goes to the
516
+ // same place.
201
517
  const codeFrames = collectCodeFrames(raw.stack, {
202
518
  ...settings,
203
519
  message: raw.message,
520
+ ...stackHeaderOf(error),
521
+ redactor: this.redactor ?? undefined,
204
522
  });
205
523
  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;
524
+ result.codeFrames = codeFrames;
215
525
  }
216
526
  }
217
527
  return result;
@@ -234,6 +544,15 @@ export class OperationTraceRegistry {
234
544
  return (snapshot !== undefined &&
235
545
  snapshot.refsCounter > snapshot.refsMarkedAsComplete);
236
546
  }
547
+ /**
548
+ * Whether the trace's operation has been named yet - by the route the
549
+ * request was routed to, or by a GraphQL operation that labelled it. False
550
+ * for a trace that is not open.
551
+ */
552
+ hasOperationId(traceId) {
553
+ const snapshot = this.traceSnapshots.get(traceId);
554
+ return snapshot?.operationId != null;
555
+ }
237
556
  startTrace(traceId, data,
238
557
  /**
239
558
  * The trace id the snapshot reports under, when it is not the registry
@@ -279,15 +598,21 @@ export class OperationTraceRegistry {
279
598
  // recorded a span for it. Both at once has one cause: the instance
280
599
  // decorator never wrapped the providers, because `instrument` never
281
600
  // reached NestFactory.
601
+ //
602
+ // Dropped before the line is written, not after: a logger taken from
603
+ // the container is wrapped like any provider and writes inside this
604
+ // operation's async store, so with the trace still registered every
605
+ // call it makes on itself opened a span here - in a span map nothing
606
+ // would ever free again.
607
+ this.abandonTrace(traceId);
282
608
  this.reportMissingInstrumentation(snapshot);
283
- this.traceSnapshots.delete(traceId);
284
609
  return;
285
610
  }
286
611
  // Ignore snapshots that have no traces as that means
287
612
  // the request didnt even have a handler in the first place - unless
288
613
  // the transport said the operation is complete without one.
289
614
  if (!snapshot.keptWithoutSpans) {
290
- this.traceSnapshots.delete(traceId);
615
+ this.abandonTrace(traceId);
291
616
  return;
292
617
  }
293
618
  }
@@ -299,7 +624,21 @@ export class OperationTraceRegistry {
299
624
  const reportedStatusCode = "statusCode" in opts && typeof opts.statusCode === "number"
300
625
  ? opts.statusCode
301
626
  : undefined;
302
- const errorStatusCode = "protocol" in snapshot ? snapshot.errorStatusCode : undefined;
627
+ // An outgoing call's error at the root (see `internalEndTraceStep`) may
628
+ // have been caught and answered: a duplicate key turned into a 409, a
629
+ // failed lookup into a 200 with a fallback. A transport that reports a
630
+ // status code says how the operation ended, so there it does not stand in
631
+ // for one; on one that reports none, it is all there is to go on. Of
632
+ // several root spans that threw, the first gives the operation its error
633
+ // below, and its status here.
634
+ const firstFailure = snapshot.traces.find((trace) => this.rootErrorStatusCodes.has(trace));
635
+ const errorStatusCode = "protocol" in snapshot
636
+ ? (firstFailure && this.rootErrorStatusCodes.get(firstFailure)) ??
637
+ snapshot.errorStatusCode ??
638
+ (reportedStatusCode === undefined
639
+ ? snapshot.outgoingErrorStatusCode
640
+ : undefined)
641
+ : undefined;
303
642
  // A root span that threw outranks a success status code reported by the
304
643
  // transport. Two cases need this. Transports that carry no status code of
305
644
  // their own (RPC, gRPC) end their trace without one at all, and the backend
@@ -321,21 +660,60 @@ export class OperationTraceRegistry {
321
660
  jobSnapshot.status = opts.status;
322
661
  }
323
662
  if ("userId" in opts && typeof opts.userId !== "undefined") {
324
- const requestSnapshot = snapshot;
325
- requestSnapshot.userId = String(opts.userId);
663
+ // Typed as a string, but a transport passes on what `getUserId`
664
+ // returned, and `String()` throws on `{"toString": 1}`. Thrown here,
665
+ // between ending the trace and plucking it, it left the trace
666
+ // registered for good; the trace goes without a user id instead.
667
+ let userId;
668
+ try {
669
+ // oxlint-disable-next-line typescript/no-unnecessary-type-conversion -- typed a string, but whatever `getUserId` returned
670
+ userId = String(opts.userId);
671
+ }
672
+ catch {
673
+ userId = undefined;
674
+ }
675
+ if (userId !== undefined) {
676
+ snapshot.userId = userId;
677
+ }
326
678
  }
327
679
  delete snapshot.startTimestamp; // Clean up to avoid confusion
328
680
  if (snapshot.traces && snapshot.traces.length > 0) {
329
- // Iterate through root traces to check if any have errors
681
+ // The first root span that failed gives the operation its error. An
682
+ // outgoing call's counts only where nothing else did and the operation
683
+ // failed by its status - or reported none: otherwise its error was
684
+ // caught and answered, and recording it as the operation's put the
685
+ // driver's message, bound values and all, in place of what the
686
+ // application returned.
687
+ //
688
+ // The first whose details were kept: past `MAX_CAPTURED_ERRORS_PER_TRACE`
689
+ // a root span is marked as failed without them, and root spans are
690
+ // listed in the order they started, not the order they failed. One that
691
+ // failed without them still says the operation did, so an outgoing
692
+ // call's error is not taken in its place.
693
+ let outgoing;
694
+ let found = false;
330
695
  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
696
+ if (!("error" in trace) || !trace.error) {
697
+ continue;
698
+ }
699
+ if (this.failedOutgoingRoots.has(trace)) {
333
700
  if (typeof trace.error === "object") {
334
- snapshot.error = trace.error;
701
+ outgoing ??= trace;
335
702
  }
336
- break; // No need to check further once an error is found
703
+ continue;
704
+ }
705
+ found = true;
706
+ if (typeof trace.error === "object") {
707
+ snapshot.error = trace.error;
708
+ break;
337
709
  }
338
710
  }
711
+ if (!found &&
712
+ typeof outgoing?.error === "object" &&
713
+ (reportedStatusCode === undefined ||
714
+ (typeof statusCode === "number" && statusCode >= 500))) {
715
+ snapshot.error = outgoing.error;
716
+ }
339
717
  }
340
718
  }
341
719
  /**
@@ -407,6 +785,12 @@ export class OperationTraceRegistry {
407
785
  if (!snapshot) {
408
786
  return undefined;
409
787
  }
788
+ // No step, as for an operation that is not recorded: every caller then
789
+ // runs the call untraced and closes nothing.
790
+ if (snapshot.refsCounter >= MAX_SPANS_PER_TRACE) {
791
+ this.countUnrecordedSpan(snapshot);
792
+ return undefined;
793
+ }
410
794
  snapshot.refsCounter += 1;
411
795
  const newNodeId = spanId ?? uuidv7();
412
796
  const startTime = performance.now();
@@ -429,6 +813,9 @@ export class OperationTraceRegistry {
429
813
  // store (CALLER_METADATA_KEY), so the two sides agree by construction
430
814
  // instead of by a timing heuristic. It costs a uuid per span on the wire.
431
815
  spanId: newNodeId,
816
+ // Set where the node is attached; in the literal so every node has the
817
+ // same shape from the start.
818
+ depth: 1,
432
819
  };
433
820
  let refsByCaller = this.callerIdsByTraceId.get(traceId);
434
821
  this.attachToCaller(snapshot, refsByCaller, callerId, newNode);
@@ -452,18 +839,45 @@ export class OperationTraceRegistry {
452
839
  * ending after its caller did, is already tolerated in
453
840
  * `internalEndTraceStep`. Auto and manual spans both attach through here, so
454
841
  * they share the tolerance.
842
+ *
843
+ * A node past `MAX_SPAN_DEPTH` is kept out of its caller's children, and so
844
+ * out of the shipped tree, and everything opened under it goes the same
845
+ * way. Nothing else about it changes: it still has its parent, so an error
846
+ * it ends with is not taken for the operation's own, and it is still
847
+ * registered and counted, so the calls under it find their caller and the
848
+ * trace completes when it would have.
455
849
  */
456
850
  attachToCaller(snapshot, refsByCaller, callerId, newNode) {
457
- const caller = callerId ? refsByCaller?.get(callerId) : undefined;
851
+ // Every node in the map was opened by this registry, with its depth.
852
+ const caller = (callerId ? refsByCaller?.get(callerId) : undefined);
458
853
  if (caller?.type === "start") {
459
- caller.children.push(newNode);
460
854
  newNode.parent = caller;
855
+ newNode.depth = caller.depth + 1;
856
+ if (newNode.depth <= MAX_SPAN_DEPTH) {
857
+ caller.children.push(newNode);
858
+ }
859
+ else {
860
+ this.reportSpanDepthLimit(snapshot, newNode);
861
+ }
461
862
  }
462
863
  else {
463
864
  // No (live) caller means insert trace at the root level
464
865
  snapshot.traces.push(newNode);
465
866
  }
466
867
  }
868
+ /**
869
+ * Once for the process: a chain that deep comes from one recursive method,
870
+ * which recurses that deep on every request it is given the same input.
871
+ * Flagged before the line is written, which an instrumented logger records
872
+ * as one more span of the same chain.
873
+ */
874
+ reportSpanDepthLimit(snapshot, node) {
875
+ if (this.hasReportedSpanDepthLimit) {
876
+ return;
877
+ }
878
+ this.hasReportedSpanDepthLimit = true;
879
+ 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.`);
880
+ }
467
881
  internalEndTraceStep(traceId,
468
882
  /**
469
883
  * Diagnostic label only - it names the span in the two warnings below and
@@ -474,7 +888,9 @@ export class OperationTraceRegistry {
474
888
  // Undefined when `internalStartTraceStep` found no snapshot to open the
475
889
  // step against; the lookup below then misses and warns, as it does for any
476
890
  // other unknown caller.
477
- callerId, error) {
891
+ callerId, error,
892
+ /** The span is an outgoing call's, opened by `OutgoingSpanRecorder`. */
893
+ outgoing = false) {
478
894
  const snapshot = this.traceSnapshots.get(traceId);
479
895
  if (!snapshot) {
480
896
  // The trace was handed off while this span was still open -
@@ -509,18 +925,38 @@ export class OperationTraceRegistry {
509
925
  activeTrace.duration = duration;
510
926
  if (error && !activeTrace.error) {
511
927
  const isRootSpan = !parent;
512
- if (isRootSpan) {
928
+ if (isRootSpan && outgoing) {
929
+ // An outgoing call at the root ran outside every traced call of the
930
+ // operation - most often a query in a cold Observable, run when Nest
931
+ // subscribed, after the provider that built it had returned. Whoever
932
+ // handles its error is not traced, so the error says nothing yet of
933
+ // how the operation ended: `endTrace` decides what it counts for.
934
+ snapshot.outgoingErrorStatusCode = this.toErrorStatusCode(error);
935
+ this.failedOutgoingRoots.add(activeTrace);
936
+ }
937
+ else if (isRootSpan) {
513
938
  // Only a root span decides this: an error thrown deeper down may well
514
939
  // have been caught and handled by its caller, in which case the
515
940
  // operation did not fail at all.
516
941
  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
519
- if (typeof error === "object") {
520
- activeTrace.error = this.toErrorPayload(error);
942
+ this.rootErrorStatusCodes.set(activeTrace, snapshot.errorStatusCode);
943
+ }
944
+ if (isRootSpan) {
945
+ // A root span keeps the error's details: it may become the
946
+ // operation's own. Out of the budget `captureError` draws on, since
947
+ // a trace can have a root span per call - see
948
+ // `MAX_CAPTURED_ERRORS_PER_TRACE`.
949
+ const captured = snapshot.capturedErrors ?? 0;
950
+ if (typeof error !== "object") {
951
+ activeTrace.error = true;
521
952
  }
522
- else {
953
+ else if (captured >= MAX_CAPTURED_ERRORS_PER_TRACE) {
523
954
  activeTrace.error = true;
955
+ this.reportCapturedErrorLimit(snapshot.traceId);
956
+ }
957
+ else {
958
+ snapshot.capturedErrors = captured + 1;
959
+ activeTrace.error = this.toErrorPayload(error);
524
960
  }
525
961
  }
526
962
  else {
@@ -628,8 +1064,40 @@ export class OperationTraceRegistry {
628
1064
  }
629
1065
  // Merge tags
630
1066
  Object.assign(targetSpan.tags, tags);
1067
+ const captured = snapshot.capturedErrors ?? 0;
1068
+ if (captured >= MAX_CAPTURED_ERRORS_PER_TRACE) {
1069
+ // A span that already holds the details of one keeps them.
1070
+ targetSpan.error ??= true;
1071
+ this.reportCapturedErrorLimit(reportedTraceId);
1072
+ return;
1073
+ }
1074
+ snapshot.capturedErrors = captured + 1;
631
1075
  targetSpan.error = this.toErrorPayload(error);
632
1076
  }
1077
+ /**
1078
+ * Once for the process: the operation that gets here does so on every
1079
+ * request it is given the same input.
1080
+ */
1081
+ reportCapturedErrorLimit(reportedTraceId) {
1082
+ if (this.hasReportedCapturedErrorLimit) {
1083
+ return;
1084
+ }
1085
+ this.hasReportedCapturedErrorLimit = true;
1086
+ this.logger.warn(`Trace "${reportedTraceId}" recorded 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.`);
1087
+ }
1088
+ /**
1089
+ * Counts a span left unopened by `MAX_SPANS_PER_TRACE`. Warned once for
1090
+ * the process: an operation that gets there does so on every request it is
1091
+ * given the same input.
1092
+ */
1093
+ countUnrecordedSpan(snapshot) {
1094
+ snapshot.unrecordedSpans = (snapshot.unrecordedSpans ?? 0) + 1;
1095
+ if (this.hasReportedSpanLimit) {
1096
+ return;
1097
+ }
1098
+ this.hasReportedSpanLimit = true;
1099
+ 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.`);
1100
+ }
633
1101
  /**
634
1102
  * Reports the trace even if it ends with no span recorded under it.
635
1103
  *
@@ -674,34 +1142,68 @@ export class OperationTraceRegistry {
674
1142
  this.callerIdsByTraceId.delete(traceId);
675
1143
  this.traceSnapshots.delete(traceId);
676
1144
  };
677
- // Ensure snapshot is complete by checking refsCounter vs refsMarkedAsComplete
678
- if (snapshot.refsCounter > snapshot.refsMarkedAsComplete) {
679
- this.awaitingCompletion += 1;
680
- try {
681
- await new Promise((resolve) => setTimeout(resolve, SNAPSHOT_COMPLETION_TIMEOUT_MS));
682
- }
683
- finally {
684
- this.awaitingCompletion -= 1;
685
- }
1145
+ // Cleaned up whatever happens on the way: a trace left registered once
1146
+ // its operation has ended is never plucked again, and holds its spans
1147
+ // and error payloads for the life of the process - a logger that
1148
+ // throws on the warning below was enough.
1149
+ try {
1150
+ // Ensure snapshot is complete by checking refsCounter vs refsMarkedAsComplete
686
1151
  if (snapshot.refsCounter > snapshot.refsMarkedAsComplete) {
687
- // Shipped without the spans still open rather than not at all: the
688
- // operation itself finished, and dropping it lost its status and
689
- // error along with every span that did end. Read before cleanup,
690
- // which takes the span map the warning names them from.
691
- this.reportUnfinishedSpans(traceId, snapshot);
692
- this.leaveOutUnfinishedSpans(snapshot);
1152
+ this.awaitingCompletion += 1;
1153
+ try {
1154
+ await new Promise((resolve) => setTimeout(resolve, SNAPSHOT_COMPLETION_TIMEOUT_MS));
1155
+ }
1156
+ finally {
1157
+ this.awaitingCompletion -= 1;
1158
+ }
1159
+ if (snapshot.refsCounter > snapshot.refsMarkedAsComplete) {
1160
+ // Shipped without the spans still open rather than not at all:
1161
+ // the operation itself finished, and dropping it lost its status
1162
+ // and error along with every span that did end. Read before
1163
+ // cleanup, which takes the span map the warning names them from.
1164
+ this.reportUnfinishedSpans(traceId, snapshot);
1165
+ this.leaveOutUnfinishedSpans(snapshot);
1166
+ }
693
1167
  }
694
1168
  }
695
- cleanup();
696
- // These five are what distinguish the registry's working copy from the
1169
+ finally {
1170
+ cleanup();
1171
+ }
1172
+ // These are what distinguish the registry's working copy from the
697
1173
  // snapshot the API receives, so removing them is the hand-off.
698
1174
  const bookkeeping = snapshot;
699
1175
  const customOperationId = bookkeeping.customOperationId;
1176
+ const unrecordedSpans = bookkeeping.unrecordedSpans;
1177
+ if (unrecordedSpans !== undefined) {
1178
+ // A copy: the object `startTrace` was given is the transport's `tags`
1179
+ // option, shared by every operation it reports.
1180
+ snapshot.tags = {
1181
+ ...snapshot.tags,
1182
+ [UNRECORDED_SPANS_TAG]: unrecordedSpans,
1183
+ };
1184
+ }
1185
+ delete bookkeeping.unrecordedSpans;
700
1186
  delete bookkeeping.refsCounter;
701
1187
  delete bookkeeping.refsMarkedAsComplete;
702
1188
  delete bookkeeping.errorStatusCode;
1189
+ delete bookkeeping.outgoingErrorStatusCode;
703
1190
  delete bookkeeping.customOperationId;
704
1191
  delete bookkeeping.keptWithoutSpans;
1192
+ delete bookkeeping.capturedErrors;
1193
+ // Before a custom name is applied: a request is named after its URL
1194
+ // when nothing else named it - by the buffer, or below as the name a
1195
+ // custom one replaces - and that URL is then sent without its query
1196
+ // string. Here, at the one point every request snapshot is handed on,
1197
+ // ahead of the buffer and of the OTLP export that reads it too.
1198
+ if ("protocol" in snapshot &&
1199
+ snapshot.operationId == null &&
1200
+ snapshot.attributes?.originalUrl !== undefined) {
1201
+ const originalUrl = withoutQueryString(snapshot.attributes.originalUrl);
1202
+ if (originalUrl !== snapshot.attributes.originalUrl) {
1203
+ // A copy: the transport may share the object it was given.
1204
+ snapshot.attributes = { ...snapshot.attributes, originalUrl };
1205
+ }
1206
+ }
705
1207
  // Before `skipSpans`, which judges the operation by the name it is
706
1208
  // reported under.
707
1209
  if (customOperationId !== undefined && "protocol" in snapshot) {
@@ -831,6 +1333,10 @@ export class OperationTraceRegistry {
831
1333
  if (!activeSpan || !snapshot) {
832
1334
  return spanFunction(new TraceSpanDelegate("", name, {}));
833
1335
  }
1336
+ if (snapshot.refsCounter >= MAX_SPANS_PER_TRACE) {
1337
+ this.countUnrecordedSpan(snapshot);
1338
+ return spanFunction(new TraceSpanDelegate("", name, {}));
1339
+ }
834
1340
  // Book the span in the same ledger auto spans use. Completion goes through
835
1341
  // internalEndTraceStep, which increments refsMarkedAsComplete - without
836
1342
  // the matching increment here, every completed manual span pushed the
@@ -850,7 +1356,9 @@ export class OperationTraceRegistry {
850
1356
  // registered under, so a log line written inside this span carries an id
851
1357
  // that resolves back to this node.
852
1358
  spanId: newNodeId,
853
- name,
1359
+ // Cut as the span opens, so the tree never holds a long name; the
1360
+ // callback's delegate keeps the one it was given.
1361
+ name: fitManualSpanName(name),
854
1362
  origin: "manual",
855
1363
  type: "start",
856
1364
  className: activeSpan.className,
@@ -858,6 +1366,7 @@ export class OperationTraceRegistry {
858
1366
  startTime,
859
1367
  startOffset: this.toStartOffset(snapshot, startTime),
860
1368
  children: [],
1369
+ depth: 1,
861
1370
  };
862
1371
  const refsByCaller = this.callerIdsByTraceId.get(traceId);
863
1372
  this.attachToCaller(snapshot, refsByCaller, callerId, manualSpan);
@@ -872,10 +1381,14 @@ export class OperationTraceRegistry {
872
1381
  throw err;
873
1382
  };
874
1383
  const tags = {};
875
- const delegate = new TraceSpanDelegate(newNodeId, manualSpan.name, tags);
1384
+ const delegate = new TraceSpanDelegate(newNodeId, name, tags);
876
1385
  manualSpan.tags = tags;
877
1386
  const store = this.als.getStore();
878
- return this.als.run(new Map([...(store?.entries() ?? []), [CALLER_METADATA_KEY, newNodeId]]), () => {
1387
+ // Copied as for an auto span, so an attribute set in the callback is
1388
+ // still there once the span has ended.
1389
+ return this.als.run(store
1390
+ ? copyStore(store, [CALLER_METADATA_KEY, newNodeId])
1391
+ : new Map([[CALLER_METADATA_KEY, newNodeId]]), () => {
879
1392
  try {
880
1393
  const result = spanFunction(delegate);
881
1394
  if (result instanceof Promise) {