@nestjs/observe 0.3.25 → 0.3.27
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/README.md +55 -2
- package/dist/agent/detached-observe-worker.js +50 -6
- package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
- package/dist/agent/observe-agent.shared-buffer.js +201 -19
- package/dist/agent/observe-agent.worker.d.ts +22 -2
- package/dist/agent/observe-agent.worker.js +43 -7
- package/dist/agent/telemetry-wire-contract.js +10 -4
- package/dist/cli/agent-notes.js +16 -4
- package/dist/cli/link.js +51 -4
- package/dist/cli/observe-cli.js +1 -19
- package/dist/cli/open-url.d.ts +27 -0
- package/dist/cli/open-url.js +63 -0
- package/dist/cli/package-manager.d.ts +6 -0
- package/dist/cli/package-manager.js +60 -3
- package/dist/cli/project-files.d.ts +62 -1
- package/dist/cli/project-files.js +229 -7
- package/dist/cli/project-setup.d.ts +6 -0
- package/dist/cli/project-setup.js +14 -1
- package/dist/cli/wire-application.js +6 -0
- package/dist/custom-metrics/counter.d.ts +13 -2
- package/dist/custom-metrics/counter.js +33 -16
- package/dist/custom-metrics/finite-value.util.d.ts +14 -0
- package/dist/custom-metrics/finite-value.util.js +33 -1
- package/dist/custom-metrics/gauge.d.ts +2 -0
- package/dist/custom-metrics/gauge.js +41 -17
- package/dist/custom-metrics/label-values.util.d.ts +37 -0
- package/dist/custom-metrics/label-values.util.js +51 -0
- package/dist/custom-metrics/summary.d.ts +23 -0
- package/dist/custom-metrics/summary.js +90 -12
- package/dist/instrument/create-instance-decorator.instrument.js +504 -116
- package/dist/instrument/raw-receiver.d.ts +6 -0
- package/dist/instrument/raw-receiver.js +32 -0
- package/dist/interfaces/observe-options.interface.d.ts +17 -6
- package/dist/objectives/objectives.registry.js +12 -0
- package/dist/observe.module.js +119 -3
- package/dist/otlp/otlp-encoders.js +22 -5
- package/dist/otlp/otlp-span.mapper.d.ts +2 -0
- package/dist/otlp/otlp-span.mapper.js +26 -4
- package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
- package/dist/otlp/otlp-trace-exporter.service.js +295 -43
- package/dist/outgoing/http.integration.d.ts +8 -4
- package/dist/outgoing/http.integration.js +49 -17
- package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
- package/dist/outgoing/llm/llm-providers.d.ts +16 -4
- package/dist/outgoing/llm/llm-providers.js +72 -22
- package/dist/outgoing/llm/llm-usage.d.ts +11 -6
- package/dist/outgoing/llm/llm-usage.js +72 -25
- package/dist/outgoing/mongodb.integration.d.ts +3 -1
- package/dist/outgoing/mongodb.integration.js +93 -18
- package/dist/outgoing/mssql.integration.js +25 -6
- package/dist/outgoing/mysql2.integration.js +17 -1
- package/dist/outgoing/outgoing-observe-agent.service.js +20 -4
- package/dist/outgoing/outgoing-span.recorder.js +17 -3
- package/dist/outgoing/pg.integration.d.ts +3 -2
- package/dist/outgoing/pg.integration.js +39 -11
- package/dist/outgoing/sql-statement.util.js +139 -21
- package/dist/outgoing/undici.integration.d.ts +13 -0
- package/dist/outgoing/undici.integration.js +68 -0
- package/dist/protocols/bull-observe-agent.service.js +23 -12
- package/dist/protocols/deferred-trace-completion.d.ts +17 -3
- package/dist/protocols/deferred-trace-completion.js +76 -9
- package/dist/protocols/graphql-observe-agent.service.d.ts +97 -6
- package/dist/protocols/graphql-observe-agent.service.js +354 -19
- package/dist/protocols/graphql-operation-parser.js +111 -26
- package/dist/protocols/http-observe-agent.service.d.ts +50 -9
- package/dist/protocols/http-observe-agent.service.js +220 -59
- package/dist/protocols/job-trace-runner.d.ts +42 -3
- package/dist/protocols/job-trace-runner.js +197 -36
- package/dist/protocols/queue-observe-agent.service.js +44 -20
- package/dist/protocols/rpc-observe-agent.service.d.ts +111 -8
- package/dist/protocols/rpc-observe-agent.service.js +332 -56
- package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
- package/dist/protocols/ws-observe-agent.service.js +227 -21
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/logger-patcher.service.js +16 -7
- package/dist/services/operation-trace.registry.d.ts +58 -1
- package/dist/services/operation-trace.registry.js +576 -63
- package/dist/services/stdout-forwarder.service.d.ts +69 -0
- package/dist/services/stdout-forwarder.service.js +308 -51
- package/dist/services/tracer.service.d.ts +39 -11
- package/dist/services/tracer.service.js +145 -36
- package/dist/utils/capture-request.util.d.ts +3 -1
- package/dist/utils/capture-request.util.js +128 -12
- package/dist/utils/context-accessor.util.d.ts +16 -0
- package/dist/utils/context-accessor.util.js +28 -0
- package/dist/utils/default-trace-id-generator.util.js +5 -7
- package/dist/utils/error-stack.util.d.ts +13 -0
- package/dist/utils/error-stack.util.js +166 -0
- package/dist/utils/fit-to-length.util.js +33 -10
- package/dist/utils/log-line.parser.d.ts +22 -0
- package/dist/utils/log-line.parser.js +20 -7
- package/dist/utils/log-redactor.d.ts +14 -0
- package/dist/utils/log-redactor.js +690 -65
- package/dist/utils/operation-state.util.d.ts +39 -0
- package/dist/utils/operation-state.util.js +50 -0
- package/dist/utils/redact-url-query.d.ts +37 -4
- package/dist/utils/redact-url-query.js +197 -32
- package/dist/utils/sensitive-keys.d.ts +4 -1
- package/dist/utils/sensitive-keys.js +48 -10
- package/dist/utils/shared-hook-slot.util.d.ts +48 -0
- package/dist/utils/shared-hook-slot.util.js +103 -0
- package/dist/utils/source-context.util.d.ts +14 -0
- package/dist/utils/source-context.util.js +142 -43
- package/dist/utils/source-map-resolver.util.js +33 -6
- package/dist/utils/store-copy.util.d.ts +10 -0
- package/dist/utils/store-copy.util.js +43 -0
- package/dist/utils/trace-context.util.js +21 -6
- package/package.json +2 -2
|
@@ -11,18 +11,27 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
11
11
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
12
|
};
|
|
13
13
|
var RpcObserveAgentService_1;
|
|
14
|
-
import { Inject, Injectable, Logger
|
|
14
|
+
import { Inject, Injectable, Logger } from "@nestjs/common";
|
|
15
15
|
import { ModulesContainer } from "@nestjs/core";
|
|
16
16
|
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
20
|
import { OBSERVE_OPTIONS, TRACE_CONTEXT_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
|
|
21
|
+
import { readContextAccessor } from "../utils/context-accessor.util.js";
|
|
21
22
|
import { handedOnTraceContext } from "../utils/trace-context.util.js";
|
|
22
23
|
import { continueHandedOnTrace } from "../utils/trace-handoff.util.js";
|
|
23
24
|
import { uuidv7 } from "../utils/uuid-v7.util.js";
|
|
25
|
+
import { setAgentHook } from "../utils/shared-hook-slot.util.js";
|
|
24
26
|
import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
|
|
25
27
|
import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
|
|
28
|
+
import { endOperation, OPERATION_STATE_KEY, openOperation, } from "../utils/operation-state.util.js";
|
|
29
|
+
/**
|
|
30
|
+
* Stands in for the transport of a custom transporter that names none, so it
|
|
31
|
+
* is traced as one named by a symbol without a description is: as `custom`.
|
|
32
|
+
* Its message used to fail before its handler ran, on `transportId.toString()`.
|
|
33
|
+
*/
|
|
34
|
+
const UNNAMED_TRANSPORT = Symbol("custom");
|
|
26
35
|
let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentService {
|
|
27
36
|
asyncLocalStorage;
|
|
28
37
|
options;
|
|
@@ -33,11 +42,29 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
33
42
|
logger = new Logger(RpcObserveAgentService_1.name);
|
|
34
43
|
rpcTargetAddedSubscription;
|
|
35
44
|
/**
|
|
36
|
-
* Assigned in
|
|
45
|
+
* Assigned in the constructor. Every use below is reached only through the
|
|
37
46
|
* hooks registered there, after a successful load - a service without the
|
|
38
47
|
* package has no RPC target to hook.
|
|
39
48
|
*/
|
|
40
49
|
microservices;
|
|
50
|
+
/**
|
|
51
|
+
* The registry key each operation was started under, by the context Nest
|
|
52
|
+
* hands its end hook. That hook cannot ask the async store: Nest runs it
|
|
53
|
+
* from the teardown of the handler's reply stream, in the async context of
|
|
54
|
+
* whatever ended the stream - a TCP socket's `close`, a gRPC cancellation,
|
|
55
|
+
* a subject another message's handler emitted into. As
|
|
56
|
+
* `HttpObserveAgentService` keeps its keys by request.
|
|
57
|
+
*/
|
|
58
|
+
registryKeys = new WeakMap();
|
|
59
|
+
/** The operation each context was started for - see `rememberOperation`. */
|
|
60
|
+
operations = new WeakMap();
|
|
61
|
+
/**
|
|
62
|
+
* The gRPC calls of a request stream, by their metadata - see
|
|
63
|
+
* `rememberGrpcCalls`.
|
|
64
|
+
*/
|
|
65
|
+
grpcCalls = new WeakMap();
|
|
66
|
+
/** The gRPC servers whose calls `rememberGrpcCalls` already notes. */
|
|
67
|
+
grpcServers = new WeakSet();
|
|
41
68
|
constructor(asyncLocalStorage, options, modulesContainer, operationTraceRegistry, observeAgentSharedBuffer, traceSamplerService) {
|
|
42
69
|
this.asyncLocalStorage = asyncLocalStorage;
|
|
43
70
|
this.options = options;
|
|
@@ -45,15 +72,23 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
45
72
|
this.operationTraceRegistry = operationTraceRegistry;
|
|
46
73
|
this.observeAgentSharedBuffer = observeAgentSharedBuffer;
|
|
47
74
|
this.traceSamplerService = traceSamplerService;
|
|
48
|
-
|
|
49
|
-
|
|
75
|
+
// From the constructor, while Nest builds the providers: Nest announces
|
|
76
|
+
// a server when it constructs the microservice around it, inside
|
|
77
|
+
// `createMicroservice()` or `connectMicroservice()`, so the hooks are in
|
|
78
|
+
// place before the application is handed the server and can set hooks
|
|
79
|
+
// of its own on it (`getTransportServer()`), which then run beside them.
|
|
50
80
|
this.microservices = this.loadMicroservices();
|
|
51
81
|
if (!this.microservices) {
|
|
52
82
|
return;
|
|
53
83
|
}
|
|
54
|
-
|
|
55
|
-
.
|
|
56
|
-
|
|
84
|
+
try {
|
|
85
|
+
this.rpcTargetAddedSubscription = this.modulesContainer
|
|
86
|
+
.getRpcTargetRegistry?.()
|
|
87
|
+
.subscribe((target) => this.registerRpcHooks(target));
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
this.logger.warn(`RPC operations will not be instrumented: the microservice registry could not be subscribed to: ${describePeerLoadError(error)}`);
|
|
91
|
+
}
|
|
57
92
|
}
|
|
58
93
|
onModuleDestroy() {
|
|
59
94
|
if (this.rpcTargetAddedSubscription) {
|
|
@@ -63,9 +98,9 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
63
98
|
/**
|
|
64
99
|
* Loads `@nestjs/microservices` without a static import, so a service that
|
|
65
100
|
* exposes no microservice need not install the package. Loaded here rather
|
|
66
|
-
* than lazily because the target registry is subscribed from
|
|
67
|
-
* and a dynamic `import()` would resolve after a target may
|
|
68
|
-
* been announced.
|
|
101
|
+
* than lazily because the target registry is subscribed from the
|
|
102
|
+
* constructor, and a dynamic `import()` would resolve after a target may
|
|
103
|
+
* already have been announced.
|
|
69
104
|
*/
|
|
70
105
|
loadMicroservices() {
|
|
71
106
|
const result = loadOptionalPeer("@nestjs/microservices");
|
|
@@ -82,20 +117,142 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
82
117
|
}
|
|
83
118
|
return result.module;
|
|
84
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* Sets the agent's processing hooks on a server, beside any the application
|
|
122
|
+
* sets on it - see `composeStartHook`.
|
|
123
|
+
*/
|
|
85
124
|
registerRpcHooks(target) {
|
|
86
125
|
// Return `done()`'s promise, as Nest's default hook does. Nest's servers
|
|
87
126
|
// hand it back from their message handlers: kafkajs waits on it to commit
|
|
88
127
|
// the offset or retry the message, and recent Nest versions log its
|
|
89
128
|
// rejection for most other transports.
|
|
90
|
-
target
|
|
129
|
+
setAgentHook(target, "setOnProcessingStartHook", (transportId, ctx, done) => {
|
|
91
130
|
if (transportId === this.microservices.Transport.GRPC) {
|
|
92
131
|
return this.startGrpcRequestTracing(transportId, ctx, done);
|
|
93
132
|
}
|
|
94
|
-
return this.startRpcRequestTracing(transportId, ctx, done);
|
|
95
|
-
});
|
|
96
|
-
target
|
|
97
|
-
this.endRpcRequestTracing(transportId, ctx);
|
|
98
|
-
});
|
|
133
|
+
return this.startRpcRequestTracing(transportId ?? UNNAMED_TRANSPORT, ctx, done, target);
|
|
134
|
+
}, composeStartHook);
|
|
135
|
+
setAgentHook(target, "setOnProcessingEndHook", (transportId, ctx) => {
|
|
136
|
+
this.endRpcRequestTracing(transportId ?? UNNAMED_TRANSPORT, ctx);
|
|
137
|
+
}, composeEndHook);
|
|
138
|
+
if (target.transportId ===
|
|
139
|
+
this.microservices.Transport.GRPC) {
|
|
140
|
+
this.rememberGrpcCalls(target);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Notes each call of a gRPC request stream by its metadata, for
|
|
145
|
+
* `startGrpcRequestTracing` to find the call itself by.
|
|
146
|
+
*
|
|
147
|
+
* The start hook is handed a copy of the call, its fields spread onto a new
|
|
148
|
+
* object (`{ ...call }`), and a copy emits nothing: the messages of the
|
|
149
|
+
* request stream are emitted on the call. The copy shares the call's
|
|
150
|
+
* `metadata`, so the call is kept by that, from the method grpc-js runs for
|
|
151
|
+
* it - the only place the call itself passes before the hook. That method
|
|
152
|
+
* is built by `createServiceMethod`, wrapped here on this server alone as
|
|
153
|
+
* Nest calls it once per method when the server starts to listen, after
|
|
154
|
+
* this hook was set. Unary and server-streaming calls are left alone: they
|
|
155
|
+
* have no later messages to run anywhere. A server without the method keeps
|
|
156
|
+
* its calls' events where grpc-js emits them.
|
|
157
|
+
*/
|
|
158
|
+
rememberGrpcCalls(target) {
|
|
159
|
+
const server = target;
|
|
160
|
+
const original = server.createServiceMethod;
|
|
161
|
+
if (typeof original !== "function" || this.grpcServers.has(target)) {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
this.grpcServers.add(target);
|
|
165
|
+
const calls = this.grpcCalls;
|
|
166
|
+
const passThrough = this.microservices.GrpcMethodStreamingType.PT_STREAMING;
|
|
167
|
+
server.createServiceMethod = function (methodHandler, protoNativeHandler, streamType) {
|
|
168
|
+
const method = original.call(this, methodHandler, protoNativeHandler, streamType);
|
|
169
|
+
if (!protoNativeHandler?.requestStream || typeof method !== "function") {
|
|
170
|
+
return method;
|
|
171
|
+
}
|
|
172
|
+
const streamCall = streamType === passThrough;
|
|
173
|
+
return function (call, ...rest) {
|
|
174
|
+
const metadata = call?.metadata;
|
|
175
|
+
if (typeof metadata === "object" && metadata !== null) {
|
|
176
|
+
calls.set(metadata, { call: call, streamCall });
|
|
177
|
+
}
|
|
178
|
+
return method.call(this, call, ...rest);
|
|
179
|
+
};
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
/** The call `ctx` is a copy of, if `rememberGrpcCalls` noted it. */
|
|
183
|
+
takeGrpcCall(ctx) {
|
|
184
|
+
const metadata = ctx?.metadata;
|
|
185
|
+
if (typeof metadata !== "object" || metadata === null) {
|
|
186
|
+
return undefined;
|
|
187
|
+
}
|
|
188
|
+
const remembered = this.grpcCalls.get(metadata);
|
|
189
|
+
this.grpcCalls.delete(metadata);
|
|
190
|
+
return remembered;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Drops the trace of a `@GrpcStreamCall` call that is cancelled while its
|
|
194
|
+
* handler is still running, as the HTTP agent drops an aborted request's.
|
|
195
|
+
*
|
|
196
|
+
* Nest ends a call's operation when its handler settles, and for a
|
|
197
|
+
* `@GrpcStreamCall` handler it waits on that alone. On a deadline or a
|
|
198
|
+
* client's cancellation grpc-js emits `cancelled` and destroys the stream,
|
|
199
|
+
* with no `end` and no `error`, so a handler that waits for either never
|
|
200
|
+
* settles: its trace stayed in the registry for the life of the process,
|
|
201
|
+
* one per call, and was never reported. Unary and `@GrpcStreamMethod` calls
|
|
202
|
+
* are left to Nest, which ends them on `cancelled` itself.
|
|
203
|
+
*
|
|
204
|
+
* Dropped a turn after `cancelled`, not at once: a handler that settles on
|
|
205
|
+
* it is ended by Nest, from microtasks, before then, and reported as ever.
|
|
206
|
+
* One that settles later outlived its client, and the registry already
|
|
207
|
+
* lets it end its spans on a trace that is gone.
|
|
208
|
+
*/
|
|
209
|
+
dropTraceOnCancel(call, operation, registryKey) {
|
|
210
|
+
const drop = () => {
|
|
211
|
+
setImmediate(() => {
|
|
212
|
+
if (operation.endedAt !== undefined) {
|
|
213
|
+
// Nest's end hook ran: ended and reported, or on its way.
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
endOperation(operation);
|
|
217
|
+
this.operationTraceRegistry.abandonTrace(registryKey);
|
|
218
|
+
});
|
|
219
|
+
};
|
|
220
|
+
if (call.cancelled === true) {
|
|
221
|
+
// Cancelled before an application's start hook let the call through.
|
|
222
|
+
drop();
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
call.once?.("cancelled", drop);
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Runs the events of a gRPC request stream in the call's store.
|
|
229
|
+
*
|
|
230
|
+
* A listener runs in the async context of whatever emits its event. The
|
|
231
|
+
* messages already queued when the handler subscribes are emitted from
|
|
232
|
+
* within `done`, inside the store; every later one from grpc-js's callback
|
|
233
|
+
* on the HTTP/2 stream, which belongs to the connection and has no store.
|
|
234
|
+
* So the second message of an ordinary stream was handled outside its call:
|
|
235
|
+
* no spans, no trace id on its log lines, and `TracerService.createSpan()`
|
|
236
|
+
* threw - a status 2 for a `@GrpcStreamMethod` handler, and for a
|
|
237
|
+
* `@GrpcStreamCall` handler's `data` listener an uncaught rejection that
|
|
238
|
+
* ended the process.
|
|
239
|
+
*
|
|
240
|
+
* An event emitted from within the call - a span of it writing to the
|
|
241
|
+
* stream - keeps the context it is emitted in, the span's, which carries
|
|
242
|
+
* the call's key.
|
|
243
|
+
*/
|
|
244
|
+
emitCallEventsInStore(call, store, registryKey) {
|
|
245
|
+
if (typeof call.emit !== "function") {
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
const asyncLocalStorage = this.asyncLocalStorage;
|
|
249
|
+
const emit = call.emit;
|
|
250
|
+
call.emit = function (...args) {
|
|
251
|
+
if (asyncLocalStorage.getStore()?.get(TRACE_REGISTRY_KEY) === registryKey) {
|
|
252
|
+
return Reflect.apply(emit, this, args);
|
|
253
|
+
}
|
|
254
|
+
return asyncLocalStorage.run(store, () => Reflect.apply(emit, this, args));
|
|
255
|
+
};
|
|
99
256
|
}
|
|
100
257
|
/**
|
|
101
258
|
* Names the transport for the snapshot's `protocol` field.
|
|
@@ -109,7 +266,9 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
109
266
|
? transportId.description ?? "custom"
|
|
110
267
|
: this.microservices.Transport[transportId];
|
|
111
268
|
}
|
|
112
|
-
startRpcRequestTracing(transportId, ctx, done
|
|
269
|
+
startRpcRequestTracing(transportId, ctx, done,
|
|
270
|
+
/** The server the message arrived at. */
|
|
271
|
+
target) {
|
|
113
272
|
// The same map `run` is given, rather than `getStore()` inside the callback:
|
|
114
273
|
// identical object, one lookup fewer, and it is known to exist.
|
|
115
274
|
const store = new Map();
|
|
@@ -120,6 +279,9 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
120
279
|
// execution before option callbacks can reach another operation's trace.
|
|
121
280
|
const registryKey = uuidv7();
|
|
122
281
|
store.set(TRACE_REGISTRY_KEY, registryKey);
|
|
282
|
+
this.rememberRegistryKey(ctx, registryKey);
|
|
283
|
+
// Ended by the end hook, recorded or not: see `liveTraceId`.
|
|
284
|
+
this.rememberOperation(ctx, openOperation(store));
|
|
123
285
|
// With OpenTelemetry interop on, the handler runs in the W3C trace
|
|
124
286
|
// context the message was sent in, for an OpenTelemetry SDK in this
|
|
125
287
|
// process - see `continueHandedOnTrace`. Recorded or not, as an
|
|
@@ -137,7 +299,7 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
137
299
|
if (traceContext) {
|
|
138
300
|
store.set(TRACE_CONTEXT_KEY, traceContext);
|
|
139
301
|
}
|
|
140
|
-
setAttributesSafely(this.options.rpc?.setAttributes, [transportId, ctx], this.options.rpc, store, this.logger, "rpc");
|
|
302
|
+
setAttributesSafely(this.options.rpc?.setAttributes, [transportId, ctx], this.options.rpc, store, this.logger, "rpc", this.options.traceIdKey);
|
|
141
303
|
if (shouldIgnoreSafely(this.options.rpc?.ignore, [transportId, ctx], this.options.rpc, this.logger, "rpc")) {
|
|
142
304
|
return handle();
|
|
143
305
|
}
|
|
@@ -150,7 +312,7 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
150
312
|
}
|
|
151
313
|
this.operationTraceRegistry.startTrace(registryKey, {
|
|
152
314
|
protocol: this.toProtocolName(transportId),
|
|
153
|
-
operationId: this.getOperationIdFromContext(ctx),
|
|
315
|
+
operationId: this.getOperationIdFromContext(ctx, target),
|
|
154
316
|
tags: this.options.rpc?.tags,
|
|
155
317
|
}, traceId, traceContext);
|
|
156
318
|
return handle();
|
|
@@ -170,9 +332,24 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
170
332
|
return this.asyncLocalStorage.run(store, () => {
|
|
171
333
|
const traceId = generateTraceIdSafely(this.options.traceIdGenerator, call, this.options, this.logger);
|
|
172
334
|
store.set(this.options.traceIdKey, traceId);
|
|
173
|
-
// The key must precede callbacks here too
|
|
335
|
+
// The key must precede callbacks here too.
|
|
174
336
|
const registryKey = uuidv7();
|
|
175
337
|
store.set(TRACE_REGISTRY_KEY, registryKey);
|
|
338
|
+
// Nest ends a gRPC call with its request message rather than the
|
|
339
|
+
// context it started it with, so the key is kept by both.
|
|
340
|
+
this.rememberRegistryKey(call, registryKey);
|
|
341
|
+
this.rememberRegistryKey(call?.request, registryKey);
|
|
342
|
+
const operation = openOperation(store);
|
|
343
|
+
this.rememberOperation(call, operation);
|
|
344
|
+
this.rememberOperation(call?.request, operation);
|
|
345
|
+
const grpcCall = this.takeGrpcCall(call);
|
|
346
|
+
if (grpcCall) {
|
|
347
|
+
// Recorded or not: `TracerService` needs the store either way.
|
|
348
|
+
this.emitCallEventsInStore(grpcCall.call, store, registryKey);
|
|
349
|
+
if (grpcCall.streamCall) {
|
|
350
|
+
this.dropTraceOnCancel(grpcCall.call, operation, registryKey);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
176
353
|
// As for a message: the call's span goes under the caller's for `otlp`,
|
|
177
354
|
// and the calls the handler makes carry its decision on. Read now, while
|
|
178
355
|
// the span a gRPC instrumentation opened for the call is the active one.
|
|
@@ -184,36 +361,45 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
184
361
|
if (traceContext) {
|
|
185
362
|
store.set(TRACE_CONTEXT_KEY, traceContext);
|
|
186
363
|
}
|
|
187
|
-
setAttributesSafely(this.options.grpc?.setAttributes, [call], this.options.grpc, store, this.logger, "grpc");
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
return resolve(done());
|
|
200
|
-
}
|
|
201
|
-
this.operationTraceRegistry.startTrace(registryKey, {
|
|
202
|
-
protocol: this.toProtocolName(transportId),
|
|
203
|
-
operationId: call.operationId,
|
|
204
|
-
tags: this.options.grpc?.tags,
|
|
205
|
-
}, traceId, traceContext);
|
|
206
|
-
resolve(done());
|
|
207
|
-
}, 0);
|
|
364
|
+
setAttributesSafely(this.options.grpc?.setAttributes, [call], this.options.grpc, store, this.logger, "grpc", this.options.traceIdKey);
|
|
365
|
+
// `done` runs before the hook returns, as for any other transport. Nest
|
|
366
|
+
// listens for the call's `cancelled` and `end` events inside it, and
|
|
367
|
+
// grpc-js emits `cancelled` once: run from a timer, a call cancelled or
|
|
368
|
+
// past its deadline on arrival had nothing listening, and a
|
|
369
|
+
// client-streaming handler waited for good on a request stream that
|
|
370
|
+
// never ended, its trace held in the registry.
|
|
371
|
+
if (shouldIgnoreSafely(this.options.grpc?.ignore, [call], this.options.grpc, this.logger, "grpc")) {
|
|
372
|
+
return done();
|
|
373
|
+
}
|
|
374
|
+
const shouldCapture = this.traceSamplerService.shouldCapture("grpc", {
|
|
375
|
+
call,
|
|
208
376
|
});
|
|
377
|
+
if (!shouldCapture) {
|
|
378
|
+
return done();
|
|
379
|
+
}
|
|
380
|
+
this.operationTraceRegistry.startTrace(registryKey, {
|
|
381
|
+
protocol: this.toProtocolName(transportId),
|
|
382
|
+
operationId: call.operationId,
|
|
383
|
+
tags: this.options.grpc?.tags,
|
|
384
|
+
}, traceId, traceContext);
|
|
385
|
+
return done();
|
|
209
386
|
});
|
|
210
387
|
}
|
|
211
388
|
endRpcRequestTracing(transportId, ctx) {
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
389
|
+
// The key this context was started under, wherever its reply stream
|
|
390
|
+
// ended. The store answers only for a context no key could be kept by:
|
|
391
|
+
// a gRPC call with no request message of its own, as a client stream has
|
|
392
|
+
// none.
|
|
393
|
+
endOperation((typeof ctx === "object" && ctx !== null
|
|
394
|
+
? this.operations.get(ctx)
|
|
395
|
+
: undefined) ??
|
|
396
|
+
this.asyncLocalStorage
|
|
397
|
+
.getStore()
|
|
398
|
+
?.get(OPERATION_STATE_KEY));
|
|
399
|
+
const registryKey = (typeof ctx === "object" && ctx !== null
|
|
400
|
+
? this.registryKeys.get(ctx)
|
|
401
|
+
: undefined) ??
|
|
402
|
+
this.asyncLocalStorage.getStore()?.get(TRACE_REGISTRY_KEY);
|
|
217
403
|
if (typeof registryKey !== "string" ||
|
|
218
404
|
!this.operationTraceRegistry.hasTrace(registryKey)) {
|
|
219
405
|
return;
|
|
@@ -237,15 +423,73 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
237
423
|
this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
|
|
238
424
|
}, this.logger, isGrpc ? "grpc" : "rpc", () => this.operationTraceRegistry.hasOpenSpans(registryKey));
|
|
239
425
|
}
|
|
240
|
-
|
|
426
|
+
/**
|
|
427
|
+
* Keeps `registryKey` for the end hook to find by `ctx`. A custom
|
|
428
|
+
* transporter delivers a context of its own making, and a gRPC call need not
|
|
429
|
+
* carry a request message: what cannot key a `WeakMap` is left to the store.
|
|
430
|
+
*/
|
|
431
|
+
rememberRegistryKey(ctx, registryKey) {
|
|
432
|
+
if (typeof ctx === "object" && ctx !== null) {
|
|
433
|
+
this.registryKeys.set(ctx, registryKey);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
/** As `rememberRegistryKey`, for the operation the end hook ends. */
|
|
437
|
+
rememberOperation(ctx, operation) {
|
|
438
|
+
if (typeof ctx === "object" && ctx !== null) {
|
|
439
|
+
this.operations.set(ctx, operation);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* The route a message's handler is registered under, for the pattern or
|
|
444
|
+
* topic as its sender wrote it. Nest parses a pattern that is JSON and finds
|
|
445
|
+
* the handler by the normalised outcome, so one handler answers to any
|
|
446
|
+
* number of texts - other whitespace, an escape, a key given twice. Named by
|
|
447
|
+
* the text, each was an operation of the sender's choosing, and a route an
|
|
448
|
+
* `@Objective` on the handler was declared for anew.
|
|
449
|
+
*
|
|
450
|
+
* The route is taken only where the server finds that route's handler for
|
|
451
|
+
* the text: a handler reached through a wildcard keeps the text it was
|
|
452
|
+
* reached on, and so does anything the server cannot be asked about.
|
|
453
|
+
*/
|
|
454
|
+
toRoute(text, target) {
|
|
455
|
+
if (!target) {
|
|
456
|
+
return text;
|
|
457
|
+
}
|
|
458
|
+
try {
|
|
459
|
+
const handlers = target.getHandlers();
|
|
460
|
+
// What a Nest client sends: the route itself. One lookup, no parse.
|
|
461
|
+
if (handlers.has(text)) {
|
|
462
|
+
return text;
|
|
463
|
+
}
|
|
464
|
+
// Protected in Nest's typings, so read by shape.
|
|
465
|
+
const route = target.getRouteFromPattern?.(text);
|
|
466
|
+
if (typeof route !== "string" || route === text) {
|
|
467
|
+
return text;
|
|
468
|
+
}
|
|
469
|
+
const handler = handlers.get(route);
|
|
470
|
+
return handler !== undefined &&
|
|
471
|
+
handler === target.getHandlerByPattern(text)
|
|
472
|
+
? route
|
|
473
|
+
: text;
|
|
474
|
+
}
|
|
475
|
+
catch {
|
|
476
|
+
return text;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* Kafka, MQTT, RabbitMQ and TCP find a message's handler by the text its
|
|
481
|
+
* context carries - see `toRoute`. NATS and Redis find it by the
|
|
482
|
+
* subscription the message came in on.
|
|
483
|
+
*/
|
|
484
|
+
getOperationIdFromContext(ctx, target) {
|
|
241
485
|
const { KafkaContext, MqttContext, NatsContext, RedisContext, RmqContext, TcpContext, } = this.microservices;
|
|
242
486
|
switch (true) {
|
|
243
487
|
case ctx instanceof KafkaContext:
|
|
244
488
|
case ctx instanceof MqttContext:
|
|
245
|
-
return ctx.getTopic();
|
|
489
|
+
return this.toRoute(ctx.getTopic(), target);
|
|
246
490
|
case ctx instanceof RmqContext:
|
|
247
491
|
case ctx instanceof TcpContext:
|
|
248
|
-
return ctx.getPattern();
|
|
492
|
+
return this.toRoute(ctx.getPattern(), target);
|
|
249
493
|
case ctx instanceof RedisContext:
|
|
250
494
|
return ctx.getChannel();
|
|
251
495
|
case ctx instanceof NatsContext:
|
|
@@ -255,8 +499,10 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
255
499
|
// `toProtocolName` - and there is no universal accessor for its
|
|
256
500
|
// routing key. Throwing here would fail the message before `done()`
|
|
257
501
|
// ever ran, so fall back to a conventional accessor when one exists.
|
|
258
|
-
const pattern = ctx
|
|
259
|
-
return typeof pattern === "string"
|
|
502
|
+
const pattern = readContextAccessor(ctx, "getPattern");
|
|
503
|
+
return typeof pattern === "string"
|
|
504
|
+
? this.toRoute(pattern, target)
|
|
505
|
+
: "unknown";
|
|
260
506
|
}
|
|
261
507
|
}
|
|
262
508
|
}
|
|
@@ -270,6 +516,40 @@ RpcObserveAgentService = RpcObserveAgentService_1 = __decorate([
|
|
|
270
516
|
TraceSamplerService])
|
|
271
517
|
], RpcObserveAgentService);
|
|
272
518
|
export { RpcObserveAgentService };
|
|
519
|
+
/**
|
|
520
|
+
* The start hook the server is given: the application's outside, and the
|
|
521
|
+
* agent's inside the `done` it is handed, returning what the application's
|
|
522
|
+
* returns. The application's hook decides whether a message is handled at
|
|
523
|
+
* all, and the agent opens a trace only once it is: one the application
|
|
524
|
+
* refuses by never calling `done` leaves nothing behind, where the other way
|
|
525
|
+
* round each would leave a trace open in the registry.
|
|
526
|
+
*/
|
|
527
|
+
function composeStartHook(application, agent) {
|
|
528
|
+
if (!application) {
|
|
529
|
+
return agent;
|
|
530
|
+
}
|
|
531
|
+
return function (transportId, ctx, done) {
|
|
532
|
+
return application.call(this, transportId, ctx, () => agent.call(this, transportId, ctx, done));
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
/**
|
|
536
|
+
* The end hook the server is given: the agent's first, inside the
|
|
537
|
+
* application's as its start hook is, then the application's whatever the
|
|
538
|
+
* agent's did.
|
|
539
|
+
*/
|
|
540
|
+
function composeEndHook(application, agent) {
|
|
541
|
+
if (!application) {
|
|
542
|
+
return agent;
|
|
543
|
+
}
|
|
544
|
+
return function (transportId, ctx) {
|
|
545
|
+
try {
|
|
546
|
+
agent.call(this, transportId, ctx);
|
|
547
|
+
}
|
|
548
|
+
finally {
|
|
549
|
+
application.call(this, transportId, ctx);
|
|
550
|
+
}
|
|
551
|
+
};
|
|
552
|
+
}
|
|
273
553
|
/**
|
|
274
554
|
* The `traceparent` the sending service's agent put in the packet's metadata
|
|
275
555
|
* beside `x-request-id` - see `traceparentToHandOn` - on a transport whose
|
|
@@ -279,11 +559,7 @@ export { RpcObserveAgentService };
|
|
|
279
559
|
*/
|
|
280
560
|
function handedOnTraceparent(ctx) {
|
|
281
561
|
try {
|
|
282
|
-
const
|
|
283
|
-
if (typeof getMetadata !== "function") {
|
|
284
|
-
return undefined;
|
|
285
|
-
}
|
|
286
|
-
const metadata = getMetadata.call(ctx);
|
|
562
|
+
const metadata = readContextAccessor(ctx, "getMetadata");
|
|
287
563
|
return metadata?.["traceparent"];
|
|
288
564
|
}
|
|
289
565
|
catch {
|
|
@@ -11,7 +11,8 @@ import { KeyOf } from "../types/key-of.type.js";
|
|
|
11
11
|
* processing hooks, so the one place every `@SubscribeMessage()` handler
|
|
12
12
|
* passes through is patched instead: `WsContextCreator.create`, which builds
|
|
13
13
|
* the guards-pipes-interceptors-handler chain for a message. Wrapping what it
|
|
14
|
-
* returns
|
|
14
|
+
* returns, and subscribing to the stream it resolves to in the same store,
|
|
15
|
+
* puts the whole chain inside the trace, whichever platform adapter -
|
|
15
16
|
* socket.io, ws - delivers the message.
|
|
16
17
|
*/
|
|
17
18
|
export declare class WsObserveAgentService<Store extends Record<string, unknown>> {
|
|
@@ -21,19 +22,68 @@ export declare class WsObserveAgentService<Store extends Record<string, unknown>
|
|
|
21
22
|
private readonly traceSamplerService;
|
|
22
23
|
private readonly asyncLocalStorage;
|
|
23
24
|
private readonly logger;
|
|
25
|
+
private readonly tracesByClient;
|
|
26
|
+
private readonly standIns;
|
|
24
27
|
constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, traceSamplerService: TraceSamplerService, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>);
|
|
25
28
|
private loadContextCreator;
|
|
26
29
|
private patchContextCreator;
|
|
27
30
|
/**
|
|
31
|
+
* The handler Nest is given for a `@SubscribeMessage()` method: the same
|
|
32
|
+
* method, called through the instance, telling the message when it runs.
|
|
33
|
+
*
|
|
28
34
|
* Nest reads a gateway's handlers off the class prototype and applies them
|
|
29
35
|
* to the instance, which steps around the instrumentation proxy - the one
|
|
30
36
|
* method of the whole chain that would go unrecorded is the handler itself,
|
|
31
37
|
* and a handler that throws before calling anything leaves no span at all.
|
|
38
|
+
* The stand-in calls the same method through the instance instead.
|
|
39
|
+
*
|
|
40
|
+
* Behind an interceptor, the chain is cold: Nest's proxy resolves to a
|
|
41
|
+
* stream once the guards have run, and the interceptors, the pipes and the
|
|
42
|
+
* handler run only when the adapter subscribes to it. The stand-in marks
|
|
43
|
+
* the message's state when it is called, so the trace can tell which of
|
|
44
|
+
* the two it was handed, and ends that trace when the handler returns a
|
|
45
|
+
* stream of its own.
|
|
46
|
+
*
|
|
47
|
+
* Guards, pipes, filters and the message pattern are all looked up as
|
|
48
|
+
* metadata on the callback, so that metadata is carried over - once per
|
|
49
|
+
* method, since on a request-scoped path `create` runs for every message.
|
|
50
|
+
*/
|
|
51
|
+
private standInFor;
|
|
52
|
+
/**
|
|
53
|
+
* Drops a message's trace when its client goes away before the handler
|
|
54
|
+
* settles, and returns what stops watching for that once the trace ends.
|
|
32
55
|
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
56
|
+
* A handler waiting on its client - an acknowledgement without a timeout,
|
|
57
|
+
* the client's next frame - never settles once the client has gone, and
|
|
58
|
+
* nothing else would end its trace: every client that hung up on one left
|
|
59
|
+
* its snapshot registered for the life of the process, and a client that
|
|
60
|
+
* reconnects can leave as many as it likes.
|
|
61
|
+
*
|
|
62
|
+
* One listener per client, however many messages it has in flight, on the
|
|
63
|
+
* events Nest's adapters stop a client's messages at: socket.io's
|
|
64
|
+
* `disconnect`, `ws`' `close`. Dropped at once, as the HTTP agent drops an
|
|
65
|
+
* aborted request: an abandoned trace is never reported, and the registry
|
|
66
|
+
* lets a handler that outlives its client end its spans on a trace that is
|
|
67
|
+
* gone. A client that is no event emitter - a custom adapter's - is not
|
|
68
|
+
* watched.
|
|
36
69
|
*/
|
|
37
|
-
private
|
|
70
|
+
private abandonWhenClientLeaves;
|
|
38
71
|
private traceMessage;
|
|
72
|
+
/**
|
|
73
|
+
* The chain's stream, subscribed in the message's store.
|
|
74
|
+
*
|
|
75
|
+
* Nest's adapters subscribe to what the chain resolves to from the socket's
|
|
76
|
+
* own events, outside the store the message was started in. Behind an
|
|
77
|
+
* interceptor that stream is all of the chain past the guards - the
|
|
78
|
+
* interceptors, the pipes, the handler, the exception filter - and for a
|
|
79
|
+
* handler that returns a stream, the stream and the filter its error goes
|
|
80
|
+
* to. Run without the store, they were missing from the trace, and
|
|
81
|
+
* `TracerService` failed in them.
|
|
82
|
+
*
|
|
83
|
+
* `end` is called at the stream's first value, error or completion, and
|
|
84
|
+
* `abandon` when the subscription is torn down before any: Nest's adapters
|
|
85
|
+
* unsubscribe a client's messages when it disconnects. Both are no-ops once
|
|
86
|
+
* either has run.
|
|
87
|
+
*/
|
|
88
|
+
private subscribeInStore;
|
|
39
89
|
}
|