@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
@@ -18,7 +18,11 @@ function describeMssqlStatement(sql, enableQuotedIdentifier, redactExecArgs = tr
18
18
  // first keeps comment markers inside strings and identifiers inert.
19
19
  // Double quotes follow connection options; SQL SET overrides are not tracked.
20
20
  // Binary literals may continue across lines after a backslash.
21
- const tokenPattern = /(?<comment>--[^\r\n]*)|\[(?:[^\]]|\]\])*(?:\]|$)|(?<quoted>"(?:[^"]|"")*(?:"|$))|(?<literal>N?'(?:[^']|'')*(?:'|$)|(?<![\w@])\$\s*[+-]?(?:\d+(?:\.\d*)?|\.\d+)|\b0x[\da-f]*(?:\\(?:\r\n|\r|\n)[\da-f]*)*|(?<![\w$@])-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?(?![\w]))|[^]/giy;
21
+ // No name starts with a digit, and T-SQL needs no space after a number:
22
+ // `42ORDER BY` is a number and a keyword, so the word that follows does not
23
+ // decide whether it is one. A digit after `#` is part of a name, `#2fa`,
24
+ // and `-0x1F` is a minus and a binary literal, not `-0` and a word.
25
+ const tokenPattern = /(?<comment>--[^\r\n]*)|\[(?:[^\]]|\]\])*(?:\]|$)|(?<quoted>"(?:[^"]|"")*(?:"|$))|(?<literal>N?'(?:[^']|'')*(?:'|$)|(?<![\w@])\$\s*[+-]?(?:\d+(?:\.\d*)?|\.\d+)|\b0x[\da-f]*(?:\\(?:\r\n|\r|\n)[\da-f]*)*|(?<![\w$@#])-?(?!0x)(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)|[^]/giy;
22
26
  for (let index = 0; index < input.length;) {
23
27
  if (input.startsWith("/*", index)) {
24
28
  let depth = 1;
@@ -57,9 +61,10 @@ function describeMssqlStatement(sql, enableQuotedIdentifier, redactExecArgs = tr
57
61
  // Anchored at the run's start. Unanchored, the engine tried every position
58
62
  // inside each run of word characters and backtracked the run each time:
59
63
  // quadratic, 0.1 s of a blocked event loop for one 8 KB name. The sign is
60
- // a number cut between its exponent's sign and digits, `987654e+`, which
61
- // the tokenizer could not read as a number and left as text.
62
- text = text.replace(/(^|[^\p{L}\p{M}\p{N}_$@#])[\p{L}\p{M}\p{N}_$@#]+[+-]?$/u, "$1?");
64
+ // a number cut between its exponent's sign and digits, `987654e+`: the
65
+ // tokenizer read its digits as a number and left `e+` as text, so the `?`
66
+ // of the digits goes with the word.
67
+ text = text.replace(/(^|[^\p{L}\p{M}\p{N}_$@#])\??[\p{L}\p{M}\p{N}_$@#]+[+-]?$/u, "$1?");
63
68
  }
64
69
  // `;WITH` is how T-SQL is often written, to end whatever came before.
65
70
  text = text.replace(/^[\s;]+/, "");
@@ -131,6 +136,12 @@ function findExec(source, start) {
131
136
  }
132
137
  return undefined;
133
138
  }
139
+ /**
140
+ * The number of a procedure in a group, `EXEC dbo.Activate;2 'key'` - by now
141
+ * usually `;?`, or a digit a word runs on from. The call goes on after it: no
142
+ * statement opens with either, so this `;` cannot be the end of one.
143
+ */
144
+ const PROCEDURE_NUMBER = /;\s*[?\d]/y;
134
145
  function redactExecArguments(sql) {
135
146
  let text = sql;
136
147
  let searchFrom = 0;
@@ -166,7 +177,10 @@ function redactExecArguments(sql) {
166
177
  inQuotedIdentifier = true;
167
178
  }
168
179
  else if (text[end] === ";") {
169
- break;
180
+ PROCEDURE_NUMBER.lastIndex = end;
181
+ if (!PROCEDURE_NUMBER.test(text)) {
182
+ break;
183
+ }
170
184
  }
171
185
  end++;
172
186
  }
@@ -214,7 +228,12 @@ export function patchMssql(mssql, recorder) {
214
228
  sql = prepared;
215
229
  procedure = false;
216
230
  }
217
- const { operation, statement } = describeMssqlStatement(procedure ? `EXEC ${sql}` : sql, this.parent?.config?.options?.enableQuotedIdentifier !== false, !procedure);
231
+ // Names in double quotes only where the driver turns the setting on:
232
+ // its default and `true`. `null` sends no SET, and the session keeps
233
+ // the server's own setting, which is OFF as installed - there a double
234
+ // quote opens a string.
235
+ const quotedIdentifier = this.parent?.config?.options?.enableQuotedIdentifier;
236
+ const { operation, statement } = describeMssqlStatement(procedure ? `EXEC ${sql}` : sql, quotedIdentifier === undefined || quotedIdentifier === true, !procedure);
218
237
  const span = recorder.open("mssql", operation, statement === undefined
219
238
  ? { "db.system": "mssql" }
220
239
  : { "db.system": "mssql", "db.statement": statement });
@@ -1,3 +1,4 @@
1
+ import { AsyncResource } from "node:async_hooks";
1
2
  import { patchMethod } from "./patch-method.util.js";
2
3
  import { describeSqlStatement } from "./sql-statement.util.js";
3
4
  /** Marks a command that already has a span, however it reaches a connection. */
@@ -17,6 +18,13 @@ export function patchMysql2(mysql2, recorder) {
17
18
  if (typeof first === "object" && first?.[SPANNED]) {
18
19
  return original.apply(this, args);
19
20
  }
21
+ const last = args.length - 1;
22
+ // mysql2 answers from the connection's socket, whose events fire in the
23
+ // context of the call that opened it - another request's. Bound first,
24
+ // so a call that is not recorded keeps its own context too.
25
+ if (typeof args[last] === "function") {
26
+ args[last] = AsyncResource.bind(args[last]);
27
+ }
20
28
  const sql = typeof first === "string" ? first : first?.sql;
21
29
  if (typeof sql !== "string") {
22
30
  return original.apply(this, args);
@@ -35,7 +43,6 @@ export function patchMysql2(mysql2, recorder) {
35
43
  // connection's `execute` reports a failed prepare to the callback it
36
44
  // was given, whatever `onResult` has been replaced with since.
37
45
  let hasCallback = false;
38
- const last = args.length - 1;
39
46
  if (typeof args[last] === "function") {
40
47
  const callback = args[last];
41
48
  hasCallback = true;
@@ -85,5 +92,14 @@ export function patchMysql2(mysql2, recorder) {
85
92
  patchMethod(mysql2.Connection?.prototype, method, wrap),
86
93
  patchMethod(mysql2.Pool?.prototype, method, wrap),
87
94
  ]);
95
+ // A queued checkout is handed its connection on a tick scheduled by
96
+ // whichever call releases one: bound, it runs where it was asked for -
97
+ // under the pool's span and its cover, or under no trace at all.
98
+ patchMethod(mysql2.Pool?.prototype, "getConnection", (original) => function (...args) {
99
+ if (typeof args[0] === "function") {
100
+ args[0] = AsyncResource.bind(args[0]);
101
+ }
102
+ return original.apply(this, args);
103
+ });
88
104
  return patched.some(Boolean);
89
105
  }
@@ -17,6 +17,7 @@ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.j
17
17
  import { OBSERVE_OPTIONS, TRACE_CONTEXT_KEY } from "../observe.constants.js";
18
18
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
19
19
  import { loadAsResolvedBy, loadOptionalPeer, } from "../utils/optional-peer.util.js";
20
+ import { toGlobalRegExp } from "../utils/redact-url-query.js";
20
21
  import { subscribeOutgoingHttp } from "./http.integration.js";
21
22
  import { activateLlmFetchObserver, llmCallsOff, uninstallLlmFetchObserver, } from "./llm/llm-fetch.integration.js";
22
23
  import { patchMongodb } from "./mongodb.integration.js";
@@ -24,6 +25,8 @@ import { patchMssql } from "./mssql.integration.js";
24
25
  import { patchMysql2 } from "./mysql2.integration.js";
25
26
  import { OutgoingSpanRecorder } from "./outgoing-span.recorder.js";
26
27
  import { patchPg } from "./pg.integration.js";
28
+ import { patchUndiciDispatch, patchUndiciUnwrap, } from "./undici.integration.js";
29
+ import { liveTraceId } from "../utils/operation-state.util.js";
27
30
  /**
28
31
  * Spans for what leaves the process: database queries and outbound HTTP.
29
32
  *
@@ -112,14 +115,27 @@ let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class Outgoing
112
115
  this.patchDriver("pg", "pg", DRIVER_DEPENDENTS.pg, (module) => patchPg(module, recorder));
113
116
  this.patchDriver("mysql2", "mysql2", DRIVER_DEPENDENTS.mysql2, (module) => patchMysql2(module, recorder));
114
117
  this.patchDriver("mongodb", "mongodb/lib/cmap/connection", DRIVER_DEPENDENTS.mongodb, (module) => patchMongodb(module, recorder));
115
- this.patchDriver("mssql", "mssql", DRIVER_DEPENDENTS.mssql, (module) => patchMssql(module, recorder));
118
+ // The class that is patched, not `mssql` itself: loading that entry
119
+ // makes tedious the driver of every request mssql creates on its own
120
+ // behalf, which breaks an application that runs on
121
+ // `mssql/msnodesqlv8`.
122
+ this.patchDriver("mssql", "mssql/lib/tedious/request", DRIVER_DEPENDENTS.mssql, (Request) => patchMssql({ Request }, recorder));
116
123
  }
117
124
  if (outgoing?.http !== false) {
125
+ // undici creates a request, and publishes the channel read below, in
126
+ // whatever context the dispatch that hands it to a client runs in -
127
+ // for a queued pool request or a followed redirect, another request's.
128
+ // Loaded by deep path: undici's entry point would install its own
129
+ // `Agent` as the global `fetch` dispatcher.
130
+ this.patchDriver("undici", "undici/lib/dispatcher/dispatcher-base", [], patchUndiciDispatch);
131
+ this.patchDriver("undici", "undici/lib/handler/unwrap-handler", [], patchUndiciUnwrap);
118
132
  const http = typeof outgoing?.http === "object" ? outgoing.http : {};
119
133
  this.unsubscribeHttp = subscribeOutgoingHttp(recorder, () => {
120
134
  const store = asyncLocalStorage.getStore();
121
- const traceId = store?.get(this.options.traceIdKey);
122
- if (typeof traceId !== "string") {
135
+ // A call a finished operation's timer makes, past the grace
136
+ // period, carries none of its ids.
137
+ const traceId = liveTraceId(store, this.options.traceIdKey);
138
+ if (traceId === undefined) {
123
139
  return undefined;
124
140
  }
125
141
  const traceContext = store?.get(TRACE_CONTEXT_KEY);
@@ -130,7 +146,7 @@ let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class Outgoing
130
146
  // `ObserveAgentSharedBuffer.isReporting`.
131
147
  () => this.options.openTelemetry === true &&
132
148
  http.traceContext !== false &&
133
- this.observeAgentSharedBuffer?.isReporting() === true);
149
+ this.observeAgentSharedBuffer?.isReporting() === true, toGlobalRegExp(this.options.http?.queryParamsObfuscateRegex));
134
150
  // Model calls are read off the spans above, so they go with them.
135
151
  if (outgoing?.llm !== false) {
136
152
  this.deactivateLlm = activateLlmFetchObserver(recorder, typeof outgoing?.llm === "object" ? outgoing.llm : {});
@@ -77,7 +77,7 @@ export class OutgoingSpanRecorder {
77
77
  }
78
78
  ended = true;
79
79
  clearTimeout(grace);
80
- this.operationTraceRegistry.internalEndTraceStep(registryKey, spanId, className, methodKey, spanId, error === undefined || error === null ? undefined : error);
80
+ this.operationTraceRegistry.internalEndTraceStep(registryKey, spanId, className, methodKey, spanId, error === undefined || error === null ? undefined : error, true);
81
81
  // A held span closes late; the call itself ended at `endedAt`.
82
82
  if (node && endedAt !== undefined && startTime !== undefined) {
83
83
  node.duration = Math.max(endedAt - startTime, 0);
@@ -154,11 +154,25 @@ export class OutgoingSpanRecorder {
154
154
  endWhenSettled(span, result) {
155
155
  const then = result?.then;
156
156
  if (typeof then === "function") {
157
- then.call(result, () => span.end(), (error) => span.end(error));
157
+ then.call(result, () => endQuietly(span), (error) => endQuietly(span, error));
158
158
  }
159
159
  else {
160
- span.end();
160
+ endQuietly(span);
161
161
  }
162
162
  return result;
163
163
  }
164
164
  }
165
+ /**
166
+ * Ends a span whose closing must not reach the caller: the span is a side
167
+ * effect of the call, not part of its outcome. Thrown from the side branch a
168
+ * promise is watched on, it would be a rejection nothing handles, and end the
169
+ * process; thrown on the spot, it would fail a call that succeeded.
170
+ */
171
+ function endQuietly(span, error) {
172
+ try {
173
+ span.end(error);
174
+ }
175
+ catch {
176
+ // Nothing to record it in.
177
+ }
178
+ }
@@ -15,8 +15,9 @@ interface PgModule {
15
15
  * up in; `Pool#query` is patched as well because it reaches the client from
16
16
  * inside the pool's checkout callback, which for a queued checkout runs in
17
17
  * whichever request released the connection - the span has to be opened
18
- * before that hop, in the caller's own context. The pool's span then covers
19
- * the client call it leads to.
18
+ * before that hop, in the caller's own context. `Pool#connect` hands the
19
+ * checkout back to that context, so the pool's span covers the client call
20
+ * it leads to.
20
21
  */
21
22
  export declare function patchPg(pg: PgModule, recorder: OutgoingSpanRecorder): boolean;
22
23
  export {};
@@ -1,3 +1,4 @@
1
+ import { AsyncResource } from "node:async_hooks";
1
2
  import { patchMethod } from "./patch-method.util.js";
2
3
  import { describeSqlStatement } from "./sql-statement.util.js";
3
4
  /**
@@ -8,11 +9,19 @@ import { describeSqlStatement } from "./sql-statement.util.js";
8
9
  * up in; `Pool#query` is patched as well because it reaches the client from
9
10
  * inside the pool's checkout callback, which for a queued checkout runs in
10
11
  * whichever request released the connection - the span has to be opened
11
- * before that hop, in the caller's own context. The pool's span then covers
12
- * the client call it leads to.
12
+ * before that hop, in the caller's own context. `Pool#connect` hands the
13
+ * checkout back to that context, so the pool's span covers the client call
14
+ * it leads to.
13
15
  */
14
16
  export function patchPg(pg, recorder) {
15
17
  const wrap = (covers) => (original) => function (...args) {
18
+ const last = args.length - 1;
19
+ // pg answers from the connection's socket, whose events fire in the
20
+ // context of the call that opened it - another request's. Bound first,
21
+ // so a call that is not recorded keeps its own context too.
22
+ if (typeof args[last] === "function") {
23
+ args[last] = AsyncResource.bind(args[last]);
24
+ }
16
25
  const config = args[0];
17
26
  const text = typeof config === "string" ? config : config?.text;
18
27
  // A submittable - a cursor, a query stream - reports completion
@@ -29,7 +38,6 @@ export function patchPg(pg, recorder) {
29
38
  return original.apply(this, args);
30
39
  }
31
40
  let hasCallback = false;
32
- const last = args.length - 1;
33
41
  if (typeof args[last] === "function") {
34
42
  const callback = args[last];
35
43
  hasCallback = true;
@@ -38,16 +46,27 @@ export function patchPg(pg, recorder) {
38
46
  return callback.call(this, error, ...rest);
39
47
  };
40
48
  }
41
- else if (typeof config?.callback === "function") {
42
- const callback = config.callback;
49
+ else if (!covers && typeof config?.callback === "function") {
50
+ // Only a client calls a config's `callback`. A pool answers through
51
+ // its promise and hands the client a callback of its own, which pg
52
+ // stores on the config: one a pool has run before carries a
53
+ // `callback` that is not the caller's, and that nothing calls again.
54
+ const callback = AsyncResource.bind(config.callback);
43
55
  hasCallback = true;
44
- args[0] = {
45
- ...config,
46
- callback(error, ...rest) {
47
- span.end(error);
48
- return callback.call(this, error, ...rest);
56
+ // Derived from the caller's config rather than copied from it: a
57
+ // statement object (sql-template-tag, sql-template-strings) keeps
58
+ // `text` on its prototype, where a spread does not reach.
59
+ args[0] = Object.create(config, {
60
+ callback: {
61
+ value(error, ...rest) {
62
+ span.end(error);
63
+ return callback.call(this, error, ...rest);
64
+ },
65
+ writable: true,
66
+ enumerable: true,
67
+ configurable: true,
49
68
  },
50
- };
69
+ });
51
70
  }
52
71
  try {
53
72
  const result = covers
@@ -62,5 +81,14 @@ export function patchPg(pg, recorder) {
62
81
  };
63
82
  const client = patchMethod(pg.Client?.prototype, "query", wrap(false));
64
83
  const pool = patchMethod(pg.Pool?.prototype, "query", wrap(true));
84
+ // A queued checkout is handed its client by whichever call releases one:
85
+ // bound, it runs where it was asked for - under the pool's span and its
86
+ // cover, or under no trace at all - not in the releasing request.
87
+ patchMethod(pg.Pool?.prototype, "connect", (original) => function (...args) {
88
+ if (typeof args[0] === "function") {
89
+ args[0] = AsyncResource.bind(args[0]);
90
+ }
91
+ return original.apply(this, args);
92
+ });
65
93
  return client || pool;
66
94
  }
@@ -11,25 +11,147 @@ const TABLE_AFTER = {
11
11
  REPLACE: /\bINTO\s+([\w."`[\]]+)/i,
12
12
  UPDATE: /^\s*UPDATE\s+(?:ONLY\s+)?([\w."`[\]]+)/i,
13
13
  };
14
+ /**
15
+ * Words that put a table or a subquery, not a function's arguments, in the
16
+ * parenthesis after them.
17
+ */
18
+ const NOT_A_FUNCTION = new Set([
19
+ "ALL",
20
+ "AND",
21
+ "ANY",
22
+ "AS",
23
+ "EXCEPT",
24
+ "EXISTS",
25
+ "FROM",
26
+ "IN",
27
+ "INTERSECT",
28
+ "JOIN",
29
+ "LATERAL",
30
+ "NOT",
31
+ "ON",
32
+ "OR",
33
+ "SELECT",
34
+ "SOME",
35
+ "UNION",
36
+ "USING",
37
+ "VALUES",
38
+ "WHERE",
39
+ "WITH",
40
+ ]);
41
+ /** Whether the parenthesis at `index` opens a function's arguments. */
42
+ function opensArguments(statement, index) {
43
+ let end = index;
44
+ if (statement[end - 1] === " ") {
45
+ end--;
46
+ }
47
+ let start = end;
48
+ while (start > 0 && /[\w$]/.test(statement[start - 1])) {
49
+ start--;
50
+ }
51
+ return (start < end &&
52
+ /^[A-Za-z_]/.test(statement[start]) &&
53
+ !NOT_A_FUNCTION.has(statement.slice(start, end).toUpperCase()));
54
+ }
55
+ /**
56
+ * `statement` with what a function's arguments hold left out:
57
+ * `EXTRACT(EPOCH FROM created_at)` and `TRIM(BOTH ' ' FROM name)` have a
58
+ * `FROM` that is an argument, not the table. A parenthesis counts as one when
59
+ * a name comes right before it. One after `FROM` or `JOIN` - a derived table,
60
+ * a subquery, a parenthesised join - is kept as it is. Only what a function
61
+ * holds is taken out, so every `FROM` left is followed by what followed it
62
+ * before. One pass, so it stays linear however deeply the parentheses nest.
63
+ */
64
+ function withoutFunctionArguments(statement) {
65
+ let text = "";
66
+ let copied = 0;
67
+ // How deep inside a function's arguments `index` is, 0 outside any.
68
+ let depth = 0;
69
+ for (let index = 0; index < statement.length; index++) {
70
+ const char = statement[index];
71
+ if (char === "(") {
72
+ if (depth) {
73
+ depth++;
74
+ }
75
+ else if (opensArguments(statement, index)) {
76
+ text += statement.slice(copied, index);
77
+ copied = index;
78
+ depth = 1;
79
+ }
80
+ }
81
+ else if (char === ")" && depth && !--depth) {
82
+ text += "()";
83
+ copied = index + 1;
84
+ }
85
+ }
86
+ // Arguments that never close are kept as they are.
87
+ return text + statement.slice(copied);
88
+ }
14
89
  /**
15
90
  * Comments, quoted names and literals, found left to right: a comment marker
16
91
  * inside a string, or a quote inside a comment or a name, is part of the token
17
92
  * it is in. Each runs to the end of the input when nothing closes it. Names
18
93
  * are kept, comments become a space and literals `?`.
19
94
  *
20
- * Postgres quotes names in `"`. A plain string takes a backslash as it is and
21
- * an `E'...'` string as an escape. A dollar quote opens only where a token
22
- * can start - Postgres reads `a$b$` as one name - and block comments nest, so
23
- * `/*` is matched alone and its end found by hand.
95
+ * Postgres quotes names in `"` alone. A backtick quotes nothing there: it is
96
+ * a character operators are spelled with (PGroonga's ``&` ``), and what
97
+ * follows it is read like any other text. A plain string takes a backslash
98
+ * as it is and an `E'...'` string as an escape. A dollar quote opens only
99
+ * where a token can start - Postgres reads `a$b$` as one name - and its tag
100
+ * is empty, or a letter, `_` or non-ASCII character followed by any of those
101
+ * or digits, so `$q1$` opens one and `$1` stays a placeholder. Block
102
+ * comments nest, so `/*` is matched alone and its end found by hand. A `--`
103
+ * comment ends at a carriage return as well as a line feed: Postgres reads
104
+ * either as the end of the line, and a comment run on past a lone `\r` would
105
+ * have the SQL after it, quotes and all, read as part of it.
24
106
  *
25
107
  * MySQL quotes strings in `"` as well as `'`, as its default sql_mode does
26
- * (under ANSI_QUOTES a `"` name goes too), with backslash escapes in both -
27
- * NO_BACKSLASH_ESCAPES is not assumed - and `#` starts a comment. Its block
28
- * comments do not nest.
108
+ * (under ANSI_QUOTES a `"` name goes too), with backslash escapes in both,
109
+ * and `#` starts a comment. `--` does
110
+ * only before whitespace or a control character, as MySQL reads it:
111
+ * `credit--5` is `credit - -5`, and the rest of its line is still SQL, quotes
112
+ * and all. Its comments end at a line feed alone, as MySQL ends them, and
113
+ * its block comments do not nest.
29
114
  */
30
115
  const TOKEN = {
31
- postgresql: /(?<nested>\/\*)|(?<comment>--[^\n]*)|(?<name>"(?:[^"]|"")*(?:"|$)|`(?:[^`]|``)*(?:`|$))|(?<![\w$])(?<escape>[eE])'(?:[^'\\]|\\[\s\S]?|'')*(?:'|$)|(?<plain>'(?:[^']|'')*(?:'|$))|(?<!\w)\$(?<tag>[A-Za-z_]*)\$[\s\S]*?(?:\$\k<tag>\$|$)/g,
32
- mysql: /(?<comment>\/\*[\s\S]*?(?:\*\/|$)|--[^\n]*|#[^\n]*)|(?<name>`(?:[^`]|``)*(?:`|$))|'(?:[^'\\]|\\[\s\S]?|'')*(?:'|$)|"(?:[^"\\]|\\[\s\S]?|"")*(?:"|$)/g,
116
+ postgresql: /(?<nested>\/\*)|(?<comment>--[^\r\n]*)|(?<name>"(?:[^"]|"")*(?:"|$))|(?<![\w$])(?<escape>[eE])'(?:[^'\\]|\\[\s\S]?|'')*(?:'|$)|(?<plain>'(?:[^']|'')*(?:'|$))|(?<!\w)\$(?<tag>(?:[A-Za-z_\u0080-\uffff][\w\u0080-\uffff]*)?)\$[\s\S]*?(?:\$\k<tag>\$|$)/g,
117
+ mysql:
118
+ // eslint-disable-next-line no-control-regex -- MySQL's rule for `--`.
119
+ /(?<comment>\/\*[\s\S]*?(?:\*\/|$)|--(?=[\u0000-\u0020\u007f]|$)[^\n]*|#[^\n]*)|(?<name>`(?:[^`]|``)*(?:`|$))|(?<plain>'(?:[^'\\]|\\[\s\S]?|'')*(?:'|$)|"(?:[^"\\]|\\[\s\S]?|"")*(?:"|$))/g,
120
+ };
121
+ /**
122
+ * A number that is not part of an identifier or a `$1` placeholder: hex,
123
+ * binary and octal too, digits grouped with `_` (Postgres 16), and a point
124
+ * with no digit after it, `3.e15`, which is one number to both dialects.
125
+ *
126
+ * The server needs no space after a number, so the word that follows does
127
+ * not decide whether it is one: `-0.141588WHERE`, and `219099999AND` before
128
+ * Postgres 15, are a number and a keyword. No Postgres name starts with a
129
+ * digit. A MySQL name can, but only digits without a point or an exponent:
130
+ * `2fa_code` is a name, `1.5AND`, `.5AND` and `1e5OR` are not, and a point
131
+ * after a name is no decimal point, `t.2fa_code`. An integer run into a word
132
+ * is a name to MySQL, `219099999AND`, and is kept as one.
133
+ *
134
+ * Quoted names are matched first, so `"2fa_code"` and `"2022_sales"` stay as
135
+ * they are. Inside one, a number standing on its own goes as it always has -
136
+ * `"order 66"` is `"order ?"`, and `"4815162342"`, more likely a value quoted
137
+ * the wrong way than a column, is `"?"`.
138
+ */
139
+ const NUMBER = {
140
+ postgresql: /(?<name>"(?:[^"]|"")*")|(?<![\w$])-?(?:0x[\da-f_]+|0b[01_]+|0o[0-7_]+|\d[\d_]*(?:\.[\d_]*)?(?:e[+-]?\d[\d_]*)?)/gi,
141
+ mysql: /(?<name>`(?:[^`]|``)*`)|(?<![\w$])(?:(?:0x[\da-f_]+|0b[01_]+|0o[0-7_]+)(?!\w)|-?\d[\d_]*(?:\.[\d_]*(?:e[+-]?\d[\d_]*)?|e[+-]?\d[\d_]*|(?!\w))|(?<=(?<![\w$`])\.)\d[\d_]*)/gi,
142
+ };
143
+ /** A number within a quoted name: one no word character runs on from. */
144
+ const NUMBER_IN_NAME = /(?<![\w$])(?:0x[\da-f_]+|0b[01_]+|0o[0-7_]+|-?\d[\d_]*(?:\.[\d_]*)?(?:e[+-]?\d[\d_]*)?)(?!\w)/gi;
145
+ /**
146
+ * An odd run of backslashes before the quote a string opened with. Whether
147
+ * that quote ends the string is a session setting the statement does not
148
+ * show: Postgres's standard_conforming_strings, MySQL's NO_BACKSLASH_ESCAPES.
149
+ * Read the wrong way, everything after it is out of step - the SQL between
150
+ * literals masked and the literals shipped - so nothing after it is kept.
151
+ */
152
+ const ESCAPED_QUOTE = {
153
+ "'": /(?<!\\)(?:\\\\)*\\'/,
154
+ '"': /(?<!\\)(?:\\\\)*\\"/,
33
155
  };
34
156
  function stripLiteralsAndComments(sql, dialect) {
35
157
  const token = TOKEN[dialect];
@@ -49,10 +171,8 @@ function stripLiteralsAndComments(sql, dialect) {
49
171
  else if (name !== undefined) {
50
172
  text += name;
51
173
  }
52
- else if (plain !== undefined && /(?<!\\)(?:\\\\)*\\'/.test(plain)) {
53
- // An odd run of backslashes before a quote: with
54
- // standard_conforming_strings off, the quote does not end the string
55
- // here, so where it does end is unknown - and so is everything after.
174
+ else if (plain !== undefined && ESCAPED_QUOTE[plain[0]].test(plain)) {
175
+ // Where this string ends is unknown, and so is everything after it.
56
176
  return `${text}?`;
57
177
  }
58
178
  else {
@@ -89,15 +209,13 @@ function endOfNestedComment(sql, index) {
89
209
  */
90
210
  export function describeSqlStatement(sql, dialect) {
91
211
  const input = sql.slice(0, MAX_STATEMENT_LENGTH * 4);
92
- let sanitized = stripLiteralsAndComments(input, dialect)
93
- // A number that is not part of an identifier or a `$1` placeholder: hex,
94
- // binary and octal too, and digits grouped with `_` (Postgres 16).
95
- .replace(/(?<![\w$])(?:0x[\da-f_]+|0b[01_]+|0o[0-7_]+|-?\d[\d_]*(?:\.[\d_]+)?(?:e[+-]?\d[\d_]*)?)(?![\w])/gi, "?");
212
+ let sanitized = stripLiteralsAndComments(input, dialect).replace(NUMBER[dialect], (_number, name) => name?.replace(NUMBER_IN_NAME, "?") ?? "?");
96
213
  if (sql.length > input.length) {
97
- // The bound may have cut a number short - `987654e+` is no longer one -
98
- // so whatever word it cut goes too. Anchored at the run's start, which
214
+ // The bound may have cut a number short - `987654e+` is no longer one,
215
+ // and its digits are a `?` with `e+` after it - so whatever word it cut
216
+ // goes too, with the `?` before it. Anchored at the run's start, which
99
217
  // keeps it linear on a run 8 KB long.
100
- sanitized = sanitized.replace(/(^|[^\p{L}\p{M}\p{N}_$])[\p{L}\p{M}\p{N}_$]+[+-]?$/u, "$1?");
218
+ sanitized = sanitized.replace(/(^|[^\p{L}\p{M}\p{N}_$])\??[\p{L}\p{M}\p{N}_$]+[+-]?$/u, "$1?");
101
219
  }
102
220
  return describeSanitizedSqlStatement(sanitized);
103
221
  }
@@ -114,7 +232,7 @@ export function describeSanitizedSqlStatement(sql) {
114
232
  return { operation: "QUERY", statement };
115
233
  }
116
234
  const table = TABLE_AFTER[verb]
117
- ?.exec(statement)?.[1]
235
+ ?.exec(withoutFunctionArguments(statement))?.[1]
118
236
  ?.replace(/["`[\]]/g, "")
119
237
  .slice(0, MAX_IDENTIFIER_LENGTH);
120
238
  return { operation: table ? `${verb} ${table}` : verb, statement };
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `Dispatcher#dispatch` on undici's base class, which `Agent`, `Pool`,
3
+ * `Client` and the rest share, and which every layer passes a request
4
+ * through.
5
+ */
6
+ export declare function patchUndiciDispatch(module: unknown): boolean;
7
+ /**
8
+ * `UnwrapHandler.unwrap` on undici 7, which hands each layer below a new
9
+ * wrapper of the handler on every pass: the wrapper is filed under its
10
+ * handler's caller, so a later pass is recognised below a dispatcher
11
+ * composed - its `dispatch` bound - before the base class was patched.
12
+ */
13
+ export declare function patchUndiciUnwrap(module: unknown): boolean;
@@ -0,0 +1,68 @@
1
+ import { AsyncResource } from "node:async_hooks";
2
+ import { patchMethod } from "./patch-method.util.js";
3
+ /**
4
+ * The async context each request was first dispatched in, by its handler.
5
+ *
6
+ * undici creates a request - and publishes `undici:request:create`, which the
7
+ * HTTP integration reads the caller from - in whatever context the dispatch
8
+ * that gets it to a client runs in. The first pass through `dispatch` is the
9
+ * caller's own call. A later one may run from a socket's events, in the
10
+ * context of whichever request opened that socket: a bounded pool handing a
11
+ * queued request to a client as another one drains, a redirect or a retry
12
+ * re-dispatched from a response. Each later pass is run where the first was.
13
+ *
14
+ * Keyed by handler: undici's own `request`, `stream`, `pipeline` and `fetch`
15
+ * make one per request. An application that calls `dispatch()` itself with
16
+ * one handler for several requests gets them all filed under the first.
17
+ */
18
+ const callers = new WeakMap();
19
+ /**
20
+ * `Dispatcher#dispatch` on undici's base class, which `Agent`, `Pool`,
21
+ * `Client` and the rest share, and which every layer passes a request
22
+ * through.
23
+ */
24
+ export function patchUndiciDispatch(module) {
25
+ const base = defaultExport(module);
26
+ return patchMethod(base?.prototype, "dispatch", (original) => function (...args) {
27
+ const handler = args[1];
28
+ if (typeof handler !== "object" || handler === null) {
29
+ return original.apply(this, args);
30
+ }
31
+ const caller = callers.get(handler);
32
+ if (caller) {
33
+ return caller.runInAsyncScope(original, this, ...args);
34
+ }
35
+ callers.set(handler, new AsyncResource("ObserveUndiciDispatch"));
36
+ return original.apply(this, args);
37
+ });
38
+ }
39
+ /**
40
+ * `UnwrapHandler.unwrap` on undici 7, which hands each layer below a new
41
+ * wrapper of the handler on every pass: the wrapper is filed under its
42
+ * handler's caller, so a later pass is recognised below a dispatcher
43
+ * composed - its `dispatch` bound - before the base class was patched.
44
+ */
45
+ export function patchUndiciUnwrap(module) {
46
+ const unwrapHandler = defaultExport(module);
47
+ return patchMethod(unwrapHandler, "unwrap", (original) => function (handler) {
48
+ const wrapped = original.call(this, handler);
49
+ if (wrapped !== handler &&
50
+ typeof wrapped === "object" &&
51
+ wrapped !== null &&
52
+ typeof handler === "object" &&
53
+ handler !== null) {
54
+ let caller = callers.get(handler);
55
+ if (!caller) {
56
+ caller = new AsyncResource("ObserveUndiciDispatch");
57
+ callers.set(handler, caller);
58
+ }
59
+ callers.set(wrapped, caller);
60
+ }
61
+ return wrapped;
62
+ });
63
+ }
64
+ function defaultExport(module) {
65
+ return typeof module === "function"
66
+ ? module
67
+ : module?.default;
68
+ }
@@ -17,10 +17,30 @@ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.j
17
17
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
18
18
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
19
19
  import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
20
- import { JobTraceRunner } from "./job-trace-runner.js";
20
+ import { JobTraceRunner, readJobTimes } from "./job-trace-runner.js";
21
21
  const ORIGINAL_SET_HANDLER = Symbol.for("nestjs.observe.bull.setHandler");
22
22
  /** Bull names an unnamed job this; reporting it would name every job the same. */
23
23
  const BULL_DEFAULT_JOB_NAME = "__default__";
24
+ /** The longest delay a Node timer keeps; a longer one fires after 1 ms. */
25
+ const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
26
+ /**
27
+ * When Bull fails a run on its own, read off the job's `timeout` option as
28
+ * Bull reads it: it races the handler's promise against a timer of that many
29
+ * ms from the moment the handler returns, and fails the job once the timer
30
+ * wins. A falsy timeout and `Infinity` arm none. Any other value that is not
31
+ * a positive number - `-1`, `"50"` - makes that race throw, which fails the
32
+ * job at once, and one past what a timer can hold fires after 1 ms.
33
+ */
34
+ function readBullTimeout(opts) {
35
+ const timeout = opts?.timeout;
36
+ if (!timeout || timeout === Number.POSITIVE_INFINITY) {
37
+ return undefined;
38
+ }
39
+ if (typeof timeout !== "number" || timeout < 0) {
40
+ return 0;
41
+ }
42
+ return timeout > MAX_TIMER_DELAY_MS ? 1 : timeout;
43
+ }
24
44
  /**
25
45
  * Job tracing for the original Bull, which `@nestjs/bull` wraps - the same
26
46
  * snapshots `@nestjs/bullmq` produces, from a driver a large share of Nest
@@ -49,17 +69,7 @@ let BullObserveAgentService = BullObserveAgentService_1 = class BullObserveAgent
49
69
  return result.module?.prototype ?? null;
50
70
  }
51
71
  readQueueMetadata(job) {
52
- const metadata = {};
53
- if (typeof job.timestamp === "number") {
54
- metadata.enqueuedAt = new Date(job.timestamp).toISOString();
55
- const startedAt = typeof job.processedOn === "number" ? job.processedOn : Date.now();
56
- // As with BullMQ: a delay the caller asked for is a schedule, not a
57
- // backlog, so the wait is measured from when the job became runnable.
58
- // `||`, not `??`: the job's own `delay` reads 0 once Bull has promoted
59
- // it, and only the options still say what was asked for.
60
- const delay = job.delay || job.opts?.delay || 0;
61
- metadata.waitDuration = Math.max(0, startedAt - (job.timestamp + delay));
62
- }
72
+ const metadata = readJobTimes(job);
63
73
  if (typeof job.attemptsMade === "number") {
64
74
  metadata.attemptsMade = job.attemptsMade;
65
75
  }
@@ -106,6 +116,7 @@ let BullObserveAgentService = BullObserveAgentService_1 = class BullObserveAgent
106
116
  id: job.id,
107
117
  opts: job.opts,
108
118
  metadata: this.readQueueMetadata(job),
119
+ timeout: readBullTimeout(job.opts),
109
120
  });
110
121
  const runner = this.runner;
111
122
  if (handler.length > 1) {