@nestjs/observe 0.2.3 → 0.3.0

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 (59) hide show
  1. package/README.md +38 -0
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/agent/telemetry-wire-contract.js +1 -0
  4. package/dist/encoders/request-snapshot.encoder.d.ts +1 -0
  5. package/dist/encoders/request-snapshot.encoder.js +1 -0
  6. package/dist/instrument/create-instance-decorator.instrument.js +2 -2
  7. package/dist/interfaces/observe-options.interface.d.ts +90 -4
  8. package/dist/interfaces/request-snapshot.interface.d.ts +8 -0
  9. package/dist/observe.constants.d.ts +16 -0
  10. package/dist/observe.constants.js +16 -0
  11. package/dist/observe.module.js +48 -4
  12. package/dist/outgoing/http.integration.d.ts +36 -0
  13. package/dist/outgoing/http.integration.js +127 -0
  14. package/dist/outgoing/mongodb.integration.d.ts +38 -0
  15. package/dist/outgoing/mongodb.integration.js +141 -0
  16. package/dist/outgoing/mysql2.integration.d.ts +20 -0
  17. package/dist/outgoing/mysql2.integration.js +89 -0
  18. package/dist/outgoing/outgoing-observe-agent.service.d.ts +17 -0
  19. package/dist/outgoing/outgoing-observe-agent.service.js +123 -0
  20. package/dist/outgoing/outgoing-span.recorder.d.ts +54 -0
  21. package/dist/outgoing/outgoing-span.recorder.js +94 -0
  22. package/dist/outgoing/patch-method.util.d.ts +15 -0
  23. package/dist/outgoing/patch-method.util.js +29 -0
  24. package/dist/outgoing/pg.integration.d.ts +22 -0
  25. package/dist/outgoing/pg.integration.js +66 -0
  26. package/dist/outgoing/sql-statement.util.d.ts +21 -0
  27. package/dist/outgoing/sql-statement.util.js +48 -0
  28. package/dist/protocols/bull-observe-agent.service.d.ts +28 -0
  29. package/dist/protocols/bull-observe-agent.service.js +130 -0
  30. package/dist/protocols/graphql-observe-agent.service.js +5 -2
  31. package/dist/protocols/graphql-operation-parser.d.ts +4 -4
  32. package/dist/protocols/graphql-operation-parser.js +28 -4
  33. package/dist/protocols/http-observe-agent.service.js +26 -7
  34. package/dist/protocols/job-trace-runner.d.ts +77 -0
  35. package/dist/protocols/job-trace-runner.js +196 -0
  36. package/dist/protocols/queue-observe-agent.service.d.ts +9 -4
  37. package/dist/protocols/queue-observe-agent.service.js +36 -95
  38. package/dist/protocols/ws-observe-agent.service.d.ts +39 -0
  39. package/dist/protocols/ws-observe-agent.service.js +180 -0
  40. package/dist/services/operation-trace.registry.d.ts +17 -1
  41. package/dist/services/operation-trace.registry.js +39 -7
  42. package/dist/services/trace-sampler.service.d.ts +4 -0
  43. package/dist/services/tracer.service.js +5 -3
  44. package/dist/utils/capture-request.util.d.ts +57 -0
  45. package/dist/utils/capture-request.util.js +116 -0
  46. package/dist/utils/default-trace-id-generator.util.d.ts +12 -0
  47. package/dist/utils/default-trace-id-generator.util.js +12 -1
  48. package/dist/utils/log-redactor.d.ts +20 -1
  49. package/dist/utils/log-redactor.js +54 -38
  50. package/dist/utils/optional-peer.util.d.ts +13 -0
  51. package/dist/utils/optional-peer.util.js +30 -0
  52. package/dist/utils/redact-url-query.d.ts +10 -1
  53. package/dist/utils/redact-url-query.js +16 -37
  54. package/dist/utils/sensitive-keys.d.ts +15 -0
  55. package/dist/utils/sensitive-keys.js +76 -0
  56. package/dist/utils/source-context.util.d.ts +6 -0
  57. package/dist/utils/source-context.util.js +113 -15
  58. package/dist/utils/source-map-resolver.util.js +12 -0
  59. package/package.json +35 -2
@@ -0,0 +1,130 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ var BullObserveAgentService_1;
14
+ import { Inject, Injectable, Logger } from "@nestjs/common";
15
+ import { AsyncLocalStorage } from "async_hooks";
16
+ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
17
+ import { OBSERVE_OPTIONS } from "../observe.constants.js";
18
+ import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
19
+ import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
20
+ import { JobTraceRunner } from "./job-trace-runner.js";
21
+ const ORIGINAL_SET_HANDLER = Symbol.for("nestjs.observe.bull.setHandler");
22
+ /** Bull names an unnamed job this; reporting it would name every job the same. */
23
+ const BULL_DEFAULT_JOB_NAME = "__default__";
24
+ /**
25
+ * Job tracing for the original Bull, which `@nestjs/bull` wraps - the same
26
+ * snapshots `@nestjs/bullmq` produces, from a driver a large share of Nest
27
+ * applications still run.
28
+ *
29
+ * Bull itself is patched rather than the Nest explorer: every processor, named
30
+ * or not, request-scoped or not, reaches the queue through `setHandler`, so
31
+ * one patch covers them all without depending on the explorer's internals.
32
+ */
33
+ let BullObserveAgentService = BullObserveAgentService_1 = class BullObserveAgentService {
34
+ logger = new Logger(BullObserveAgentService_1.name);
35
+ runner;
36
+ constructor(observeAgentSharedBuffer, options, operationTraceRegistry, asyncLocalStorage) {
37
+ this.runner = new JobTraceRunner(observeAgentSharedBuffer, options, operationTraceRegistry, asyncLocalStorage, this.logger);
38
+ this.patchBull();
39
+ }
40
+ loadQueuePrototype() {
41
+ const result = loadOptionalPeer("bull");
42
+ if (!result.installed) {
43
+ return undefined;
44
+ }
45
+ if (result.error) {
46
+ this.logger.warn(`bull is installed but could not be loaded, so its jobs will not be instrumented: ${describePeerLoadError(result.error)}`);
47
+ return null;
48
+ }
49
+ return result.module?.prototype ?? null;
50
+ }
51
+ readQueueMetadata(job) {
52
+ const metadata = {};
53
+ if (typeof job.timestamp === "number") {
54
+ metadata.enqueuedAt = new Date(job.timestamp).toISOString();
55
+ const startedAt = typeof job.processedOn === "number" ? job.processedOn : Date.now();
56
+ // As with BullMQ: a delay the caller asked for is a schedule, not a
57
+ // backlog, so the wait is measured from when the job became runnable.
58
+ // `||`, not `??`: the job's own `delay` reads 0 once Bull has promoted
59
+ // it, and only the options still say what was asked for.
60
+ const delay = job.delay || job.opts?.delay || 0;
61
+ metadata.waitDuration = Math.max(0, startedAt - (job.timestamp + delay));
62
+ }
63
+ if (typeof job.attemptsMade === "number") {
64
+ metadata.attemptsMade = job.attemptsMade;
65
+ }
66
+ if (typeof job.opts?.attempts === "number") {
67
+ metadata.maxAttempts = job.opts.attempts;
68
+ }
69
+ return metadata;
70
+ }
71
+ patchBull() {
72
+ const prototype = this.loadQueuePrototype();
73
+ if (prototype === undefined) {
74
+ // An optional peer. No Bull means no processor to wrap.
75
+ return;
76
+ }
77
+ const originalSetHandler = (prototype?.[ORIGINAL_SET_HANDLER] ??
78
+ prototype?.setHandler);
79
+ if (!prototype || typeof originalSetHandler !== "function") {
80
+ this.logger.warn("Bull's Queue.prototype.setHandler is not available, so its jobs will not be instrumented.");
81
+ return;
82
+ }
83
+ prototype[ORIGINAL_SET_HANDLER] = originalSetHandler;
84
+ const instrument = (handler) => this.instrument(handler);
85
+ prototype.setHandler = function (name, handler) {
86
+ // A string is a path to a sandboxed processor. It runs in a child
87
+ // process this agent is not loaded in, so there is nothing to wrap.
88
+ return originalSetHandler.call(this, name, typeof handler === "function"
89
+ ? instrument(handler)
90
+ : handler);
91
+ };
92
+ // add(name?, data, opts)
93
+ this.runner.patchEnqueue(prototype, (args) => typeof args[0] === "string" ? 2 : 1);
94
+ }
95
+ /**
96
+ * Bull decides between a promise and a callback handler by arity, after
97
+ * binding it to the queue - so each wrapper declares the parameters of the
98
+ * kind it stands in for, and leaves `this` to that bind.
99
+ */
100
+ instrument(handler) {
101
+ const describe = (job) => ({
102
+ queueName: job.queue?.name ?? "bull",
103
+ name: job.name && job.name !== BULL_DEFAULT_JOB_NAME
104
+ ? job.name
105
+ : job.queue?.name ?? "bull",
106
+ id: job.id,
107
+ opts: job.opts,
108
+ metadata: this.readQueueMetadata(job),
109
+ });
110
+ const runner = this.runner;
111
+ if (handler.length > 1) {
112
+ return function (job, done) {
113
+ return runner.run(describe(job), (settle) => handler.call(this, job, (error, value) => {
114
+ settle(error ? "failed" : "completed");
115
+ done?.(error, value);
116
+ }), true);
117
+ };
118
+ }
119
+ return function (job) {
120
+ return runner.run(describe(job), () => handler.call(this, job));
121
+ };
122
+ }
123
+ };
124
+ BullObserveAgentService = BullObserveAgentService_1 = __decorate([
125
+ Injectable(),
126
+ __param(1, Inject(OBSERVE_OPTIONS)),
127
+ __metadata("design:paramtypes", [ObserveAgentSharedBuffer, Object, OperationTraceRegistry,
128
+ AsyncLocalStorage])
129
+ ], BullObserveAgentService);
130
+ export { BullObserveAgentService };
@@ -15,7 +15,7 @@ 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 { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "../observe.constants.js";
18
+ import { CALLER_METADATA_KEY, OBSERVE_OPTIONS, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
19
19
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
20
20
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
21
21
  import { parseGraphQLOperation, toResolveInfoLike, } from "./graphql-operation-parser.js";
@@ -186,7 +186,10 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
186
186
  originalUrl: parsed.sanitizedDocument,
187
187
  };
188
188
  const store = this.asyncLocalStorage.getStore();
189
- const traceId = store?.get(this.options.traceIdKey);
189
+ // The registry key, where the transport in front gave the request one
190
+ // of its own; the trace id otherwise, which is then the key as well.
191
+ const traceId = store?.get(TRACE_REGISTRY_KEY) ??
192
+ store?.get(this.options.traceIdKey);
190
193
  if (traceId) {
191
194
  return this.startWithinRequest(traceId, operationId, attributes, info, ctx);
192
195
  }
@@ -7,10 +7,10 @@ export interface ParsedGraphQLOperation {
7
7
  /** The operation's name, when the document gave it one. */
8
8
  operationName?: string;
9
9
  /**
10
- * The document with comments dropped, string literals blanked to `_`, and
11
- * whitespace collapsed. What a trace records as the shape of the request:
12
- * stable across formatting, and stripped of the one token kind that
13
- * routinely carries user data inline.
10
+ * The document with comments dropped, string and number literals blanked to
11
+ * `_`, and whitespace collapsed. What a trace records as the shape of the
12
+ * request: stable across formatting, and stripped of the token kinds that
13
+ * carry user data inline.
14
14
  */
15
15
  sanitizedDocument: string;
16
16
  }
@@ -164,8 +164,7 @@ function truncate(document) {
164
164
  if (document.length <= MAX_SANITIZED_DOCUMENT_LENGTH) {
165
165
  return document;
166
166
  }
167
- return (document.slice(0, MAX_SANITIZED_DOCUMENT_LENGTH - TRUNCATION_SUFFIX.length) +
168
- TRUNCATION_SUFFIX);
167
+ return (document.slice(0, MAX_SANITIZED_DOCUMENT_LENGTH - TRUNCATION_SUFFIX.length) + TRUNCATION_SUFFIX);
169
168
  }
170
169
  /**
171
170
  * Reads the first field selected inside a selection set, seeing through an
@@ -205,8 +204,8 @@ function readFirstFieldName(source, from) {
205
204
  return undefined;
206
205
  }
207
206
  /**
208
- * Blanks out comments and strings, so neither can be mistaken for a name or a
209
- * brace. Offsets are not preserved - nothing downstream maps back to the
207
+ * Blanks out comments, strings and numbers, so none can be mistaken for a name
208
+ * or a brace. Offsets are not preserved - nothing downstream maps back to the
210
209
  * original text.
211
210
  */
212
211
  function stripIgnoredTokens(document) {
@@ -237,11 +236,36 @@ function stripIgnoredTokens(document) {
237
236
  out += "_";
238
237
  continue;
239
238
  }
239
+ // Numbers go the same way as strings. An inline `verifyOtp(code: 489213)`
240
+ // or `charge(amount: 1999)` is user data exactly as a string literal is,
241
+ // and blanking it also keeps `first: 10` and `first: 20` one shape. A
242
+ // digit that continues a name (`field2`, `$var1`) is not a literal.
243
+ const startsNumber = isDigit(char) || (char === "-" && isDigit(document[index + 1] ?? ""));
244
+ if (startsNumber && !isNameChar(out[out.length - 1] ?? "")) {
245
+ index += 1;
246
+ while (index < document.length && isNumberChar(document, index)) {
247
+ index += 1;
248
+ }
249
+ out += "_";
250
+ continue;
251
+ }
240
252
  out += char;
241
253
  index += 1;
242
254
  }
243
255
  return out;
244
256
  }
257
+ function isDigit(char) {
258
+ return char >= "0" && char <= "9";
259
+ }
260
+ /** Digits, the fraction point, and an exponent with its sign: `-1.5e+3`. */
261
+ function isNumberChar(document, index) {
262
+ const char = document[index];
263
+ if (isDigit(char) || char === "." || char === "e" || char === "E") {
264
+ return true;
265
+ }
266
+ const previous = document[index - 1];
267
+ return ((char === "+" || char === "-") && (previous === "e" || previous === "E"));
268
+ }
245
269
  function skipBalanced(source, from, open, close) {
246
270
  let depth = 0;
247
271
  let index = from;
@@ -11,13 +11,15 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
11
  return function (target, key) { decorator(target, key, paramIndex); }
12
12
  };
13
13
  import { Inject, Injectable, } from "@nestjs/common";
14
+ import { captureRequest, shouldCaptureRequest, } from "../utils/capture-request.util.js";
14
15
  import { HttpAdapterHost } from "@nestjs/core";
15
16
  import { AsyncLocalStorage } from "async_hooks";
16
17
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
17
- import { OBSERVE_OPTIONS } from "../observe.constants.js";
18
+ import { OBSERVE_OPTIONS, TRACE_REGISTRY_KEY } from "../observe.constants.js";
18
19
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
19
20
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
20
21
  import { redactUrlQuery } from "../utils/redact-url-query.js";
22
+ import { uuidv7 } from "../utils/uuid-v7.util.js";
21
23
  /**
22
24
  * How long an aborted request's handler gets to finish its spans before the
23
25
  * trace is dropped from the registry. Generous next to a typical handler, tiny
@@ -62,7 +64,8 @@ let HttpObserveAgentService = class HttpObserveAgentService {
62
64
  if (!store) {
63
65
  return;
64
66
  }
65
- const traceId = store.get(this.options.traceIdKey);
67
+ const traceId = store.get(TRACE_REGISTRY_KEY) ??
68
+ store.get(this.options.traceIdKey);
66
69
  if (!traceId) {
67
70
  return;
68
71
  }
@@ -120,19 +123,28 @@ let HttpObserveAgentService = class HttpObserveAgentService {
120
123
  // disclosure either way. A configured regex still applies, on top rather
121
124
  // than instead - it exists for the keys only that deployment knows
122
125
  // about.
123
- const redactedUrl = redactUrlQuery(req.url);
126
+ const redactedUrl = redactUrlQuery(req.url, this.operationTraceRegistry.getRedactor());
124
127
  const originalUrl = this.queryParamsObfuscateRegex
125
128
  ? redactedUrl.replaceAll(this.queryParamsObfuscateRegex, "[REDACTED]")
126
129
  : redactedUrl;
127
- this.operationTraceRegistry.startTrace(traceId, {
130
+ // An adopted `x-request-id` is not unique to this request: a caller
131
+ // that fans out, or retries, sends the same id twice, and both requests
132
+ // can be open here at once. The second gets a registry key of its own -
133
+ // only the second, so the ordinary request is still keyed by its id.
134
+ let registryKey = traceId;
135
+ if (this.operationTraceRegistry.hasTrace(traceId)) {
136
+ registryKey = uuidv7();
137
+ store.set(TRACE_REGISTRY_KEY, registryKey);
138
+ }
139
+ this.operationTraceRegistry.startTrace(registryKey, {
128
140
  protocol: req.protocol,
129
141
  tags: this.options.http?.tags,
130
142
  attributes: {
131
143
  method: req.method,
132
144
  originalUrl,
133
145
  },
134
- });
135
- this.evictTraceOnClientAbort(res, traceId);
146
+ }, traceId);
147
+ this.evictTraceOnClientAbort(res, registryKey);
136
148
  done();
137
149
  });
138
150
  }
@@ -141,7 +153,8 @@ let HttpObserveAgentService = class HttpObserveAgentService {
141
153
  if (!store) {
142
154
  return;
143
155
  }
144
- const traceId = store.get(this.options.traceIdKey);
156
+ const traceId = store.get(TRACE_REGISTRY_KEY) ??
157
+ store.get(this.options.traceIdKey);
145
158
  if (!traceId) {
146
159
  return;
147
160
  }
@@ -158,6 +171,12 @@ let HttpObserveAgentService = class HttpObserveAgentService {
158
171
  if (!snapshot) {
159
172
  return;
160
173
  }
174
+ if (shouldCaptureRequest(snapshot, this.options.http?.capture)) {
175
+ const captured = captureRequest(req, this.options.http?.capture, this.operationTraceRegistry.getRedactor());
176
+ if (captured) {
177
+ snapshot.request = captured;
178
+ }
179
+ }
161
180
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
162
181
  }, 0);
163
182
  }
@@ -0,0 +1,77 @@
1
+ import { Logger } from "@nestjs/common";
2
+ import { AsyncLocalStorage } from "async_hooks";
3
+ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
4
+ import { JobSnapshot, ObserveModuleOptionsWithDefaults } from "../interfaces/index.js";
5
+ import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
6
+ import { KeyOf } from "../types/key-of.type.js";
7
+ /** What a queue driver knows about the run it is about to start. */
8
+ export interface JobRunDescriptor {
9
+ queueName: string;
10
+ name: string;
11
+ id?: string | number;
12
+ /** The job's options as the driver read them back from Redis. */
13
+ opts?: Record<string, unknown>;
14
+ metadata: Partial<JobSnapshot>;
15
+ }
16
+ type JobStatus = NonNullable<JobSnapshot["status"]>;
17
+ /** The slice of a queue's prototype the enqueue patch touches. */
18
+ interface QueuePrototypeLike {
19
+ add?: (...args: any[]) => unknown;
20
+ addBulk?: (jobs: any[]) => unknown;
21
+ [key: symbol]: unknown;
22
+ }
23
+ /**
24
+ * The part of job tracing that is the same whichever driver runs the queue:
25
+ * stamping the active trace id onto a job as it is enqueued, and opening the
26
+ * run under that id when a worker picks it up.
27
+ *
28
+ * A plain class rather than a provider - each driver agent builds its own from
29
+ * what it was injected with, so supporting another driver adds no wiring to
30
+ * the module.
31
+ */
32
+ export declare class JobTraceRunner<Store extends Record<string, unknown>> {
33
+ private readonly observeAgentSharedBuffer;
34
+ private readonly options;
35
+ private readonly operationTraceRegistry;
36
+ private readonly asyncLocalStorage;
37
+ private readonly logger;
38
+ constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>, logger: Logger);
39
+ /**
40
+ * Makes `add` and `addBulk` carry the enqueuing operation's trace id, so the
41
+ * run reports under the request - or job, or cron firing - that caused it.
42
+ *
43
+ * The originals are parked on the prototype under a symbol: a second agent
44
+ * (a second Nest app in one process, a test suite) replaces the wrapper
45
+ * instead of wrapping it again.
46
+ */
47
+ patchEnqueue(prototype: QueuePrototypeLike,
48
+ /** Index of the options argument in `add`, given the arguments passed. */
49
+ optsIndexOf: (args: unknown[]) => number): void;
50
+ /**
51
+ * Returns the options with the active trace id added, or `undefined` when
52
+ * there is nothing to add.
53
+ *
54
+ * A repeatable job is left alone: every repetition would otherwise report
55
+ * under the one request that happened to register the schedule, for as long
56
+ * as the schedule lives. Those runs are cron firings, and each mints its own
57
+ * id like any other.
58
+ */
59
+ private stampTraceId;
60
+ /**
61
+ * The id stamped at enqueue time, if it is one this agent would have minted
62
+ * or adopted itself. Job options are readable and writable by anything with
63
+ * access to Redis, so it is held to the same shape as an inbound
64
+ * `x-request-id`.
65
+ */
66
+ private readInheritedTraceId;
67
+ /**
68
+ * Runs one job under a trace.
69
+ *
70
+ * `invoke` is handed `settle` for drivers whose handlers finish through a
71
+ * callback; pass `settlesItself` for those, and a plain return is then not
72
+ * read as completion. Promise-returning and throwing handlers are settled
73
+ * here either way.
74
+ */
75
+ run<T>(job: JobRunDescriptor, invoke: (settle: (status: JobStatus) => void) => T, settlesItself?: boolean): T;
76
+ }
77
+ export {};
@@ -0,0 +1,196 @@
1
+ import { JOB_TRACE_OPTION_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
2
+ import { REQUEST_ID_PATTERN } from "../utils/default-trace-id-generator.util.js";
3
+ import { uuidv7 } from "../utils/uuid-v7.util.js";
4
+ const ORIGINAL_ADD = Symbol.for("nestjs.observe.queue.add");
5
+ const ORIGINAL_ADD_BULK = Symbol.for("nestjs.observe.queue.addBulk");
6
+ /**
7
+ * The part of job tracing that is the same whichever driver runs the queue:
8
+ * stamping the active trace id onto a job as it is enqueued, and opening the
9
+ * run under that id when a worker picks it up.
10
+ *
11
+ * A plain class rather than a provider - each driver agent builds its own from
12
+ * what it was injected with, so supporting another driver adds no wiring to
13
+ * the module.
14
+ */
15
+ export class JobTraceRunner {
16
+ observeAgentSharedBuffer;
17
+ options;
18
+ operationTraceRegistry;
19
+ asyncLocalStorage;
20
+ logger;
21
+ constructor(observeAgentSharedBuffer, options, operationTraceRegistry, asyncLocalStorage, logger) {
22
+ this.observeAgentSharedBuffer = observeAgentSharedBuffer;
23
+ this.options = options;
24
+ this.operationTraceRegistry = operationTraceRegistry;
25
+ this.asyncLocalStorage = asyncLocalStorage;
26
+ this.logger = logger;
27
+ }
28
+ /**
29
+ * Makes `add` and `addBulk` carry the enqueuing operation's trace id, so the
30
+ * run reports under the request - or job, or cron firing - that caused it.
31
+ *
32
+ * The originals are parked on the prototype under a symbol: a second agent
33
+ * (a second Nest app in one process, a test suite) replaces the wrapper
34
+ * instead of wrapping it again.
35
+ */
36
+ patchEnqueue(prototype,
37
+ /** Index of the options argument in `add`, given the arguments passed. */
38
+ optsIndexOf) {
39
+ const stamp = (opts) => this.stampTraceId(opts);
40
+ const originalAdd = (prototype[ORIGINAL_ADD] ??= prototype.add);
41
+ if (typeof originalAdd === "function") {
42
+ prototype.add = function (...args) {
43
+ const index = optsIndexOf(args);
44
+ const stamped = stamp(args[index]);
45
+ if (stamped) {
46
+ args[index] = stamped;
47
+ }
48
+ return originalAdd.apply(this, args);
49
+ };
50
+ }
51
+ const originalAddBulk = (prototype[ORIGINAL_ADD_BULK] ??=
52
+ prototype.addBulk);
53
+ if (typeof originalAddBulk === "function") {
54
+ prototype.addBulk = function (jobs) {
55
+ if (!Array.isArray(jobs)) {
56
+ return originalAddBulk.call(this, jobs);
57
+ }
58
+ return originalAddBulk.call(this, jobs.map((job) => {
59
+ const stamped = stamp(job?.opts);
60
+ return stamped ? { ...job, opts: stamped } : job;
61
+ }));
62
+ };
63
+ }
64
+ }
65
+ /**
66
+ * Returns the options with the active trace id added, or `undefined` when
67
+ * there is nothing to add.
68
+ *
69
+ * A repeatable job is left alone: every repetition would otherwise report
70
+ * under the one request that happened to register the schedule, for as long
71
+ * as the schedule lives. Those runs are cron firings, and each mints its own
72
+ * id like any other.
73
+ */
74
+ stampTraceId(opts) {
75
+ const traceId = this.asyncLocalStorage
76
+ .getStore()
77
+ ?.get(this.options.traceIdKey);
78
+ if (typeof traceId !== "string") {
79
+ return undefined;
80
+ }
81
+ if (opts !== undefined && (typeof opts !== "object" || opts === null)) {
82
+ return undefined;
83
+ }
84
+ const current = (opts ?? {});
85
+ if (current["repeat"] || current[JOB_TRACE_OPTION_KEY] !== undefined) {
86
+ return undefined;
87
+ }
88
+ return { ...current, [JOB_TRACE_OPTION_KEY]: traceId };
89
+ }
90
+ /**
91
+ * The id stamped at enqueue time, if it is one this agent would have minted
92
+ * or adopted itself. Job options are readable and writable by anything with
93
+ * access to Redis, so it is held to the same shape as an inbound
94
+ * `x-request-id`.
95
+ */
96
+ readInheritedTraceId(opts) {
97
+ const inherited = opts?.[JOB_TRACE_OPTION_KEY];
98
+ return typeof inherited === "string" && REQUEST_ID_PATTERN.test(inherited)
99
+ ? inherited
100
+ : undefined;
101
+ }
102
+ /**
103
+ * Runs one job under a trace.
104
+ *
105
+ * `invoke` is handed `settle` for drivers whose handlers finish through a
106
+ * callback; pass `settlesItself` for those, and a plain return is then not
107
+ * read as completion. Promise-returning and throwing handlers are settled
108
+ * here either way.
109
+ */
110
+ run(job, invoke, settlesItself = false) {
111
+ const hasOuterContext = this.asyncLocalStorage
112
+ .getStore()
113
+ ?.has(this.options.traceIdKey);
114
+ // The same map `run` is given, rather than `getStore()` inside the
115
+ // callback: identical object, one lookup fewer, and it is known to exist.
116
+ const store = new Map();
117
+ return this.asyncLocalStorage.run(store, () => {
118
+ if (hasOuterContext) {
119
+ // If the outer context already has a trace ID
120
+ // ignore the inner context
121
+ if (this.options.debug) {
122
+ this.logger.debug(`Outer context already has a trace ID. Skipping inner context for job "${job.name}" job.id: ${job.id}`);
123
+ }
124
+ return invoke(() => undefined);
125
+ }
126
+ // The registry key is always this run's own. The inherited id may belong
127
+ // to a request still open in this process, and a retry reuses it.
128
+ const registryKey = uuidv7();
129
+ const traceId = this.readInheritedTraceId(job.opts) ?? registryKey;
130
+ store.set(this.options.traceIdKey, traceId);
131
+ store.set(TRACE_REGISTRY_KEY, registryKey);
132
+ const attributes = this.options.jobs?.setAttributes?.({
133
+ queueName: job.queueName,
134
+ name: job.name,
135
+ id: job.id,
136
+ });
137
+ if (attributes) {
138
+ for (const [key, value] of Object.entries(attributes)) {
139
+ store.set(key, value);
140
+ }
141
+ }
142
+ this.operationTraceRegistry.startTrace(registryKey, {
143
+ tags: this.options.jobs?.tags,
144
+ queueName: job.queueName,
145
+ name: job.name,
146
+ id: typeof job.id === "number" ? `${job.id}` : job.id,
147
+ ...job.metadata,
148
+ }, traceId);
149
+ let settled = false;
150
+ const settle = (status) => {
151
+ if (settled) {
152
+ return;
153
+ }
154
+ settled = true;
155
+ setTimeout(async () => {
156
+ this.operationTraceRegistry.endTrace(registryKey, { status });
157
+ const snapshot = (await this.operationTraceRegistry.pluckSnapshot(registryKey));
158
+ // `pluckSnapshot` deletes what it returns, so a trace already
159
+ // plucked answers undefined, and the encoder would dereference it
160
+ // inside a `setTimeout`, where no try/catch can reach: an unhandled
161
+ // TypeError that took the whole process down.
162
+ //
163
+ // Dropped rather than reported: there is no snapshot, so there is
164
+ // nothing to send, and losing one job's self-instrumentation is
165
+ // not worth a crash loop.
166
+ if (!snapshot) {
167
+ return;
168
+ }
169
+ this.observeAgentSharedBuffer.insertJobSnapshot(snapshot);
170
+ }, 0);
171
+ };
172
+ try {
173
+ const returnValue = invoke(settle);
174
+ if (returnValue instanceof Promise) {
175
+ return returnValue
176
+ .then((ret) => {
177
+ settle("completed");
178
+ return ret;
179
+ })
180
+ .catch((error) => {
181
+ settle("failed");
182
+ throw error;
183
+ });
184
+ }
185
+ if (!settlesItself) {
186
+ settle("completed");
187
+ }
188
+ return returnValue;
189
+ }
190
+ catch (error) {
191
+ settle("failed");
192
+ throw error;
193
+ }
194
+ });
195
+ }
196
+ }
@@ -4,11 +4,8 @@ import { ObserveModuleOptionsWithDefaults } from "../interfaces/index.js";
4
4
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
5
5
  import { KeyOf } from "../types/key-of.type.js";
6
6
  export declare class QueueObserveAgentService<Store extends Record<string, unknown>> {
7
- private readonly observeAgentSharedBuffer;
8
- private readonly options;
9
- private readonly operationTraceRegistry;
10
- private readonly asyncLocalStorage;
11
7
  private readonly logger;
8
+ private readonly runner;
12
9
  constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>);
13
10
  /**
14
11
  * Queue-level facts BullMQ already tracks but that never reached telemetry:
@@ -29,4 +26,12 @@ export declare class QueueObserveAgentService<Store extends Record<string, unkno
29
26
  */
30
27
  private loadProcessorDecoratorService;
31
28
  private patchDecorate;
29
+ /**
30
+ * The enqueuing half: without it a worker has no way to learn which
31
+ * operation a job came from, and every run opens an unrelated trace.
32
+ *
33
+ * `bullmq` is loaded the way `@nestjs/bullmq` loads it, so the prototype
34
+ * patched here is the one behind every `@InjectQueue()`.
35
+ */
36
+ private patchQueue;
32
37
  }