@nestjs/observe 0.3.0 → 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([
@@ -62,14 +62,27 @@ let LoggerPatcherService = LoggerPatcherService_1 = class LoggerPatcherService {
62
62
  }
63
63
  return jsonLogObject;
64
64
  };
65
- ConsoleLogger.prototype["formatMessage"] = function (logLevel, message, pidMessage, formattedLogLevel, contextMessage, timestampDiff) {
65
+ ConsoleLogger.prototype["formatMessage"] = function (
66
+ // Everything Nest passes is forwarded untouched. Naming the parameters
67
+ // once pinned this wrapper to one release's signature: Nest 12 added a
68
+ // seventh (`params`), and a wrapper that forwarded six silently dropped
69
+ // every structured param from text-mode output.
70
+ ...args) {
71
+ const output = originalFormatMessage.apply(this, args);
66
72
  const store = asyncLocalStorage.getStore();
67
73
  const requestId = store?.get(options.traceIdKey);
68
- const output = originalFormatMessage.call(this, logLevel, message, pidMessage, formattedLogLevel, contextMessage, timestampDiff);
69
- if (requestId) {
70
- return `${output} Trace ID: ${this.colorize(requestId, logLevel)}\n`;
74
+ if (!requestId) {
75
+ return output;
71
76
  }
72
- return output;
77
+ // The suffix has to sit before the line's own newline. Appended after
78
+ // it, the id lands on a line of its own - which the stdout forwarder
79
+ // then ships as a separate, level-less entry, and the parser (which
80
+ // reads the id off the end of the log line) never sees it.
81
+ const [logLevel] = args;
82
+ const suffix = ` Trace ID: ${this.colorize(requestId, logLevel)}`;
83
+ return output.endsWith("\n")
84
+ ? `${output.slice(0, -1)}${suffix}\n`
85
+ : `${output}${suffix}`;
73
86
  };
74
87
  // Add watermark to flag that the logger has been patched
75
88
  Reflect.defineProperty(ConsoleLogger.prototype, this.patchedWatermark, {
@@ -8,13 +8,16 @@ export declare class StdoutForwarderService implements OnModuleInit, OnModuleDes
8
8
  private readonly als;
9
9
  private readonly logger;
10
10
  /**
11
- * stdout arrives in chunks, not lines: a single write can carry half a line,
11
+ * Output arrives in chunks, not lines: a single write can carry half a line,
12
12
  * several lines, or a line split across two calls. Parsing a chunk directly
13
13
  * would mangle every log that straddles a boundary, so the trailing fragment
14
14
  * is held here until its newline shows up.
15
+ *
16
+ * One fragment per stream: stdout and stderr interleave freely, and joining
17
+ * the tail of one onto the head of the other would fuse two unrelated lines.
15
18
  */
16
- private partialLine;
17
- private originalWrite;
19
+ private readonly partialLines;
20
+ private originalWrites;
18
21
  /**
19
22
  * Null only when redaction has been switched off explicitly. Defaulting to on
20
23
  * matters more here than anywhere else in the agent: enabling `forwardLogs`
@@ -25,9 +28,16 @@ export declare class StdoutForwarderService implements OnModuleInit, OnModuleDes
25
28
  constructor(options: ObserveModuleOptionsWithDefaults, observeAgentSharedBuffer: ObserveAgentSharedBuffer, als: AsyncLocalStorage<Map<string, any>>);
26
29
  onModuleInit(): void;
27
30
  onModuleDestroy(): void;
31
+ /**
32
+ * Patches both stdout and stderr. Nest's `ConsoleLogger` writes `error` to
33
+ * stderr and every other level to stdout, so a stdout-only patch forwarded
34
+ * warnings and fatals but never a single error - including the line the
35
+ * exceptions handler writes for every unhandled exception.
36
+ */
28
37
  start(): void;
38
+ private patch;
29
39
  /**
30
- * Restores the original stdout.write.
40
+ * Restores the original stdout and stderr writes.
31
41
  *
32
42
  * Without this the patch outlives the module - which matters in tests, where
33
43
  * a torn-down app would keep pushing into a buffer nobody drains, and in any
@@ -42,19 +42,26 @@ const MAX_PARTIAL_LINE_LENGTH = 8 * 1024;
42
42
  * inside this window, so it is redacted before the cut can split it.
43
43
  */
44
44
  const MAX_PARSED_LINE_LENGTH = 16 * 1024;
45
+ const FORWARDED_STREAMS = ["stdout", "stderr"];
45
46
  let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderService {
46
47
  options;
47
48
  observeAgentSharedBuffer;
48
49
  als;
49
50
  logger = new Logger(StdoutForwarderService_1.name);
50
51
  /**
51
- * stdout arrives in chunks, not lines: a single write can carry half a line,
52
+ * Output arrives in chunks, not lines: a single write can carry half a line,
52
53
  * several lines, or a line split across two calls. Parsing a chunk directly
53
54
  * would mangle every log that straddles a boundary, so the trailing fragment
54
55
  * is held here until its newline shows up.
56
+ *
57
+ * One fragment per stream: stdout and stderr interleave freely, and joining
58
+ * the tail of one onto the head of the other would fuse two unrelated lines.
55
59
  */
56
- partialLine = "";
57
- originalWrite = null;
60
+ partialLines = {
61
+ stdout: "",
62
+ stderr: "",
63
+ };
64
+ originalWrites = null;
58
65
  /**
59
66
  * Null only when redaction has been switched off explicitly. Defaulting to on
60
67
  * matters more here than anywhere else in the agent: enabling `forwardLogs`
@@ -82,22 +89,37 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
82
89
  onModuleDestroy() {
83
90
  this.restore();
84
91
  }
92
+ /**
93
+ * Patches both stdout and stderr. Nest's `ConsoleLogger` writes `error` to
94
+ * stderr and every other level to stdout, so a stdout-only patch forwarded
95
+ * warnings and fatals but never a single error - including the line the
96
+ * exceptions handler writes for every unhandled exception.
97
+ */
85
98
  start() {
86
- if (this.originalWrite) {
99
+ if (this.originalWrites) {
87
100
  return;
88
101
  }
89
- // The unbound original is kept, so `restore` puts back exactly what was
102
+ // The unbound originals are kept, so `restore` puts back exactly what was
90
103
  // there. Storing the bound copy instead meant every start/restore cycle
91
104
  // left one more `bind` wrapper on the stream - and this module is designed
92
105
  // to be torn down and recreated.
93
- this.originalWrite = process.stdout.write;
94
- const originalWrite = process.stdout.write.bind(process.stdout);
95
- process.stdout.write = ((chunk, encoding, callback) => {
106
+ this.originalWrites = {
107
+ stdout: process.stdout.write,
108
+ stderr: process.stderr.write,
109
+ };
110
+ for (const name of FORWARDED_STREAMS) {
111
+ this.patch(name);
112
+ }
113
+ }
114
+ patch(name) {
115
+ const stream = process[name];
116
+ const originalWrite = stream.write.bind(stream);
117
+ stream.write = ((chunk, encoding, callback) => {
96
118
  if (typeof chunk === "string") {
97
119
  // Never let a forwarding failure take down the write it wrapped -
98
- // stdout has to keep working even if telemetry does not.
120
+ // the stream has to keep working even if telemetry does not.
99
121
  try {
100
- this.consume(chunk);
122
+ this.consume(chunk, name);
101
123
  }
102
124
  catch {
103
125
  // Intentionally silent: logging here would re-enter this same patched
@@ -108,43 +130,45 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
108
130
  });
109
131
  }
110
132
  /**
111
- * Restores the original stdout.write.
133
+ * Restores the original stdout and stderr writes.
112
134
  *
113
135
  * Without this the patch outlives the module - which matters in tests, where
114
136
  * a torn-down app would keep pushing into a buffer nobody drains, and in any
115
137
  * process that recreates the Nest application.
116
138
  */
117
139
  restore() {
118
- if (!this.originalWrite) {
140
+ if (!this.originalWrites) {
119
141
  return;
120
142
  }
121
- this.flushPartial();
122
- process.stdout.write = this.originalWrite;
123
- this.originalWrite = null;
143
+ for (const name of FORWARDED_STREAMS) {
144
+ this.flushPartial(name);
145
+ process[name].write = this.originalWrites[name];
146
+ }
147
+ this.originalWrites = null;
124
148
  }
125
- consume(chunk) {
126
- const combined = this.partialLine + chunk;
149
+ consume(chunk, name = "stdout") {
150
+ const combined = this.partialLines[name] + chunk;
127
151
  const segments = combined.split("\n");
128
152
  // The final segment has no newline yet, so it is either an incomplete line
129
153
  // or the empty string left by a chunk that ended cleanly.
130
- this.partialLine = segments.pop() ?? "";
154
+ this.partialLines[name] = segments.pop() ?? "";
131
155
  const entries = segments
132
156
  .filter((line) => line.trim().length > 0)
133
157
  .map((line) => this.toLogEntry(line));
134
158
  if (entries.length > 0) {
135
159
  this.observeAgentSharedBuffer.pushLogs(entries);
136
160
  }
137
- if (this.partialLine.length > MAX_PARTIAL_LINE_LENGTH) {
138
- this.flushPartial();
161
+ if (this.partialLines[name].length > MAX_PARTIAL_LINE_LENGTH) {
162
+ this.flushPartial(name);
139
163
  }
140
164
  }
141
- flushPartial() {
142
- if (this.partialLine.trim().length === 0) {
143
- this.partialLine = "";
165
+ flushPartial(name) {
166
+ const partialLine = this.partialLines[name];
167
+ this.partialLines[name] = "";
168
+ if (partialLine.trim().length === 0) {
144
169
  return;
145
170
  }
146
- this.observeAgentSharedBuffer.pushLogs([this.toLogEntry(this.partialLine)]);
147
- this.partialLine = "";
171
+ this.observeAgentSharedBuffer.pushLogs([this.toLogEntry(partialLine)]);
148
172
  }
149
173
  toLogEntry(rawLine) {
150
174
  const line = rawLine.length > MAX_PARSED_LINE_LENGTH
@@ -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.0",
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",