@nestjs/observe 0.3.19 → 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.
Files changed (33) hide show
  1. package/LICENSE +105 -22
  2. package/NOTICE +31 -0
  3. package/README.md +97 -8
  4. package/dist/agent/observe-agent.worker.js +8 -7
  5. package/dist/instrument/create-instance-decorator.instrument.js +134 -88
  6. package/dist/interfaces/observe-options.interface.d.ts +18 -2
  7. package/dist/interfaces/trace-events.interfaces.d.ts +11 -5
  8. package/dist/observe.constants.d.ts +5 -5
  9. package/dist/observe.constants.js +5 -5
  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 +13 -2
  23. package/dist/protocols/deferred-trace-completion.js +27 -4
  24. package/dist/protocols/graphql-observe-agent.service.js +1 -1
  25. package/dist/protocols/http-observe-agent.service.js +20 -28
  26. package/dist/protocols/job-trace-runner.js +2 -2
  27. package/dist/protocols/rpc-observe-agent.service.js +19 -10
  28. package/dist/protocols/ws-observe-agent.service.js +1 -1
  29. package/dist/services/collapse-repeated-spans.util.js +41 -37
  30. package/dist/services/operation-trace.registry.d.ts +15 -9
  31. package/dist/services/operation-trace.registry.js +79 -25
  32. package/dist/utils/uuid-v7.util.js +53 -15
  33. package/package.json +5 -3
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Reading token usage out of a model provider's response - a JSON body, or
3
+ * the events of a server-sent stream - without ever keeping its text.
4
+ */
5
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6
+ const count = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0
7
+ ? Math.round(value)
8
+ : undefined;
9
+ const sum = (...values) => values.some((value) => value !== undefined)
10
+ ? values.reduce((total, value) => total + (value ?? 0), 0)
11
+ : undefined;
12
+ /**
13
+ * One usage object, in whichever provider's spelling, as input, output and
14
+ * cached input.
15
+ *
16
+ * Input means every input token. OpenAI already counts cached tokens inside
17
+ * `prompt_tokens`; Anthropic reports cache reads and writes beside
18
+ * `input_tokens`, so they are added in - otherwise its cached calls would
19
+ * look nearly free of input.
20
+ */
21
+ export function normalizeUsage(usage) {
22
+ if (!isObject(usage)) {
23
+ return {};
24
+ }
25
+ // Cohere v2 nests its counts.
26
+ const billed = isObject(usage.billed_units) ? usage.billed_units : undefined;
27
+ const anthropicCacheRead = count(usage.cache_read_input_tokens);
28
+ const anthropicCacheWrite = count(usage.cache_creation_input_tokens);
29
+ const openAiInput = count(usage.prompt_tokens);
30
+ const input = openAiInput ??
31
+ count(usage.promptTokenCount) ??
32
+ count(usage.inputTokens) ??
33
+ (count(usage.input_tokens) !== undefined ||
34
+ anthropicCacheRead !== undefined ||
35
+ anthropicCacheWrite !== undefined
36
+ ? sum(count(usage.input_tokens), anthropicCacheRead, anthropicCacheWrite)
37
+ : count(billed?.input_tokens));
38
+ const output = count(usage.completion_tokens) ??
39
+ count(usage.output_tokens) ??
40
+ count(usage.outputTokens) ??
41
+ sum(count(usage.candidatesTokenCount), count(usage.thoughtsTokenCount)) ??
42
+ count(billed?.output_tokens);
43
+ const details = (isObject(usage.prompt_tokens_details) && usage.prompt_tokens_details) ||
44
+ (isObject(usage.input_tokens_details) && usage.input_tokens_details) ||
45
+ undefined;
46
+ const cached = count(details?.cached_tokens) ??
47
+ anthropicCacheRead ??
48
+ count(usage.cachedContentTokenCount) ??
49
+ count(usage.prompt_cache_hit_tokens) ??
50
+ count(usage.cacheReadInputTokens);
51
+ return {
52
+ ...(input !== undefined ? { inputTokens: input } : {}),
53
+ ...(output !== undefined ? { outputTokens: output } : {}),
54
+ ...(cached !== undefined ? { cachedInputTokens: cached } : {}),
55
+ };
56
+ }
57
+ /** Later readings win, field by field - a stream reports in pieces. */
58
+ export function mergeUsage(into, next) {
59
+ return {
60
+ model: next.model ?? into.model,
61
+ inputTokens: next.inputTokens ?? into.inputTokens,
62
+ outputTokens: next.outputTokens ?? into.outputTokens,
63
+ cachedInputTokens: next.cachedInputTokens ?? into.cachedInputTokens,
64
+ };
65
+ }
66
+ const modelOf = (value) => typeof value.model === "string"
67
+ ? value.model.slice(0, 128)
68
+ : typeof value.modelVersion === "string"
69
+ ? value.modelVersion.slice(0, 128)
70
+ : undefined;
71
+ /**
72
+ * The usage in one parsed JSON document: a whole response body, or one event
73
+ * of a stream.
74
+ */
75
+ export function usageFromDocument(document) {
76
+ if (!isObject(document)) {
77
+ return {};
78
+ }
79
+ // OpenAI's Responses API streams `response.*` events around a nested
80
+ // response object; Anthropic opens its stream with `message_start` around
81
+ // a nested message.
82
+ const nested = isObject(document.response)
83
+ ? document.response
84
+ : isObject(document.message)
85
+ ? document.message
86
+ : undefined;
87
+ const source = nested ?? document;
88
+ const usage = normalizeUsage(source.usage ??
89
+ source.usageMetadata ??
90
+ document.usage ??
91
+ document.usageMetadata ??
92
+ (isObject(document.meta) ? document.meta.billed_units : undefined));
93
+ const model = modelOf(source) ?? modelOf(document);
94
+ return { ...usage, ...(model ? { model } : {}) };
95
+ }
96
+ /** Largest JSON body parsed whole. Past it only the head and tail are read. */
97
+ const MAX_JSON_BYTES = 2 * 1024 * 1024;
98
+ /** What is kept of an oversized body: usage sits at its end, model at its start. */
99
+ const EDGE_BYTES = 32 * 1024;
100
+ /**
101
+ * Reads a JSON response as it passes through, keeping at most 2 MB.
102
+ *
103
+ * A larger body - a long completion, a batch of embeddings - is not kept: its
104
+ * first and last 32 KB are, and the usage is matched out of those. Every
105
+ * provider writes `usage` after the content and `model` before it.
106
+ */
107
+ export class JsonUsageReader {
108
+ chunks = [];
109
+ size = 0;
110
+ head;
111
+ tail;
112
+ push(chunk) {
113
+ if (this.head) {
114
+ this.tail = keepTail(this.tail, chunk, EDGE_BYTES);
115
+ return;
116
+ }
117
+ this.chunks.push(chunk);
118
+ this.size += chunk.byteLength;
119
+ if (this.size > MAX_JSON_BYTES) {
120
+ const whole = concat(this.chunks, this.size);
121
+ this.head = whole.subarray(0, EDGE_BYTES);
122
+ this.tail = whole.subarray(whole.byteLength - EDGE_BYTES);
123
+ this.chunks.length = 0;
124
+ }
125
+ }
126
+ finish() {
127
+ const decoder = new TextDecoder();
128
+ if (!this.head) {
129
+ try {
130
+ return usageFromDocument(JSON.parse(decoder.decode(concat(this.chunks, this.size))));
131
+ }
132
+ catch {
133
+ return {};
134
+ }
135
+ }
136
+ return usageFromEdges(decoder.decode(this.head), decoder.decode(this.tail ?? new Uint8Array()));
137
+ }
138
+ }
139
+ /** Usage matched out of the two ends of a body too large to parse. */
140
+ function usageFromEdges(head, tail) {
141
+ const number = (name) => {
142
+ const match = new RegExp(`"${name}"\\s*:\\s*(\\d+)`).exec(tail);
143
+ return match ? { [name]: Number(match[1]) } : {};
144
+ };
145
+ const usage = normalizeUsage({
146
+ ...number("prompt_tokens"),
147
+ ...number("completion_tokens"),
148
+ ...number("input_tokens"),
149
+ ...number("output_tokens"),
150
+ ...number("cached_tokens"),
151
+ ...number("cache_read_input_tokens"),
152
+ ...number("cache_creation_input_tokens"),
153
+ ...number("promptTokenCount"),
154
+ ...number("candidatesTokenCount"),
155
+ });
156
+ const cached = /"cached_tokens"\s*:\s*(\d+)/.exec(tail);
157
+ if (cached && usage.cachedInputTokens === undefined) {
158
+ usage.cachedInputTokens = Number(cached[1]);
159
+ }
160
+ const model = /"model"\s*:\s*"([^"\\]{1,128})"/.exec(head)?.[1];
161
+ return { ...usage, ...(model ? { model } : {}) };
162
+ }
163
+ /** Longest stream line examined. Longer lines carry content, not usage. */
164
+ const MAX_SSE_LINE = 1024 * 1024;
165
+ /**
166
+ * Reads a server-sent event stream as it passes through, one line at a time.
167
+ *
168
+ * Only `data:` lines that can carry usage or a model are parsed - the first
169
+ * event, and any that mention `usage` - so a long stream of text deltas costs
170
+ * a substring search per line rather than a parse.
171
+ */
172
+ export class SseUsageReader {
173
+ now;
174
+ decoder = new TextDecoder();
175
+ pending = "";
176
+ skipping = false;
177
+ usage = {};
178
+ sawEvent = false;
179
+ /** When the first content event arrived, for time to first token. */
180
+ firstEventAt;
181
+ constructor(now = () => performance.now()) {
182
+ this.now = now;
183
+ }
184
+ push(chunk) {
185
+ const text = this.decoder.decode(chunk, { stream: true });
186
+ let start = 0;
187
+ for (;;) {
188
+ const newline = text.indexOf("\n", start);
189
+ if (newline === -1) {
190
+ break;
191
+ }
192
+ if (this.skipping) {
193
+ // The oversized line ends here, unread.
194
+ this.skipping = false;
195
+ }
196
+ else {
197
+ this.line(this.pending + text.slice(start, newline));
198
+ }
199
+ this.pending = "";
200
+ start = newline + 1;
201
+ }
202
+ if (this.skipping) {
203
+ return;
204
+ }
205
+ const rest = text.slice(start);
206
+ if (this.pending.length + rest.length > MAX_SSE_LINE) {
207
+ // An oversized line is content; drop it until its end comes past.
208
+ this.pending = "";
209
+ this.skipping = true;
210
+ return;
211
+ }
212
+ this.pending += rest;
213
+ }
214
+ finish() {
215
+ if (this.pending) {
216
+ this.line(this.pending);
217
+ this.pending = "";
218
+ }
219
+ return this.usage;
220
+ }
221
+ line(raw) {
222
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
223
+ if (!line.startsWith("data:")) {
224
+ return;
225
+ }
226
+ const data = line.slice(5).trim();
227
+ if (!data || data === "[DONE]") {
228
+ return;
229
+ }
230
+ this.firstEventAt ??= this.now();
231
+ const first = !this.sawEvent;
232
+ this.sawEvent = true;
233
+ if (!first && !data.includes("sage")) {
234
+ return;
235
+ }
236
+ try {
237
+ this.usage = mergeUsage(this.usage, usageFromDocument(JSON.parse(data)));
238
+ }
239
+ catch {
240
+ /* not JSON, or not ours to read */
241
+ }
242
+ }
243
+ }
244
+ function concat(chunks, size) {
245
+ const whole = new Uint8Array(size);
246
+ let offset = 0;
247
+ for (const chunk of chunks) {
248
+ whole.set(chunk, offset);
249
+ offset += chunk.byteLength;
250
+ }
251
+ return whole;
252
+ }
253
+ function keepTail(tail, chunk, limit) {
254
+ if (chunk.byteLength >= limit) {
255
+ return chunk.slice(chunk.byteLength - limit);
256
+ }
257
+ const previous = tail ?? new Uint8Array();
258
+ const keep = Math.min(previous.byteLength, limit - chunk.byteLength);
259
+ const next = new Uint8Array(keep + chunk.byteLength);
260
+ next.set(previous.subarray(previous.byteLength - keep), 0);
261
+ next.set(chunk, keep);
262
+ return next;
263
+ }
@@ -6,6 +6,7 @@ export declare class OutgoingObserveAgentService implements OnApplicationShutdow
6
6
  private readonly options;
7
7
  private readonly logger;
8
8
  private unsubscribeHttp?;
9
+ private deactivateLlm?;
9
10
  constructor(options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<any, any>>);
10
11
  onApplicationShutdown(): void;
11
12
  /**
@@ -17,6 +17,7 @@ import { OBSERVE_OPTIONS } from "../observe.constants.js";
17
17
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
18
18
  import { loadAsResolvedBy, loadOptionalPeer, } from "../utils/optional-peer.util.js";
19
19
  import { subscribeOutgoingHttp } from "./http.integration.js";
20
+ import { activateLlmFetchObserver, llmCallsOff, uninstallLlmFetchObserver, } from "./llm/llm-fetch.integration.js";
20
21
  import { patchMongodb } from "./mongodb.integration.js";
21
22
  import { patchMssql } from "./mssql.integration.js";
22
23
  import { patchMysql2 } from "./mysql2.integration.js";
@@ -91,9 +92,15 @@ let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class Outgoing
91
92
  options;
92
93
  logger = new Logger(OutgoingObserveAgentService_1.name);
93
94
  unsubscribeHttp;
95
+ deactivateLlm;
94
96
  constructor(options, operationTraceRegistry, asyncLocalStorage) {
95
97
  this.options = options;
96
98
  const outgoing = this.options.outgoing;
99
+ // `forRoot` has given `fetch` back already; `forRootAsync` options are
100
+ // only known from here.
101
+ if (llmCallsOff(outgoing)) {
102
+ uninstallLlmFetchObserver();
103
+ }
97
104
  if (outgoing === false) {
98
105
  return;
99
106
  }
@@ -111,9 +118,14 @@ let OutgoingObserveAgentService = OutgoingObserveAgentService_1 = class Outgoing
111
118
  ?.get(this.options.traceIdKey);
112
119
  return typeof traceId === "string" ? traceId : undefined;
113
120
  }, typeof outgoing?.http === "object" ? outgoing.http : {}, () => operationTraceRegistry.getRedactor());
121
+ // Model calls are read off the spans above, so they go with them.
122
+ if (outgoing?.llm !== false) {
123
+ this.deactivateLlm = activateLlmFetchObserver(recorder, typeof outgoing?.llm === "object" ? outgoing.llm : {});
124
+ }
114
125
  }
115
126
  }
116
127
  onApplicationShutdown() {
128
+ this.deactivateLlm?.();
117
129
  this.unsubscribeHttp?.();
118
130
  }
119
131
  /**
@@ -4,6 +4,15 @@ type Tags = Record<string, string | number | boolean>;
4
4
  /** A span that has been opened and is waiting to be told how the call went. */
5
5
  export interface OpenOutgoingSpan {
6
6
  end(error?: unknown): void;
7
+ /** Adds tags to the span - what the response said, once it has been read. */
8
+ tag?(tags: Tags): void;
9
+ /**
10
+ * Keeps the span from closing at `end` until the returned function runs,
11
+ * so tags read from the response can still reach it. The span keeps the
12
+ * duration it had at `end`, and closes on its own `HOLD_GRACE_MS` later if
13
+ * the hold is never released.
14
+ */
15
+ hold?(): () => void;
7
16
  }
8
17
  /**
9
18
  * Opens leaf spans for calls that leave the process - a database query, an
@@ -1,5 +1,11 @@
1
1
  import { AsyncLocalStorage } from "async_hooks";
2
2
  import { CALLER_METADATA_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
3
+ /**
4
+ * How long a held span may stay open after its call ended, waiting for what
5
+ * is reading its response. Well under the second the registry waits for open
6
+ * spans before it ships an operation without them.
7
+ */
8
+ const HOLD_GRACE_MS = 250;
3
9
  /**
4
10
  * Opens leaf spans for calls that leave the process - a database query, an
5
11
  * outbound HTTP request - under whatever span is active when they are made.
@@ -52,17 +58,60 @@ export class OutgoingSpanRecorder {
52
58
  if (node) {
53
59
  node.tags = { ...node.tags, ...tags };
54
60
  }
61
+ const startTime = node?.startTime;
55
62
  let ended = false;
63
+ let holds = 0;
64
+ let deferred;
65
+ let grace;
66
+ const close = (error, endedAt) => {
67
+ // A driver may report one call twice - a callback and an `error`
68
+ // event, a settled promise and a late listener. The registry counts
69
+ // closes against opens, so the second would unbalance the snapshot.
70
+ if (ended) {
71
+ return;
72
+ }
73
+ ended = true;
74
+ clearTimeout(grace);
75
+ this.operationTraceRegistry.internalEndTraceStep(registryKey, spanId, className, methodKey, spanId, error === undefined || error === null ? undefined : error);
76
+ // A held span closes late; the call itself ended at `endedAt`.
77
+ if (node && endedAt !== undefined && startTime !== undefined) {
78
+ node.duration = Math.max(endedAt - startTime, 0);
79
+ }
80
+ };
56
81
  return {
57
82
  end: (error) => {
58
- // A driver may report one call twice - a callback and an `error`
59
- // event, a settled promise and a late listener. The registry counts
60
- // closes against opens, so the second would unbalance the snapshot.
61
- if (ended) {
83
+ if (ended || deferred) {
84
+ return;
85
+ }
86
+ if (holds === 0) {
87
+ close(error);
62
88
  return;
63
89
  }
64
- ended = true;
65
- this.operationTraceRegistry.internalEndTraceStep(registryKey, spanId, className, methodKey, spanId, error === undefined || error === null ? undefined : error);
90
+ deferred = { at: performance.now(), error };
91
+ grace = setTimeout(() => close(deferred?.error, deferred?.at), HOLD_GRACE_MS);
92
+ grace.unref?.();
93
+ },
94
+ tag: (extra) => {
95
+ if (node) {
96
+ node.tags = { ...node.tags, ...extra };
97
+ }
98
+ },
99
+ hold: () => {
100
+ if (ended) {
101
+ return () => undefined;
102
+ }
103
+ holds += 1;
104
+ let released = false;
105
+ return () => {
106
+ if (released) {
107
+ return;
108
+ }
109
+ released = true;
110
+ holds -= 1;
111
+ if (holds === 0 && deferred) {
112
+ close(deferred.error, deferred.at);
113
+ }
114
+ };
66
115
  },
67
116
  };
68
117
  }
@@ -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);