@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
@@ -19,24 +19,51 @@ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.j
19
19
  import { OBSERVE_OPTIONS, TRACE_CONTEXT_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
20
20
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
21
21
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
22
- import { redactUrlQuery } from "../utils/redact-url-query.js";
22
+ import { redactUrlQuery, toGlobalRegExp } from "../utils/redact-url-query.js";
23
23
  import { openTelemetryTraceIdGenerator } from "../utils/default-trace-id-generator.util.js";
24
24
  import { usesDefaultTraceIdGenerator } from "../utils/trace-id-generator-origin.util.js";
25
25
  import { inboundTraceContext } from "../utils/trace-context.util.js";
26
26
  import { uuidv7 } from "../utils/uuid-v7.util.js";
27
+ import { setAgentHook, shareHookSlot } from "../utils/shared-hook-slot.util.js";
27
28
  import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
28
- /**
29
- * How long an aborted request's handler gets to finish its spans before the
30
- * trace is dropped from the registry. Generous next to a typical handler, tiny
31
- * next to a leak that never frees.
32
- */
33
- const ABORTED_TRACE_EVICTION_GRACE_MS = 30_000;
29
+ import { endOperation, openOperation, } from "../utils/operation-state.util.js";
34
30
  /** The adapter hooks requests are traced through, all added in Nest 11.1.4. */
35
31
  const REQUEST_HOOKS = [
36
32
  "setOnRequestHook",
37
33
  "setOnResponseHook",
38
34
  "setOnRouteTriggered",
39
35
  ];
36
+ /**
37
+ * Takes the adapter's request and response hooks over as soon as there is an
38
+ * adapter, so that hooks the application sets on it from then on run beside
39
+ * the agent's rather than in their place: from a provider, from `main.ts`
40
+ * before `listen()`. They have no getter, so a hook set on the adapter before
41
+ * it reached Nest cannot be found, and stays the agent's to replace. Called
42
+ * from the instance decorator, the moment Nest creates the `HttpAdapterHost`,
43
+ * and again from the agent, for an application without the decorator. On
44
+ * `init$` rather than the adapter itself: `@nestjs/testing` attaches the
45
+ * adapter only once the testing module is compiled.
46
+ */
47
+ export function shareHttpAdapterHooks(httpAdapterHost) {
48
+ const share = () => {
49
+ try {
50
+ const { httpAdapter } = httpAdapterHost;
51
+ if (httpAdapter) {
52
+ shareHookSlot(httpAdapter, "setOnRequestHook");
53
+ shareHookSlot(httpAdapter, "setOnResponseHook");
54
+ }
55
+ }
56
+ catch {
57
+ // An adapter that cannot be read is one there is nothing to share on.
58
+ }
59
+ };
60
+ try {
61
+ httpAdapterHost.init$?.subscribe(share);
62
+ }
63
+ catch {
64
+ // Run from the instance decorator, which Nest 11 does not guard.
65
+ }
66
+ }
40
67
  let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgentService {
41
68
  httpAdapterHost;
42
69
  asyncLocalStorage;
@@ -47,6 +74,23 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
47
74
  logger = new Logger(HttpObserveAgentService_1.name);
48
75
  warnedAboutHooks = false;
49
76
  httpAdapterInitSubscription;
77
+ /**
78
+ * The registry key each request was started under, by the Node request -
79
+ * see `nodeRequestOf` - which every adapter hands to both of its hooks. The
80
+ * response hook cannot ask the async store: it runs from `finish`, in the
81
+ * async context of whatever ended the response, and that need not be the
82
+ * request's own. A request pipelined behind another has its `finish`
83
+ * emitted from the earlier one's; a stream piped into the response ends it
84
+ * where its source emits - for a pooled database connection, in the
85
+ * request that opened it. Taken out by the first response hook to run, so
86
+ * a request routed twice is completed once.
87
+ */
88
+ registryKeys = new WeakMap();
89
+ /**
90
+ * The store each request runs in, by the Node request, for a request that
91
+ * comes through the router again - see `startHttpRequestTracing`.
92
+ */
93
+ requestStores = new WeakMap();
50
94
  /**
51
95
  * `http.queryParamsObfuscateRegex`, rebuilt with the global flag when it was
52
96
  * supplied without one. It is applied with `replaceAll`, which throws on a
@@ -63,13 +107,17 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
63
107
  this.observeAgentSharedBuffer = observeAgentSharedBuffer;
64
108
  this.traceSamplerService = traceSamplerService;
65
109
  this.queryParamsObfuscateRegex = toGlobalRegExp(this.options.http?.queryParamsObfuscateRegex);
110
+ shareHttpAdapterHooks(this.httpAdapterHost);
66
111
  // The "setOnRouteTriggered" hook must be set immediately
67
112
  // to ensure that route metadata is captured correctly.
68
113
  const { httpAdapter } = this.httpAdapterHost;
69
114
  if (!httpAdapter || !this.hasRequestHooks(httpAdapter)) {
70
115
  return;
71
116
  }
72
- httpAdapter.setOnRouteTriggered((requestMethod, path) => {
117
+ // Beside the application's, one set before (found through the getter,
118
+ // which Nest's router reads the hook from too, and is left to it) or
119
+ // after.
120
+ setAgentHook(httpAdapter, "setOnRouteTriggered", (requestMethod, path) => {
73
121
  const store = this.asyncLocalStorage.getStore();
74
122
  if (!store) {
75
123
  return;
@@ -79,7 +127,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
79
127
  return;
80
128
  }
81
129
  this.operationTraceRegistry.addRouteMetadataToTrace(registryKey, requestMethod, path);
82
- });
130
+ }, composeRouteTriggered, { getter: "getOnRouteTriggered" });
83
131
  }
84
132
  onModuleInit() {
85
133
  this.httpAdapterInitSubscription = this.httpAdapterHost.init$?.subscribe(() => this.registerHttpHooks());
@@ -94,21 +142,40 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
94
142
  if (!httpAdapter || !this.hasRequestHooks(httpAdapter)) {
95
143
  return;
96
144
  }
97
- httpAdapter.setOnRequestHook((req, res, done) => {
98
- this.startHttpRequestTracing(req, res, done);
99
- });
100
- // Fastify waits for `done` before it runs the next onResponse hook.
101
- // Express does not pass one.
102
- httpAdapter.setOnResponseHook((req, res, done) => {
103
- this.endHttpRequestTracing(req, res);
104
- done?.();
105
- });
145
+ // Set beside the application's hooks, which `shareHttpAdapterHooks` has
146
+ // made the slots keep.
147
+ setAgentHook(httpAdapter, "setOnRequestHook", (req, res, done) => this.startHttpRequestTracing(req, res, done), composeRequestHook);
148
+ setAgentHook(httpAdapter, "setOnResponseHook", (req, res) => this.endHttpRequestTracing(req, res), composeResponseHook);
106
149
  }
150
+ /**
151
+ * Opens the request's trace and calls `done` inside its store, handing back
152
+ * what `done` returns: an application's request hook runs inside it, and
153
+ * the adapter waits on or fails the request by what that hook returns.
154
+ */
107
155
  startHttpRequestTracing(req, res, done) {
156
+ // A request the application routes again - `req.app(req, res, next)` or
157
+ // `app.handle()` on Express, `routing()` on Fastify - passes the
158
+ // adapter's hooks once per pass. Traced anew each time, the first pass's
159
+ // trace was never completed: both response hooks completed the last
160
+ // one, and every such request left a trace in the registry for the life
161
+ // of the process, holding the URL the client sent. It is one request,
162
+ // traced once, on the URL it arrived with: the later pass runs in the
163
+ // first one's store, or in the context it is in when that is a span of
164
+ // the request already.
165
+ const request = nodeRequestOf(req);
166
+ const started = this.requestStores.get(request);
167
+ if (started) {
168
+ const current = this.asyncLocalStorage.getStore();
169
+ return current?.get(TRACE_REGISTRY_KEY) ===
170
+ started.get(TRACE_REGISTRY_KEY)
171
+ ? done()
172
+ : this.asyncLocalStorage.run(started, done);
173
+ }
108
174
  // The same map `run` is given, rather than `getStore()` inside the callback:
109
175
  // identical object, one lookup fewer, and it is known to exist.
110
176
  const store = new Map();
111
- this.asyncLocalStorage.run(store, () => {
177
+ this.requestStores.set(request, store);
178
+ return this.asyncLocalStorage.run(store, () => {
112
179
  // OpenTelemetry interop runs only beside reporting to NestJS Observe -
113
180
  // see `ObserveAgentSharedBuffer.isReporting`. Asked once per request,
114
181
  // so a request is named and carried on one way throughout.
@@ -125,6 +192,10 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
125
192
  // lookups stay off a recorded request sharing its id.
126
193
  const registryKey = uuidv7();
127
194
  store.set(TRACE_REGISTRY_KEY, registryKey);
195
+ this.registryKeys.set(request, registryKey);
196
+ // Ended when the response closes, recorded or not, answered or
197
+ // aborted: see `liveTraceId`.
198
+ this.watchResponseClose(res, openOperation(store), registryKey);
128
199
  // With OpenTelemetry interop on, read whatever produced the trace id: a
129
200
  // `traceIdGenerator` of the application's own decides what Observe
130
201
  // calls the trace, not which OpenTelemetry trace the caller is in, and
@@ -139,7 +210,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
139
210
  if (traceContext) {
140
211
  store.set(TRACE_CONTEXT_KEY, traceContext);
141
212
  }
142
- setAttributesSafely(this.options.http?.setAttributes, [req], this.options.http, store, this.logger, "http");
213
+ setAttributesSafely(this.options.http?.setAttributes, [req], this.options.http, store, this.logger, "http", this.options.traceIdKey);
143
214
  if (this.shouldIgnoreRequest(req) || this.isUntracedPreflight(req)) {
144
215
  return done();
145
216
  }
@@ -156,10 +227,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
156
227
  // disclosure either way. A configured regex still applies, on top rather
157
228
  // than instead - it exists for the keys only that deployment knows
158
229
  // about.
159
- const redactedUrl = redactUrlQuery(req.url, this.operationTraceRegistry.getRedactor());
160
- const originalUrl = this.queryParamsObfuscateRegex
161
- ? redactedUrl.replaceAll(this.queryParamsObfuscateRegex, "[REDACTED]")
162
- : redactedUrl;
230
+ const originalUrl = redactUrlQuery(req.url, this.operationTraceRegistry.getRedactor(), this.queryParamsObfuscateRegex);
163
231
  this.operationTraceRegistry.startTrace(registryKey, {
164
232
  protocol: req.protocol,
165
233
  tags: this.options.http?.tags,
@@ -173,20 +241,23 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
173
241
  if (isPreflight(req)) {
174
242
  this.operationTraceRegistry.keepWithoutSpans(registryKey);
175
243
  }
176
- this.evictTraceOnClientAbort(res, registryKey);
177
- done();
244
+ return done();
178
245
  });
179
246
  }
180
247
  endHttpRequestTracing(req, res) {
181
- const store = this.asyncLocalStorage.getStore();
182
- if (!store) {
248
+ // This request's own key, never the one in the async store: the store
249
+ // here is that of whatever ended the response, a finished request's or
250
+ // another one still running, and neither may be completed in this one's
251
+ // place, nor leave this one open.
252
+ const request = typeof req === "object" && req !== null ? nodeRequestOf(req) : undefined;
253
+ const registryKey = request === undefined ? undefined : this.registryKeys.get(request);
254
+ if (registryKey === undefined) {
183
255
  return;
184
256
  }
185
- // Only this execution's own key: a stale store left by a finished request
186
- // must not complete a later one that reuses its id.
187
- const registryKey = store.get(TRACE_REGISTRY_KEY);
188
- if (typeof registryKey !== "string" ||
189
- !this.operationTraceRegistry.hasTrace(registryKey)) {
257
+ // A request routed twice has a response hook per pass, and both run
258
+ // before the first completion takes the trace out of the registry.
259
+ this.registryKeys.delete(request);
260
+ if (!this.operationTraceRegistry.hasTrace(registryKey)) {
190
261
  return;
191
262
  }
192
263
  deferTraceCompletion(async () => {
@@ -200,7 +271,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
200
271
  return;
201
272
  }
202
273
  if (shouldCaptureRequest(snapshot, this.options.http?.capture)) {
203
- const captured = captureRequest(req, this.options.http?.capture, this.operationTraceRegistry.getRedactor());
274
+ const captured = captureRequest(req, this.options.http?.capture, this.operationTraceRegistry.getRedactor(), this.queryParamsObfuscateRegex);
204
275
  if (captured) {
205
276
  snapshot.request = captured;
206
277
  }
@@ -209,7 +280,9 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
209
280
  }, this.logger, "http", () => this.operationTraceRegistry.hasOpenSpans(registryKey));
210
281
  }
211
282
  /**
212
- * Frees the trace when the client goes away before the response finishes.
283
+ * Ends the request's operation when its response closes - answered or
284
+ * aborted, recorded or not - and frees the trace when the client went away
285
+ * before the response finished.
213
286
  *
214
287
  * The adapter's response hook rides `res.on("finish")`, and an aborted
215
288
  * request never emits it - the socket emits `close` instead. Without this,
@@ -217,26 +290,32 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
217
290
  * of the process; on an ingest endpoint taking 16MB bodies over slow links,
218
291
  * aborts are routine, not exceptional.
219
292
  *
293
+ * Express and the Node adapter hand the request hook the Node response
294
+ * itself; Fastify hands it the reply, which is no emitter, with the Node
295
+ * response under it as `raw`.
296
+ *
220
297
  * On the normal path `close` follows `finish` with `writableFinished`
221
- * already true, so this stays a no-op there - `endHttpRequestTracing` has
222
- * either plucked the trace or is about to.
298
+ * already true, so the trace is left alone there - `endHttpRequestTracing`
299
+ * has either plucked it or is about to. A response that does not say is
300
+ * left alone too.
223
301
  *
224
- * Eviction is deferred, not immediate: Express does not cancel the handler
225
- * on abort, so its spans are usually still closing when `close` fires. The
226
- * grace period lets the handler drain first; `unref` keeps the timer from
227
- * holding a shutting-down process open.
302
+ * Dropped at once, not after a grace period: an abandoned trace is never
303
+ * reported, and the registry already lets a handler that outlives its
304
+ * client end its spans on a trace that is gone. Held for 30 s, it was the
305
+ * client's to say how many such traces the process kept.
228
306
  */
229
- evictTraceOnClientAbort(res, traceId) {
230
- const response = res;
307
+ watchResponseClose(res, operation, traceId) {
308
+ const given = res;
309
+ const response = (typeof given?.on === "function" ? given : given?.raw);
231
310
  if (typeof response?.on !== "function") {
232
311
  return;
233
312
  }
234
313
  response.on("close", () => {
235
- if (response.writableFinished) {
236
- return;
314
+ endOperation(operation);
315
+ // A request that was never recorded has nothing registered to drop.
316
+ if (response.writableFinished === false) {
317
+ this.operationTraceRegistry.abandonTrace(traceId);
237
318
  }
238
- const timer = setTimeout(() => this.operationTraceRegistry.abandonTrace(traceId), ABORTED_TRACE_EVICTION_GRACE_MS);
239
- timer.unref?.();
240
319
  });
241
320
  }
242
321
  /**
@@ -271,7 +350,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
271
350
  const blocklist = this.options.http.ignore;
272
351
  return blocklist.some((item) => {
273
352
  if (typeof item === "string") {
274
- return req.url === item;
353
+ return matchesPath(item, req.url);
275
354
  }
276
355
  if (item instanceof RegExp) {
277
356
  return testIgnoreRegex(item, req.url);
@@ -279,7 +358,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
279
358
  if (typeof item === "object") {
280
359
  return (item.method === req.method &&
281
360
  (typeof item.path === "string"
282
- ? req.url === item.path
361
+ ? matchesPath(item.path, req.url)
283
362
  : testIgnoreRegex(item.path, req.url)));
284
363
  }
285
364
  return false;
@@ -297,6 +376,85 @@ HttpObserveAgentService = HttpObserveAgentService_1 = __decorate([
297
376
  TraceSamplerService])
298
377
  ], HttpObserveAgentService);
299
378
  export { HttpObserveAgentService };
379
+ /**
380
+ * The request hook the adapter is given: the agent's outside, and the
381
+ * application's inside the agent's `done`, so it runs in the request's store
382
+ * - its log lines and calls carry the trace - and whatever it returns, a
383
+ * promise the adapter fails the request by, goes back to the adapter. It
384
+ * refuses a request with `done(err)`, by throwing or by answering it itself,
385
+ * as without the agent; the response hook still closes the trace.
386
+ */
387
+ function composeRequestHook(application, agent) {
388
+ if (!application) {
389
+ return agent;
390
+ }
391
+ return function (req, res, done) {
392
+ return agent.call(this, req, res, () => application.call(this, req, res, done));
393
+ };
394
+ }
395
+ /**
396
+ * The response hook the adapter is given: the agent's first, whatever the
397
+ * application's does, then the application's, handed `done` - Fastify waits
398
+ * for it before its next `onResponse` hook, Express passes none - and
399
+ * returning what it returns.
400
+ */
401
+ function composeResponseHook(application, agent) {
402
+ return function (req, res, done) {
403
+ if (!application) {
404
+ agent.call(this, req, res);
405
+ return done?.();
406
+ }
407
+ let returned;
408
+ try {
409
+ agent.call(this, req, res);
410
+ }
411
+ finally {
412
+ returned = application.call(this, req, res, done);
413
+ }
414
+ return returned;
415
+ };
416
+ }
417
+ /**
418
+ * How deep composed route hooks are running. The getter Nest's router reads
419
+ * the hook from hands an application the composed hook, and one chaining
420
+ * "the previous hook" calls it from inside the next composed one: there only
421
+ * the hook it wraps runs, as the agent's part already has.
422
+ */
423
+ let routeTriggeredDepth = 0;
424
+ /** The route hook the adapter is given: the agent's part, then the application's. */
425
+ function composeRouteTriggered(application, agent) {
426
+ return function (requestMethod, path) {
427
+ if (routeTriggeredDepth > 0) {
428
+ return application?.call(this, requestMethod, path);
429
+ }
430
+ routeTriggeredDepth++;
431
+ try {
432
+ agent.call(this, requestMethod, path);
433
+ return application?.call(this, requestMethod, path);
434
+ }
435
+ finally {
436
+ routeTriggeredDepth--;
437
+ }
438
+ };
439
+ }
440
+ /**
441
+ * Whether a string entry of `http.ignore` names this request: the URL itself,
442
+ * or its path - the URL up to a `?` or `#`. `req.url` carries the query string
443
+ * on every adapter, so compared whole, an endpoint that takes its input there
444
+ * was never ignored, and `/health` was traced whenever a caller added one. An
445
+ * entry written with a query string still matches that URL exactly. Read in
446
+ * place, without cutting the URL, as this runs for every request.
447
+ */
448
+ function matchesPath(literal, url) {
449
+ if (url === literal) {
450
+ return true;
451
+ }
452
+ const next = url[literal.length];
453
+ return ((next === "?" || next === "#") &&
454
+ url.startsWith(literal) &&
455
+ !literal.includes("?") &&
456
+ !literal.includes("#"));
457
+ }
300
458
  /**
301
459
  * Global and sticky regular expressions carry a lastIndex between calls. Use
302
460
  * a fresh expression for each ignore decision so matching always starts at the
@@ -309,22 +467,25 @@ function testIgnoreRegex(pattern, value) {
309
467
  }
310
468
  return new RegExp(pattern.source, pattern.flags).test(value);
311
469
  }
312
- /**
313
- * Rebuilds a RegExp with the global flag when it lacks one, keeping the
314
- * original otherwise. `replaceAll` refuses a non-global pattern outright.
315
- */
316
- function toGlobalRegExp(pattern) {
317
- if (!pattern || pattern.global) {
318
- return pattern;
319
- }
320
- return new RegExp(pattern.source, pattern.flags + "g");
321
- }
322
470
  /**
323
471
  * A CORS preflight: what the CORS spec defines one to be - `OPTIONS` with an
324
472
  * `Access-Control-Request-Method` header - rather than the method alone, so
325
473
  * an application's own `OPTIONS` handler is still traced as a request. Every
326
474
  * adapter lower-cases header names.
327
475
  */
476
+ /**
477
+ * The Node request under what an adapter hands its hooks, which a request
478
+ * routed again shares between its passes: Express and the Node adapter hand
479
+ * over the Node request itself, and Fastify a request object of its own per
480
+ * pass, which is no emitter, with the Node request under it as `raw`.
481
+ */
482
+ function nodeRequestOf(req) {
483
+ if (typeof req.on === "function") {
484
+ return req;
485
+ }
486
+ const raw = req.raw;
487
+ return typeof raw === "object" && raw !== null ? raw : req;
488
+ }
328
489
  function isPreflight(req) {
329
490
  return (req.method === "OPTIONS" &&
330
491
  req.headers?.["access-control-request-method"] !== undefined);
@@ -12,8 +12,46 @@ export interface JobRunDescriptor {
12
12
  /** The job's options as the driver read them back from Redis. */
13
13
  opts?: Record<string, unknown>;
14
14
  metadata: Partial<JobSnapshot>;
15
+ /**
16
+ * How long, in ms, the driver gives the run once its handler has returned
17
+ * before it fails the job itself, when it does - Bull's `timeout` option.
18
+ * The run is reported as failed then, whether the handler ever finishes or
19
+ * not.
20
+ */
21
+ timeout?: number;
15
22
  }
16
23
  type JobStatus = NonNullable<JobSnapshot["status"]>;
24
+ /** What a queue driver read back of a job's times. */
25
+ interface JobTimes {
26
+ /** When the job was created. */
27
+ timestamp?: unknown;
28
+ /** When the worker took it, set just before the processor runs. */
29
+ processedOn?: unknown;
30
+ /** The delay still pending, which BullMQ and Bull reset on promotion. */
31
+ delay?: unknown;
32
+ opts?: {
33
+ delay?: unknown;
34
+ };
35
+ }
36
+ /**
37
+ * When a job was enqueued, and how long it waited for a worker once it could
38
+ * run - left out when its times are not ones a `Date` can hold.
39
+ *
40
+ * Job fields are read back from Redis, which anything with access to it can
41
+ * write, and BullMQ takes a caller's `timestamp` option unchecked:
42
+ * `new Date(8.64e15 + 1).toISOString()` throws, and adding an object-valued
43
+ * `delay` to a number throws too. Both ran before the processor, so the
44
+ * worker failed a job that completes without the agent.
45
+ *
46
+ * `timestamp` is when the job was created, not when it became runnable, so for
47
+ * a delayed job the gap between the two is a schedule the caller asked for -
48
+ * not a queue that fell behind. Counting it would report a job dated a week
49
+ * out as a week of backlog and drag `job_wait_p95` with it. The delay is read
50
+ * off the options when the job's own reads 0: it is reset as a delayed job is
51
+ * promoted, so by the time a worker holds the job it says 0 whatever was
52
+ * asked for. `||`, not `??`, for that reason.
53
+ */
54
+ export declare function readJobTimes(job: JobTimes): Partial<JobSnapshot>;
17
55
  /** The slice of a queue's prototype the enqueue patch touches. */
18
56
  interface QueuePrototypeLike {
19
57
  add?: (...args: any[]) => unknown;
@@ -91,9 +129,10 @@ export declare class JobTraceRunner<Store extends Record<string, unknown>> {
91
129
  * Runs one job under a trace.
92
130
  *
93
131
  * `invoke` is handed `settle` for drivers whose handlers finish through a
94
- * callback; pass `settlesItself` for those, and a plain return is then not
95
- * read as completion. Promise-returning and throwing handlers are settled
96
- * here either way.
132
+ * callback; pass `settlesItself` for those, and what the handler returns,
133
+ * a promise included, is then not read as the outcome. A throwing handler
134
+ * is settled here either way, and a promise goes back to the driver as the
135
+ * handler returned it.
97
136
  */
98
137
  run<T>(job: JobRunDescriptor, invoke: (settle: (status: JobStatus) => void) => T, settlesItself?: boolean): T;
99
138
  }