@nestjs/observe 0.3.25 → 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 (94) hide show
  1. package/README.md +17 -0
  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 +41 -17
  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 +158 -96
  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.js +7 -3
  34. package/dist/otlp/otlp-trace-exporter.service.js +63 -5
  35. package/dist/outgoing/http.integration.d.ts +8 -4
  36. package/dist/outgoing/http.integration.js +13 -6
  37. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  38. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  39. package/dist/outgoing/llm/llm-providers.js +72 -22
  40. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  41. package/dist/outgoing/llm/llm-usage.js +72 -25
  42. package/dist/outgoing/mssql.integration.js +16 -2
  43. package/dist/outgoing/mysql2.integration.js +17 -1
  44. package/dist/outgoing/outgoing-observe-agent.service.js +15 -3
  45. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  46. package/dist/outgoing/pg.integration.d.ts +3 -2
  47. package/dist/outgoing/pg.integration.js +39 -11
  48. package/dist/outgoing/sql-statement.util.js +106 -14
  49. package/dist/outgoing/undici.integration.d.ts +13 -0
  50. package/dist/outgoing/undici.integration.js +68 -0
  51. package/dist/protocols/bull-observe-agent.service.js +2 -12
  52. package/dist/protocols/deferred-trace-completion.d.ts +9 -1
  53. package/dist/protocols/deferred-trace-completion.js +36 -6
  54. package/dist/protocols/graphql-observe-agent.service.d.ts +36 -5
  55. package/dist/protocols/graphql-observe-agent.service.js +166 -5
  56. package/dist/protocols/graphql-operation-parser.js +72 -18
  57. package/dist/protocols/http-observe-agent.service.d.ts +43 -9
  58. package/dist/protocols/http-observe-agent.service.js +177 -59
  59. package/dist/protocols/job-trace-runner.d.ts +35 -3
  60. package/dist/protocols/job-trace-runner.js +126 -29
  61. package/dist/protocols/queue-observe-agent.service.js +44 -20
  62. package/dist/protocols/rpc-observe-agent.service.d.ts +50 -8
  63. package/dist/protocols/rpc-observe-agent.service.js +187 -47
  64. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  65. package/dist/protocols/ws-observe-agent.service.js +226 -20
  66. package/dist/services/index.d.ts +1 -1
  67. package/dist/services/index.js +1 -1
  68. package/dist/services/logger-patcher.service.js +3 -4
  69. package/dist/services/operation-trace.registry.d.ts +45 -1
  70. package/dist/services/operation-trace.registry.js +418 -35
  71. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  72. package/dist/services/stdout-forwarder.service.js +288 -51
  73. package/dist/services/tracer.service.d.ts +23 -0
  74. package/dist/services/tracer.service.js +91 -5
  75. package/dist/utils/capture-request.util.d.ts +3 -1
  76. package/dist/utils/capture-request.util.js +100 -12
  77. package/dist/utils/fit-to-length.util.js +33 -10
  78. package/dist/utils/log-line.parser.d.ts +14 -0
  79. package/dist/utils/log-line.parser.js +7 -3
  80. package/dist/utils/log-redactor.d.ts +14 -0
  81. package/dist/utils/log-redactor.js +512 -61
  82. package/dist/utils/operation-state.util.d.ts +39 -0
  83. package/dist/utils/operation-state.util.js +50 -0
  84. package/dist/utils/redact-url-query.d.ts +26 -4
  85. package/dist/utils/redact-url-query.js +184 -32
  86. package/dist/utils/sensitive-keys.d.ts +4 -1
  87. package/dist/utils/sensitive-keys.js +48 -10
  88. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  89. package/dist/utils/shared-hook-slot.util.js +103 -0
  90. package/dist/utils/source-context.util.d.ts +8 -0
  91. package/dist/utils/source-context.util.js +88 -24
  92. package/dist/utils/source-map-resolver.util.js +8 -2
  93. package/dist/utils/trace-context.util.js +21 -6
  94. package/package.json +2 -2
@@ -2,6 +2,7 @@
2
2
  * Reading token usage out of a model provider's response - a JSON body, or
3
3
  * the events of a server-sent stream - without ever keeping its text.
4
4
  */
5
+ import { topLevelModel } from "./llm-providers.js";
5
6
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6
7
  const count = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0
7
8
  ? Math.round(value)
@@ -103,10 +104,14 @@ const EDGE_BYTES = 32 * 1024;
103
104
  * A larger body - a long completion, a batch of embeddings - is not kept: its
104
105
  * first and last 32 KB are, and the usage is matched out of those. Every
105
106
  * provider writes `usage` after the content and `model` before it.
107
+ *
108
+ * The bytes are copied, not the chunks kept: a chunk object costs a few
109
+ * hundred bytes of heap whatever it holds, and the sender decides how the
110
+ * body is cut - one byte at a time, a 2 MB body would be held a hundred
111
+ * times over.
106
112
  */
107
113
  export class JsonUsageReader {
108
- chunks = [];
109
- size = 0;
114
+ body = new Bytes(MAX_JSON_BYTES);
110
115
  head;
111
116
  tail;
112
117
  push(chunk) {
@@ -114,20 +119,23 @@ export class JsonUsageReader {
114
119
  this.tail = keepTail(this.tail, chunk, EDGE_BYTES);
115
120
  return;
116
121
  }
117
- this.chunks.push(chunk);
118
- this.size += chunk.byteLength;
119
- if (this.size > MAX_JSON_BYTES) {
120
- const whole = concat(this.chunks, this.size);
121
- this.head = whole.subarray(0, EDGE_BYTES);
122
- this.tail = whole.subarray(whole.byteLength - EDGE_BYTES);
123
- this.chunks.length = 0;
122
+ if (this.body.size + chunk.byteLength <= MAX_JSON_BYTES) {
123
+ this.body.append(chunk);
124
+ return;
124
125
  }
126
+ const kept = this.body.view();
127
+ this.head =
128
+ kept.byteLength >= EDGE_BYTES
129
+ ? kept.slice(0, EDGE_BYTES)
130
+ : concat([kept, chunk.subarray(0, EDGE_BYTES - kept.byteLength)], Math.min(EDGE_BYTES, kept.byteLength + chunk.byteLength));
131
+ this.tail = keepTail(kept, chunk, EDGE_BYTES);
132
+ this.body = new Bytes(0);
125
133
  }
126
134
  finish() {
127
135
  const decoder = new TextDecoder();
128
136
  if (!this.head) {
129
137
  try {
130
- return usageFromDocument(JSON.parse(decoder.decode(concat(this.chunks, this.size))));
138
+ return usageFromDocument(JSON.parse(decoder.decode(this.body.view())));
131
139
  }
132
140
  catch {
133
141
  return {};
@@ -157,10 +165,10 @@ function usageFromEdges(head, tail) {
157
165
  if (cached && usage.cachedInputTokens === undefined) {
158
166
  usage.cachedInputTokens = Number(cached[1]);
159
167
  }
160
- const model = /"model"\s*:\s*"([^"\\]{1,128})"/.exec(head)?.[1];
168
+ const model = topLevelModel(head);
161
169
  return { ...usage, ...(model ? { model } : {}) };
162
170
  }
163
- /** Longest stream line examined. Longer lines carry content, not usage. */
171
+ /** Longest stream line examined, in bytes. Longer lines carry content, not usage. */
164
172
  const MAX_SSE_LINE = 1024 * 1024;
165
173
  /**
166
174
  * Reads a server-sent event stream as it passes through, one line at a time.
@@ -168,11 +176,16 @@ const MAX_SSE_LINE = 1024 * 1024;
168
176
  * Only `data:` lines that can carry usage or a model are parsed - the first
169
177
  * event, and any that mention `usage` - so a long stream of text deltas costs
170
178
  * a substring search per line rather than a parse.
179
+ *
180
+ * A line still arriving is held as bytes, copied, and decoded once it is
181
+ * whole: grown a chunk at a time as a string, a line sent a byte at a time
182
+ * would be a million string objects. A line feed is never part of another
183
+ * UTF-8 character, so the bytes split into lines as the text does.
171
184
  */
172
185
  export class SseUsageReader {
173
186
  now;
174
187
  decoder = new TextDecoder();
175
- pending = "";
188
+ pending = new Bytes(MAX_SSE_LINE);
176
189
  skipping = false;
177
190
  usage = {};
178
191
  sawEvent = false;
@@ -182,10 +195,9 @@ export class SseUsageReader {
182
195
  this.now = now;
183
196
  }
184
197
  push(chunk) {
185
- const text = this.decoder.decode(chunk, { stream: true });
186
198
  let start = 0;
187
199
  for (;;) {
188
- const newline = text.indexOf("\n", start);
200
+ const newline = chunk.indexOf(0x0a, start);
189
201
  if (newline === -1) {
190
202
  break;
191
203
  }
@@ -193,29 +205,32 @@ export class SseUsageReader {
193
205
  // The oversized line ends here, unread.
194
206
  this.skipping = false;
195
207
  }
208
+ else if (this.pending.size === 0) {
209
+ this.line(this.decoder.decode(chunk.subarray(start, newline)));
210
+ }
196
211
  else {
197
- this.line(this.pending + text.slice(start, newline));
212
+ this.pending.append(chunk.subarray(start, newline));
213
+ this.line(this.decoder.decode(this.pending.view()));
198
214
  }
199
- this.pending = "";
215
+ this.pending.clear();
200
216
  start = newline + 1;
201
217
  }
202
- if (this.skipping) {
218
+ if (this.skipping || start === chunk.byteLength) {
203
219
  return;
204
220
  }
205
- const rest = text.slice(start);
206
- if (this.pending.length + rest.length > MAX_SSE_LINE) {
221
+ if (this.pending.size + chunk.byteLength - start > MAX_SSE_LINE) {
207
222
  // An oversized line is content; drop it until its end comes past.
208
- this.pending = "";
223
+ this.pending.clear();
209
224
  this.skipping = true;
210
225
  return;
211
226
  }
212
- this.pending += rest;
227
+ this.pending.append(chunk.subarray(start));
213
228
  }
214
229
  finish() {
215
- if (this.pending) {
216
- this.line(this.pending);
217
- this.pending = "";
230
+ if (this.pending.size > 0 && !this.skipping) {
231
+ this.line(this.decoder.decode(this.pending.view()));
218
232
  }
233
+ this.pending.clear();
219
234
  return this.usage;
220
235
  }
221
236
  line(raw) {
@@ -241,6 +256,38 @@ export class SseUsageReader {
241
256
  }
242
257
  }
243
258
  }
259
+ /**
260
+ * Bytes copied in as they arrive, into one buffer that doubles as it fills -
261
+ * up to `expected`, past it only as far as is needed.
262
+ */
263
+ class Bytes {
264
+ expected;
265
+ buffer = new Uint8Array(0);
266
+ size = 0;
267
+ constructor(expected) {
268
+ this.expected = expected;
269
+ }
270
+ append(chunk) {
271
+ const needed = this.size + chunk.byteLength;
272
+ if (needed > this.buffer.byteLength) {
273
+ const grown = new Uint8Array(Math.max(needed, Math.min(Math.max(this.buffer.byteLength * 2, 1024), this.expected)));
274
+ grown.set(this.view());
275
+ this.buffer = grown;
276
+ }
277
+ this.buffer.set(chunk, this.size);
278
+ this.size = needed;
279
+ }
280
+ view() {
281
+ return this.buffer.subarray(0, this.size);
282
+ }
283
+ /** Empties it, and lets a large buffer go rather than keep it for later. */
284
+ clear() {
285
+ this.size = 0;
286
+ if (this.buffer.byteLength > 64 * 1024) {
287
+ this.buffer = new Uint8Array(0);
288
+ }
289
+ }
290
+ }
244
291
  function concat(chunks, size) {
245
292
  const whole = new Uint8Array(size);
246
293
  let offset = 0;
@@ -131,6 +131,12 @@ function findExec(source, start) {
131
131
  }
132
132
  return undefined;
133
133
  }
134
+ /**
135
+ * The number of a procedure in a group, `EXEC dbo.Activate;2 'key'` - by now
136
+ * usually `;?`, or a digit a word runs on from. The call goes on after it: no
137
+ * statement opens with either, so this `;` cannot be the end of one.
138
+ */
139
+ const PROCEDURE_NUMBER = /;\s*[?\d]/y;
134
140
  function redactExecArguments(sql) {
135
141
  let text = sql;
136
142
  let searchFrom = 0;
@@ -166,7 +172,10 @@ function redactExecArguments(sql) {
166
172
  inQuotedIdentifier = true;
167
173
  }
168
174
  else if (text[end] === ";") {
169
- break;
175
+ PROCEDURE_NUMBER.lastIndex = end;
176
+ if (!PROCEDURE_NUMBER.test(text)) {
177
+ break;
178
+ }
170
179
  }
171
180
  end++;
172
181
  }
@@ -214,7 +223,12 @@ export function patchMssql(mssql, recorder) {
214
223
  sql = prepared;
215
224
  procedure = false;
216
225
  }
217
- const { operation, statement } = describeMssqlStatement(procedure ? `EXEC ${sql}` : sql, this.parent?.config?.options?.enableQuotedIdentifier !== false, !procedure);
226
+ // Names in double quotes only where the driver turns the setting on:
227
+ // its default and `true`. `null` sends no SET, and the session keeps
228
+ // the server's own setting, which is OFF as installed - there a double
229
+ // quote opens a string.
230
+ const quotedIdentifier = this.parent?.config?.options?.enableQuotedIdentifier;
231
+ const { operation, statement } = describeMssqlStatement(procedure ? `EXEC ${sql}` : sql, quotedIdentifier === undefined || quotedIdentifier === true, !procedure);
218
232
  const span = recorder.open("mssql", operation, statement === undefined
219
233
  ? { "db.system": "mssql" }
220
234
  : { "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
  *
@@ -115,11 +118,20 @@ let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class Outgoing
115
118
  this.patchDriver("mssql", "mssql", DRIVER_DEPENDENTS.mssql, (module) => patchMssql(module, recorder));
116
119
  }
117
120
  if (outgoing?.http !== false) {
121
+ // undici creates a request, and publishes the channel read below, in
122
+ // whatever context the dispatch that hands it to a client runs in -
123
+ // for a queued pool request or a followed redirect, another request's.
124
+ // Loaded by deep path: undici's entry point would install its own
125
+ // `Agent` as the global `fetch` dispatcher.
126
+ this.patchDriver("undici", "undici/lib/dispatcher/dispatcher-base", [], patchUndiciDispatch);
127
+ this.patchDriver("undici", "undici/lib/handler/unwrap-handler", [], patchUndiciUnwrap);
118
128
  const http = typeof outgoing?.http === "object" ? outgoing.http : {};
119
129
  this.unsubscribeHttp = subscribeOutgoingHttp(recorder, () => {
120
130
  const store = asyncLocalStorage.getStore();
121
- const traceId = store?.get(this.options.traceIdKey);
122
- if (typeof traceId !== "string") {
131
+ // A call a finished operation's timer makes, past the grace
132
+ // period, carries none of its ids.
133
+ const traceId = liveTraceId(store, this.options.traceIdKey);
134
+ if (traceId === undefined) {
123
135
  return undefined;
124
136
  }
125
137
  const traceContext = store?.get(TRACE_CONTEXT_KEY);
@@ -130,7 +142,7 @@ let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class Outgoing
130
142
  // `ObserveAgentSharedBuffer.isReporting`.
131
143
  () => this.options.openTelemetry === true &&
132
144
  http.traceContext !== false &&
133
- this.observeAgentSharedBuffer?.isReporting() === true);
145
+ this.observeAgentSharedBuffer?.isReporting() === true, toGlobalRegExp(this.options.http?.queryParamsObfuscateRegex));
134
146
  // Model calls are read off the spans above, so they go with them.
135
147
  if (outgoing?.llm !== false) {
136
148
  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,119 @@ 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.
24
103
  *
25
104
  * 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.
105
+ * (under ANSI_QUOTES a `"` name goes too), with backslash escapes in both,
106
+ * and `#` starts a comment. `--` does
107
+ * only before whitespace or a control character, as MySQL reads it:
108
+ * `credit--5` is `credit - -5`, and the rest of its line is still SQL, quotes
109
+ * and all. Its block comments do not nest.
29
110
  */
30
111
  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,
112
+ postgresql: /(?<nested>\/\*)|(?<comment>--[^\n]*)|(?<name>"(?:[^"]|"")*(?:"|$))|(?<![\w$])(?<escape>[eE])'(?:[^'\\]|\\[\s\S]?|'')*(?:'|$)|(?<plain>'(?:[^']|'')*(?:'|$))|(?<!\w)\$(?<tag>(?:[A-Za-z_\u0080-\uffff][\w\u0080-\uffff]*)?)\$[\s\S]*?(?:\$\k<tag>\$|$)/g,
113
+ mysql:
114
+ // eslint-disable-next-line no-control-regex -- MySQL's rule for `--`.
115
+ /(?<comment>\/\*[\s\S]*?(?:\*\/|$)|--(?=[\u0000-\u0020\u007f]|$)[^\n]*|#[^\n]*)|(?<name>`(?:[^`]|``)*(?:`|$))|(?<plain>'(?:[^'\\]|\\[\s\S]?|'')*(?:'|$)|"(?:[^"\\]|\\[\s\S]?|"")*(?:"|$))/g,
116
+ };
117
+ /**
118
+ * An odd run of backslashes before the quote a string opened with. Whether
119
+ * that quote ends the string is a session setting the statement does not
120
+ * show: Postgres's standard_conforming_strings, MySQL's NO_BACKSLASH_ESCAPES.
121
+ * Read the wrong way, everything after it is out of step - the SQL between
122
+ * literals masked and the literals shipped - so nothing after it is kept.
123
+ */
124
+ const ESCAPED_QUOTE = {
125
+ "'": /(?<!\\)(?:\\\\)*\\'/,
126
+ '"': /(?<!\\)(?:\\\\)*\\"/,
33
127
  };
34
128
  function stripLiteralsAndComments(sql, dialect) {
35
129
  const token = TOKEN[dialect];
@@ -49,10 +143,8 @@ function stripLiteralsAndComments(sql, dialect) {
49
143
  else if (name !== undefined) {
50
144
  text += name;
51
145
  }
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.
146
+ else if (plain !== undefined && ESCAPED_QUOTE[plain[0]].test(plain)) {
147
+ // Where this string ends is unknown, and so is everything after it.
56
148
  return `${text}?`;
57
149
  }
58
150
  else {
@@ -114,7 +206,7 @@ export function describeSanitizedSqlStatement(sql) {
114
206
  return { operation: "QUERY", statement };
115
207
  }
116
208
  const table = TABLE_AFTER[verb]
117
- ?.exec(statement)?.[1]
209
+ ?.exec(withoutFunctionArguments(statement))?.[1]
118
210
  ?.replace(/["`[\]]/g, "")
119
211
  .slice(0, MAX_IDENTIFIER_LENGTH);
120
212
  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;