@nestjs/observe 0.3.2 → 0.3.3
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 +39 -2
- package/dist/.tsbuildinfo +1 -1
- package/dist/interfaces/observe-options.interface.d.ts +62 -0
- package/dist/observe.module.js +4 -1
- package/dist/protocols/job-trace-runner.d.ts +9 -3
- package/dist/protocols/job-trace-runner.js +53 -9
- package/dist/protocols/queue-observe-agent.service.d.ts +34 -0
- package/dist/protocols/queue-observe-agent.service.js +92 -7
- package/dist/protocols/rpc-observe-agent.service.d.ts +2 -2
- package/dist/protocols/rpc-observe-agent.service.js +28 -23
- package/dist/services/operation-trace.registry.d.ts +25 -0
- package/dist/services/operation-trace.registry.js +54 -0
- package/dist/services/skip-spans.util.d.ts +14 -0
- package/dist/services/skip-spans.util.js +20 -0
- package/package.json +5 -1
|
@@ -270,6 +270,40 @@ export interface ObserveOptions {
|
|
|
270
270
|
*/
|
|
271
271
|
keepSlowest?: number;
|
|
272
272
|
};
|
|
273
|
+
/**
|
|
274
|
+
* Reports an operation without its spans when it ends with one of these
|
|
275
|
+
* status codes - or, given a function, whenever that function returns true.
|
|
276
|
+
*
|
|
277
|
+
* Meant for outcomes that are part of an application's ordinary control
|
|
278
|
+
* flow: a `NotFoundException` for a record that does not exist, a 401 for an
|
|
279
|
+
* expired token, a 400 from a `ValidationPipe`. Every span is a metered
|
|
280
|
+
* event, and the waterfall behind a request that was turned away on purpose
|
|
281
|
+
* is rarely one anybody opens.
|
|
282
|
+
*
|
|
283
|
+
* The operation itself is still reported - its route, status code, duration,
|
|
284
|
+
* user and error - so it stays in every chart and on the Errors page, stack
|
|
285
|
+
* included. What is left behind is the span tree underneath it, manual spans
|
|
286
|
+
* too: the waterfall shows the operation with nothing inside it, and the
|
|
287
|
+
* calls it made are missing from the per-method numbers. That tree is the
|
|
288
|
+
* saving - each of its nodes is an event, so a skipped operation costs its
|
|
289
|
+
* own event (plus its error's, when it failed with one) and nothing more.
|
|
290
|
+
*
|
|
291
|
+
* The status code is the one the operation is reported with. Transports
|
|
292
|
+
* without one of their own - microservices, gRPC, WebSocket gateways -
|
|
293
|
+
* carry a status only when the handler threw: a Nest exception's own 4xx,
|
|
294
|
+
* 500 for anything else. So `[404]` also skips the spans of a message
|
|
295
|
+
* handler that threw `NotFoundException`. Jobs always keep their spans.
|
|
296
|
+
*
|
|
297
|
+
* Decided once the operation has finished, since the outcome is not known
|
|
298
|
+
* before: spans are still recorded while it runs, and dropped before
|
|
299
|
+
* anything is serialized or sent. A function that throws is reported once
|
|
300
|
+
* and read as "keep the spans".
|
|
301
|
+
*
|
|
302
|
+
* @example [400, 401, 403, 404]
|
|
303
|
+
* @example ({ statusCode, duration }) => statusCode === 404 && duration < 1000
|
|
304
|
+
* @default undefined - every operation ships its spans
|
|
305
|
+
*/
|
|
306
|
+
skipSpans?: number[] | ((operation: SkipSpansContext) => boolean);
|
|
273
307
|
/**
|
|
274
308
|
* Whether to forward logs to the Observe APM.
|
|
275
309
|
* If true, logs will be forwarded to the Agent for correlation with traces.
|
|
@@ -611,6 +645,34 @@ export interface JobContext {
|
|
|
611
645
|
*/
|
|
612
646
|
id: string | undefined;
|
|
613
647
|
}
|
|
648
|
+
/** What a `skipSpans` function is told about the operation that finished. */
|
|
649
|
+
export interface SkipSpansContext {
|
|
650
|
+
/**
|
|
651
|
+
* The transport, as reported: `http` or `https`, `graphql` for an operation
|
|
652
|
+
* that arrived without an HTTP request, `ws` for a gateway message, or the
|
|
653
|
+
* microservice transport's name (`TCP`, `GRPC`, ...).
|
|
654
|
+
*/
|
|
655
|
+
protocol: string;
|
|
656
|
+
/**
|
|
657
|
+
* The route, message pattern, gateway pattern or GraphQL root field.
|
|
658
|
+
* Absent when none was resolved.
|
|
659
|
+
*/
|
|
660
|
+
operationId: string | undefined;
|
|
661
|
+
/** The HTTP method. Absent off HTTP. */
|
|
662
|
+
method: string | undefined;
|
|
663
|
+
/**
|
|
664
|
+
* The status the operation is reported with. See `skipSpans` for where it
|
|
665
|
+
* comes from on transports that have none of their own.
|
|
666
|
+
*/
|
|
667
|
+
statusCode: number | undefined;
|
|
668
|
+
/** How long the operation took, in milliseconds. */
|
|
669
|
+
duration: number;
|
|
670
|
+
/**
|
|
671
|
+
* Class name of the exception the operation failed with, e.g.
|
|
672
|
+
* `NotFoundException`. Absent when it did not fail with one.
|
|
673
|
+
*/
|
|
674
|
+
errorClass: string | undefined;
|
|
675
|
+
}
|
|
614
676
|
/** What a `ws` option hook is told about the message being handled. */
|
|
615
677
|
export interface WsMessageContext {
|
|
616
678
|
/** Class name of the gateway handling the message. */
|
package/dist/observe.module.js
CHANGED
|
@@ -29,6 +29,7 @@ import { LoggerPatcherService } from "./services/logger-patcher.service.js";
|
|
|
29
29
|
import { NodeRuntimeMetricsService } from "./services/node-runtime-metrics.service.js";
|
|
30
30
|
import { resolveSpanCollapseSettings } from "./services/collapse-repeated-spans.util.js";
|
|
31
31
|
import { OperationTraceRegistry } from "./services/operation-trace.registry.js";
|
|
32
|
+
import { resolveSkipSpans } from "./services/skip-spans.util.js";
|
|
32
33
|
import { StdoutForwarderService } from "./services/stdout-forwarder.service.js";
|
|
33
34
|
import { TraceSamplerService } from "./services/trace-sampler.service.js";
|
|
34
35
|
import { TracerService } from "./services/tracer.service.js";
|
|
@@ -147,11 +148,13 @@ export function createObserveModule(options = {}) {
|
|
|
147
148
|
provide: OperationTraceRegistry,
|
|
148
149
|
// The instance already exists (the instrumentation hook below holds
|
|
149
150
|
// it), so this is the one moment the resolved `ObserveOptions` and the
|
|
150
|
-
// registry meet: `spanCollapse` and `redaction` are
|
|
151
|
+
// registry meet: `spanCollapse`, `skipSpans` and `redaction` are
|
|
152
|
+
// applied here.
|
|
151
153
|
// Optional because `ASSERT_MODULE_OPTIONS` owns the missing-options
|
|
152
154
|
// error.
|
|
153
155
|
useFactory: (observeOptions) => {
|
|
154
156
|
operationTraceRegistry.configureSpanCollapse(resolveSpanCollapseSettings(observeOptions?.spanCollapse));
|
|
157
|
+
operationTraceRegistry.configureSkipSpans(resolveSkipSpans(observeOptions?.skipSpans));
|
|
155
158
|
operationTraceRegistry.configureRedaction(observeOptions?.redaction?.enabled === false
|
|
156
159
|
? null
|
|
157
160
|
: new LogRedactor(observeOptions?.redaction));
|
|
@@ -40,9 +40,7 @@ export declare class JobTraceRunner<Store extends Record<string, unknown>> {
|
|
|
40
40
|
* Makes `add` and `addBulk` carry the enqueuing operation's trace id, so the
|
|
41
41
|
* run reports under the request - or job, or cron firing - that caused it.
|
|
42
42
|
*
|
|
43
|
-
* The originals are parked on the prototype
|
|
44
|
-
* (a second Nest app in one process, a test suite) replaces the wrapper
|
|
45
|
-
* instead of wrapping it again.
|
|
43
|
+
* The originals are parked on the prototype itself (see `parkOriginal`).
|
|
46
44
|
*/
|
|
47
45
|
patchEnqueue(prototype: QueuePrototypeLike,
|
|
48
46
|
/** Index of the options argument in `add`, given the arguments passed. */
|
|
@@ -64,6 +62,14 @@ export declare class JobTraceRunner<Store extends Record<string, unknown>> {
|
|
|
64
62
|
* `x-request-id`.
|
|
65
63
|
*/
|
|
66
64
|
private readInheritedTraceId;
|
|
65
|
+
/**
|
|
66
|
+
* What identifies the run to a layer nested inside it: the queue and the
|
|
67
|
+
* job id, rather than the job object, which a driver is free to wrap or
|
|
68
|
+
* rebuild on its way to the processor. A retry is a later run, never a
|
|
69
|
+
* nested one, so the two cannot be told apart by accident. A run without
|
|
70
|
+
* an id has nothing to be recognised by.
|
|
71
|
+
*/
|
|
72
|
+
private activeJobOf;
|
|
67
73
|
/**
|
|
68
74
|
* Whether `jobs.ignore` matches this run. A predicate that throws is
|
|
69
75
|
* reported and read as "trace it": a bug in tracing configuration must not
|
|
@@ -3,6 +3,29 @@ import { REQUEST_ID_PATTERN } from "../utils/default-trace-id-generator.util.js"
|
|
|
3
3
|
import { uuidv7 } from "../utils/uuid-v7.util.js";
|
|
4
4
|
const ORIGINAL_ADD = Symbol.for("nestjs.observe.queue.add");
|
|
5
5
|
const ORIGINAL_ADD_BULK = Symbol.for("nestjs.observe.queue.addBulk");
|
|
6
|
+
/** Where a run records which job it is running, for a layer nested inside it. */
|
|
7
|
+
const ACTIVE_JOB_KEY = Symbol("nestjs.observe.activeJob");
|
|
8
|
+
/**
|
|
9
|
+
* The method a prototype had before any agent patched it, parked on that
|
|
10
|
+
* prototype under `key` the first time round, so a second agent (a second Nest
|
|
11
|
+
* app in one process, a test suite) replaces the wrapper instead of wrapping it
|
|
12
|
+
* again.
|
|
13
|
+
*
|
|
14
|
+
* Own properties only. A subclass prototype - `QueuePro` over BullMQ's `Queue` -
|
|
15
|
+
* would otherwise read the original its parent parked through the prototype
|
|
16
|
+
* chain, and the wrapper would call *that*, skipping the subclass's own
|
|
17
|
+
* override altogether.
|
|
18
|
+
*/
|
|
19
|
+
function parkOriginal(prototype, key, method) {
|
|
20
|
+
if (!Object.prototype.hasOwnProperty.call(prototype, key)) {
|
|
21
|
+
prototype[key] = prototype[method];
|
|
22
|
+
}
|
|
23
|
+
return prototype[key];
|
|
24
|
+
}
|
|
25
|
+
function isSameJob(outer, job) {
|
|
26
|
+
const active = outer;
|
|
27
|
+
return active?.queueName === job.queueName && active.id === job.id;
|
|
28
|
+
}
|
|
6
29
|
/**
|
|
7
30
|
* The part of job tracing that is the same whichever driver runs the queue:
|
|
8
31
|
* stamping the active trace id onto a job as it is enqueued, and opening the
|
|
@@ -29,15 +52,13 @@ export class JobTraceRunner {
|
|
|
29
52
|
* Makes `add` and `addBulk` carry the enqueuing operation's trace id, so the
|
|
30
53
|
* run reports under the request - or job, or cron firing - that caused it.
|
|
31
54
|
*
|
|
32
|
-
* The originals are parked on the prototype
|
|
33
|
-
* (a second Nest app in one process, a test suite) replaces the wrapper
|
|
34
|
-
* instead of wrapping it again.
|
|
55
|
+
* The originals are parked on the prototype itself (see `parkOriginal`).
|
|
35
56
|
*/
|
|
36
57
|
patchEnqueue(prototype,
|
|
37
58
|
/** Index of the options argument in `add`, given the arguments passed. */
|
|
38
59
|
optsIndexOf) {
|
|
39
60
|
const stamp = (opts) => this.stampTraceId(opts);
|
|
40
|
-
const originalAdd = (prototype
|
|
61
|
+
const originalAdd = parkOriginal(prototype, ORIGINAL_ADD, "add");
|
|
41
62
|
if (typeof originalAdd === "function") {
|
|
42
63
|
prototype.add = function (...args) {
|
|
43
64
|
const index = optsIndexOf(args);
|
|
@@ -48,8 +69,7 @@ export class JobTraceRunner {
|
|
|
48
69
|
return originalAdd.apply(this, args);
|
|
49
70
|
};
|
|
50
71
|
}
|
|
51
|
-
const originalAddBulk = (prototype
|
|
52
|
-
prototype.addBulk);
|
|
72
|
+
const originalAddBulk = parkOriginal(prototype, ORIGINAL_ADD_BULK, "addBulk");
|
|
53
73
|
if (typeof originalAddBulk === "function") {
|
|
54
74
|
prototype.addBulk = function (jobs) {
|
|
55
75
|
if (!Array.isArray(jobs)) {
|
|
@@ -99,6 +119,18 @@ export class JobTraceRunner {
|
|
|
99
119
|
? inherited
|
|
100
120
|
: undefined;
|
|
101
121
|
}
|
|
122
|
+
/**
|
|
123
|
+
* What identifies the run to a layer nested inside it: the queue and the
|
|
124
|
+
* job id, rather than the job object, which a driver is free to wrap or
|
|
125
|
+
* rebuild on its way to the processor. A retry is a later run, never a
|
|
126
|
+
* nested one, so the two cannot be told apart by accident. A run without
|
|
127
|
+
* an id has nothing to be recognised by.
|
|
128
|
+
*/
|
|
129
|
+
activeJobOf(job) {
|
|
130
|
+
return job.id === undefined
|
|
131
|
+
? undefined
|
|
132
|
+
: { queueName: job.queueName, id: String(job.id) };
|
|
133
|
+
}
|
|
102
134
|
/**
|
|
103
135
|
* Whether `jobs.ignore` matches this run. A predicate that throws is
|
|
104
136
|
* reported and read as "trace it": a bug in tracing configuration must not
|
|
@@ -122,12 +154,24 @@ export class JobTraceRunner {
|
|
|
122
154
|
* here either way.
|
|
123
155
|
*/
|
|
124
156
|
run(job, invoke, settlesItself = false) {
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
157
|
+
const outerStore = this.asyncLocalStorage.getStore();
|
|
158
|
+
const activeJob = this.activeJobOf(job);
|
|
159
|
+
// A second layer of instrumentation around a run that is already open -
|
|
160
|
+
// a BullMQ Pro worker whose processor `@nestjs/bullmq` decorated as well.
|
|
161
|
+
// The layer that saw the job first owns the trace; this one runs the job
|
|
162
|
+
// inside it. Taking the branch below instead would hide that trace behind
|
|
163
|
+
// an empty store, and the run would report without a single span.
|
|
164
|
+
if (activeJob &&
|
|
165
|
+
isSameJob(outerStore?.get(ACTIVE_JOB_KEY), activeJob)) {
|
|
166
|
+
return invoke(() => undefined);
|
|
167
|
+
}
|
|
168
|
+
const hasOuterContext = outerStore?.has(this.options.traceIdKey);
|
|
128
169
|
// The same map `run` is given, rather than `getStore()` inside the
|
|
129
170
|
// callback: identical object, one lookup fewer, and it is known to exist.
|
|
130
171
|
const store = new Map();
|
|
172
|
+
if (activeJob) {
|
|
173
|
+
store.set(ACTIVE_JOB_KEY, activeJob);
|
|
174
|
+
}
|
|
131
175
|
return this.asyncLocalStorage.run(store, () => {
|
|
132
176
|
if (hasOuterContext) {
|
|
133
177
|
// If the outer context already has a trace ID
|
|
@@ -3,10 +3,15 @@ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.j
|
|
|
3
3
|
import { ObserveModuleOptionsWithDefaults } from "../interfaces/index.js";
|
|
4
4
|
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
5
5
|
import { KeyOf } from "../types/key-of.type.js";
|
|
6
|
+
/**
|
|
7
|
+
* Job tracing for BullMQ: through `@nestjs/bullmq`'s processor decorator, and
|
|
8
|
+
* for BullMQ Pro through its worker, whichever package wires it into Nest.
|
|
9
|
+
*/
|
|
6
10
|
export declare class QueueObserveAgentService<Store extends Record<string, unknown>> {
|
|
7
11
|
private readonly logger;
|
|
8
12
|
private readonly runner;
|
|
9
13
|
constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>);
|
|
14
|
+
private describeJob;
|
|
10
15
|
/**
|
|
11
16
|
* Queue-level facts BullMQ already tracks but that never reached telemetry:
|
|
12
17
|
* how long the job waited before a worker took it, and which attempt this is.
|
|
@@ -34,4 +39,33 @@ export declare class QueueObserveAgentService<Store extends Record<string, unkno
|
|
|
34
39
|
* patched here is the one behind every `@InjectQueue()`.
|
|
35
40
|
*/
|
|
36
41
|
private patchQueue;
|
|
42
|
+
/**
|
|
43
|
+
* Loads `@taskforcesh/bullmq-pro` - an optional peer, published only to
|
|
44
|
+
* Taskforce's own registry - the same way as the packages above.
|
|
45
|
+
*
|
|
46
|
+
* Returns `undefined` both when it is not installed, which is the normal
|
|
47
|
+
* case, and when it is installed but cannot be loaded, which is said out
|
|
48
|
+
* loud.
|
|
49
|
+
*/
|
|
50
|
+
private loadBullMQPro;
|
|
51
|
+
/**
|
|
52
|
+
* BullMQ Pro, whichever way it is wired into Nest.
|
|
53
|
+
*
|
|
54
|
+
* `@taskforcesh/nestjs-bullmq-pro` is a fork of `@nestjs/bullmq` from before
|
|
55
|
+
* the processor decorator existed: its explorer hands `process` straight to
|
|
56
|
+
* a `WorkerPro`, and there is no seam on the Nest side to patch. The worker
|
|
57
|
+
* is patched instead. Every job a `WorkerPro` runs goes through the
|
|
58
|
+
* `callProcessJob` it inherits from BullMQ's `Worker`, so one patch covers
|
|
59
|
+
* the fork, `@nestjs/bullmq` told to build Pro workers
|
|
60
|
+
* (`BullModule.workerClass`), and a worker built by hand - without depending
|
|
61
|
+
* on anybody's explorer. Where `@nestjs/bullmq` decorated the processor too,
|
|
62
|
+
* the runner recognises the job it is already running and opens no second
|
|
63
|
+
* trace.
|
|
64
|
+
*
|
|
65
|
+
* `QueuePro` overrides `add` and `addBulk`, and an override need not go
|
|
66
|
+
* through `Queue.prototype.add`, so the enqueuing half is patched on
|
|
67
|
+
* `QueuePro` itself.
|
|
68
|
+
*/
|
|
69
|
+
private patchBullMQPro;
|
|
70
|
+
private patchWorkerPro;
|
|
37
71
|
}
|
|
@@ -18,12 +18,27 @@ import { OperationTraceRegistry } from "../services/operation-trace.registry.js"
|
|
|
18
18
|
import { OBSERVE_OPTIONS } from "../observe.constants.js";
|
|
19
19
|
import { JobTraceRunner } from "./job-trace-runner.js";
|
|
20
20
|
import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
|
|
21
|
+
const ORIGINAL_CALL_PROCESS_JOB = Symbol.for("nestjs.observe.bullmqPro.callProcessJob");
|
|
22
|
+
/**
|
|
23
|
+
* Job tracing for BullMQ: through `@nestjs/bullmq`'s processor decorator, and
|
|
24
|
+
* for BullMQ Pro through its worker, whichever package wires it into Nest.
|
|
25
|
+
*/
|
|
21
26
|
let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAgentService {
|
|
22
27
|
logger = new Logger(QueueObserveAgentService_1.name);
|
|
23
28
|
runner;
|
|
24
29
|
constructor(observeAgentSharedBuffer, options, operationTraceRegistry, asyncLocalStorage) {
|
|
25
30
|
this.runner = new JobTraceRunner(observeAgentSharedBuffer, options, operationTraceRegistry, asyncLocalStorage, this.logger);
|
|
26
31
|
this.patchDecorate();
|
|
32
|
+
this.patchBullMQPro();
|
|
33
|
+
}
|
|
34
|
+
describeJob(job) {
|
|
35
|
+
return {
|
|
36
|
+
queueName: job.queueName,
|
|
37
|
+
name: job.name,
|
|
38
|
+
id: job.id,
|
|
39
|
+
opts: job.opts,
|
|
40
|
+
metadata: this.readQueueMetadata(job),
|
|
41
|
+
};
|
|
27
42
|
}
|
|
28
43
|
/**
|
|
29
44
|
* Queue-level facts BullMQ already tracks but that never reached telemetry:
|
|
@@ -93,14 +108,11 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
|
|
|
93
108
|
this.logger.warn("ProcessorDecoratorService is not available. Please, update to the latest version of @nestjs/bullmq. Skipping patching.");
|
|
94
109
|
return;
|
|
95
110
|
}
|
|
111
|
+
// The worker calls the processor with `(job, token, signal)`, and all of it
|
|
112
|
+
// is passed on: a processor that moves its own job (`moveToDelayed`,
|
|
113
|
+
// `extendLock`) needs the token to prove it holds the lock.
|
|
96
114
|
ProcessorDecoratorService.prototype["decorate"] =
|
|
97
|
-
(processor) => (job) => this.runner.run(
|
|
98
|
-
queueName: job.queueName,
|
|
99
|
-
name: job.name,
|
|
100
|
-
id: job.id,
|
|
101
|
-
opts: job.opts,
|
|
102
|
-
metadata: this.readQueueMetadata(job),
|
|
103
|
-
}, () => processor(job));
|
|
115
|
+
(processor) => (job, ...rest) => this.runner.run(this.describeJob(job), () => processor(job, ...rest));
|
|
104
116
|
this.patchQueue();
|
|
105
117
|
}
|
|
106
118
|
/**
|
|
@@ -123,6 +135,79 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
|
|
|
123
135
|
// add(name, data, opts)
|
|
124
136
|
this.runner.patchEnqueue(prototype, () => 2);
|
|
125
137
|
}
|
|
138
|
+
/**
|
|
139
|
+
* Loads `@taskforcesh/bullmq-pro` - an optional peer, published only to
|
|
140
|
+
* Taskforce's own registry - the same way as the packages above.
|
|
141
|
+
*
|
|
142
|
+
* Returns `undefined` both when it is not installed, which is the normal
|
|
143
|
+
* case, and when it is installed but cannot be loaded, which is said out
|
|
144
|
+
* loud.
|
|
145
|
+
*/
|
|
146
|
+
loadBullMQPro() {
|
|
147
|
+
const result = loadOptionalPeer("@taskforcesh/bullmq-pro");
|
|
148
|
+
if (!result.installed) {
|
|
149
|
+
return undefined;
|
|
150
|
+
}
|
|
151
|
+
if (!result.module) {
|
|
152
|
+
this.logger.warn(`@taskforcesh/bullmq-pro is installed but could not be loaded, so BullMQ Pro jobs will not be instrumented${result.error ? `: ${describePeerLoadError(result.error)}` : "."}`);
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
return result.module;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* BullMQ Pro, whichever way it is wired into Nest.
|
|
159
|
+
*
|
|
160
|
+
* `@taskforcesh/nestjs-bullmq-pro` is a fork of `@nestjs/bullmq` from before
|
|
161
|
+
* the processor decorator existed: its explorer hands `process` straight to
|
|
162
|
+
* a `WorkerPro`, and there is no seam on the Nest side to patch. The worker
|
|
163
|
+
* is patched instead. Every job a `WorkerPro` runs goes through the
|
|
164
|
+
* `callProcessJob` it inherits from BullMQ's `Worker`, so one patch covers
|
|
165
|
+
* the fork, `@nestjs/bullmq` told to build Pro workers
|
|
166
|
+
* (`BullModule.workerClass`), and a worker built by hand - without depending
|
|
167
|
+
* on anybody's explorer. Where `@nestjs/bullmq` decorated the processor too,
|
|
168
|
+
* the runner recognises the job it is already running and opens no second
|
|
169
|
+
* trace.
|
|
170
|
+
*
|
|
171
|
+
* `QueuePro` overrides `add` and `addBulk`, and an override need not go
|
|
172
|
+
* through `Queue.prototype.add`, so the enqueuing half is patched on
|
|
173
|
+
* `QueuePro` itself.
|
|
174
|
+
*/
|
|
175
|
+
patchBullMQPro() {
|
|
176
|
+
const bullmqPro = this.loadBullMQPro();
|
|
177
|
+
if (!bullmqPro) {
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
this.patchWorkerPro(bullmqPro.WorkerPro?.prototype);
|
|
181
|
+
const queuePrototype = bullmqPro.QueuePro?.prototype;
|
|
182
|
+
if (!queuePrototype) {
|
|
183
|
+
this.logger.warn("@taskforcesh/bullmq-pro does not expose QueuePro, so BullMQ Pro jobs will not inherit the trace that enqueued them.");
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
// add(name, data, opts)
|
|
187
|
+
this.runner.patchEnqueue(queuePrototype, () => 2);
|
|
188
|
+
}
|
|
189
|
+
patchWorkerPro(prototype) {
|
|
190
|
+
// Parked as an own property, like the queue's originals: a second agent
|
|
191
|
+
// replaces the wrapper instead of wrapping it again.
|
|
192
|
+
if (prototype &&
|
|
193
|
+
!Object.prototype.hasOwnProperty.call(prototype, ORIGINAL_CALL_PROCESS_JOB)) {
|
|
194
|
+
prototype[ORIGINAL_CALL_PROCESS_JOB] = prototype.callProcessJob;
|
|
195
|
+
}
|
|
196
|
+
const original = prototype?.[ORIGINAL_CALL_PROCESS_JOB];
|
|
197
|
+
if (!prototype || typeof original !== "function") {
|
|
198
|
+
this.logger.warn("BullMQ Pro's WorkerPro.prototype.callProcessJob is not available, so BullMQ Pro jobs will not be instrumented.");
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const runner = this.runner;
|
|
202
|
+
const describe = (job) => this.describeJob(job);
|
|
203
|
+
prototype.callProcessJob = function (job, ...rest) {
|
|
204
|
+
// Nothing to describe; instrumentation must never be why a run fails.
|
|
205
|
+
if (typeof job !== "object" || job === null) {
|
|
206
|
+
return original.call(this, job, ...rest);
|
|
207
|
+
}
|
|
208
|
+
return runner.run(describe(job), () => original.call(this, job, ...rest));
|
|
209
|
+
};
|
|
210
|
+
}
|
|
126
211
|
};
|
|
127
212
|
QueueObserveAgentService = QueueObserveAgentService_1 = __decorate([
|
|
128
213
|
Injectable(),
|
|
@@ -47,8 +47,8 @@ export declare class RpcObserveAgentService<Store extends Record<string, unknown
|
|
|
47
47
|
* transport used to arrive with no protocol at all.
|
|
48
48
|
*/
|
|
49
49
|
private toProtocolName;
|
|
50
|
-
startRpcRequestTracing(transportId: Transport | symbol, ctx: BaseRpcContext, done: () => Promise<any>):
|
|
51
|
-
startGrpcRequestTracing(transportId: Transport | symbol, call: GrpcCall, done: () => Promise<any>):
|
|
50
|
+
startRpcRequestTracing(transportId: Transport | symbol, ctx: BaseRpcContext, done: () => Promise<any>): Promise<unknown>;
|
|
51
|
+
startGrpcRequestTracing(transportId: Transport | symbol, call: GrpcCall, done: () => Promise<any>): Promise<unknown>;
|
|
52
52
|
endRpcRequestTracing(transportId: Transport | symbol, ctx: BaseRpcContext | GrpcCall): void;
|
|
53
53
|
private getOperationIdFromContext;
|
|
54
54
|
}
|
|
@@ -79,12 +79,15 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
79
79
|
return result.module;
|
|
80
80
|
}
|
|
81
81
|
registerRpcHooks(target) {
|
|
82
|
+
// Return `done()`'s promise, as Nest's default hook does. Nest's servers
|
|
83
|
+
// hand it back from their message handlers: kafkajs waits on it to commit
|
|
84
|
+
// the offset or retry the message, and recent Nest versions log its
|
|
85
|
+
// rejection for most other transports.
|
|
82
86
|
target.setOnProcessingStartHook((transportId, ctx, done) => {
|
|
83
87
|
if (transportId === this.microservices.Transport.GRPC) {
|
|
84
|
-
this.startGrpcRequestTracing(transportId, ctx, done);
|
|
85
|
-
return;
|
|
88
|
+
return this.startGrpcRequestTracing(transportId, ctx, done);
|
|
86
89
|
}
|
|
87
|
-
this.startRpcRequestTracing(transportId, ctx, done);
|
|
90
|
+
return this.startRpcRequestTracing(transportId, ctx, done);
|
|
88
91
|
});
|
|
89
92
|
target.setOnProcessingEndHook((transportId, ctx) => {
|
|
90
93
|
this.endRpcRequestTracing(transportId, ctx);
|
|
@@ -106,7 +109,7 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
106
109
|
// The same map `run` is given, rather than `getStore()` inside the callback:
|
|
107
110
|
// identical object, one lookup fewer, and it is known to exist.
|
|
108
111
|
const store = new Map();
|
|
109
|
-
this.asyncLocalStorage.run(store, () => {
|
|
112
|
+
return this.asyncLocalStorage.run(store, () => {
|
|
110
113
|
const traceId = this.options.traceIdGenerator(ctx);
|
|
111
114
|
store.set(this.options.traceIdKey, traceId);
|
|
112
115
|
if (this.options.rpc?.setAttributes) {
|
|
@@ -133,14 +136,14 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
133
136
|
operationId: this.getOperationIdFromContext(ctx),
|
|
134
137
|
tags: this.options.rpc?.tags,
|
|
135
138
|
});
|
|
136
|
-
done();
|
|
139
|
+
return done();
|
|
137
140
|
// });
|
|
138
141
|
});
|
|
139
142
|
}
|
|
140
143
|
startGrpcRequestTracing(transportId, call, done) {
|
|
141
144
|
// As above: the map `run` is given, not looked back up.
|
|
142
145
|
const store = new Map();
|
|
143
|
-
this.asyncLocalStorage.run(store, () => {
|
|
146
|
+
return this.asyncLocalStorage.run(store, () => {
|
|
144
147
|
const traceId = this.options.traceIdGenerator(call);
|
|
145
148
|
store.set(this.options.traceIdKey, traceId);
|
|
146
149
|
if (this.options.grpc?.setAttributes) {
|
|
@@ -151,23 +154,25 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
151
154
|
}
|
|
152
155
|
}
|
|
153
156
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
157
|
+
return new Promise((resolve) => {
|
|
158
|
+
setTimeout(() => {
|
|
159
|
+
if (this.options.grpc?.ignore?.(call)) {
|
|
160
|
+
return resolve(done());
|
|
161
|
+
}
|
|
162
|
+
const shouldCapture = this.traceSamplerService.shouldCapture("grpc", {
|
|
163
|
+
call,
|
|
164
|
+
});
|
|
165
|
+
if (!shouldCapture) {
|
|
166
|
+
return resolve(done());
|
|
167
|
+
}
|
|
168
|
+
this.operationTraceRegistry.startTrace(traceId, {
|
|
169
|
+
protocol: this.toProtocolName(transportId),
|
|
170
|
+
operationId: call.operationId,
|
|
171
|
+
tags: this.options.grpc?.tags,
|
|
172
|
+
});
|
|
173
|
+
resolve(done());
|
|
174
|
+
}, 0);
|
|
175
|
+
});
|
|
171
176
|
});
|
|
172
177
|
}
|
|
173
178
|
endRpcRequestTracing(transportId, ctx) {
|
|
@@ -9,6 +9,7 @@ import { KeyOf } from "../types/key-of.type.js";
|
|
|
9
9
|
import { LogRedactor } from "../utils/log-redactor.js";
|
|
10
10
|
import { CALLER_METADATA_KEY } from "../observe.constants.js";
|
|
11
11
|
import { SpanCollapseSettings } from "./collapse-repeated-spans.util.js";
|
|
12
|
+
import { SkipSpansPredicate } from "./skip-spans.util.js";
|
|
12
13
|
type TraceId = string;
|
|
13
14
|
export declare class OperationTraceRegistry {
|
|
14
15
|
private readonly als;
|
|
@@ -28,6 +29,15 @@ export declare class OperationTraceRegistry {
|
|
|
28
29
|
* registry the module has not (yet) configured still bounds what it ships.
|
|
29
30
|
*/
|
|
30
31
|
private spanCollapse;
|
|
32
|
+
/**
|
|
33
|
+
* `skipSpans`, resolved. Undefined - the default - ships every tree.
|
|
34
|
+
*/
|
|
35
|
+
private skipSpans;
|
|
36
|
+
/**
|
|
37
|
+
* A `skipSpans` function that throws does so on every request, so the
|
|
38
|
+
* failure is reported once rather than once per request.
|
|
39
|
+
*/
|
|
40
|
+
private hasReportedSkipSpansFailure;
|
|
31
41
|
/**
|
|
32
42
|
* Scrubs error messages and stacks before they are attached to a span.
|
|
33
43
|
*
|
|
@@ -49,6 +59,12 @@ export declare class OperationTraceRegistry {
|
|
|
49
59
|
* before the DI container so the instrumentation hook can hold it.
|
|
50
60
|
*/
|
|
51
61
|
configureSpanCollapse(settings: SpanCollapseSettings | undefined): void;
|
|
62
|
+
/**
|
|
63
|
+
* Sets which finished operations ship without their spans, or none with
|
|
64
|
+
* `undefined`. Called by the module alongside `configureSpanCollapse`, for
|
|
65
|
+
* the same reason.
|
|
66
|
+
*/
|
|
67
|
+
configureSkipSpans(predicate: SkipSpansPredicate | undefined): void;
|
|
52
68
|
/**
|
|
53
69
|
* Applies the resolved `redaction` options to error payloads, or switches
|
|
54
70
|
* redaction off with `null`. Called by the module alongside
|
|
@@ -161,6 +177,15 @@ export declare class OperationTraceRegistry {
|
|
|
161
177
|
*/
|
|
162
178
|
abandonTrace(traceId: TraceId): void;
|
|
163
179
|
pluckSnapshot(traceId: string): Promise<RequestSnapshot | JobSnapshot | undefined>;
|
|
180
|
+
/**
|
|
181
|
+
* Whether `skipSpans` claims a finished operation. Only request snapshots
|
|
182
|
+
* are asked: a job has no status to be judged by.
|
|
183
|
+
*
|
|
184
|
+
* Asked once the snapshot is complete, so the rule sees the status and the
|
|
185
|
+
* error the operation is reported with. A rule that throws keeps the spans:
|
|
186
|
+
* a mistake in it must not cost the application its traces.
|
|
187
|
+
*/
|
|
188
|
+
private shouldSkipSpans;
|
|
164
189
|
getActiveSpan(traceId: string, callerId: string | undefined): OngoingTraceEventNode | undefined;
|
|
165
190
|
createManualSpan(traceId: string, callerId: string | undefined, name: string, spanFunction: (span: TraceSpanDelegate) => any): Promise<any>;
|
|
166
191
|
}
|
|
@@ -38,6 +38,15 @@ export class OperationTraceRegistry {
|
|
|
38
38
|
* registry the module has not (yet) configured still bounds what it ships.
|
|
39
39
|
*/
|
|
40
40
|
spanCollapse = DEFAULT_SPAN_COLLAPSE;
|
|
41
|
+
/**
|
|
42
|
+
* `skipSpans`, resolved. Undefined - the default - ships every tree.
|
|
43
|
+
*/
|
|
44
|
+
skipSpans;
|
|
45
|
+
/**
|
|
46
|
+
* A `skipSpans` function that throws does so on every request, so the
|
|
47
|
+
* failure is reported once rather than once per request.
|
|
48
|
+
*/
|
|
49
|
+
hasReportedSkipSpansFailure = false;
|
|
41
50
|
/**
|
|
42
51
|
* Scrubs error messages and stacks before they are attached to a span.
|
|
43
52
|
*
|
|
@@ -62,6 +71,14 @@ export class OperationTraceRegistry {
|
|
|
62
71
|
configureSpanCollapse(settings) {
|
|
63
72
|
this.spanCollapse = settings;
|
|
64
73
|
}
|
|
74
|
+
/**
|
|
75
|
+
* Sets which finished operations ship without their spans, or none with
|
|
76
|
+
* `undefined`. Called by the module alongside `configureSpanCollapse`, for
|
|
77
|
+
* the same reason.
|
|
78
|
+
*/
|
|
79
|
+
configureSkipSpans(predicate) {
|
|
80
|
+
this.skipSpans = predicate;
|
|
81
|
+
}
|
|
65
82
|
/**
|
|
66
83
|
* Applies the resolved `redaction` options to error payloads, or switches
|
|
67
84
|
* redaction off with `null`. Called by the module alongside
|
|
@@ -511,6 +528,13 @@ export class OperationTraceRegistry {
|
|
|
511
528
|
delete bookkeeping.refsCounter;
|
|
512
529
|
delete bookkeeping.refsMarkedAsComplete;
|
|
513
530
|
delete bookkeeping.errorStatusCode;
|
|
531
|
+
// Emptied rather than removed: the collector requires the field, and an
|
|
532
|
+
// empty tree is what it already stores for a trace it sampled out - the
|
|
533
|
+
// operation keeps its row, its error and every chart it feeds.
|
|
534
|
+
if (this.shouldSkipSpans(snapshot)) {
|
|
535
|
+
snapshot.traces = [];
|
|
536
|
+
return snapshot;
|
|
537
|
+
}
|
|
514
538
|
// Last, on the finished tree: every span has closed by now, so a group
|
|
515
539
|
// is judged on its complete membership and durations, and nothing that
|
|
516
540
|
// reads the tree afterwards - the encoder, the buffer - sees the
|
|
@@ -522,6 +546,36 @@ export class OperationTraceRegistry {
|
|
|
522
546
|
}
|
|
523
547
|
return undefined;
|
|
524
548
|
}
|
|
549
|
+
/**
|
|
550
|
+
* Whether `skipSpans` claims a finished operation. Only request snapshots
|
|
551
|
+
* are asked: a job has no status to be judged by.
|
|
552
|
+
*
|
|
553
|
+
* Asked once the snapshot is complete, so the rule sees the status and the
|
|
554
|
+
* error the operation is reported with. A rule that throws keeps the spans:
|
|
555
|
+
* a mistake in it must not cost the application its traces.
|
|
556
|
+
*/
|
|
557
|
+
shouldSkipSpans(snapshot) {
|
|
558
|
+
if (!this.skipSpans || !("protocol" in snapshot)) {
|
|
559
|
+
return false;
|
|
560
|
+
}
|
|
561
|
+
try {
|
|
562
|
+
return this.skipSpans({
|
|
563
|
+
protocol: snapshot.protocol,
|
|
564
|
+
operationId: snapshot.operationId,
|
|
565
|
+
method: snapshot.attributes?.method,
|
|
566
|
+
statusCode: snapshot.attributes?.statusCode,
|
|
567
|
+
duration: snapshot.duration ?? 0,
|
|
568
|
+
errorClass: snapshot.error?.cls,
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
catch (error) {
|
|
572
|
+
if (!this.hasReportedSkipSpansFailure) {
|
|
573
|
+
this.hasReportedSkipSpansFailure = true;
|
|
574
|
+
this.logger.warn(`"skipSpans" threw for "${snapshot.operationId ?? snapshot.protocol}"; keeping its spans. Later failures are not reported: ${error instanceof Error ? error.message : String(error)}`);
|
|
575
|
+
}
|
|
576
|
+
return false;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
525
579
|
getActiveSpan(traceId, callerId) {
|
|
526
580
|
const refsByCaller = this.callerIdsByTraceId.get(traceId);
|
|
527
581
|
if (!refsByCaller) {
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { ObserveOptions, SkipSpansContext } from "../interfaces/observe-options.interface.js";
|
|
2
|
+
/** Resolved form of `ObserveOptions.skipSpans`. */
|
|
3
|
+
export type SkipSpansPredicate = (operation: SkipSpansContext) => boolean;
|
|
4
|
+
/**
|
|
5
|
+
* Turns the user-facing option into the one predicate the registry asks, or
|
|
6
|
+
* `undefined` when nothing is to be skipped - so an application that never
|
|
7
|
+
* set it pays one falsy check per operation and builds no context object.
|
|
8
|
+
*
|
|
9
|
+
* A list matches on the status code alone, by strict equality: a status never
|
|
10
|
+
* reaches the registry as a string, so `"404"` in the list can only be a
|
|
11
|
+
* mistake, and a list that coerced its way into skipping more than it names
|
|
12
|
+
* would be the worse one to get wrong.
|
|
13
|
+
*/
|
|
14
|
+
export declare function resolveSkipSpans(option: ObserveOptions["skipSpans"]): SkipSpansPredicate | undefined;
|