@nestjs/observe 0.3.26 → 0.3.28
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 +38 -2
- package/dist/agent/observe-agent.shared-buffer.js +5 -0
- package/dist/agent/telemetry-wire-contract.js +3 -3
- package/dist/cli/link.js +24 -2
- package/dist/cli/package-manager.d.ts +6 -0
- package/dist/cli/package-manager.js +60 -3
- package/dist/cli/project-files.d.ts +25 -5
- package/dist/cli/project-files.js +98 -15
- package/dist/custom-metrics/summary.js +17 -10
- package/dist/instrument/create-instance-decorator.instrument.js +390 -38
- 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 +14 -5
- package/dist/otlp/otlp-span.mapper.d.ts +2 -0
- package/dist/otlp/otlp-span.mapper.js +19 -1
- package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
- package/dist/otlp/otlp-trace-exporter.service.js +232 -38
- package/dist/outgoing/http.integration.js +36 -11
- package/dist/outgoing/mongodb.integration.d.ts +3 -1
- package/dist/outgoing/mongodb.integration.js +93 -18
- package/dist/outgoing/mssql.integration.js +9 -4
- package/dist/outgoing/mysql2.integration.js +3 -1
- package/dist/outgoing/outgoing-observe-agent.service.js +5 -1
- package/dist/outgoing/pg.integration.js +5 -0
- package/dist/outgoing/sql-statement.util.js +36 -10
- package/dist/protocols/bull-observe-agent.service.js +21 -0
- package/dist/protocols/deferred-trace-completion.d.ts +8 -2
- package/dist/protocols/deferred-trace-completion.js +40 -3
- package/dist/protocols/graphql-observe-agent.service.d.ts +62 -2
- package/dist/protocols/graphql-observe-agent.service.js +188 -14
- package/dist/protocols/graphql-operation-parser.js +45 -14
- package/dist/protocols/http-observe-agent.service.d.ts +14 -7
- package/dist/protocols/http-observe-agent.service.js +57 -14
- package/dist/protocols/job-trace-runner.d.ts +7 -0
- package/dist/protocols/job-trace-runner.js +72 -8
- package/dist/protocols/rpc-observe-agent.service.d.ts +61 -0
- package/dist/protocols/rpc-observe-agent.service.js +146 -10
- package/dist/protocols/ws-observe-agent.service.js +1 -1
- package/dist/services/logger-patcher.service.js +13 -3
- package/dist/services/operation-trace.registry.d.ts +13 -0
- package/dist/services/operation-trace.registry.js +195 -65
- package/dist/services/stdout-forwarder.service.js +22 -2
- package/dist/services/tracer.service.d.ts +19 -14
- package/dist/services/tracer.service.js +57 -34
- package/dist/utils/capture-request.util.js +36 -8
- 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/log-line.parser.d.ts +8 -0
- package/dist/utils/log-line.parser.js +13 -4
- package/dist/utils/log-redactor.js +184 -10
- package/dist/utils/redact-url-query.d.ts +16 -5
- package/dist/utils/redact-url-query.js +20 -7
- package/dist/utils/source-context.util.d.ts +6 -0
- package/dist/utils/source-context.util.js +68 -33
- package/dist/utils/source-map-resolver.util.js +25 -4
- package/dist/utils/store-copy.util.d.ts +10 -0
- package/dist/utils/store-copy.util.js +43 -0
- package/package.json +4 -3
|
@@ -48,6 +48,10 @@ function isDateTimestamp(value) {
|
|
|
48
48
|
}
|
|
49
49
|
const ORIGINAL_ADD = Symbol.for("nestjs.observe.queue.add");
|
|
50
50
|
const ORIGINAL_ADD_BULK = Symbol.for("nestjs.observe.queue.addBulk");
|
|
51
|
+
/** What Bull and BullMQ read by name off an entry handed to `addBulk`. */
|
|
52
|
+
const BULK_ENTRY_KEYS_READ_BY_NAME = ["name", "data"];
|
|
53
|
+
/** What they read by name off a job's options; the rest they spread. */
|
|
54
|
+
const JOB_OPTION_KEYS_READ_BY_NAME = ["jobId", "telemetry"];
|
|
51
55
|
/** Where a run records which job it is running, for a layer nested inside it. */
|
|
52
56
|
const ACTIVE_JOB_KEY = Symbol("nestjs.observe.activeJob");
|
|
53
57
|
/**
|
|
@@ -67,6 +71,41 @@ function parkOriginal(prototype, key, method) {
|
|
|
67
71
|
}
|
|
68
72
|
return prototype[key];
|
|
69
73
|
}
|
|
74
|
+
/**
|
|
75
|
+
* Lets a driver read off `copy` what it would have read off `source`, the
|
|
76
|
+
* object the caller passed and the copy stands in for.
|
|
77
|
+
*
|
|
78
|
+
* A spread copies own enumerable properties, and the drivers read a few -
|
|
79
|
+
* `keys` - by name instead, which reaches what the caller keeps elsewhere
|
|
80
|
+
* too: an accessor on the prototype of a job class, an options class or an
|
|
81
|
+
* ODM document. A job whose `data` was a getter ran with `{}`, and options
|
|
82
|
+
* whose `jobId` was one enqueued the job again on every call instead of
|
|
83
|
+
* finding it. Each such key the spread left behind is read through to
|
|
84
|
+
* `source`, as the driver would have read it, and kept off the copy's own
|
|
85
|
+
* enumerable properties, so a spread the driver takes of the copy leaves it
|
|
86
|
+
* behind as a spread of `source` would have.
|
|
87
|
+
*/
|
|
88
|
+
function readableByName(copy, source, keys) {
|
|
89
|
+
for (const key of keys) {
|
|
90
|
+
if (Object.prototype.hasOwnProperty.call(copy, key) || !(key in source)) {
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
Object.defineProperty(copy, key, {
|
|
94
|
+
get: () => source[key],
|
|
95
|
+
set(value) {
|
|
96
|
+
Object.defineProperty(this, key, {
|
|
97
|
+
value,
|
|
98
|
+
writable: true,
|
|
99
|
+
enumerable: true,
|
|
100
|
+
configurable: true,
|
|
101
|
+
});
|
|
102
|
+
},
|
|
103
|
+
enumerable: false,
|
|
104
|
+
configurable: true,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
return copy;
|
|
108
|
+
}
|
|
70
109
|
function isSameJob(outer, job) {
|
|
71
110
|
const active = outer;
|
|
72
111
|
return active?.queueName === job.queueName && active.id === job.id;
|
|
@@ -121,8 +160,15 @@ export class JobTraceRunner {
|
|
|
121
160
|
return originalAddBulk.call(this, jobs);
|
|
122
161
|
}
|
|
123
162
|
return originalAddBulk.call(this, jobs.map((job) => {
|
|
124
|
-
|
|
125
|
-
|
|
163
|
+
// What is no job is the driver's to refuse, as it does without
|
|
164
|
+
// the agent: stamped, a null entry became an empty job.
|
|
165
|
+
if (typeof job !== "object" || job === null) {
|
|
166
|
+
return job;
|
|
167
|
+
}
|
|
168
|
+
const stamped = stamp(job.opts);
|
|
169
|
+
return stamped
|
|
170
|
+
? readableByName({ ...job, opts: stamped }, job, BULK_ENTRY_KEYS_READ_BY_NAME)
|
|
171
|
+
: job;
|
|
126
172
|
}));
|
|
127
173
|
};
|
|
128
174
|
}
|
|
@@ -155,10 +201,7 @@ export class JobTraceRunner {
|
|
|
155
201
|
if (current["repeat"] || current[JOB_TRACE_OPTION_KEY] !== undefined) {
|
|
156
202
|
return undefined;
|
|
157
203
|
}
|
|
158
|
-
const stamped = {
|
|
159
|
-
...current,
|
|
160
|
-
[JOB_TRACE_OPTION_KEY]: traceId,
|
|
161
|
-
};
|
|
204
|
+
const stamped = readableByName({ ...current, [JOB_TRACE_OPTION_KEY]: traceId }, current, JOB_OPTION_KEYS_READ_BY_NAME);
|
|
162
205
|
if (this.openTelemetryInteropOn() &&
|
|
163
206
|
current[JOB_TRACE_CONTEXT_OPTION_KEY] === undefined) {
|
|
164
207
|
stamped[JOB_TRACE_CONTEXT_OPTION_KEY] = traceparentToHandOn(store, traceId);
|
|
@@ -276,7 +319,7 @@ export class JobTraceRunner {
|
|
|
276
319
|
name: job.name,
|
|
277
320
|
id: typeof job.id === "number" ? `${job.id}` : job.id,
|
|
278
321
|
};
|
|
279
|
-
setAttributesSafely(this.options.jobs?.setAttributes, [context], this.options.jobs, store, this.logger, "jobs");
|
|
322
|
+
setAttributesSafely(this.options.jobs?.setAttributes, [context], this.options.jobs, store, this.logger, "jobs", this.options.traceIdKey);
|
|
280
323
|
if (this.isIgnored(context)) {
|
|
281
324
|
// The trace id stays in the store so logs and jobs enqueued from here
|
|
282
325
|
// still correlate; nothing is registered under the registry key, so
|
|
@@ -314,15 +357,27 @@ export class JobTraceRunner {
|
|
|
314
357
|
// The promise a callback-style handler returned, which its driver
|
|
315
358
|
// drops - see where it is handed back, below.
|
|
316
359
|
let dropped;
|
|
360
|
+
let completed = false;
|
|
361
|
+
let deadline;
|
|
317
362
|
const settle = (status) => {
|
|
318
363
|
if (outcome) {
|
|
319
364
|
return;
|
|
320
365
|
}
|
|
321
366
|
outcome = status;
|
|
322
|
-
endOperation(operation);
|
|
323
367
|
if (status === "failed") {
|
|
324
368
|
dropped?.then(undefined, ignoreRejection);
|
|
325
369
|
}
|
|
370
|
+
complete(status);
|
|
371
|
+
};
|
|
372
|
+
// Apart from `settle`, which is the handler's: the deadline ends the
|
|
373
|
+
// run, not what its handler reports later.
|
|
374
|
+
const complete = (status) => {
|
|
375
|
+
if (completed) {
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
completed = true;
|
|
379
|
+
clearTimeout(deadline);
|
|
380
|
+
endOperation(operation);
|
|
326
381
|
deferTraceCompletion(async () => {
|
|
327
382
|
this.operationTraceRegistry.endTrace(registryKey, { status });
|
|
328
383
|
const snapshot = (await this.operationTraceRegistry.pluckSnapshot(registryKey));
|
|
@@ -344,6 +399,15 @@ export class JobTraceRunner {
|
|
|
344
399
|
const returnValue = handedOn === undefined
|
|
345
400
|
? invoke(settle)
|
|
346
401
|
: continueHandedOnTrace(handedOn, traceId, () => invoke(settle));
|
|
402
|
+
// Armed as the driver arms its own, once the handler has returned:
|
|
403
|
+
// Bull fails a job past its `timeout` and takes the next one, and a
|
|
404
|
+
// handler that never finishes left its trace in the registry for the
|
|
405
|
+
// life of the process, one per job, never reported. Unref'd, as it
|
|
406
|
+
// must not keep a worker alive that is done otherwise.
|
|
407
|
+
if (job.timeout !== undefined && !completed) {
|
|
408
|
+
deadline = setTimeout(() => complete("failed"), job.timeout);
|
|
409
|
+
deadline.unref?.();
|
|
410
|
+
}
|
|
347
411
|
if (returnValue instanceof Promise) {
|
|
348
412
|
// Handed back as the handler returned it, never as a promise
|
|
349
413
|
// chained onto it: a chained promise has none of the members of the
|
|
@@ -38,6 +38,13 @@ export declare class RpcObserveAgentService<Store extends Record<string, unknown
|
|
|
38
38
|
private readonly registryKeys;
|
|
39
39
|
/** The operation each context was started for - see `rememberOperation`. */
|
|
40
40
|
private readonly operations;
|
|
41
|
+
/**
|
|
42
|
+
* The gRPC calls of a request stream, by their metadata - see
|
|
43
|
+
* `rememberGrpcCalls`.
|
|
44
|
+
*/
|
|
45
|
+
private readonly grpcCalls;
|
|
46
|
+
/** The gRPC servers whose calls `rememberGrpcCalls` already notes. */
|
|
47
|
+
private readonly grpcServers;
|
|
41
48
|
constructor(asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>, options: ObserveModuleOptionsWithDefaults, modulesContainer: ModulesContainer, operationTraceRegistry: OperationTraceRegistry, observeAgentSharedBuffer: ObserveAgentSharedBuffer, traceSamplerService: TraceSamplerService);
|
|
42
49
|
onModuleDestroy(): void;
|
|
43
50
|
/**
|
|
@@ -53,6 +60,60 @@ export declare class RpcObserveAgentService<Store extends Record<string, unknown
|
|
|
53
60
|
* sets on it - see `composeStartHook`.
|
|
54
61
|
*/
|
|
55
62
|
registerRpcHooks(target: Server): void;
|
|
63
|
+
/**
|
|
64
|
+
* Notes each call of a gRPC request stream by its metadata, for
|
|
65
|
+
* `startGrpcRequestTracing` to find the call itself by.
|
|
66
|
+
*
|
|
67
|
+
* The start hook is handed a copy of the call, its fields spread onto a new
|
|
68
|
+
* object (`{ ...call }`), and a copy emits nothing: the messages of the
|
|
69
|
+
* request stream are emitted on the call. The copy shares the call's
|
|
70
|
+
* `metadata`, so the call is kept by that, from the method grpc-js runs for
|
|
71
|
+
* it - the only place the call itself passes before the hook. That method
|
|
72
|
+
* is built by `createServiceMethod`, wrapped here on this server alone as
|
|
73
|
+
* Nest calls it once per method when the server starts to listen, after
|
|
74
|
+
* this hook was set. Unary and server-streaming calls are left alone: they
|
|
75
|
+
* have no later messages to run anywhere. A server without the method keeps
|
|
76
|
+
* its calls' events where grpc-js emits them.
|
|
77
|
+
*/
|
|
78
|
+
private rememberGrpcCalls;
|
|
79
|
+
/** The call `ctx` is a copy of, if `rememberGrpcCalls` noted it. */
|
|
80
|
+
private takeGrpcCall;
|
|
81
|
+
/**
|
|
82
|
+
* Drops the trace of a `@GrpcStreamCall` call that is cancelled while its
|
|
83
|
+
* handler is still running, as the HTTP agent drops an aborted request's.
|
|
84
|
+
*
|
|
85
|
+
* Nest ends a call's operation when its handler settles, and for a
|
|
86
|
+
* `@GrpcStreamCall` handler it waits on that alone. On a deadline or a
|
|
87
|
+
* client's cancellation grpc-js emits `cancelled` and destroys the stream,
|
|
88
|
+
* with no `end` and no `error`, so a handler that waits for either never
|
|
89
|
+
* settles: its trace stayed in the registry for the life of the process,
|
|
90
|
+
* one per call, and was never reported. Unary and `@GrpcStreamMethod` calls
|
|
91
|
+
* are left to Nest, which ends them on `cancelled` itself.
|
|
92
|
+
*
|
|
93
|
+
* Dropped a turn after `cancelled`, not at once: a handler that settles on
|
|
94
|
+
* it is ended by Nest, from microtasks, before then, and reported as ever.
|
|
95
|
+
* One that settles later outlived its client, and the registry already
|
|
96
|
+
* lets it end its spans on a trace that is gone.
|
|
97
|
+
*/
|
|
98
|
+
private dropTraceOnCancel;
|
|
99
|
+
/**
|
|
100
|
+
* Runs the events of a gRPC request stream in the call's store.
|
|
101
|
+
*
|
|
102
|
+
* A listener runs in the async context of whatever emits its event. The
|
|
103
|
+
* messages already queued when the handler subscribes are emitted from
|
|
104
|
+
* within `done`, inside the store; every later one from grpc-js's callback
|
|
105
|
+
* on the HTTP/2 stream, which belongs to the connection and has no store.
|
|
106
|
+
* So the second message of an ordinary stream was handled outside its call:
|
|
107
|
+
* no spans, no trace id on its log lines, and `TracerService.createSpan()`
|
|
108
|
+
* threw - a status 2 for a `@GrpcStreamMethod` handler, and for a
|
|
109
|
+
* `@GrpcStreamCall` handler's `data` listener an uncaught rejection that
|
|
110
|
+
* ended the process.
|
|
111
|
+
*
|
|
112
|
+
* An event emitted from within the call - a span of it writing to the
|
|
113
|
+
* stream - keeps the context it is emitted in, the span's, which carries
|
|
114
|
+
* the call's key.
|
|
115
|
+
*/
|
|
116
|
+
private emitCallEventsInStore;
|
|
56
117
|
/**
|
|
57
118
|
* Names the transport for the snapshot's `protocol` field.
|
|
58
119
|
*
|
|
@@ -18,6 +18,7 @@ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.j
|
|
|
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,6 +26,12 @@ import { setAgentHook } from "../utils/shared-hook-slot.util.js";
|
|
|
25
26
|
import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
|
|
26
27
|
import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
|
|
27
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");
|
|
28
35
|
let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentService {
|
|
29
36
|
asyncLocalStorage;
|
|
30
37
|
options;
|
|
@@ -51,6 +58,13 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
51
58
|
registryKeys = new WeakMap();
|
|
52
59
|
/** The operation each context was started for - see `rememberOperation`. */
|
|
53
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();
|
|
54
68
|
constructor(asyncLocalStorage, options, modulesContainer, operationTraceRegistry, observeAgentSharedBuffer, traceSamplerService) {
|
|
55
69
|
this.asyncLocalStorage = asyncLocalStorage;
|
|
56
70
|
this.options = options;
|
|
@@ -116,11 +130,129 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
116
130
|
if (transportId === this.microservices.Transport.GRPC) {
|
|
117
131
|
return this.startGrpcRequestTracing(transportId, ctx, done);
|
|
118
132
|
}
|
|
119
|
-
return this.startRpcRequestTracing(transportId, ctx, done, target);
|
|
133
|
+
return this.startRpcRequestTracing(transportId ?? UNNAMED_TRANSPORT, ctx, done, target);
|
|
120
134
|
}, composeStartHook);
|
|
121
135
|
setAgentHook(target, "setOnProcessingEndHook", (transportId, ctx) => {
|
|
122
|
-
this.endRpcRequestTracing(transportId, ctx);
|
|
136
|
+
this.endRpcRequestTracing(transportId ?? UNNAMED_TRANSPORT, ctx);
|
|
123
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
|
+
};
|
|
124
256
|
}
|
|
125
257
|
/**
|
|
126
258
|
* Names the transport for the snapshot's `protocol` field.
|
|
@@ -167,7 +299,7 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
167
299
|
if (traceContext) {
|
|
168
300
|
store.set(TRACE_CONTEXT_KEY, traceContext);
|
|
169
301
|
}
|
|
170
|
-
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);
|
|
171
303
|
if (shouldIgnoreSafely(this.options.rpc?.ignore, [transportId, ctx], this.options.rpc, this.logger, "rpc")) {
|
|
172
304
|
return handle();
|
|
173
305
|
}
|
|
@@ -210,6 +342,14 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
210
342
|
const operation = openOperation(store);
|
|
211
343
|
this.rememberOperation(call, operation);
|
|
212
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
|
+
}
|
|
213
353
|
// As for a message: the call's span goes under the caller's for `otlp`,
|
|
214
354
|
// and the calls the handler makes carry its decision on. Read now, while
|
|
215
355
|
// the span a gRPC instrumentation opened for the call is the active one.
|
|
@@ -221,7 +361,7 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
221
361
|
if (traceContext) {
|
|
222
362
|
store.set(TRACE_CONTEXT_KEY, traceContext);
|
|
223
363
|
}
|
|
224
|
-
setAttributesSafely(this.options.grpc?.setAttributes, [call], this.options.grpc, store, this.logger, "grpc");
|
|
364
|
+
setAttributesSafely(this.options.grpc?.setAttributes, [call], this.options.grpc, store, this.logger, "grpc", this.options.traceIdKey);
|
|
225
365
|
// `done` runs before the hook returns, as for any other transport. Nest
|
|
226
366
|
// listens for the call's `cancelled` and `end` events inside it, and
|
|
227
367
|
// grpc-js emits `cancelled` once: run from a timer, a call cancelled or
|
|
@@ -359,7 +499,7 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
359
499
|
// `toProtocolName` - and there is no universal accessor for its
|
|
360
500
|
// routing key. Throwing here would fail the message before `done()`
|
|
361
501
|
// ever ran, so fall back to a conventional accessor when one exists.
|
|
362
|
-
const pattern = ctx
|
|
502
|
+
const pattern = readContextAccessor(ctx, "getPattern");
|
|
363
503
|
return typeof pattern === "string"
|
|
364
504
|
? this.toRoute(pattern, target)
|
|
365
505
|
: "unknown";
|
|
@@ -419,11 +559,7 @@ function composeEndHook(application, agent) {
|
|
|
419
559
|
*/
|
|
420
560
|
function handedOnTraceparent(ctx) {
|
|
421
561
|
try {
|
|
422
|
-
const
|
|
423
|
-
if (typeof getMetadata !== "function") {
|
|
424
|
-
return undefined;
|
|
425
|
-
}
|
|
426
|
-
const metadata = getMetadata.call(ctx);
|
|
562
|
+
const metadata = readContextAccessor(ctx, "getMetadata");
|
|
427
563
|
return metadata?.["traceparent"];
|
|
428
564
|
}
|
|
429
565
|
catch {
|
|
@@ -219,7 +219,7 @@ let WsObserveAgentService = WsObserveAgentService_1 = class WsObserveAgentServic
|
|
|
219
219
|
// Ended with the message's trace, or as an untraced message settles:
|
|
220
220
|
// see `liveTraceId`.
|
|
221
221
|
const operation = openOperation(store);
|
|
222
|
-
setAttributesSafely(this.options.ws?.setAttributes, [message], this.options.ws, store, this.logger, "ws");
|
|
222
|
+
setAttributesSafely(this.options.ws?.setAttributes, [message], this.options.ws, store, this.logger, "ws", this.options.traceIdKey);
|
|
223
223
|
if (shouldIgnoreSafely(this.options.ws?.ignore, [message], this.options.ws, this.logger, "ws") ||
|
|
224
224
|
!this.traceSamplerService.shouldCapture("ws", {
|
|
225
225
|
gateway: message.gateway,
|
|
@@ -77,11 +77,21 @@ let LoggerPatcherService = LoggerPatcherService_1 = class LoggerPatcherService {
|
|
|
77
77
|
// it, the id lands on a line of its own - which the stdout forwarder
|
|
78
78
|
// then ships as a separate, level-less entry, and the parser (which
|
|
79
79
|
// reads the id off the end of the log line) never sees it.
|
|
80
|
+
//
|
|
81
|
+
// Before the first newline, not the last: a record can run to several
|
|
82
|
+
// lines - an error is its message and then its stack - and only the
|
|
83
|
+
// first carries the prefix the parser reads an id from. Put after the
|
|
84
|
+
// stack, the id was on no line that is read, and the first line ended
|
|
85
|
+
// with the error's message - whose own last words, `Trace ID: <id>`
|
|
86
|
+
// from a client's value, then named the trace the line was filed under.
|
|
80
87
|
const [logLevel] = args;
|
|
81
88
|
const suffix = ` Trace ID: ${this.colorize(requestId, logLevel)}`;
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
89
|
+
const newline = output.indexOf("\n");
|
|
90
|
+
if (newline === -1) {
|
|
91
|
+
return `${output}${suffix}`;
|
|
92
|
+
}
|
|
93
|
+
const lineEnd = output[newline - 1] === "\r" ? newline - 1 : newline;
|
|
94
|
+
return `${output.slice(0, lineEnd)}${suffix}${output.slice(lineEnd)}`;
|
|
85
95
|
};
|
|
86
96
|
// Add watermark to flag that the logger has been patched
|
|
87
97
|
Reflect.defineProperty(ConsoleLogger.prototype, this.patchedWatermark, {
|
|
@@ -51,6 +51,13 @@ export declare class OperationTraceRegistry {
|
|
|
51
51
|
* an error. See `endTrace` for what they decide.
|
|
52
52
|
*/
|
|
53
53
|
private readonly failedOutgoingRoots;
|
|
54
|
+
/**
|
|
55
|
+
* The status code each root span that threw stands for. An operation with
|
|
56
|
+
* several - the operations of a batched GraphQL request, side by side - is
|
|
57
|
+
* reported with the error of the first, and so with its status: the one
|
|
58
|
+
* the last to end set left a 500's error filed as a 401.
|
|
59
|
+
*/
|
|
60
|
+
private readonly rootErrorStatusCodes;
|
|
54
61
|
/**
|
|
55
62
|
* Applied to every tree as it is plucked. Defaults are live from
|
|
56
63
|
* construction rather than waiting for `configureSpanCollapse`, so a
|
|
@@ -131,6 +138,12 @@ export declare class OperationTraceRegistry {
|
|
|
131
138
|
* that span a moment to close. False for a trace that is not open at all.
|
|
132
139
|
*/
|
|
133
140
|
hasOpenSpans(traceId: TraceId): boolean;
|
|
141
|
+
/**
|
|
142
|
+
* Whether the trace's operation has been named yet - by the route the
|
|
143
|
+
* request was routed to, or by a GraphQL operation that labelled it. False
|
|
144
|
+
* for a trace that is not open.
|
|
145
|
+
*/
|
|
146
|
+
hasOperationId(traceId: TraceId): boolean;
|
|
134
147
|
startTrace(traceId: TraceId, data: Omit<RequestSnapshot, "traces" | "startTimestamp" | "calledAt" | "traceId"> | Omit<JobSnapshot, "duration">,
|
|
135
148
|
/**
|
|
136
149
|
* The trace id the snapshot reports under, when it is not the registry
|