@nestjs/observe 0.3.17 → 0.3.19

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 (32) hide show
  1. package/LICENSE +1 -2
  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/cli/agent-notes.d.ts +46 -0
  9. package/dist/cli/agent-notes.js +93 -0
  10. package/dist/cli/link.js +13 -0
  11. package/dist/protocols/deferred-trace-completion.d.ts +27 -0
  12. package/dist/protocols/deferred-trace-completion.js +91 -0
  13. package/dist/protocols/graphql-observe-agent.service.d.ts +3 -3
  14. package/dist/protocols/graphql-observe-agent.service.js +10 -15
  15. package/dist/protocols/http-observe-agent.service.d.ts +2 -2
  16. package/dist/protocols/http-observe-agent.service.js +22 -19
  17. package/dist/protocols/job-trace-runner.d.ts +3 -3
  18. package/dist/protocols/job-trace-runner.js +10 -20
  19. package/dist/protocols/rpc-observe-agent.service.js +15 -29
  20. package/dist/protocols/ws-observe-agent.service.js +6 -10
  21. package/dist/services/index.d.ts +1 -0
  22. package/dist/services/index.js +1 -0
  23. package/dist/services/operation-trace.registry.d.ts +25 -3
  24. package/dist/services/operation-trace.registry.js +66 -10
  25. package/dist/services/trace-sampler.service.d.ts +1 -0
  26. package/dist/services/trace-sampler.service.js +10 -4
  27. package/dist/services/tracer.service.d.ts +2 -3
  28. package/dist/services/tracer.service.js +2 -4
  29. package/dist/types/path-value.type.d.ts +2 -2
  30. package/dist/utils/sdk-version.util.d.ts +19 -0
  31. package/dist/utils/sdk-version.util.js +34 -0
  32. package/package.json +6 -5
@@ -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,2 +1,3 @@
1
1
  export * from "./tracer.service.js";
2
2
  export { SPAN_COLLAPSED_TAG } from "./collapse-repeated-spans.util.js";
3
+ export { UNFINISHED_SPANS_TAG } from "./operation-trace.registry.js";
@@ -1,2 +1,3 @@
1
1
  export * from "./tracer.service.js";
2
2
  export { SPAN_COLLAPSED_TAG } from "./collapse-repeated-spans.util.js";
3
+ export { UNFINISHED_SPANS_TAG } from "./operation-trace.registry.js";
@@ -10,6 +10,16 @@ import { LogRedactor } from "../utils/log-redactor.js";
10
10
  import { CALLER_METADATA_KEY } from "../observe.constants.js";
11
11
  import { SpanCollapseSettings } from "./collapse-repeated-spans.util.js";
12
12
  import { SkipSpansPredicate } from "./skip-spans.util.js";
13
+ /**
14
+ * Tag under which a snapshot records how many spans were left out of its tree
15
+ * because they had not ended when it was shipped - the spans still open and
16
+ * everything recorded under them.
17
+ *
18
+ * A tag for the same reason `SPAN_COLLAPSED_TAG` is one: `tags` is already on
19
+ * every snapshot and already declared by the collector's contract, so no
20
+ * collector release has to come first. Absent on a snapshot shipped whole.
21
+ */
22
+ export declare const UNFINISHED_SPANS_TAG = "observe.unfinishedSpans";
13
23
  type TraceId = string;
14
24
  export declare class OperationTraceRegistry {
15
25
  private readonly als;
@@ -196,11 +206,23 @@ export declare class OperationTraceRegistry {
196
206
  hasSnapshotsAwaitingCompletion(): boolean;
197
207
  pluckSnapshot(traceId: string): Promise<RequestSnapshot | JobSnapshot | undefined>;
198
208
  /**
199
- * One line per trace `pluckSnapshot` gives up on, naming the spans that kept
200
- * it open. Their late ends are silent: one un-awaited call usually holds a
209
+ * Takes every span that is still open out of the tree, together with
210
+ * everything recorded under it, and counts what went on the snapshot.
211
+ *
212
+ * An open node cannot be shipped: it has no duration yet, and a parent's
213
+ * self time is its duration minus its children's, so it would skew the
214
+ * numbers of the span that called it. What finished under it goes too, as
215
+ * there is no truthful place left to hang it. After cleanup nothing writes
216
+ * to the shipped tree again - a late end or start finds no snapshot and
217
+ * returns.
218
+ */
219
+ private leaveOutUnfinishedSpans;
220
+ /**
221
+ * One line per trace `pluckSnapshot` ships without its open spans, naming
222
+ * them. Their late ends are silent: one un-awaited call usually holds a
201
223
  * whole chain of spans open, and a line per span said the same thing N times.
202
224
  */
203
- private reportDroppedTrace;
225
+ private reportUnfinishedSpans;
204
226
  /**
205
227
  * Whether `skipSpans` claims a finished operation. Only request snapshots
206
228
  * are asked: a job has no status to be judged by.
@@ -8,6 +8,16 @@ import { LogRedactor } from "../utils/log-redactor.js";
8
8
  import { CALLER_METADATA_KEY } from "../observe.constants.js";
9
9
  import { collapseRepeatedSpans, DEFAULT_SPAN_COLLAPSE, } from "./collapse-repeated-spans.util.js";
10
10
  const SNAPSHOT_COMPLETION_TIMEOUT_MS = 1000;
11
+ /**
12
+ * Tag under which a snapshot records how many spans were left out of its tree
13
+ * because they had not ended when it was shipped - the spans still open and
14
+ * everything recorded under them.
15
+ *
16
+ * A tag for the same reason `SPAN_COLLAPSED_TAG` is one: `tags` is already on
17
+ * every snapshot and already declared by the collector's contract, so no
18
+ * collector release has to come first. Absent on a snapshot shipped whole.
19
+ */
20
+ export const UNFINISHED_SPANS_TAG = "observe.unfinishedSpans";
11
21
  /**
12
22
  * An error the business logic did not model. `IntrinsicException` is what Nest
13
23
  * itself uses to tell a deliberately raised failure from a leaked one.
@@ -18,6 +28,14 @@ const UNHANDLED_ERROR_STATUS_CODE = 500;
18
28
  * count as handled; the exact code only matters when the exception carries one.
19
29
  */
20
30
  const HANDLED_ERROR_STATUS_CODE = 400;
31
+ /** A node and everything below it. */
32
+ function countNodes(node) {
33
+ let count = 1;
34
+ for (const child of node.children ?? []) {
35
+ count += countNodes(child);
36
+ }
37
+ return count;
38
+ }
21
39
  export class OperationTraceRegistry {
22
40
  als;
23
41
  sourceContext;
@@ -370,9 +388,10 @@ export class OperationTraceRegistry {
370
388
  callerId, error) {
371
389
  const snapshot = this.traceSnapshots.get(traceId);
372
390
  if (!snapshot) {
373
- // The trace was dropped while this span was still open - `pluckSnapshot`
374
- // gave up on it (and said so, once for the whole trace), or the client
375
- // aborted. Nothing is left to record it in.
391
+ // The trace was handed off while this span was still open -
392
+ // `pluckSnapshot` shipped it without the span (and said so, once for the
393
+ // whole trace) - or dropped because the client aborted. Nothing is left
394
+ // to record it in.
376
395
  return;
377
396
  }
378
397
  snapshot.refsMarkedAsComplete += 1;
@@ -563,9 +582,12 @@ export class OperationTraceRegistry {
563
582
  this.awaitingCompletion -= 1;
564
583
  }
565
584
  if (snapshot.refsCounter > snapshot.refsMarkedAsComplete) {
566
- this.reportDroppedTrace(traceId, snapshot);
567
- cleanup();
568
- return undefined;
585
+ // Shipped without the spans still open rather than not at all: the
586
+ // operation itself finished, and dropping it lost its status and
587
+ // error along with every span that did end. Read before cleanup,
588
+ // which takes the span map the warning names them from.
589
+ this.reportUnfinishedSpans(traceId, snapshot);
590
+ this.leaveOutUnfinishedSpans(snapshot);
569
591
  }
570
592
  }
571
593
  cleanup();
@@ -601,11 +623,45 @@ export class OperationTraceRegistry {
601
623
  return undefined;
602
624
  }
603
625
  /**
604
- * One line per trace `pluckSnapshot` gives up on, naming the spans that kept
605
- * it open. Their late ends are silent: one un-awaited call usually holds a
626
+ * Takes every span that is still open out of the tree, together with
627
+ * everything recorded under it, and counts what went on the snapshot.
628
+ *
629
+ * An open node cannot be shipped: it has no duration yet, and a parent's
630
+ * self time is its duration minus its children's, so it would skew the
631
+ * numbers of the span that called it. What finished under it goes too, as
632
+ * there is no truthful place left to hang it. After cleanup nothing writes
633
+ * to the shipped tree again - a late end or start finds no snapshot and
634
+ * returns.
635
+ */
636
+ leaveOutUnfinishedSpans(snapshot) {
637
+ let leftOut = 0;
638
+ const keepFinished = (nodes) => nodes.filter((node) => {
639
+ if ("type" in node && node.type === "start") {
640
+ leftOut += countNodes(node);
641
+ return false;
642
+ }
643
+ if (node.children && node.children.length > 0) {
644
+ node.children = keepFinished(node.children);
645
+ if (node.children.length === 0) {
646
+ // Same shape a leaf has when the registry completes it.
647
+ delete node.children;
648
+ }
649
+ }
650
+ return true;
651
+ });
652
+ snapshot.traces = keepFinished(snapshot.traces);
653
+ if (leftOut > 0) {
654
+ // A copy: the object `startTrace` was given is the transport's `tags`
655
+ // option, shared by every operation it reports.
656
+ snapshot.tags = { ...snapshot.tags, [UNFINISHED_SPANS_TAG]: leftOut };
657
+ }
658
+ }
659
+ /**
660
+ * One line per trace `pluckSnapshot` ships without its open spans, naming
661
+ * them. Their late ends are silent: one un-awaited call usually holds a
606
662
  * whole chain of spans open, and a line per span said the same thing N times.
607
663
  */
608
- reportDroppedTrace(traceId, snapshot) {
664
+ reportUnfinishedSpans(traceId, snapshot) {
609
665
  const open = [];
610
666
  for (const node of this.callerIdsByTraceId.get(traceId)?.values() ?? []) {
611
667
  if (node.type === "start") {
@@ -615,7 +671,7 @@ export class OperationTraceRegistry {
615
671
  const operation = ("operationId" in snapshot && snapshot.operationId) ||
616
672
  ("name" in snapshot && snapshot.name) ||
617
673
  traceId;
618
- this.logger.warn(`Trace "${traceId}" (${operation}) was not reported: ${open.join(", ") || "a span"} had not ended ${SNAPSHOT_COMPLETION_TIMEOUT_MS}ms after the operation did. Some of your async operations were not awaited and outlived the operation that started them. Ignore if this is the desired behavior.`);
674
+ this.logger.warn(`Trace "${traceId}" (${operation}) was reported without ${open.join(", ") || "a span"}, which had not ended ${SNAPSHOT_COMPLETION_TIMEOUT_MS}ms after the operation did. Some of your async operations were not awaited and outlived the operation that started them. Ignore if this is the desired behavior.`);
619
675
  }
620
676
  /**
621
677
  * Whether `skipSpans` claims a finished operation. Only request snapshots
@@ -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])
@@ -4,10 +4,9 @@ import { Gauge, GaugeKind, Summary } from "../custom-metrics/index.js";
4
4
  import { Counter } from "../custom-metrics/counter.js";
5
5
  import { ObserveModuleOptionsWithDefaults } from "../interfaces/index.js";
6
6
  import { TraceSpanDelegate } from "../trace-span.delegate.js";
7
- import { KeyOf } from "../types/key-of.type.js";
8
7
  import { Path, PathValue } from "../types/path-value.type.js";
9
8
  import { OperationTraceRegistry } from "./operation-trace.registry.js";
10
- export declare class TracerService<Store extends Record<string | symbol, unknown> = Record<string | symbol, unknown>, TraceKey extends string = "traceId"> {
9
+ export declare class TracerService<Store extends object = Record<string | symbol, unknown>, TraceKey extends string = "traceId"> {
11
10
  private readonly operationTraceRegistry;
12
11
  private readonly als;
13
12
  private readonly observeAgentSharedBuffer;
@@ -17,7 +16,7 @@ export declare class TracerService<Store extends Record<string | symbol, unknown
17
16
  private readonly summaries;
18
17
  private readonly logger;
19
18
  private hasReportedUnusableOperationId;
20
- constructor(operationTraceRegistry: OperationTraceRegistry, als: AsyncLocalStorage<Map<KeyOf<Store> | TraceKey, any>>, observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults);
19
+ constructor(operationTraceRegistry: OperationTraceRegistry, als: AsyncLocalStorage<Map<string | symbol | TraceKey, any>>, observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults);
21
20
  /**
22
21
  * Creates a new trace span with the given name and executes the provided callback within that span.
23
22
  * The callback can be synchronous or asynchronous.
@@ -104,8 +104,7 @@ let TracerService = TracerService_1 = class TracerService {
104
104
  if (!store) {
105
105
  throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "captureError" method within an async context.');
106
106
  }
107
- const traceId = store.get(TRACE_REGISTRY_KEY) ??
108
- store.get(this.options.traceIdKey);
107
+ const traceId = store.get(TRACE_REGISTRY_KEY) ?? store.get(this.options.traceIdKey);
109
108
  if (typeof traceId !== "string") {
110
109
  // Reporting an error must not raise one. The registry warned and gave up
111
110
  // in this case anyway, so the outcome is unchanged.
@@ -274,8 +273,7 @@ let TracerService = TracerService_1 = class TracerService {
274
273
  * methods with no async context at all - and is reported the same way.
275
274
  */
276
275
  requireTraceId(store, method) {
277
- const traceId = store.get(TRACE_REGISTRY_KEY) ??
278
- store.get(this.options.traceIdKey);
276
+ const traceId = store.get(TRACE_REGISTRY_KEY) ?? store.get(this.options.traceIdKey);
279
277
  if (typeof traceId !== "string") {
280
278
  throw new Error(`No trace id found in the current context. Ensure that you are using the "${method}" method within a traced operation.`);
281
279
  }
@@ -5,6 +5,6 @@
5
5
  type IsAny<T> = unknown extends T ? [keyof T] extends [never] ? false : true : false;
6
6
  export type PathImpl<T, Key extends keyof T> = Key extends string ? IsAny<T[Key]> extends true ? never : T[Key] extends Record<string, any> ? `${Key}.${PathImpl<T[Key], Exclude<keyof T[Key], keyof any[]>> & string}` | `${Key}.${Exclude<keyof T[Key], keyof any[]> & string}` : never : never;
7
7
  export type PathImpl2<T> = PathImpl<T, keyof T> | keyof T;
8
- export type Path<T> = keyof T extends string ? PathImpl2<T> extends infer P ? P extends string | keyof T ? P : keyof T : keyof T : never;
9
- export type PathValue<T, P extends Path<T>> = P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path<T[Key]> ? PathValue<T[Key], Rest> : never : never : P extends keyof T ? T[P] : never;
8
+ export type Path<T> = string extends keyof T ? string : keyof T extends string ? PathImpl2<T> extends infer P ? P extends string | keyof T ? P : keyof T : keyof T : never;
9
+ export type PathValue<T, P extends Path<T>> = string extends keyof T ? T[P & keyof T] : P extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? Rest extends Path<T[Key]> ? PathValue<T[Key], Rest> : never : never : P extends keyof T ? T[P] : never;
10
10
  export {};
@@ -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;