@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
@@ -11,12 +11,19 @@
11
11
  * runs on every operation, so it stops at the first field of the first
12
12
  * operation definition and never looks at the rest of the document.
13
13
  */
14
- /** Operation keywords, mapped to the root type each one resolves against. */
15
- const ROOT_TYPE_BY_KEYWORD = {
16
- query: "Query",
17
- mutation: "Mutation",
18
- subscription: "Subscription",
19
- };
14
+ /**
15
+ * Operation keywords, mapped to the root type each one resolves against.
16
+ *
17
+ * A `Map`, not an object literal: the key is the first word of a client's
18
+ * document, and `constructor` or `__proto__` found an inherited member there,
19
+ * whose labelling then threw inside the request hook - a 500 for a document
20
+ * the server would have answered.
21
+ */
22
+ const ROOT_TYPE_BY_KEYWORD = new Map([
23
+ ["query", "Query"],
24
+ ["mutation", "Mutation"],
25
+ ["subscription", "Subscription"],
26
+ ]);
20
27
  /**
21
28
  * Parsed results are cached: a client sends the same handful of documents over
22
29
  * and over, and re-scanning each one per request is pure waste. Bounded in
@@ -147,19 +154,33 @@ function toOperation(words, fieldName, source) {
147
154
  }
148
155
  // Shorthand - `{ orders { id } }` - has no keyword at all and is a query.
149
156
  const keyword = words[0] ? words[0].toLowerCase() : "query";
150
- const rootTypeName = ROOT_TYPE_BY_KEYWORD[keyword];
157
+ const rootTypeName = ROOT_TYPE_BY_KEYWORD.get(keyword);
151
158
  if (!rootTypeName) {
152
159
  return undefined;
153
160
  }
161
+ const operationName = words[0] ? words[1] : undefined;
162
+ // Whitespace is collapsed only here, at the end: `source` positions have to
163
+ // stay valid while the scan is still reading from it.
164
+ const sanitizedDocument = truncate(source.replace(/\s+/g, " ").trim());
165
+ // All three are cut from a string the size of the document, and V8 makes a
166
+ // cut a view that keeps the whole string it was cut from in memory. They
167
+ // outlive the request, on its trace until the batch is flushed, so past
168
+ // what the trace records they are copied out: a 100 kB document whose 8 kB
169
+ // the trace sent kept the 100 kB, twice over.
170
+ if (source.length <= MAX_SANITIZED_DOCUMENT_LENGTH) {
171
+ return { rootTypeName, fieldName, operationName, sanitizedDocument };
172
+ }
154
173
  return {
155
174
  rootTypeName,
156
- fieldName,
157
- operationName: words[0] ? words[1] : undefined,
158
- // Whitespace is collapsed only here, at the end: `source` positions have to
159
- // stay valid while the scan is still reading from it.
160
- sanitizedDocument: truncate(source.replace(/\s+/g, " ").trim()),
175
+ fieldName: ownCopy(fieldName),
176
+ operationName: operationName === undefined ? undefined : ownCopy(operationName),
177
+ sanitizedDocument: ownCopy(sanitizedDocument),
161
178
  };
162
179
  }
180
+ /** The same code units, lone surrogates included, in storage of their own. */
181
+ function ownCopy(value) {
182
+ return Buffer.from(value, "utf16le").toString("utf16le");
183
+ }
163
184
  function truncate(document) {
164
185
  if (document.length <= MAX_SANITIZED_DOCUMENT_LENGTH) {
165
186
  return document;
@@ -206,42 +227,70 @@ function readFirstFieldName(source, from) {
206
227
  /**
207
228
  * Blanks out comments, strings and numbers, so none can be mistaken for a name
208
229
  * or a brace. Offsets are not preserved - nothing downstream maps back to the
209
- * original text.
230
+ * original text. A document with a string that is never closed is kept only
231
+ * up to its first string.
210
232
  */
211
233
  function stripIgnoredTokens(document) {
212
234
  let out = "";
213
235
  let index = 0;
236
+ // Where in `out` the document's first string went.
237
+ let firstString = -1;
214
238
  while (index < document.length) {
215
239
  const char = document[index];
240
+ // A comment ends at either line terminator, as graphql-js ends it. Read on
241
+ // to the next `\n`, it swallowed what the server reads after a bare `\r` -
242
+ // the opening quotes of a block string included.
216
243
  if (char === "#") {
217
- while (index < document.length && document[index] !== "\n") {
244
+ while (index < document.length &&
245
+ document[index] !== "\n" &&
246
+ document[index] !== "\r") {
218
247
  index += 1;
219
248
  }
220
249
  continue;
221
250
  }
222
251
  if (char === '"') {
223
- if (document.startsWith('"""', index)) {
224
- const end = document.indexOf('"""', index + 3);
225
- index = end === -1 ? document.length : end + 3;
252
+ if (firstString === -1) {
253
+ firstString = out.length;
226
254
  }
227
- else {
228
- index += 1;
229
- while (index < document.length && document[index] !== '"') {
230
- index += document[index] === "\\" ? 2 : 1;
231
- }
232
- index += 1;
255
+ index = document.startsWith('"""', index)
256
+ ? endOfBlockString(document, index + 3)
257
+ : endOfString(document, index + 1);
258
+ if (index === -1) {
259
+ // Never closed, so the server refuses the document - and its quotes
260
+ // do not pair. Paired regardless, a stray quote took the opening
261
+ // quote of the next literal for its close, and from there every
262
+ // string was recorded while the text between them was blanked. Which
263
+ // side of a quote is a literal cannot be told for the earlier quotes
264
+ // either: in `"24" monitor"`, the ` monitor` a user typed is already
265
+ // in `out`. Nothing from the first string on is recorded.
266
+ return out.slice(0, firstString) + "_";
233
267
  }
234
268
  // Left as a token that is neither a name nor a brace, so a default value
235
269
  // of `""` still reads as a value rather than as nothing at all.
236
270
  out += "_";
237
271
  continue;
238
272
  }
273
+ // A name is copied whole, so a digit that continues one (`field2`,
274
+ // `$var1`) never reaches the number rule below. Whether a digit belongs
275
+ // to a name is read from the document, never from `out`: the `_` a
276
+ // literal leaves there is a name character itself, so the number straight
277
+ // after one - `["draft"489213]`, commas being optional - read as its
278
+ // tail, and indexing a string built with `+=` copied all of it, once per
279
+ // digit.
280
+ if (isNameStart(char)) {
281
+ const start = index;
282
+ index += 1;
283
+ while (index < document.length && isNameChar(document[index])) {
284
+ index += 1;
285
+ }
286
+ out += document.slice(start, index);
287
+ continue;
288
+ }
239
289
  // Numbers go the same way as strings. An inline `verifyOtp(code: 489213)`
240
290
  // or `charge(amount: 1999)` is user data exactly as a string literal is,
241
- // and blanking it also keeps `first: 10` and `first: 20` one shape. A
242
- // digit that continues a name (`field2`, `$var1`) is not a literal.
291
+ // and blanking it also keeps `first: 10` and `first: 20` one shape.
243
292
  const startsNumber = isDigit(char) || (char === "-" && isDigit(document[index + 1] ?? ""));
244
- if (startsNumber && !isNameChar(out[out.length - 1] ?? "")) {
293
+ if (startsNumber) {
245
294
  index += 1;
246
295
  while (index < document.length && isNumberChar(document, index)) {
247
296
  index += 1;
@@ -254,6 +303,42 @@ function stripIgnoredTokens(document) {
254
303
  }
255
304
  return out;
256
305
  }
306
+ /**
307
+ * Where a block string that opened before `from` ends, its closing quotes
308
+ * included, or -1 when it is never closed. `\"""` is three quotes of content,
309
+ * as graphql-js reads it, not the end: ended there, the rest of the literal
310
+ * was recorded as document syntax. A block string has no other escape, so a
311
+ * backslash before the quotes always escapes them.
312
+ */
313
+ function endOfBlockString(document, from) {
314
+ let end = document.indexOf('"""', from);
315
+ while (end > from && document[end - 1] === "\\") {
316
+ end = document.indexOf('"""', end + 3);
317
+ }
318
+ return end === -1 ? -1 : end + 3;
319
+ }
320
+ /**
321
+ * Where a `"` string whose content starts at `from` ends, its closing quote
322
+ * included, or -1 when it is not closed on its line. graphql-js ends a string
323
+ * at a line terminator, and refuses it there: a quote found beyond one is the
324
+ * opening quote of the next literal. Only `\"` and `\\` are stepped over, so
325
+ * that a backslash cannot carry the scan past the line end either.
326
+ */
327
+ function endOfString(document, from) {
328
+ let index = from;
329
+ while (index < document.length) {
330
+ const char = document[index];
331
+ if (char === '"') {
332
+ return index + 1;
333
+ }
334
+ if (char === "\n" || char === "\r") {
335
+ return -1;
336
+ }
337
+ const next = document[index + 1];
338
+ index += char === "\\" && (next === '"' || next === "\\") ? 2 : 1;
339
+ }
340
+ return -1;
341
+ }
257
342
  function isDigit(char) {
258
343
  return char >= "0" && char <= "9";
259
344
  }
@@ -13,6 +13,18 @@ interface IncomingHttpRequest {
13
13
  protocol: string;
14
14
  headers?: Record<string, string | string[] | undefined>;
15
15
  }
16
+ /**
17
+ * Takes the adapter's request and response hooks over as soon as there is an
18
+ * adapter, so that hooks the application sets on it from then on run beside
19
+ * the agent's rather than in their place: from a provider, from `main.ts`
20
+ * before `listen()`. They have no getter, so a hook set on the adapter before
21
+ * it reached Nest cannot be found, and stays the agent's to replace. Called
22
+ * from the instance decorator, the moment Nest creates the `HttpAdapterHost`,
23
+ * and again from the agent, for an application without the decorator. On
24
+ * `init$` rather than the adapter itself: `@nestjs/testing` attaches the
25
+ * adapter only once the testing module is compiled.
26
+ */
27
+ export declare function shareHttpAdapterHooks(httpAdapterHost: Pick<HttpAdapterHost, "httpAdapter" | "init$">): void;
16
28
  export declare class HttpObserveAgentService<Store extends Record<string, unknown>> implements OnModuleInit, OnModuleDestroy {
17
29
  private readonly httpAdapterHost;
18
30
  private readonly asyncLocalStorage;
@@ -23,6 +35,23 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
23
35
  private readonly logger;
24
36
  private warnedAboutHooks;
25
37
  private httpAdapterInitSubscription;
38
+ /**
39
+ * The registry key each request was started under, by the Node request -
40
+ * see `nodeRequestOf` - which every adapter hands to both of its hooks. The
41
+ * response hook cannot ask the async store: it runs from `finish`, in the
42
+ * async context of whatever ended the response, and that need not be the
43
+ * request's own. A request pipelined behind another has its `finish`
44
+ * emitted from the earlier one's; a stream piped into the response ends it
45
+ * where its source emits - for a pooled database connection, in the
46
+ * request that opened it. Taken out by the first response hook to run, so
47
+ * a request routed twice is completed once.
48
+ */
49
+ private readonly registryKeys;
50
+ /**
51
+ * The store each request runs in, by the Node request, for a request that
52
+ * comes through the router again - see `startHttpRequestTracing`.
53
+ */
54
+ private readonly requestStores;
26
55
  /**
27
56
  * `http.queryParamsObfuscateRegex`, rebuilt with the global flag when it was
28
57
  * supplied without one. It is applied with `replaceAll`, which throws on a
@@ -35,12 +64,19 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
35
64
  onModuleInit(): void;
36
65
  onModuleDestroy(): void;
37
66
  registerHttpHooks(): void;
38
- startHttpRequestTracing(req: IncomingHttpRequest, res: unknown, done: () => void): void;
67
+ /**
68
+ * Opens the request's trace and calls `done` inside its store, handing back
69
+ * what `done` returns: an application's request hook runs inside it, and
70
+ * the adapter waits on or fails the request by what that hook returns.
71
+ */
72
+ startHttpRequestTracing(req: IncomingHttpRequest, res: unknown, done: () => unknown): unknown;
39
73
  endHttpRequestTracing(req: unknown, res: {
40
74
  statusCode: number;
41
75
  }): void;
42
76
  /**
43
- * Frees the trace when the client goes away before the response finishes.
77
+ * Ends the request's operation when its response closes - answered or
78
+ * aborted, recorded or not - and frees the trace when the client went away
79
+ * before the response finished.
44
80
  *
45
81
  * The adapter's response hook rides `res.on("finish")`, and an aborted
46
82
  * request never emits it - the socket emits `close` instead. Without this,
@@ -48,16 +84,21 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
48
84
  * of the process; on an ingest endpoint taking 16MB bodies over slow links,
49
85
  * aborts are routine, not exceptional.
50
86
  *
87
+ * Express and the Node adapter hand the request hook the Node response
88
+ * itself; Fastify hands it the reply, which is no emitter, with the Node
89
+ * response under it as `raw`.
90
+ *
51
91
  * On the normal path `close` follows `finish` with `writableFinished`
52
- * already true, so this stays a no-op there - `endHttpRequestTracing` has
53
- * either plucked the trace or is about to.
92
+ * already true, so the trace is left alone there - `endHttpRequestTracing`
93
+ * has either plucked it or is about to. A response that does not say is
94
+ * left alone too.
54
95
  *
55
- * Eviction is deferred, not immediate: Express does not cancel the handler
56
- * on abort, so its spans are usually still closing when `close` fires. The
57
- * grace period lets the handler drain first; `unref` keeps the timer from
58
- * holding a shutting-down process open.
96
+ * Dropped at once, not after a grace period: an abandoned trace is never
97
+ * reported, and the registry already lets a handler that outlives its
98
+ * client end its spans on a trace that is gone. Held for 30 s, it was the
99
+ * client's to say how many such traces the process kept.
59
100
  */
60
- private evictTraceOnClientAbort;
101
+ private watchResponseClose;
61
102
  /**
62
103
  * Whether the adapter has the hooks requests are traced through, warning
63
104
  * the first time it does not.