@nestjs/observe 0.3.24 → 0.3.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +26 -1
  2. package/dist/agent/detached-observe-worker.js +50 -6
  3. package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
  4. package/dist/agent/observe-agent.shared-buffer.js +196 -19
  5. package/dist/agent/observe-agent.worker.d.ts +22 -2
  6. package/dist/agent/observe-agent.worker.js +43 -7
  7. package/dist/agent/telemetry-wire-contract.js +7 -1
  8. package/dist/cli/agent-notes.js +16 -4
  9. package/dist/cli/link.js +28 -3
  10. package/dist/cli/observe-cli.js +1 -19
  11. package/dist/cli/open-url.d.ts +27 -0
  12. package/dist/cli/open-url.js +63 -0
  13. package/dist/cli/project-files.d.ts +42 -1
  14. package/dist/cli/project-files.js +146 -7
  15. package/dist/cli/project-setup.d.ts +6 -0
  16. package/dist/cli/project-setup.js +14 -1
  17. package/dist/cli/wire-application.js +6 -0
  18. package/dist/custom-metrics/counter.d.ts +13 -2
  19. package/dist/custom-metrics/counter.js +33 -16
  20. package/dist/custom-metrics/finite-value.util.d.ts +14 -0
  21. package/dist/custom-metrics/finite-value.util.js +33 -1
  22. package/dist/custom-metrics/gauge.d.ts +2 -0
  23. package/dist/custom-metrics/gauge.js +43 -21
  24. package/dist/custom-metrics/label-values.util.d.ts +37 -0
  25. package/dist/custom-metrics/label-values.util.js +51 -0
  26. package/dist/custom-metrics/summary.d.ts +23 -0
  27. package/dist/custom-metrics/summary.js +73 -2
  28. package/dist/instrument/create-instance-decorator.instrument.js +244 -97
  29. package/dist/interfaces/observe-options.interface.d.ts +3 -1
  30. package/dist/objectives/objectives.registry.js +12 -0
  31. package/dist/observe.module.js +119 -3
  32. package/dist/otlp/otlp-encoders.js +22 -5
  33. package/dist/otlp/otlp-span.mapper.d.ts +4 -3
  34. package/dist/otlp/otlp-span.mapper.js +16 -8
  35. package/dist/otlp/otlp-trace-exporter.service.d.ts +3 -0
  36. package/dist/otlp/otlp-trace-exporter.service.js +71 -6
  37. package/dist/outgoing/http.integration.d.ts +8 -4
  38. package/dist/outgoing/http.integration.js +13 -6
  39. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  40. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  41. package/dist/outgoing/llm/llm-providers.js +72 -22
  42. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  43. package/dist/outgoing/llm/llm-usage.js +72 -25
  44. package/dist/outgoing/mssql.integration.js +16 -2
  45. package/dist/outgoing/mysql2.integration.js +17 -1
  46. package/dist/outgoing/outgoing-observe-agent.service.js +15 -3
  47. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  48. package/dist/outgoing/pg.integration.d.ts +3 -2
  49. package/dist/outgoing/pg.integration.js +39 -11
  50. package/dist/outgoing/sql-statement.util.js +106 -14
  51. package/dist/outgoing/undici.integration.d.ts +13 -0
  52. package/dist/outgoing/undici.integration.js +68 -0
  53. package/dist/protocols/bull-observe-agent.service.js +2 -12
  54. package/dist/protocols/deferred-trace-completion.d.ts +9 -1
  55. package/dist/protocols/deferred-trace-completion.js +36 -6
  56. package/dist/protocols/graphql-observe-agent.service.d.ts +36 -5
  57. package/dist/protocols/graphql-observe-agent.service.js +166 -5
  58. package/dist/protocols/graphql-operation-parser.js +72 -18
  59. package/dist/protocols/http-observe-agent.service.d.ts +43 -9
  60. package/dist/protocols/http-observe-agent.service.js +177 -59
  61. package/dist/protocols/job-trace-runner.d.ts +35 -3
  62. package/dist/protocols/job-trace-runner.js +136 -31
  63. package/dist/protocols/queue-observe-agent.service.js +44 -20
  64. package/dist/protocols/rpc-observe-agent.service.d.ts +50 -8
  65. package/dist/protocols/rpc-observe-agent.service.js +225 -49
  66. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  67. package/dist/protocols/ws-observe-agent.service.js +226 -20
  68. package/dist/services/index.d.ts +1 -1
  69. package/dist/services/index.js +1 -1
  70. package/dist/services/logger-patcher.service.js +3 -4
  71. package/dist/services/operation-trace.registry.d.ts +45 -1
  72. package/dist/services/operation-trace.registry.js +418 -35
  73. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  74. package/dist/services/stdout-forwarder.service.js +288 -51
  75. package/dist/services/tracer.service.d.ts +23 -0
  76. package/dist/services/tracer.service.js +99 -7
  77. package/dist/utils/capture-request.util.d.ts +3 -1
  78. package/dist/utils/capture-request.util.js +100 -12
  79. package/dist/utils/fit-to-length.util.js +33 -10
  80. package/dist/utils/log-line.parser.d.ts +14 -0
  81. package/dist/utils/log-line.parser.js +7 -3
  82. package/dist/utils/log-redactor.d.ts +14 -0
  83. package/dist/utils/log-redactor.js +512 -61
  84. package/dist/utils/operation-state.util.d.ts +39 -0
  85. package/dist/utils/operation-state.util.js +50 -0
  86. package/dist/utils/redact-url-query.d.ts +26 -4
  87. package/dist/utils/redact-url-query.js +184 -32
  88. package/dist/utils/sensitive-keys.d.ts +4 -1
  89. package/dist/utils/sensitive-keys.js +48 -10
  90. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  91. package/dist/utils/shared-hook-slot.util.js +103 -0
  92. package/dist/utils/source-context.util.d.ts +8 -0
  93. package/dist/utils/source-context.util.js +88 -19
  94. package/dist/utils/source-map-resolver.util.js +8 -2
  95. package/dist/utils/trace-context.util.d.ts +20 -0
  96. package/dist/utils/trace-context.util.js +50 -6
  97. package/package.json +4 -1
@@ -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,196 @@ 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
+ for (let index = 0; index < read; index += 1) {
294
+ const line = lines[index];
295
+ // Parsed whole: see `MAX_REDACTED_LENGTH`.
296
+ const parsed = parseLogLine(line);
297
+ const message = messages.at(-1);
298
+ if (message !== undefined &&
299
+ message.head.format !== "json" &&
300
+ parsed.format === "plain") {
301
+ message.lines.push(parsed.message);
302
+ message.longest = Math.max(message.longest, line.length);
303
+ }
304
+ else {
305
+ messages.push({
306
+ head: parsed,
307
+ // A bracket read as the context is redacted with the message - see
308
+ // `splitContext`.
309
+ lines: [parsed.unsplit ?? parsed.message],
310
+ longest: line.length,
311
+ });
312
+ }
313
+ }
314
+ const entries = [];
315
+ for (const [index, message] of messages.entries()) {
316
+ const { head } = message;
317
+ let text = message.lines.join("\n");
318
+ let keep = text.length;
319
+ if (index === messages.length - 1 && head.format !== "json") {
320
+ if (read < lines.length) {
321
+ text += this.linesAfter(lines, read);
322
+ }
323
+ else if (unfinished) {
324
+ keep -= REDACTION_LOOKAHEAD;
325
+ }
326
+ }
327
+ const redacted = this.redact(text, keep);
328
+ const texts = head.format === "json" ? [redacted] : redacted.split("\n");
329
+ const first = this.splitContext(head, texts[0]);
330
+ entries.push(this.toLogEntry(first.text, store, head, first.context, message.longest));
331
+ // The lines under the first had no prefix of their own.
332
+ for (let at = 1; at < texts.length; at += 1) {
333
+ entries.push(this.toLogEntry(texts[at], store));
334
+ }
335
+ }
336
+ if (read < lines.length) {
337
+ entries.push(this.toLogEntry(`[observe] ${lines.length - read} more lines of this write not forwarded`, store));
338
+ }
339
+ return entries;
340
+ }
341
+ /**
342
+ * The lines from `from` on, as the redactor is shown them past the last line
343
+ * that is sent: each after a line break, and only as many as
344
+ * `REDACTION_LOOKAHEAD` covers.
345
+ */
346
+ linesAfter(lines, from) {
347
+ let after = "";
348
+ for (let index = from; index < lines.length && after.length < REDACTION_LOOKAHEAD; index += 1) {
349
+ after += "\n" + stripAnsi(lines[index]).trimEnd();
350
+ }
351
+ return after;
352
+ }
353
+ /**
354
+ * The context and the text of a message's first line, `line` redacted.
355
+ *
356
+ * On a text line the context is a guess: the first `[...]` after the level.
357
+ * A line logged without a context reads the same when its message opens
358
+ * with `[` - `Logger.log(JSON.stringify(users))` - and the bracket then
359
+ * closes at the message's first `]`, wherever that falls. Inside a
360
+ * password, neither half matched a rule redacted apart, and both went out.
361
+ * So the bracket was redacted together with the message, as written, and
362
+ * the guess is kept only when the context, redacted by itself, is how the
363
+ * line still opens. When a mask runs across the bracket the line is sent
364
+ * whole, without a context. Either way both fields are cut from the line
365
+ * redacted whole.
366
+ */
367
+ splitContext(head, line) {
368
+ if (head.unsplit === undefined) {
369
+ return {
370
+ context: head.context === undefined ? undefined : this.toContext(head.context),
371
+ text: line,
372
+ };
373
+ }
374
+ const context = this.redact(head.context ?? "");
375
+ if (!line.startsWith(`[${context}`)) {
376
+ return { text: line };
377
+ }
378
+ return {
379
+ context: fitToLength(context, MAX_CONTEXT_LENGTH),
380
+ // A value without quotes runs on to the next space and takes the
381
+ // bracket's own `]` with it: `[token=abc] login`.
382
+ text: line.slice(context.length + 1).replace(/^\]?\s*/, ""),
383
+ };
384
+ }
385
+ /**
386
+ * `text` is redacted by now; `parsed` is the line it opens, when that line
387
+ * said more than its text, and `context` that line's, redacted. `longest`
388
+ * is the longest line `text` was read from: a line too long for the
389
+ * redactor's window goes without its attributes, whose length only it
390
+ * bounds - every string in them would need the window too.
391
+ */
392
+ toLogEntry(text, store, parsed, context, longest = 0) {
393
+ // Not a store whose operation ended a while ago: a line a timer it left
394
+ // armed writes is no line of that operation's.
395
+ const contextTraceId = liveTraceId(store, this.options.traceIdKey);
197
396
  // The line's own trace id wins: it was captured when the log was written,
198
397
  // whereas the async store is read now and may already have moved on.
199
398
  //
@@ -201,7 +400,7 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
201
400
  // gets a newline into a logged value can end a line with whatever
202
401
  // `Trace ID:` they like - so it is held to the rule a client-supplied
203
402
  // `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)
403
+ const lineTraceId = parsed?.traceId !== undefined && REQUEST_ID_PATTERN.test(parsed.traceId)
205
404
  ? parsed.traceId
206
405
  : undefined;
207
406
  const traceId = lineTraceId ?? contextTraceId;
@@ -215,22 +414,45 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
215
414
  spanId: traceId === contextTraceId
216
415
  ? store?.get(CALLER_METADATA_KEY)
217
416
  : 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
417
+ level: parsed?.level,
418
+ context,
419
+ // Redaction happens before the entry reaches the shared buffer - which
420
+ // is also before the buffer truncates oversized lines. That order is
224
421
  // deliberate: truncating first would cut a long secret in half and ship
225
422
  // 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,
423
+ attributes: parsed?.attributes === undefined || longest > MAX_REDACTED_LENGTH
424
+ ? undefined
425
+ : this.redactor
426
+ ? this.redactor.redactAttributes(parsed.attributes)
427
+ : parsed.attributes,
428
+ text,
232
429
  };
233
430
  }
431
+ /**
432
+ * `text` redacted, and cut where it has to be: to its first `keep`
433
+ * characters, and to what the redactor's window leaves room to send.
434
+ *
435
+ * Text that fits whole is redacted whole - the common case, one pass. Text
436
+ * that has to be cut is redacted cut and with `REDACTION_LOOKAHEAD` more of
437
+ * it, within the window, and only the prefix the two results share is sent:
438
+ * a secret the cut splits is masked in the longer one, so the two part
439
+ * before any of it.
440
+ */
441
+ redact(text, keep = text.length) {
442
+ const shown = text.length > MAX_REDACTED_LENGTH
443
+ ? text.slice(0, MAX_REDACTED_LENGTH)
444
+ : text;
445
+ const sent = Math.max(0, Math.min(keep, shown.length < text.length
446
+ ? MAX_REDACTED_LENGTH - REDACTION_LOOKAHEAD
447
+ : text.length));
448
+ if (!this.redactor) {
449
+ return sent < text.length ? text.slice(0, sent) : text;
450
+ }
451
+ if (sent >= text.length) {
452
+ return this.redactor.redactMessage(text);
453
+ }
454
+ return sharedPrefix(this.redactor.redactMessage(text.slice(0, sent)), this.redactor.redactMessage(shown));
455
+ }
234
456
  /**
235
457
  * A context is normally a class name, but it is read off the line like the
236
458
  * message, so it holds whatever was written there - a secret passed where a
@@ -239,10 +461,7 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
239
461
  * cut to what the collector accepts.
240
462
  */
241
463
  toContext(context) {
242
- const redacted = this.redactor
243
- ? this.redactor.redactMessage(context)
244
- : context;
245
- return fitToLength(redacted, MAX_CONTEXT_LENGTH);
464
+ return fitToLength(this.redact(context), MAX_CONTEXT_LENGTH);
246
465
  }
247
466
  };
248
467
  StdoutForwarderService = StdoutForwarderService_1 = __decorate([
@@ -252,3 +471,21 @@ StdoutForwarderService = StdoutForwarderService_1 = __decorate([
252
471
  AsyncLocalStorage])
253
472
  ], StdoutForwarderService);
254
473
  export { StdoutForwarderService };
474
+ /**
475
+ * The start `cut` and `whole` share, as a slice of `cut`. Never ends between
476
+ * the two halves of a surrogate pair, which would send half a character.
477
+ */
478
+ function sharedPrefix(cut, whole) {
479
+ const max = Math.min(cut.length, whole.length);
480
+ let at = 0;
481
+ while (at < max && cut.charCodeAt(at) === whole.charCodeAt(at)) {
482
+ at += 1;
483
+ }
484
+ if (at > 0 && at < cut.length) {
485
+ const last = cut.charCodeAt(at - 1);
486
+ if (last >= 0xd800 && last <= 0xdbff) {
487
+ at -= 1;
488
+ }
489
+ }
490
+ return at === cut.length ? cut : cut.slice(0, at);
491
+ }
@@ -16,6 +16,9 @@ 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.
@@ -34,8 +37,21 @@ export declare class TracerService<Store extends object = Record<string | symbol
34
37
  /**
35
38
  * Captures an error and associates it with the current trace.
36
39
  * This method should be called within an async context where the AsyncLocalStorage is active.
40
+ *
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
+ *
45
+ * Called outside any async context, it records nothing and says so once.
37
46
  */
38
47
  captureError(error: Error, tags?: Record<string, string | number | boolean>): Promise<void>;
48
+ /** Said once: a call site outside any context is outside it every time. */
49
+ private reportErrorOutsideContext;
50
+ /**
51
+ * A failure to record an error comes from the same call site on every
52
+ * request, so it is reported once rather than once per request.
53
+ */
54
+ private reportUncapturedError;
39
55
  /**
40
56
  * Creates or retrieves a counter metric with the specified name.
41
57
  * If a counter with the same name already exists, it returns the existing counter.
@@ -159,6 +175,13 @@ export declare class TracerService<Store extends object = Record<string | symbol
159
175
  * under, which a reader has no way to look up.
160
176
  */
161
177
  private reportedTraceId;
178
+ /**
179
+ * Whether a metric not yet registered is, under `MAX_METRICS`. One that is
180
+ * not is still handed to the caller, so the code around it runs as it
181
+ * would, but it is neither reported nor kept: each call gets a new one.
182
+ * Reported once, as it comes from the same call site every time.
183
+ */
184
+ private admitsMetric;
162
185
  private registerCounterChangeHandler;
163
186
  private registerGaugeChangeHandler;
164
187
  private registerSummaryChangeHandler;