@nestjs/observe 0.3.20 → 0.3.21

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.
@@ -3,11 +3,11 @@ export const CALLER_METADATA_KEY = "#caller";
3
3
  /**
4
4
  * Where a store keeps the registry key when it differs from the trace id.
5
5
  *
6
- * A queued job reports under the trace id of the operation that enqueued it,
7
- * and that operation may still be open in this very process - an API that
8
- * also runs its own workers. The registry is keyed per execution, so the job
9
- * gets a key of its own here while `traceIdKey` keeps the id everything
10
- * user-facing reads: logs, `currentTraceId()`, the snapshot.
6
+ * Queued jobs and RPC calls can share the trace id of the operation that
7
+ * dispatched them, including one still open in this process. The registry is
8
+ * keyed per execution, so each gets a key of its own here while `traceIdKey`
9
+ * keeps the id everything user-facing reads: logs, `currentTraceId()`, the
10
+ * snapshot.
11
11
  */
12
12
  export const TRACE_REGISTRY_KEY = "#registryKey";
13
13
  /**
@@ -23,5 +23,16 @@ export declare function setAttributesSafely<TArgs extends unknown[]>(callback: (
23
23
  export declare function shouldIgnoreSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => boolean) | undefined, args: TArgs, receiver: unknown, logger: Logger, transport: string): boolean;
24
24
  /** A bad identity callback must not prevent the trace from being closed. */
25
25
  export declare function getUserIdSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => string | undefined) | undefined, args: TArgs, receiver: unknown, logger: Logger, transport: string): string | undefined;
26
- /** Run deferred completion without ever leaking a rejection from its timer. */
27
- export declare function deferTraceCompletion(completion: () => Promise<void>, logger: Logger, transport: string): void;
26
+ /**
27
+ * Completes a trace once its operation has ended, without ever leaking a
28
+ * rejection from the completion.
29
+ *
30
+ * Right away - in a microtask, once the rest of the listeners of the event
31
+ * that ended the operation have run - when `hasOpenSpans` says every span of
32
+ * the trace has closed, which is the usual case: spans close as the handler's
33
+ * calls return. Otherwise on a timer, so that a span still closing has that
34
+ * moment to end before the trace is plucked. A timer for every operation cost
35
+ * a lightly loaded process a wake-up of its event loop per request, about
36
+ * 35 µs of CPU each on a laptop, and a busy one nothing it would notice.
37
+ */
38
+ export declare function deferTraceCompletion(completion: () => Promise<void>, logger: Logger, transport: string, hasOpenSpans?: () => boolean): void;
@@ -76,9 +76,20 @@ export function getUserIdSafely(callback, args, receiver, logger, transport) {
76
76
  }
77
77
  return invokeUserCallbackSafely(callback, args, receiver, () => undefined, logger, `${transport}.getUserId`, "completing the trace without a user id");
78
78
  }
79
- /** Run deferred completion without ever leaking a rejection from its timer. */
80
- export function deferTraceCompletion(completion, logger, transport) {
81
- setTimeout(() => {
79
+ /**
80
+ * Completes a trace once its operation has ended, without ever leaking a
81
+ * rejection from the completion.
82
+ *
83
+ * Right away - in a microtask, once the rest of the listeners of the event
84
+ * that ended the operation have run - when `hasOpenSpans` says every span of
85
+ * the trace has closed, which is the usual case: spans close as the handler's
86
+ * calls return. Otherwise on a timer, so that a span still closing has that
87
+ * moment to end before the trace is plucked. A timer for every operation cost
88
+ * a lightly loaded process a wake-up of its event loop per request, about
89
+ * 35 µs of CPU each on a laptop, and a busy one nothing it would notice.
90
+ */
91
+ export function deferTraceCompletion(completion, logger, transport, hasOpenSpans) {
92
+ const complete = () => {
82
93
  void Promise.resolve()
83
94
  .then(completion)
84
95
  .catch((error) => {
@@ -87,5 +98,17 @@ export function deferTraceCompletion(completion, logger, transport) {
87
98
  warnSafely(logger, `Deferred ${transport} trace completion failed; later failures are not reported: ${describeFailure(error)}`);
88
99
  }
89
100
  });
90
- }, 0);
101
+ };
102
+ if (!hasOpenSpans) {
103
+ setTimeout(complete, 0);
104
+ return;
105
+ }
106
+ queueMicrotask(() => {
107
+ if (hasOpenSpans()) {
108
+ setTimeout(complete, 0);
109
+ }
110
+ else {
111
+ complete();
112
+ }
113
+ });
91
114
  }
@@ -338,7 +338,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
338
338
  return;
339
339
  }
340
340
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
341
- }, this.logger, "graphql");
341
+ }, this.logger, "graphql", () => this.operationTraceRegistry.hasOpenSpans(traceId));
342
342
  }
343
343
  /**
344
344
  * Picks the error a failed operation is recorded with.
@@ -71,12 +71,11 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
71
71
  if (!store) {
72
72
  return;
73
73
  }
74
- const traceId = store.get(TRACE_REGISTRY_KEY) ??
75
- store.get(this.options.traceIdKey);
76
- if (!traceId) {
74
+ const registryKey = store.get(TRACE_REGISTRY_KEY);
75
+ if (typeof registryKey !== "string") {
77
76
  return;
78
77
  }
79
- this.operationTraceRegistry.addRouteMetadataToTrace(traceId, requestMethod, path);
78
+ this.operationTraceRegistry.addRouteMetadataToTrace(registryKey, requestMethod, path);
80
79
  });
81
80
  }
82
81
  onModuleInit() {
@@ -109,23 +108,23 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
109
108
  this.asyncLocalStorage.run(store, () => {
110
109
  const traceId = generateTraceIdSafely(this.options.traceIdGenerator, req, this.options, this.logger);
111
110
  store.set(this.options.traceIdKey, traceId);
111
+ // An adopted `x-request-id` is not unique to this request: a caller that
112
+ // fans out, or retries, sends the same id twice. Claim this execution
113
+ // before option callbacks can reach another request's trace. A request
114
+ // that is not recorded keeps the key too, never registered, so its
115
+ // lookups stay off a recorded request sharing its id.
116
+ const registryKey = uuidv7();
117
+ store.set(TRACE_REGISTRY_KEY, registryKey);
112
118
  setAttributesSafely(this.options.http?.setAttributes, [req], this.options.http, store, this.logger, "http");
113
- // A request that is not recorded still carries its trace id, which an
114
- // adopted `x-request-id` can share with a recorded request. A registry
115
- // key of its own, never registered, keeps its lookups off that trace.
116
- const skip = () => {
117
- store.set(TRACE_REGISTRY_KEY, uuidv7());
118
- done();
119
- };
120
119
  if (this.shouldIgnoreRequest(req) || this.isUntracedPreflight(req)) {
121
- return skip();
120
+ return done();
122
121
  }
123
122
  const shouldCapture = this.traceSamplerService.shouldCapture("http", {
124
123
  url: req.url,
125
124
  method: req.method,
126
125
  });
127
126
  if (!shouldCapture) {
128
- return skip();
127
+ return done();
129
128
  }
130
129
  // Sensitive query parameters are masked whether or not the deployment
131
130
  // configured anything: an opt-in redactor protects only those who
@@ -137,15 +136,6 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
137
136
  const originalUrl = this.queryParamsObfuscateRegex
138
137
  ? redactedUrl.replaceAll(this.queryParamsObfuscateRegex, "[REDACTED]")
139
138
  : redactedUrl;
140
- // An adopted `x-request-id` is not unique to this request: a caller
141
- // that fans out, or retries, sends the same id twice, and both requests
142
- // can be open here at once. The second gets a registry key of its own -
143
- // only the second, so the ordinary request is still keyed by its id.
144
- let registryKey = traceId;
145
- if (this.operationTraceRegistry.hasTrace(traceId)) {
146
- registryKey = uuidv7();
147
- store.set(TRACE_REGISTRY_KEY, registryKey);
148
- }
149
139
  this.operationTraceRegistry.startTrace(registryKey, {
150
140
  protocol: req.protocol,
151
141
  tags: this.options.http?.tags,
@@ -163,18 +153,20 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
163
153
  if (!store) {
164
154
  return;
165
155
  }
166
- const traceId = store.get(TRACE_REGISTRY_KEY) ??
167
- store.get(this.options.traceIdKey);
168
- if (!traceId) {
156
+ // Only this execution's own key: a stale store left by a finished request
157
+ // must not complete a later one that reuses its id.
158
+ const registryKey = store.get(TRACE_REGISTRY_KEY);
159
+ if (typeof registryKey !== "string" ||
160
+ !this.operationTraceRegistry.hasTrace(registryKey)) {
169
161
  return;
170
162
  }
171
163
  deferTraceCompletion(async () => {
172
164
  const userId = getUserIdSafely(this.options.http?.getUserId, [req], this.options.http, this.logger, "http");
173
- this.operationTraceRegistry.endTrace(traceId, {
165
+ this.operationTraceRegistry.endTrace(registryKey, {
174
166
  statusCode: res.statusCode,
175
167
  userId,
176
168
  });
177
- const snapshot = await this.operationTraceRegistry.pluckSnapshot(traceId);
169
+ const snapshot = await this.operationTraceRegistry.pluckSnapshot(registryKey);
178
170
  if (!snapshot) {
179
171
  return;
180
172
  }
@@ -185,7 +177,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
185
177
  }
186
178
  }
187
179
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
188
- }, this.logger, "http");
180
+ }, this.logger, "http", () => this.operationTraceRegistry.hasOpenSpans(registryKey));
189
181
  }
190
182
  /**
191
183
  * Frees the trace when the client goes away before the response finishes.
@@ -215,7 +215,7 @@ export class JobTraceRunner {
215
215
  const snapshot = (await this.operationTraceRegistry.pluckSnapshot(registryKey));
216
216
  // `pluckSnapshot` deletes what it returns, so a trace already
217
217
  // plucked answers undefined, and the encoder would dereference it
218
- // inside a `setTimeout`, where no try/catch can reach: an
218
+ // in this deferred completion, where no try/catch can reach: an
219
219
  // unhandled TypeError that took the whole process down.
220
220
  //
221
221
  // Dropped rather than reported: there is no snapshot, so there is
@@ -225,7 +225,7 @@ export class JobTraceRunner {
225
225
  return;
226
226
  }
227
227
  this.observeAgentSharedBuffer.insertJobSnapshot(snapshot);
228
- }, this.logger, "job");
228
+ }, this.logger, "job", () => this.operationTraceRegistry.hasOpenSpans(registryKey));
229
229
  };
230
230
  try {
231
231
  const returnValue = invoke(settle);
@@ -17,7 +17,8 @@ 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
- import { OBSERVE_OPTIONS } from "../observe.constants.js";
20
+ import { OBSERVE_OPTIONS, TRACE_REGISTRY_KEY } from "../observe.constants.js";
21
+ import { uuidv7 } from "../utils/uuid-v7.util.js";
21
22
  import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
22
23
  import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
23
24
  let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentService {
@@ -113,6 +114,10 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
113
114
  return this.asyncLocalStorage.run(store, () => {
114
115
  const traceId = generateTraceIdSafely(this.options.traceIdGenerator, ctx, this.options, this.logger);
115
116
  store.set(this.options.traceIdKey, traceId);
117
+ // Fan-out calls and retries can share a correlation id. Claim this
118
+ // execution before option callbacks can reach another operation's trace.
119
+ const registryKey = uuidv7();
120
+ store.set(TRACE_REGISTRY_KEY, registryKey);
116
121
  setAttributesSafely(this.options.rpc?.setAttributes, [transportId, ctx], this.options.rpc, store, this.logger, "rpc");
117
122
  if (shouldIgnoreSafely(this.options.rpc?.ignore, [transportId, ctx], this.options.rpc, this.logger, "rpc")) {
118
123
  return done();
@@ -124,11 +129,11 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
124
129
  if (!shouldCapture) {
125
130
  return done();
126
131
  }
127
- this.operationTraceRegistry.startTrace(traceId, {
132
+ this.operationTraceRegistry.startTrace(registryKey, {
128
133
  protocol: this.toProtocolName(transportId),
129
134
  operationId: this.getOperationIdFromContext(ctx),
130
135
  tags: this.options.rpc?.tags,
131
- });
136
+ }, traceId);
132
137
  return done();
133
138
  });
134
139
  }
@@ -138,6 +143,9 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
138
143
  return this.asyncLocalStorage.run(store, () => {
139
144
  const traceId = generateTraceIdSafely(this.options.traceIdGenerator, call, this.options, this.logger);
140
145
  store.set(this.options.traceIdKey, traceId);
146
+ // The key must precede callbacks here too, before the deferred startup.
147
+ const registryKey = uuidv7();
148
+ store.set(TRACE_REGISTRY_KEY, registryKey);
141
149
  setAttributesSafely(this.options.grpc?.setAttributes, [call], this.options.grpc, store, this.logger, "grpc");
142
150
  return new Promise((resolve) => {
143
151
  // A throw in this timer escapes the promise: `done()` never runs, and
@@ -152,11 +160,11 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
152
160
  if (!shouldCapture) {
153
161
  return resolve(done());
154
162
  }
155
- this.operationTraceRegistry.startTrace(traceId, {
163
+ this.operationTraceRegistry.startTrace(registryKey, {
156
164
  protocol: this.toProtocolName(transportId),
157
165
  operationId: call.operationId,
158
166
  tags: this.options.grpc?.tags,
159
- });
167
+ }, traceId);
160
168
  resolve(done());
161
169
  }, 0);
162
170
  });
@@ -167,8 +175,9 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
167
175
  if (!store) {
168
176
  return;
169
177
  }
170
- const traceId = store.get(this.options.traceIdKey);
171
- if (!traceId) {
178
+ const registryKey = store.get(TRACE_REGISTRY_KEY);
179
+ if (typeof registryKey !== "string" ||
180
+ !this.operationTraceRegistry.hasTrace(registryKey)) {
172
181
  return;
173
182
  }
174
183
  const isGrpc = transportId === this.microservices.Transport.GRPC;
@@ -180,15 +189,15 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
180
189
  else {
181
190
  userId = getUserIdSafely(this.options.rpc?.getUserId, [transportId, ctx], this.options.rpc, this.logger, "rpc");
182
191
  }
183
- this.operationTraceRegistry.endTrace(traceId, {
192
+ this.operationTraceRegistry.endTrace(registryKey, {
184
193
  userId,
185
194
  });
186
- const snapshot = await this.operationTraceRegistry.pluckSnapshot(traceId);
195
+ const snapshot = await this.operationTraceRegistry.pluckSnapshot(registryKey);
187
196
  if (!snapshot) {
188
197
  return;
189
198
  }
190
199
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
191
- }, this.logger, isGrpc ? "grpc" : "rpc");
200
+ }, this.logger, isGrpc ? "grpc" : "rpc", () => this.operationTraceRegistry.hasOpenSpans(registryKey));
192
201
  }
193
202
  getOperationIdFromContext(ctx) {
194
203
  const { KafkaContext, MqttContext, NatsContext, RedisContext, RmqContext, TcpContext, } = this.microservices;
@@ -144,7 +144,7 @@ let WsObserveAgentService = WsObserveAgentService_1 = class WsObserveAgentServic
144
144
  return;
145
145
  }
146
146
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
147
- }, this.logger, "ws");
147
+ }, this.logger, "ws", () => this.operationTraceRegistry.hasOpenSpans(traceId));
148
148
  };
149
149
  // Nest's ws proxy hands a thrown error to the exception filter and
150
150
  // resolves, so there is no rejection to read a failure from here - the
@@ -84,14 +84,9 @@ export function collapseRepeatedSpans(siblings, settings) {
84
84
  const collapsed = collapseSiblings(siblings, settings);
85
85
  for (const node of collapsed) {
86
86
  if (Array.isArray(node.children) && node.children.length > 0) {
87
- const children = collapseRepeatedSpans(node.children, settings);
88
- if (children.length > 0) {
89
- node.children = children;
90
- }
91
- else {
92
- // Same shape a leaf has when the registry completes it.
93
- delete node.children;
94
- }
87
+ // Never empty: collapsing replaces repeated siblings, keeping at least
88
+ // one node for each group, so no child list loses all its members.
89
+ node.children = collapseRepeatedSpans(node.children, settings);
95
90
  }
96
91
  }
97
92
  return collapsed;
@@ -100,44 +95,51 @@ function collapseSiblings(siblings, settings) {
100
95
  if (siblings.length <= settings.threshold) {
101
96
  return siblings;
102
97
  }
103
- const groups = new Map();
98
+ // By class, then by method. Both names are strings the instrumentation made
99
+ // once and V8 has already hashed; a key joining them was a new string to
100
+ // build and hash for every sibling, which made it the costliest line here.
101
+ const groupsByClass = new Map();
104
102
  for (const node of siblings) {
105
103
  if (!isCollapsible(node)) {
106
104
  continue;
107
105
  }
108
- // A separator no identifier contains, so `A.b` + `c` and `A` + `b.c`
109
- // cannot share a key.
110
- const key = `${node.className}\0${node.methodKey}`;
111
- const group = groups.get(key);
106
+ let groupsByMethod = groupsByClass.get(node.className);
107
+ if (!groupsByMethod) {
108
+ groupsByMethod = new Map();
109
+ groupsByClass.set(node.className, groupsByMethod);
110
+ }
111
+ const group = groupsByMethod.get(node.methodKey);
112
112
  if (group) {
113
113
  group.push(node);
114
114
  }
115
115
  else {
116
- groups.set(key, [node]);
116
+ groupsByMethod.set(node.methodKey, [node]);
117
117
  }
118
118
  }
119
119
  // Which node each collapsed call is replaced by: the earliest call maps to
120
120
  // the collapsed node, the others to nothing.
121
121
  const replacements = new Map();
122
122
  const removed = new Set();
123
- for (const group of groups.values()) {
124
- if (group.length <= settings.threshold) {
125
- continue;
126
- }
127
- const candidates = group
128
- .filter((node) => !node.error)
129
- .sort((a, b) => b.duration - a.duration);
130
- const surplus = candidates.slice(settings.keepSlowest);
131
- // A node standing for a single call would be a relabelled span, not an
132
- // aggregate.
133
- if (surplus.length < 2) {
134
- continue;
135
- }
136
- const earliest = surplus.reduce((first, node) => compareStart(node, first, siblings) < 0 ? node : first);
137
- replacements.set(earliest, toCollapsedNode(surplus, earliest));
138
- for (const node of surplus) {
139
- if (node !== earliest) {
140
- removed.add(node);
123
+ for (const groupsByMethod of groupsByClass.values()) {
124
+ for (const group of groupsByMethod.values()) {
125
+ if (group.length <= settings.threshold) {
126
+ continue;
127
+ }
128
+ const candidates = group
129
+ .filter((node) => !node.error)
130
+ .sort((a, b) => b.duration - a.duration);
131
+ const surplus = candidates.slice(settings.keepSlowest);
132
+ // A node standing for a single call would be a relabelled span, not an
133
+ // aggregate.
134
+ if (surplus.length < 2) {
135
+ continue;
136
+ }
137
+ const earliest = surplus.reduce((first, node) => compareStart(node, first, siblings) < 0 ? node : first);
138
+ replacements.set(earliest, toCollapsedNode(surplus, earliest));
139
+ for (const node of surplus) {
140
+ if (node !== earliest) {
141
+ removed.add(node);
142
+ }
141
143
  }
142
144
  }
143
145
  }
@@ -187,7 +189,6 @@ function toCollapsedNode(surplus, earliest) {
187
189
  name: `${earliest.className}.${earliest.methodKey} ×${surplus.length}`,
188
190
  tags: { [SPAN_COLLAPSED_TAG]: surplus.length },
189
191
  duration,
190
- children,
191
192
  };
192
193
  if (startOffset !== undefined) {
193
194
  collapsed.startOffset = startOffset;
@@ -198,14 +199,17 @@ function toCollapsedNode(surplus, earliest) {
198
199
  // they would for any span that was not shipped.
199
200
  collapsed.spanId = earliest.spanId;
200
201
  }
201
- if (children.length === 0) {
202
- delete collapsed.children;
202
+ // Added when there are any rather than deleted when there are none: a
203
+ // deleted property sends the node into V8's slow dictionary mode.
204
+ if (children.length > 0) {
205
+ collapsed.children = children;
203
206
  }
204
207
  return collapsed;
205
208
  }
206
209
  /**
207
- * Only completed auto spans collapse. `type` is what marks a node as still
208
- * ongoing; the registry deletes it on completion.
210
+ * Only completed auto spans collapse. A node still carrying `type` is one that
211
+ * was not shipped as complete: the registry rebuilds the trees it ships
212
+ * without it.
209
213
  */
210
214
  function isCollapsible(node) {
211
215
  return (!("type" in node) &&
@@ -97,6 +97,12 @@ export declare class OperationTraceRegistry {
97
97
  * this process may already hold.
98
98
  */
99
99
  hasTrace(traceId: TraceId): boolean;
100
+ /**
101
+ * Whether a span of the trace has started and not yet ended - what tells a
102
+ * transport whether completing the trace can happen now or should give
103
+ * that span a moment to close. False for a trace that is not open at all.
104
+ */
105
+ hasOpenSpans(traceId: TraceId): boolean;
100
106
  startTrace(traceId: TraceId, data: Omit<RequestSnapshot, "traces" | "startTimestamp" | "calledAt" | "traceId"> | Omit<JobSnapshot, "duration">,
101
107
  /**
102
108
  * The trace id the snapshot reports under, when it is not the registry
@@ -134,15 +140,15 @@ export declare class OperationTraceRegistry {
134
140
  * Nests a freshly opened node under its caller when that caller is still
135
141
  * live, and at the trace root otherwise.
136
142
  *
137
- * A caller that has already completed has had its scratch fields stripped
138
- * (`type`, and `children` when it had none), so there is nothing left to
139
- * nest under. That happens whenever a callee outlives its caller - most
140
- * commonly a handler that Nest bound (`AsyncResource.bind` in its
141
- * interceptors consumer) to the async context of an interceptor whose
142
- * `intercept()` returned synchronously. Fall back to the root rather than
143
- * throw into the request: the mirror case, a step ending after its caller
144
- * did, is already tolerated in `internalEndTraceStep`. Auto and manual spans
145
- * both attach through here, so they share the tolerance.
143
+ * A caller that has already completed - its `type` is `"end"` - takes no
144
+ * more children: its span is closed. That happens whenever a callee
145
+ * outlives its caller - most commonly a handler that Nest bound
146
+ * (`AsyncResource.bind` in its interceptors consumer) to the async context
147
+ * of an interceptor whose `intercept()` returned synchronously. Fall back
148
+ * to the root rather than throw into the request: the mirror case, a step
149
+ * ending after its caller did, is already tolerated in
150
+ * `internalEndTraceStep`. Auto and manual spans both attach through here, so
151
+ * they share the tolerance.
146
152
  */
147
153
  private attachToCaller;
148
154
  internalEndTraceStep(traceId: TraceId,
@@ -36,6 +36,55 @@ function countNodes(node) {
36
36
  }
37
37
  return count;
38
38
  }
39
+ /** Whether an object has an own enumerable key, as `Object.keys` counts them. */
40
+ function hasOwnKeys(value) {
41
+ for (const key in value) {
42
+ if (Object.hasOwn(value, key)) {
43
+ return true;
44
+ }
45
+ }
46
+ return false;
47
+ }
48
+ /**
49
+ * A span as it is shipped: a new node holding what the encoder reads, and
50
+ * none of the registry's bookkeeping - `type`, `startTime`, `parent` - nor a
51
+ * `tags` or `children` with nothing in them.
52
+ *
53
+ * Built afresh instead of deleting those from the live node, which sent every
54
+ * span into V8's slow dictionary mode. Fields are added in one order, so the
55
+ * shipped nodes share a handful of shapes and stay fast for what reads them
56
+ * next: collapsing, encoding. A node that never ended, which only a trace
57
+ * whose starts and ends were miscounted can still hold here, goes without a
58
+ * duration, as it always did - and without the `parent` that made such a tree
59
+ * impossible to serialise.
60
+ */
61
+ function toShippedNode(node) {
62
+ const shipped = {
63
+ origin: node.origin,
64
+ className: node.className,
65
+ methodKey: node.methodKey,
66
+ startOffset: node.startOffset,
67
+ };
68
+ if (node.name !== undefined) {
69
+ shipped.name = node.name;
70
+ }
71
+ if (node.children && node.children.length > 0) {
72
+ shipped.children = node.children.map(toShippedNode);
73
+ }
74
+ if (node.spanId !== undefined) {
75
+ shipped.spanId = node.spanId;
76
+ }
77
+ if (node.tags && hasOwnKeys(node.tags)) {
78
+ shipped.tags = node.tags;
79
+ }
80
+ if ("duration" in node) {
81
+ shipped.duration = node.duration;
82
+ }
83
+ if (node.error !== undefined) {
84
+ shipped.error = node.error;
85
+ }
86
+ return shipped;
87
+ }
39
88
  export class OperationTraceRegistry {
40
89
  als;
41
90
  sourceContext;
@@ -165,6 +214,16 @@ export class OperationTraceRegistry {
165
214
  hasTrace(traceId) {
166
215
  return this.traceSnapshots.has(traceId);
167
216
  }
217
+ /**
218
+ * Whether a span of the trace has started and not yet ended - what tells a
219
+ * transport whether completing the trace can happen now or should give
220
+ * that span a moment to close. False for a trace that is not open at all.
221
+ */
222
+ hasOpenSpans(traceId) {
223
+ const snapshot = this.traceSnapshots.get(traceId);
224
+ return (snapshot !== undefined &&
225
+ snapshot.refsCounter > snapshot.refsMarkedAsComplete);
226
+ }
168
227
  startTrace(traceId, data,
169
228
  /**
170
229
  * The trace id the snapshot reports under, when it is not the registry
@@ -354,15 +413,15 @@ export class OperationTraceRegistry {
354
413
  * Nests a freshly opened node under its caller when that caller is still
355
414
  * live, and at the trace root otherwise.
356
415
  *
357
- * A caller that has already completed has had its scratch fields stripped
358
- * (`type`, and `children` when it had none), so there is nothing left to
359
- * nest under. That happens whenever a callee outlives its caller - most
360
- * commonly a handler that Nest bound (`AsyncResource.bind` in its
361
- * interceptors consumer) to the async context of an interceptor whose
362
- * `intercept()` returned synchronously. Fall back to the root rather than
363
- * throw into the request: the mirror case, a step ending after its caller
364
- * did, is already tolerated in `internalEndTraceStep`. Auto and manual spans
365
- * both attach through here, so they share the tolerance.
416
+ * A caller that has already completed - its `type` is `"end"` - takes no
417
+ * more children: its span is closed. That happens whenever a callee
418
+ * outlives its caller - most commonly a handler that Nest bound
419
+ * (`AsyncResource.bind` in its interceptors consumer) to the async context
420
+ * of an interceptor whose `intercept()` returned synchronously. Fall back
421
+ * to the root rather than throw into the request: the mirror case, a step
422
+ * ending after its caller did, is already tolerated in
423
+ * `internalEndTraceStep`. Auto and manual spans both attach through here, so
424
+ * they share the tolerance.
366
425
  */
367
426
  attachToCaller(snapshot, refsByCaller, callerId, newNode) {
368
427
  const caller = callerId ? refsByCaller?.get(callerId) : undefined;
@@ -407,23 +466,15 @@ export class OperationTraceRegistry {
407
466
  return;
408
467
  }
409
468
  const duration = performance.now() - cursor.startTime;
410
- // `type`, `startTime` and `parent` are exactly what separates an ongoing
411
- // node from a complete one, so removing them *is* the conversion the cast
412
- // below records. They go through a view that admits their absence rather
413
- // than each needing its own suppression.
414
- const completing = cursor;
415
- delete completing.type; // The node is now complete
416
- delete completing.startTime; // The duration is now set
417
469
  const parent = cursor.parent;
418
- delete completing.parent; // Complete nodes carry no parent reference
419
- // Remove tags if empty
420
- if (Object.keys(cursor.tags || {}).length === 0) {
421
- delete completing.tags;
422
- }
423
- // Clean up children array if it is empty
424
- if (cursor.children.length === 0) {
425
- delete completing.children;
426
- }
470
+ // The node has ended. It keeps its fields rather than having `type`,
471
+ // `startTime` and an empty `tags` or `children` deleted: a deleted
472
+ // property sends a V8 object into slow dictionary mode, and every span
473
+ // ended there, slowing everything that read the tree afterwards. `type`
474
+ // tells the live tree the node has ended; `toShippedNode` leaves the rest
475
+ // out when the trace is plucked. Complete nodes carry no parent reference.
476
+ cursor.type = "end";
477
+ cursor.parent = undefined;
427
478
  const activeTrace = cursor;
428
479
  activeTrace.duration = duration;
429
480
  if (error && !activeTrace.error) {
@@ -611,6 +662,9 @@ export class OperationTraceRegistry {
611
662
  snapshot.traces = [];
612
663
  return snapshot;
613
664
  }
665
+ // Every span has closed, and nothing writes to the tree any more: it is
666
+ // rebuilt once, as it will be shipped.
667
+ snapshot.traces = snapshot.traces.map(toShippedNode);
614
668
  // Last, on the finished tree: every span has closed by now, so a group
615
669
  // is judged on its complete membership and durations, and nothing that
616
670
  // reads the tree afterwards - the encoder, the buffer - sees the