@nestjs/observe 0.1.0 → 0.1.2

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
@@ -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. Synchronous on purpose: a dynamic
39
+ * `import()` would resolve after provider instantiation, with no guarantee
40
+ * of landing before the explorer's `onModuleInit` has already wrapped every
41
+ * handler. `@nestjs/schedule` ships CommonJS, so `require` can load it.
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,221 @@
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 { createRequire } from "module";
18
+ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
19
+ import { OBSERVE_OPTIONS } from "../observe.constants.js";
20
+ import { OperationTraceRegistry } from "../services/operation-trace.registry.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. Synchronous on purpose: a dynamic
75
+ * `import()` would resolve after provider instantiation, with no guarantee
76
+ * of landing before the explorer's `onModuleInit` has already wrapped every
77
+ * handler. `@nestjs/schedule` ships CommonJS, so `require` can load it.
78
+ */
79
+ loadScheduleExplorer() {
80
+ try {
81
+ const require = createRequire(import.meta.url);
82
+ const { ScheduleExplorer } = require("@nestjs/schedule/dist/schedule.explorer.js");
83
+ return ScheduleExplorer;
84
+ }
85
+ catch {
86
+ // The @nestjs/schedule package is an optional peer. Nothing scheduled,
87
+ // nothing to patch, and that is not a misconfiguration.
88
+ return undefined;
89
+ }
90
+ }
91
+ patchScheduleExplorer() {
92
+ const ScheduleExplorer = this.loadScheduleExplorer();
93
+ if (!ScheduleExplorer) {
94
+ return;
95
+ }
96
+ const prototype = ScheduleExplorer.prototype;
97
+ const originalWrap = prototype?.wrapFunctionInTryCatchBlocks;
98
+ if (typeof originalWrap !== "function") {
99
+ // Installed, but shaped differently from every version this was written
100
+ // against. Worth saying out loud: the symptom otherwise is a service
101
+ // whose jobs silently never appear.
102
+ this.logger.warn("The installed version of @nestjs/schedule does not expose 'ScheduleExplorer.wrapFunctionInTryCatchBlocks', so scheduled jobs cannot be instrumented. Skipping patching.");
103
+ return;
104
+ }
105
+ // Re-entrant patching (a second `createObserveModule()` in the same
106
+ // process, tests included) must not nest one wrapper inside another.
107
+ const PATCHED = Symbol.for("@nestjs/observe:schedule-patched");
108
+ const marked = originalWrap;
109
+ if (marked[PATCHED]) {
110
+ return;
111
+ }
112
+ const instrument = (methodRef, instance) => this.instrumentHandler(methodRef, instance);
113
+ const patched = function (methodRef, instance) {
114
+ return originalWrap.call(this, instrument(methodRef, instance), instance);
115
+ };
116
+ patched[PATCHED] = true;
117
+ prototype.wrapFunctionInTryCatchBlocks = patched;
118
+ }
119
+ /**
120
+ * Labels one handler the way the dashboard groups jobs.
121
+ *
122
+ * Read off the handler rather than handed in: the explorer already resolved
123
+ * the method, and the instance decorator copies reflect-metadata onto the
124
+ * wrapper it returns, so the decorator's stamps are there either way.
125
+ */
126
+ describeHandler(methodRef, instance) {
127
+ const schedulerType = Reflect.getMetadata(SCHEDULER_TYPE, methodRef);
128
+ const cronOptions = Reflect.getMetadata(SCHEDULE_CRON_OPTIONS, methodRef);
129
+ const explicitName = Reflect.getMetadata(SCHEDULER_NAME, methodRef) ??
130
+ cronOptions?.name;
131
+ const className = instance?.constructor?.name || "Object";
132
+ const methodName = methodRef.name || "anonymous";
133
+ return {
134
+ queueName: (schedulerType !== undefined && SCHEDULER_TYPE_LABELS[schedulerType]) ||
135
+ "schedule",
136
+ name: explicitName || `${className}.${methodName}`,
137
+ };
138
+ }
139
+ instrumentHandler(methodRef, instance) {
140
+ const { queueName, name } = this.describeHandler(methodRef, instance);
141
+ return (...args) => {
142
+ const hasOuterContext = this.asyncLocalStorage
143
+ .getStore()
144
+ ?.has(this.options.traceIdKey);
145
+ const store = new Map();
146
+ return this.asyncLocalStorage.run(store, () => {
147
+ if (hasOuterContext) {
148
+ // Already inside a trace - a handler invoked by hand from a request,
149
+ // say. The outer trace owns the spans; opening a second one would
150
+ // report the same work twice.
151
+ if (this.options.debug) {
152
+ this.logger.debug(`Outer context already has a trace ID. Skipping inner context for scheduled job "${name}"`);
153
+ }
154
+ return methodRef.call(instance, ...args);
155
+ }
156
+ const traceId = randomUUID();
157
+ store.set(this.options.traceIdKey, traceId);
158
+ // Every firing is its own job run, so every firing gets its own id.
159
+ const id = randomUUID();
160
+ if (this.options.jobs?.setAttributes) {
161
+ const attributes = this.options.jobs.setAttributes({
162
+ queueName,
163
+ name,
164
+ id,
165
+ });
166
+ if (attributes) {
167
+ for (const [key, value] of Object.entries(attributes)) {
168
+ store.set(key, value);
169
+ }
170
+ }
171
+ }
172
+ this.operationTraceRegistry.startTrace(traceId, {
173
+ tags: this.options.jobs?.tags,
174
+ queueName,
175
+ name,
176
+ id,
177
+ });
178
+ const endTrace = (status) => {
179
+ setTimeout(async () => {
180
+ this.operationTraceRegistry.endTrace(traceId, { status });
181
+ const snapshot = (await this.operationTraceRegistry.pluckSnapshot(traceId));
182
+ // Absent when the registry discarded the trace - a handler on a
183
+ // provider the instance decorator never wrapped records no spans,
184
+ // and a trace with no spans is dropped rather than shipped empty.
185
+ if (!snapshot) {
186
+ return;
187
+ }
188
+ this.observeAgentSharedBuffer.insertJobSnapshot(snapshot);
189
+ }, 0);
190
+ };
191
+ try {
192
+ const returnValue = methodRef.call(instance, ...args);
193
+ if (returnValue instanceof Promise) {
194
+ return returnValue.then((ret) => {
195
+ endTrace("completed");
196
+ return ret;
197
+ }, (error) => {
198
+ endTrace("failed");
199
+ // The explorer's own wrapper is outside this one and logs the
200
+ // rejection as it always did.
201
+ throw error;
202
+ });
203
+ }
204
+ endTrace("completed");
205
+ return returnValue;
206
+ }
207
+ catch (error) {
208
+ endTrace("failed");
209
+ throw error;
210
+ }
211
+ });
212
+ };
213
+ }
214
+ };
215
+ ScheduleObserveAgentService = ScheduleObserveAgentService_1 = __decorate([
216
+ Injectable(),
217
+ __param(1, Inject(OBSERVE_OPTIONS)),
218
+ __metadata("design:paramtypes", [ObserveAgentSharedBuffer, Object, OperationTraceRegistry,
219
+ AsyncLocalStorage])
220
+ ], ScheduleObserveAgentService);
221
+ export { ScheduleObserveAgentService };
@@ -1,41 +1,20 @@
1
- import { createRequire } from "node:module";
2
- import { readFileSync } from "node:fs";
3
- import { dirname, resolve } from "node:path";
4
1
  /**
5
- * The package is loaded synchronously and only on demand, which ESM `import()`
6
- * cannot do. A CommonJS require bound to this module's URL keeps that lazy,
7
- * throw-free behaviour intact.
2
+ * `@jridgewell/trace-mapping` is imported statically rather than pulled in on
3
+ * first use through `createRequire(import.meta.url)`. The shim was valid only
4
+ * under ESM: consumers whose test runner transpiles this package down to
5
+ * CommonJS got `const require = ...` on top of the module-scope `require`,
6
+ * which is a redeclaration - the package failed to load at all under Jest.
7
+ * It is a hard dependency with no import-time side effects, so binding it
8
+ * eagerly costs one module parse and keeps this file loadable either way.
8
9
  */
9
- const require = createRequire(import.meta.url);
10
+ import { originalPositionFor, sourceContentFor, TraceMap, } from "@jridgewell/trace-mapping";
11
+ import { readFileSync } from "node:fs";
12
+ import { dirname, resolve } from "node:path";
10
13
  const SOURCE_MAPPING_URL_PATTERN = /\/\/[#@]\s*sourceMappingURL=(\S+)\s*$/gm;
11
14
  const INLINE_MAP_PREFIX = "data:application/json";
12
15
  /** Parsed maps by compiled-file path; null marks "looked, found none". */
13
16
  const mapCache = new Map();
14
- let traceMappingModule = null;
15
- let traceMappingLoadAttempted = false;
16
- /**
17
- * Loaded on first use rather than at import time, so a process that never enables
18
- * source maps never pays for it - and a missing install degrades to raw frames
19
- * instead of taking the app down.
20
- */
21
- function loadTraceMapping() {
22
- if (traceMappingLoadAttempted) {
23
- return traceMappingModule;
24
- }
25
- traceMappingLoadAttempted = true;
26
- try {
27
- traceMappingModule = require("@jridgewell/trace-mapping");
28
- }
29
- catch {
30
- traceMappingModule = null;
31
- }
32
- return traceMappingModule;
33
- }
34
17
  function readMapFor(file) {
35
- const traceMapping = loadTraceMapping();
36
- if (!traceMapping) {
37
- return null;
38
- }
39
18
  let compiled;
40
19
  try {
41
20
  compiled = readFileSync(file, "utf8");
@@ -73,7 +52,7 @@ function readMapFor(file) {
73
52
  }
74
53
  try {
75
54
  return {
76
- tracer: new traceMapping.TraceMap(JSON.parse(rawMap)),
55
+ tracer: new TraceMap(JSON.parse(rawMap)),
77
56
  mapDir,
78
57
  };
79
58
  }
@@ -96,15 +75,11 @@ function getMap(file) {
96
75
  * to the compiled file - a degraded but still truthful result.
97
76
  */
98
77
  export function resolveOriginalPosition(file, line, column) {
99
- const traceMapping = loadTraceMapping();
100
- if (!traceMapping) {
101
- return undefined;
102
- }
103
78
  const map = getMap(file);
104
79
  if (!map) {
105
80
  return undefined;
106
81
  }
107
- const position = traceMapping.originalPositionFor(map.tracer, {
82
+ const position = originalPositionFor(map.tracer, {
108
83
  line,
109
84
  // Stack columns are 1-based, source map columns are 0-based.
110
85
  column: Math.max(0, column - 1),
@@ -115,7 +90,7 @@ export function resolveOriginalPosition(file, line, column) {
115
90
  // `sourcesContent` is the reliable path: the original text is embedded in the
116
91
  // map, so it works even when the source tree is absent at runtime (a container
117
92
  // shipping only dist, for instance).
118
- const embedded = traceMapping.sourceContentFor(map.tracer, position.source);
93
+ const embedded = sourceContentFor(map.tracer, position.source);
119
94
  return {
120
95
  file: position.source.startsWith("/")
121
96
  ? position.source
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Observability and APM agent for NestJS - traces, runtime metrics, custom metrics and CPU profiles",
5
5
  "author": "Kamil Mysliwiec",
6
6
  "homepage": "https://nestjs.com",
@@ -68,6 +68,7 @@
68
68
  "@nestjs/core": "^11.0.0",
69
69
  "@nestjs/graphql": "^13.0.0",
70
70
  "@nestjs/microservices": "^11.0.0",
71
+ "@nestjs/schedule": "^4.0.0 || ^5.0.0 || ^6.0.0",
71
72
  "bullmq": "^5.0.0 || ^6.0.0",
72
73
  "reflect-metadata": "^0.1.12 || ^0.2.0",
73
74
  "rxjs": "^7.0.0"
@@ -82,6 +83,9 @@
82
83
  "@nestjs/microservices": {
83
84
  "optional": true
84
85
  },
86
+ "@nestjs/schedule": {
87
+ "optional": true
88
+ },
85
89
  "bullmq": {
86
90
  "optional": true
87
91
  }
@@ -100,6 +104,7 @@
100
104
  "@nestjs/graphql": "13.4.5",
101
105
  "@nestjs/microservices": "11.2.1",
102
106
  "@nestjs/platform-express": "11.2.1",
107
+ "@nestjs/schedule": "^6.1.3",
103
108
  "@nestjs/testing": "11.2.1",
104
109
  "@swc/core": "1.16.1",
105
110
  "@types/node": "22.20.1",