@nestjs/observe 0.3.20 → 0.3.22
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.
- package/LICENSE +105 -22
- package/NOTICE +31 -0
- package/README.md +138 -21
- package/dist/agent/degraded-ingest.protocol.d.ts +20 -0
- package/dist/agent/degraded-ingest.protocol.js +25 -0
- package/dist/agent/detached-observe-worker.assembly.js +2 -1
- package/dist/agent/detached-observe-worker.d.ts +2 -0
- package/dist/agent/detached-observe-worker.js +7 -0
- package/dist/agent/observe-agent.shared-buffer.d.ts +36 -0
- package/dist/agent/observe-agent.shared-buffer.js +56 -1
- package/dist/agent/observe-agent.worker.d.ts +12 -0
- package/dist/agent/observe-agent.worker.js +63 -8
- package/dist/instrument/create-instance-decorator.instrument.js +99 -86
- package/dist/interfaces/observe-options.interface.d.ts +42 -3
- package/dist/interfaces/trace-events.interfaces.d.ts +11 -5
- package/dist/observe.constants.d.ts +15 -5
- package/dist/observe.constants.js +15 -5
- package/dist/observe.module.js +3 -0
- package/dist/outgoing/http.integration.d.ts +34 -3
- package/dist/outgoing/http.integration.js +84 -17
- package/dist/outgoing/outgoing-observe-agent.service.d.ts +14 -1
- package/dist/outgoing/outgoing-observe-agent.service.js +24 -9
- package/dist/outgoing/outgoing-span.recorder.d.ts +11 -1
- package/dist/outgoing/outgoing-span.recorder.js +8 -2
- package/dist/protocols/deferred-trace-completion.d.ts +13 -2
- package/dist/protocols/deferred-trace-completion.js +27 -4
- package/dist/protocols/graphql-observe-agent.service.js +1 -1
- package/dist/protocols/http-observe-agent.service.js +45 -30
- package/dist/protocols/job-trace-runner.js +2 -2
- package/dist/protocols/rpc-observe-agent.service.js +19 -10
- package/dist/protocols/ws-observe-agent.service.js +1 -1
- package/dist/services/collapse-repeated-spans.util.js +41 -37
- package/dist/services/operation-trace.registry.d.ts +32 -11
- package/dist/services/operation-trace.registry.js +102 -33
- package/dist/services/tracer.service.d.ts +6 -0
- package/dist/services/tracer.service.js +11 -2
- package/dist/utils/default-trace-id-generator.util.d.ts +18 -0
- package/dist/utils/default-trace-id-generator.util.js +33 -0
- package/dist/utils/opentelemetry.util.d.ts +31 -0
- package/dist/utils/opentelemetry.util.js +52 -0
- package/dist/utils/trace-context.util.d.ts +91 -0
- package/dist/utils/trace-context.util.js +219 -0
- package/dist/utils/trace-id-generator-origin.util.d.ts +11 -0
- package/dist/utils/trace-id-generator-origin.util.js +26 -0
- package/dist/utils/uuid-v7.util.js +53 -15
- package/package.json +18 -4
|
@@ -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(
|
|
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(
|
|
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
|
|
171
|
-
if (
|
|
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(
|
|
192
|
+
this.operationTraceRegistry.endTrace(registryKey, {
|
|
184
193
|
userId,
|
|
185
194
|
});
|
|
186
|
-
const snapshot = await this.operationTraceRegistry.pluckSnapshot(
|
|
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
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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
|
-
|
|
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
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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
|
-
|
|
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
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
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
|
-
|
|
202
|
-
|
|
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
|
|
208
|
-
*
|
|
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
|
|
@@ -129,20 +135,25 @@ export declare class OperationTraceRegistry {
|
|
|
129
135
|
*/
|
|
130
136
|
private toErrorStatusCode;
|
|
131
137
|
private setStatusCode;
|
|
132
|
-
internalStartTraceStep(traceId: TraceId, className: string, methodKey: string, callerId: string | undefined
|
|
138
|
+
internalStartTraceStep(traceId: TraceId, className: string, methodKey: string, callerId: string | undefined,
|
|
139
|
+
/**
|
|
140
|
+
* An id minted ahead of the span - by an outbound call that had to name
|
|
141
|
+
* its span in a `traceparent` before the span could be opened.
|
|
142
|
+
*/
|
|
143
|
+
spanId?: string): string | undefined;
|
|
133
144
|
/**
|
|
134
145
|
* Nests a freshly opened node under its caller when that caller is still
|
|
135
146
|
* live, and at the trace root otherwise.
|
|
136
147
|
*
|
|
137
|
-
* A caller that has already completed
|
|
138
|
-
*
|
|
139
|
-
*
|
|
140
|
-
*
|
|
141
|
-
*
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
*
|
|
148
|
+
* A caller that has already completed - its `type` is `"end"` - takes no
|
|
149
|
+
* more children: its span is closed. That happens whenever a callee
|
|
150
|
+
* outlives its caller - most commonly a handler that Nest bound
|
|
151
|
+
* (`AsyncResource.bind` in its interceptors consumer) to the async context
|
|
152
|
+
* of an interceptor whose `intercept()` returned synchronously. Fall back
|
|
153
|
+
* to the root rather than throw into the request: the mirror case, a step
|
|
154
|
+
* ending after its caller did, is already tolerated in
|
|
155
|
+
* `internalEndTraceStep`. Auto and manual spans both attach through here, so
|
|
156
|
+
* they share the tolerance.
|
|
146
157
|
*/
|
|
147
158
|
private attachToCaller;
|
|
148
159
|
internalEndTraceStep(traceId: TraceId,
|
|
@@ -186,7 +197,13 @@ export declare class OperationTraceRegistry {
|
|
|
186
197
|
* async call) would otherwise lose its offset entirely.
|
|
187
198
|
*/
|
|
188
199
|
private toStartOffset;
|
|
189
|
-
captureError(traceId: string, callerId: string | undefined, error: Error | string, tags: Record<string, string | number | boolean
|
|
200
|
+
captureError(traceId: string, callerId: string | undefined, error: Error | string, tags: Record<string, string | number | boolean>,
|
|
201
|
+
/**
|
|
202
|
+
* The trace id the warnings below name, when it is not the registry key:
|
|
203
|
+
* the one the operation's logs carry. The key itself appears nowhere a
|
|
204
|
+
* reader could look it up.
|
|
205
|
+
*/
|
|
206
|
+
reportedTraceId?: string): void;
|
|
190
207
|
/**
|
|
191
208
|
* Drops a trace that will never be plucked, freeing both maps.
|
|
192
209
|
*
|
|
@@ -221,6 +238,10 @@ export declare class OperationTraceRegistry {
|
|
|
221
238
|
* One line per trace `pluckSnapshot` ships without its open spans, naming
|
|
222
239
|
* them. Their late ends are silent: one un-awaited call usually holds a
|
|
223
240
|
* whole chain of spans open, and a line per span said the same thing N times.
|
|
241
|
+
*
|
|
242
|
+
* The line names the trace id the snapshot reports under, which the
|
|
243
|
+
* operation's logs and its trace carry too - not the registry key, which
|
|
244
|
+
* appears nowhere a reader could look it up.
|
|
224
245
|
*/
|
|
225
246
|
private reportUnfinishedSpans;
|
|
226
247
|
/**
|
|
@@ -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
|
|
@@ -313,13 +372,18 @@ export class OperationTraceRegistry {
|
|
|
313
372
|
}
|
|
314
373
|
requestSnapshot.attributes.statusCode = statusCode;
|
|
315
374
|
}
|
|
316
|
-
internalStartTraceStep(traceId, className, methodKey, callerId
|
|
375
|
+
internalStartTraceStep(traceId, className, methodKey, callerId,
|
|
376
|
+
/**
|
|
377
|
+
* An id minted ahead of the span - by an outbound call that had to name
|
|
378
|
+
* its span in a `traceparent` before the span could be opened.
|
|
379
|
+
*/
|
|
380
|
+
spanId) {
|
|
317
381
|
const snapshot = this.traceSnapshots.get(traceId);
|
|
318
382
|
if (!snapshot) {
|
|
319
383
|
return undefined;
|
|
320
384
|
}
|
|
321
385
|
snapshot.refsCounter += 1;
|
|
322
|
-
const newNodeId = uuidv7();
|
|
386
|
+
const newNodeId = spanId ?? uuidv7();
|
|
323
387
|
const startTime = performance.now();
|
|
324
388
|
// Records which span owns the thread from here. A no-op unless continuous
|
|
325
389
|
// profiling is on, and the only way profile samples can be attributed to a
|
|
@@ -354,15 +418,15 @@ export class OperationTraceRegistry {
|
|
|
354
418
|
* Nests a freshly opened node under its caller when that caller is still
|
|
355
419
|
* live, and at the trace root otherwise.
|
|
356
420
|
*
|
|
357
|
-
* A caller that has already completed
|
|
358
|
-
*
|
|
359
|
-
*
|
|
360
|
-
*
|
|
361
|
-
*
|
|
362
|
-
*
|
|
363
|
-
*
|
|
364
|
-
*
|
|
365
|
-
*
|
|
421
|
+
* A caller that has already completed - its `type` is `"end"` - takes no
|
|
422
|
+
* more children: its span is closed. That happens whenever a callee
|
|
423
|
+
* outlives its caller - most commonly a handler that Nest bound
|
|
424
|
+
* (`AsyncResource.bind` in its interceptors consumer) to the async context
|
|
425
|
+
* of an interceptor whose `intercept()` returned synchronously. Fall back
|
|
426
|
+
* to the root rather than throw into the request: the mirror case, a step
|
|
427
|
+
* ending after its caller did, is already tolerated in
|
|
428
|
+
* `internalEndTraceStep`. Auto and manual spans both attach through here, so
|
|
429
|
+
* they share the tolerance.
|
|
366
430
|
*/
|
|
367
431
|
attachToCaller(snapshot, refsByCaller, callerId, newNode) {
|
|
368
432
|
const caller = callerId ? refsByCaller?.get(callerId) : undefined;
|
|
@@ -407,23 +471,15 @@ export class OperationTraceRegistry {
|
|
|
407
471
|
return;
|
|
408
472
|
}
|
|
409
473
|
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
474
|
const parent = cursor.parent;
|
|
418
|
-
|
|
419
|
-
//
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
//
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
}
|
|
475
|
+
// The node has ended. It keeps its fields rather than having `type`,
|
|
476
|
+
// `startTime` and an empty `tags` or `children` deleted: a deleted
|
|
477
|
+
// property sends a V8 object into slow dictionary mode, and every span
|
|
478
|
+
// ended there, slowing everything that read the tree afterwards. `type`
|
|
479
|
+
// tells the live tree the node has ended; `toShippedNode` leaves the rest
|
|
480
|
+
// out when the trace is plucked. Complete nodes carry no parent reference.
|
|
481
|
+
cursor.type = "end";
|
|
482
|
+
cursor.parent = undefined;
|
|
427
483
|
const activeTrace = cursor;
|
|
428
484
|
activeTrace.duration = duration;
|
|
429
485
|
if (error && !activeTrace.error) {
|
|
@@ -520,20 +576,26 @@ export class OperationTraceRegistry {
|
|
|
520
576
|
}
|
|
521
577
|
return startTime - snapshot.startTimestamp;
|
|
522
578
|
}
|
|
523
|
-
captureError(traceId, callerId, error, tags
|
|
579
|
+
captureError(traceId, callerId, error, tags,
|
|
580
|
+
/**
|
|
581
|
+
* The trace id the warnings below name, when it is not the registry key:
|
|
582
|
+
* the one the operation's logs carry. The key itself appears nowhere a
|
|
583
|
+
* reader could look it up.
|
|
584
|
+
*/
|
|
585
|
+
reportedTraceId = traceId) {
|
|
524
586
|
const snapshot = this.traceSnapshots.get(traceId);
|
|
525
587
|
if (!snapshot) {
|
|
526
|
-
this.logger.warn(`No request snapshot found for traceId: "${
|
|
588
|
+
this.logger.warn(`No request snapshot found for traceId: "${reportedTraceId}". Cannot capture error.`);
|
|
527
589
|
return;
|
|
528
590
|
}
|
|
529
591
|
if (!snapshot.traces || snapshot.traces.length === 0) {
|
|
530
|
-
this.logger.warn(`No traces found for traceId: "${
|
|
592
|
+
this.logger.warn(`No traces found for traceId: "${reportedTraceId}". Cannot capture error.`);
|
|
531
593
|
return;
|
|
532
594
|
}
|
|
533
595
|
const refsByCaller = this.callerIdsByTraceId.get(traceId);
|
|
534
596
|
const targetSpan = refsByCaller?.get(callerId);
|
|
535
597
|
if (!targetSpan) {
|
|
536
|
-
this.logger.warn(`No active span found for traceId: "${
|
|
598
|
+
this.logger.warn(`No active span found for traceId: "${reportedTraceId}". Cannot capture error.`);
|
|
537
599
|
return;
|
|
538
600
|
}
|
|
539
601
|
if (!targetSpan.tags) {
|
|
@@ -611,6 +673,9 @@ export class OperationTraceRegistry {
|
|
|
611
673
|
snapshot.traces = [];
|
|
612
674
|
return snapshot;
|
|
613
675
|
}
|
|
676
|
+
// Every span has closed, and nothing writes to the tree any more: it is
|
|
677
|
+
// rebuilt once, as it will be shipped.
|
|
678
|
+
snapshot.traces = snapshot.traces.map(toShippedNode);
|
|
614
679
|
// Last, on the finished tree: every span has closed by now, so a group
|
|
615
680
|
// is judged on its complete membership and durations, and nothing that
|
|
616
681
|
// reads the tree afterwards - the encoder, the buffer - sees the
|
|
@@ -660,6 +725,10 @@ export class OperationTraceRegistry {
|
|
|
660
725
|
* One line per trace `pluckSnapshot` ships without its open spans, naming
|
|
661
726
|
* them. Their late ends are silent: one un-awaited call usually holds a
|
|
662
727
|
* whole chain of spans open, and a line per span said the same thing N times.
|
|
728
|
+
*
|
|
729
|
+
* The line names the trace id the snapshot reports under, which the
|
|
730
|
+
* operation's logs and its trace carry too - not the registry key, which
|
|
731
|
+
* appears nowhere a reader could look it up.
|
|
663
732
|
*/
|
|
664
733
|
reportUnfinishedSpans(traceId, snapshot) {
|
|
665
734
|
const open = [];
|
|
@@ -670,8 +739,8 @@ export class OperationTraceRegistry {
|
|
|
670
739
|
}
|
|
671
740
|
const operation = ("operationId" in snapshot && snapshot.operationId) ||
|
|
672
741
|
("name" in snapshot && snapshot.name) ||
|
|
673
|
-
traceId;
|
|
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.`);
|
|
742
|
+
snapshot.traceId;
|
|
743
|
+
this.logger.warn(`Trace "${snapshot.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.`);
|
|
675
744
|
}
|
|
676
745
|
/**
|
|
677
746
|
* Whether `skipSpans` claims a finished operation. Only request snapshots
|
|
@@ -153,6 +153,12 @@ export declare class TracerService<Store extends object = Record<string | symbol
|
|
|
153
153
|
* methods with no async context at all - and is reported the same way.
|
|
154
154
|
*/
|
|
155
155
|
private requireTraceId;
|
|
156
|
+
/**
|
|
157
|
+
* The trace id a message names: the one the operation's logs and
|
|
158
|
+
* `currentTraceId()` carry, rather than the registry key its trace is kept
|
|
159
|
+
* under, which a reader has no way to look up.
|
|
160
|
+
*/
|
|
161
|
+
private reportedTraceId;
|
|
156
162
|
private registerCounterChangeHandler;
|
|
157
163
|
private registerGaugeChangeHandler;
|
|
158
164
|
private registerSummaryChangeHandler;
|
|
@@ -81,7 +81,7 @@ let TracerService = TracerService_1 = class TracerService {
|
|
|
81
81
|
return new TraceSpanDelegate("", undefined, {});
|
|
82
82
|
}
|
|
83
83
|
if (!activeOngoingEvent) {
|
|
84
|
-
throw new Error(`No active span found for traceId: ${traceId}. Ensure that a span is created before calling "activeSpan".`);
|
|
84
|
+
throw new Error(`No active span found for traceId: ${this.reportedTraceId(store, traceId)}. Ensure that a span is created before calling "activeSpan".`);
|
|
85
85
|
}
|
|
86
86
|
let tags = activeOngoingEvent.tags;
|
|
87
87
|
if (!tags) {
|
|
@@ -116,7 +116,7 @@ let TracerService = TracerService_1 = class TracerService {
|
|
|
116
116
|
return;
|
|
117
117
|
}
|
|
118
118
|
const callerId = store.get(CALLER_METADATA_KEY);
|
|
119
|
-
this.operationTraceRegistry.captureError(traceId, callerId, error, tags ?? {});
|
|
119
|
+
this.operationTraceRegistry.captureError(traceId, callerId, error, tags ?? {}, this.reportedTraceId(store, traceId));
|
|
120
120
|
}
|
|
121
121
|
counter(name, attributes) {
|
|
122
122
|
const existingRef = this.counters.get(name);
|
|
@@ -279,6 +279,15 @@ let TracerService = TracerService_1 = class TracerService {
|
|
|
279
279
|
}
|
|
280
280
|
return traceId;
|
|
281
281
|
}
|
|
282
|
+
/**
|
|
283
|
+
* The trace id a message names: the one the operation's logs and
|
|
284
|
+
* `currentTraceId()` carry, rather than the registry key its trace is kept
|
|
285
|
+
* under, which a reader has no way to look up.
|
|
286
|
+
*/
|
|
287
|
+
reportedTraceId(store, registryKey) {
|
|
288
|
+
const traceId = store.get(this.options.traceIdKey);
|
|
289
|
+
return typeof traceId === "string" ? traceId : registryKey;
|
|
290
|
+
}
|
|
282
291
|
registerCounterChangeHandler(counter) {
|
|
283
292
|
counter["_onChange"] = (self) => {
|
|
284
293
|
this.observeAgentSharedBuffer.upsertCustomMetric(self);
|
|
@@ -11,3 +11,21 @@
|
|
|
11
11
|
*/
|
|
12
12
|
export declare const REQUEST_ID_PATTERN: RegExp;
|
|
13
13
|
export declare function defaultTraceIdGenerator(req: unknown): string;
|
|
14
|
+
/**
|
|
15
|
+
* The default `traceIdGenerator` with `openTelemetry` on.
|
|
16
|
+
*
|
|
17
|
+
* A request in a W3C trace is named after that trace, so it has the id the
|
|
18
|
+
* rest of the trace has in the caller's OpenTelemetry backend: the trace a
|
|
19
|
+
* caller's `traceparent` names - a service in another language, a mesh, a
|
|
20
|
+
* load balancer that starts traces - or, when an OpenTelemetry SDK runs in
|
|
21
|
+
* this process, the one it continued or started for the request (see
|
|
22
|
+
* `inboundTraceContext`). Anything else is named as `defaultTraceIdGenerator`
|
|
23
|
+
* names it.
|
|
24
|
+
*
|
|
25
|
+
* An `x-request-id` beside the trace names some other one when a mesh or a
|
|
26
|
+
* router stamped it (Envoy and Heroku's router stamp every request), and gives
|
|
27
|
+
* way. It stays only when it names this same trace: another service running
|
|
28
|
+
* this agent sends both, and its id may be one `traceparent` cannot carry - a
|
|
29
|
+
* custom id, or a UUIDv7 whose mint time the collector reads.
|
|
30
|
+
*/
|
|
31
|
+
export declare function openTelemetryTraceIdGenerator(req: unknown): string;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { inboundTraceId, w3cTraceIdOf } from "./trace-context.util.js";
|
|
1
2
|
import { uuidv7 } from "./uuid-v7.util.js";
|
|
2
3
|
/**
|
|
3
4
|
* What an inbound `x-request-id` must look like to be adopted as the trace id.
|
|
@@ -32,3 +33,35 @@ export function defaultTraceIdGenerator(req) {
|
|
|
32
33
|
// Minted here, so it can carry its time - see uuidv7.
|
|
33
34
|
return uuidv7();
|
|
34
35
|
}
|
|
36
|
+
/**
|
|
37
|
+
* The default `traceIdGenerator` with `openTelemetry` on.
|
|
38
|
+
*
|
|
39
|
+
* A request in a W3C trace is named after that trace, so it has the id the
|
|
40
|
+
* rest of the trace has in the caller's OpenTelemetry backend: the trace a
|
|
41
|
+
* caller's `traceparent` names - a service in another language, a mesh, a
|
|
42
|
+
* load balancer that starts traces - or, when an OpenTelemetry SDK runs in
|
|
43
|
+
* this process, the one it continued or started for the request (see
|
|
44
|
+
* `inboundTraceContext`). Anything else is named as `defaultTraceIdGenerator`
|
|
45
|
+
* names it.
|
|
46
|
+
*
|
|
47
|
+
* An `x-request-id` beside the trace names some other one when a mesh or a
|
|
48
|
+
* router stamped it (Envoy and Heroku's router stamp every request), and gives
|
|
49
|
+
* way. It stays only when it names this same trace: another service running
|
|
50
|
+
* this agent sends both, and its id may be one `traceparent` cannot carry - a
|
|
51
|
+
* custom id, or a UUIDv7 whose mint time the collector reads.
|
|
52
|
+
*/
|
|
53
|
+
export function openTelemetryTraceIdGenerator(req) {
|
|
54
|
+
if (typeof req === "object" && req !== null && "headers" in req) {
|
|
55
|
+
const headers = req.headers;
|
|
56
|
+
const fromTraceContext = inboundTraceId(headers);
|
|
57
|
+
if (fromTraceContext) {
|
|
58
|
+
const requestId = headers?.["x-request-id"];
|
|
59
|
+
return typeof requestId === "string" &&
|
|
60
|
+
REQUEST_ID_PATTERN.test(requestId) &&
|
|
61
|
+
w3cTraceIdOf(requestId) === w3cTraceIdOf(fromTraceContext)
|
|
62
|
+
? requestId
|
|
63
|
+
: fromTraceContext;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return defaultTraceIdGenerator(req);
|
|
67
|
+
}
|