@nestjs/observe 0.3.10 → 0.3.12

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.
@@ -14,6 +14,8 @@ var StdoutForwarderService_1;
14
14
  import { Inject, Injectable, Logger, } from "@nestjs/common";
15
15
  import { AsyncLocalStorage } from "async_hooks";
16
16
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
17
+ import { REQUEST_ID_PATTERN } from "../utils/default-trace-id-generator.util.js";
18
+ import { fitToLength } from "../utils/fit-to-length.util.js";
17
19
  import { parseLogLine } from "../utils/log-line.parser.js";
18
20
  import { LogRedactor } from "../utils/log-redactor.js";
19
21
  import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "../observe.constants.js";
@@ -34,7 +36,9 @@ const MAX_PARTIAL_LINE_LENGTH = 8 * 1024;
34
36
  * is a set of regular expressions whose cost grows with input length. A single
35
37
  * multi-megabyte line - a dumped payload, and payloads can carry content an
36
38
  * outside caller chose - must not be able to hold the event loop while every
37
- * rule walks it.
39
+ * rule walks it. A bound only helps while that cost stays linear: a pattern
40
+ * 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.
38
42
  *
39
43
  * The bound is safe because it is four times what can ship: the shared buffer
40
44
  * truncates entries to 4 KB, so bytes beyond this window were never going to
@@ -42,6 +46,11 @@ const MAX_PARTIAL_LINE_LENGTH = 8 * 1024;
42
46
  * inside this window, so it is redacted before the cut can split it.
43
47
  */
44
48
  const MAX_PARSED_LINE_LENGTH = 16 * 1024;
49
+ /**
50
+ * Longest `context` the collector accepts. It does not cut a longer one down:
51
+ * it refuses the whole batch the line rides in, traces and metrics included.
52
+ */
53
+ const MAX_CONTEXT_LENGTH = 255;
45
54
  const FORWARDED_STREAMS = ["stdout", "stderr"];
46
55
  let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderService {
47
56
  options;
@@ -187,7 +196,15 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
187
196
  const contextTraceId = store?.get(this.options.traceIdKey);
188
197
  // The line's own trace id wins: it was captured when the log was written,
189
198
  // whereas the async store is read now and may already have moved on.
190
- const traceId = parsed.traceId ?? contextTraceId;
199
+ //
200
+ // Only an id shaped like one, though. It is read off text, and anyone who
201
+ // gets a newline into a logged value can end a line with whatever
202
+ // `Trace ID:` they like - so it is held to the rule a client-supplied
203
+ // `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)
205
+ ? parsed.traceId
206
+ : undefined;
207
+ const traceId = lineTraceId ?? contextTraceId;
191
208
  return {
192
209
  timestamp: Date.now(),
193
210
  traceId,
@@ -199,7 +216,9 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
199
216
  ? store?.get(CALLER_METADATA_KEY)
200
217
  : undefined,
201
218
  level: parsed.level,
202
- context: parsed.context,
219
+ context: parsed.context === undefined
220
+ ? undefined
221
+ : this.toContext(parsed.context),
203
222
  // Redaction happens here, before the entry reaches the shared buffer -
204
223
  // which is also before the buffer truncates oversized lines. That order is
205
224
  // deliberate: truncating first would cut a long secret in half and ship
@@ -212,6 +231,19 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
212
231
  : parsed.message,
213
232
  };
214
233
  }
234
+ /**
235
+ * A context is normally a class name, but it is read off the line like the
236
+ * message, so it holds whatever was written there - a secret passed where a
237
+ * context was expected (`logger.log("login", "token=" + token)`) included.
238
+ * Redacted as the message is, and before the cut for the same reason, then
239
+ * cut to what the collector accepts.
240
+ */
241
+ toContext(context) {
242
+ const redacted = this.redactor
243
+ ? this.redactor.redactMessage(context)
244
+ : context;
245
+ return fitToLength(redacted, MAX_CONTEXT_LENGTH);
246
+ }
215
247
  };
216
248
  StdoutForwarderService = StdoutForwarderService_1 = __decorate([
217
249
  Injectable(),
@@ -1,14 +1,17 @@
1
1
  /**
2
2
  * Explains a 429 from the collector in the operator's terms.
3
3
  *
4
- * The collector refuses ingest for three different reasons, and until this
4
+ * The collector refuses ingest for several different reasons, and until this
5
5
  * existed the agent reported all of them as "the account may be out of
6
6
  * credits or over budget" - which sent an operator whose card had been
7
7
  * declined to the pricing page, and one whose rate cap had engaged to their
8
8
  * invoices. The body tells them apart: a quota refusal carries
9
9
  * `code: "USAGE_LIMIT_REACHED"` with the plan and the counts, and a quota
10
- * refusal caused by a declined payment adds `reason: "payment_failed"`. A
11
- * rate cap, and any older collector, sends neither and gets the old sentence.
10
+ * refusal caused by a declined payment adds `reason: "payment_failed"`.
11
+ * Credentials the collector has already rejected carry
12
+ * `code: "CREDENTIALS_REJECTED"` - a 429 rather than another 401, so that
13
+ * agents which pause only on a 429 stop retrying them. A rate cap, and any
14
+ * older collector, sends none of these and gets the old sentence.
12
15
  *
13
16
  * Written self-contained on purpose - no imports, no module-scope constants -
14
17
  * because the telemetry worker is a stringified function and this travels
@@ -1,14 +1,17 @@
1
1
  /**
2
2
  * Explains a 429 from the collector in the operator's terms.
3
3
  *
4
- * The collector refuses ingest for three different reasons, and until this
4
+ * The collector refuses ingest for several different reasons, and until this
5
5
  * existed the agent reported all of them as "the account may be out of
6
6
  * credits or over budget" - which sent an operator whose card had been
7
7
  * declined to the pricing page, and one whose rate cap had engaged to their
8
8
  * invoices. The body tells them apart: a quota refusal carries
9
9
  * `code: "USAGE_LIMIT_REACHED"` with the plan and the counts, and a quota
10
- * refusal caused by a declined payment adds `reason: "payment_failed"`. A
11
- * rate cap, and any older collector, sends neither and gets the old sentence.
10
+ * refusal caused by a declined payment adds `reason: "payment_failed"`.
11
+ * Credentials the collector has already rejected carry
12
+ * `code: "CREDENTIALS_REJECTED"` - a 429 rather than another 401, so that
13
+ * agents which pause only on a 429 stop retrying them. A rate cap, and any
14
+ * older collector, sends none of these and gets the old sentence.
12
15
  *
13
16
  * Written self-contained on purpose - no imports, no module-scope constants -
14
17
  * because the telemetry worker is a stringified function and this travels
@@ -22,6 +25,12 @@ export const describeIngestRefusal = (body) => {
22
25
  const detail = body !== null && typeof body === "object"
23
26
  ? body
24
27
  : {};
28
+ if (detail.code === "CREDENTIALS_REJECTED") {
29
+ // Nothing to do with the account's usage: the credentials are wrong and
30
+ // the process reads them once, so the fix is valid ones and a restart.
31
+ // The pause that follows only stops the agent asking in the meantime.
32
+ return "appKey and appSecret were rejected; check that both are valid for this application, then restart the process, which reads them once at start-up";
33
+ }
25
34
  if (detail.code !== "USAGE_LIMIT_REACHED") {
26
35
  return "the account may be out of credits or over budget";
27
36
  }
@@ -12,8 +12,9 @@
12
12
  * Nothing is ever dropped for being unparseable. A log the agent does not
13
13
  * understand is still the log the user is looking for.
14
14
  */
15
+ import type { LogLevel } from "@nestjs/common";
15
16
  export interface ParsedLogLine {
16
- level?: string;
17
+ level?: LogLevel;
17
18
  context?: string;
18
19
  message: string;
19
20
  traceId?: string;
@@ -23,14 +23,46 @@ const ANSI_PATTERN = /\x1B\[[0-9;]*[A-Za-z]/g;
23
23
  * Nest's default ConsoleLogger line:
24
24
  * [Nest] 1234 - 07/29/2026, 10:42:18 AM LOG [AppController] message
25
25
  * The context bracket is optional - `logger.log()` without a context omits it.
26
+ * The level is right-aligned in seven columns, so `VERBOSE` follows the
27
+ * timestamp after a single space and every other level after several.
28
+ *
29
+ * Must stay linear in the length of the line: it runs on every line the
30
+ * process writes, synchronously inside `process.stdout.write`, on text a caller
31
+ * can shape. The pattern this replaced read `.+?\s{2,}` here - two quantifiers
32
+ * that could both take the same run of whitespace - and backtracked cubically
33
+ * on a `[Nest]` line that never reached a level: seconds for a few thousand
34
+ * spaces. Here no two neighbouring quantifiers can take the same character.
35
+ * The timestamp opens with a non-space, exactly one whitespace character
36
+ * precedes the level, and nothing after the level can fail.
26
37
  */
27
- const NEST_TEXT_PATTERN = /^\[Nest\]\s+\d+\s+-\s+.+?\s{2,}(FATAL|ERROR|WARN|LOG|DEBUG|VERBOSE)\s+(?:\[([^\]]+)\]\s*)?([\s\S]*)$/;
38
+ const NEST_TEXT_PATTERN = /^\[Nest\]\s+\d+\s+-\s+\S.*?\s(FATAL|ERROR|WARN|LOG|DEBUG|VERBOSE)\s+(?:\[([^\]]+)\]\s*)?([\s\S]*)$/;
28
39
  /**
29
- * Suffix appended by LoggerPatcherService when a trace is in scope. Parsing it
30
- * back off recovers the trace id even for lines whose async context is gone by
31
- * the time the forwarder sees them.
40
+ * Marker LoggerPatcherService puts before the trace id it appends when a trace
41
+ * is in scope. Parsing the id back off recovers it even for lines whose async
42
+ * context is gone by the time the forwarder sees them.
32
43
  */
33
- const TRACE_ID_SUFFIX_PATTERN = /\s*Trace ID:\s*(\S+)\s*$/;
44
+ const TRACE_ID_MARKER = "Trace ID:";
45
+ /** What may follow the marker: one token, and nothing after it. */
46
+ const TRACE_ID_VALUE_PATTERN = /^\s*(\S+)\s*$/;
47
+ /**
48
+ * The levels the collector accepts, which are Nest's own. It refuses a batch
49
+ * carrying any other value whole - every trace and metric in it lost over one
50
+ * log line - so nothing else is ever put in `level`.
51
+ */
52
+ const LOG_LEVELS = new Set([
53
+ "fatal",
54
+ "error",
55
+ "warn",
56
+ "log",
57
+ "debug",
58
+ "verbose",
59
+ ]);
60
+ /** Other loggers' names for a level the collector models. */
61
+ const LEVEL_ALIASES = new Map([
62
+ ["info", "log"],
63
+ ["warning", "warn"],
64
+ ["trace", "verbose"],
65
+ ]);
34
66
  /**
35
67
  * Keys the JSON logger sets that map onto modelled columns; anything else a
36
68
  * service attaches is preserved under `attributes`.
@@ -71,9 +103,13 @@ function parseStructured(line) {
71
103
  if (typeof record.message !== "string") {
72
104
  return null;
73
105
  }
74
- const attributes = Object.fromEntries(Object.entries(record).filter(([key]) => !STRUCTURED_KEYS.has(key)));
106
+ const level = toLogLevel(record.level);
107
+ const attributes = Object.fromEntries(Object.entries(record).filter(
108
+ // A level the collector does not model - pino's numeric ones, a logger's
109
+ // own `notice` - stays an attribute rather than being dropped.
110
+ ([key]) => !STRUCTURED_KEYS.has(key) || (key === "level" && level === undefined)));
75
111
  return {
76
- level: typeof record.level === "string" ? record.level : undefined,
112
+ level,
77
113
  context: typeof record.context === "string" ? record.context : undefined,
78
114
  traceId: typeof record.traceId === "string" ? record.traceId : undefined,
79
115
  message: record.message,
@@ -86,11 +122,38 @@ function parseNestText(line) {
86
122
  return null;
87
123
  }
88
124
  const [, level, context, rest] = match;
89
- const traceIdMatch = TRACE_ID_SUFFIX_PATTERN.exec(rest);
125
+ const { message, traceId } = splitTraceIdSuffix(rest);
90
126
  return {
91
- level: level.toLowerCase(),
127
+ level: toLogLevel(level),
92
128
  context: context || undefined,
93
- traceId: traceIdMatch?.[1],
94
- message: traceIdMatch ? rest.slice(0, traceIdMatch.index).trimEnd() : rest,
129
+ traceId,
130
+ message,
95
131
  };
96
132
  }
133
+ /**
134
+ * Splits the trace id suffix off the end of a message, when there is one.
135
+ *
136
+ * Found with `lastIndexOf` rather than an unanchored `\s*Trace ID:...$`
137
+ * pattern, which retried its leading `\s*` from every offset - quadratic in a
138
+ * long run of whitespace, and that whitespace can come from a caller. Only the
139
+ * last marker can be the suffix anyway: the marker itself contains a space, so
140
+ * an earlier one is always followed by more than one token.
141
+ */
142
+ function splitTraceIdSuffix(rest) {
143
+ const markerIndex = rest.lastIndexOf(TRACE_ID_MARKER);
144
+ if (markerIndex === -1) {
145
+ return { message: rest };
146
+ }
147
+ const value = TRACE_ID_VALUE_PATTERN.exec(rest.slice(markerIndex + TRACE_ID_MARKER.length));
148
+ if (!value) {
149
+ return { message: rest };
150
+ }
151
+ return { message: rest.slice(0, markerIndex).trimEnd(), traceId: value[1] };
152
+ }
153
+ function toLogLevel(value) {
154
+ if (typeof value !== "string") {
155
+ return undefined;
156
+ }
157
+ const lower = value.toLowerCase();
158
+ return LOG_LEVELS.has(lower) ? lower : LEVEL_ALIASES.get(lower);
159
+ }
@@ -84,8 +84,13 @@ function buildDefaultRules(literalValuesOnly = false) {
84
84
  replace: (replacement, prefix) => `${prefix}${replacement}`,
85
85
  },
86
86
  // Bare JWTs - they show up outside any header often enough to matter.
87
+ //
88
+ // Must not follow a token character, rather than `\b`: a hyphen is a word
89
+ // boundary but also a token character, so under `\b` every `eyJ` in a run
90
+ // like `eyJ-eyJ-eyJ-...` started a match that rescanned the rest of the
91
+ // run - quadratic, on a line a caller can fill.
87
92
  {
88
- pattern: /\beyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]*/g,
93
+ pattern: /(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]*/g,
89
94
  replace: (replacement) => replacement,
90
95
  },
91
96
  // AWS access key ids. Distinctive enough to match on sight; the matching
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.3.10",
3
+ "version": "0.3.12",
4
4
  "description": "Observability and APM agent for NestJS - traces, runtime metrics and custom metrics",
5
5
  "author": "Kamil Mysliwiec",
6
6
  "homepage": "https://observe.nestjs.com",