@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.
- package/LICENSE +105 -22
- package/NOTICE +31 -0
- package/README.md +97 -8
- package/dist/agent/observe-agent.worker.js +8 -7
- package/dist/instrument/create-instance-decorator.instrument.js +134 -88
- package/dist/interfaces/observe-options.interface.d.ts +18 -2
- package/dist/interfaces/trace-events.interfaces.d.ts +11 -5
- package/dist/observe.constants.d.ts +5 -5
- package/dist/observe.constants.js +5 -5
- package/dist/observe.module.js +12 -0
- package/dist/outgoing/http.integration.js +4 -0
- package/dist/outgoing/llm/llm-fetch.integration.d.ts +56 -0
- package/dist/outgoing/llm/llm-fetch.integration.js +236 -0
- package/dist/outgoing/llm/llm-providers.d.ts +25 -0
- package/dist/outgoing/llm/llm-providers.js +96 -0
- package/dist/outgoing/llm/llm-usage.d.ts +67 -0
- package/dist/outgoing/llm/llm-usage.js +263 -0
- package/dist/outgoing/outgoing-observe-agent.service.d.ts +1 -0
- package/dist/outgoing/outgoing-observe-agent.service.js +12 -0
- package/dist/outgoing/outgoing-span.recorder.d.ts +9 -0
- package/dist/outgoing/outgoing-span.recorder.js +55 -6
- 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 +20 -28
- 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 +15 -9
- package/dist/services/operation-trace.registry.js +79 -25
- package/dist/utils/uuid-v7.util.js +53 -15
- package/package.json +5 -3
|
@@ -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
|
|
@@ -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
|
|
138
|
-
*
|
|
139
|
-
*
|
|
140
|
-
*
|
|
141
|
-
*
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
*
|
|
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
|
|
358
|
-
*
|
|
359
|
-
*
|
|
360
|
-
*
|
|
361
|
-
*
|
|
362
|
-
*
|
|
363
|
-
*
|
|
364
|
-
*
|
|
365
|
-
*
|
|
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
|
-
|
|
419
|
-
//
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
//
|
|
424
|
-
|
|
425
|
-
|
|
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
|
|
@@ -1,4 +1,33 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomFillSync } from "crypto";
|
|
2
|
+
/** Random bytes in each id: 12 bits go into `rand_a`, 62 into `rand_b`. */
|
|
3
|
+
const RANDOM_BYTES_PER_ID = 10;
|
|
4
|
+
/**
|
|
5
|
+
* Random bytes for the ids below, refilled 1,024 ids' worth at a time.
|
|
6
|
+
*
|
|
7
|
+
* The agent mints an id for every span, so this runs once per provider call
|
|
8
|
+
* of every traced request. A `randomBytes(10)` per id - a native call and a
|
|
9
|
+
* buffer each time - was the agent's largest single cost on the request path:
|
|
10
|
+
* a fifth of the main thread's busy time on an endpoint with nine spans. The
|
|
11
|
+
* bytes still come from the CSPRNG; it is asked once per 1,024 ids, the way
|
|
12
|
+
* `crypto.randomUUID()` caches its own entropy.
|
|
13
|
+
*/
|
|
14
|
+
const pool = Buffer.allocUnsafe(RANDOM_BYTES_PER_ID * 1024);
|
|
15
|
+
let poolOffset = pool.length;
|
|
16
|
+
const HEX_DIGITS = "0123456789abcdef";
|
|
17
|
+
/** Each byte value's two hex digits, as character codes. */
|
|
18
|
+
const HIGH_DIGIT = Uint8Array.from({ length: 256 }, (_, byte) => HEX_DIGITS.charCodeAt(byte >>> 4));
|
|
19
|
+
const LOW_DIGIT = Uint8Array.from({ length: 256 }, (_, byte) => HEX_DIGITS.charCodeAt(byte & 0x0f));
|
|
20
|
+
/**
|
|
21
|
+
* The id's 36 characters, written in place and read out as one string; the
|
|
22
|
+
* hyphens never move. Joined from pieces instead, an id was a concatenation
|
|
23
|
+
* V8 had to flatten before it could hash it, and the registry hashes every
|
|
24
|
+
* span id - as a map key - the moment it is minted.
|
|
25
|
+
*/
|
|
26
|
+
const text = Buffer.alloc(36, "-");
|
|
27
|
+
function writeByte(at, byte) {
|
|
28
|
+
text[at] = HIGH_DIGIT[byte];
|
|
29
|
+
text[at + 1] = LOW_DIGIT[byte];
|
|
30
|
+
}
|
|
2
31
|
/**
|
|
3
32
|
* A UUID whose first 48 bits are the minting time, milliseconds since the
|
|
4
33
|
* epoch (RFC 9562 version 7).
|
|
@@ -15,20 +44,29 @@ import { randomBytes } from "crypto";
|
|
|
15
44
|
* decode the same way.
|
|
16
45
|
*/
|
|
17
46
|
export function uuidv7(now = Date.now()) {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
47
|
+
if (poolOffset + RANDOM_BYTES_PER_ID > pool.length) {
|
|
48
|
+
randomFillSync(pool);
|
|
49
|
+
poolOffset = 0;
|
|
50
|
+
}
|
|
51
|
+
const r = poolOffset;
|
|
52
|
+
poolOffset += RANDOM_BYTES_PER_ID;
|
|
53
|
+
// 48-bit big-endian timestamp, split 32/16 so no shift runs past 2^32.
|
|
54
|
+
const high = Math.floor(now / 0x10000);
|
|
55
|
+
const low = now % 0x10000;
|
|
56
|
+
writeByte(0, (high >>> 24) & 0xff);
|
|
57
|
+
writeByte(2, (high >>> 16) & 0xff);
|
|
58
|
+
writeByte(4, (high >>> 8) & 0xff);
|
|
59
|
+
writeByte(6, high & 0xff);
|
|
60
|
+
writeByte(9, (low >>> 8) & 0xff);
|
|
61
|
+
writeByte(11, low & 0xff);
|
|
26
62
|
// Version 7 in the top nibble, 12 random bits below it.
|
|
27
|
-
|
|
28
|
-
|
|
63
|
+
writeByte(14, 0x70 | (pool[r] & 0x0f));
|
|
64
|
+
writeByte(16, pool[r + 1]);
|
|
29
65
|
// Variant `10` in the top two bits, 62 random bits below.
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
66
|
+
writeByte(19, 0x80 | (pool[r + 2] & 0x3f));
|
|
67
|
+
writeByte(21, pool[r + 3]);
|
|
68
|
+
for (let i = 0; i < 6; i++) {
|
|
69
|
+
writeByte(24 + i * 2, pool[r + 4 + i]);
|
|
70
|
+
}
|
|
71
|
+
return text.toString("latin1");
|
|
34
72
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nestjs/observe",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.21",
|
|
4
4
|
"description": "Observability and APM agent for NestJS - traces, runtime metrics and custom metrics",
|
|
5
5
|
"author": "Kamil Mysliwiec",
|
|
6
6
|
"homepage": "https://observe.nestjs.com",
|
|
@@ -42,7 +42,8 @@
|
|
|
42
42
|
},
|
|
43
43
|
"files": [
|
|
44
44
|
"dist",
|
|
45
|
-
"!dist/**/*.tsbuildinfo"
|
|
45
|
+
"!dist/**/*.tsbuildinfo",
|
|
46
|
+
"NOTICE"
|
|
46
47
|
],
|
|
47
48
|
"publishConfig": {
|
|
48
49
|
"access": "public"
|
|
@@ -61,6 +62,7 @@
|
|
|
61
62
|
"test:watch": "vitest",
|
|
62
63
|
"test:cov": "vitest run --coverage",
|
|
63
64
|
"test:int": "vitest run --config vitest.int.config.ts",
|
|
65
|
+
"bench": "npm run build && tsc -p bench/tsconfig.json && node bench/.build/run.js",
|
|
64
66
|
"prepack": "npm run build",
|
|
65
67
|
"prepublish:next": "npm run build",
|
|
66
68
|
"publish:next": "npm publish --access public --tag next",
|
|
@@ -70,7 +72,7 @@
|
|
|
70
72
|
"release": "release-it",
|
|
71
73
|
"prepare": "husky"
|
|
72
74
|
},
|
|
73
|
-
"license": "
|
|
75
|
+
"license": "SEE LICENSE IN LICENSE",
|
|
74
76
|
"dependencies": {
|
|
75
77
|
"@jridgewell/trace-mapping": "0.3.31"
|
|
76
78
|
},
|