@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.
@@ -77,6 +77,19 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
77
77
  this.options = options;
78
78
  }
79
79
  insertRequestSnapshot(snapshot) {
80
+ // A request can end before its route metadata is ever captured - an auth
81
+ // guard rejecting it, or a GraphQL document that never reaches a resolver
82
+ // (`{ __typename }`) - leaving no operation id. The collector requires one
83
+ // on every snapshot and rejects the *entire batch* over a single miss, so
84
+ // fall back to the transport's URL, and drop the snapshot when even that
85
+ // is absent rather than poison the batch it would ride in.
86
+ snapshot.operationId ??= snapshot.attributes?.originalUrl;
87
+ if (!snapshot.operationId) {
88
+ if (this.options.debug) {
89
+ this.logger.debug(`Snapshot for traceId "${snapshot.traceId}" has no operation id nor URL to fall back on. Ignoring snapshot.`);
90
+ }
91
+ return;
92
+ }
80
93
  if (!this._mainThreadBuffer) {
81
94
  this._mainThreadBuffer = this.createEmptyPayload();
82
95
  }
@@ -36,6 +36,19 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
36
36
  spec.setActive(true);
37
37
  const callerId = store?.get(CALLER_METADATA_KEY);
38
38
  const newStepId = operationTraceRegistry.internalStartTraceStep(requestId, className, methodName, callerId);
39
+ // No step means the registry holds no snapshot for this trace id: the
40
+ // request was dropped by `http.ignore` or sampled out, but its store
41
+ // still carries the id - log correlation needs it there. Nothing was
42
+ // opened, so nothing must be closed; without this bail-out every
43
+ // provider call on an ignored route logged a registry error.
44
+ if (newStepId === undefined) {
45
+ try {
46
+ return callUntraced(this, args);
47
+ }
48
+ finally {
49
+ spec.setActive(false);
50
+ }
51
+ }
39
52
  const onReturnValue = (res) => {
40
53
  operationTraceRegistry.internalEndTraceStep(requestId, spanId, className, methodName, newStepId);
41
54
  return res;
@@ -104,6 +117,22 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
104
117
  if (options.skipInstrumentation(instance)) {
105
118
  return instance;
106
119
  }
120
+ // Native private members (`this.#x`) are branded to the instance itself,
121
+ // and no proxy trap can satisfy that check: a method invoked with the
122
+ // proxy as its receiver throws "Receiver must be an instance of class".
123
+ // Such classes get the raw instance as receiver instead - trading away
124
+ // nested `this.other()` spans (those calls no longer pass through the
125
+ // proxy) for methods that run at all.
126
+ let hasPrivateMembers;
127
+ try {
128
+ hasPrivateMembers = usesNativePrivateMembers(instance);
129
+ }
130
+ catch {
131
+ // Reading the prototype ran a trap that threw (nestjs-cls proxy
132
+ // providers do this outside a CLS context). An instance that cannot be
133
+ // inspected cannot be instrumented; hand it back untouched.
134
+ return instance;
135
+ }
107
136
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
108
137
  const methodRefsCache = new WeakMap();
109
138
  const currentlyTracing = new WeakMap();
@@ -111,11 +140,17 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
111
140
  get: (target, prop, receiver) => {
112
141
  const attributeValue = Reflect.get(target, prop);
113
142
  const isFunction = typeof attributeValue === "function" && prop !== "constructor";
114
- const shouldProxy = isFunction && !isClass(attributeValue);
115
- // For Axios instance, do not proxy its methods
116
- // its an exception case
117
- const isAxios = attributeValue?.Axios;
118
- if (!shouldProxy || isAxios) {
143
+ const shouldProxy = isFunction &&
144
+ !isClass(attributeValue) &&
145
+ // A callable *object* - a Mongoose model, an Axios instance, an
146
+ // EventEmitter-backed client - is a field, not a method. The traced
147
+ // wrapper is a fresh bound function, so wrapping one silently drops
148
+ // everything hanging off it (`svc.model.find` became undefined
149
+ // mid-trace). This subsumes the Axios special case that used to sit
150
+ // here: an Axios instance is a bound `request` carrying its API as
151
+ // own properties.
152
+ !isCallableObject(attributeValue);
153
+ if (!shouldProxy) {
119
154
  return Reflect.get(target, prop);
120
155
  }
121
156
  const className = target.constructor.name;
@@ -125,7 +160,13 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
125
160
  if (methodRefsCache.has(attributeValue)) {
126
161
  return methodRefsCache.get(attributeValue);
127
162
  }
128
- const originalMethod = Reflect.get(target, prop, receiver);
163
+ // For a private-member class, `Reflect.get` with the proxy as receiver
164
+ // would already throw on an accessor that touches `this.#x`, so the
165
+ // value fetched against the target above is reused instead.
166
+ const originalMethod = hasPrivateMembers
167
+ ? attributeValue
168
+ : Reflect.get(target, prop, receiver);
169
+ const tracedReceiver = hasPrivateMembers ? target : receiver;
129
170
  const proxyFn = createTracedWrapper({
130
171
  className,
131
172
  methodName,
@@ -144,8 +185,10 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
144
185
  }
145
186
  },
146
187
  // Traced calls run against the proxy so that a method calling into
147
- // itself (`this.other()`) is instrumented as a nested step.
148
- call: named(frameName, (_thisArg, args) => originalMethod.apply(receiver, args)),
188
+ // itself (`this.other()`) is instrumented as a nested step - except
189
+ // for private-member classes, whose brand checks only the raw
190
+ // instance satisfies.
191
+ call: named(frameName, (_thisArg, args) => originalMethod.apply(tracedReceiver, args)),
149
192
  callUntraced: named(frameName, (_thisArg, args) => originalMethod.apply(target, args)),
150
193
  });
151
194
  // V8 hard-codes the type name of a stack frame to "Proxy" whenever the
@@ -227,6 +270,76 @@ function escapeRegExp(value) {
227
270
  function isClass(value) {
228
271
  return /^\s*class\s+/.test(value.toString());
229
272
  }
273
+ /**
274
+ * The prototypes every ordinary function - plain, async, generator, async
275
+ * generator, arrow, bound - hangs off. Anything else above a callable means it
276
+ * was built by a library as an object that happens to be invocable.
277
+ */
278
+ const INTRINSIC_FUNCTION_PROTOTYPES = new Set([
279
+ Function.prototype,
280
+ Object.getPrototypeOf(async function () { }),
281
+ Object.getPrototypeOf(function* () { }),
282
+ Object.getPrototypeOf(async function* () { }),
283
+ ]);
284
+ /**
285
+ * Whether a function is really an object with a call signature - a Mongoose
286
+ * model with its statics, a client with methods hung directly on it - rather
287
+ * than a method to be traced.
288
+ *
289
+ * Two tells, either sufficient: a prototype that is not one of the intrinsic
290
+ * function prototypes (Mongoose sets `M.__proto__ = Model`), or own enumerable
291
+ * properties, which a plain method never carries but statics are. The traced
292
+ * wrapper is a fresh function that preserves only `name` and reflect-metadata,
293
+ * so anything matching here must be handed out untouched.
294
+ */
295
+ function isCallableObject(fn) {
296
+ return (!INTRINSIC_FUNCTION_PROTOTYPES.has(Object.getPrototypeOf(fn)) ||
297
+ Object.keys(fn).length > 0);
298
+ }
299
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
300
+ const privateMemberCache = new WeakMap();
301
+ /**
302
+ * Whether any class in the instance's prototype chain declares native private
303
+ * members (`#field`, `#method()`).
304
+ *
305
+ * Detection reads the class source: private members can only be touched from
306
+ * inside the lexical class body, so a class whose text contains no `#name`
307
+ * token cannot perform a brand check. A `#` inside a string or comment can
308
+ * false-positive, which merely selects the raw-instance receiver - every call
309
+ * still works, only nested self-call spans are lost - so the cheap test is
310
+ * safe to lean on.
311
+ */
312
+ function usesNativePrivateMembers(instance) {
313
+ let proto = Object.getPrototypeOf(instance);
314
+ while (proto && proto !== Object.prototype) {
315
+ const ctor = proto.constructor;
316
+ if (typeof ctor === "function" && ctor !== Object) {
317
+ let hasPrivate = privateMemberCache.get(ctor);
318
+ if (hasPrivate === undefined) {
319
+ hasPrivate = declaresPrivateMembers(ctor);
320
+ privateMemberCache.set(ctor, hasPrivate);
321
+ }
322
+ if (hasPrivate) {
323
+ return true;
324
+ }
325
+ }
326
+ proto = Object.getPrototypeOf(proto);
327
+ }
328
+ return false;
329
+ }
330
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
331
+ function declaresPrivateMembers(ctor) {
332
+ try {
333
+ // `#` starting a private name is never preceded by an identifier
334
+ // character; `obj.#x` and `#x in obj` and declarations all match.
335
+ return /(^|[^\w$])#[\w$]/.test(Function.prototype.toString.call(ctor));
336
+ }
337
+ catch {
338
+ // A constructor whose source is unavailable (bound functions, some
339
+ // natives) cannot be a class body with private members.
340
+ return false;
341
+ }
342
+ }
230
343
  function generateSpanId(instance, methodKey) {
231
344
  return `${instance.constructor.name}#${methodKey}`;
232
345
  }
@@ -63,6 +63,21 @@ export interface CreateObserveModuleOptions {
63
63
  * @default true
64
64
  */
65
65
  attachTraceIdToLogs?: boolean;
66
+ /**
67
+ * Excludes providers from instrumentation. Return true for an instance that
68
+ * should stay untouched - no proxy is placed around it and none of its
69
+ * methods produce spans.
70
+ *
71
+ * Runs before the built-in checks, so it also shields providers that
72
+ * cannot even be inspected safely: some libraries (nestjs-cls proxy
73
+ * providers, for instance) register proxies that throw on any property
74
+ * access outside their own context. Those are skipped automatically when
75
+ * inspection throws, but this hook lets you exclude them - or anything
76
+ * else - explicitly.
77
+ * @example (instance) => instance instanceof MyUninstrumentableService
78
+ * @default () => false
79
+ */
80
+ skipInstrumentation?: (instance: unknown) => boolean;
66
81
  /**
67
82
  * Attaches the source around each in-app stack frame to captured errors, so the
68
83
  * throw site can be shown with its code rather than just a file and line.
@@ -41,6 +41,7 @@ export function createObserveModule(options = {}) {
41
41
  options.traceIdKey ??= "traceId";
42
42
  options.attachTraceIdToLogs ??= true;
43
43
  options.traceIdGenerator ??= defaultTraceIdGenerator;
44
+ options.skipInstrumentation ??= () => false;
44
45
  const asyncLocalStorage = new AsyncLocalStorage();
45
46
  const operationTraceRegistry = new OperationTraceRegistry(asyncLocalStorage, options.sourceContext);
46
47
  let ObserveModule = ObserveModule_1 = class ObserveModule {
@@ -166,37 +167,60 @@ export function createObserveModule(options = {}) {
166
167
  __metadata("design:paramtypes", [HttpAdapterHost,
167
168
  AsyncLocalStorage, Object])
168
169
  ], ObserveModule);
170
+ const skipInstrumentation = (instance) => {
171
+ try {
172
+ return (
173
+ // The user hook runs first so it can exclude providers whose mere
174
+ // inspection throws before the structural checks below ever touch
175
+ // them.
176
+ options.skipInstrumentation(instance) ||
177
+ [asyncLocalStorage, operationTraceRegistry].includes(instance) ||
178
+ instance instanceof TraceSamplerService ||
179
+ instance instanceof TracerService ||
180
+ instance instanceof ObserveAgentSharedBuffer ||
181
+ // Its methods run *inside* the traces it opens, so instrumenting it
182
+ // would put a span for the agent itself at the root of every GraphQL
183
+ // operation it records.
184
+ instance instanceof GraphQLObserveAgentService ||
185
+ // Same reason: its wrapper runs inside the job traces it opens.
186
+ instance instanceof ScheduleObserveAgentService ||
187
+ // Nest's discovery machinery, which the GraphQL agent walks to map
188
+ // root fields back to their resolver classes. It has to stay
189
+ // unproxied: ModulesContainer extends Map, and a Map method invoked
190
+ // with the instrumentation proxy as its receiver throws "called on
191
+ // incompatible receiver" - Map's internal slots live on the target,
192
+ // and a proxy does not forward them.
193
+ instance instanceof ModulesContainer ||
194
+ instance instanceof DiscoveryService ||
195
+ instance instanceof MetadataScanner ||
196
+ // `@nestjs/graphql`'s ResolverDecoratorHost, matched structurally
197
+ // because the package is an optional peer. Its `onRequestStart` /
198
+ // `onRequestEnd` methods invoke the hooks this module registers, so
199
+ // instrumenting it would wrap the agent's own bookkeeping in spans
200
+ // inside every operation it measures.
201
+ isResolverDecoratorHost(instance));
202
+ }
203
+ catch {
204
+ // An instance that throws on inspection - `instanceof` runs its
205
+ // prototype trap, `isResolverDecoratorHost` reads properties - cannot
206
+ // be instrumented either way. nestjs-cls proxy providers are the
207
+ // canonical case: any access outside a CLS context throws
208
+ // ProxyProviderNotResolvedException, and instrumentation runs at
209
+ // bootstrap, where no such context exists. Leaving the provider alone
210
+ // is the only answer that lets the app start.
211
+ return true;
212
+ }
213
+ };
169
214
  return {
170
215
  ObserveInstrument: {
216
+ // Exclusions live entirely in the decorator: the framework's contract
217
+ // is `instanceDecorator` alone (nestjs/nest#17559 dropped a separate
218
+ // skip hook to avoid duplicating APIs). Newer cores additionally wrap
219
+ // this in a safety net that falls back to the undecorated instance,
220
+ // with a warning, should it ever throw.
171
221
  instanceDecorator: createInstanceDecorator(asyncLocalStorage, operationTraceRegistry, {
172
222
  traceIdKey: options.traceIdKey,
173
- skipInstrumentation: (instance) => {
174
- return ([asyncLocalStorage, operationTraceRegistry].includes(instance) ||
175
- instance instanceof TraceSamplerService ||
176
- instance instanceof TracerService ||
177
- instance instanceof ObserveAgentSharedBuffer ||
178
- // Its methods run *inside* the traces it opens, so instrumenting
179
- // it would put a span for the agent itself at the root of every
180
- // GraphQL operation it records.
181
- instance instanceof GraphQLObserveAgentService ||
182
- // Same reason: its wrapper runs inside the job traces it opens.
183
- instance instanceof ScheduleObserveAgentService ||
184
- // Nest's discovery machinery, which the GraphQL agent walks to
185
- // map root fields back to their resolver classes. It has to stay
186
- // unproxied: ModulesContainer extends Map, and a Map method
187
- // invoked with the instrumentation proxy as its receiver throws
188
- // "called on incompatible receiver" - Map's internal slots live
189
- // on the target, and a proxy does not forward them.
190
- instance instanceof ModulesContainer ||
191
- instance instanceof DiscoveryService ||
192
- instance instanceof MetadataScanner ||
193
- // `@nestjs/graphql`'s ResolverDecoratorHost, matched structurally
194
- // because the package is an optional peer. Its `onRequestStart` /
195
- // `onRequestEnd` methods invoke the hooks this module registers,
196
- // so instrumenting it would wrap the agent's own bookkeeping in
197
- // spans inside every operation it measures.
198
- isResolverDecoratorHost(instance));
199
- },
223
+ skipInstrumentation,
200
224
  }),
201
225
  },
202
226
  ObserveModule,
@@ -14,6 +14,14 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
14
14
  private readonly observeAgentSharedBuffer;
15
15
  private readonly traceSamplerService;
16
16
  private httpAdapterInitSubscription;
17
+ /**
18
+ * `http.queryParamsObfuscateRegex`, rebuilt with the global flag when it was
19
+ * supplied without one. It is applied with `replaceAll`, which throws on a
20
+ * non-global RegExp - inside the request hook, so every traced request would
21
+ * answer 500 while ignored routes (health checks) kept passing. Same
22
+ * normalisation `RedactionOptions.patterns` already receives.
23
+ */
24
+ private readonly queryParamsObfuscateRegex;
17
25
  constructor(httpAdapterHost: HttpAdapterHost, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, observeAgentSharedBuffer: ObserveAgentSharedBuffer, traceSamplerService: TraceSamplerService);
18
26
  onModuleInit(): void;
19
27
  onModuleDestroy(): void;
@@ -32,6 +32,14 @@ let HttpObserveAgentService = class HttpObserveAgentService {
32
32
  observeAgentSharedBuffer;
33
33
  traceSamplerService;
34
34
  httpAdapterInitSubscription;
35
+ /**
36
+ * `http.queryParamsObfuscateRegex`, rebuilt with the global flag when it was
37
+ * supplied without one. It is applied with `replaceAll`, which throws on a
38
+ * non-global RegExp - inside the request hook, so every traced request would
39
+ * answer 500 while ignored routes (health checks) kept passing. Same
40
+ * normalisation `RedactionOptions.patterns` already receives.
41
+ */
42
+ queryParamsObfuscateRegex;
35
43
  constructor(httpAdapterHost, asyncLocalStorage, options, operationTraceRegistry, observeAgentSharedBuffer, traceSamplerService) {
36
44
  this.httpAdapterHost = httpAdapterHost;
37
45
  this.asyncLocalStorage = asyncLocalStorage;
@@ -39,6 +47,7 @@ let HttpObserveAgentService = class HttpObserveAgentService {
39
47
  this.operationTraceRegistry = operationTraceRegistry;
40
48
  this.observeAgentSharedBuffer = observeAgentSharedBuffer;
41
49
  this.traceSamplerService = traceSamplerService;
50
+ this.queryParamsObfuscateRegex = toGlobalRegExp(this.options.http?.queryParamsObfuscateRegex);
42
51
  // The "setOnRouteTriggered" hook must be set immediately
43
52
  // to ensure that route metadata is captured correctly.
44
53
  const { httpAdapter } = this.httpAdapterHost;
@@ -112,8 +121,8 @@ let HttpObserveAgentService = class HttpObserveAgentService {
112
121
  // than instead - it exists for the keys only that deployment knows
113
122
  // about.
114
123
  const redactedUrl = redactUrlQuery(req.url);
115
- const originalUrl = this.options.http?.queryParamsObfuscateRegex
116
- ? redactedUrl.replaceAll(this.options.http.queryParamsObfuscateRegex, "[REDACTED]")
124
+ const originalUrl = this.queryParamsObfuscateRegex
125
+ ? redactedUrl.replaceAll(this.queryParamsObfuscateRegex, "[REDACTED]")
117
126
  : redactedUrl;
118
127
  this.operationTraceRegistry.startTrace(traceId, {
119
128
  protocol: req.protocol,
@@ -218,3 +227,13 @@ HttpObserveAgentService = __decorate([
218
227
  TraceSamplerService])
219
228
  ], HttpObserveAgentService);
220
229
  export { HttpObserveAgentService };
230
+ /**
231
+ * Rebuilds a RegExp with the global flag when it lacks one, keeping the
232
+ * original otherwise. `replaceAll` refuses a non-global pattern outright.
233
+ */
234
+ function toGlobalRegExp(pattern) {
235
+ if (!pattern || pattern.global) {
236
+ return pattern;
237
+ }
238
+ return new RegExp(pattern.source, pattern.flags + "g");
239
+ }
@@ -19,5 +19,14 @@ export declare class QueueObserveAgentService<Store extends Record<string, unkno
19
19
  * omitted rather than reported as zero.
20
20
  */
21
21
  private readQueueMetadata;
22
+ /**
23
+ * Loads `@nestjs/bullmq`'s processor decorator without a static import, so a
24
+ * service that runs no queue need not install the package. The prototype is
25
+ * patched from the constructor, strictly before any processor is decorated.
26
+ *
27
+ * Returns `undefined` when the package is not installed and `null` when it
28
+ * is, but does not expose the decorator service where expected.
29
+ */
30
+ private loadProcessorDecoratorService;
22
31
  private patchDecorate;
23
32
  }
@@ -11,13 +11,13 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
11
  return function (target, key) { decorator(target, key, paramIndex); }
12
12
  };
13
13
  var QueueObserveAgentService_1;
14
- import { ProcessorDecoratorService } from "@nestjs/bullmq/dist/instrument/processor-decorator.service.js";
15
14
  import { Inject, Injectable, Logger } from "@nestjs/common";
16
15
  import { AsyncLocalStorage } from "async_hooks";
17
16
  import { randomUUID } from "crypto";
18
17
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
19
18
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
20
19
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
20
+ import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
21
21
  let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAgentService {
22
22
  observeAgentSharedBuffer;
23
23
  options;
@@ -62,7 +62,35 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
62
62
  }
63
63
  return metadata;
64
64
  }
65
+ /**
66
+ * Loads `@nestjs/bullmq`'s processor decorator without a static import, so a
67
+ * service that runs no queue need not install the package. The prototype is
68
+ * patched from the constructor, strictly before any processor is decorated.
69
+ *
70
+ * Returns `undefined` when the package is not installed and `null` when it
71
+ * is, but does not expose the decorator service where expected.
72
+ */
73
+ loadProcessorDecoratorService() {
74
+ const result = loadOptionalPeer("@nestjs/bullmq", "@nestjs/bullmq/dist/instrument/processor-decorator.service.js");
75
+ if (!result.installed) {
76
+ return undefined;
77
+ }
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
81
+ // never the only diagnostic.
82
+ this.logger.warn(`@nestjs/bullmq is installed but its processor decorator could not be loaded: ${describePeerLoadError(result.error)}`);
83
+ return null;
84
+ }
85
+ return result.module?.ProcessorDecoratorService ?? null;
86
+ }
65
87
  patchDecorate() {
88
+ const ProcessorDecoratorService = this.loadProcessorDecoratorService();
89
+ if (ProcessorDecoratorService === undefined) {
90
+ // The @nestjs/bullmq package is an optional peer. No queue means no
91
+ // processor to wrap, and that is not a misconfiguration.
92
+ return;
93
+ }
66
94
  if (!ProcessorDecoratorService?.prototype) {
67
95
  this.logger.warn("ProcessorDecoratorService is not available. Please, update to the latest version of @nestjs/bullmq. Skipping patching.");
68
96
  return;
@@ -1,6 +1,6 @@
1
1
  import { OnModuleDestroy, OnModuleInit } from "@nestjs/common";
2
2
  import { ModulesContainer } from "@nestjs/core";
3
- import { BaseRpcContext, Server, Transport } from "@nestjs/microservices";
3
+ import type { BaseRpcContext, Server, Transport } from "@nestjs/microservices";
4
4
  import { AsyncLocalStorage } from "async_hooks";
5
5
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
6
6
  import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.interface.js";
@@ -19,10 +19,25 @@ export declare class RpcObserveAgentService<Store extends Record<string, unknown
19
19
  private readonly operationTraceRegistry;
20
20
  private readonly observeAgentSharedBuffer;
21
21
  private readonly traceSamplerService;
22
+ private readonly logger;
22
23
  private rpcTargetAddedSubscription;
24
+ /**
25
+ * Assigned in `onModuleInit`. Every use below is reached only through the
26
+ * hooks registered there, after a successful load - a service without the
27
+ * package has no RPC target to hook.
28
+ */
29
+ private microservices;
23
30
  constructor(asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>, options: ObserveModuleOptionsWithDefaults, modulesContainer: ModulesContainer, operationTraceRegistry: OperationTraceRegistry, observeAgentSharedBuffer: ObserveAgentSharedBuffer, traceSamplerService: TraceSamplerService);
24
31
  onModuleInit(): void;
25
32
  onModuleDestroy(): void;
33
+ /**
34
+ * Loads `@nestjs/microservices` without a static import, so a service that
35
+ * exposes no microservice need not install the package. Loaded here rather
36
+ * than lazily because the target registry is subscribed from `onModuleInit`,
37
+ * and a dynamic `import()` would resolve after a target may already have
38
+ * been announced.
39
+ */
40
+ private loadMicroservices;
26
41
  registerRpcHooks(target: Server): void;
27
42
  /**
28
43
  * Names the transport for the snapshot's `protocol` field.
@@ -10,22 +10,30 @@ var __metadata = (this && this.__metadata) || function (k, v) {
10
10
  var __param = (this && this.__param) || function (paramIndex, decorator) {
11
11
  return function (target, key) { decorator(target, key, paramIndex); }
12
12
  };
13
- import { Inject, Injectable, } from "@nestjs/common";
13
+ var RpcObserveAgentService_1;
14
+ import { Inject, Injectable, Logger, } from "@nestjs/common";
14
15
  import { ModulesContainer } from "@nestjs/core";
15
- import { KafkaContext, MqttContext, NatsContext, RedisContext, RmqContext, TcpContext, Transport, } from "@nestjs/microservices";
16
16
  import { AsyncLocalStorage } from "async_hooks";
17
17
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
18
18
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
19
19
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
20
20
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
21
- let RpcObserveAgentService = class RpcObserveAgentService {
21
+ import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
22
+ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentService {
22
23
  asyncLocalStorage;
23
24
  options;
24
25
  modulesContainer;
25
26
  operationTraceRegistry;
26
27
  observeAgentSharedBuffer;
27
28
  traceSamplerService;
29
+ logger = new Logger(RpcObserveAgentService_1.name);
28
30
  rpcTargetAddedSubscription;
31
+ /**
32
+ * Assigned in `onModuleInit`. Every use below is reached only through the
33
+ * hooks registered there, after a successful load - a service without the
34
+ * package has no RPC target to hook.
35
+ */
36
+ microservices;
29
37
  constructor(asyncLocalStorage, options, modulesContainer, operationTraceRegistry, observeAgentSharedBuffer, traceSamplerService) {
30
38
  this.asyncLocalStorage = asyncLocalStorage;
31
39
  this.options = options;
@@ -35,6 +43,10 @@ let RpcObserveAgentService = class RpcObserveAgentService {
35
43
  this.traceSamplerService = traceSamplerService;
36
44
  }
37
45
  onModuleInit() {
46
+ this.microservices = this.loadMicroservices();
47
+ if (!this.microservices) {
48
+ return;
49
+ }
38
50
  this.rpcTargetAddedSubscription = this.modulesContainer
39
51
  .getRpcTargetRegistry?.()
40
52
  .subscribe((target) => this.registerRpcHooks(target));
@@ -44,9 +56,31 @@ let RpcObserveAgentService = class RpcObserveAgentService {
44
56
  this.rpcTargetAddedSubscription.unsubscribe();
45
57
  }
46
58
  }
59
+ /**
60
+ * Loads `@nestjs/microservices` without a static import, so a service that
61
+ * exposes no microservice need not install the package. Loaded here rather
62
+ * than lazily because the target registry is subscribed from `onModuleInit`,
63
+ * and a dynamic `import()` would resolve after a target may already have
64
+ * been announced.
65
+ */
66
+ loadMicroservices() {
67
+ const result = loadOptionalPeer("@nestjs/microservices");
68
+ if (!result.installed) {
69
+ // No microservice means no RPC target to hook, and that is not a
70
+ // misconfiguration.
71
+ return undefined;
72
+ }
73
+ if (!result.module) {
74
+ // Installed but unloadable is a misconfiguration, and the symptom
75
+ // otherwise is a service whose RPC operations silently never appear.
76
+ this.logger.warn(`@nestjs/microservices is installed but could not be loaded, so RPC operations will not be instrumented: ${describePeerLoadError(result.error)}`);
77
+ return undefined;
78
+ }
79
+ return result.module;
80
+ }
47
81
  registerRpcHooks(target) {
48
82
  target.setOnProcessingStartHook((transportId, ctx, done) => {
49
- if (transportId === Transport.GRPC) {
83
+ if (transportId === this.microservices.Transport.GRPC) {
50
84
  this.startGrpcRequestTracing(transportId, ctx, done);
51
85
  return;
52
86
  }
@@ -66,7 +100,7 @@ let RpcObserveAgentService = class RpcObserveAgentService {
66
100
  toProtocolName(transportId) {
67
101
  return typeof transportId === "symbol"
68
102
  ? transportId.description ?? "custom"
69
- : Transport[transportId];
103
+ : this.microservices.Transport[transportId];
70
104
  }
71
105
  startRpcRequestTracing(transportId, ctx, done) {
72
106
  // The same map `run` is given, rather than `getStore()` inside the callback:
@@ -147,7 +181,7 @@ let RpcObserveAgentService = class RpcObserveAgentService {
147
181
  }
148
182
  setTimeout(async () => {
149
183
  let userId;
150
- if (transportId === Transport.GRPC) {
184
+ if (transportId === this.microservices.Transport.GRPC) {
151
185
  if (this.options.grpc?.getUserId) {
152
186
  userId = this.options.grpc?.getUserId?.(ctx);
153
187
  }
@@ -168,6 +202,7 @@ let RpcObserveAgentService = class RpcObserveAgentService {
168
202
  }, 0);
169
203
  }
170
204
  getOperationIdFromContext(ctx) {
205
+ const { KafkaContext, MqttContext, NatsContext, RedisContext, RmqContext, TcpContext, } = this.microservices;
171
206
  switch (true) {
172
207
  case ctx instanceof KafkaContext:
173
208
  case ctx instanceof MqttContext:
@@ -179,12 +214,18 @@ let RpcObserveAgentService = class RpcObserveAgentService {
179
214
  return ctx.getChannel();
180
215
  case ctx instanceof NatsContext:
181
216
  return ctx.getSubject();
182
- default:
183
- throw new Error(`Unsupported context type: ${ctx.constructor.name}`);
217
+ default: {
218
+ // A custom transporter delivers its own context class - expected, per
219
+ // `toProtocolName` - and there is no universal accessor for its
220
+ // routing key. Throwing here would fail the message before `done()`
221
+ // ever ran, so fall back to a conventional accessor when one exists.
222
+ const pattern = ctx?.getPattern?.();
223
+ return typeof pattern === "string" ? pattern : "unknown";
224
+ }
184
225
  }
185
226
  }
186
227
  };
187
- RpcObserveAgentService = __decorate([
228
+ RpcObserveAgentService = RpcObserveAgentService_1 = __decorate([
188
229
  Injectable(),
189
230
  __param(1, Inject(OBSERVE_OPTIONS)),
190
231
  __metadata("design:paramtypes", [AsyncLocalStorage, Object, ModulesContainer,
@@ -35,10 +35,10 @@ export declare class ScheduleObserveAgentService<Store extends Record<string, un
35
35
  constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>);
36
36
  /**
37
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.
38
+ * nothing need not install the package. Loaded from the constructor because
39
+ * a dynamic `import()` would resolve after provider instantiation, with no
40
+ * guarantee of landing before the explorer's `onModuleInit` has already
41
+ * wrapped every handler.
42
42
  */
43
43
  private loadScheduleExplorer;
44
44
  private patchScheduleExplorer;