@nestjs/observe 0.1.2 → 0.1.4

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.
@@ -14,10 +14,10 @@ var ScheduleObserveAgentService_1;
14
14
  import { Inject, Injectable, Logger } from "@nestjs/common";
15
15
  import { AsyncLocalStorage } from "async_hooks";
16
16
  import { randomUUID } from "crypto";
17
- import { createRequire } from "module";
18
17
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
19
18
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
20
19
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
20
+ import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
21
21
  /**
22
22
  * `@nestjs/schedule`'s metadata keys and scheduler-type enum, inlined so the
23
23
  * package stays an optional peer. `@Cron`/`@Interval`/`@Timeout` stamp all
@@ -71,22 +71,26 @@ let ScheduleObserveAgentService = ScheduleObserveAgentService_1 = class Schedule
71
71
  }
72
72
  /**
73
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.
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
78
  */
79
79
  loadScheduleExplorer() {
80
- try {
81
- const require = createRequire(import.meta.url);
82
- const { ScheduleExplorer } = require("@nestjs/schedule/dist/schedule.explorer.js");
83
- return ScheduleExplorer;
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;
84
85
  }
85
- catch {
86
- // The @nestjs/schedule package is an optional peer. Nothing scheduled,
87
- // nothing to patch, and that is not a misconfiguration.
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)}`);
88
91
  return undefined;
89
92
  }
93
+ return result.module?.ScheduleExplorer;
90
94
  }
91
95
  patchScheduleExplorer() {
92
96
  const ScheduleExplorer = this.loadScheduleExplorer();
@@ -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
@@ -227,15 +227,7 @@ export class OperationTraceRegistry {
227
227
  spanId: newNodeId,
228
228
  };
229
229
  let refsByCaller = this.callerIdsByTraceId.get(traceId);
230
- if (callerId) {
231
- const caller = refsByCaller.get(callerId);
232
- caller.children.push(newNode);
233
- newNode.parent = caller;
234
- }
235
- else {
236
- // No caller means insert trace at the root level
237
- snapshot.traces.push(newNode);
238
- }
230
+ this.attachToCaller(snapshot, refsByCaller, callerId, newNode);
239
231
  if (!refsByCaller) {
240
232
  refsByCaller = new Map();
241
233
  this.callerIdsByTraceId.set(traceId, refsByCaller);
@@ -243,6 +235,31 @@ export class OperationTraceRegistry {
243
235
  refsByCaller.set(newNodeId, newNode);
244
236
  return newNodeId;
245
237
  }
238
+ /**
239
+ * Nests a freshly opened node under its caller when that caller is still
240
+ * live, and at the trace root otherwise.
241
+ *
242
+ * A caller that has already completed has had its scratch fields stripped
243
+ * (`type`, and `children` when it had none), so there is nothing left to
244
+ * nest under. That happens whenever a callee outlives its caller - most
245
+ * commonly a handler that Nest bound (`AsyncResource.bind` in its
246
+ * interceptors consumer) to the async context of an interceptor whose
247
+ * `intercept()` returned synchronously. Fall back to the root rather than
248
+ * throw into the request: the mirror case, a step ending after its caller
249
+ * did, is already tolerated in `internalEndTraceStep`. Auto and manual spans
250
+ * both attach through here, so they share the tolerance.
251
+ */
252
+ attachToCaller(snapshot, refsByCaller, callerId, newNode) {
253
+ const caller = callerId ? refsByCaller?.get(callerId) : undefined;
254
+ if (caller?.type === "start") {
255
+ caller.children.push(newNode);
256
+ newNode.parent = caller;
257
+ }
258
+ else {
259
+ // No (live) caller means insert trace at the root level
260
+ snapshot.traces.push(newNode);
261
+ }
262
+ }
246
263
  internalEndTraceStep(traceId,
247
264
  /**
248
265
  * Diagnostic label only - it names the span in the two warnings below and
@@ -429,11 +446,15 @@ export class OperationTraceRegistry {
429
446
  }
430
447
  async createManualSpan(traceId, callerId, name, spanFunction) {
431
448
  // await new Promise((resolve) => setImmediate(resolve));
449
+ // The caller may already have completed (its entry survives completion in
450
+ // `refsByCaller`); it is still the right source for the class and method
451
+ // labels, which outlive completion. Where the new span *attaches* is
452
+ // decided by `attachToCaller`, which nests only under a live caller.
432
453
  const activeSpan = this.getActiveSpan(traceId, callerId);
433
- if (!activeSpan) {
454
+ const snapshot = this.traceSnapshots.get(traceId);
455
+ if (!activeSpan || !snapshot) {
434
456
  return spanFunction(new TraceSpanDelegate("", name, {}));
435
457
  }
436
- const snapshot = this.traceSnapshots.get(traceId);
437
458
  // Book the span in the same ledger auto spans use. Completion goes through
438
459
  // internalEndTraceStep, which increments refsMarkedAsComplete - without
439
460
  // the matching increment here, every completed manual span pushed the
@@ -441,9 +462,7 @@ export class OperationTraceRegistry {
441
462
  // one manual span read as complete: pluckSnapshot then shipped a
442
463
  // half-built tree whose ongoing node still held its circular `parent`
443
464
  // reference, and JSON.stringify threw away the whole flush window.
444
- if (snapshot) {
445
- snapshot.refsCounter += 1;
446
- }
465
+ snapshot.refsCounter += 1;
447
466
  const newNodeId = randomUUID();
448
467
  const startTime = performance.now();
449
468
  // Same as internalStartTraceStep: without an enter, the exit issued on
@@ -463,10 +482,10 @@ export class OperationTraceRegistry {
463
482
  startTime,
464
483
  startOffset: this.toStartOffset(snapshot, startTime),
465
484
  children: [],
466
- parent: activeSpan,
467
485
  };
468
- activeSpan.children.push(manualSpan);
469
- this.callerIdsByTraceId.get(traceId)?.set(newNodeId, manualSpan);
486
+ const refsByCaller = this.callerIdsByTraceId.get(traceId);
487
+ this.attachToCaller(snapshot, refsByCaller, callerId, manualSpan);
488
+ refsByCaller?.set(newNodeId, manualSpan);
470
489
  const onResponse = (res) => {
471
490
  // setImmediate
472
491
  this.internalEndTraceStep(traceId, newNodeId, manualSpan.className, manualSpan.methodKey, newNodeId);
@@ -0,0 +1,36 @@
1
+ /**
2
+ * What loading an optional peer produced.
3
+ *
4
+ * `installed: false` is the normal case for a service that does not use the
5
+ * feature - not a misconfiguration, and callers should stay silent about it.
6
+ * `installed: true` with no `module` means the package is present but the
7
+ * requested entry could not be loaded; `error` carries the cause so the
8
+ * caller can say something truthful instead of guessing.
9
+ */
10
+ export type OptionalPeerResult<T> = {
11
+ installed: false;
12
+ } | {
13
+ installed: true;
14
+ module: T | undefined;
15
+ error?: unknown;
16
+ };
17
+ /**
18
+ * Loads an optional peer dependency without a static import, so a service
19
+ * that does not use the feature need not install the package.
20
+ *
21
+ * Synchronous on purpose: every caller patches or subscribes during provider
22
+ * instantiation or `onModuleInit`, strictly before the peer's own lifecycle
23
+ * runs, and a dynamic `import()` would resolve too late. All current peers
24
+ * ship CommonJS, so `require` can load them.
25
+ *
26
+ * The package's presence is probed with `require.resolve(packageName)` before
27
+ * `specifier` (which may be a deep path into the package) is required, so
28
+ * "not installed" is kept apart from "installed but broken or reshaped".
29
+ * `createRequire` itself failing - a CJS bundle that erased `import.meta.url`,
30
+ * say - is treated as "not installed": with no resolver there is nothing to
31
+ * load, and crashing the constructor would defeat the point of the peer being
32
+ * optional.
33
+ */
34
+ /** Names a load failure for a log line: the message for an `Error`, `String` otherwise. */
35
+ export declare function describePeerLoadError(error: unknown): string;
36
+ export declare function loadOptionalPeer<T>(packageName: string, specifier?: string): OptionalPeerResult<T>;
@@ -0,0 +1,38 @@
1
+ import { createRequire } from "module";
2
+ /**
3
+ * Loads an optional peer dependency without a static import, so a service
4
+ * that does not use the feature need not install the package.
5
+ *
6
+ * Synchronous on purpose: every caller patches or subscribes during provider
7
+ * instantiation or `onModuleInit`, strictly before the peer's own lifecycle
8
+ * runs, and a dynamic `import()` would resolve too late. All current peers
9
+ * ship CommonJS, so `require` can load them.
10
+ *
11
+ * The package's presence is probed with `require.resolve(packageName)` before
12
+ * `specifier` (which may be a deep path into the package) is required, so
13
+ * "not installed" is kept apart from "installed but broken or reshaped".
14
+ * `createRequire` itself failing - a CJS bundle that erased `import.meta.url`,
15
+ * say - is treated as "not installed": with no resolver there is nothing to
16
+ * load, and crashing the constructor would defeat the point of the peer being
17
+ * optional.
18
+ */
19
+ /** Names a load failure for a log line: the message for an `Error`, `String` otherwise. */
20
+ export function describePeerLoadError(error) {
21
+ return error instanceof Error ? error.message : String(error);
22
+ }
23
+ export function loadOptionalPeer(packageName, specifier = packageName) {
24
+ let require;
25
+ try {
26
+ require = createRequire(import.meta.url);
27
+ require.resolve(packageName);
28
+ }
29
+ catch {
30
+ return { installed: false };
31
+ }
32
+ try {
33
+ return { installed: true, module: require(specifier) };
34
+ }
35
+ catch (error) {
36
+ return { installed: true, module: undefined, error };
37
+ }
38
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
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",
@@ -100,7 +100,7 @@
100
100
  "@nestjs/apollo": "13.4.5",
101
101
  "@nestjs/bullmq": "11.0.5",
102
102
  "@nestjs/common": "11.2.1",
103
- "@nestjs/core": "11.2.1",
103
+ "@nestjs/core": "11.2.2",
104
104
  "@nestjs/graphql": "13.4.5",
105
105
  "@nestjs/microservices": "11.2.1",
106
106
  "@nestjs/platform-express": "11.2.1",
@@ -115,6 +115,7 @@
115
115
  "graphql": "16.14.2",
116
116
  "husky": "9.1.7",
117
117
  "lint-staged": "17.3.0",
118
+ "nestjs-cls": "6.2.1",
118
119
  "oxlint": "1.79.0",
119
120
  "oxlint-tsgolint": "7.0.2001",
120
121
  "prettier": "3.2.5",