@nestjs/observe 0.3.26 → 0.3.28

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 (61) hide show
  1. package/README.md +38 -2
  2. package/dist/agent/observe-agent.shared-buffer.js +5 -0
  3. package/dist/agent/telemetry-wire-contract.js +3 -3
  4. package/dist/cli/link.js +24 -2
  5. package/dist/cli/package-manager.d.ts +6 -0
  6. package/dist/cli/package-manager.js +60 -3
  7. package/dist/cli/project-files.d.ts +25 -5
  8. package/dist/cli/project-files.js +98 -15
  9. package/dist/custom-metrics/summary.js +17 -10
  10. package/dist/instrument/create-instance-decorator.instrument.js +390 -38
  11. package/dist/instrument/raw-receiver.d.ts +6 -0
  12. package/dist/instrument/raw-receiver.js +32 -0
  13. package/dist/interfaces/observe-options.interface.d.ts +14 -5
  14. package/dist/otlp/otlp-span.mapper.d.ts +2 -0
  15. package/dist/otlp/otlp-span.mapper.js +19 -1
  16. package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
  17. package/dist/otlp/otlp-trace-exporter.service.js +232 -38
  18. package/dist/outgoing/http.integration.js +36 -11
  19. package/dist/outgoing/mongodb.integration.d.ts +3 -1
  20. package/dist/outgoing/mongodb.integration.js +93 -18
  21. package/dist/outgoing/mssql.integration.js +9 -4
  22. package/dist/outgoing/mysql2.integration.js +3 -1
  23. package/dist/outgoing/outgoing-observe-agent.service.js +5 -1
  24. package/dist/outgoing/pg.integration.js +5 -0
  25. package/dist/outgoing/sql-statement.util.js +36 -10
  26. package/dist/protocols/bull-observe-agent.service.js +21 -0
  27. package/dist/protocols/deferred-trace-completion.d.ts +8 -2
  28. package/dist/protocols/deferred-trace-completion.js +40 -3
  29. package/dist/protocols/graphql-observe-agent.service.d.ts +62 -2
  30. package/dist/protocols/graphql-observe-agent.service.js +188 -14
  31. package/dist/protocols/graphql-operation-parser.js +45 -14
  32. package/dist/protocols/http-observe-agent.service.d.ts +14 -7
  33. package/dist/protocols/http-observe-agent.service.js +57 -14
  34. package/dist/protocols/job-trace-runner.d.ts +7 -0
  35. package/dist/protocols/job-trace-runner.js +72 -8
  36. package/dist/protocols/rpc-observe-agent.service.d.ts +61 -0
  37. package/dist/protocols/rpc-observe-agent.service.js +146 -10
  38. package/dist/protocols/ws-observe-agent.service.js +1 -1
  39. package/dist/services/logger-patcher.service.js +13 -3
  40. package/dist/services/operation-trace.registry.d.ts +13 -0
  41. package/dist/services/operation-trace.registry.js +195 -65
  42. package/dist/services/stdout-forwarder.service.js +22 -2
  43. package/dist/services/tracer.service.d.ts +19 -14
  44. package/dist/services/tracer.service.js +57 -34
  45. package/dist/utils/capture-request.util.js +36 -8
  46. package/dist/utils/context-accessor.util.d.ts +16 -0
  47. package/dist/utils/context-accessor.util.js +28 -0
  48. package/dist/utils/default-trace-id-generator.util.js +5 -7
  49. package/dist/utils/error-stack.util.d.ts +13 -0
  50. package/dist/utils/error-stack.util.js +166 -0
  51. package/dist/utils/log-line.parser.d.ts +8 -0
  52. package/dist/utils/log-line.parser.js +13 -4
  53. package/dist/utils/log-redactor.js +184 -10
  54. package/dist/utils/redact-url-query.d.ts +16 -5
  55. package/dist/utils/redact-url-query.js +20 -7
  56. package/dist/utils/source-context.util.d.ts +6 -0
  57. package/dist/utils/source-context.util.js +68 -33
  58. package/dist/utils/source-map-resolver.util.js +25 -4
  59. package/dist/utils/store-copy.util.d.ts +10 -0
  60. package/dist/utils/store-copy.util.js +43 -0
  61. package/package.json +4 -3
@@ -15,10 +15,12 @@ import { Inject, Injectable, Logger } from "@nestjs/common";
15
15
  import { DiscoveryService, MetadataScanner, ModuleRef } from "@nestjs/core";
16
16
  import { AsyncLocalStorage } from "async_hooks";
17
17
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
18
+ import { rawReceiverOf } from "../instrument/raw-receiver.js";
18
19
  import { CALLER_METADATA_KEY, OBSERVE_OPTIONS, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
19
20
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
20
21
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
21
22
  import { setAgentHook } from "../utils/shared-hook-slot.util.js";
23
+ import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
22
24
  import { parseGraphQLOperation, toResolveInfoLike, } from "./graphql-operation-parser.js";
23
25
  import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
24
26
  import { endOperation, OPERATION_STATE_KEY, openOperation, } from "../utils/operation-state.util.js";
@@ -94,6 +96,23 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
94
96
  * after the schema is built.
95
97
  */
96
98
  resolverIndex;
99
+ /**
100
+ * The operations each async store has open, in the order they started.
101
+ *
102
+ * Usually one. A batched HTTP request (Apollo's `allowBatchedHttpRequests`)
103
+ * is the exception: its operations run at once in the one store the
104
+ * request has, so the caller a later one found there was the span of the
105
+ * one before it - a sibling, not a caller - and they end in any order.
106
+ * Nested that way, the trace was as deep as the client made the batch
107
+ * long, and a failure behind the first operation was on no root span, so
108
+ * the request was reported as a success.
109
+ *
110
+ * Beside the store rather than in it: a span's store is a copy of its
111
+ * caller's, and an operation started inside the copy really is a callee.
112
+ * Weakly keyed, so an unmatched start - see `onRequestEnd` - leaves
113
+ * nothing behind once the request's store is gone.
114
+ */
115
+ openOperationsByStore = new WeakMap();
97
116
  constructor(asyncLocalStorage, options, operationTraceRegistry, observeAgentSharedBuffer, traceSamplerService, moduleRef, discoveryService, metadataScanner) {
98
117
  this.asyncLocalStorage = asyncLocalStorage;
99
118
  this.options = options;
@@ -103,6 +122,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
103
122
  this.moduleRef = moduleRef;
104
123
  this.discoveryService = discoveryService;
105
124
  this.metadataScanner = metadataScanner;
125
+ this.patchResolversExplorer();
106
126
  // Attempted twice, and idempotent, because `GraphQLModule` may be
107
127
  // instantiated on either side of this service. Whichever module Nest
108
128
  // reaches first, one of the two attempts lands: if GraphQLModule came
@@ -170,6 +190,67 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
170
190
  setAgentHook(host, "setOnRequestEndHook", (ctx) => this.onRequestEnd(ctx), composeEndHook, { getter: "getOnRequestEndHook", repointGetter: true });
171
191
  this.isPatched = true;
172
192
  }
193
+ /**
194
+ * Has `@nestjs/graphql` apply a resolver's methods to the instance itself
195
+ * where the instrumentation proxy cannot be their receiver.
196
+ *
197
+ * The explorer reads each `@Query`, `@Mutation`, `@Subscription` and
198
+ * `@ResolveField` method off the class prototype and applies it to the
199
+ * instance the container holds, which is the proxy. For a class with
200
+ * private members (`this.#x`), whose methods only the instance itself can
201
+ * run against, the first such read threw: the proxy only helps the methods
202
+ * read through it. `createContextCallback` is where every one of them is
203
+ * paired with its instance, the field resolvers' fast path included, so
204
+ * that is where the instance behind the proxy is handed over instead -
205
+ * what the explorer would have held without the agent. Only the receiver
206
+ * changes: the method is still the class's own, so `getHandler()`, guards,
207
+ * pipes and interceptors see what they saw before, and no span is added,
208
+ * as none is for any other resolver. A request-scoped resolver reads its
209
+ * method through the instance already, and is left alone.
210
+ *
211
+ * Patched on the prototype from the constructor, which Nest runs before any
212
+ * `onModuleInit`, `GraphQLModule`'s included, where the explorer does its
213
+ * work - synchronously, for the reason given on `loadOptionalPeer`. The
214
+ * original is parked under a symbol, so a second agent replaces the wrapper
215
+ * instead of wrapping it again.
216
+ */
217
+ patchResolversExplorer() {
218
+ // The entry point first, although it does not export the explorer: the
219
+ // explorer's file sits on an import cycle that only resolves when the
220
+ // package is entered the way an application enters it. Loaded on its
221
+ // own, it throws "Cannot access 'ResolversExplorerService' before
222
+ // initialization".
223
+ const entryPoint = loadOptionalPeer("@nestjs/graphql");
224
+ if (!entryPoint.installed || !entryPoint.module) {
225
+ // An optional peer; absent, or unable to load, it serves no resolvers.
226
+ return;
227
+ }
228
+ let explorer = entryPoint.module.ResolversExplorerService;
229
+ let loadError;
230
+ if (!explorer) {
231
+ const deepPath = loadOptionalPeer("@nestjs/graphql", "@nestjs/graphql/dist/services/resolvers-explorer.service.js");
232
+ if (deepPath.installed) {
233
+ explorer = deepPath.module?.ResolversExplorerService;
234
+ loadError = deepPath.error;
235
+ }
236
+ }
237
+ const prototype = explorer?.prototype;
238
+ const originalCreate = (prototype?.[ORIGINAL_CREATE_CONTEXT_CALLBACK] ??
239
+ prototype?.createContextCallback);
240
+ if (!prototype || typeof originalCreate !== "function") {
241
+ // Worth saying out loud: the symptom otherwise is a resolver that
242
+ // fails on its own private members for no visible reason.
243
+ const cause = loadError ? `: ${describePeerLoadError(loadError)}` : "";
244
+ this.logger.warn(`The installed version of @nestjs/graphql does not expose 'ResolversExplorerService.createContextCallback', so resolvers that use private members (#field) will throw when instrumented${cause}. Skipping patching.`);
245
+ return;
246
+ }
247
+ prototype[ORIGINAL_CREATE_CONTEXT_CALLBACK] = originalCreate;
248
+ prototype.createContextCallback = function (instance, resolverPrototype, wrapper, ...rest) {
249
+ // rest: [moduleRef, resolver, isRequestScoped, transform]
250
+ const receiver = rest[2] === true ? instance : resolverReceiverOf(instance, wrapper);
251
+ return originalCreate.call(this, receiver, resolverPrototype, wrapper, ...rest);
252
+ };
253
+ }
173
254
  /**
174
255
  * The start hook the host is given: this service's part first, so the span
175
256
  * covers the application's hook, then the application's, whose result is
@@ -241,7 +322,37 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
241
322
  ...parsed,
242
323
  operationName,
243
324
  });
325
+ const store = this.asyncLocalStorage.getStore();
326
+ // The registry key, where the transport in front gave the request one
327
+ // of its own; the trace id otherwise, which is then the key as well.
328
+ const traceId = store?.get(TRACE_REGISTRY_KEY) ??
329
+ store?.get(this.options.traceIdKey);
330
+ if (traceId) {
331
+ // Ahead of `ignore`, as every other transport does: what a resolver
332
+ // reads back with `TracerService.getAttribute` must not depend on
333
+ // whether the operation is recorded. `ignore` is asked about the
334
+ // document's first root field, which the client picks, and the
335
+ // resolvers of the fields behind it run all the same. With no
336
+ // transport in front there is no store yet; `startAsOperation` opens
337
+ // one and sets them there.
338
+ this.applyAttributes(info, ctx.context);
339
+ }
244
340
  if (shouldIgnoreSafely(this.options.graphql?.ignore, [info], this.options.graphql, this.logger, "graphql")) {
341
+ if (traceId && !this.operationTraceRegistry.hasOperationId(traceId)) {
342
+ // Not opening the operation's span is not enough where a transport
343
+ // in front opened a trace for the request, which it did before the
344
+ // operation was known. Left open, it went on recording every
345
+ // provider, guard and outbound call the operation made, failures
346
+ // with their stacks and headers included, and shipped them as
347
+ // `/graphql`. Dropped, the request goes on as one `http.ignore`
348
+ // excluded: its store keeps the key, and nothing is registered
349
+ // under it. Only while nothing has named the trace, though: a
350
+ // route handler that runs the operation in-process, or a batch an
351
+ // operation that is recorded leads, keeps its trace. The trace is
352
+ // the request's, so a batch an ignored operation leads is not
353
+ // recorded at all.
354
+ this.operationTraceRegistry.abandonTrace(traceId);
355
+ }
245
356
  return undefined;
246
357
  }
247
358
  const operationId = `${info.parentType.name}.${info.fieldName}`;
@@ -254,11 +365,6 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
254
365
  const attributes = {
255
366
  originalUrl: parsed.sanitizedDocument,
256
367
  };
257
- const store = this.asyncLocalStorage.getStore();
258
- // The registry key, where the transport in front gave the request one
259
- // of its own; the trace id otherwise, which is then the key as well.
260
- const traceId = store?.get(TRACE_REGISTRY_KEY) ??
261
- store?.get(this.options.traceIdKey);
262
368
  if (traceId) {
263
369
  return this.startWithinRequest(traceId, operationId, attributes, info, ctx);
264
370
  }
@@ -290,14 +396,16 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
290
396
  }
291
397
  state.ended = true;
292
398
  if (state.store) {
293
- // Handing the request back whatever owned it before this operation. The
294
- // store is shared by reference across the request, so this is a real
295
- // restore rather than a scoped one.
296
- if (state.previousCallerId === undefined) {
399
+ // Handing the request to an operation of its still open, or back to
400
+ // whatever owned it before them. The store is shared by reference
401
+ // across the request, so this is a real restore rather than a scoped
402
+ // one.
403
+ const callerId = this.closeOperation(state, state.store);
404
+ if (callerId === undefined) {
297
405
  state.store.delete(CALLER_METADATA_KEY);
298
406
  }
299
407
  else {
300
- state.store.set(CALLER_METADATA_KEY, state.previousCallerId);
408
+ state.store.set(CALLER_METADATA_KEY, callerId);
301
409
  }
302
410
  }
303
411
  this.operationTraceRegistry.internalEndTraceStep(state.traceId, `${state.className}#${state.methodKey}`, state.className, state.methodKey, state.spanId, error);
@@ -313,7 +421,6 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
313
421
  * shipping the snapshot.
314
422
  */
315
423
  startWithinRequest(traceId, operationId, attributes, info, ctx) {
316
- this.applyAttributes(info, ctx.context);
317
424
  this.operationTraceRegistry.addGraphQLMetadataToTrace(traceId, {
318
425
  operationId,
319
426
  tags: this.options.graphql?.tags,
@@ -381,7 +488,15 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
381
488
  const className = handler?.className ?? info.parentType.name;
382
489
  const methodKey = handler?.methodKey ?? info.fieldName;
383
490
  const store = this.asyncLocalStorage.getStore();
384
- const previousCallerId = store?.get(CALLER_METADATA_KEY);
491
+ // With another operation open in this store, the caller the store names
492
+ // is that operation: the one before this in a batch. This one takes the
493
+ // caller that one took instead, which makes the operations of a batch
494
+ // siblings - each a root span of the request, reporting its own failure.
495
+ const openOperations = store && this.openOperationsByStore.get(store);
496
+ const sibling = openOperations?.at(-1);
497
+ const previousCallerId = sibling
498
+ ? sibling.previousCallerId
499
+ : store?.get(CALLER_METADATA_KEY);
385
500
  const spanId = this.operationTraceRegistry.internalStartTraceStep(traceId, className, methodKey, previousCallerId);
386
501
  if (!spanId) {
387
502
  // The trace was sampled out, or never started - an HTTP request that
@@ -390,7 +505,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
390
505
  return undefined;
391
506
  }
392
507
  store?.set(CALLER_METADATA_KEY, spanId);
393
- return {
508
+ const state = {
394
509
  traceId,
395
510
  spanId,
396
511
  className,
@@ -400,6 +515,40 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
400
515
  ownsTrace,
401
516
  context: ctx.context,
402
517
  };
518
+ if (openOperations) {
519
+ openOperations.push(state);
520
+ }
521
+ else if (store) {
522
+ this.openOperationsByStore.set(store, [state]);
523
+ }
524
+ return state;
525
+ }
526
+ /**
527
+ * Takes the operations that have ended off the ones a store has open, and
528
+ * returns the caller the store names from here on.
529
+ *
530
+ * While another operation is open there, that is the one of them that
531
+ * started last, whichever just ended: the work still running in the store
532
+ * belongs to an open operation, and a slot emptied or left naming an ended
533
+ * span put it at the root of the trace, beside the operation, and had
534
+ * `activeSpan()` find nothing. Once the last has ended, it is the caller
535
+ * they displaced.
536
+ */
537
+ closeOperation(state, store) {
538
+ const openOperations = this.openOperationsByStore.get(store);
539
+ // Ended ones are dropped once nothing open is left above them, so a batch
540
+ // that ends in the order it started does not search the list every time.
541
+ while (openOperations?.at(-1)?.ended) {
542
+ openOperations.pop();
543
+ }
544
+ const current = openOperations?.at(-1);
545
+ if (current) {
546
+ return current.spanId;
547
+ }
548
+ this.openOperationsByStore.delete(store);
549
+ // The same for every operation of a batch: each later one took it from
550
+ // the one before.
551
+ return state.previousCallerId;
403
552
  }
404
553
  /**
405
554
  * Ends and ships a trace this service opened itself.
@@ -499,7 +648,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
499
648
  if (!store) {
500
649
  return;
501
650
  }
502
- setAttributesSafely(this.options.graphql.setAttributes, [info, context], this.options.graphql, store, this.logger, "graphql");
651
+ setAttributesSafely(this.options.graphql.setAttributes, [info, context], this.options.graphql, store, this.logger, "graphql", this.options.traceIdKey);
503
652
  }
504
653
  };
505
654
  GraphQLObserveAgentService = GraphQLObserveAgentService_1 = __decorate([
@@ -584,3 +733,28 @@ function toRefusal(first, error) {
584
733
  });
585
734
  return refusal;
586
735
  }
736
+ const ORIGINAL_CREATE_CONTEXT_CALLBACK = Symbol.for("nestjs.observe.graphql.createContextCallback");
737
+ /**
738
+ * The instance `@nestjs/graphql` applies a resolver's methods to: the one
739
+ * behind the instrumentation proxy for a class whose methods cannot run
740
+ * against the proxy, the container's own for every other.
741
+ *
742
+ * Only for a resolver registered under its own class. Nest finds the module
743
+ * of one registered under another token
744
+ * (`{ provide: "TOKEN", useClass: Resolver }`) by looking for the instance
745
+ * the container holds, and with any other it finds none: the resolver would
746
+ * run with the guards, pipes and interceptors that module provides silently
747
+ * left out. Such a resolver keeps the proxy, and still fails on its private
748
+ * members.
749
+ */
750
+ function resolverReceiverOf(instance, wrapper) {
751
+ const receiver = rawReceiverOf(instance);
752
+ if (receiver === undefined) {
753
+ return instance;
754
+ }
755
+ const token = wrapper?.token;
756
+ return typeof token === "function" &&
757
+ token.prototype === Object.getPrototypeOf(receiver)
758
+ ? receiver
759
+ : instance;
760
+ }
@@ -227,11 +227,14 @@ function readFirstFieldName(source, from) {
227
227
  /**
228
228
  * Blanks out comments, strings and numbers, so none can be mistaken for a name
229
229
  * or a brace. Offsets are not preserved - nothing downstream maps back to the
230
- * original text.
230
+ * original text. A document with a string that is never closed is kept only
231
+ * up to its first string.
231
232
  */
232
233
  function stripIgnoredTokens(document) {
233
234
  let out = "";
234
235
  let index = 0;
236
+ // Where in `out` the document's first string went.
237
+ let firstString = -1;
235
238
  while (index < document.length) {
236
239
  const char = document[index];
237
240
  // A comment ends at either line terminator, as graphql-js ends it. Read on
@@ -246,15 +249,21 @@ function stripIgnoredTokens(document) {
246
249
  continue;
247
250
  }
248
251
  if (char === '"') {
249
- if (document.startsWith('"""', index)) {
250
- index = endOfBlockString(document, index + 3);
252
+ if (firstString === -1) {
253
+ firstString = out.length;
251
254
  }
252
- else {
253
- index += 1;
254
- while (index < document.length && document[index] !== '"') {
255
- index += document[index] === "\\" ? 2 : 1;
256
- }
257
- index += 1;
255
+ index = document.startsWith('"""', index)
256
+ ? endOfBlockString(document, index + 3)
257
+ : endOfString(document, index + 1);
258
+ if (index === -1) {
259
+ // Never closed, so the server refuses the document - and its quotes
260
+ // do not pair. Paired regardless, a stray quote took the opening
261
+ // quote of the next literal for its close, and from there every
262
+ // string was recorded while the text between them was blanked. Which
263
+ // side of a quote is a literal cannot be told for the earlier quotes
264
+ // either: in `"24" monitor"`, the ` monitor` a user typed is already
265
+ // in `out`. Nothing from the first string on is recorded.
266
+ return out.slice(0, firstString) + "_";
258
267
  }
259
268
  // Left as a token that is neither a name nor a brace, so a default value
260
269
  // of `""` still reads as a value rather than as nothing at all.
@@ -296,17 +305,39 @@ function stripIgnoredTokens(document) {
296
305
  }
297
306
  /**
298
307
  * Where a block string that opened before `from` ends, its closing quotes
299
- * included. `\"""` is three quotes of content, as graphql-js reads it, not the
300
- * end: ended there, the rest of the literal was recorded as document syntax.
301
- * A block string has no other escape, so a backslash before the quotes always
302
- * escapes them.
308
+ * included, or -1 when it is never closed. `\"""` is three quotes of content,
309
+ * as graphql-js reads it, not the end: ended there, the rest of the literal
310
+ * was recorded as document syntax. A block string has no other escape, so a
311
+ * backslash before the quotes always escapes them.
303
312
  */
304
313
  function endOfBlockString(document, from) {
305
314
  let end = document.indexOf('"""', from);
306
315
  while (end > from && document[end - 1] === "\\") {
307
316
  end = document.indexOf('"""', end + 3);
308
317
  }
309
- return end === -1 ? document.length : end + 3;
318
+ return end === -1 ? -1 : end + 3;
319
+ }
320
+ /**
321
+ * Where a `"` string whose content starts at `from` ends, its closing quote
322
+ * included, or -1 when it is not closed on its line. graphql-js ends a string
323
+ * at a line terminator, and refuses it there: a quote found beyond one is the
324
+ * opening quote of the next literal. Only `\"` and `\\` are stepped over, so
325
+ * that a backslash cannot carry the scan past the line end either.
326
+ */
327
+ function endOfString(document, from) {
328
+ let index = from;
329
+ while (index < document.length) {
330
+ const char = document[index];
331
+ if (char === '"') {
332
+ return index + 1;
333
+ }
334
+ if (char === "\n" || char === "\r") {
335
+ return -1;
336
+ }
337
+ const next = document[index + 1];
338
+ index += char === "\\" && (next === '"' || next === "\\") ? 2 : 1;
339
+ }
340
+ return -1;
310
341
  }
311
342
  function isDigit(char) {
312
343
  return char >= "0" && char <= "9";
@@ -36,15 +36,22 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
36
36
  private warnedAboutHooks;
37
37
  private httpAdapterInitSubscription;
38
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.
39
+ * The registry key each request was started under, by the Node request -
40
+ * see `nodeRequestOf` - which every adapter hands to both of its hooks. The
41
+ * response hook cannot ask the async store: it runs from `finish`, in the
42
+ * async context of whatever ended the response, and that need not be the
43
+ * request's own. A request pipelined behind another has its `finish`
44
+ * emitted from the earlier one's; a stream piped into the response ends it
45
+ * where its source emits - for a pooled database connection, in the
46
+ * request that opened it. Taken out by the first response hook to run, so
47
+ * a request routed twice is completed once.
46
48
  */
47
49
  private readonly registryKeys;
50
+ /**
51
+ * The store each request runs in, by the Node request, for a request that
52
+ * comes through the router again - see `startHttpRequestTracing`.
53
+ */
54
+ private readonly requestStores;
48
55
  /**
49
56
  * `http.queryParamsObfuscateRegex`, rebuilt with the global flag when it was
50
57
  * supplied without one. It is applied with `replaceAll`, which throws on a
@@ -75,15 +75,22 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
75
75
  warnedAboutHooks = false;
76
76
  httpAdapterInitSubscription;
77
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.
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.
85
87
  */
86
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();
87
94
  /**
88
95
  * `http.queryParamsObfuscateRegex`, rebuilt with the global flag when it was
89
96
  * supplied without one. It is applied with `replaceAll`, which throws on a
@@ -146,9 +153,28 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
146
153
  * the adapter waits on or fails the request by what that hook returns.
147
154
  */
148
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
+ }
149
174
  // The same map `run` is given, rather than `getStore()` inside the callback:
150
175
  // identical object, one lookup fewer, and it is known to exist.
151
176
  const store = new Map();
177
+ this.requestStores.set(request, store);
152
178
  return this.asyncLocalStorage.run(store, () => {
153
179
  // OpenTelemetry interop runs only beside reporting to NestJS Observe -
154
180
  // see `ObserveAgentSharedBuffer.isReporting`. Asked once per request,
@@ -166,7 +192,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
166
192
  // lookups stay off a recorded request sharing its id.
167
193
  const registryKey = uuidv7();
168
194
  store.set(TRACE_REGISTRY_KEY, registryKey);
169
- this.registryKeys.set(req, registryKey);
195
+ this.registryKeys.set(request, registryKey);
170
196
  // Ended when the response closes, recorded or not, answered or
171
197
  // aborted: see `liveTraceId`.
172
198
  this.watchResponseClose(res, openOperation(store), registryKey);
@@ -184,7 +210,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
184
210
  if (traceContext) {
185
211
  store.set(TRACE_CONTEXT_KEY, traceContext);
186
212
  }
187
- 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);
188
214
  if (this.shouldIgnoreRequest(req) || this.isUntracedPreflight(req)) {
189
215
  return done();
190
216
  }
@@ -223,11 +249,15 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
223
249
  // here is that of whatever ended the response, a finished request's or
224
250
  // another one still running, and neither may be completed in this one's
225
251
  // 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 ||
230
- !this.operationTraceRegistry.hasTrace(registryKey)) {
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) {
255
+ return;
256
+ }
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)) {
231
261
  return;
232
262
  }
233
263
  deferTraceCompletion(async () => {
@@ -443,6 +473,19 @@ function testIgnoreRegex(pattern, value) {
443
473
  * an application's own `OPTIONS` handler is still traced as a request. Every
444
474
  * adapter lower-cases header names.
445
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
+ }
446
489
  function isPreflight(req) {
447
490
  return (req.method === "OPTIONS" &&
448
491
  req.headers?.["access-control-request-method"] !== undefined);
@@ -12,6 +12,13 @@ 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"]>;
17
24
  /** What a queue driver read back of a job's times. */