@nestjs/observe 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -0
- package/dist/.tsbuildinfo +1 -1
- package/dist/agent/detached-observe-worker.assembly.d.ts +18 -0
- package/dist/agent/detached-observe-worker.assembly.js +29 -0
- package/dist/agent/detached-observe-worker.d.ts +21 -0
- package/dist/agent/detached-observe-worker.js +74 -24
- package/dist/agent/observe-agent.shared-buffer.js +7 -5
- package/dist/agent/observe-agent.worker.js +17 -21
- package/dist/agent/telemetry-wire-contract.js +1 -0
- package/dist/encoders/remap-keys.util.js +6 -0
- package/dist/encoders/request-snapshot.encoder.d.ts +1 -0
- package/dist/encoders/request-snapshot.encoder.js +1 -0
- package/dist/instrument/create-instance-decorator.instrument.js +2 -2
- package/dist/interfaces/observe-options.interface.d.ts +97 -9
- package/dist/interfaces/request-snapshot.interface.d.ts +8 -0
- package/dist/observe.constants.d.ts +16 -0
- package/dist/observe.constants.js +16 -0
- package/dist/observe.module.js +55 -6
- package/dist/outgoing/http.integration.d.ts +36 -0
- package/dist/outgoing/http.integration.js +127 -0
- package/dist/outgoing/mongodb.integration.d.ts +38 -0
- package/dist/outgoing/mongodb.integration.js +141 -0
- package/dist/outgoing/mysql2.integration.d.ts +20 -0
- package/dist/outgoing/mysql2.integration.js +89 -0
- package/dist/outgoing/outgoing-observe-agent.service.d.ts +17 -0
- package/dist/outgoing/outgoing-observe-agent.service.js +123 -0
- package/dist/outgoing/outgoing-span.recorder.d.ts +54 -0
- package/dist/outgoing/outgoing-span.recorder.js +94 -0
- package/dist/outgoing/patch-method.util.d.ts +15 -0
- package/dist/outgoing/patch-method.util.js +29 -0
- package/dist/outgoing/pg.integration.d.ts +22 -0
- package/dist/outgoing/pg.integration.js +66 -0
- package/dist/outgoing/sql-statement.util.d.ts +21 -0
- package/dist/outgoing/sql-statement.util.js +48 -0
- package/dist/protocols/bull-observe-agent.service.d.ts +28 -0
- package/dist/protocols/bull-observe-agent.service.js +130 -0
- package/dist/protocols/graphql-observe-agent.service.js +5 -2
- package/dist/protocols/graphql-operation-parser.d.ts +6 -4
- package/dist/protocols/graphql-operation-parser.js +61 -6
- package/dist/protocols/http-observe-agent.service.js +26 -7
- package/dist/protocols/job-trace-runner.d.ts +77 -0
- package/dist/protocols/job-trace-runner.js +196 -0
- package/dist/protocols/queue-observe-agent.service.d.ts +9 -4
- package/dist/protocols/queue-observe-agent.service.js +36 -95
- package/dist/protocols/ws-observe-agent.service.d.ts +39 -0
- package/dist/protocols/ws-observe-agent.service.js +180 -0
- package/dist/services/operation-trace.registry.d.ts +35 -1
- package/dist/services/operation-trace.registry.js +68 -5
- package/dist/services/trace-sampler.service.d.ts +4 -0
- package/dist/services/tracer.service.js +5 -3
- package/dist/utils/capture-request.util.d.ts +57 -0
- package/dist/utils/capture-request.util.js +116 -0
- package/dist/utils/default-trace-id-generator.util.d.ts +12 -0
- package/dist/utils/default-trace-id-generator.util.js +12 -1
- package/dist/utils/log-redactor.d.ts +20 -1
- package/dist/utils/log-redactor.js +54 -38
- package/dist/utils/optional-peer.util.d.ts +13 -0
- package/dist/utils/optional-peer.util.js +30 -0
- package/dist/utils/redact-url-query.d.ts +10 -1
- package/dist/utils/redact-url-query.js +16 -37
- package/dist/utils/sensitive-keys.d.ts +15 -0
- package/dist/utils/sensitive-keys.js +76 -0
- package/dist/utils/source-context.util.d.ts +6 -0
- package/dist/utils/source-context.util.js +121 -15
- package/dist/utils/source-map-resolver.util.js +12 -0
- package/package.json +35 -2
|
@@ -7,10 +7,10 @@ export interface ParsedGraphQLOperation {
|
|
|
7
7
|
/** The operation's name, when the document gave it one. */
|
|
8
8
|
operationName?: string;
|
|
9
9
|
/**
|
|
10
|
-
* The document with comments dropped, string literals blanked to
|
|
11
|
-
* whitespace collapsed. What a trace records as the shape of the
|
|
12
|
-
* stable across formatting, and stripped of the
|
|
13
|
-
*
|
|
10
|
+
* The document with comments dropped, string and number literals blanked to
|
|
11
|
+
* `_`, and whitespace collapsed. What a trace records as the shape of the
|
|
12
|
+
* request: stable across formatting, and stripped of the token kinds that
|
|
13
|
+
* carry user data inline.
|
|
14
14
|
*/
|
|
15
15
|
sanitizedDocument: string;
|
|
16
16
|
}
|
|
@@ -34,3 +34,5 @@ export declare function toResolveInfoLike(operation: Pick<ParsedGraphQLOperation
|
|
|
34
34
|
export declare function parseGraphQLOperation(document: string | undefined): ParsedGraphQLOperation | undefined;
|
|
35
35
|
/** Test seam: the cache is process-wide and would leak between cases. */
|
|
36
36
|
export declare function clearGraphQLOperationCache(): void;
|
|
37
|
+
/** Test seam: what the cache holds is otherwise unobservable from outside. */
|
|
38
|
+
export declare function graphQLOperationCacheSize(): number;
|
|
@@ -19,12 +19,29 @@ const ROOT_TYPE_BY_KEYWORD = {
|
|
|
19
19
|
};
|
|
20
20
|
/**
|
|
21
21
|
* Parsed results are cached: a client sends the same handful of documents over
|
|
22
|
-
* and over, and re-scanning each one per request is pure waste. Bounded
|
|
23
|
-
* the key is attacker-supplied
|
|
24
|
-
*
|
|
22
|
+
* and over, and re-scanning each one per request is pure waste. Bounded in
|
|
23
|
+
* both dimensions because the key is attacker-supplied: the entry count stops
|
|
24
|
+
* a client sending unique documents from growing the map without limit, and
|
|
25
|
+
* the per-entry size stops 512 entries from being 512 multi-megabyte strings.
|
|
26
|
+
* A document past the size cap is still parsed, just not remembered - a
|
|
27
|
+
* client that sends one is not a client whose documents repeat.
|
|
25
28
|
*/
|
|
26
29
|
const CACHE_LIMIT = 512;
|
|
30
|
+
const MAX_CACHEABLE_DOCUMENT_LENGTH = 16 * 1024;
|
|
27
31
|
const cache = new Map();
|
|
32
|
+
/**
|
|
33
|
+
* Cap on the document shape a trace records.
|
|
34
|
+
*
|
|
35
|
+
* `sanitizedDocument` travels as the snapshot's `originalUrl`, and a query is
|
|
36
|
+
* a request body, not a URL: nothing upstream bounds its size the way the
|
|
37
|
+
* HTTP parser bounds a header. Left uncapped, one multi-megabyte document
|
|
38
|
+
* from an unauthenticated client overflows the shared buffer and takes every
|
|
39
|
+
* other trace, metric and log in that batch down with it. Same order of size
|
|
40
|
+
* as the log-entry cap, for the same reason: past this a document is no
|
|
41
|
+
* longer something a reader scans, and the collector indexes it by trigram.
|
|
42
|
+
*/
|
|
43
|
+
const MAX_SANITIZED_DOCUMENT_LENGTH = 8 * 1024;
|
|
44
|
+
const TRUNCATION_SUFFIX = "... [truncated by observe]";
|
|
28
45
|
/**
|
|
29
46
|
* Builds the `GraphQLResolveInfo`-shaped object the `graphql` options receive.
|
|
30
47
|
*
|
|
@@ -61,6 +78,9 @@ export function parseGraphQLOperation(document) {
|
|
|
61
78
|
return cache.get(document);
|
|
62
79
|
}
|
|
63
80
|
const parsed = scan(document);
|
|
81
|
+
if (document.length > MAX_CACHEABLE_DOCUMENT_LENGTH) {
|
|
82
|
+
return parsed;
|
|
83
|
+
}
|
|
64
84
|
if (cache.size >= CACHE_LIMIT) {
|
|
65
85
|
// Oldest entry out. Map iterates in insertion order, so this is the least
|
|
66
86
|
// recently *added* document rather than the least recently used one - close
|
|
@@ -74,6 +94,10 @@ export function parseGraphQLOperation(document) {
|
|
|
74
94
|
export function clearGraphQLOperationCache() {
|
|
75
95
|
cache.clear();
|
|
76
96
|
}
|
|
97
|
+
/** Test seam: what the cache holds is otherwise unobservable from outside. */
|
|
98
|
+
export function graphQLOperationCacheSize() {
|
|
99
|
+
return cache.size;
|
|
100
|
+
}
|
|
77
101
|
function scan(document) {
|
|
78
102
|
const source = stripIgnoredTokens(document);
|
|
79
103
|
const words = [];
|
|
@@ -133,9 +157,15 @@ function toOperation(words, fieldName, source) {
|
|
|
133
157
|
operationName: words[0] ? words[1] : undefined,
|
|
134
158
|
// Whitespace is collapsed only here, at the end: `source` positions have to
|
|
135
159
|
// stay valid while the scan is still reading from it.
|
|
136
|
-
sanitizedDocument: source.replace(/\s+/g, " ").trim(),
|
|
160
|
+
sanitizedDocument: truncate(source.replace(/\s+/g, " ").trim()),
|
|
137
161
|
};
|
|
138
162
|
}
|
|
163
|
+
function truncate(document) {
|
|
164
|
+
if (document.length <= MAX_SANITIZED_DOCUMENT_LENGTH) {
|
|
165
|
+
return document;
|
|
166
|
+
}
|
|
167
|
+
return (document.slice(0, MAX_SANITIZED_DOCUMENT_LENGTH - TRUNCATION_SUFFIX.length) + TRUNCATION_SUFFIX);
|
|
168
|
+
}
|
|
139
169
|
/**
|
|
140
170
|
* Reads the first field selected inside a selection set, seeing through an
|
|
141
171
|
* alias: `latest: orders` is a selection of `orders`, and that is the name a
|
|
@@ -174,8 +204,8 @@ function readFirstFieldName(source, from) {
|
|
|
174
204
|
return undefined;
|
|
175
205
|
}
|
|
176
206
|
/**
|
|
177
|
-
* Blanks out comments and
|
|
178
|
-
* brace. Offsets are not preserved - nothing downstream maps back to the
|
|
207
|
+
* Blanks out comments, strings and numbers, so none can be mistaken for a name
|
|
208
|
+
* or a brace. Offsets are not preserved - nothing downstream maps back to the
|
|
179
209
|
* original text.
|
|
180
210
|
*/
|
|
181
211
|
function stripIgnoredTokens(document) {
|
|
@@ -206,11 +236,36 @@ function stripIgnoredTokens(document) {
|
|
|
206
236
|
out += "_";
|
|
207
237
|
continue;
|
|
208
238
|
}
|
|
239
|
+
// Numbers go the same way as strings. An inline `verifyOtp(code: 489213)`
|
|
240
|
+
// or `charge(amount: 1999)` is user data exactly as a string literal is,
|
|
241
|
+
// and blanking it also keeps `first: 10` and `first: 20` one shape. A
|
|
242
|
+
// digit that continues a name (`field2`, `$var1`) is not a literal.
|
|
243
|
+
const startsNumber = isDigit(char) || (char === "-" && isDigit(document[index + 1] ?? ""));
|
|
244
|
+
if (startsNumber && !isNameChar(out[out.length - 1] ?? "")) {
|
|
245
|
+
index += 1;
|
|
246
|
+
while (index < document.length && isNumberChar(document, index)) {
|
|
247
|
+
index += 1;
|
|
248
|
+
}
|
|
249
|
+
out += "_";
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
209
252
|
out += char;
|
|
210
253
|
index += 1;
|
|
211
254
|
}
|
|
212
255
|
return out;
|
|
213
256
|
}
|
|
257
|
+
function isDigit(char) {
|
|
258
|
+
return char >= "0" && char <= "9";
|
|
259
|
+
}
|
|
260
|
+
/** Digits, the fraction point, and an exponent with its sign: `-1.5e+3`. */
|
|
261
|
+
function isNumberChar(document, index) {
|
|
262
|
+
const char = document[index];
|
|
263
|
+
if (isDigit(char) || char === "." || char === "e" || char === "E") {
|
|
264
|
+
return true;
|
|
265
|
+
}
|
|
266
|
+
const previous = document[index - 1];
|
|
267
|
+
return ((char === "+" || char === "-") && (previous === "e" || previous === "E"));
|
|
268
|
+
}
|
|
214
269
|
function skipBalanced(source, from, open, close) {
|
|
215
270
|
let depth = 0;
|
|
216
271
|
let index = from;
|
|
@@ -11,13 +11,15 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
11
11
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
12
|
};
|
|
13
13
|
import { Inject, Injectable, } from "@nestjs/common";
|
|
14
|
+
import { captureRequest, shouldCaptureRequest, } from "../utils/capture-request.util.js";
|
|
14
15
|
import { HttpAdapterHost } from "@nestjs/core";
|
|
15
16
|
import { AsyncLocalStorage } from "async_hooks";
|
|
16
17
|
import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
|
|
17
|
-
import { OBSERVE_OPTIONS } from "../observe.constants.js";
|
|
18
|
+
import { OBSERVE_OPTIONS, TRACE_REGISTRY_KEY } from "../observe.constants.js";
|
|
18
19
|
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
19
20
|
import { TraceSamplerService } from "../services/trace-sampler.service.js";
|
|
20
21
|
import { redactUrlQuery } from "../utils/redact-url-query.js";
|
|
22
|
+
import { uuidv7 } from "../utils/uuid-v7.util.js";
|
|
21
23
|
/**
|
|
22
24
|
* How long an aborted request's handler gets to finish its spans before the
|
|
23
25
|
* trace is dropped from the registry. Generous next to a typical handler, tiny
|
|
@@ -62,7 +64,8 @@ let HttpObserveAgentService = class HttpObserveAgentService {
|
|
|
62
64
|
if (!store) {
|
|
63
65
|
return;
|
|
64
66
|
}
|
|
65
|
-
const traceId = store.get(
|
|
67
|
+
const traceId = store.get(TRACE_REGISTRY_KEY) ??
|
|
68
|
+
store.get(this.options.traceIdKey);
|
|
66
69
|
if (!traceId) {
|
|
67
70
|
return;
|
|
68
71
|
}
|
|
@@ -120,19 +123,28 @@ let HttpObserveAgentService = class HttpObserveAgentService {
|
|
|
120
123
|
// disclosure either way. A configured regex still applies, on top rather
|
|
121
124
|
// than instead - it exists for the keys only that deployment knows
|
|
122
125
|
// about.
|
|
123
|
-
const redactedUrl = redactUrlQuery(req.url);
|
|
126
|
+
const redactedUrl = redactUrlQuery(req.url, this.operationTraceRegistry.getRedactor());
|
|
124
127
|
const originalUrl = this.queryParamsObfuscateRegex
|
|
125
128
|
? redactedUrl.replaceAll(this.queryParamsObfuscateRegex, "[REDACTED]")
|
|
126
129
|
: redactedUrl;
|
|
127
|
-
this
|
|
130
|
+
// An adopted `x-request-id` is not unique to this request: a caller
|
|
131
|
+
// that fans out, or retries, sends the same id twice, and both requests
|
|
132
|
+
// can be open here at once. The second gets a registry key of its own -
|
|
133
|
+
// only the second, so the ordinary request is still keyed by its id.
|
|
134
|
+
let registryKey = traceId;
|
|
135
|
+
if (this.operationTraceRegistry.hasTrace(traceId)) {
|
|
136
|
+
registryKey = uuidv7();
|
|
137
|
+
store.set(TRACE_REGISTRY_KEY, registryKey);
|
|
138
|
+
}
|
|
139
|
+
this.operationTraceRegistry.startTrace(registryKey, {
|
|
128
140
|
protocol: req.protocol,
|
|
129
141
|
tags: this.options.http?.tags,
|
|
130
142
|
attributes: {
|
|
131
143
|
method: req.method,
|
|
132
144
|
originalUrl,
|
|
133
145
|
},
|
|
134
|
-
});
|
|
135
|
-
this.evictTraceOnClientAbort(res,
|
|
146
|
+
}, traceId);
|
|
147
|
+
this.evictTraceOnClientAbort(res, registryKey);
|
|
136
148
|
done();
|
|
137
149
|
});
|
|
138
150
|
}
|
|
@@ -141,7 +153,8 @@ let HttpObserveAgentService = class HttpObserveAgentService {
|
|
|
141
153
|
if (!store) {
|
|
142
154
|
return;
|
|
143
155
|
}
|
|
144
|
-
const traceId = store.get(
|
|
156
|
+
const traceId = store.get(TRACE_REGISTRY_KEY) ??
|
|
157
|
+
store.get(this.options.traceIdKey);
|
|
145
158
|
if (!traceId) {
|
|
146
159
|
return;
|
|
147
160
|
}
|
|
@@ -158,6 +171,12 @@ let HttpObserveAgentService = class HttpObserveAgentService {
|
|
|
158
171
|
if (!snapshot) {
|
|
159
172
|
return;
|
|
160
173
|
}
|
|
174
|
+
if (shouldCaptureRequest(snapshot, this.options.http?.capture)) {
|
|
175
|
+
const captured = captureRequest(req, this.options.http?.capture, this.operationTraceRegistry.getRedactor());
|
|
176
|
+
if (captured) {
|
|
177
|
+
snapshot.request = captured;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
161
180
|
this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
|
|
162
181
|
}, 0);
|
|
163
182
|
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { Logger } from "@nestjs/common";
|
|
2
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
3
|
+
import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
|
|
4
|
+
import { JobSnapshot, ObserveModuleOptionsWithDefaults } from "../interfaces/index.js";
|
|
5
|
+
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
6
|
+
import { KeyOf } from "../types/key-of.type.js";
|
|
7
|
+
/** What a queue driver knows about the run it is about to start. */
|
|
8
|
+
export interface JobRunDescriptor {
|
|
9
|
+
queueName: string;
|
|
10
|
+
name: string;
|
|
11
|
+
id?: string | number;
|
|
12
|
+
/** The job's options as the driver read them back from Redis. */
|
|
13
|
+
opts?: Record<string, unknown>;
|
|
14
|
+
metadata: Partial<JobSnapshot>;
|
|
15
|
+
}
|
|
16
|
+
type JobStatus = NonNullable<JobSnapshot["status"]>;
|
|
17
|
+
/** The slice of a queue's prototype the enqueue patch touches. */
|
|
18
|
+
interface QueuePrototypeLike {
|
|
19
|
+
add?: (...args: any[]) => unknown;
|
|
20
|
+
addBulk?: (jobs: any[]) => unknown;
|
|
21
|
+
[key: symbol]: unknown;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The part of job tracing that is the same whichever driver runs the queue:
|
|
25
|
+
* stamping the active trace id onto a job as it is enqueued, and opening the
|
|
26
|
+
* run under that id when a worker picks it up.
|
|
27
|
+
*
|
|
28
|
+
* A plain class rather than a provider - each driver agent builds its own from
|
|
29
|
+
* what it was injected with, so supporting another driver adds no wiring to
|
|
30
|
+
* the module.
|
|
31
|
+
*/
|
|
32
|
+
export declare class JobTraceRunner<Store extends Record<string, unknown>> {
|
|
33
|
+
private readonly observeAgentSharedBuffer;
|
|
34
|
+
private readonly options;
|
|
35
|
+
private readonly operationTraceRegistry;
|
|
36
|
+
private readonly asyncLocalStorage;
|
|
37
|
+
private readonly logger;
|
|
38
|
+
constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>, logger: Logger);
|
|
39
|
+
/**
|
|
40
|
+
* Makes `add` and `addBulk` carry the enqueuing operation's trace id, so the
|
|
41
|
+
* run reports under the request - or job, or cron firing - that caused it.
|
|
42
|
+
*
|
|
43
|
+
* The originals are parked on the prototype under a symbol: a second agent
|
|
44
|
+
* (a second Nest app in one process, a test suite) replaces the wrapper
|
|
45
|
+
* instead of wrapping it again.
|
|
46
|
+
*/
|
|
47
|
+
patchEnqueue(prototype: QueuePrototypeLike,
|
|
48
|
+
/** Index of the options argument in `add`, given the arguments passed. */
|
|
49
|
+
optsIndexOf: (args: unknown[]) => number): void;
|
|
50
|
+
/**
|
|
51
|
+
* Returns the options with the active trace id added, or `undefined` when
|
|
52
|
+
* there is nothing to add.
|
|
53
|
+
*
|
|
54
|
+
* A repeatable job is left alone: every repetition would otherwise report
|
|
55
|
+
* under the one request that happened to register the schedule, for as long
|
|
56
|
+
* as the schedule lives. Those runs are cron firings, and each mints its own
|
|
57
|
+
* id like any other.
|
|
58
|
+
*/
|
|
59
|
+
private stampTraceId;
|
|
60
|
+
/**
|
|
61
|
+
* The id stamped at enqueue time, if it is one this agent would have minted
|
|
62
|
+
* or adopted itself. Job options are readable and writable by anything with
|
|
63
|
+
* access to Redis, so it is held to the same shape as an inbound
|
|
64
|
+
* `x-request-id`.
|
|
65
|
+
*/
|
|
66
|
+
private readInheritedTraceId;
|
|
67
|
+
/**
|
|
68
|
+
* Runs one job under a trace.
|
|
69
|
+
*
|
|
70
|
+
* `invoke` is handed `settle` for drivers whose handlers finish through a
|
|
71
|
+
* callback; pass `settlesItself` for those, and a plain return is then not
|
|
72
|
+
* read as completion. Promise-returning and throwing handlers are settled
|
|
73
|
+
* here either way.
|
|
74
|
+
*/
|
|
75
|
+
run<T>(job: JobRunDescriptor, invoke: (settle: (status: JobStatus) => void) => T, settlesItself?: boolean): T;
|
|
76
|
+
}
|
|
77
|
+
export {};
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { JOB_TRACE_OPTION_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
|
|
2
|
+
import { REQUEST_ID_PATTERN } from "../utils/default-trace-id-generator.util.js";
|
|
3
|
+
import { uuidv7 } from "../utils/uuid-v7.util.js";
|
|
4
|
+
const ORIGINAL_ADD = Symbol.for("nestjs.observe.queue.add");
|
|
5
|
+
const ORIGINAL_ADD_BULK = Symbol.for("nestjs.observe.queue.addBulk");
|
|
6
|
+
/**
|
|
7
|
+
* The part of job tracing that is the same whichever driver runs the queue:
|
|
8
|
+
* stamping the active trace id onto a job as it is enqueued, and opening the
|
|
9
|
+
* run under that id when a worker picks it up.
|
|
10
|
+
*
|
|
11
|
+
* A plain class rather than a provider - each driver agent builds its own from
|
|
12
|
+
* what it was injected with, so supporting another driver adds no wiring to
|
|
13
|
+
* the module.
|
|
14
|
+
*/
|
|
15
|
+
export class JobTraceRunner {
|
|
16
|
+
observeAgentSharedBuffer;
|
|
17
|
+
options;
|
|
18
|
+
operationTraceRegistry;
|
|
19
|
+
asyncLocalStorage;
|
|
20
|
+
logger;
|
|
21
|
+
constructor(observeAgentSharedBuffer, options, operationTraceRegistry, asyncLocalStorage, logger) {
|
|
22
|
+
this.observeAgentSharedBuffer = observeAgentSharedBuffer;
|
|
23
|
+
this.options = options;
|
|
24
|
+
this.operationTraceRegistry = operationTraceRegistry;
|
|
25
|
+
this.asyncLocalStorage = asyncLocalStorage;
|
|
26
|
+
this.logger = logger;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Makes `add` and `addBulk` carry the enqueuing operation's trace id, so the
|
|
30
|
+
* run reports under the request - or job, or cron firing - that caused it.
|
|
31
|
+
*
|
|
32
|
+
* The originals are parked on the prototype under a symbol: a second agent
|
|
33
|
+
* (a second Nest app in one process, a test suite) replaces the wrapper
|
|
34
|
+
* instead of wrapping it again.
|
|
35
|
+
*/
|
|
36
|
+
patchEnqueue(prototype,
|
|
37
|
+
/** Index of the options argument in `add`, given the arguments passed. */
|
|
38
|
+
optsIndexOf) {
|
|
39
|
+
const stamp = (opts) => this.stampTraceId(opts);
|
|
40
|
+
const originalAdd = (prototype[ORIGINAL_ADD] ??= prototype.add);
|
|
41
|
+
if (typeof originalAdd === "function") {
|
|
42
|
+
prototype.add = function (...args) {
|
|
43
|
+
const index = optsIndexOf(args);
|
|
44
|
+
const stamped = stamp(args[index]);
|
|
45
|
+
if (stamped) {
|
|
46
|
+
args[index] = stamped;
|
|
47
|
+
}
|
|
48
|
+
return originalAdd.apply(this, args);
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
const originalAddBulk = (prototype[ORIGINAL_ADD_BULK] ??=
|
|
52
|
+
prototype.addBulk);
|
|
53
|
+
if (typeof originalAddBulk === "function") {
|
|
54
|
+
prototype.addBulk = function (jobs) {
|
|
55
|
+
if (!Array.isArray(jobs)) {
|
|
56
|
+
return originalAddBulk.call(this, jobs);
|
|
57
|
+
}
|
|
58
|
+
return originalAddBulk.call(this, jobs.map((job) => {
|
|
59
|
+
const stamped = stamp(job?.opts);
|
|
60
|
+
return stamped ? { ...job, opts: stamped } : job;
|
|
61
|
+
}));
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Returns the options with the active trace id added, or `undefined` when
|
|
67
|
+
* there is nothing to add.
|
|
68
|
+
*
|
|
69
|
+
* A repeatable job is left alone: every repetition would otherwise report
|
|
70
|
+
* under the one request that happened to register the schedule, for as long
|
|
71
|
+
* as the schedule lives. Those runs are cron firings, and each mints its own
|
|
72
|
+
* id like any other.
|
|
73
|
+
*/
|
|
74
|
+
stampTraceId(opts) {
|
|
75
|
+
const traceId = this.asyncLocalStorage
|
|
76
|
+
.getStore()
|
|
77
|
+
?.get(this.options.traceIdKey);
|
|
78
|
+
if (typeof traceId !== "string") {
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
if (opts !== undefined && (typeof opts !== "object" || opts === null)) {
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
const current = (opts ?? {});
|
|
85
|
+
if (current["repeat"] || current[JOB_TRACE_OPTION_KEY] !== undefined) {
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
return { ...current, [JOB_TRACE_OPTION_KEY]: traceId };
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The id stamped at enqueue time, if it is one this agent would have minted
|
|
92
|
+
* or adopted itself. Job options are readable and writable by anything with
|
|
93
|
+
* access to Redis, so it is held to the same shape as an inbound
|
|
94
|
+
* `x-request-id`.
|
|
95
|
+
*/
|
|
96
|
+
readInheritedTraceId(opts) {
|
|
97
|
+
const inherited = opts?.[JOB_TRACE_OPTION_KEY];
|
|
98
|
+
return typeof inherited === "string" && REQUEST_ID_PATTERN.test(inherited)
|
|
99
|
+
? inherited
|
|
100
|
+
: undefined;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Runs one job under a trace.
|
|
104
|
+
*
|
|
105
|
+
* `invoke` is handed `settle` for drivers whose handlers finish through a
|
|
106
|
+
* callback; pass `settlesItself` for those, and a plain return is then not
|
|
107
|
+
* read as completion. Promise-returning and throwing handlers are settled
|
|
108
|
+
* here either way.
|
|
109
|
+
*/
|
|
110
|
+
run(job, invoke, settlesItself = false) {
|
|
111
|
+
const hasOuterContext = this.asyncLocalStorage
|
|
112
|
+
.getStore()
|
|
113
|
+
?.has(this.options.traceIdKey);
|
|
114
|
+
// The same map `run` is given, rather than `getStore()` inside the
|
|
115
|
+
// callback: identical object, one lookup fewer, and it is known to exist.
|
|
116
|
+
const store = new Map();
|
|
117
|
+
return this.asyncLocalStorage.run(store, () => {
|
|
118
|
+
if (hasOuterContext) {
|
|
119
|
+
// If the outer context already has a trace ID
|
|
120
|
+
// ignore the inner context
|
|
121
|
+
if (this.options.debug) {
|
|
122
|
+
this.logger.debug(`Outer context already has a trace ID. Skipping inner context for job "${job.name}" job.id: ${job.id}`);
|
|
123
|
+
}
|
|
124
|
+
return invoke(() => undefined);
|
|
125
|
+
}
|
|
126
|
+
// The registry key is always this run's own. The inherited id may belong
|
|
127
|
+
// to a request still open in this process, and a retry reuses it.
|
|
128
|
+
const registryKey = uuidv7();
|
|
129
|
+
const traceId = this.readInheritedTraceId(job.opts) ?? registryKey;
|
|
130
|
+
store.set(this.options.traceIdKey, traceId);
|
|
131
|
+
store.set(TRACE_REGISTRY_KEY, registryKey);
|
|
132
|
+
const attributes = this.options.jobs?.setAttributes?.({
|
|
133
|
+
queueName: job.queueName,
|
|
134
|
+
name: job.name,
|
|
135
|
+
id: job.id,
|
|
136
|
+
});
|
|
137
|
+
if (attributes) {
|
|
138
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
139
|
+
store.set(key, value);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
this.operationTraceRegistry.startTrace(registryKey, {
|
|
143
|
+
tags: this.options.jobs?.tags,
|
|
144
|
+
queueName: job.queueName,
|
|
145
|
+
name: job.name,
|
|
146
|
+
id: typeof job.id === "number" ? `${job.id}` : job.id,
|
|
147
|
+
...job.metadata,
|
|
148
|
+
}, traceId);
|
|
149
|
+
let settled = false;
|
|
150
|
+
const settle = (status) => {
|
|
151
|
+
if (settled) {
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
settled = true;
|
|
155
|
+
setTimeout(async () => {
|
|
156
|
+
this.operationTraceRegistry.endTrace(registryKey, { status });
|
|
157
|
+
const snapshot = (await this.operationTraceRegistry.pluckSnapshot(registryKey));
|
|
158
|
+
// `pluckSnapshot` deletes what it returns, so a trace already
|
|
159
|
+
// plucked answers undefined, and the encoder would dereference it
|
|
160
|
+
// inside a `setTimeout`, where no try/catch can reach: an unhandled
|
|
161
|
+
// TypeError that took the whole process down.
|
|
162
|
+
//
|
|
163
|
+
// Dropped rather than reported: there is no snapshot, so there is
|
|
164
|
+
// nothing to send, and losing one job's self-instrumentation is
|
|
165
|
+
// not worth a crash loop.
|
|
166
|
+
if (!snapshot) {
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
this.observeAgentSharedBuffer.insertJobSnapshot(snapshot);
|
|
170
|
+
}, 0);
|
|
171
|
+
};
|
|
172
|
+
try {
|
|
173
|
+
const returnValue = invoke(settle);
|
|
174
|
+
if (returnValue instanceof Promise) {
|
|
175
|
+
return returnValue
|
|
176
|
+
.then((ret) => {
|
|
177
|
+
settle("completed");
|
|
178
|
+
return ret;
|
|
179
|
+
})
|
|
180
|
+
.catch((error) => {
|
|
181
|
+
settle("failed");
|
|
182
|
+
throw error;
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
if (!settlesItself) {
|
|
186
|
+
settle("completed");
|
|
187
|
+
}
|
|
188
|
+
return returnValue;
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
settle("failed");
|
|
192
|
+
throw error;
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
}
|
|
@@ -4,11 +4,8 @@ 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
6
|
export declare class QueueObserveAgentService<Store extends Record<string, unknown>> {
|
|
7
|
-
private readonly observeAgentSharedBuffer;
|
|
8
|
-
private readonly options;
|
|
9
|
-
private readonly operationTraceRegistry;
|
|
10
|
-
private readonly asyncLocalStorage;
|
|
11
7
|
private readonly logger;
|
|
8
|
+
private readonly runner;
|
|
12
9
|
constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>);
|
|
13
10
|
/**
|
|
14
11
|
* Queue-level facts BullMQ already tracks but that never reached telemetry:
|
|
@@ -29,4 +26,12 @@ export declare class QueueObserveAgentService<Store extends Record<string, unkno
|
|
|
29
26
|
*/
|
|
30
27
|
private loadProcessorDecoratorService;
|
|
31
28
|
private patchDecorate;
|
|
29
|
+
/**
|
|
30
|
+
* The enqueuing half: without it a worker has no way to learn which
|
|
31
|
+
* operation a job came from, and every run opens an unrelated trace.
|
|
32
|
+
*
|
|
33
|
+
* `bullmq` is loaded the way `@nestjs/bullmq` loads it, so the prototype
|
|
34
|
+
* patched here is the one behind every `@InjectQueue()`.
|
|
35
|
+
*/
|
|
36
|
+
private patchQueue;
|
|
32
37
|
}
|