@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
@@ -15,6 +15,14 @@ export declare class StdoutForwarderService implements OnModuleInit, OnModuleDes
15
15
  *
16
16
  * One fragment per stream: stdout and stderr interleave freely, and joining
17
17
  * the tail of one onto the head of the other would fuse two unrelated lines.
18
+ *
19
+ * And one per execution, for the same reason: while one request prints a
20
+ * reply piece by piece, others log. Joined, the pieces written so far went
21
+ * out under the trace of whoever logged next, in front of a line that no
22
+ * longer parsed, and a secret still being written was cut in two before it
23
+ * was redacted. Keyed by the trace, as the registry is, rather than by the
24
+ * store, which is copied for every span. Writes outside any execution share
25
+ * the `undefined` key. Kept in the order the lines were last written to.
18
26
  */
19
27
  private readonly partialLines;
20
28
  private originalWrites;
@@ -53,8 +61,69 @@ export declare class StdoutForwarderService implements OnModuleInit, OnModuleDes
53
61
  */
54
62
  private restore;
55
63
  private consume;
64
+ /** Forwards, as it is, the line one execution left unfinished. */
56
65
  private flushPartial;
66
+ /**
67
+ * The entries for the complete lines of one write - an entry per line, but
68
+ * with the lines of one message redacted as the one text they were written
69
+ * as.
70
+ *
71
+ * A logger hands over a message in a single write however many lines it
72
+ * runs to, and only the first carries its prefix: the rest - the stack
73
+ * under an error, a key in its PEM layout, a value that holds a line break -
74
+ * arrive plain. Redacted a line at a time, such a secret is never seen
75
+ * whole. So a line is redacted together with the plain lines under it; a
76
+ * line with a prefix of its own starts another message, and a JSON record
77
+ * is always a message by itself. A masked value takes its line breaks with
78
+ * it, so a message can come back as fewer entries than it had lines.
79
+ *
80
+ * At most `MAX_ENTRIES_PER_WRITE` lines are read, and the lines past them
81
+ * are shown to the redactor with the last message, so a secret the cut
82
+ * splits is not half-sent. `store` is the one the lines were written in.
83
+ * `unfinished` for a line that goes on past what was written of it - see
84
+ * `MAX_PARTIAL_LINE_LENGTH`.
85
+ */
86
+ private toLogEntries;
87
+ /**
88
+ * The lines from `from` on, as the redactor is shown them past the last line
89
+ * that is sent: each after a line break, and only as many as
90
+ * `REDACTION_LOOKAHEAD` covers.
91
+ */
92
+ private linesAfter;
93
+ /**
94
+ * The context and the text of a message's first line, `line` redacted.
95
+ *
96
+ * On a text line the context is a guess: the first `[...]` after the level.
97
+ * A line logged without a context reads the same when its message opens
98
+ * with `[` - `Logger.log(JSON.stringify(users))` - and the bracket then
99
+ * closes at the message's first `]`, wherever that falls. Inside a
100
+ * password, neither half matched a rule redacted apart, and both went out.
101
+ * So the bracket was redacted together with the message, as written, and
102
+ * the guess is kept only when the context, redacted by itself, is how the
103
+ * line still opens. When a mask runs across the bracket the line is sent
104
+ * whole, without a context. Either way both fields are cut from the line
105
+ * redacted whole.
106
+ */
107
+ private splitContext;
108
+ /**
109
+ * `text` is redacted by now; `parsed` is the line it opens, when that line
110
+ * said more than its text, and `context` that line's, redacted. `longest`
111
+ * is the longest line `text` was read from: a line too long for the
112
+ * redactor's window goes without its attributes, whose length only it
113
+ * bounds - every string in them would need the window too.
114
+ */
57
115
  private toLogEntry;
116
+ /**
117
+ * `text` redacted, and cut where it has to be: to its first `keep`
118
+ * characters, and to what the redactor's window leaves room to send.
119
+ *
120
+ * Text that fits whole is redacted whole - the common case, one pass. Text
121
+ * that has to be cut is redacted cut and with `REDACTION_LOOKAHEAD` more of
122
+ * it, within the window, and only the prefix the two results share is sent:
123
+ * a secret the cut splits is masked in the longer one, so the two part
124
+ * before any of it.
125
+ */
126
+ private redact;
58
127
  /**
59
128
  * A context is normally a class name, but it is read off the line like the
60
129
  * message, so it holds whatever was written there - a secret passed where a
@@ -16,41 +16,78 @@ import { AsyncLocalStorage } from "async_hooks";
16
16
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
17
17
  import { REQUEST_ID_PATTERN } from "../utils/default-trace-id-generator.util.js";
18
18
  import { fitToLength } from "../utils/fit-to-length.util.js";
19
- import { parseLogLine } from "../utils/log-line.parser.js";
19
+ import { parseLogLine, stripAnsi, } from "../utils/log-line.parser.js";
20
20
  import { LogRedactor } from "../utils/log-redactor.js";
21
- import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "../observe.constants.js";
21
+ import { CALLER_METADATA_KEY, OBSERVE_OPTIONS, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
22
+ import { liveTraceId } from "../utils/operation-state.util.js";
22
23
  /**
23
24
  * Cap on the unterminated tail held between writes.
24
25
  *
25
26
  * A process that writes a long stretch without a newline (a progress bar, a
26
27
  * streamed response) would otherwise grow this string without bound. At the cap
27
- * the tail is forwarded as-is rather than discarded - a partial line is still
28
- * evidence.
28
+ * the tail is forwarded rather than discarded - a partial line is still
29
+ * evidence - and the rest of that line, up to its newline, is dropped: it is
30
+ * not a line of its own, and a secret the cap split would start it. A line
31
+ * written in one call loses everything past the 4 KB the shared buffer keeps
32
+ * of an entry anyway.
29
33
  */
30
34
  const MAX_PARTIAL_LINE_LENGTH = 8 * 1024;
31
35
  /**
32
- * Most of a line the parser and redactor are ever given.
36
+ * Most text the redactor is ever given in one go - a line, or a message and
37
+ * the lines under it. Text past it is not sent: see `REDACTION_LOOKAHEAD`.
33
38
  *
34
- * Everything in `toLogEntry` runs synchronously inside the patched
39
+ * Everything in `toLogEntries` runs synchronously inside the patched
35
40
  * `process.stdout.write`, on the application's own hot path, and the redactor
36
41
  * is a set of regular expressions whose cost grows with input length. A single
37
42
  * multi-megabyte line - a dumped payload, and payloads can carry content an
38
43
  * outside caller chose - must not be able to hold the event loop while every
39
44
  * rule walks it. A bound only helps while that cost stays linear: a pattern
40
45
  * that backtracks super-linearly holds the loop for minutes inside 16 KB, which
41
- * is why the parser's patterns are written to be linear.
46
+ * is why the redactor's patterns are written to be linear.
42
47
  *
43
- * The bound is safe because it is four times what can ship: the shared buffer
44
- * truncates entries to 4 KB, so bytes beyond this window were never going to
45
- * leave the process - and a secret straddling the 4 KB cut still sits whole
46
- * inside this window, so it is redacted before the cut can split it.
48
+ * The parser is not held to it. It is linear, and a line cut before it reads
49
+ * it is a different line: a JSON record no longer parses, and goes out as raw
50
+ * text that nothing masks by key.
47
51
  */
48
- const MAX_PARSED_LINE_LENGTH = 16 * 1024;
52
+ const MAX_REDACTED_LENGTH = 16 * 1024;
53
+ /**
54
+ * How much of what the redactor is shown is there only to be seen, past the
55
+ * text that is sent.
56
+ *
57
+ * A cut through a secret leaves two pieces no rule recognises, and the piece
58
+ * in front of the cut ships: masking shortens the text before it - a long
59
+ * `token=AAAA…` becomes `token=[REDACTED]` - so the edge of a 16 KB window can
60
+ * land inside the 4 KB the shared buffer keeps of an entry. So text that has
61
+ * to be cut is redacted twice, cut and with this much more of it, and only
62
+ * what the two agree on is sent: a secret the cut splits is whole, and
63
+ * masked, in the longer text, and the two part where it starts. A secret
64
+ * longer than this that a cut splits can still leave its start behind.
65
+ */
66
+ const REDACTION_LOOKAHEAD = 4 * 1024;
49
67
  /**
50
68
  * Longest `context` the collector accepts. It does not cut a longer one down:
51
69
  * it refuses the whole batch the line rides in, traces and metrics included.
52
70
  */
53
71
  const MAX_CONTEXT_LENGTH = 255;
72
+ /**
73
+ * Most entries one write may add to the log buffer.
74
+ *
75
+ * The buffer's caps are shared by the whole process and keep what came first,
76
+ * so a single logged value full of line breaks - a client's username, a
77
+ * posted object `util.inspect` prints a property per line - would otherwise
78
+ * become thousands of entries, push every other request's lines out of the
79
+ * batch, and hold the event loop while each one was parsed and redacted.
80
+ * Past this many, the opening lines are kept and one more entry says how many
81
+ * followed.
82
+ */
83
+ const MAX_ENTRIES_PER_WRITE = 50;
84
+ /**
85
+ * Most unfinished lines held per stream, one for each execution that has
86
+ * written one. An execution that ends without writing its newline leaves its
87
+ * line behind, so past this many the one written to longest ago is forwarded
88
+ * as it is.
89
+ */
90
+ const MAX_HELD_LINES = 64;
54
91
  const FORWARDED_STREAMS = ["stdout", "stderr"];
55
92
  let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderService {
56
93
  options;
@@ -65,10 +102,18 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
65
102
  *
66
103
  * One fragment per stream: stdout and stderr interleave freely, and joining
67
104
  * the tail of one onto the head of the other would fuse two unrelated lines.
105
+ *
106
+ * And one per execution, for the same reason: while one request prints a
107
+ * reply piece by piece, others log. Joined, the pieces written so far went
108
+ * out under the trace of whoever logged next, in front of a line that no
109
+ * longer parsed, and a secret still being written was cut in two before it
110
+ * was redacted. Keyed by the trace, as the registry is, rather than by the
111
+ * store, which is copied for every span. Writes outside any execution share
112
+ * the `undefined` key. Kept in the order the lines were last written to.
68
113
  */
69
114
  partialLines = {
70
- stdout: "",
71
- stderr: "",
115
+ stdout: new Map(),
116
+ stderr: new Map(),
72
117
  };
73
118
  originalWrites = null;
74
119
  /**
@@ -158,42 +203,216 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
158
203
  return;
159
204
  }
160
205
  for (const name of FORWARDED_STREAMS) {
161
- this.flushPartial(name);
206
+ // Deleting the entry being visited is safe while iterating a Map.
207
+ for (const writer of this.partialLines[name].keys()) {
208
+ this.flushPartial(name, writer);
209
+ }
162
210
  process[name].write = this.originalWrites[name];
163
211
  }
164
212
  this.originalWrites = null;
165
213
  }
166
214
  consume(chunk, name = "stdout") {
167
- const combined = this.partialLines[name] + chunk;
215
+ const store = this.als.getStore();
216
+ const writer = store?.get(TRACE_REGISTRY_KEY) ?? store?.get(this.options.traceIdKey);
217
+ const held = this.partialLines[name];
218
+ const heldLine = held.get(writer);
219
+ let combined = chunk;
220
+ if (heldLine !== undefined) {
221
+ // Set again below rather than updated in place, so the map stays in
222
+ // the order the lines were last written to.
223
+ held.delete(writer);
224
+ if (heldLine.overflowed) {
225
+ const newline = chunk.indexOf("\n");
226
+ if (newline === -1) {
227
+ held.set(writer, heldLine);
228
+ return;
229
+ }
230
+ combined = chunk.slice(newline + 1);
231
+ }
232
+ else {
233
+ combined = heldLine.text + chunk;
234
+ }
235
+ }
168
236
  const segments = combined.split("\n");
169
237
  // The final segment has no newline yet, so it is either an incomplete line
170
238
  // or the empty string left by a chunk that ended cleanly.
171
- this.partialLines[name] = segments.pop() ?? "";
172
- const entries = segments
173
- .filter((line) => line.trim().length > 0)
174
- .map((line) => this.toLogEntry(line));
239
+ const tail = segments.pop() ?? "";
240
+ const entries = this.toLogEntries(segments.filter((line) => line.trim().length > 0), store);
241
+ if (tail.length > MAX_PARTIAL_LINE_LENGTH) {
242
+ if (tail.trim().length > 0) {
243
+ entries.push(...this.toLogEntries([tail], store, true));
244
+ }
245
+ held.set(writer, { text: "", store, overflowed: true });
246
+ }
247
+ else if (tail.length > 0) {
248
+ held.set(writer, { text: tail, store, overflowed: false });
249
+ }
175
250
  if (entries.length > 0) {
176
251
  this.observeAgentSharedBuffer.pushLogs(entries);
177
252
  }
178
- if (this.partialLines[name].length > MAX_PARTIAL_LINE_LENGTH) {
179
- this.flushPartial(name);
253
+ if (held.size > MAX_HELD_LINES) {
254
+ this.flushPartial(name, held.keys().next().value);
180
255
  }
181
256
  }
182
- flushPartial(name) {
183
- const partialLine = this.partialLines[name];
184
- this.partialLines[name] = "";
185
- if (partialLine.trim().length === 0) {
257
+ /** Forwards, as it is, the line one execution left unfinished. */
258
+ flushPartial(name, writer) {
259
+ const line = this.partialLines[name].get(writer);
260
+ this.partialLines[name].delete(writer);
261
+ if (line === undefined || line.text.trim().length === 0) {
186
262
  return;
187
263
  }
188
- this.observeAgentSharedBuffer.pushLogs([this.toLogEntry(partialLine)]);
264
+ this.observeAgentSharedBuffer.pushLogs(this.toLogEntries([line.text], line.store));
189
265
  }
190
- toLogEntry(rawLine) {
191
- const line = rawLine.length > MAX_PARSED_LINE_LENGTH
192
- ? rawLine.slice(0, MAX_PARSED_LINE_LENGTH)
193
- : rawLine;
194
- const parsed = parseLogLine(line);
195
- const store = this.als.getStore();
196
- const contextTraceId = store?.get(this.options.traceIdKey);
266
+ /**
267
+ * The entries for the complete lines of one write - an entry per line, but
268
+ * with the lines of one message redacted as the one text they were written
269
+ * as.
270
+ *
271
+ * A logger hands over a message in a single write however many lines it
272
+ * runs to, and only the first carries its prefix: the rest - the stack
273
+ * under an error, a key in its PEM layout, a value that holds a line break -
274
+ * arrive plain. Redacted a line at a time, such a secret is never seen
275
+ * whole. So a line is redacted together with the plain lines under it; a
276
+ * line with a prefix of its own starts another message, and a JSON record
277
+ * is always a message by itself. A masked value takes its line breaks with
278
+ * it, so a message can come back as fewer entries than it had lines.
279
+ *
280
+ * At most `MAX_ENTRIES_PER_WRITE` lines are read, and the lines past them
281
+ * are shown to the redactor with the last message, so a secret the cut
282
+ * splits is not half-sent. `store` is the one the lines were written in.
283
+ * `unfinished` for a line that goes on past what was written of it - see
284
+ * `MAX_PARTIAL_LINE_LENGTH`.
285
+ */
286
+ toLogEntries(lines, store, unfinished = false) {
287
+ // Cut before anything is parsed or redacted, which is where the time
288
+ // goes.
289
+ const read = lines.length > MAX_ENTRIES_PER_WRITE
290
+ ? MAX_ENTRIES_PER_WRITE - 1
291
+ : lines.length;
292
+ const messages = [];
293
+ const storeTraceId = liveTraceId(store, this.options.traceIdKey);
294
+ for (let index = 0; index < read; index += 1) {
295
+ const line = lines[index];
296
+ // Parsed whole: see `MAX_REDACTED_LENGTH`.
297
+ const parsed = parseLogLine(line);
298
+ const message = messages.at(-1);
299
+ if (message !== undefined &&
300
+ message.head.format !== "json" &&
301
+ parsed.format === "plain") {
302
+ message.lines.push(parsed.message);
303
+ message.longest = Math.max(message.longest, line.length);
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;
315
+ messages.push({
316
+ head: parsed,
317
+ // A bracket read as the context is redacted with the message - see
318
+ // `splitContext`.
319
+ lines: [(parsed.unsplit ?? parsed.message) + (suffix ?? "")],
320
+ longest: line.length,
321
+ suffix,
322
+ });
323
+ }
324
+ }
325
+ const entries = [];
326
+ for (const [index, message] of messages.entries()) {
327
+ let { head } = message;
328
+ let text = message.lines.join("\n");
329
+ let keep = text.length;
330
+ if (index === messages.length - 1 && head.format !== "json") {
331
+ if (read < lines.length) {
332
+ text += this.linesAfter(lines, read);
333
+ }
334
+ else if (unfinished) {
335
+ keep -= REDACTION_LOOKAHEAD;
336
+ }
337
+ }
338
+ const redacted = this.redact(text, keep);
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
+ }
349
+ const first = this.splitContext(head, texts[0]);
350
+ entries.push(this.toLogEntry(first.text, store, head, first.context, message.longest));
351
+ // The lines under the first had no prefix of their own.
352
+ for (let at = 1; at < texts.length; at += 1) {
353
+ entries.push(this.toLogEntry(texts[at], store));
354
+ }
355
+ }
356
+ if (read < lines.length) {
357
+ entries.push(this.toLogEntry(`[observe] ${lines.length - read} more lines of this write not forwarded`, store));
358
+ }
359
+ return entries;
360
+ }
361
+ /**
362
+ * The lines from `from` on, as the redactor is shown them past the last line
363
+ * that is sent: each after a line break, and only as many as
364
+ * `REDACTION_LOOKAHEAD` covers.
365
+ */
366
+ linesAfter(lines, from) {
367
+ let after = "";
368
+ for (let index = from; index < lines.length && after.length < REDACTION_LOOKAHEAD; index += 1) {
369
+ after += "\n" + stripAnsi(lines[index]).trimEnd();
370
+ }
371
+ return after;
372
+ }
373
+ /**
374
+ * The context and the text of a message's first line, `line` redacted.
375
+ *
376
+ * On a text line the context is a guess: the first `[...]` after the level.
377
+ * A line logged without a context reads the same when its message opens
378
+ * with `[` - `Logger.log(JSON.stringify(users))` - and the bracket then
379
+ * closes at the message's first `]`, wherever that falls. Inside a
380
+ * password, neither half matched a rule redacted apart, and both went out.
381
+ * So the bracket was redacted together with the message, as written, and
382
+ * the guess is kept only when the context, redacted by itself, is how the
383
+ * line still opens. When a mask runs across the bracket the line is sent
384
+ * whole, without a context. Either way both fields are cut from the line
385
+ * redacted whole.
386
+ */
387
+ splitContext(head, line) {
388
+ if (head.unsplit === undefined) {
389
+ return {
390
+ context: head.context === undefined ? undefined : this.toContext(head.context),
391
+ text: line,
392
+ };
393
+ }
394
+ const context = this.redact(head.context ?? "");
395
+ if (!line.startsWith(`[${context}`)) {
396
+ return { text: line };
397
+ }
398
+ return {
399
+ context: fitToLength(context, MAX_CONTEXT_LENGTH),
400
+ // A value without quotes runs on to the next space and takes the
401
+ // bracket's own `]` with it: `[token=abc] login`.
402
+ text: line.slice(context.length + 1).replace(/^\]?\s*/, ""),
403
+ };
404
+ }
405
+ /**
406
+ * `text` is redacted by now; `parsed` is the line it opens, when that line
407
+ * said more than its text, and `context` that line's, redacted. `longest`
408
+ * is the longest line `text` was read from: a line too long for the
409
+ * redactor's window goes without its attributes, whose length only it
410
+ * bounds - every string in them would need the window too.
411
+ */
412
+ toLogEntry(text, store, parsed, context, longest = 0) {
413
+ // Not a store whose operation ended a while ago: a line a timer it left
414
+ // armed writes is no line of that operation's.
415
+ const contextTraceId = liveTraceId(store, this.options.traceIdKey);
197
416
  // The line's own trace id wins: it was captured when the log was written,
198
417
  // whereas the async store is read now and may already have moved on.
199
418
  //
@@ -201,7 +420,7 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
201
420
  // gets a newline into a logged value can end a line with whatever
202
421
  // `Trace ID:` they like - so it is held to the rule a client-supplied
203
422
  // `x-request-id` is. An over-long one would get the whole batch refused.
204
- const lineTraceId = parsed.traceId !== undefined && REQUEST_ID_PATTERN.test(parsed.traceId)
423
+ const lineTraceId = parsed?.traceId !== undefined && REQUEST_ID_PATTERN.test(parsed.traceId)
205
424
  ? parsed.traceId
206
425
  : undefined;
207
426
  const traceId = lineTraceId ?? contextTraceId;
@@ -215,22 +434,45 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
215
434
  spanId: traceId === contextTraceId
216
435
  ? store?.get(CALLER_METADATA_KEY)
217
436
  : undefined,
218
- level: parsed.level,
219
- context: parsed.context === undefined
220
- ? undefined
221
- : this.toContext(parsed.context),
222
- // Redaction happens here, before the entry reaches the shared buffer -
223
- // which is also before the buffer truncates oversized lines. That order is
437
+ level: parsed?.level,
438
+ context,
439
+ // Redaction happens before the entry reaches the shared buffer - which
440
+ // is also before the buffer truncates oversized lines. That order is
224
441
  // deliberate: truncating first would cut a long secret in half and ship
225
442
  // the surviving half.
226
- attributes: this.redactor
227
- ? this.redactor.redactAttributes(parsed.attributes)
228
- : parsed.attributes,
229
- text: this.redactor
230
- ? this.redactor.redactMessage(parsed.message)
231
- : parsed.message,
443
+ attributes: parsed?.attributes === undefined || longest > MAX_REDACTED_LENGTH
444
+ ? undefined
445
+ : this.redactor
446
+ ? this.redactor.redactAttributes(parsed.attributes)
447
+ : parsed.attributes,
448
+ text,
232
449
  };
233
450
  }
451
+ /**
452
+ * `text` redacted, and cut where it has to be: to its first `keep`
453
+ * characters, and to what the redactor's window leaves room to send.
454
+ *
455
+ * Text that fits whole is redacted whole - the common case, one pass. Text
456
+ * that has to be cut is redacted cut and with `REDACTION_LOOKAHEAD` more of
457
+ * it, within the window, and only the prefix the two results share is sent:
458
+ * a secret the cut splits is masked in the longer one, so the two part
459
+ * before any of it.
460
+ */
461
+ redact(text, keep = text.length) {
462
+ const shown = text.length > MAX_REDACTED_LENGTH
463
+ ? text.slice(0, MAX_REDACTED_LENGTH)
464
+ : text;
465
+ const sent = Math.max(0, Math.min(keep, shown.length < text.length
466
+ ? MAX_REDACTED_LENGTH - REDACTION_LOOKAHEAD
467
+ : text.length));
468
+ if (!this.redactor) {
469
+ return sent < text.length ? text.slice(0, sent) : text;
470
+ }
471
+ if (sent >= text.length) {
472
+ return this.redactor.redactMessage(text);
473
+ }
474
+ return sharedPrefix(this.redactor.redactMessage(text.slice(0, sent)), this.redactor.redactMessage(shown));
475
+ }
234
476
  /**
235
477
  * A context is normally a class name, but it is read off the line like the
236
478
  * message, so it holds whatever was written there - a secret passed where a
@@ -239,10 +481,7 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
239
481
  * cut to what the collector accepts.
240
482
  */
241
483
  toContext(context) {
242
- const redacted = this.redactor
243
- ? this.redactor.redactMessage(context)
244
- : context;
245
- return fitToLength(redacted, MAX_CONTEXT_LENGTH);
484
+ return fitToLength(this.redact(context), MAX_CONTEXT_LENGTH);
246
485
  }
247
486
  };
248
487
  StdoutForwarderService = StdoutForwarderService_1 = __decorate([
@@ -252,3 +491,21 @@ StdoutForwarderService = StdoutForwarderService_1 = __decorate([
252
491
  AsyncLocalStorage])
253
492
  ], StdoutForwarderService);
254
493
  export { StdoutForwarderService };
494
+ /**
495
+ * The start `cut` and `whole` share, as a slice of `cut`. Never ends between
496
+ * the two halves of a surrogate pair, which would send half a character.
497
+ */
498
+ function sharedPrefix(cut, whole) {
499
+ const max = Math.min(cut.length, whole.length);
500
+ let at = 0;
501
+ while (at < max && cut.charCodeAt(at) === whole.charCodeAt(at)) {
502
+ at += 1;
503
+ }
504
+ if (at > 0 && at < cut.length) {
505
+ const last = cut.charCodeAt(at - 1);
506
+ if (last >= 0xd800 && last <= 0xdbff) {
507
+ at -= 1;
508
+ }
509
+ }
510
+ return at === cut.length ? cut : cut.slice(0, at);
511
+ }
@@ -16,26 +16,46 @@ export declare class TracerService<Store extends object = Record<string | symbol
16
16
  private readonly summaries;
17
17
  private readonly logger;
18
18
  private hasReportedUnusableOperationId;
19
+ private hasReportedMetricLimit;
20
+ private hasReportedUncapturedError;
21
+ private hasReportedErrorOutsideContext;
19
22
  constructor(operationTraceRegistry: OperationTraceRegistry, als: AsyncLocalStorage<Map<string | symbol | TraceKey, any>>, observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults);
20
23
  /**
21
24
  * Creates a new trace span with the given name and executes the provided callback within that span.
22
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.
23
29
  */
24
30
  createSpan(name: string, callback: (span: TraceSpanDelegate) => unknown | Promise<unknown>): Promise<any>;
25
31
  /**
26
32
  * Retrieves the active span for the current request.
27
- * This method should be called within an async context where the AsyncLocalStorage is active.
28
- * If the operation is traced but no span is active, an error is thrown. An
29
- * operation that is not being recorded (ignored or sampled out) gets a
30
- * 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.
31
37
  * @returns {Promise<TraceSpanDelegate>} A promise that resolves to the active span delegate.
32
38
  */
33
39
  activeSpan(): Promise<TraceSpanDelegate>;
34
40
  /**
35
41
  * Captures an error and associates it with the current trace.
36
42
  * This method should be called within an async context where the AsyncLocalStorage is active.
43
+ *
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.
48
+ *
49
+ * Called outside any async context, it records nothing and says so once.
37
50
  */
38
51
  captureError(error: Error, tags?: Record<string, string | number | boolean>): Promise<void>;
52
+ /** Said once: a call site outside any context is outside it every time. */
53
+ private reportErrorOutsideContext;
54
+ /**
55
+ * A failure to record an error comes from the same call site on every
56
+ * request, so it is reported once rather than once per request.
57
+ */
58
+ private reportUncapturedError;
39
59
  /**
40
60
  * Creates or retrieves a counter metric with the specified name.
41
61
  * If a counter with the same name already exists, it returns the existing counter.
@@ -106,7 +126,7 @@ export declare class TracerService<Store extends object = Record<string | symbol
106
126
  /**
107
127
  * The id of the trace currently in flight, or `null` outside one.
108
128
  *
109
- * 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
110
130
  * active store - reading the trace id to forward it downstream (an outgoing
111
131
  * HTTP header, gRPC metadata, a queued job payload) is exactly the kind of
112
132
  * call that may legitimately happen outside a traced context, and a thrown
@@ -134,7 +154,8 @@ export declare class TracerService<Store extends object = Record<string | symbol
134
154
  /**
135
155
  * Sets an attribute on the current trace.
136
156
  * For example, you can use this to add metadata to the current request trace for later use and retrieval.
137
- * 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.
138
159
  * @param key The attribute key.
139
160
  * @param value The attribute value.
140
161
  */
@@ -142,15 +163,15 @@ export declare class TracerService<Store extends object = Record<string | symbol
142
163
  /**
143
164
  * Retrieves an attribute from the current trace (request context).
144
165
  * This allows you to access metadata that was set earlier in the request lifecycle.
145
- * This method should be called within an async context where the AsyncLocalStorage is active.
146
166
  * @param key The attribute key.
147
- * @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.
148
169
  */
149
170
  getAttribute<P extends Path<Store>>(key: P): PathValue<Store, P> | undefined;
150
171
  /**
151
- * Reads the trace id the request was opened under. Its absence means the call
152
- * is outside any traced operation, which is the same mistake as calling these
153
- * 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.
154
175
  */
155
176
  private requireTraceId;
156
177
  /**
@@ -159,6 +180,13 @@ export declare class TracerService<Store extends object = Record<string | symbol
159
180
  * under, which a reader has no way to look up.
160
181
  */
161
182
  private reportedTraceId;
183
+ /**
184
+ * Whether a metric not yet registered is, under `MAX_METRICS`. One that is
185
+ * not is still handed to the caller, so the code around it runs as it
186
+ * would, but it is neither reported nor kept: each call gets a new one.
187
+ * Reported once, as it comes from the same call site every time.
188
+ */
189
+ private admitsMetric;
162
190
  private registerCounterChangeHandler;
163
191
  private registerGaugeChangeHandler;
164
192
  private registerSummaryChangeHandler;