@nestjs/observe 0.3.26 → 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 (59) hide show
  1. package/README.md +38 -2
  2. package/dist/agent/observe-agent.shared-buffer.js +5 -0
  3. package/dist/agent/telemetry-wire-contract.js +3 -3
  4. package/dist/cli/link.js +24 -2
  5. package/dist/cli/package-manager.d.ts +6 -0
  6. package/dist/cli/package-manager.js +60 -3
  7. package/dist/cli/project-files.d.ts +25 -5
  8. package/dist/cli/project-files.js +98 -15
  9. package/dist/custom-metrics/summary.js +17 -10
  10. package/dist/instrument/create-instance-decorator.instrument.js +364 -38
  11. package/dist/instrument/raw-receiver.d.ts +6 -0
  12. package/dist/instrument/raw-receiver.js +32 -0
  13. package/dist/interfaces/observe-options.interface.d.ts +14 -5
  14. package/dist/otlp/otlp-span.mapper.d.ts +2 -0
  15. package/dist/otlp/otlp-span.mapper.js +19 -1
  16. package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
  17. package/dist/otlp/otlp-trace-exporter.service.js +232 -38
  18. package/dist/outgoing/http.integration.js +36 -11
  19. package/dist/outgoing/mongodb.integration.d.ts +3 -1
  20. package/dist/outgoing/mongodb.integration.js +93 -18
  21. package/dist/outgoing/mssql.integration.js +9 -4
  22. package/dist/outgoing/outgoing-observe-agent.service.js +5 -1
  23. package/dist/outgoing/sql-statement.util.js +36 -10
  24. package/dist/protocols/bull-observe-agent.service.js +21 -0
  25. package/dist/protocols/deferred-trace-completion.d.ts +8 -2
  26. package/dist/protocols/deferred-trace-completion.js +40 -3
  27. package/dist/protocols/graphql-observe-agent.service.d.ts +62 -2
  28. package/dist/protocols/graphql-observe-agent.service.js +188 -14
  29. package/dist/protocols/graphql-operation-parser.js +45 -14
  30. package/dist/protocols/http-observe-agent.service.d.ts +14 -7
  31. package/dist/protocols/http-observe-agent.service.js +57 -14
  32. package/dist/protocols/job-trace-runner.d.ts +7 -0
  33. package/dist/protocols/job-trace-runner.js +72 -8
  34. package/dist/protocols/rpc-observe-agent.service.d.ts +61 -0
  35. package/dist/protocols/rpc-observe-agent.service.js +146 -10
  36. package/dist/protocols/ws-observe-agent.service.js +1 -1
  37. package/dist/services/logger-patcher.service.js +13 -3
  38. package/dist/services/operation-trace.registry.d.ts +13 -0
  39. package/dist/services/operation-trace.registry.js +195 -65
  40. package/dist/services/stdout-forwarder.service.js +22 -2
  41. package/dist/services/tracer.service.d.ts +19 -14
  42. package/dist/services/tracer.service.js +57 -34
  43. package/dist/utils/capture-request.util.js +36 -8
  44. package/dist/utils/context-accessor.util.d.ts +16 -0
  45. package/dist/utils/context-accessor.util.js +28 -0
  46. package/dist/utils/default-trace-id-generator.util.js +5 -7
  47. package/dist/utils/error-stack.util.d.ts +13 -0
  48. package/dist/utils/error-stack.util.js +166 -0
  49. package/dist/utils/log-line.parser.d.ts +8 -0
  50. package/dist/utils/log-line.parser.js +13 -4
  51. package/dist/utils/log-redactor.js +184 -10
  52. package/dist/utils/redact-url-query.d.ts +16 -5
  53. package/dist/utils/redact-url-query.js +20 -7
  54. package/dist/utils/source-context.util.d.ts +6 -0
  55. package/dist/utils/source-context.util.js +68 -33
  56. package/dist/utils/source-map-resolver.util.js +25 -4
  57. package/dist/utils/store-copy.util.d.ts +10 -0
  58. package/dist/utils/store-copy.util.js +43 -0
  59. package/package.json +1 -1
@@ -3,10 +3,12 @@ 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";
7
8
  import { fitToLength } from "../utils/fit-to-length.util.js";
8
9
  import { LogRedactor } from "../utils/log-redactor.js";
9
10
  import { CALLER_METADATA_KEY } from "../observe.constants.js";
11
+ import { copyStore } from "../utils/store-copy.util.js";
10
12
  import { collapseRepeatedSpans, DEFAULT_SPAN_COLLAPSE, } from "./collapse-repeated-spans.util.js";
11
13
  const SNAPSHOT_COMPLETION_TIMEOUT_MS = 1000;
12
14
  /**
@@ -53,15 +55,20 @@ export const UNRECORDED_SPANS_TAG = "observe.unrecordedSpans";
53
55
  */
54
56
  const MAX_SPANS_PER_TRACE = 10_000;
55
57
  /**
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
+ * 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.
58
61
  *
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.
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.
65
72
  */
66
73
  const MAX_CAPTURED_ERRORS_PER_TRACE = 20;
67
74
  /**
@@ -92,6 +99,8 @@ const MAX_ERROR_STACK_LENGTH = 8 * 1024;
92
99
  */
93
100
  const ERROR_STACK_HEAD_LENGTH = 2 * 1024;
94
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;
95
104
  /** The first `length` characters, not ending in half a surrogate pair. */
96
105
  function headOf(text, length) {
97
106
  const last = text.charCodeAt(length - 1);
@@ -123,21 +132,71 @@ function fitErrorStack(stack) {
123
132
  if (typeof stack !== "string" || stack.length <= MAX_ERROR_STACK_LENGTH) {
124
133
  return stack;
125
134
  }
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);
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);
129
145
  if (line !== -1) {
130
- tailStart = line;
146
+ return line;
131
147
  }
132
- else {
133
- const first = stack.charCodeAt(tailStart);
134
- if (first >= 0xdc00 && first <= 0xdfff) {
135
- tailStart += 1;
136
- }
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));
137
173
  }
138
- return copyOf(headOf(stack, ERROR_STACK_HEAD_LENGTH) +
139
- ERROR_TEXT_CUT +
140
- stack.slice(tailStart));
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));
141
200
  }
142
201
  /**
143
202
  * Longest span name the collector takes - the encoder's own limit, which it
@@ -191,16 +250,41 @@ function toErrorText(value) {
191
250
  }
192
251
  }
193
252
  }
194
- /** An error's stack, when it has one that is text. */
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
+ */
195
257
  function stackOf(error) {
196
258
  try {
197
- const stack = error.stack;
259
+ const stack = readStack(error);
198
260
  return typeof stack === "string" ? stack : undefined;
199
261
  }
200
262
  catch {
201
263
  return undefined;
202
264
  }
203
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
+ }
204
288
  /** The name of a thrown value's class, when it can be read. */
205
289
  function classNameOf(error) {
206
290
  try {
@@ -321,6 +405,13 @@ export class OperationTraceRegistry {
321
405
  * an error. See `endTrace` for what they decide.
322
406
  */
323
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();
324
415
  /**
325
416
  * Applied to every tree as it is plucked. Defaults are live from
326
417
  * construction rather than waiting for `configureSpanCollapse`, so a
@@ -402,18 +493,13 @@ export class OperationTraceRegistry {
402
493
  ? { message: toErrorText(error.message), stack: stackOf(error) }
403
494
  : { message: toErrorText(error), stack: undefined };
404
495
  // Redacted here, at the one point every error payload passes through.
405
- const redacted = this.redactor
406
- ? {
407
- message: this.redactor.redactMessage(raw.message),
408
- stack: raw.stack === undefined
409
- ? undefined
410
- : this.redactor.redactMessage(raw.stack),
411
- }
412
- : raw;
413
- // Cut once redacted, so no rule is handed half of what it matches.
496
+ const redactor = this.redactor;
497
+ const redact = redactor
498
+ ? (text) => redactor.redactMessage(text)
499
+ : (text) => text;
414
500
  const payload = {
415
- message: fitErrorMessage(redacted.message),
416
- stack: fitErrorStack(redacted.stack),
501
+ message: redactErrorMessage(raw.message, redact),
502
+ stack: redactErrorStack(raw.stack, redact),
417
503
  };
418
504
  const result = payload;
419
505
  const cls = classNameOf(error);
@@ -422,14 +508,16 @@ export class OperationTraceRegistry {
422
508
  }
423
509
  if (this.sourceContext !== false) {
424
510
  const settings = this.sourceContext === true ? {} : this.sourceContext;
425
- // Read off the raw stack with the raw message: the message is what marks
426
- // where the frames start, and it only matches the stack it came from.
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.
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.
430
517
  const codeFrames = collectCodeFrames(raw.stack, {
431
518
  ...settings,
432
519
  message: raw.message,
520
+ ...stackHeaderOf(error),
433
521
  redactor: this.redactor ?? undefined,
434
522
  });
435
523
  if (codeFrames) {
@@ -456,6 +544,15 @@ export class OperationTraceRegistry {
456
544
  return (snapshot !== undefined &&
457
545
  snapshot.refsCounter > snapshot.refsMarkedAsComplete);
458
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
+ }
459
556
  startTrace(traceId, data,
460
557
  /**
461
558
  * The trace id the snapshot reports under, when it is not the registry
@@ -531,9 +628,13 @@ export class OperationTraceRegistry {
531
628
  // have been caught and answered: a duplicate key turned into a 409, a
532
629
  // failed lookup into a 200 with a fallback. A transport that reports a
533
630
  // 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.
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));
535
635
  const errorStatusCode = "protocol" in snapshot
536
- ? snapshot.errorStatusCode ??
636
+ ? (firstFailure && this.rootErrorStatusCodes.get(firstFailure)) ??
637
+ snapshot.errorStatusCode ??
537
638
  (reportedStatusCode === undefined
538
639
  ? snapshot.outgoingErrorStatusCode
539
640
  : undefined)
@@ -583,6 +684,12 @@ export class OperationTraceRegistry {
583
684
  // caught and answered, and recording it as the operation's put the
584
685
  // driver's message, bound values and all, in place of what the
585
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.
586
693
  let outgoing;
587
694
  let found = false;
588
695
  for (const trace of snapshot.traces) {
@@ -590,14 +697,16 @@ export class OperationTraceRegistry {
590
697
  continue;
591
698
  }
592
699
  if (this.failedOutgoingRoots.has(trace)) {
593
- outgoing ??= trace;
700
+ if (typeof trace.error === "object") {
701
+ outgoing ??= trace;
702
+ }
594
703
  continue;
595
704
  }
705
+ found = true;
596
706
  if (typeof trace.error === "object") {
597
707
  snapshot.error = trace.error;
708
+ break;
598
709
  }
599
- found = true;
600
- break;
601
710
  }
602
711
  if (!found &&
603
712
  typeof outgoing?.error === "object" &&
@@ -830,15 +939,24 @@ export class OperationTraceRegistry {
830
939
  // have been caught and handled by its caller, in which case the
831
940
  // operation did not fail at all.
832
941
  snapshot.errorStatusCode = this.toErrorStatusCode(error);
942
+ this.rootErrorStatusCodes.set(activeTrace, snapshot.errorStatusCode);
833
943
  }
834
944
  if (isRootSpan) {
835
945
  // A root span keeps the error's details: it may become the
836
- // operation's own.
837
- if (typeof error === "object") {
838
- activeTrace.error = this.toErrorPayload(error);
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;
839
952
  }
840
- else {
953
+ else if (captured >= MAX_CAPTURED_ERRORS_PER_TRACE) {
841
954
  activeTrace.error = true;
955
+ this.reportCapturedErrorLimit(snapshot.traceId);
956
+ }
957
+ else {
958
+ snapshot.capturedErrors = captured + 1;
959
+ activeTrace.error = this.toErrorPayload(error);
842
960
  }
843
961
  }
844
962
  else {
@@ -965,7 +1083,7 @@ export class OperationTraceRegistry {
965
1083
  return;
966
1084
  }
967
1085
  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.`);
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.`);
969
1087
  }
970
1088
  /**
971
1089
  * Counts a span left unopened by `MAX_SPANS_PER_TRACE`. Warned once for
@@ -1024,25 +1142,33 @@ export class OperationTraceRegistry {
1024
1142
  this.callerIdsByTraceId.delete(traceId);
1025
1143
  this.traceSnapshots.delete(traceId);
1026
1144
  };
1027
- // Ensure snapshot is complete by checking refsCounter vs refsMarkedAsComplete
1028
- if (snapshot.refsCounter > snapshot.refsMarkedAsComplete) {
1029
- this.awaitingCompletion += 1;
1030
- try {
1031
- await new Promise((resolve) => setTimeout(resolve, SNAPSHOT_COMPLETION_TIMEOUT_MS));
1032
- }
1033
- finally {
1034
- this.awaitingCompletion -= 1;
1035
- }
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
1036
1151
  if (snapshot.refsCounter > snapshot.refsMarkedAsComplete) {
1037
- // Shipped without the spans still open rather than not at all: the
1038
- // operation itself finished, and dropping it lost its status and
1039
- // error along with every span that did end. Read before cleanup,
1040
- // which takes the span map the warning names them from.
1041
- this.reportUnfinishedSpans(traceId, snapshot);
1042
- 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
+ }
1043
1167
  }
1044
1168
  }
1045
- cleanup();
1169
+ finally {
1170
+ cleanup();
1171
+ }
1046
1172
  // These are what distinguish the registry's working copy from the
1047
1173
  // snapshot the API receives, so removing them is the hand-off.
1048
1174
  const bookkeeping = snapshot;
@@ -1258,7 +1384,11 @@ export class OperationTraceRegistry {
1258
1384
  const delegate = new TraceSpanDelegate(newNodeId, name, tags);
1259
1385
  manualSpan.tags = tags;
1260
1386
  const store = this.als.getStore();
1261
- 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]]), () => {
1262
1392
  try {
1263
1393
  const result = spanFunction(delegate);
1264
1394
  if (result instanceof Promise) {
@@ -290,6 +290,7 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
290
290
  ? MAX_ENTRIES_PER_WRITE - 1
291
291
  : lines.length;
292
292
  const messages = [];
293
+ const storeTraceId = liveTraceId(store, this.options.traceIdKey);
293
294
  for (let index = 0; index < read; index += 1) {
294
295
  const line = lines[index];
295
296
  // Parsed whole: see `MAX_REDACTED_LENGTH`.
@@ -302,18 +303,28 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
302
303
  message.longest = Math.max(message.longest, line.length);
303
304
  }
304
305
  else {
306
+ // A `Trace ID:` ending is the logger's suffix only when it names the
307
+ // trace the line was written in. Any other may be the message's own
308
+ // last words - a client's value, then a secret - and cut off before
309
+ // redaction it was sent as the trace id unread. So it is redacted
310
+ // with the message, and is a trace id only if it comes out as it
311
+ // went in.
312
+ const suffix = this.redactor && parsed.traceId !== storeTraceId
313
+ ? parsed.traceIdSuffix
314
+ : undefined;
305
315
  messages.push({
306
316
  head: parsed,
307
317
  // A bracket read as the context is redacted with the message - see
308
318
  // `splitContext`.
309
- lines: [parsed.unsplit ?? parsed.message],
319
+ lines: [(parsed.unsplit ?? parsed.message) + (suffix ?? "")],
310
320
  longest: line.length,
321
+ suffix,
311
322
  });
312
323
  }
313
324
  }
314
325
  const entries = [];
315
326
  for (const [index, message] of messages.entries()) {
316
- const { head } = message;
327
+ let { head } = message;
317
328
  let text = message.lines.join("\n");
318
329
  let keep = text.length;
319
330
  if (index === messages.length - 1 && head.format !== "json") {
@@ -326,6 +337,15 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
326
337
  }
327
338
  const redacted = this.redact(text, keep);
328
339
  const texts = head.format === "json" ? [redacted] : redacted.split("\n");
340
+ if (message.suffix !== undefined) {
341
+ if (texts[0].endsWith(message.suffix)) {
342
+ texts[0] = texts[0].slice(0, -message.suffix.length);
343
+ }
344
+ else {
345
+ // Masked, or part of it: no trace id, and the ending stays text.
346
+ head = { ...head, traceId: undefined };
347
+ }
348
+ }
329
349
  const first = this.splitContext(head, texts[0]);
330
350
  entries.push(this.toLogEntry(first.text, store, head, first.context, message.longest));
331
351
  // The lines under the first had no prefix of their own.
@@ -23,14 +23,17 @@ export declare class TracerService<Store extends object = Record<string | symbol
23
23
  /**
24
24
  * Creates a new trace span with the given name and executes the provided callback within that span.
25
25
  * The callback can be synchronous or asynchronous.
26
+ * Outside any operation the agent traces, the callback still runs, with a
27
+ * detached delegate whose tags go nowhere, as in an operation that is not
28
+ * recorded.
26
29
  */
27
30
  createSpan(name: string, callback: (span: TraceSpanDelegate) => unknown | Promise<unknown>): Promise<any>;
28
31
  /**
29
32
  * Retrieves the active span for the current request.
30
- * This method should be called within an async context where the AsyncLocalStorage is active.
31
- * If the operation is traced but no span is active, an error is thrown. An
32
- * operation that is not being recorded (ignored or sampled out) gets a
33
- * detached delegate whose tags go nowhere, as `createSpan` does.
33
+ * Where there is none - the operation is not being recorded (ignored or
34
+ * sampled out), nothing opened a span around the caller, or the call is
35
+ * outside any operation the agent traces - the delegate is a detached one
36
+ * whose tags go nowhere, as `createSpan`'s is then.
34
37
  * @returns {Promise<TraceSpanDelegate>} A promise that resolves to the active span delegate.
35
38
  */
36
39
  activeSpan(): Promise<TraceSpanDelegate>;
@@ -38,9 +41,10 @@ export declare class TracerService<Store extends object = Record<string | symbol
38
41
  * Captures an error and associates it with the current trace.
39
42
  * This method should be called within an async context where the AsyncLocalStorage is active.
40
43
  *
41
- * The details of at most 20 errors are recorded per trace; the span an
42
- * error is captured on after that is marked as failed, and its tags are
43
- * still recorded.
44
+ * The details of at most 20 errors are recorded per trace, counting the
45
+ * root spans that fail as well as captured errors; the span an error is
46
+ * captured on after that is marked as failed, and its tags are still
47
+ * recorded.
44
48
  *
45
49
  * Called outside any async context, it records nothing and says so once.
46
50
  */
@@ -122,7 +126,7 @@ export declare class TracerService<Store extends object = Record<string | symbol
122
126
  /**
123
127
  * The id of the trace currently in flight, or `null` outside one.
124
128
  *
125
- * Unlike `getAttribute`/`activeSpan`, this does not throw when there is no
129
+ * Like the rest of this service, this does not throw when there is no
126
130
  * active store - reading the trace id to forward it downstream (an outgoing
127
131
  * HTTP header, gRPC metadata, a queued job payload) is exactly the kind of
128
132
  * call that may legitimately happen outside a traced context, and a thrown
@@ -150,7 +154,8 @@ export declare class TracerService<Store extends object = Record<string | symbol
150
154
  /**
151
155
  * Sets an attribute on the current trace.
152
156
  * For example, you can use this to add metadata to the current request trace for later use and retrieval.
153
- * This method should be called within an async context where the AsyncLocalStorage is active.
157
+ * Does nothing outside any operation the agent traces, where there is no
158
+ * request context to keep the attribute in.
154
159
  * @param key The attribute key.
155
160
  * @param value The attribute value.
156
161
  */
@@ -158,15 +163,15 @@ export declare class TracerService<Store extends object = Record<string | symbol
158
163
  /**
159
164
  * Retrieves an attribute from the current trace (request context).
160
165
  * This allows you to access metadata that was set earlier in the request lifecycle.
161
- * This method should be called within an async context where the AsyncLocalStorage is active.
162
166
  * @param key The attribute key.
163
- * @returns The attribute value or undefined if not found.
167
+ * @returns The attribute value, or undefined if not found or when called
168
+ * outside any operation the agent traces.
164
169
  */
165
170
  getAttribute<P extends Path<Store>>(key: P): PathValue<Store, P> | undefined;
166
171
  /**
167
- * Reads the trace id the request was opened under. Its absence means the call
168
- * is outside any traced operation, which is the same mistake as calling these
169
- * methods with no async context at all - and is reported the same way.
172
+ * Reads the trace id the request was opened under. A store that carries none
173
+ * is reported as a mistake. No store at all is not one - it is code running
174
+ * outside any operation - and never gets here.
170
175
  */
171
176
  private requireTraceId;
172
177
  /**