@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
@@ -1,5 +1,6 @@
1
1
  import { readFileSync, realpathSync } from "fs";
2
2
  import { resolve, sep } from "path";
3
+ import { fileURLToPath } from "url";
3
4
  import { resolveOriginalPosition } from "./source-map-resolver.util.js";
4
5
  const DEFAULT_LINES_OF_CONTEXT = 5;
5
6
  /**
@@ -25,6 +26,31 @@ const MAX_FRAMES = 20;
25
26
  * deleted file is not retried on every single throw.
26
27
  */
27
28
  const sourceCache = new Map();
29
+ /** Each redactor's copy of a cached source, held as long as the source is. */
30
+ const redactedSources = new WeakMap();
31
+ /**
32
+ * The whole file redacted, rather than the frame cut from it. A rule that
33
+ * knows a secret by both its ends - a PEM key's BEGIN and END lines - finds
34
+ * neither in a frame whose edge falls inside the key, and the lines between
35
+ * would ship as they are. Cached against the source's own array, which the
36
+ * file and source-map caches keep stable, so each file is redacted once.
37
+ */
38
+ function redactedSource(source, redactor) {
39
+ if (!redactor) {
40
+ return source;
41
+ }
42
+ let byRedactor = redactedSources.get(redactor);
43
+ if (!byRedactor) {
44
+ byRedactor = new WeakMap();
45
+ redactedSources.set(redactor, byRedactor);
46
+ }
47
+ let redacted = byRedactor.get(source);
48
+ if (!redacted) {
49
+ redacted = redactor.redactSource(source);
50
+ byRedactor.set(source, redacted);
51
+ }
52
+ return redacted;
53
+ }
28
54
  /** What opens every V8 frame line. */
29
55
  const FRAME_PREFIX = /^\s*at\s+/;
30
56
  /**
@@ -91,11 +117,20 @@ function frameLines(stack, message) {
91
117
  headerEnd = stack.indexOf("\n");
92
118
  }
93
119
  else {
94
- const at = stack.indexOf(message);
95
- if (at === -1 || stack.lastIndexOf("\n", at) !== -1) {
96
- return [];
97
- }
98
- headerEnd = at + message.length;
120
+ // A match that starts on the first line and runs to the end of a line
121
+ // has one possible place: the message's first line has to end where the
122
+ // stack's first line does. That steps over a match inside the name -
123
+ // `UnauthorizedException: Unauthorized` - and it is computed rather than
124
+ // searched for. Neither string is bounded here, nor certain to be what
125
+ // V8 wrote - a driver can copy both off a server's reply - and visiting
126
+ // every match on a first line that repeats the message was quadratic.
127
+ const stackLineEnd = stack.indexOf("\n");
128
+ const messageLineEnd = message.indexOf("\n");
129
+ const at = stackLineEnd - (messageLineEnd === -1 ? message.length : messageLineEnd);
130
+ headerEnd =
131
+ at >= 0 && at < stackLineEnd && stack.startsWith(message, at)
132
+ ? at + message.length
133
+ : -1;
99
134
  }
100
135
  if (headerEnd === -1 || stack[headerEnd] !== "\n") {
101
136
  return [];
@@ -150,6 +185,23 @@ function parseFrameLine(raw) {
150
185
  column: Number(column),
151
186
  };
152
187
  }
188
+ /**
189
+ * A frame's file as a path. V8 names an ES module's file by its URL -
190
+ * `at run (file:///app/dist/main.js:3:9)` - which is the same file as the
191
+ * path a CommonJS frame carries. `undefined` for a URL that names no local
192
+ * file.
193
+ */
194
+ function toFilePath(file) {
195
+ if (!file.startsWith("file://")) {
196
+ return file;
197
+ }
198
+ try {
199
+ return fileURLToPath(file);
200
+ }
201
+ catch {
202
+ return undefined;
203
+ }
204
+ }
153
205
  function parseFrames(stack, message) {
154
206
  const frames = [];
155
207
  for (const raw of frameLines(stack, message)) {
@@ -157,8 +209,9 @@ function parseFrames(stack, message) {
157
209
  if (!parsed) {
158
210
  continue;
159
211
  }
160
- const { file, line, column } = parsed;
161
- if (isIgnored(file)) {
212
+ const { line, column } = parsed;
213
+ const file = toFilePath(parsed.file);
214
+ if (file === undefined || isIgnored(file)) {
162
215
  continue;
163
216
  }
164
217
  // Only absolute paths can be read back off disk. Anything else (an eval
@@ -169,10 +222,20 @@ function parseFrames(stack, message) {
169
222
  if (!isReadableSourcePath(file)) {
170
223
  continue;
171
224
  }
172
- frames.push({ file, line, column });
225
+ frames.push({ file, path: resolve(file), line, column });
173
226
  }
174
227
  return frames;
175
228
  }
229
+ function rememberSource(file, lines) {
230
+ if (sourceCache.size >= MAX_CACHED_FILES) {
231
+ const oldest = sourceCache.keys().next().value;
232
+ if (oldest !== undefined) {
233
+ sourceCache.delete(oldest);
234
+ }
235
+ }
236
+ sourceCache.set(file, lines);
237
+ }
238
+ /** The lines of `file`, a resolved path. */
176
239
  function readSource(file) {
177
240
  if (sourceCache.has(file)) {
178
241
  return sourceCache.get(file);
@@ -185,8 +248,18 @@ function readSource(file) {
185
248
  // resolved path has to clear the same gate. The root is resolved too: a
186
249
  // working directory reached through a link is otherwise outside itself.
187
250
  const real = realpathSync(file);
188
- if (isReadableSourcePath(real, realpathSync(process.cwd()))) {
251
+ if (real !== file && sourceCache.has(real)) {
252
+ // Another name for a file already read - a directory link inside the
253
+ // application, which can even lead back to where it sits and so spell
254
+ // one file endlessly. It shares that file's lines rather than holding
255
+ // a copy of its own.
256
+ lines = sourceCache.get(real);
257
+ }
258
+ else if (isReadableSourcePath(real, realpathSync(process.cwd()))) {
189
259
  lines = readFileSync(real, "utf8").split("\n");
260
+ if (real !== file) {
261
+ rememberSource(real, lines);
262
+ }
190
263
  }
191
264
  }
192
265
  catch {
@@ -194,13 +267,7 @@ function readSource(file) {
194
267
  // build. Cached as a miss so it is not retried on the next throw.
195
268
  lines = null;
196
269
  }
197
- if (sourceCache.size >= MAX_CACHED_FILES) {
198
- const oldest = sourceCache.keys().next().value;
199
- if (oldest !== undefined) {
200
- sourceCache.delete(oldest);
201
- }
202
- }
203
- sourceCache.set(file, lines);
270
+ rememberSource(file, lines);
204
271
  return lines;
205
272
  }
206
273
  /**
@@ -245,10 +312,11 @@ export function collectCodeFrames(stack, options = {}) {
245
312
  const codeFrames = [];
246
313
  for (const frame of frames) {
247
314
  let file = frame.file;
315
+ let path = frame.path;
248
316
  let line = frame.line;
249
317
  let source = null;
250
318
  if (options.sourceMaps) {
251
- const original = resolveOriginalPosition(frame.file, frame.line, frame.column);
319
+ const original = resolveOriginalPosition(frame.path, frame.line, frame.column);
252
320
  if (original) {
253
321
  // Re-apply the in-app filter to the mapped path: a frame in
254
322
  // dist/main.js can map back into node_modules, and that is still noise.
@@ -264,13 +332,14 @@ export function collectCodeFrames(stack, options = {}) {
264
332
  continue;
265
333
  }
266
334
  file = original.file;
335
+ path = resolve(original.file);
267
336
  line = original.line;
268
337
  // Prefer the map's embedded copy - it is the source this build was
269
338
  // compiled from, and it works when the source tree is not deployed.
270
339
  source = original.content ?? null;
271
340
  }
272
341
  }
273
- source ??= readSource(file);
342
+ source ??= readSource(path);
274
343
  if (!source) {
275
344
  continue;
276
345
  }
@@ -285,7 +354,7 @@ export function collectCodeFrames(stack, options = {}) {
285
354
  file,
286
355
  line,
287
356
  firstLine,
288
- lines: source.slice(firstLine - 1, lastLine),
357
+ lines: redactedSource(source, options.redactor).slice(firstLine - 1, lastLine),
289
358
  });
290
359
  }
291
360
  return codeFrames.length ? codeFrames : undefined;
@@ -60,6 +60,7 @@ function readMapFor(file) {
60
60
  return {
61
61
  tracer: new TraceMap(JSON.parse(rawMap)),
62
62
  mapDir,
63
+ contentLines: new Map(),
63
64
  };
64
65
  }
65
66
  catch {
@@ -102,13 +103,18 @@ export function resolveOriginalPosition(file, line, column) {
102
103
  // `sourcesContent` is the reliable path: the original text is embedded in the
103
104
  // map, so it works even when the source tree is absent at runtime (a container
104
105
  // shipping only dist, for instance).
105
- const embedded = sourceContentFor(map.tracer, position.source);
106
+ let content = map.contentLines.get(position.source);
107
+ if (!map.contentLines.has(position.source)) {
108
+ const embedded = sourceContentFor(map.tracer, position.source);
109
+ content = embedded ? embedded.split("\n") : undefined;
110
+ map.contentLines.set(position.source, content);
111
+ }
106
112
  return {
107
113
  file: position.source.startsWith("/")
108
114
  ? position.source
109
115
  : resolve(map.mapDir, position.source),
110
116
  line: position.line,
111
- content: embedded ? embedded.split("\n") : undefined,
117
+ content,
112
118
  };
113
119
  }
114
120
  /** Testing seam - the caches are process-lifetime otherwise. */
@@ -62,6 +62,26 @@ export declare function inboundTraceContext(headers: Record<string, unknown> | u
62
62
  * `traceIdFromTraceparent` writes it.
63
63
  */
64
64
  export declare function inboundTraceId(headers: Record<string, unknown> | undefined): string | undefined;
65
+ /**
66
+ * The W3C trace context a queue job or a microservice message runs in -
67
+ * `inboundTraceContext`'s counterpart for work handed on with a `traceparent`
68
+ * (see `traceparentToHandOn`), whose span the exporter puts under it. That is
69
+ * the span an OpenTelemetry SDK in this process has open for the work, when
70
+ * it is in that trace - an instrumentation that covers the hop opens one:
71
+ * `bullmq-otel` for a job, the SDK's gRPC, Kafka or RabbitMQ instrumentation
72
+ * for a message - else the `traceparent` itself.
73
+ *
74
+ * Only a `traceparent` in the trace `traceId` - the Observe trace id the work
75
+ * runs under - maps onto, as `continueHandedOnTrace` takes it: job options and
76
+ * packet metadata are writable by anything that reaches Redis or the socket.
77
+ *
78
+ * And only a sampled one, which a request's `traceparent` need not be. The
79
+ * agent hands work on unsampled when the operation that sent it was not
80
+ * recorded, naming a span that exists nowhere; or its caller sampled the
81
+ * trace out, and nothing upstream exports it. Either way there is no parent
82
+ * to put the work's span under, so it stays as it was without one.
83
+ */
84
+ export declare function handedOnTraceContext(traceparent: unknown, traceId: string): TraceContext | undefined;
65
85
  /**
66
86
  * The W3C trace id an Observe trace id goes out under.
67
87
  *
@@ -48,8 +48,11 @@ export function readTraceContext(headers) {
48
48
  return undefined;
49
49
  }
50
50
  const context = {
51
- traceId,
52
- parentSpanId,
51
+ // Copied: a capture is a slice of the header, and would keep all of it
52
+ // alive for as long as the context - in the OTLP retry queue, that can
53
+ // be long. A version past 00 may carry anything after its flags.
54
+ traceId: copyOf(traceId),
55
+ parentSpanId: copyOf(parentSpanId),
53
56
  sampled: (parseInt(flags, 16) & 0x01) === 0x01,
54
57
  };
55
58
  const traceState = fitTraceState(headers?.["tracestate"]);
@@ -72,8 +75,10 @@ function fitTraceState(value) {
72
75
  if (!trimmed || !TRACE_STATE_PATTERN.test(trimmed)) {
73
76
  return undefined;
74
77
  }
78
+ // Copied, here and below: what `trim` and `split` give back are slices of
79
+ // the value, however long it was.
75
80
  if (trimmed.length <= MAX_TRACE_STATE_LENGTH) {
76
- return trimmed;
81
+ return copyOf(trimmed);
77
82
  }
78
83
  let fitted = "";
79
84
  for (const entry of trimmed.split(",")) {
@@ -87,7 +92,15 @@ function fitTraceState(value) {
87
92
  }
88
93
  fitted = next;
89
94
  }
90
- return fitted || undefined;
95
+ return fitted ? copyOf(fitted) : undefined;
96
+ }
97
+ /**
98
+ * `text`, which is printable ASCII, as a string that shares no memory with
99
+ * what it was cut from. V8 keeps a substring as a slice of its source, so a
100
+ * 32-character trace id would otherwise hold a header of any length.
101
+ */
102
+ function copyOf(text) {
103
+ return Buffer.from(text, "latin1").toString("latin1");
91
104
  }
92
105
  /**
93
106
  * The trace id a `traceparent` header carries, written as a UUID - the
@@ -126,6 +139,35 @@ export function inboundTraceId(headers) {
126
139
  const traceId = inboundTraceContext(headers)?.traceId;
127
140
  return traceId === undefined ? undefined : toUuid(traceId);
128
141
  }
142
+ /**
143
+ * The W3C trace context a queue job or a microservice message runs in -
144
+ * `inboundTraceContext`'s counterpart for work handed on with a `traceparent`
145
+ * (see `traceparentToHandOn`), whose span the exporter puts under it. That is
146
+ * the span an OpenTelemetry SDK in this process has open for the work, when
147
+ * it is in that trace - an instrumentation that covers the hop opens one:
148
+ * `bullmq-otel` for a job, the SDK's gRPC, Kafka or RabbitMQ instrumentation
149
+ * for a message - else the `traceparent` itself.
150
+ *
151
+ * Only a `traceparent` in the trace `traceId` - the Observe trace id the work
152
+ * runs under - maps onto, as `continueHandedOnTrace` takes it: job options and
153
+ * packet metadata are writable by anything that reaches Redis or the socket.
154
+ *
155
+ * And only a sampled one, which a request's `traceparent` need not be. The
156
+ * agent hands work on unsampled when the operation that sent it was not
157
+ * recorded, naming a span that exists nowhere; or its caller sampled the
158
+ * trace out, and nothing upstream exports it. Either way there is no parent
159
+ * to put the work's span under, so it stays as it was without one.
160
+ */
161
+ export function handedOnTraceContext(traceparent, traceId) {
162
+ const handedOn = typeof traceparent === "string"
163
+ ? readTraceContext({ traceparent })
164
+ : undefined;
165
+ if (!handedOn?.sampled || handedOn.traceId !== w3cTraceIdOf(traceId)) {
166
+ return undefined;
167
+ }
168
+ const active = traceContextOfSpan(activeOpenTelemetrySpanContext());
169
+ return active?.traceId === handedOn.traceId ? active : handedOn;
170
+ }
129
171
  /**
130
172
  * An OpenTelemetry span context as the trace context an operation runs in,
131
173
  * the span becoming the operation's parent - or `undefined` for one the spec
@@ -140,8 +182,10 @@ function traceContextOfSpan(spanContext) {
140
182
  return undefined;
141
183
  }
142
184
  const context = {
143
- traceId: spanContext.traceId,
144
- parentSpanId: spanContext.spanId,
185
+ // Copied: the SDK's ids for a span with a remote parent are substrings
186
+ // of the carrier its propagator read, and would keep all of it alive.
187
+ traceId: copyOf(spanContext.traceId),
188
+ parentSpanId: copyOf(spanContext.spanId),
145
189
  sampled: (spanContext.traceFlags & 0x01) === 0x01,
146
190
  };
147
191
  let traceState;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.3.24",
3
+ "version": "0.3.26",
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",
@@ -163,6 +163,8 @@
163
163
  "@types/supertest": "7.2.1",
164
164
  "@types/ws": "8.18.1",
165
165
  "@vitest/coverage-v8": "4.1.11",
166
+ "amqp-connection-manager": "5.0.1",
167
+ "amqplib": "2.2.0",
166
168
  "bull": "4.16.5",
167
169
  "bullmq": "6.2.0",
168
170
  "bullmq-otel": "2.0.1",
@@ -172,6 +174,7 @@
172
174
  "graphql": "16.14.2",
173
175
  "husky": "9.1.7",
174
176
  "ioredis": "6.0.0",
177
+ "kafkajs": "2.2.4",
175
178
  "lint-staged": "17.6.0",
176
179
  "mongodb": "7.6.0",
177
180
  "mongoose": "9.10.1",