@nestjs/observe 0.3.1 → 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 +86 -10
- package/dist/observe.module.js +4 -1
- package/dist/protocols/job-trace-runner.d.ts +15 -3
- package/dist/protocols/job-trace-runner.js +78 -15
- 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/protocols/schedule-observe-agent.service.d.ts +1 -4
- package/dist/protocols/schedule-observe-agent.service.js +12 -80
- 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/dist/services/tracer.service.d.ts +3 -1
- package/dist/services/tracer.service.js +10 -1
- 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.
|
|
@@ -547,6 +581,18 @@ export interface ObserveOptions {
|
|
|
547
581
|
* gets a fresh `id`.
|
|
548
582
|
*/
|
|
549
583
|
jobs?: {
|
|
584
|
+
/**
|
|
585
|
+
* A function that determines whether to skip tracing a given job run.
|
|
586
|
+
* Receives the same descriptor as `setAttributes`, so it can match on the
|
|
587
|
+
* queue (or scheduler type) and the job name.
|
|
588
|
+
*
|
|
589
|
+
* An ignored run still executes under a trace id of its own - log lines
|
|
590
|
+
* stay correlated, and jobs it enqueues inherit that id - but no trace is
|
|
591
|
+
* opened for it, so none of its spans are recorded and nothing is shipped.
|
|
592
|
+
* @example (job) => job.queueName === 'interval' && job.name === 'heartbeat'
|
|
593
|
+
* @default () => false
|
|
594
|
+
*/
|
|
595
|
+
ignore?: (job: JobContext) => boolean;
|
|
550
596
|
/**
|
|
551
597
|
* Tags to be added to all job requests.
|
|
552
598
|
* These tags can be used to provide additional context for the requests.
|
|
@@ -561,16 +607,7 @@ export interface ObserveOptions {
|
|
|
561
607
|
* @example (job) => ({ 'queueName': job.queueName, 'jobName': job.name })
|
|
562
608
|
* @default (job) => ({})
|
|
563
609
|
*/
|
|
564
|
-
setAttributes?: (job: {
|
|
565
|
-
/** The BullMQ queue, or the scheduler type for a scheduled handler. */
|
|
566
|
-
queueName: string;
|
|
567
|
-
name: string;
|
|
568
|
-
/**
|
|
569
|
-
* Absent until the queue driver has assigned one. Always present for a
|
|
570
|
-
* scheduled handler, where it identifies this particular firing.
|
|
571
|
-
*/
|
|
572
|
-
id: string | undefined;
|
|
573
|
-
}) => {
|
|
610
|
+
setAttributes?: (job: JobContext) => {
|
|
574
611
|
[key: string]: string | number | boolean;
|
|
575
612
|
};
|
|
576
613
|
};
|
|
@@ -597,6 +634,45 @@ export interface ObserveModuleAsyncOptions extends Pick<ModuleMetadata, "imports
|
|
|
597
634
|
*/
|
|
598
635
|
global?: boolean;
|
|
599
636
|
}
|
|
637
|
+
/** What a `jobs` option hook is told about the run being started. */
|
|
638
|
+
export interface JobContext {
|
|
639
|
+
/** The BullMQ queue, or the scheduler type for a scheduled handler. */
|
|
640
|
+
queueName: string;
|
|
641
|
+
name: string;
|
|
642
|
+
/**
|
|
643
|
+
* Absent until the queue driver has assigned one. Always present for a
|
|
644
|
+
* scheduled handler, where it identifies this particular firing.
|
|
645
|
+
*/
|
|
646
|
+
id: string | undefined;
|
|
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
|
+
}
|
|
600
676
|
/** What a `ws` option hook is told about the message being handled. */
|
|
601
677
|
export interface WsMessageContext {
|
|
602
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,20 @@ 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;
|
|
73
|
+
/**
|
|
74
|
+
* Whether `jobs.ignore` matches this run. A predicate that throws is
|
|
75
|
+
* reported and read as "trace it": a bug in tracing configuration must not
|
|
76
|
+
* stop the job itself from running.
|
|
77
|
+
*/
|
|
78
|
+
private isIgnored;
|
|
67
79
|
/**
|
|
68
80
|
* Runs one job under a trace.
|
|
69
81
|
*
|
|
@@ -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,32 @@ 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
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Whether `jobs.ignore` matches this run. A predicate that throws is
|
|
136
|
+
* reported and read as "trace it": a bug in tracing configuration must not
|
|
137
|
+
* stop the job itself from running.
|
|
138
|
+
*/
|
|
139
|
+
isIgnored(context) {
|
|
140
|
+
try {
|
|
141
|
+
return Boolean(this.options.jobs?.ignore?.(context));
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
this.logger.warn(`"jobs.ignore" threw for job "${context.name}" (queue "${context.queueName}"); tracing it anyway: ${error instanceof Error ? error.message : String(error)}`);
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
102
148
|
/**
|
|
103
149
|
* Runs one job under a trace.
|
|
104
150
|
*
|
|
@@ -108,12 +154,24 @@ export class JobTraceRunner {
|
|
|
108
154
|
* here either way.
|
|
109
155
|
*/
|
|
110
156
|
run(job, invoke, settlesItself = false) {
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
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);
|
|
114
169
|
// The same map `run` is given, rather than `getStore()` inside the
|
|
115
170
|
// callback: identical object, one lookup fewer, and it is known to exist.
|
|
116
171
|
const store = new Map();
|
|
172
|
+
if (activeJob) {
|
|
173
|
+
store.set(ACTIVE_JOB_KEY, activeJob);
|
|
174
|
+
}
|
|
117
175
|
return this.asyncLocalStorage.run(store, () => {
|
|
118
176
|
if (hasOuterContext) {
|
|
119
177
|
// If the outer context already has a trace ID
|
|
@@ -129,21 +187,26 @@ export class JobTraceRunner {
|
|
|
129
187
|
const traceId = this.readInheritedTraceId(job.opts) ?? registryKey;
|
|
130
188
|
store.set(this.options.traceIdKey, traceId);
|
|
131
189
|
store.set(TRACE_REGISTRY_KEY, registryKey);
|
|
132
|
-
const
|
|
190
|
+
const context = {
|
|
133
191
|
queueName: job.queueName,
|
|
134
192
|
name: job.name,
|
|
135
|
-
id: job.id,
|
|
136
|
-
}
|
|
193
|
+
id: typeof job.id === "number" ? `${job.id}` : job.id,
|
|
194
|
+
};
|
|
195
|
+
const attributes = this.options.jobs?.setAttributes?.(context);
|
|
137
196
|
if (attributes) {
|
|
138
197
|
for (const [key, value] of Object.entries(attributes)) {
|
|
139
198
|
store.set(key, value);
|
|
140
199
|
}
|
|
141
200
|
}
|
|
201
|
+
if (this.isIgnored(context)) {
|
|
202
|
+
// The trace id stays in the store so logs and jobs enqueued from here
|
|
203
|
+
// still correlate; nothing is registered under the registry key, so
|
|
204
|
+
// its spans have no trace to join.
|
|
205
|
+
return invoke(() => undefined);
|
|
206
|
+
}
|
|
142
207
|
this.operationTraceRegistry.startTrace(registryKey, {
|
|
143
208
|
tags: this.options.jobs?.tags,
|
|
144
|
-
|
|
145
|
-
name: job.name,
|
|
146
|
-
id: typeof job.id === "number" ? `${job.id}` : job.id,
|
|
209
|
+
...context,
|
|
147
210
|
...job.metadata,
|
|
148
211
|
}, traceId);
|
|
149
212
|
let settled = false;
|
|
@@ -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) {
|
|
@@ -27,11 +27,8 @@ import { KeyOf } from "../types/key-of.type.js";
|
|
|
27
27
|
* `emails / send-welcome` in the same view.
|
|
28
28
|
*/
|
|
29
29
|
export declare class ScheduleObserveAgentService<Store extends Record<string, unknown>> {
|
|
30
|
-
private readonly observeAgentSharedBuffer;
|
|
31
|
-
private readonly options;
|
|
32
|
-
private readonly operationTraceRegistry;
|
|
33
|
-
private readonly asyncLocalStorage;
|
|
34
30
|
private readonly logger;
|
|
31
|
+
private readonly runner;
|
|
35
32
|
constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>);
|
|
36
33
|
/**
|
|
37
34
|
* Loads the explorer without a static import, so a service that schedules
|