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