@nestjs/observe 0.3.18 → 0.3.20

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.
Files changed (35) hide show
  1. package/README.md +2 -1
  2. package/dist/agent/credentials-notice.d.ts +39 -0
  3. package/dist/agent/credentials-notice.js +68 -0
  4. package/dist/agent/detached-observe-worker.assembly.js +2 -0
  5. package/dist/agent/detached-observe-worker.d.ts +5 -0
  6. package/dist/agent/detached-observe-worker.js +3 -0
  7. package/dist/agent/observe-agent.worker.js +17 -16
  8. package/dist/instrument/create-instance-decorator.instrument.js +35 -2
  9. package/dist/interfaces/observe-options.interface.d.ts +16 -1
  10. package/dist/observe.module.js +12 -0
  11. package/dist/outgoing/http.integration.js +4 -0
  12. package/dist/outgoing/llm/llm-fetch.integration.d.ts +56 -0
  13. package/dist/outgoing/llm/llm-fetch.integration.js +236 -0
  14. package/dist/outgoing/llm/llm-providers.d.ts +25 -0
  15. package/dist/outgoing/llm/llm-providers.js +96 -0
  16. package/dist/outgoing/llm/llm-usage.d.ts +67 -0
  17. package/dist/outgoing/llm/llm-usage.js +263 -0
  18. package/dist/outgoing/outgoing-observe-agent.service.d.ts +1 -0
  19. package/dist/outgoing/outgoing-observe-agent.service.js +12 -0
  20. package/dist/outgoing/outgoing-span.recorder.d.ts +9 -0
  21. package/dist/outgoing/outgoing-span.recorder.js +55 -6
  22. package/dist/protocols/deferred-trace-completion.d.ts +27 -0
  23. package/dist/protocols/deferred-trace-completion.js +91 -0
  24. package/dist/protocols/graphql-observe-agent.service.js +7 -12
  25. package/dist/protocols/http-observe-agent.service.d.ts +2 -2
  26. package/dist/protocols/http-observe-agent.service.js +22 -19
  27. package/dist/protocols/job-trace-runner.d.ts +3 -3
  28. package/dist/protocols/job-trace-runner.js +10 -20
  29. package/dist/protocols/rpc-observe-agent.service.js +15 -29
  30. package/dist/protocols/ws-observe-agent.service.js +6 -10
  31. package/dist/services/trace-sampler.service.d.ts +1 -0
  32. package/dist/services/trace-sampler.service.js +10 -4
  33. package/dist/utils/sdk-version.util.d.ts +19 -0
  34. package/dist/utils/sdk-version.util.js +34 -0
  35. package/package.json +3 -2
@@ -0,0 +1,91 @@
1
+ import { uuidv7 } from "../utils/uuid-v7.util.js";
2
+ const reportedCallbacks = new WeakSet();
3
+ const reportedDeferredFailures = new WeakSet();
4
+ function describeFailure(error) {
5
+ try {
6
+ return error instanceof Error ? error.message : String(error);
7
+ }
8
+ catch {
9
+ return "an unprintable error";
10
+ }
11
+ }
12
+ function warnSafely(logger, message) {
13
+ try {
14
+ logger.warn(message);
15
+ }
16
+ catch {
17
+ // Diagnostics must not become another failure in the operation traced -
18
+ // or in its deferred telemetry.
19
+ }
20
+ }
21
+ /**
22
+ * Runs a callback from the module options, answering `fallback()` when it
23
+ * throws. These callbacks only shape what is recorded, so a bug in one must
24
+ * not fail the request, message or job being recorded - or, thrown from a
25
+ * timer, end the process. The first failure of each callback is reported
26
+ * with its error and `outcome`, what was given up for it; later ones are not.
27
+ */
28
+ export function invokeUserCallbackSafely(callback, args, receiver, fallback, logger, name, outcome) {
29
+ try {
30
+ return callback.apply(receiver, args);
31
+ }
32
+ catch (error) {
33
+ if (!reportedCallbacks.has(callback)) {
34
+ reportedCallbacks.add(callback);
35
+ warnSafely(logger, `"${name}" threw; ${outcome}. Later failures are not reported: ${describeFailure(error)}`);
36
+ }
37
+ return fallback();
38
+ }
39
+ }
40
+ /**
41
+ * The trace id for an operation. A generator that throws is replaced by a
42
+ * fresh uuidv7, which no open trace can share, so the operation is still
43
+ * traced under a registry key of its own.
44
+ */
45
+ export function generateTraceIdSafely(generator, context, receiver, logger) {
46
+ return invokeUserCallbackSafely(generator, [context], receiver, uuidv7, logger, "traceIdGenerator", "using a random trace id");
47
+ }
48
+ /** Copies an operation's `setAttributes` into its store, unless it throws. */
49
+ export function setAttributesSafely(callback, args, receiver, store, logger, transport) {
50
+ if (!callback) {
51
+ return;
52
+ }
53
+ const attributes = invokeUserCallbackSafely(callback, args, receiver, () => undefined, logger, `${transport}.setAttributes`, "continuing without its attributes");
54
+ if (!attributes) {
55
+ return;
56
+ }
57
+ for (const [key, value] of Object.entries(attributes)) {
58
+ store.set(key, value);
59
+ }
60
+ }
61
+ /**
62
+ * Whether `ignore` excludes an operation. One that throws excludes it as
63
+ * well: the operation still runs, but recording what a broken predicate may
64
+ * have been written to keep out is not a safe guess.
65
+ */
66
+ export function shouldIgnoreSafely(callback, args, receiver, logger, transport) {
67
+ if (!callback) {
68
+ return false;
69
+ }
70
+ return invokeUserCallbackSafely(callback, args, receiver, () => true, logger, `${transport}.ignore`, "not tracing the operation");
71
+ }
72
+ /** A bad identity callback must not prevent the trace from being closed. */
73
+ export function getUserIdSafely(callback, args, receiver, logger, transport) {
74
+ if (!callback) {
75
+ return undefined;
76
+ }
77
+ return invokeUserCallbackSafely(callback, args, receiver, () => undefined, logger, `${transport}.getUserId`, "completing the trace without a user id");
78
+ }
79
+ /** Run deferred completion without ever leaking a rejection from its timer. */
80
+ export function deferTraceCompletion(completion, logger, transport) {
81
+ setTimeout(() => {
82
+ void Promise.resolve()
83
+ .then(completion)
84
+ .catch((error) => {
85
+ if (!reportedDeferredFailures.has(logger)) {
86
+ reportedDeferredFailures.add(logger);
87
+ warnSafely(logger, `Deferred ${transport} trace completion failed; later failures are not reported: ${describeFailure(error)}`);
88
+ }
89
+ });
90
+ }, 0);
91
+ }
@@ -19,6 +19,7 @@ import { CALLER_METADATA_KEY, OBSERVE_OPTIONS, TRACE_REGISTRY_KEY, } from "../ob
19
19
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
20
20
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
21
21
  import { parseGraphQLOperation, toResolveInfoLike, } from "./graphql-operation-parser.js";
22
+ import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
22
23
  /**
23
24
  * Protocol recorded for a GraphQL operation that arrived over something other
24
25
  * than an instrumented HTTP request. A query over HTTP keeps `http` as its
@@ -172,7 +173,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
172
173
  ...parsed,
173
174
  operationName,
174
175
  });
175
- if (this.options.graphql?.ignore?.(info)) {
176
+ if (shouldIgnoreSafely(this.options.graphql?.ignore, [info], this.options.graphql, this.logger, "graphql")) {
176
177
  return undefined;
177
178
  }
178
179
  const operationId = `${info.parentType.name}.${info.fieldName}`;
@@ -273,7 +274,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
273
274
  if (!shouldCapture) {
274
275
  return undefined;
275
276
  }
276
- const traceId = this.options.traceIdGenerator(info);
277
+ const traceId = generateTraceIdSafely(this.options.traceIdGenerator, info, this.options, this.logger);
277
278
  const store = new Map();
278
279
  store.set(this.options.traceIdKey, traceId);
279
280
  this.asyncLocalStorage.enterWith(store);
@@ -329,15 +330,15 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
329
330
  * operation out of the success bucket.
330
331
  */
331
332
  endOperationTrace(traceId, context) {
332
- setTimeout(async () => {
333
- const userId = this.options.graphql?.getUserId?.(context);
333
+ deferTraceCompletion(async () => {
334
+ const userId = getUserIdSafely(this.options.graphql?.getUserId, [context], this.options.graphql, this.logger, "graphql");
334
335
  this.operationTraceRegistry.endTrace(traceId, { userId });
335
336
  const snapshot = await this.operationTraceRegistry.pluckSnapshot(traceId);
336
337
  if (!snapshot) {
337
338
  return;
338
339
  }
339
340
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
340
- }, 0);
341
+ }, this.logger, "graphql");
341
342
  }
342
343
  /**
343
344
  * Picks the error a failed operation is recorded with.
@@ -408,13 +409,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
408
409
  if (!store) {
409
410
  return;
410
411
  }
411
- const attributes = this.options.graphql.setAttributes(info, context);
412
- if (!attributes) {
413
- return;
414
- }
415
- for (const [key, value] of Object.entries(attributes)) {
416
- store.set(key, value);
417
- }
412
+ setAttributesSafely(this.options.graphql.setAttributes, [info, context], this.options.graphql, store, this.logger, "graphql");
418
413
  }
419
414
  };
420
415
  GraphQLObserveAgentService = GraphQLObserveAgentService_1 = __decorate([
@@ -6,7 +6,7 @@ import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.
6
6
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
7
7
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
8
8
  import { KeyOf } from "../types/key-of.type.js";
9
- /** What the request hook reads of an Express or Fastify request. */
9
+ /** What the request hook reads of an Express, Fastify or Node request. */
10
10
  interface IncomingHttpRequest {
11
11
  url: string;
12
12
  method: string;
@@ -75,7 +75,7 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
75
75
  * Recognised by what the CORS spec defines a preflight to be - `OPTIONS`
76
76
  * with an `Access-Control-Request-Method` header - rather than by the
77
77
  * method alone, so an application's own `OPTIONS` handler is still traced.
78
- * Both adapters lower-case header names.
78
+ * Every adapter lower-cases header names.
79
79
  */
80
80
  private isUntracedPreflight;
81
81
  private shouldIgnoreRequest;
@@ -21,6 +21,7 @@ import { OperationTraceRegistry } from "../services/operation-trace.registry.js"
21
21
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
22
22
  import { redactUrlQuery } from "../utils/redact-url-query.js";
23
23
  import { uuidv7 } from "../utils/uuid-v7.util.js";
24
+ import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
24
25
  /**
25
26
  * How long an aborted request's handler gets to finish its spans before the
26
27
  * trace is dropped from the registry. Generous next to a typical handler, tiny
@@ -106,16 +107,9 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
106
107
  // identical object, one lookup fewer, and it is known to exist.
107
108
  const store = new Map();
108
109
  this.asyncLocalStorage.run(store, () => {
109
- const traceId = this.options.traceIdGenerator(req);
110
+ const traceId = generateTraceIdSafely(this.options.traceIdGenerator, req, this.options, this.logger);
110
111
  store.set(this.options.traceIdKey, traceId);
111
- if (this.options.http?.setAttributes) {
112
- const attributes = this.options.http?.setAttributes?.(req);
113
- if (attributes) {
114
- for (const [key, value] of Object.entries(attributes)) {
115
- store.set(key, value);
116
- }
117
- }
118
- }
112
+ setAttributesSafely(this.options.http?.setAttributes, [req], this.options.http, store, this.logger, "http");
119
113
  // A request that is not recorded still carries its trace id, which an
120
114
  // adopted `x-request-id` can share with a recorded request. A registry
121
115
  // key of its own, never registered, keeps its lookups off that trace.
@@ -174,11 +168,8 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
174
168
  if (!traceId) {
175
169
  return;
176
170
  }
177
- setTimeout(async () => {
178
- let userId;
179
- if (this.options.http?.getUserId) {
180
- userId = this.options.http?.getUserId?.(req);
181
- }
171
+ deferTraceCompletion(async () => {
172
+ const userId = getUserIdSafely(this.options.http?.getUserId, [req], this.options.http, this.logger, "http");
182
173
  this.operationTraceRegistry.endTrace(traceId, {
183
174
  statusCode: res.statusCode,
184
175
  userId,
@@ -194,7 +185,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
194
185
  }
195
186
  }
196
187
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
197
- }, 0);
188
+ }, this.logger, "http");
198
189
  }
199
190
  /**
200
191
  * Frees the trace when the client goes away before the response finishes.
@@ -253,7 +244,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
253
244
  * Recognised by what the CORS spec defines a preflight to be - `OPTIONS`
254
245
  * with an `Access-Control-Request-Method` header - rather than by the
255
246
  * method alone, so an application's own `OPTIONS` handler is still traced.
256
- * Both adapters lower-case header names.
247
+ * Every adapter lower-cases header names.
257
248
  */
258
249
  isUntracedPreflight(req) {
259
250
  return (!this.options.http?.tracePreflights &&
@@ -262,7 +253,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
262
253
  }
263
254
  shouldIgnoreRequest(req) {
264
255
  if (typeof this.options.http?.ignore === "function") {
265
- return this.options.http.ignore(req);
256
+ return shouldIgnoreSafely(this.options.http.ignore, [req], this.options.http, this.logger, "http");
266
257
  }
267
258
  if (Array.isArray(this.options.http?.ignore)) {
268
259
  const blocklist = this.options.http.ignore;
@@ -271,13 +262,13 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
271
262
  return req.url === item;
272
263
  }
273
264
  if (item instanceof RegExp) {
274
- return item.test(req.url);
265
+ return testIgnoreRegex(item, req.url);
275
266
  }
276
267
  if (typeof item === "object") {
277
268
  return (item.method === req.method &&
278
269
  (typeof item.path === "string"
279
270
  ? req.url === item.path
280
- : item.path.test(req.url)));
271
+ : testIgnoreRegex(item.path, req.url)));
281
272
  }
282
273
  return false;
283
274
  });
@@ -294,6 +285,18 @@ HttpObserveAgentService = HttpObserveAgentService_1 = __decorate([
294
285
  TraceSamplerService])
295
286
  ], HttpObserveAgentService);
296
287
  export { HttpObserveAgentService };
288
+ /**
289
+ * Global and sticky regular expressions carry a lastIndex between calls. Use
290
+ * a fresh expression for each ignore decision so matching always starts at the
291
+ * beginning without changing the user's regex state. Ordinary expressions
292
+ * are stateless here and can be tested directly.
293
+ */
294
+ function testIgnoreRegex(pattern, value) {
295
+ if (!pattern.global && !pattern.sticky) {
296
+ return pattern.test(value);
297
+ }
298
+ return new RegExp(pattern.source, pattern.flags).test(value);
299
+ }
297
300
  /**
298
301
  * Rebuilds a RegExp with the global flag when it lacks one, keeping the
299
302
  * original otherwise. `replaceAll` refuses a non-global pattern outright.
@@ -71,9 +71,9 @@ export declare class JobTraceRunner<Store extends Record<string, unknown>> {
71
71
  */
72
72
  private activeJobOf;
73
73
  /**
74
- * Whether `jobs.ignore` matches this run. A predicate that throws is
75
- * reported and read as "trace it": a bug in tracing configuration must not
76
- * stop the job itself from running.
74
+ * Whether `jobs.ignore` matches this run. A predicate that throws is read
75
+ * as a match, as every other protocol reads its own: the job still runs,
76
+ * just without a trace.
77
77
  */
78
78
  private isIgnored;
79
79
  /**
@@ -1,6 +1,7 @@
1
1
  import { JOB_TRACE_OPTION_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
2
2
  import { REQUEST_ID_PATTERN } from "../utils/default-trace-id-generator.util.js";
3
3
  import { uuidv7 } from "../utils/uuid-v7.util.js";
4
+ import { deferTraceCompletion, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
4
5
  const ORIGINAL_ADD = Symbol.for("nestjs.observe.queue.add");
5
6
  const ORIGINAL_ADD_BULK = Symbol.for("nestjs.observe.queue.addBulk");
6
7
  /** Where a run records which job it is running, for a layer nested inside it. */
@@ -132,9 +133,9 @@ export class JobTraceRunner {
132
133
  : { queueName: job.queueName, id: String(job.id) };
133
134
  }
134
135
  /**
135
- * Whether `jobs.ignore` matches this run. A predicate that throws is
136
- * reported and read as "trace it": a bug in tracing configuration must not
137
- * stop the job itself from running.
136
+ * Whether `jobs.ignore` matches this run. A predicate that throws is read
137
+ * as a match, as every other protocol reads its own: the job still runs,
138
+ * just without a trace.
138
139
  */
139
140
  isIgnored(context) {
140
141
  // Jobs never reach the sampler, which is where every other protocol
@@ -142,13 +143,7 @@ export class JobTraceRunner {
142
143
  if (this.options.enabled === false) {
143
144
  return true;
144
145
  }
145
- try {
146
- return Boolean(this.options.jobs?.ignore?.(context));
147
- }
148
- catch (error) {
149
- this.logger.warn(`"jobs.ignore" threw for job "${context.name}" (queue "${context.queueName}"); tracing it anyway: ${error instanceof Error ? error.message : String(error)}`);
150
- return false;
151
- }
146
+ return shouldIgnoreSafely(this.options.jobs?.ignore, [context], this.options.jobs, this.logger, "jobs");
152
147
  }
153
148
  /**
154
149
  * Runs one job under a trace.
@@ -197,12 +192,7 @@ export class JobTraceRunner {
197
192
  name: job.name,
198
193
  id: typeof job.id === "number" ? `${job.id}` : job.id,
199
194
  };
200
- const attributes = this.options.jobs?.setAttributes?.(context);
201
- if (attributes) {
202
- for (const [key, value] of Object.entries(attributes)) {
203
- store.set(key, value);
204
- }
205
- }
195
+ setAttributesSafely(this.options.jobs?.setAttributes, [context], this.options.jobs, store, this.logger, "jobs");
206
196
  if (this.isIgnored(context)) {
207
197
  // The trace id stays in the store so logs and jobs enqueued from here
208
198
  // still correlate; nothing is registered under the registry key, so
@@ -220,13 +210,13 @@ export class JobTraceRunner {
220
210
  return;
221
211
  }
222
212
  settled = true;
223
- setTimeout(async () => {
213
+ deferTraceCompletion(async () => {
224
214
  this.operationTraceRegistry.endTrace(registryKey, { status });
225
215
  const snapshot = (await this.operationTraceRegistry.pluckSnapshot(registryKey));
226
216
  // `pluckSnapshot` deletes what it returns, so a trace already
227
217
  // plucked answers undefined, and the encoder would dereference it
228
- // inside a `setTimeout`, where no try/catch can reach: an unhandled
229
- // TypeError that took the whole process down.
218
+ // inside a `setTimeout`, where no try/catch can reach: an
219
+ // unhandled TypeError that took the whole process down.
230
220
  //
231
221
  // Dropped rather than reported: there is no snapshot, so there is
232
222
  // nothing to send, and losing one job's self-instrumentation is
@@ -235,7 +225,7 @@ export class JobTraceRunner {
235
225
  return;
236
226
  }
237
227
  this.observeAgentSharedBuffer.insertJobSnapshot(snapshot);
238
- }, 0);
228
+ }, this.logger, "job");
239
229
  };
240
230
  try {
241
231
  const returnValue = invoke(settle);
@@ -19,6 +19,7 @@ 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
21
  import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
22
+ import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
22
23
  let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentService {
23
24
  asyncLocalStorage;
24
25
  options;
@@ -110,17 +111,10 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
110
111
  // identical object, one lookup fewer, and it is known to exist.
111
112
  const store = new Map();
112
113
  return this.asyncLocalStorage.run(store, () => {
113
- const traceId = this.options.traceIdGenerator(ctx);
114
+ const traceId = generateTraceIdSafely(this.options.traceIdGenerator, ctx, this.options, this.logger);
114
115
  store.set(this.options.traceIdKey, traceId);
115
- if (this.options.rpc?.setAttributes) {
116
- const attributes = this.options.rpc?.setAttributes?.(transportId, ctx);
117
- if (attributes) {
118
- for (const [key, value] of Object.entries(attributes)) {
119
- store.set(key, value);
120
- }
121
- }
122
- }
123
- if (this.options.rpc?.ignore?.(transportId, ctx)) {
116
+ setAttributesSafely(this.options.rpc?.setAttributes, [transportId, ctx], this.options.rpc, store, this.logger, "rpc");
117
+ if (shouldIgnoreSafely(this.options.rpc?.ignore, [transportId, ctx], this.options.rpc, this.logger, "rpc")) {
124
118
  return done();
125
119
  }
126
120
  const shouldCapture = this.traceSamplerService.shouldCapture("rpc", {
@@ -142,19 +136,14 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
142
136
  // As above: the map `run` is given, not looked back up.
143
137
  const store = new Map();
144
138
  return this.asyncLocalStorage.run(store, () => {
145
- const traceId = this.options.traceIdGenerator(call);
139
+ const traceId = generateTraceIdSafely(this.options.traceIdGenerator, call, this.options, this.logger);
146
140
  store.set(this.options.traceIdKey, traceId);
147
- if (this.options.grpc?.setAttributes) {
148
- const attributes = this.options.grpc?.setAttributes?.(call);
149
- if (attributes) {
150
- for (const [key, value] of Object.entries(attributes)) {
151
- store.set(key, value);
152
- }
153
- }
154
- }
141
+ setAttributesSafely(this.options.grpc?.setAttributes, [call], this.options.grpc, store, this.logger, "grpc");
155
142
  return new Promise((resolve) => {
143
+ // A throw in this timer escapes the promise: `done()` never runs, and
144
+ // the exception is uncaught. Both decisions below are guarded.
156
145
  setTimeout(() => {
157
- if (this.options.grpc?.ignore?.(call)) {
146
+ if (shouldIgnoreSafely(this.options.grpc?.ignore, [call], this.options.grpc, this.logger, "grpc")) {
158
147
  return resolve(done());
159
148
  }
160
149
  const shouldCapture = this.traceSamplerService.shouldCapture("grpc", {
@@ -182,17 +171,14 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
182
171
  if (!traceId) {
183
172
  return;
184
173
  }
185
- setTimeout(async () => {
174
+ const isGrpc = transportId === this.microservices.Transport.GRPC;
175
+ deferTraceCompletion(async () => {
186
176
  let userId;
187
- if (transportId === this.microservices.Transport.GRPC) {
188
- if (this.options.grpc?.getUserId) {
189
- userId = this.options.grpc?.getUserId?.(ctx);
190
- }
177
+ if (isGrpc) {
178
+ userId = getUserIdSafely(this.options.grpc?.getUserId, [ctx], this.options.grpc, this.logger, "grpc");
191
179
  }
192
180
  else {
193
- if (this.options.rpc?.getUserId) {
194
- userId = this.options.rpc?.getUserId?.(transportId, ctx);
195
- }
181
+ userId = getUserIdSafely(this.options.rpc?.getUserId, [transportId, ctx], this.options.rpc, this.logger, "rpc");
196
182
  }
197
183
  this.operationTraceRegistry.endTrace(traceId, {
198
184
  userId,
@@ -202,7 +188,7 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
202
188
  return;
203
189
  }
204
190
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
205
- }, 0);
191
+ }, this.logger, isGrpc ? "grpc" : "rpc");
206
192
  }
207
193
  getOperationIdFromContext(ctx) {
208
194
  const { KafkaContext, MqttContext, NatsContext, RedisContext, RmqContext, TcpContext, } = this.microservices;
@@ -19,6 +19,7 @@ import { OperationTraceRegistry } from "../services/operation-trace.registry.js"
19
19
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
20
20
  import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
21
21
  import { uuidv7 } from "../utils/uuid-v7.util.js";
22
+ import { deferTraceCompletion, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
22
23
  const ORIGINAL_CREATE = Symbol.for("nestjs.observe.ws.create");
23
24
  /** `@nestjs/websockets`' MESSAGE_METADATA - what `@SubscribeMessage()` writes. */
24
25
  const MESSAGE_METADATA = "message";
@@ -120,13 +121,8 @@ let WsObserveAgentService = WsObserveAgentService_1 = class WsObserveAgentServic
120
121
  return this.asyncLocalStorage.run(store, () => {
121
122
  const traceId = uuidv7();
122
123
  store.set(this.options.traceIdKey, traceId);
123
- const attributes = this.options.ws?.setAttributes?.(message);
124
- if (attributes) {
125
- for (const [key, value] of Object.entries(attributes)) {
126
- store.set(key, value);
127
- }
128
- }
129
- if (this.options.ws?.ignore?.(message) ||
124
+ setAttributesSafely(this.options.ws?.setAttributes, [message], this.options.ws, store, this.logger, "ws");
125
+ if (shouldIgnoreSafely(this.options.ws?.ignore, [message], this.options.ws, this.logger, "ws") ||
130
126
  !this.traceSamplerService.shouldCapture("ws", {
131
127
  gateway: message.gateway,
132
128
  pattern: message.pattern,
@@ -139,16 +135,16 @@ let WsObserveAgentService = WsObserveAgentService_1 = class WsObserveAgentServic
139
135
  tags: this.options.ws?.tags,
140
136
  });
141
137
  const endTrace = () => {
142
- setTimeout(async () => {
138
+ deferTraceCompletion(async () => {
143
139
  this.operationTraceRegistry.endTrace(traceId, {
144
- userId: this.options.ws?.getUserId?.(message),
140
+ userId: getUserIdSafely(this.options.ws?.getUserId, [message], this.options.ws, this.logger, "ws"),
145
141
  });
146
142
  const snapshot = await this.operationTraceRegistry.pluckSnapshot(traceId);
147
143
  if (!snapshot) {
148
144
  return;
149
145
  }
150
146
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
151
- }, 0);
147
+ }, this.logger, "ws");
152
148
  };
153
149
  // Nest's ws proxy hands a thrown error to the exception filter and
154
150
  // resolves, so there is no rejection to read a failure from here - the
@@ -1,6 +1,7 @@
1
1
  import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.interface.js";
2
2
  export declare class TraceSamplerService {
3
3
  private readonly options;
4
+ private readonly logger;
4
5
  constructor(options: ObserveModuleOptionsWithDefaults);
5
6
  /**
6
7
  * Determines if a trace should be captured based on the protocol and attributes.
@@ -10,10 +10,13 @@ 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 TraceSamplerService_1;
14
+ import { Inject, Injectable, Logger } from "@nestjs/common";
14
15
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
15
- let TraceSamplerService = class TraceSamplerService {
16
+ import { invokeUserCallbackSafely } from "../protocols/deferred-trace-completion.js";
17
+ let TraceSamplerService = TraceSamplerService_1 = class TraceSamplerService {
16
18
  options;
19
+ logger = new Logger(TraceSamplerService_1.name);
17
20
  constructor(options) {
18
21
  this.options = options;
19
22
  }
@@ -32,10 +35,13 @@ let TraceSamplerService = class TraceSamplerService {
32
35
  }
33
36
  return Math.random() < this.options.tracesSampleRate; // Randomly capture traces based on sample rate
34
37
  }
35
- return this.options.tracesSampleRate(protocol, attributes);
38
+ // Guarded here rather than at each call site, since every transport asks.
39
+ // A callback that throws keeps the operation out, as a throwing `ignore`
40
+ // does.
41
+ return invokeUserCallbackSafely(this.options.tracesSampleRate, [protocol, attributes], this.options, () => false, this.logger, "tracesSampleRate", "not tracing the operation");
36
42
  }
37
43
  };
38
- TraceSamplerService = __decorate([
44
+ TraceSamplerService = TraceSamplerService_1 = __decorate([
39
45
  Injectable(),
40
46
  __param(0, Inject(OBSERVE_OPTIONS)),
41
47
  __metadata("design:paramtypes", [Object])
@@ -0,0 +1,19 @@
1
+ /**
2
+ * What `x-observe-sdk-version` carries when this package's own manifest cannot
3
+ * be read.
4
+ */
5
+ export declare const UNKNOWN_SDK_VERSION = "unknown";
6
+ /**
7
+ * This package's own version, as its installed `package.json` states it.
8
+ *
9
+ * Sent with every batch so the collector knows which agent an application
10
+ * runs - nothing else tells it, and a project scaffolded with `^0.1.8` keeps
11
+ * installing 0.1.x for as long as nobody edits that range.
12
+ *
13
+ * Resolved by the package's name rather than a relative path, and checked by
14
+ * name: a bundle that moved this file would otherwise read the application's
15
+ * own manifest and report its version instead. A bundle that erased
16
+ * `import.meta.url`, or one shipped without `node_modules`, gets
17
+ * {@link UNKNOWN_SDK_VERSION} - never an exception at start-up.
18
+ */
19
+ export declare function readSdkVersion(): string;
@@ -0,0 +1,34 @@
1
+ import { createRequire } from "module";
2
+ /**
3
+ * What `x-observe-sdk-version` carries when this package's own manifest cannot
4
+ * be read.
5
+ */
6
+ export const UNKNOWN_SDK_VERSION = "unknown";
7
+ /**
8
+ * This package's own version, as its installed `package.json` states it.
9
+ *
10
+ * Sent with every batch so the collector knows which agent an application
11
+ * runs - nothing else tells it, and a project scaffolded with `^0.1.8` keeps
12
+ * installing 0.1.x for as long as nobody edits that range.
13
+ *
14
+ * Resolved by the package's name rather than a relative path, and checked by
15
+ * name: a bundle that moved this file would otherwise read the application's
16
+ * own manifest and report its version instead. A bundle that erased
17
+ * `import.meta.url`, or one shipped without `node_modules`, gets
18
+ * {@link UNKNOWN_SDK_VERSION} - never an exception at start-up.
19
+ */
20
+ export function readSdkVersion() {
21
+ try {
22
+ const require = createRequire(import.meta.url);
23
+ const manifest = require("@nestjs/observe/package.json");
24
+ if (manifest.name === "@nestjs/observe" &&
25
+ typeof manifest.version === "string" &&
26
+ manifest.version.length > 0) {
27
+ return manifest.version;
28
+ }
29
+ }
30
+ catch {
31
+ // Falls through to the placeholder below.
32
+ }
33
+ return UNKNOWN_SDK_VERSION;
34
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.3.18",
3
+ "version": "0.3.20",
4
4
  "description": "Observability and APM agent for NestJS - traces, runtime metrics and custom metrics",
5
5
  "author": "Kamil Mysliwiec",
6
6
  "homepage": "https://observe.nestjs.com",
@@ -128,7 +128,7 @@
128
128
  "@mikro-orm/core": "7.2.0",
129
129
  "@mikro-orm/mysql": "7.2.0",
130
130
  "@mikro-orm/postgresql": "7.2.0",
131
- "@nestjs/apollo": "14.0.0",
131
+ "@nestjs/apollo": "14.1.1",
132
132
  "@nestjs/bull": "12.0.0",
133
133
  "@nestjs/bullmq": "12.0.0",
134
134
  "@nestjs/common": "12.0.1",
@@ -137,6 +137,7 @@
137
137
  "@nestjs/microservices": "12.0.1",
138
138
  "@nestjs/platform-express": "12.0.1",
139
139
  "@nestjs/platform-fastify": "12.0.3",
140
+ "@nestjs/platform-node": "12.3.2",
140
141
  "@nestjs/platform-socket.io": "12.0.3",
141
142
  "@nestjs/platform-ws": "12.0.3",
142
143
  "@nestjs/schedule": "12.0.1",