@nestjs/observe 0.3.2 → 0.3.4
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 +40 -2
- package/dist/.tsbuildinfo +1 -1
- package/dist/agent/observe-agent.shared-buffer.d.ts +3 -1
- package/dist/agent/observe-agent.shared-buffer.js +24 -3
- package/dist/agent/telemetry-wire-contract.js +26 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/interfaces/observe-options.interface.d.ts +72 -6
- package/dist/objectives/index.d.ts +1 -0
- package/dist/objectives/index.js +1 -0
- package/dist/objectives/objective.decorator.d.ts +59 -0
- package/dist/objectives/objective.decorator.js +102 -0
- package/dist/objectives/objectives.registry.d.ts +58 -0
- package/dist/objectives/objectives.registry.js +204 -0
- package/dist/observe.module.js +35 -6
- 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/dist/utils/infer-service-version.util.d.ts +15 -0
- package/dist/utils/infer-service-version.util.js +185 -0
- package/package.json +5 -1
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
import { Injectable, Logger, RequestMethod, } from "@nestjs/common";
|
|
11
|
+
import { DiscoveryService, MetadataScanner } from "@nestjs/core";
|
|
12
|
+
import { OBJECTIVES_METADATA, objectiveProblems, toDeclaredObjective, unknownObjectiveFields, } from "./objective.decorator.js";
|
|
13
|
+
/**
|
|
14
|
+
* How often a declaration is restated while the process runs. Once per
|
|
15
|
+
* process covers every deploy; the restatement covers a batch that never
|
|
16
|
+
* arrived, so a dropped one costs an hour of the SLO, not a release.
|
|
17
|
+
*/
|
|
18
|
+
const RESTATE_EVERY_MS = 60 * 60 * 1000;
|
|
19
|
+
/**
|
|
20
|
+
* How many spans of a trace are searched for the handler's own. It sits under
|
|
21
|
+
* whatever wraps it - each class middleware, and each interceptor that awaits
|
|
22
|
+
* the handler, nests it one level deeper - but above everything it calls, so
|
|
23
|
+
* a breadth-first search meets it long before this.
|
|
24
|
+
*/
|
|
25
|
+
const MAX_SPANS_SEARCHED = 200;
|
|
26
|
+
/**
|
|
27
|
+
* The collector's bounds on a declaration. It validates a batch whole, so one
|
|
28
|
+
* declaration past any of them would cost every snapshot in the batch - and
|
|
29
|
+
* again at every restatement.
|
|
30
|
+
*/
|
|
31
|
+
const MAX_OBJECTIVES_PER_HANDLER = 10;
|
|
32
|
+
const MAX_HANDLER_LENGTH = 255;
|
|
33
|
+
const MAX_ROUTE_LENGTH = 255;
|
|
34
|
+
/** `@nestjs/common`'s METHOD_METADATA - what `@Get()`, `@Post()` and the rest write. */
|
|
35
|
+
const METHOD_METADATA = "method";
|
|
36
|
+
/** `@nestjs/common`'s PATH_METADATA and VERSION_METADATA, on the controller and the handler. */
|
|
37
|
+
const PATH_METADATA = "path";
|
|
38
|
+
const VERSION_METADATA = "__version__";
|
|
39
|
+
/** How many values a route decorator was given: an array's length, else one. */
|
|
40
|
+
const entries = (value) => Array.isArray(value) ? Math.max(value.length, 1) : 1;
|
|
41
|
+
/**
|
|
42
|
+
* What the application declares with `@Objective`, and the moment to say so.
|
|
43
|
+
*
|
|
44
|
+
* The decorators are read at boot, keyed by `Class.method` - the name a
|
|
45
|
+
* request's handler span carries. A route is not known until a request takes
|
|
46
|
+
* it, and taking it is the one way to know the route exactly as the
|
|
47
|
+
* collector will key it, prefix and version included. So each completed
|
|
48
|
+
* request is matched to a declaring handler, and the first match per route is
|
|
49
|
+
* handed to the batch being built.
|
|
50
|
+
*/
|
|
51
|
+
let ObjectivesRegistry = class ObjectivesRegistry {
|
|
52
|
+
discoveryService;
|
|
53
|
+
metadataScanner;
|
|
54
|
+
logger = new Logger("ObserveObjectives");
|
|
55
|
+
byHandler = new Map();
|
|
56
|
+
statedAt = new Map();
|
|
57
|
+
refusedRoutes = new Set();
|
|
58
|
+
constructor(discoveryService, metadataScanner) {
|
|
59
|
+
this.discoveryService = discoveryService;
|
|
60
|
+
this.metadataScanner = metadataScanner;
|
|
61
|
+
}
|
|
62
|
+
onModuleInit() {
|
|
63
|
+
for (const wrapper of this.discoveryService.getControllers()) {
|
|
64
|
+
const metatype = wrapper.metatype;
|
|
65
|
+
if (!metatype?.prototype) {
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
for (const methodName of this.metadataScanner.getAllMethodNames(metatype.prototype)) {
|
|
69
|
+
const handlerRef = metatype.prototype[methodName];
|
|
70
|
+
const declared = Reflect.getMetadata(OBJECTIVES_METADATA, handlerRef);
|
|
71
|
+
if (!declared?.length) {
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
const handler = `${metatype.name}.${methodName}`;
|
|
75
|
+
const routes = this.routeCount(metatype, handlerRef);
|
|
76
|
+
if (routes > 1) {
|
|
77
|
+
this.logger.warn(`@Objective on ${handler} ignored: it serves ${routes} routes, and an SLO watches one - give each route a handler of its own to declare it.`);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const objectives = this.acceptedObjectives(handler, declared);
|
|
81
|
+
if (objectives.length > 0) {
|
|
82
|
+
this.byHandler.set(handler, {
|
|
83
|
+
objectives,
|
|
84
|
+
method: this.routedMethod(handlerRef),
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* What of a handler's declarations the collector will take: each checked
|
|
92
|
+
* against its bounds, stripped to the fields it knows, and no more of them
|
|
93
|
+
* than it accepts for one handler. Everything left out is said at boot, once.
|
|
94
|
+
*/
|
|
95
|
+
acceptedObjectives(handler, declared) {
|
|
96
|
+
if (handler.length > MAX_HANDLER_LENGTH) {
|
|
97
|
+
this.logger.warn(`@Objective on ${handler} ignored: a handler name is at most ${MAX_HANDLER_LENGTH} characters.`);
|
|
98
|
+
return [];
|
|
99
|
+
}
|
|
100
|
+
const accepted = [];
|
|
101
|
+
for (const objective of declared) {
|
|
102
|
+
const problems = objectiveProblems(objective);
|
|
103
|
+
if (problems.length > 0) {
|
|
104
|
+
this.logger.warn(`@Objective on ${handler} ignored: ${problems.join("; ")}.`);
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
const unknown = unknownObjectiveFields(objective);
|
|
108
|
+
if (unknown.length > 0) {
|
|
109
|
+
this.logger.warn(`@Objective on ${handler}: ${unknown.join(", ")} not sent - an objective has availability, latency, windowDays and name.`);
|
|
110
|
+
}
|
|
111
|
+
accepted.push(toDeclaredObjective(objective));
|
|
112
|
+
}
|
|
113
|
+
if (accepted.length > MAX_OBJECTIVES_PER_HANDLER) {
|
|
114
|
+
this.logger.warn(`@Objective on ${handler}: only the first ${MAX_OBJECTIVES_PER_HANDLER} of ${accepted.length} are sent - a handler declares at most ${MAX_OBJECTIVES_PER_HANDLER}.`);
|
|
115
|
+
return accepted.slice(0, MAX_OBJECTIVES_PER_HANDLER);
|
|
116
|
+
}
|
|
117
|
+
return accepted;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* How many routes a handler is mounted on: its controller's paths, times its
|
|
121
|
+
* own, times the versions it answers. A declaration names one route, and
|
|
122
|
+
* the SLO it makes is the handler's, so a handler on several would move
|
|
123
|
+
* that SLO from route to route with every restatement.
|
|
124
|
+
*/
|
|
125
|
+
routeCount(metatype, handlerRef) {
|
|
126
|
+
const versions = Reflect.getMetadata(VERSION_METADATA, handlerRef) ??
|
|
127
|
+
Reflect.getMetadata(VERSION_METADATA, metatype);
|
|
128
|
+
return (entries(Reflect.getMetadata(PATH_METADATA, metatype)) *
|
|
129
|
+
entries(Reflect.getMetadata(PATH_METADATA, handlerRef)) *
|
|
130
|
+
entries(versions));
|
|
131
|
+
}
|
|
132
|
+
routedMethod(handlerRef) {
|
|
133
|
+
const routed = Reflect.getMetadata(METHOD_METADATA, handlerRef);
|
|
134
|
+
if (routed === undefined || routed === RequestMethod.ALL) {
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
return RequestMethod[routed];
|
|
138
|
+
}
|
|
139
|
+
get size() {
|
|
140
|
+
return this.byHandler.size;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* The declaration a completed request brings due, if any: its handler
|
|
144
|
+
* declares objectives, and this route has not been stated for them within
|
|
145
|
+
* the restatement interval.
|
|
146
|
+
*/
|
|
147
|
+
declarationFor(snapshot, now = Date.now()) {
|
|
148
|
+
if (this.byHandler.size === 0 || !snapshot.operationId) {
|
|
149
|
+
return undefined;
|
|
150
|
+
}
|
|
151
|
+
const handler = this.handlerOf(snapshot.traces);
|
|
152
|
+
if (!handler) {
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
const declared = this.byHandler.get(handler);
|
|
156
|
+
// Routed for one method: that one, whatever the request was - a HEAD
|
|
157
|
+
// probe of a GET route is still the GET route.
|
|
158
|
+
const method = declared.method ?? snapshot.attributes?.method;
|
|
159
|
+
const route = `${handler} ${method ?? ""} ${snapshot.operationId}`;
|
|
160
|
+
if (snapshot.operationId.length > MAX_ROUTE_LENGTH) {
|
|
161
|
+
if (!this.refusedRoutes.has(route)) {
|
|
162
|
+
this.refusedRoutes.add(route);
|
|
163
|
+
this.logger.warn(`@Objective on ${handler} not declared for a route longer than ${MAX_ROUTE_LENGTH} characters.`);
|
|
164
|
+
}
|
|
165
|
+
return undefined;
|
|
166
|
+
}
|
|
167
|
+
const stated = this.statedAt.get(route);
|
|
168
|
+
if (stated !== undefined && now - stated < RESTATE_EVERY_MS) {
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
this.statedAt.set(route, now);
|
|
172
|
+
return {
|
|
173
|
+
handler,
|
|
174
|
+
operationId: snapshot.operationId,
|
|
175
|
+
...(method ? { method } : {}),
|
|
176
|
+
objectives: declared.objectives,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* The declaring handler whose span sits nearest the root: the request's own
|
|
181
|
+
* handler, however many middlewares and interceptors wrap it.
|
|
182
|
+
*/
|
|
183
|
+
handlerOf(roots) {
|
|
184
|
+
const queue = [...(roots ?? [])];
|
|
185
|
+
for (let searched = 0; searched < queue.length; searched++) {
|
|
186
|
+
if (searched >= MAX_SPANS_SEARCHED) {
|
|
187
|
+
return undefined;
|
|
188
|
+
}
|
|
189
|
+
const node = queue[searched];
|
|
190
|
+
const key = `${node.className}.${node.methodKey}`;
|
|
191
|
+
if (this.byHandler.has(key)) {
|
|
192
|
+
return key;
|
|
193
|
+
}
|
|
194
|
+
queue.push(...(node.children ?? []));
|
|
195
|
+
}
|
|
196
|
+
return undefined;
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
ObjectivesRegistry = __decorate([
|
|
200
|
+
Injectable(),
|
|
201
|
+
__metadata("design:paramtypes", [DiscoveryService,
|
|
202
|
+
MetadataScanner])
|
|
203
|
+
], ObjectivesRegistry);
|
|
204
|
+
export { ObjectivesRegistry };
|
package/dist/observe.module.js
CHANGED
|
@@ -15,6 +15,7 @@ import { DiscoveryModule, DiscoveryService, HttpAdapterHost, MetadataScanner, Mo
|
|
|
15
15
|
import { AsyncLocalStorage } from "async_hooks";
|
|
16
16
|
import { ObserveAgentSharedBuffer } from "./agent/observe-agent.shared-buffer.js";
|
|
17
17
|
import { ObserveAgentWorker } from "./agent/observe-agent.worker.js";
|
|
18
|
+
import { ObjectivesRegistry } from "./objectives/objectives.registry.js";
|
|
18
19
|
import { createInstanceDecorator } from "./instrument/create-instance-decorator.instrument.js";
|
|
19
20
|
import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "./observe.constants.js";
|
|
20
21
|
import { GraphQLObserveAgentService } from "./protocols/graphql-observe-agent.service.js";
|
|
@@ -29,11 +30,13 @@ import { LoggerPatcherService } from "./services/logger-patcher.service.js";
|
|
|
29
30
|
import { NodeRuntimeMetricsService } from "./services/node-runtime-metrics.service.js";
|
|
30
31
|
import { resolveSpanCollapseSettings } from "./services/collapse-repeated-spans.util.js";
|
|
31
32
|
import { OperationTraceRegistry } from "./services/operation-trace.registry.js";
|
|
33
|
+
import { resolveSkipSpans } from "./services/skip-spans.util.js";
|
|
32
34
|
import { StdoutForwarderService } from "./services/stdout-forwarder.service.js";
|
|
33
35
|
import { TraceSamplerService } from "./services/trace-sampler.service.js";
|
|
34
36
|
import { TracerService } from "./services/tracer.service.js";
|
|
35
37
|
import { assertModuleOptions } from "./utils/assert-module-options.util.js";
|
|
36
38
|
import { defaultTraceIdGenerator } from "./utils/default-trace-id-generator.util.js";
|
|
39
|
+
import { inferServiceVersion } from "./utils/infer-service-version.util.js";
|
|
37
40
|
import { LogRedactor } from "./utils/log-redactor.js";
|
|
38
41
|
/**
|
|
39
42
|
* All three async providers are optional on the options type, but one of them
|
|
@@ -41,6 +44,24 @@ import { LogRedactor } from "./utils/log-redactor.js";
|
|
|
41
44
|
* otherwise try to resolve, which fails much later with no mention of why.
|
|
42
45
|
*/
|
|
43
46
|
const MISSING_ASYNC_OPTIONS_PROVIDER = 'ObserveModule.forRootAsync() requires one of "useFactory", "useClass" or "useExisting".';
|
|
47
|
+
/**
|
|
48
|
+
* Names the release when the application did not, so Releases, regressions
|
|
49
|
+
* and fix verification work without anyone threading a version through the
|
|
50
|
+
* build. Resolved once, with the rest of the options: the answer cannot change
|
|
51
|
+
* while the process runs. `serviceVersion: false` opts out.
|
|
52
|
+
*/
|
|
53
|
+
function withServiceVersion(options) {
|
|
54
|
+
if (options.serviceVersion || options.serviceVersion === false) {
|
|
55
|
+
return options;
|
|
56
|
+
}
|
|
57
|
+
const inferred = inferServiceVersion();
|
|
58
|
+
if (options.debug) {
|
|
59
|
+
new Logger("ObserveModule").debug(inferred
|
|
60
|
+
? `serviceVersion "${inferred.version}" inferred from ${inferred.source}.`
|
|
61
|
+
: "serviceVersion is not set and none could be inferred, so telemetry will carry no release.");
|
|
62
|
+
}
|
|
63
|
+
return inferred ? { ...options, serviceVersion: inferred.version } : options;
|
|
64
|
+
}
|
|
44
65
|
export function createObserveModule(options = {}) {
|
|
45
66
|
var ObserveModule_1;
|
|
46
67
|
options.traceIdKey ??= "traceId";
|
|
@@ -66,10 +87,10 @@ export function createObserveModule(options = {}) {
|
|
|
66
87
|
providers: [
|
|
67
88
|
{
|
|
68
89
|
provide: OBSERVE_OPTIONS,
|
|
69
|
-
useValue: {
|
|
90
|
+
useValue: withServiceVersion({
|
|
70
91
|
...options,
|
|
71
92
|
...observeOpts,
|
|
72
|
-
},
|
|
93
|
+
}),
|
|
73
94
|
},
|
|
74
95
|
],
|
|
75
96
|
};
|
|
@@ -108,10 +129,10 @@ export function createObserveModule(options = {}) {
|
|
|
108
129
|
provide: OBSERVE_OPTIONS,
|
|
109
130
|
useFactory: async (...args) => {
|
|
110
131
|
const opts = await useFactory(...args);
|
|
111
|
-
return {
|
|
132
|
+
return withServiceVersion({
|
|
112
133
|
...options,
|
|
113
134
|
...opts,
|
|
114
|
-
};
|
|
135
|
+
});
|
|
115
136
|
},
|
|
116
137
|
inject: asyncOptions.inject || [],
|
|
117
138
|
};
|
|
@@ -122,7 +143,7 @@ export function createObserveModule(options = {}) {
|
|
|
122
143
|
}
|
|
123
144
|
return {
|
|
124
145
|
provide: OBSERVE_OPTIONS,
|
|
125
|
-
useFactory: async (optionsFactory) => ({
|
|
146
|
+
useFactory: async (optionsFactory) => withServiceVersion({
|
|
126
147
|
...options,
|
|
127
148
|
...(await optionsFactory.createObserveOptions()),
|
|
128
149
|
}),
|
|
@@ -147,11 +168,13 @@ export function createObserveModule(options = {}) {
|
|
|
147
168
|
provide: OperationTraceRegistry,
|
|
148
169
|
// The instance already exists (the instrumentation hook below holds
|
|
149
170
|
// it), so this is the one moment the resolved `ObserveOptions` and the
|
|
150
|
-
// registry meet: `spanCollapse` and `redaction` are
|
|
171
|
+
// registry meet: `spanCollapse`, `skipSpans` and `redaction` are
|
|
172
|
+
// applied here.
|
|
151
173
|
// Optional because `ASSERT_MODULE_OPTIONS` owns the missing-options
|
|
152
174
|
// error.
|
|
153
175
|
useFactory: (observeOptions) => {
|
|
154
176
|
operationTraceRegistry.configureSpanCollapse(resolveSpanCollapseSettings(observeOptions?.spanCollapse));
|
|
177
|
+
operationTraceRegistry.configureSkipSpans(resolveSkipSpans(observeOptions?.skipSpans));
|
|
155
178
|
operationTraceRegistry.configureRedaction(observeOptions?.redaction?.enabled === false
|
|
156
179
|
? null
|
|
157
180
|
: new LogRedactor(observeOptions?.redaction));
|
|
@@ -168,6 +191,9 @@ export function createObserveModule(options = {}) {
|
|
|
168
191
|
GraphQLObserveAgentService,
|
|
169
192
|
ObserveAgentWorker,
|
|
170
193
|
ObserveAgentSharedBuffer,
|
|
194
|
+
// Reads `@Objective` off the controllers at boot, for the buffer to
|
|
195
|
+
// pair with the routes their handlers serve.
|
|
196
|
+
ObjectivesRegistry,
|
|
171
197
|
TraceSamplerService,
|
|
172
198
|
NodeRuntimeMetricsService,
|
|
173
199
|
// Registered unconditionally; the service itself is a no-op unless
|
|
@@ -200,6 +226,9 @@ export function createObserveModule(options = {}) {
|
|
|
200
226
|
instance instanceof TraceSamplerService ||
|
|
201
227
|
instance instanceof TracerService ||
|
|
202
228
|
instance instanceof ObserveAgentSharedBuffer ||
|
|
229
|
+
// Consulted as each request's snapshot is buffered: agent bookkeeping,
|
|
230
|
+
// not application code.
|
|
231
|
+
instance instanceof ObjectivesRegistry ||
|
|
203
232
|
// Its methods run *inside* the traces it opens, so instrumenting it
|
|
204
233
|
// would put a span for the agent itself at the root of every GraphQL
|
|
205
234
|
// operation it records.
|
|
@@ -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
|
}
|