@nestjs/observe 0.1.1 → 0.1.3

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.
@@ -401,6 +401,13 @@ export interface ObserveOptions {
401
401
  };
402
402
  /**
403
403
  * Jobs configuration options for the Observe APM.
404
+ *
405
+ * Covers every handler reported as a job: BullMQ processors, and the
406
+ * `@Cron`, `@Interval` and `@Timeout` handlers of `@nestjs/schedule`. For a
407
+ * scheduled handler the scheduler type (`cron`, `interval`, `timeout`)
408
+ * stands in for `queueName`, the decorator's `name` option - or
409
+ * `ClassName.methodName` when none was given - for `name`, and every firing
410
+ * gets a fresh `id`.
404
411
  */
405
412
  jobs?: {
406
413
  /**
@@ -418,9 +425,13 @@ export interface ObserveOptions {
418
425
  * @default (job) => ({})
419
426
  */
420
427
  setAttributes?: (job: {
428
+ /** The BullMQ queue, or the scheduler type for a scheduled handler. */
421
429
  queueName: string;
422
430
  name: string;
423
- /** Absent until the queue driver has assigned one. */
431
+ /**
432
+ * Absent until the queue driver has assigned one. Always present for a
433
+ * scheduled handler, where it identifies this particular firing.
434
+ */
424
435
  id: string | undefined;
425
436
  }) => {
426
437
  [key: string]: string | number | boolean;
@@ -21,6 +21,7 @@ import { GraphQLObserveAgentService } from "./protocols/graphql-observe-agent.se
21
21
  import { HttpObserveAgentService } from "./protocols/http-observe-agent.service.js";
22
22
  import { QueueObserveAgentService } from "./protocols/queue-observe-agent.service.js";
23
23
  import { RpcObserveAgentService } from "./protocols/rpc-observe-agent.service.js";
24
+ import { ScheduleObserveAgentService } from "./protocols/schedule-observe-agent.service.js";
24
25
  import { LoggerPatcherService } from "./services/logger-patcher.service.js";
25
26
  import { NodeRuntimeMetricsService } from "./services/node-runtime-metrics.service.js";
26
27
  import { OperationTraceRegistry } from "./services/operation-trace.registry.js";
@@ -155,6 +156,9 @@ export function createObserveModule(options = {}) {
155
156
  // `forwardLogs` is enabled, and it redacts before anything is buffered.
156
157
  StdoutForwarderService,
157
158
  QueueObserveAgentService,
159
+ // A no-op unless @nestjs/schedule is installed; it patches the explorer
160
+ // from its constructor so the patch lands before any handler is found.
161
+ ScheduleObserveAgentService,
158
162
  ],
159
163
  exports: [AsyncLocalStorage, TracerService],
160
164
  }),
@@ -175,6 +179,8 @@ export function createObserveModule(options = {}) {
175
179
  // it would put a span for the agent itself at the root of every
176
180
  // GraphQL operation it records.
177
181
  instance instanceof GraphQLObserveAgentService ||
182
+ // Same reason: its wrapper runs inside the job traces it opens.
183
+ instance instanceof ScheduleObserveAgentService ||
178
184
  // Nest's discovery machinery, which the GraphQL agent walks to
179
185
  // map root fields back to their resolver classes. It has to stay
180
186
  // unproxied: ModulesContainer extends Map, and a Map method
@@ -19,5 +19,14 @@ export declare class QueueObserveAgentService<Store extends Record<string, unkno
19
19
  * omitted rather than reported as zero.
20
20
  */
21
21
  private readQueueMetadata;
22
+ /**
23
+ * Loads `@nestjs/bullmq`'s processor decorator without a static import, so a
24
+ * service that runs no queue need not install the package. The prototype is
25
+ * patched from the constructor, strictly before any processor is decorated.
26
+ *
27
+ * Returns `undefined` when the package is not installed and `null` when it
28
+ * is, but does not expose the decorator service where expected.
29
+ */
30
+ private loadProcessorDecoratorService;
22
31
  private patchDecorate;
23
32
  }
@@ -11,13 +11,13 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
11
  return function (target, key) { decorator(target, key, paramIndex); }
12
12
  };
13
13
  var QueueObserveAgentService_1;
14
- import { ProcessorDecoratorService } from "@nestjs/bullmq/dist/instrument/processor-decorator.service.js";
15
14
  import { Inject, Injectable, Logger } from "@nestjs/common";
16
15
  import { AsyncLocalStorage } from "async_hooks";
17
16
  import { randomUUID } from "crypto";
18
17
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
19
18
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
20
19
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
20
+ import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
21
21
  let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAgentService {
22
22
  observeAgentSharedBuffer;
23
23
  options;
@@ -62,7 +62,35 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
62
62
  }
63
63
  return metadata;
64
64
  }
65
+ /**
66
+ * Loads `@nestjs/bullmq`'s processor decorator without a static import, so a
67
+ * service that runs no queue need not install the package. The prototype is
68
+ * patched from the constructor, strictly before any processor is decorated.
69
+ *
70
+ * Returns `undefined` when the package is not installed and `null` when it
71
+ * is, but does not expose the decorator service where expected.
72
+ */
73
+ loadProcessorDecoratorService() {
74
+ const result = loadOptionalPeer("@nestjs/bullmq", "@nestjs/bullmq/dist/instrument/processor-decorator.service.js");
75
+ if (!result.installed) {
76
+ return undefined;
77
+ }
78
+ if (result.error) {
79
+ // The real cause - a version that moved the file, an exports map that
80
+ // hides it - so the "update to the latest version" advice below is
81
+ // never the only diagnostic.
82
+ this.logger.warn(`@nestjs/bullmq is installed but its processor decorator could not be loaded: ${describePeerLoadError(result.error)}`);
83
+ return null;
84
+ }
85
+ return result.module?.ProcessorDecoratorService ?? null;
86
+ }
65
87
  patchDecorate() {
88
+ const ProcessorDecoratorService = this.loadProcessorDecoratorService();
89
+ if (ProcessorDecoratorService === undefined) {
90
+ // The @nestjs/bullmq package is an optional peer. No queue means no
91
+ // processor to wrap, and that is not a misconfiguration.
92
+ return;
93
+ }
66
94
  if (!ProcessorDecoratorService?.prototype) {
67
95
  this.logger.warn("ProcessorDecoratorService is not available. Please, update to the latest version of @nestjs/bullmq. Skipping patching.");
68
96
  return;
@@ -1,6 +1,6 @@
1
1
  import { OnModuleDestroy, OnModuleInit } from "@nestjs/common";
2
2
  import { ModulesContainer } from "@nestjs/core";
3
- import { BaseRpcContext, Server, Transport } from "@nestjs/microservices";
3
+ import type { BaseRpcContext, Server, Transport } from "@nestjs/microservices";
4
4
  import { AsyncLocalStorage } from "async_hooks";
5
5
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
6
6
  import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.interface.js";
@@ -19,10 +19,25 @@ export declare class RpcObserveAgentService<Store extends Record<string, unknown
19
19
  private readonly operationTraceRegistry;
20
20
  private readonly observeAgentSharedBuffer;
21
21
  private readonly traceSamplerService;
22
+ private readonly logger;
22
23
  private rpcTargetAddedSubscription;
24
+ /**
25
+ * Assigned in `onModuleInit`. Every use below is reached only through the
26
+ * hooks registered there, after a successful load - a service without the
27
+ * package has no RPC target to hook.
28
+ */
29
+ private microservices;
23
30
  constructor(asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>, options: ObserveModuleOptionsWithDefaults, modulesContainer: ModulesContainer, operationTraceRegistry: OperationTraceRegistry, observeAgentSharedBuffer: ObserveAgentSharedBuffer, traceSamplerService: TraceSamplerService);
24
31
  onModuleInit(): void;
25
32
  onModuleDestroy(): void;
33
+ /**
34
+ * Loads `@nestjs/microservices` without a static import, so a service that
35
+ * exposes no microservice need not install the package. Loaded here rather
36
+ * than lazily because the target registry is subscribed from `onModuleInit`,
37
+ * and a dynamic `import()` would resolve after a target may already have
38
+ * been announced.
39
+ */
40
+ private loadMicroservices;
26
41
  registerRpcHooks(target: Server): void;
27
42
  /**
28
43
  * Names the transport for the snapshot's `protocol` field.
@@ -10,22 +10,30 @@ var __metadata = (this && this.__metadata) || function (k, v) {
10
10
  var __param = (this && this.__param) || function (paramIndex, decorator) {
11
11
  return function (target, key) { decorator(target, key, paramIndex); }
12
12
  };
13
- import { Inject, Injectable, } from "@nestjs/common";
13
+ var RpcObserveAgentService_1;
14
+ import { Inject, Injectable, Logger, } from "@nestjs/common";
14
15
  import { ModulesContainer } from "@nestjs/core";
15
- import { KafkaContext, MqttContext, NatsContext, RedisContext, RmqContext, TcpContext, Transport, } from "@nestjs/microservices";
16
16
  import { AsyncLocalStorage } from "async_hooks";
17
17
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
18
18
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
19
19
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
20
20
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
21
- let RpcObserveAgentService = class RpcObserveAgentService {
21
+ import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
22
+ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentService {
22
23
  asyncLocalStorage;
23
24
  options;
24
25
  modulesContainer;
25
26
  operationTraceRegistry;
26
27
  observeAgentSharedBuffer;
27
28
  traceSamplerService;
29
+ logger = new Logger(RpcObserveAgentService_1.name);
28
30
  rpcTargetAddedSubscription;
31
+ /**
32
+ * Assigned in `onModuleInit`. Every use below is reached only through the
33
+ * hooks registered there, after a successful load - a service without the
34
+ * package has no RPC target to hook.
35
+ */
36
+ microservices;
29
37
  constructor(asyncLocalStorage, options, modulesContainer, operationTraceRegistry, observeAgentSharedBuffer, traceSamplerService) {
30
38
  this.asyncLocalStorage = asyncLocalStorage;
31
39
  this.options = options;
@@ -35,6 +43,10 @@ let RpcObserveAgentService = class RpcObserveAgentService {
35
43
  this.traceSamplerService = traceSamplerService;
36
44
  }
37
45
  onModuleInit() {
46
+ this.microservices = this.loadMicroservices();
47
+ if (!this.microservices) {
48
+ return;
49
+ }
38
50
  this.rpcTargetAddedSubscription = this.modulesContainer
39
51
  .getRpcTargetRegistry?.()
40
52
  .subscribe((target) => this.registerRpcHooks(target));
@@ -44,9 +56,31 @@ let RpcObserveAgentService = class RpcObserveAgentService {
44
56
  this.rpcTargetAddedSubscription.unsubscribe();
45
57
  }
46
58
  }
59
+ /**
60
+ * Loads `@nestjs/microservices` without a static import, so a service that
61
+ * exposes no microservice need not install the package. Loaded here rather
62
+ * than lazily because the target registry is subscribed from `onModuleInit`,
63
+ * and a dynamic `import()` would resolve after a target may already have
64
+ * been announced.
65
+ */
66
+ loadMicroservices() {
67
+ const result = loadOptionalPeer("@nestjs/microservices");
68
+ if (!result.installed) {
69
+ // No microservice means no RPC target to hook, and that is not a
70
+ // misconfiguration.
71
+ return undefined;
72
+ }
73
+ if (!result.module) {
74
+ // Installed but unloadable is a misconfiguration, and the symptom
75
+ // otherwise is a service whose RPC operations silently never appear.
76
+ this.logger.warn(`@nestjs/microservices is installed but could not be loaded, so RPC operations will not be instrumented: ${describePeerLoadError(result.error)}`);
77
+ return undefined;
78
+ }
79
+ return result.module;
80
+ }
47
81
  registerRpcHooks(target) {
48
82
  target.setOnProcessingStartHook((transportId, ctx, done) => {
49
- if (transportId === Transport.GRPC) {
83
+ if (transportId === this.microservices.Transport.GRPC) {
50
84
  this.startGrpcRequestTracing(transportId, ctx, done);
51
85
  return;
52
86
  }
@@ -66,7 +100,7 @@ let RpcObserveAgentService = class RpcObserveAgentService {
66
100
  toProtocolName(transportId) {
67
101
  return typeof transportId === "symbol"
68
102
  ? transportId.description ?? "custom"
69
- : Transport[transportId];
103
+ : this.microservices.Transport[transportId];
70
104
  }
71
105
  startRpcRequestTracing(transportId, ctx, done) {
72
106
  // The same map `run` is given, rather than `getStore()` inside the callback:
@@ -147,7 +181,7 @@ let RpcObserveAgentService = class RpcObserveAgentService {
147
181
  }
148
182
  setTimeout(async () => {
149
183
  let userId;
150
- if (transportId === Transport.GRPC) {
184
+ if (transportId === this.microservices.Transport.GRPC) {
151
185
  if (this.options.grpc?.getUserId) {
152
186
  userId = this.options.grpc?.getUserId?.(ctx);
153
187
  }
@@ -168,6 +202,7 @@ let RpcObserveAgentService = class RpcObserveAgentService {
168
202
  }, 0);
169
203
  }
170
204
  getOperationIdFromContext(ctx) {
205
+ const { KafkaContext, MqttContext, NatsContext, RedisContext, RmqContext, TcpContext, } = this.microservices;
171
206
  switch (true) {
172
207
  case ctx instanceof KafkaContext:
173
208
  case ctx instanceof MqttContext:
@@ -179,12 +214,18 @@ let RpcObserveAgentService = class RpcObserveAgentService {
179
214
  return ctx.getChannel();
180
215
  case ctx instanceof NatsContext:
181
216
  return ctx.getSubject();
182
- default:
183
- throw new Error(`Unsupported context type: ${ctx.constructor.name}`);
217
+ default: {
218
+ // A custom transporter delivers its own context class - expected, per
219
+ // `toProtocolName` - and there is no universal accessor for its
220
+ // routing key. Throwing here would fail the message before `done()`
221
+ // ever ran, so fall back to a conventional accessor when one exists.
222
+ const pattern = ctx?.getPattern?.();
223
+ return typeof pattern === "string" ? pattern : "unknown";
224
+ }
184
225
  }
185
226
  }
186
227
  };
187
- RpcObserveAgentService = __decorate([
228
+ RpcObserveAgentService = RpcObserveAgentService_1 = __decorate([
188
229
  Injectable(),
189
230
  __param(1, Inject(OBSERVE_OPTIONS)),
190
231
  __metadata("design:paramtypes", [AsyncLocalStorage, Object, ModulesContainer,
@@ -0,0 +1,54 @@
1
+ import { AsyncLocalStorage } from "async_hooks";
2
+ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
3
+ import { ObserveModuleOptionsWithDefaults } from "../interfaces/index.js";
4
+ import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
5
+ import { KeyOf } from "../types/key-of.type.js";
6
+ /**
7
+ * Scheduled job instrumentation for `@nestjs/schedule`.
8
+ *
9
+ * A `@Cron`, `@Interval` or `@Timeout` handler fires from a timer, so no
10
+ * request ever reaches it and none of the protocol agents see it run. Left
11
+ * alone, a nightly job that takes twenty minutes or fails every other night is
12
+ * invisible: the instance decorator only records spans inside a trace, and
13
+ * nothing opened one.
14
+ *
15
+ * `ScheduleExplorer` routes every handler it discovers through
16
+ * `wrapFunctionInTryCatchBlocks(methodRef, instance)` before registering it
17
+ * with the orchestrator - one seam that covers all three decorators. It is
18
+ * patched on the prototype from this constructor, which Nest runs while it is
19
+ * still instantiating providers and therefore strictly before any
20
+ * `onModuleInit`, including the explorer's own, where discovery happens. The
21
+ * explorer's wrapper is kept and ours goes inside it, so a throwing handler is
22
+ * still logged by the scheduler exactly as before - it is just also reported.
23
+ *
24
+ * Each execution is reported as a job snapshot, the same shape BullMQ jobs
25
+ * use: the scheduler type stands in for the queue name and the handler for the
26
+ * job name, so `cron / ReportsService.nightly` sits alongside
27
+ * `emails / send-welcome` in the same view.
28
+ */
29
+ export declare class ScheduleObserveAgentService<Store extends Record<string, unknown>> {
30
+ private readonly observeAgentSharedBuffer;
31
+ private readonly options;
32
+ private readonly operationTraceRegistry;
33
+ private readonly asyncLocalStorage;
34
+ private readonly logger;
35
+ constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>);
36
+ /**
37
+ * Loads the explorer without a static import, so a service that schedules
38
+ * nothing need not install the package. Loaded from the constructor because
39
+ * a dynamic `import()` would resolve after provider instantiation, with no
40
+ * guarantee of landing before the explorer's `onModuleInit` has already
41
+ * wrapped every handler.
42
+ */
43
+ private loadScheduleExplorer;
44
+ private patchScheduleExplorer;
45
+ /**
46
+ * Labels one handler the way the dashboard groups jobs.
47
+ *
48
+ * Read off the handler rather than handed in: the explorer already resolved
49
+ * the method, and the instance decorator copies reflect-metadata onto the
50
+ * wrapper it returns, so the decorator's stamps are there either way.
51
+ */
52
+ private describeHandler;
53
+ private instrumentHandler;
54
+ }
@@ -0,0 +1,225 @@
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 ScheduleObserveAgentService_1;
14
+ import { Inject, Injectable, Logger } from "@nestjs/common";
15
+ import { AsyncLocalStorage } from "async_hooks";
16
+ import { randomUUID } from "crypto";
17
+ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
18
+ import { OBSERVE_OPTIONS } from "../observe.constants.js";
19
+ import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
20
+ import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
21
+ /**
22
+ * `@nestjs/schedule`'s metadata keys and scheduler-type enum, inlined so the
23
+ * package stays an optional peer. `@Cron`/`@Interval`/`@Timeout` stamp all
24
+ * three onto the handler: which kind of scheduler it is, the name it was given
25
+ * (if any), and the options the decorator was called with.
26
+ */
27
+ const SCHEDULER_TYPE = "SCHEDULER_TYPE";
28
+ const SCHEDULER_NAME = "SCHEDULER_NAME";
29
+ const SCHEDULE_CRON_OPTIONS = "SCHEDULE_CRON_OPTIONS";
30
+ /** `SchedulerType` from `@nestjs/schedule`, by value. */
31
+ const SCHEDULER_TYPE_LABELS = {
32
+ 1: "cron",
33
+ 2: "timeout",
34
+ 3: "interval",
35
+ };
36
+ /**
37
+ * Scheduled job instrumentation for `@nestjs/schedule`.
38
+ *
39
+ * A `@Cron`, `@Interval` or `@Timeout` handler fires from a timer, so no
40
+ * request ever reaches it and none of the protocol agents see it run. Left
41
+ * alone, a nightly job that takes twenty minutes or fails every other night is
42
+ * invisible: the instance decorator only records spans inside a trace, and
43
+ * nothing opened one.
44
+ *
45
+ * `ScheduleExplorer` routes every handler it discovers through
46
+ * `wrapFunctionInTryCatchBlocks(methodRef, instance)` before registering it
47
+ * with the orchestrator - one seam that covers all three decorators. It is
48
+ * patched on the prototype from this constructor, which Nest runs while it is
49
+ * still instantiating providers and therefore strictly before any
50
+ * `onModuleInit`, including the explorer's own, where discovery happens. The
51
+ * explorer's wrapper is kept and ours goes inside it, so a throwing handler is
52
+ * still logged by the scheduler exactly as before - it is just also reported.
53
+ *
54
+ * Each execution is reported as a job snapshot, the same shape BullMQ jobs
55
+ * use: the scheduler type stands in for the queue name and the handler for the
56
+ * job name, so `cron / ReportsService.nightly` sits alongside
57
+ * `emails / send-welcome` in the same view.
58
+ */
59
+ let ScheduleObserveAgentService = ScheduleObserveAgentService_1 = class ScheduleObserveAgentService {
60
+ observeAgentSharedBuffer;
61
+ options;
62
+ operationTraceRegistry;
63
+ asyncLocalStorage;
64
+ logger = new Logger(ScheduleObserveAgentService_1.name);
65
+ constructor(observeAgentSharedBuffer, options, operationTraceRegistry, asyncLocalStorage) {
66
+ this.observeAgentSharedBuffer = observeAgentSharedBuffer;
67
+ this.options = options;
68
+ this.operationTraceRegistry = operationTraceRegistry;
69
+ this.asyncLocalStorage = asyncLocalStorage;
70
+ this.patchScheduleExplorer();
71
+ }
72
+ /**
73
+ * Loads the explorer without a static import, so a service that schedules
74
+ * nothing need not install the package. Loaded from the constructor because
75
+ * a dynamic `import()` would resolve after provider instantiation, with no
76
+ * guarantee of landing before the explorer's `onModuleInit` has already
77
+ * wrapped every handler.
78
+ */
79
+ loadScheduleExplorer() {
80
+ const result = loadOptionalPeer("@nestjs/schedule", "@nestjs/schedule/dist/schedule.explorer.js");
81
+ if (!result.installed) {
82
+ // Nothing scheduled, nothing to patch, and that is not a
83
+ // misconfiguration.
84
+ return undefined;
85
+ }
86
+ if (result.error) {
87
+ // Installed but the explorer cannot be loaded - a version that moved
88
+ // the file, say. Worth saying out loud, with the actual cause: the
89
+ // symptom otherwise is a service whose jobs silently never appear.
90
+ this.logger.warn(`@nestjs/schedule is installed but its ScheduleExplorer could not be loaded, so scheduled jobs will not be instrumented: ${describePeerLoadError(result.error)}`);
91
+ return undefined;
92
+ }
93
+ return result.module?.ScheduleExplorer;
94
+ }
95
+ patchScheduleExplorer() {
96
+ const ScheduleExplorer = this.loadScheduleExplorer();
97
+ if (!ScheduleExplorer) {
98
+ return;
99
+ }
100
+ const prototype = ScheduleExplorer.prototype;
101
+ const originalWrap = prototype?.wrapFunctionInTryCatchBlocks;
102
+ if (typeof originalWrap !== "function") {
103
+ // Installed, but shaped differently from every version this was written
104
+ // against. Worth saying out loud: the symptom otherwise is a service
105
+ // whose jobs silently never appear.
106
+ this.logger.warn("The installed version of @nestjs/schedule does not expose 'ScheduleExplorer.wrapFunctionInTryCatchBlocks', so scheduled jobs cannot be instrumented. Skipping patching.");
107
+ return;
108
+ }
109
+ // Re-entrant patching (a second `createObserveModule()` in the same
110
+ // process, tests included) must not nest one wrapper inside another.
111
+ const PATCHED = Symbol.for("@nestjs/observe:schedule-patched");
112
+ const marked = originalWrap;
113
+ if (marked[PATCHED]) {
114
+ return;
115
+ }
116
+ const instrument = (methodRef, instance) => this.instrumentHandler(methodRef, instance);
117
+ const patched = function (methodRef, instance) {
118
+ return originalWrap.call(this, instrument(methodRef, instance), instance);
119
+ };
120
+ patched[PATCHED] = true;
121
+ prototype.wrapFunctionInTryCatchBlocks = patched;
122
+ }
123
+ /**
124
+ * Labels one handler the way the dashboard groups jobs.
125
+ *
126
+ * Read off the handler rather than handed in: the explorer already resolved
127
+ * the method, and the instance decorator copies reflect-metadata onto the
128
+ * wrapper it returns, so the decorator's stamps are there either way.
129
+ */
130
+ describeHandler(methodRef, instance) {
131
+ const schedulerType = Reflect.getMetadata(SCHEDULER_TYPE, methodRef);
132
+ const cronOptions = Reflect.getMetadata(SCHEDULE_CRON_OPTIONS, methodRef);
133
+ const explicitName = Reflect.getMetadata(SCHEDULER_NAME, methodRef) ??
134
+ cronOptions?.name;
135
+ const className = instance?.constructor?.name || "Object";
136
+ const methodName = methodRef.name || "anonymous";
137
+ return {
138
+ queueName: (schedulerType !== undefined && SCHEDULER_TYPE_LABELS[schedulerType]) ||
139
+ "schedule",
140
+ name: explicitName || `${className}.${methodName}`,
141
+ };
142
+ }
143
+ instrumentHandler(methodRef, instance) {
144
+ const { queueName, name } = this.describeHandler(methodRef, instance);
145
+ return (...args) => {
146
+ const hasOuterContext = this.asyncLocalStorage
147
+ .getStore()
148
+ ?.has(this.options.traceIdKey);
149
+ const store = new Map();
150
+ return this.asyncLocalStorage.run(store, () => {
151
+ if (hasOuterContext) {
152
+ // Already inside a trace - a handler invoked by hand from a request,
153
+ // say. The outer trace owns the spans; opening a second one would
154
+ // report the same work twice.
155
+ if (this.options.debug) {
156
+ this.logger.debug(`Outer context already has a trace ID. Skipping inner context for scheduled job "${name}"`);
157
+ }
158
+ return methodRef.call(instance, ...args);
159
+ }
160
+ const traceId = randomUUID();
161
+ store.set(this.options.traceIdKey, traceId);
162
+ // Every firing is its own job run, so every firing gets its own id.
163
+ const id = randomUUID();
164
+ if (this.options.jobs?.setAttributes) {
165
+ const attributes = this.options.jobs.setAttributes({
166
+ queueName,
167
+ name,
168
+ id,
169
+ });
170
+ if (attributes) {
171
+ for (const [key, value] of Object.entries(attributes)) {
172
+ store.set(key, value);
173
+ }
174
+ }
175
+ }
176
+ this.operationTraceRegistry.startTrace(traceId, {
177
+ tags: this.options.jobs?.tags,
178
+ queueName,
179
+ name,
180
+ id,
181
+ });
182
+ const endTrace = (status) => {
183
+ setTimeout(async () => {
184
+ this.operationTraceRegistry.endTrace(traceId, { status });
185
+ const snapshot = (await this.operationTraceRegistry.pluckSnapshot(traceId));
186
+ // Absent when the registry discarded the trace - a handler on a
187
+ // provider the instance decorator never wrapped records no spans,
188
+ // and a trace with no spans is dropped rather than shipped empty.
189
+ if (!snapshot) {
190
+ return;
191
+ }
192
+ this.observeAgentSharedBuffer.insertJobSnapshot(snapshot);
193
+ }, 0);
194
+ };
195
+ try {
196
+ const returnValue = methodRef.call(instance, ...args);
197
+ if (returnValue instanceof Promise) {
198
+ return returnValue.then((ret) => {
199
+ endTrace("completed");
200
+ return ret;
201
+ }, (error) => {
202
+ endTrace("failed");
203
+ // The explorer's own wrapper is outside this one and logs the
204
+ // rejection as it always did.
205
+ throw error;
206
+ });
207
+ }
208
+ endTrace("completed");
209
+ return returnValue;
210
+ }
211
+ catch (error) {
212
+ endTrace("failed");
213
+ throw error;
214
+ }
215
+ });
216
+ };
217
+ }
218
+ };
219
+ ScheduleObserveAgentService = ScheduleObserveAgentService_1 = __decorate([
220
+ Injectable(),
221
+ __param(1, Inject(OBSERVE_OPTIONS)),
222
+ __metadata("design:paramtypes", [ObserveAgentSharedBuffer, Object, OperationTraceRegistry,
223
+ AsyncLocalStorage])
224
+ ], ScheduleObserveAgentService);
225
+ export { ScheduleObserveAgentService };
@@ -56,6 +56,21 @@ export declare class OperationTraceRegistry {
56
56
  private toErrorStatusCode;
57
57
  private setStatusCode;
58
58
  internalStartTraceStep(traceId: TraceId, className: string, methodKey: string, callerId: string | undefined): string | undefined;
59
+ /**
60
+ * Nests a freshly opened node under its caller when that caller is still
61
+ * live, and at the trace root otherwise.
62
+ *
63
+ * A caller that has already completed has had its scratch fields stripped
64
+ * (`type`, and `children` when it had none), so there is nothing left to
65
+ * nest under. That happens whenever a callee outlives its caller - most
66
+ * commonly a handler that Nest bound (`AsyncResource.bind` in its
67
+ * interceptors consumer) to the async context of an interceptor whose
68
+ * `intercept()` returned synchronously. Fall back to the root rather than
69
+ * throw into the request: the mirror case, a step ending after its caller
70
+ * did, is already tolerated in `internalEndTraceStep`. Auto and manual spans
71
+ * both attach through here, so they share the tolerance.
72
+ */
73
+ private attachToCaller;
59
74
  internalEndTraceStep(traceId: TraceId,
60
75
  /**
61
76
  * Diagnostic label only - it names the span in the two warnings below and