@nestjs/observe 0.1.7 → 0.1.9

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.
@@ -224,6 +224,10 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
224
224
  value: originalMethod.name,
225
225
  configurable: true,
226
226
  });
227
+ Object.defineProperty(boundFn, "length", {
228
+ value: originalMethod.length,
229
+ configurable: true,
230
+ });
227
231
  const metadataKeys = Reflect.getMetadataKeys(originalMethod);
228
232
  for (const key of metadataKeys) {
229
233
  const metadata = Reflect.getMetadata(key, originalMethod);
@@ -52,8 +52,9 @@ export interface CreateObserveModuleOptions {
52
52
  * For HTTP protocols, the request object is passed to the function.
53
53
  * For non-HTTP protocols, the request object will be contextual and may not be available.
54
54
  * The default implementation uses the 'x-request-id' header if available,
55
- * or generates a random UUID if the header is not present.
56
- * @default (req) => req.headers['x-request-id'] || randomUUID()
55
+ * or mints a time-ordered UUID (version 7) if the header is not present -
56
+ * an id the collector can locate in time without a scan.
57
+ * @default (req) => req.headers['x-request-id'] || uuidv7()
57
58
  */
58
59
  traceIdGenerator?: (req: unknown) => string;
59
60
  /**
@@ -13,7 +13,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
13
13
  var QueueObserveAgentService_1;
14
14
  import { Inject, Injectable, Logger } from "@nestjs/common";
15
15
  import { AsyncLocalStorage } from "async_hooks";
16
- import { randomUUID } from "crypto";
16
+ import { uuidv7 } from "../utils/uuid-v7.util.js";
17
17
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
18
18
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
19
19
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
@@ -71,13 +71,13 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
71
71
  * is, but does not expose the decorator service where expected.
72
72
  */
73
73
  loadProcessorDecoratorService() {
74
- const result = loadOptionalPeer("@nestjs/bullmq", "@nestjs/bullmq/dist/instrument/processor-decorator.service.js");
74
+ const result = loadOptionalPeer("@nestjs/bullmq");
75
75
  if (!result.installed) {
76
76
  return undefined;
77
77
  }
78
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
79
+ // The real cause - a version that no longer re-exports it, a broken
80
+ // install - so the "update to the latest version" advice below is
81
81
  // never the only diagnostic.
82
82
  this.logger.warn(`@nestjs/bullmq is installed but its processor decorator could not be loaded: ${describePeerLoadError(result.error)}`);
83
83
  return null;
@@ -112,7 +112,7 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
112
112
  }
113
113
  return processor(job);
114
114
  }
115
- const traceId = randomUUID();
115
+ const traceId = uuidv7();
116
116
  store.set(this.options.traceIdKey, traceId);
117
117
  if (this.options.jobs?.setAttributes) {
118
118
  const attributes = this.options.jobs?.setAttributes?.({
@@ -13,7 +13,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
13
13
  var ScheduleObserveAgentService_1;
14
14
  import { Inject, Injectable, Logger } from "@nestjs/common";
15
15
  import { AsyncLocalStorage } from "async_hooks";
16
- import { randomUUID } from "crypto";
16
+ import { uuidv7 } from "../utils/uuid-v7.util.js";
17
17
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
18
18
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
19
19
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
@@ -77,20 +77,31 @@ let ScheduleObserveAgentService = ScheduleObserveAgentService_1 = class Schedule
77
77
  * wrapped every handler.
78
78
  */
79
79
  loadScheduleExplorer() {
80
- const result = loadOptionalPeer("@nestjs/schedule", "@nestjs/schedule/dist/schedule.explorer.js");
81
- if (!result.installed) {
80
+ // The entry point is the supported source, but it only re-exports the
81
+ // explorer from 12.0.1 onwards; every earlier version keeps it behind a
82
+ // deep path. Try the public export first, then the file, so a supported
83
+ // import is preferred wherever one exists.
84
+ const entryPoint = loadOptionalPeer("@nestjs/schedule");
85
+ if (!entryPoint.installed) {
82
86
  // Nothing scheduled, nothing to patch, and that is not a
83
87
  // misconfiguration.
84
88
  return undefined;
85
89
  }
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;
90
+ if (entryPoint.module?.ScheduleExplorer) {
91
+ return entryPoint.module.ScheduleExplorer;
92
+ }
93
+ const deepPath = loadOptionalPeer("@nestjs/schedule", "@nestjs/schedule/dist/schedule.explorer.js");
94
+ if (deepPath.installed && deepPath.module?.ScheduleExplorer) {
95
+ return deepPath.module.ScheduleExplorer;
92
96
  }
93
- return result.module?.ScheduleExplorer;
97
+ // Installed, but the explorer is in neither place - a version that moved
98
+ // it, say. Worth saying out loud, with whichever cause was recorded: the
99
+ // symptom otherwise is a service whose jobs silently never appear.
100
+ const cause = (deepPath.installed && deepPath.error) ||
101
+ entryPoint.error ||
102
+ new Error("ScheduleExplorer is not exported by @nestjs/schedule");
103
+ this.logger.warn(`@nestjs/schedule is installed but its ScheduleExplorer could not be loaded, so scheduled jobs will not be instrumented: ${describePeerLoadError(cause)}`);
104
+ return undefined;
94
105
  }
95
106
  patchScheduleExplorer() {
96
107
  const ScheduleExplorer = this.loadScheduleExplorer();
@@ -157,10 +168,10 @@ let ScheduleObserveAgentService = ScheduleObserveAgentService_1 = class Schedule
157
168
  }
158
169
  return methodRef.call(instance, ...args);
159
170
  }
160
- const traceId = randomUUID();
171
+ const traceId = uuidv7();
161
172
  store.set(this.options.traceIdKey, traceId);
162
173
  // Every firing is its own job run, so every firing gets its own id.
163
- const id = randomUUID();
174
+ const id = uuidv7();
164
175
  if (this.options.jobs?.setAttributes) {
165
176
  const attributes = this.options.jobs.setAttributes({
166
177
  queueName,
@@ -1,6 +1,6 @@
1
1
  import { IntrinsicException, Logger } from "@nestjs/common";
2
2
  import { activeSliceRecorder } from "../profiling/span-slice-recorder.js";
3
- import { randomUUID } from "crypto";
3
+ import { uuidv7 } from "../utils/uuid-v7.util.js";
4
4
  import { TraceSpanDelegate } from "../trace-span.delegate.js";
5
5
  import { collectCodeFrames } from "../utils/source-context.util.js";
6
6
  import { CALLER_METADATA_KEY } from "../observe.constants.js";
@@ -204,7 +204,7 @@ export class OperationTraceRegistry {
204
204
  return undefined;
205
205
  }
206
206
  snapshot.refsCounter += 1;
207
- const newNodeId = randomUUID();
207
+ const newNodeId = uuidv7();
208
208
  const startTime = performance.now();
209
209
  // Records which span owns the thread from here. A no-op unless continuous
210
210
  // profiling is on, and the only way profile samples can be attributed to a
@@ -463,7 +463,7 @@ export class OperationTraceRegistry {
463
463
  // half-built tree whose ongoing node still held its circular `parent`
464
464
  // reference, and JSON.stringify threw away the whole flush window.
465
465
  snapshot.refsCounter += 1;
466
- const newNodeId = randomUUID();
466
+ const newNodeId = uuidv7();
467
467
  const startTime = performance.now();
468
468
  // Same as internalStartTraceStep: without an enter, the exit issued on
469
469
  // completion no-ops and the span's execution time is silently attributed
@@ -1,4 +1,4 @@
1
- import { randomUUID } from "crypto";
1
+ import { uuidv7 } from "./uuid-v7.util.js";
2
2
  /**
3
3
  * What an inbound `x-request-id` must look like to be adopted as the trace id.
4
4
  *
@@ -18,5 +18,6 @@ export function defaultTraceIdGenerator(req) {
18
18
  return requestId;
19
19
  }
20
20
  }
21
- return randomUUID();
21
+ // Minted here, so it can carry its time - see uuidv7.
22
+ return uuidv7();
22
23
  }
@@ -30,6 +30,12 @@ export type OptionalPeerResult<T> = {
30
30
  * say - is treated as "not installed": with no resolver there is nothing to
31
31
  * load, and crashing the constructor would defeat the point of the peer being
32
32
  * optional.
33
+ *
34
+ * A deep specifier that an `exports` map refuses (Nest v12 added one to
35
+ * several packages) is retried as an absolute path built from the package's
36
+ * own `package.json` - always exported, and an absolute path is not subject
37
+ * to the map. The file still has to be there, so a genuinely moved or removed
38
+ * entry keeps reporting its own failure.
33
39
  */
34
40
  /** Names a load failure for a log line: the message for an `Error`, `String` otherwise. */
35
41
  export declare function describePeerLoadError(error: unknown): string;
@@ -1,4 +1,5 @@
1
1
  import { createRequire } from "module";
2
+ import { dirname, join } from "path";
2
3
  /**
3
4
  * Loads an optional peer dependency without a static import, so a service
4
5
  * that does not use the feature need not install the package.
@@ -15,6 +16,12 @@ import { createRequire } from "module";
15
16
  * say - is treated as "not installed": with no resolver there is nothing to
16
17
  * load, and crashing the constructor would defeat the point of the peer being
17
18
  * optional.
19
+ *
20
+ * A deep specifier that an `exports` map refuses (Nest v12 added one to
21
+ * several packages) is retried as an absolute path built from the package's
22
+ * own `package.json` - always exported, and an absolute path is not subject
23
+ * to the map. The file still has to be there, so a genuinely moved or removed
24
+ * entry keeps reporting its own failure.
18
25
  */
19
26
  /** Names a load failure for a log line: the message for an `Error`, `String` otherwise. */
20
27
  export function describePeerLoadError(error) {
@@ -33,6 +40,35 @@ export function loadOptionalPeer(packageName, specifier = packageName) {
33
40
  return { installed: true, module: require(specifier) };
34
41
  }
35
42
  catch (error) {
43
+ const withinPackage = resolveWithinPackage(require, packageName, specifier);
44
+ if (withinPackage) {
45
+ try {
46
+ return { installed: true, module: require(withinPackage) };
47
+ }
48
+ catch {
49
+ // Fall through and report the original failure: it names the
50
+ // specifier the caller actually asked for.
51
+ }
52
+ }
36
53
  return { installed: true, module: undefined, error };
37
54
  }
38
55
  }
56
+ /**
57
+ * Turns a deep specifier such as `@nestjs/schedule/dist/schedule.explorer.js`
58
+ * into an absolute path inside the installed package, so an `exports` map
59
+ * that hides the subpath is bypassed. Returns `undefined` when the specifier
60
+ * is not a subpath of `packageName` or the package cannot be located.
61
+ */
62
+ function resolveWithinPackage(require, packageName, specifier) {
63
+ const prefix = `${packageName}/`;
64
+ if (!specifier.startsWith(prefix)) {
65
+ return undefined;
66
+ }
67
+ try {
68
+ const manifest = require.resolve(`${packageName}/package.json`);
69
+ return join(dirname(manifest), specifier.slice(prefix.length));
70
+ }
71
+ catch {
72
+ return undefined;
73
+ }
74
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * A UUID whose first 48 bits are the minting time, milliseconds since the
3
+ * epoch (RFC 9562 version 7).
4
+ *
5
+ * Every id the agent mints itself - a trace id when no request id arrived, a
6
+ * span id, a scheduled run's id - is stored by the collector in time-ordered
7
+ * hypertables and later looked up by that id alone. A random id says nothing
8
+ * about when, so a lookup by it has to consider every chunk the project
9
+ * keeps; a v7 id tells the collector which chunk to open. Ids the agent did
10
+ * not mint - a propagated `x-request-id`, a customer's own trace key - are
11
+ * passed through untouched, and the collector treats those as before.
12
+ *
13
+ * Same layout as the collector's own generator, so ids from either side
14
+ * decode the same way.
15
+ */
16
+ export declare function uuidv7(now?: number): string;
@@ -0,0 +1,34 @@
1
+ import { randomBytes } from "crypto";
2
+ /**
3
+ * A UUID whose first 48 bits are the minting time, milliseconds since the
4
+ * epoch (RFC 9562 version 7).
5
+ *
6
+ * Every id the agent mints itself - a trace id when no request id arrived, a
7
+ * span id, a scheduled run's id - is stored by the collector in time-ordered
8
+ * hypertables and later looked up by that id alone. A random id says nothing
9
+ * about when, so a lookup by it has to consider every chunk the project
10
+ * keeps; a v7 id tells the collector which chunk to open. Ids the agent did
11
+ * not mint - a propagated `x-request-id`, a customer's own trace key - are
12
+ * passed through untouched, and the collector treats those as before.
13
+ *
14
+ * Same layout as the collector's own generator, so ids from either side
15
+ * decode the same way.
16
+ */
17
+ export function uuidv7(now = Date.now()) {
18
+ // Ten random bytes: 12 bits go into `rand_a`, 62 into `rand_b`. The two
19
+ // version and two variant bits overwrite what they need.
20
+ const rand = randomBytes(10);
21
+ const bytes = Buffer.allocUnsafe(16);
22
+ // 48-bit big-endian timestamp, placed as a 32/16 split so no shift runs
23
+ // past 2^32.
24
+ bytes.writeUInt32BE(Math.floor(now / 0x10000), 0);
25
+ bytes.writeUInt16BE(now % 0x10000, 4);
26
+ // Version 7 in the top nibble, 12 random bits below it.
27
+ bytes[6] = 0x70 | (rand[0] & 0x0f);
28
+ bytes[7] = rand[1];
29
+ // Variant `10` in the top two bits, 62 random bits below.
30
+ bytes[8] = 0x80 | (rand[2] & 0x3f);
31
+ rand.copy(bytes, 9, 3, 10);
32
+ const hex = bytes.toString("hex");
33
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
34
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
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",
@@ -63,12 +63,12 @@
63
63
  "@jridgewell/trace-mapping": "0.3.31"
64
64
  },
65
65
  "peerDependencies": {
66
- "@nestjs/bullmq": "^11.0.0",
67
- "@nestjs/common": "^11.0.0",
68
- "@nestjs/core": "^11.0.0",
69
- "@nestjs/graphql": "^13.0.0",
70
- "@nestjs/microservices": "^11.0.0",
71
- "@nestjs/schedule": "^4.0.0 || ^5.0.0 || ^6.0.0",
66
+ "@nestjs/bullmq": "^11.0.0 || ^12.0.0",
67
+ "@nestjs/common": "^11.0.0 || ^12.0.0",
68
+ "@nestjs/core": "^11.0.0 || ^12.0.0",
69
+ "@nestjs/graphql": "^13.0.0 || ^14.0.0",
70
+ "@nestjs/microservices": "^11.0.0 || ^12.0.0",
71
+ "@nestjs/schedule": "^4.0.0 || ^5.0.0 || ^6.0.0 || ^12.0.0",
72
72
  "bullmq": "^5.0.0 || ^6.0.0",
73
73
  "reflect-metadata": "^0.1.12 || ^0.2.0",
74
74
  "rxjs": "^7.0.0"
@@ -97,15 +97,15 @@
97
97
  "@commitlint/config-angular": "21.2.2",
98
98
  "@grpc/grpc-js": "1.14.4",
99
99
  "@grpc/proto-loader": "0.8.1",
100
- "@nestjs/apollo": "13.4.5",
101
- "@nestjs/bullmq": "11.0.5",
102
- "@nestjs/common": "11.2.1",
103
- "@nestjs/core": "11.2.2",
104
- "@nestjs/graphql": "13.4.5",
105
- "@nestjs/microservices": "11.2.1",
106
- "@nestjs/platform-express": "11.2.1",
107
- "@nestjs/schedule": "^6.1.3",
108
- "@nestjs/testing": "11.2.1",
100
+ "@nestjs/apollo": "14.0.0",
101
+ "@nestjs/bullmq": "12.0.0",
102
+ "@nestjs/common": "12.0.1",
103
+ "@nestjs/core": "12.0.1",
104
+ "@nestjs/graphql": "14.0.0",
105
+ "@nestjs/microservices": "12.0.1",
106
+ "@nestjs/platform-express": "12.0.1",
107
+ "@nestjs/schedule": "12.0.1",
108
+ "@nestjs/testing": "12.0.1",
109
109
  "@swc/core": "1.16.1",
110
110
  "@types/node": "22.20.1",
111
111
  "@types/supertest": "7.2.1",
@@ -128,6 +128,12 @@
128
128
  "unplugin-swc": "1.5.11",
129
129
  "vitest": "4.1.11"
130
130
  },
131
+ "overrides": {
132
+ "nestjs-cls": {
133
+ "@nestjs/common": "$@nestjs/common",
134
+ "@nestjs/core": "$@nestjs/core"
135
+ }
136
+ },
131
137
  "lint-staged": {
132
138
  "**/*.{ts,json}": []
133
139
  },