@nestjs/observe 0.3.24 → 0.3.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +26 -1
  2. package/dist/agent/detached-observe-worker.js +50 -6
  3. package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
  4. package/dist/agent/observe-agent.shared-buffer.js +196 -19
  5. package/dist/agent/observe-agent.worker.d.ts +22 -2
  6. package/dist/agent/observe-agent.worker.js +43 -7
  7. package/dist/agent/telemetry-wire-contract.js +7 -1
  8. package/dist/cli/agent-notes.js +16 -4
  9. package/dist/cli/link.js +28 -3
  10. package/dist/cli/observe-cli.js +1 -19
  11. package/dist/cli/open-url.d.ts +27 -0
  12. package/dist/cli/open-url.js +63 -0
  13. package/dist/cli/project-files.d.ts +42 -1
  14. package/dist/cli/project-files.js +146 -7
  15. package/dist/cli/project-setup.d.ts +6 -0
  16. package/dist/cli/project-setup.js +14 -1
  17. package/dist/cli/wire-application.js +6 -0
  18. package/dist/custom-metrics/counter.d.ts +13 -2
  19. package/dist/custom-metrics/counter.js +33 -16
  20. package/dist/custom-metrics/finite-value.util.d.ts +14 -0
  21. package/dist/custom-metrics/finite-value.util.js +33 -1
  22. package/dist/custom-metrics/gauge.d.ts +2 -0
  23. package/dist/custom-metrics/gauge.js +43 -21
  24. package/dist/custom-metrics/label-values.util.d.ts +37 -0
  25. package/dist/custom-metrics/label-values.util.js +51 -0
  26. package/dist/custom-metrics/summary.d.ts +23 -0
  27. package/dist/custom-metrics/summary.js +73 -2
  28. package/dist/instrument/create-instance-decorator.instrument.js +244 -97
  29. package/dist/interfaces/observe-options.interface.d.ts +3 -1
  30. package/dist/objectives/objectives.registry.js +12 -0
  31. package/dist/observe.module.js +119 -3
  32. package/dist/otlp/otlp-encoders.js +22 -5
  33. package/dist/otlp/otlp-span.mapper.d.ts +4 -3
  34. package/dist/otlp/otlp-span.mapper.js +16 -8
  35. package/dist/otlp/otlp-trace-exporter.service.d.ts +3 -0
  36. package/dist/otlp/otlp-trace-exporter.service.js +71 -6
  37. package/dist/outgoing/http.integration.d.ts +8 -4
  38. package/dist/outgoing/http.integration.js +13 -6
  39. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  40. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  41. package/dist/outgoing/llm/llm-providers.js +72 -22
  42. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  43. package/dist/outgoing/llm/llm-usage.js +72 -25
  44. package/dist/outgoing/mssql.integration.js +16 -2
  45. package/dist/outgoing/mysql2.integration.js +17 -1
  46. package/dist/outgoing/outgoing-observe-agent.service.js +15 -3
  47. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  48. package/dist/outgoing/pg.integration.d.ts +3 -2
  49. package/dist/outgoing/pg.integration.js +39 -11
  50. package/dist/outgoing/sql-statement.util.js +106 -14
  51. package/dist/outgoing/undici.integration.d.ts +13 -0
  52. package/dist/outgoing/undici.integration.js +68 -0
  53. package/dist/protocols/bull-observe-agent.service.js +2 -12
  54. package/dist/protocols/deferred-trace-completion.d.ts +9 -1
  55. package/dist/protocols/deferred-trace-completion.js +36 -6
  56. package/dist/protocols/graphql-observe-agent.service.d.ts +36 -5
  57. package/dist/protocols/graphql-observe-agent.service.js +166 -5
  58. package/dist/protocols/graphql-operation-parser.js +72 -18
  59. package/dist/protocols/http-observe-agent.service.d.ts +43 -9
  60. package/dist/protocols/http-observe-agent.service.js +177 -59
  61. package/dist/protocols/job-trace-runner.d.ts +35 -3
  62. package/dist/protocols/job-trace-runner.js +136 -31
  63. package/dist/protocols/queue-observe-agent.service.js +44 -20
  64. package/dist/protocols/rpc-observe-agent.service.d.ts +50 -8
  65. package/dist/protocols/rpc-observe-agent.service.js +225 -49
  66. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  67. package/dist/protocols/ws-observe-agent.service.js +226 -20
  68. package/dist/services/index.d.ts +1 -1
  69. package/dist/services/index.js +1 -1
  70. package/dist/services/logger-patcher.service.js +3 -4
  71. package/dist/services/operation-trace.registry.d.ts +45 -1
  72. package/dist/services/operation-trace.registry.js +418 -35
  73. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  74. package/dist/services/stdout-forwarder.service.js +288 -51
  75. package/dist/services/tracer.service.d.ts +23 -0
  76. package/dist/services/tracer.service.js +99 -7
  77. package/dist/utils/capture-request.util.d.ts +3 -1
  78. package/dist/utils/capture-request.util.js +100 -12
  79. package/dist/utils/fit-to-length.util.js +33 -10
  80. package/dist/utils/log-line.parser.d.ts +14 -0
  81. package/dist/utils/log-line.parser.js +7 -3
  82. package/dist/utils/log-redactor.d.ts +14 -0
  83. package/dist/utils/log-redactor.js +512 -61
  84. package/dist/utils/operation-state.util.d.ts +39 -0
  85. package/dist/utils/operation-state.util.js +50 -0
  86. package/dist/utils/redact-url-query.d.ts +26 -4
  87. package/dist/utils/redact-url-query.js +184 -32
  88. package/dist/utils/sensitive-keys.d.ts +4 -1
  89. package/dist/utils/sensitive-keys.js +48 -10
  90. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  91. package/dist/utils/shared-hook-slot.util.js +103 -0
  92. package/dist/utils/source-context.util.d.ts +8 -0
  93. package/dist/utils/source-context.util.js +88 -19
  94. package/dist/utils/source-map-resolver.util.js +8 -2
  95. package/dist/utils/trace-context.util.d.ts +20 -0
  96. package/dist/utils/trace-context.util.js +50 -6
  97. package/package.json +4 -1
@@ -6,21 +6,25 @@
6
6
  * SDK, LangChain and a hand-written `fetch` all end in the same request to the
7
7
  * same host, so a host list covers every client without knowing any of them.
8
8
  */
9
- /** Exact hosts, each with the provider name the dashboard groups by. */
10
- const EXACT_HOSTS = {
11
- "api.openai.com": "openai",
12
- "api.anthropic.com": "anthropic",
13
- "generativelanguage.googleapis.com": "google",
14
- "api.mistral.ai": "mistral",
15
- "api.groq.com": "groq",
16
- "openrouter.ai": "openrouter",
17
- "api.together.xyz": "together",
18
- "api.deepseek.com": "deepseek",
19
- "api.x.ai": "xai",
20
- "api.cohere.ai": "cohere",
21
- "api.cohere.com": "cohere",
22
- "api.perplexity.ai": "perplexity",
23
- };
9
+ /**
10
+ * Exact hosts, each with the provider name the dashboard groups by. A `Map`,
11
+ * not an object literal: looked up by the host of any outgoing call, and a
12
+ * host spelt `constructor` or `__proto__` found an inherited member there.
13
+ */
14
+ const EXACT_HOSTS = new Map([
15
+ ["api.openai.com", "openai"],
16
+ ["api.anthropic.com", "anthropic"],
17
+ ["generativelanguage.googleapis.com", "google"],
18
+ ["api.mistral.ai", "mistral"],
19
+ ["api.groq.com", "groq"],
20
+ ["openrouter.ai", "openrouter"],
21
+ ["api.together.xyz", "together"],
22
+ ["api.deepseek.com", "deepseek"],
23
+ ["api.x.ai", "xai"],
24
+ ["api.cohere.ai", "cohere"],
25
+ ["api.cohere.com", "cohere"],
26
+ ["api.perplexity.ai", "perplexity"],
27
+ ]);
24
28
  /** Hosts that carry a tenant or a region in a subdomain. */
25
29
  const HOST_PATTERNS = [
26
30
  [/^[a-z0-9-]+\.openai\.azure\.com$/, "azure-openai"],
@@ -32,7 +36,7 @@ const HOST_PATTERNS = [
32
36
  export function llmProviderForHost(host, extraHosts = new Set()) {
33
37
  const normalized = host.toLowerCase();
34
38
  const hostname = normalized.replace(/:\d+$/, "");
35
- const exact = EXACT_HOSTS[hostname];
39
+ const exact = EXACT_HOSTS.get(hostname);
36
40
  if (exact) {
37
41
  return exact;
38
42
  }
@@ -48,14 +52,60 @@ export function llmProviderForHost(host, extraHosts = new Set()) {
48
52
  }
49
53
  /** Most of a request body read for its `model` field. Prompts can be megabytes. */
50
54
  const MODEL_SCAN_BYTES = 64 * 1024;
51
- const MODEL_FIELD = /"model"\s*:\s*"([^"\\]{1,128})"/;
55
+ /** What follows a `"model"` key: the value, when it is a short string. */
56
+ const MODEL_VALUE = /\s*:\s*"([^"\\]{1,128})"/y;
57
+ /**
58
+ * The `model` of the outermost object of a JSON document, or of as much of
59
+ * one as `text` holds - and nothing for text that does not open with `{`.
60
+ *
61
+ * A scan rather than `JSON.parse`, which a cut-off document would fail, and
62
+ * rather than a search for `"model":`, which finds that key at any depth: a
63
+ * tool call's input, a tool result or a JSON-mode completion can carry one,
64
+ * and what it holds is the prompt's, not the model's. Strings are skipped
65
+ * whole, so a brace or a key inside one counts for nothing. Linear, and done
66
+ * at the first `model` key of the outermost object - where clients put it.
67
+ */
68
+ export function topLevelModel(text) {
69
+ let index = text.search(/\S/);
70
+ if (index === -1 || text[index] !== "{") {
71
+ return undefined;
72
+ }
73
+ let depth = 0;
74
+ for (; index < text.length; index++) {
75
+ const char = text[index];
76
+ if (char === '"') {
77
+ const start = index;
78
+ for (index++; index < text.length && text[index] !== '"'; index++) {
79
+ if (text[index] === "\\") {
80
+ index++;
81
+ }
82
+ }
83
+ if (depth === 1 &&
84
+ index - start === 6 &&
85
+ text.startsWith('"model"', start)) {
86
+ MODEL_VALUE.lastIndex = index + 1;
87
+ const value = MODEL_VALUE.exec(text);
88
+ if (value) {
89
+ return value[1];
90
+ }
91
+ }
92
+ }
93
+ else if (char === "{" || char === "[") {
94
+ depth++;
95
+ }
96
+ else if ((char === "}" || char === "]") && --depth === 0) {
97
+ return undefined;
98
+ }
99
+ }
100
+ return undefined;
101
+ }
52
102
  /**
53
103
  * The model a JSON request body names, read from its first 64 KB.
54
104
  *
55
- * A pattern rather than `JSON.parse`: the body is the application's prompt,
56
- * often far larger than the one field wanted, and every client puts `model`
57
- * near the top. Bodies that are streams or forms are not read at all - reading
58
- * them would consume what the request is about to send.
105
+ * Read with `topLevelModel`: the body is the application's prompt, often far
106
+ * larger than the one field wanted, and every client puts `model` near the
107
+ * top. Bodies that are streams or forms are not read at all - reading them
108
+ * would consume what the request is about to send.
59
109
  */
60
110
  export function modelFromRequestBody(body) {
61
111
  let text;
@@ -68,7 +118,7 @@ export function modelFromRequestBody(body) {
68
118
  else if (body instanceof ArrayBuffer) {
69
119
  text = new TextDecoder().decode(new Uint8Array(body, 0, Math.min(body.byteLength, MODEL_SCAN_BYTES)));
70
120
  }
71
- return text ? MODEL_FIELD.exec(text)?.[1] : undefined;
121
+ return text ? topLevelModel(text) : undefined;
72
122
  }
73
123
  /**
74
124
  * The model a URL names, for the providers that put it in the path rather
@@ -1,7 +1,3 @@
1
- /**
2
- * Reading token usage out of a model provider's response - a JSON body, or
3
- * the events of a server-sent stream - without ever keeping its text.
4
- */
5
1
  /** What one call consumed, as far as the response said. */
6
2
  export interface LlmUsage {
7
3
  /** The model that answered - more precise than the one asked for. */
@@ -35,10 +31,14 @@ export declare function usageFromDocument(document: unknown): LlmUsage;
35
31
  * A larger body - a long completion, a batch of embeddings - is not kept: its
36
32
  * first and last 32 KB are, and the usage is matched out of those. Every
37
33
  * provider writes `usage` after the content and `model` before it.
34
+ *
35
+ * The bytes are copied, not the chunks kept: a chunk object costs a few
36
+ * hundred bytes of heap whatever it holds, and the sender decides how the
37
+ * body is cut - one byte at a time, a 2 MB body would be held a hundred
38
+ * times over.
38
39
  */
39
40
  export declare class JsonUsageReader {
40
- private readonly chunks;
41
- private size;
41
+ private body;
42
42
  private head;
43
43
  private tail;
44
44
  push(chunk: Uint8Array): void;
@@ -50,6 +50,11 @@ export declare class JsonUsageReader {
50
50
  * Only `data:` lines that can carry usage or a model are parsed - the first
51
51
  * event, and any that mention `usage` - so a long stream of text deltas costs
52
52
  * a substring search per line rather than a parse.
53
+ *
54
+ * A line still arriving is held as bytes, copied, and decoded once it is
55
+ * whole: grown a chunk at a time as a string, a line sent a byte at a time
56
+ * would be a million string objects. A line feed is never part of another
57
+ * UTF-8 character, so the bytes split into lines as the text does.
53
58
  */
54
59
  export declare class SseUsageReader {
55
60
  private readonly now;
@@ -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
  }