@nestjs/observe 0.3.1 → 0.3.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.
@@ -547,6 +547,18 @@ export interface ObserveOptions {
547
547
  * gets a fresh `id`.
548
548
  */
549
549
  jobs?: {
550
+ /**
551
+ * A function that determines whether to skip tracing a given job run.
552
+ * Receives the same descriptor as `setAttributes`, so it can match on the
553
+ * queue (or scheduler type) and the job name.
554
+ *
555
+ * An ignored run still executes under a trace id of its own - log lines
556
+ * stay correlated, and jobs it enqueues inherit that id - but no trace is
557
+ * opened for it, so none of its spans are recorded and nothing is shipped.
558
+ * @example (job) => job.queueName === 'interval' && job.name === 'heartbeat'
559
+ * @default () => false
560
+ */
561
+ ignore?: (job: JobContext) => boolean;
550
562
  /**
551
563
  * Tags to be added to all job requests.
552
564
  * These tags can be used to provide additional context for the requests.
@@ -561,16 +573,7 @@ export interface ObserveOptions {
561
573
  * @example (job) => ({ 'queueName': job.queueName, 'jobName': job.name })
562
574
  * @default (job) => ({})
563
575
  */
564
- setAttributes?: (job: {
565
- /** The BullMQ queue, or the scheduler type for a scheduled handler. */
566
- queueName: string;
567
- name: string;
568
- /**
569
- * Absent until the queue driver has assigned one. Always present for a
570
- * scheduled handler, where it identifies this particular firing.
571
- */
572
- id: string | undefined;
573
- }) => {
576
+ setAttributes?: (job: JobContext) => {
574
577
  [key: string]: string | number | boolean;
575
578
  };
576
579
  };
@@ -597,6 +600,17 @@ export interface ObserveModuleAsyncOptions extends Pick<ModuleMetadata, "imports
597
600
  */
598
601
  global?: boolean;
599
602
  }
603
+ /** What a `jobs` option hook is told about the run being started. */
604
+ export interface JobContext {
605
+ /** The BullMQ queue, or the scheduler type for a scheduled handler. */
606
+ queueName: string;
607
+ name: string;
608
+ /**
609
+ * Absent until the queue driver has assigned one. Always present for a
610
+ * scheduled handler, where it identifies this particular firing.
611
+ */
612
+ id: string | undefined;
613
+ }
600
614
  /** What a `ws` option hook is told about the message being handled. */
601
615
  export interface WsMessageContext {
602
616
  /** Class name of the gateway handling the message. */
@@ -64,6 +64,12 @@ export declare class JobTraceRunner<Store extends Record<string, unknown>> {
64
64
  * `x-request-id`.
65
65
  */
66
66
  private readInheritedTraceId;
67
+ /**
68
+ * Whether `jobs.ignore` matches this run. A predicate that throws is
69
+ * reported and read as "trace it": a bug in tracing configuration must not
70
+ * stop the job itself from running.
71
+ */
72
+ private isIgnored;
67
73
  /**
68
74
  * Runs one job under a trace.
69
75
  *
@@ -99,6 +99,20 @@ export class JobTraceRunner {
99
99
  ? inherited
100
100
  : undefined;
101
101
  }
102
+ /**
103
+ * Whether `jobs.ignore` matches this run. A predicate that throws is
104
+ * reported and read as "trace it": a bug in tracing configuration must not
105
+ * stop the job itself from running.
106
+ */
107
+ isIgnored(context) {
108
+ try {
109
+ return Boolean(this.options.jobs?.ignore?.(context));
110
+ }
111
+ catch (error) {
112
+ this.logger.warn(`"jobs.ignore" threw for job "${context.name}" (queue "${context.queueName}"); tracing it anyway: ${error instanceof Error ? error.message : String(error)}`);
113
+ return false;
114
+ }
115
+ }
102
116
  /**
103
117
  * Runs one job under a trace.
104
118
  *
@@ -129,21 +143,26 @@ export class JobTraceRunner {
129
143
  const traceId = this.readInheritedTraceId(job.opts) ?? registryKey;
130
144
  store.set(this.options.traceIdKey, traceId);
131
145
  store.set(TRACE_REGISTRY_KEY, registryKey);
132
- const attributes = this.options.jobs?.setAttributes?.({
146
+ const context = {
133
147
  queueName: job.queueName,
134
148
  name: job.name,
135
- id: job.id,
136
- });
149
+ id: typeof job.id === "number" ? `${job.id}` : job.id,
150
+ };
151
+ const attributes = this.options.jobs?.setAttributes?.(context);
137
152
  if (attributes) {
138
153
  for (const [key, value] of Object.entries(attributes)) {
139
154
  store.set(key, value);
140
155
  }
141
156
  }
157
+ if (this.isIgnored(context)) {
158
+ // The trace id stays in the store so logs and jobs enqueued from here
159
+ // still correlate; nothing is registered under the registry key, so
160
+ // its spans have no trace to join.
161
+ return invoke(() => undefined);
162
+ }
142
163
  this.operationTraceRegistry.startTrace(registryKey, {
143
164
  tags: this.options.jobs?.tags,
144
- queueName: job.queueName,
145
- name: job.name,
146
- id: typeof job.id === "number" ? `${job.id}` : job.id,
165
+ ...context,
147
166
  ...job.metadata,
148
167
  }, traceId);
149
168
  let settled = false;
@@ -27,11 +27,8 @@ import { KeyOf } from "../types/key-of.type.js";
27
27
  * `emails / send-welcome` in the same view.
28
28
  */
29
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
30
  private readonly logger;
31
+ private readonly runner;
35
32
  constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>);
36
33
  /**
37
34
  * Loads the explorer without a static import, so a service that schedules
@@ -18,6 +18,7 @@ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.j
18
18
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
19
19
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
20
20
  import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
21
+ import { JobTraceRunner } from "./job-trace-runner.js";
21
22
  /**
22
23
  * `@nestjs/schedule`'s metadata keys and scheduler-type enum, inlined so the
23
24
  * package stays an optional peer. `@Cron`/`@Interval`/`@Timeout` stamp all
@@ -57,16 +58,10 @@ const SCHEDULER_TYPE_LABELS = {
57
58
  * `emails / send-welcome` in the same view.
58
59
  */
59
60
  let ScheduleObserveAgentService = ScheduleObserveAgentService_1 = class ScheduleObserveAgentService {
60
- observeAgentSharedBuffer;
61
- options;
62
- operationTraceRegistry;
63
- asyncLocalStorage;
64
61
  logger = new Logger(ScheduleObserveAgentService_1.name);
62
+ runner;
65
63
  constructor(observeAgentSharedBuffer, options, operationTraceRegistry, asyncLocalStorage) {
66
- this.observeAgentSharedBuffer = observeAgentSharedBuffer;
67
- this.options = options;
68
- this.operationTraceRegistry = operationTraceRegistry;
69
- this.asyncLocalStorage = asyncLocalStorage;
64
+ this.runner = new JobTraceRunner(observeAgentSharedBuffer, options, operationTraceRegistry, asyncLocalStorage, this.logger);
70
65
  this.patchScheduleExplorer();
71
66
  }
72
67
  /**
@@ -153,78 +148,15 @@ let ScheduleObserveAgentService = ScheduleObserveAgentService_1 = class Schedule
153
148
  }
154
149
  instrumentHandler(methodRef, instance) {
155
150
  const { queueName, name } = this.describeHandler(methodRef, instance);
156
- return (...args) => {
157
- const hasOuterContext = this.asyncLocalStorage
158
- .getStore()
159
- ?.has(this.options.traceIdKey);
160
- const store = new Map();
161
- return this.asyncLocalStorage.run(store, () => {
162
- if (hasOuterContext) {
163
- // Already inside a trace - a handler invoked by hand from a request,
164
- // say. The outer trace owns the spans; opening a second one would
165
- // report the same work twice.
166
- if (this.options.debug) {
167
- this.logger.debug(`Outer context already has a trace ID. Skipping inner context for scheduled job "${name}"`);
168
- }
169
- return methodRef.call(instance, ...args);
170
- }
171
- const traceId = uuidv7();
172
- store.set(this.options.traceIdKey, traceId);
173
- // Every firing is its own job run, so every firing gets its own id.
174
- const id = uuidv7();
175
- if (this.options.jobs?.setAttributes) {
176
- const attributes = this.options.jobs.setAttributes({
177
- queueName,
178
- name,
179
- id,
180
- });
181
- if (attributes) {
182
- for (const [key, value] of Object.entries(attributes)) {
183
- store.set(key, value);
184
- }
185
- }
186
- }
187
- this.operationTraceRegistry.startTrace(traceId, {
188
- tags: this.options.jobs?.tags,
189
- queueName,
190
- name,
191
- id,
192
- });
193
- const endTrace = (status) => {
194
- setTimeout(async () => {
195
- this.operationTraceRegistry.endTrace(traceId, { status });
196
- const snapshot = (await this.operationTraceRegistry.pluckSnapshot(traceId));
197
- // Absent when the registry discarded the trace - a handler on a
198
- // provider the instance decorator never wrapped records no spans,
199
- // and a trace with no spans is dropped rather than shipped empty.
200
- if (!snapshot) {
201
- return;
202
- }
203
- this.observeAgentSharedBuffer.insertJobSnapshot(snapshot);
204
- }, 0);
205
- };
206
- try {
207
- const returnValue = methodRef.call(instance, ...args);
208
- if (returnValue instanceof Promise) {
209
- return returnValue.then((ret) => {
210
- endTrace("completed");
211
- return ret;
212
- }, (error) => {
213
- endTrace("failed");
214
- // The explorer's own wrapper is outside this one and logs the
215
- // rejection as it always did.
216
- throw error;
217
- });
218
- }
219
- endTrace("completed");
220
- return returnValue;
221
- }
222
- catch (error) {
223
- endTrace("failed");
224
- throw error;
225
- }
226
- });
227
- };
151
+ // The explorer's own wrapper is outside this one, so a throwing or
152
+ // rejecting handler is still logged by the scheduler as it always was.
153
+ return (...args) => this.runner.run({
154
+ queueName,
155
+ name,
156
+ // Every firing is its own job run, so every firing gets its own id.
157
+ id: uuidv7(),
158
+ metadata: {},
159
+ }, () => methodRef.call(instance, ...args));
228
160
  }
229
161
  };
230
162
  ScheduleObserveAgentService = ScheduleObserveAgentService_1 = __decorate([
@@ -24,7 +24,9 @@ export declare class TracerService<Store extends Record<string | symbol, unknown
24
24
  /**
25
25
  * Retrieves the active span for the current request.
26
26
  * This method should be called within an async context where the AsyncLocalStorage is active.
27
- * If no active span is found, an error is thrown.
27
+ * If the operation is traced but no span is active, an error is thrown. An
28
+ * operation that is not being recorded (ignored or sampled out) gets a
29
+ * detached delegate whose tags go nowhere, as `createSpan` does.
28
30
  * @returns {Promise<TraceSpanDelegate>} A promise that resolves to the active span delegate.
29
31
  */
30
32
  activeSpan(): Promise<TraceSpanDelegate>;
@@ -52,7 +52,9 @@ let TracerService = class TracerService {
52
52
  /**
53
53
  * Retrieves the active span for the current request.
54
54
  * This method should be called within an async context where the AsyncLocalStorage is active.
55
- * If no active span is found, an error is thrown.
55
+ * If the operation is traced but no span is active, an error is thrown. An
56
+ * operation that is not being recorded (ignored or sampled out) gets a
57
+ * detached delegate whose tags go nowhere, as `createSpan` does.
56
58
  * @returns {Promise<TraceSpanDelegate>} A promise that resolves to the active span delegate.
57
59
  */
58
60
  async activeSpan() {
@@ -64,6 +66,13 @@ let TracerService = class TracerService {
64
66
  const traceId = this.requireTraceId(store, "activeSpan");
65
67
  const callerId = store.get(CALLER_METADATA_KEY);
66
68
  const activeOngoingEvent = this.operationTraceRegistry.getActiveSpan(traceId, callerId);
69
+ if (!activeOngoingEvent && !this.operationTraceRegistry.hasTrace(traceId)) {
70
+ // The store carries the id for log correlation, but no trace was opened
71
+ // under it: `http.ignore`, `jobs.ignore`, or the sampler said no. Which
72
+ // operations get recorded is configuration; a handler tagging its span
73
+ // must not start failing because someone changed it.
74
+ return new TraceSpanDelegate("", undefined, {});
75
+ }
67
76
  if (!activeOngoingEvent) {
68
77
  throw new Error(`No active span found for traceId: ${traceId}. Ensure that a span is created before calling "activeSpan".`);
69
78
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.3.1",
3
+ "version": "0.3.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://observe.nestjs.com",