@nestjs/observe 0.3.25 → 0.3.27
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 +55 -2
- package/dist/agent/detached-observe-worker.js +50 -6
- package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
- package/dist/agent/observe-agent.shared-buffer.js +201 -19
- package/dist/agent/observe-agent.worker.d.ts +22 -2
- package/dist/agent/observe-agent.worker.js +43 -7
- package/dist/agent/telemetry-wire-contract.js +10 -4
- package/dist/cli/agent-notes.js +16 -4
- package/dist/cli/link.js +51 -4
- package/dist/cli/observe-cli.js +1 -19
- package/dist/cli/open-url.d.ts +27 -0
- package/dist/cli/open-url.js +63 -0
- package/dist/cli/package-manager.d.ts +6 -0
- package/dist/cli/package-manager.js +60 -3
- package/dist/cli/project-files.d.ts +62 -1
- package/dist/cli/project-files.js +229 -7
- package/dist/cli/project-setup.d.ts +6 -0
- package/dist/cli/project-setup.js +14 -1
- package/dist/cli/wire-application.js +6 -0
- package/dist/custom-metrics/counter.d.ts +13 -2
- package/dist/custom-metrics/counter.js +33 -16
- package/dist/custom-metrics/finite-value.util.d.ts +14 -0
- package/dist/custom-metrics/finite-value.util.js +33 -1
- package/dist/custom-metrics/gauge.d.ts +2 -0
- package/dist/custom-metrics/gauge.js +41 -17
- package/dist/custom-metrics/label-values.util.d.ts +37 -0
- package/dist/custom-metrics/label-values.util.js +51 -0
- package/dist/custom-metrics/summary.d.ts +23 -0
- package/dist/custom-metrics/summary.js +90 -12
- package/dist/instrument/create-instance-decorator.instrument.js +504 -116
- package/dist/instrument/raw-receiver.d.ts +6 -0
- package/dist/instrument/raw-receiver.js +32 -0
- package/dist/interfaces/observe-options.interface.d.ts +17 -6
- package/dist/objectives/objectives.registry.js +12 -0
- package/dist/observe.module.js +119 -3
- package/dist/otlp/otlp-encoders.js +22 -5
- package/dist/otlp/otlp-span.mapper.d.ts +2 -0
- package/dist/otlp/otlp-span.mapper.js +26 -4
- package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
- package/dist/otlp/otlp-trace-exporter.service.js +295 -43
- package/dist/outgoing/http.integration.d.ts +8 -4
- package/dist/outgoing/http.integration.js +49 -17
- package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
- package/dist/outgoing/llm/llm-providers.d.ts +16 -4
- package/dist/outgoing/llm/llm-providers.js +72 -22
- package/dist/outgoing/llm/llm-usage.d.ts +11 -6
- package/dist/outgoing/llm/llm-usage.js +72 -25
- package/dist/outgoing/mongodb.integration.d.ts +3 -1
- package/dist/outgoing/mongodb.integration.js +93 -18
- package/dist/outgoing/mssql.integration.js +25 -6
- package/dist/outgoing/mysql2.integration.js +17 -1
- package/dist/outgoing/outgoing-observe-agent.service.js +20 -4
- package/dist/outgoing/outgoing-span.recorder.js +17 -3
- package/dist/outgoing/pg.integration.d.ts +3 -2
- package/dist/outgoing/pg.integration.js +39 -11
- package/dist/outgoing/sql-statement.util.js +139 -21
- package/dist/outgoing/undici.integration.d.ts +13 -0
- package/dist/outgoing/undici.integration.js +68 -0
- package/dist/protocols/bull-observe-agent.service.js +23 -12
- package/dist/protocols/deferred-trace-completion.d.ts +17 -3
- package/dist/protocols/deferred-trace-completion.js +76 -9
- package/dist/protocols/graphql-observe-agent.service.d.ts +97 -6
- package/dist/protocols/graphql-observe-agent.service.js +354 -19
- package/dist/protocols/graphql-operation-parser.js +111 -26
- package/dist/protocols/http-observe-agent.service.d.ts +50 -9
- package/dist/protocols/http-observe-agent.service.js +220 -59
- package/dist/protocols/job-trace-runner.d.ts +42 -3
- package/dist/protocols/job-trace-runner.js +197 -36
- package/dist/protocols/queue-observe-agent.service.js +44 -20
- package/dist/protocols/rpc-observe-agent.service.d.ts +111 -8
- package/dist/protocols/rpc-observe-agent.service.js +332 -56
- package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
- package/dist/protocols/ws-observe-agent.service.js +227 -21
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/logger-patcher.service.js +16 -7
- package/dist/services/operation-trace.registry.d.ts +58 -1
- package/dist/services/operation-trace.registry.js +576 -63
- package/dist/services/stdout-forwarder.service.d.ts +69 -0
- package/dist/services/stdout-forwarder.service.js +308 -51
- package/dist/services/tracer.service.d.ts +39 -11
- package/dist/services/tracer.service.js +145 -36
- package/dist/utils/capture-request.util.d.ts +3 -1
- package/dist/utils/capture-request.util.js +128 -12
- package/dist/utils/context-accessor.util.d.ts +16 -0
- package/dist/utils/context-accessor.util.js +28 -0
- package/dist/utils/default-trace-id-generator.util.js +5 -7
- package/dist/utils/error-stack.util.d.ts +13 -0
- package/dist/utils/error-stack.util.js +166 -0
- package/dist/utils/fit-to-length.util.js +33 -10
- package/dist/utils/log-line.parser.d.ts +22 -0
- package/dist/utils/log-line.parser.js +20 -7
- package/dist/utils/log-redactor.d.ts +14 -0
- package/dist/utils/log-redactor.js +690 -65
- package/dist/utils/operation-state.util.d.ts +39 -0
- package/dist/utils/operation-state.util.js +50 -0
- package/dist/utils/redact-url-query.d.ts +37 -4
- package/dist/utils/redact-url-query.js +197 -32
- package/dist/utils/sensitive-keys.d.ts +4 -1
- package/dist/utils/sensitive-keys.js +48 -10
- package/dist/utils/shared-hook-slot.util.d.ts +48 -0
- package/dist/utils/shared-hook-slot.util.js +103 -0
- package/dist/utils/source-context.util.d.ts +14 -0
- package/dist/utils/source-context.util.js +142 -43
- package/dist/utils/source-map-resolver.util.js +33 -6
- package/dist/utils/store-copy.util.d.ts +10 -0
- package/dist/utils/store-copy.util.js +43 -0
- package/dist/utils/trace-context.util.js +21 -6
- package/package.json +2 -2
|
@@ -4,8 +4,54 @@ import { handedOnTraceContext } from "../utils/trace-context.util.js";
|
|
|
4
4
|
import { continueHandedOnTrace, traceparentToHandOn, } from "../utils/trace-handoff.util.js";
|
|
5
5
|
import { uuidv7 } from "../utils/uuid-v7.util.js";
|
|
6
6
|
import { deferTraceCompletion, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
|
|
7
|
+
import { endOperation, liveTraceId, openOperation, } from "../utils/operation-state.util.js";
|
|
8
|
+
/** The later of the two ends of the range a `Date` can hold, in ms. */
|
|
9
|
+
const MAX_DATE_TIMESTAMP = 8.64e15;
|
|
10
|
+
/**
|
|
11
|
+
* When a job was enqueued, and how long it waited for a worker once it could
|
|
12
|
+
* run - left out when its times are not ones a `Date` can hold.
|
|
13
|
+
*
|
|
14
|
+
* Job fields are read back from Redis, which anything with access to it can
|
|
15
|
+
* write, and BullMQ takes a caller's `timestamp` option unchecked:
|
|
16
|
+
* `new Date(8.64e15 + 1).toISOString()` throws, and adding an object-valued
|
|
17
|
+
* `delay` to a number throws too. Both ran before the processor, so the
|
|
18
|
+
* worker failed a job that completes without the agent.
|
|
19
|
+
*
|
|
20
|
+
* `timestamp` is when the job was created, not when it became runnable, so for
|
|
21
|
+
* a delayed job the gap between the two is a schedule the caller asked for -
|
|
22
|
+
* not a queue that fell behind. Counting it would report a job dated a week
|
|
23
|
+
* out as a week of backlog and drag `job_wait_p95` with it. The delay is read
|
|
24
|
+
* off the options when the job's own reads 0: it is reset as a delayed job is
|
|
25
|
+
* promoted, so by the time a worker holds the job it says 0 whatever was
|
|
26
|
+
* asked for. `||`, not `??`, for that reason.
|
|
27
|
+
*/
|
|
28
|
+
export function readJobTimes(job) {
|
|
29
|
+
const { timestamp } = job;
|
|
30
|
+
if (!isDateTimestamp(timestamp)) {
|
|
31
|
+
return {};
|
|
32
|
+
}
|
|
33
|
+
// Falling back to now() keeps the measurement honest if it is missing.
|
|
34
|
+
const startedAt = isDateTimestamp(job.processedOn)
|
|
35
|
+
? job.processedOn
|
|
36
|
+
: Date.now();
|
|
37
|
+
const asked = job.delay || job.opts?.delay;
|
|
38
|
+
const delay = typeof asked === "number" && Number.isFinite(asked) ? asked : 0;
|
|
39
|
+
return {
|
|
40
|
+
enqueuedAt: new Date(timestamp).toISOString(),
|
|
41
|
+
waitDuration: Math.max(0, startedAt - (timestamp + delay)),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function isDateTimestamp(value) {
|
|
45
|
+
return (typeof value === "number" &&
|
|
46
|
+
Number.isFinite(value) &&
|
|
47
|
+
Math.abs(value) <= MAX_DATE_TIMESTAMP);
|
|
48
|
+
}
|
|
7
49
|
const ORIGINAL_ADD = Symbol.for("nestjs.observe.queue.add");
|
|
8
50
|
const ORIGINAL_ADD_BULK = Symbol.for("nestjs.observe.queue.addBulk");
|
|
51
|
+
/** What Bull and BullMQ read by name off an entry handed to `addBulk`. */
|
|
52
|
+
const BULK_ENTRY_KEYS_READ_BY_NAME = ["name", "data"];
|
|
53
|
+
/** What they read by name off a job's options; the rest they spread. */
|
|
54
|
+
const JOB_OPTION_KEYS_READ_BY_NAME = ["jobId", "telemetry"];
|
|
9
55
|
/** Where a run records which job it is running, for a layer nested inside it. */
|
|
10
56
|
const ACTIVE_JOB_KEY = Symbol("nestjs.observe.activeJob");
|
|
11
57
|
/**
|
|
@@ -25,6 +71,41 @@ function parkOriginal(prototype, key, method) {
|
|
|
25
71
|
}
|
|
26
72
|
return prototype[key];
|
|
27
73
|
}
|
|
74
|
+
/**
|
|
75
|
+
* Lets a driver read off `copy` what it would have read off `source`, the
|
|
76
|
+
* object the caller passed and the copy stands in for.
|
|
77
|
+
*
|
|
78
|
+
* A spread copies own enumerable properties, and the drivers read a few -
|
|
79
|
+
* `keys` - by name instead, which reaches what the caller keeps elsewhere
|
|
80
|
+
* too: an accessor on the prototype of a job class, an options class or an
|
|
81
|
+
* ODM document. A job whose `data` was a getter ran with `{}`, and options
|
|
82
|
+
* whose `jobId` was one enqueued the job again on every call instead of
|
|
83
|
+
* finding it. Each such key the spread left behind is read through to
|
|
84
|
+
* `source`, as the driver would have read it, and kept off the copy's own
|
|
85
|
+
* enumerable properties, so a spread the driver takes of the copy leaves it
|
|
86
|
+
* behind as a spread of `source` would have.
|
|
87
|
+
*/
|
|
88
|
+
function readableByName(copy, source, keys) {
|
|
89
|
+
for (const key of keys) {
|
|
90
|
+
if (Object.prototype.hasOwnProperty.call(copy, key) || !(key in source)) {
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
Object.defineProperty(copy, key, {
|
|
94
|
+
get: () => source[key],
|
|
95
|
+
set(value) {
|
|
96
|
+
Object.defineProperty(this, key, {
|
|
97
|
+
value,
|
|
98
|
+
writable: true,
|
|
99
|
+
enumerable: true,
|
|
100
|
+
configurable: true,
|
|
101
|
+
});
|
|
102
|
+
},
|
|
103
|
+
enumerable: false,
|
|
104
|
+
configurable: true,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
return copy;
|
|
108
|
+
}
|
|
28
109
|
function isSameJob(outer, job) {
|
|
29
110
|
const active = outer;
|
|
30
111
|
return active?.queueName === job.queueName && active.id === job.id;
|
|
@@ -79,8 +160,15 @@ export class JobTraceRunner {
|
|
|
79
160
|
return originalAddBulk.call(this, jobs);
|
|
80
161
|
}
|
|
81
162
|
return originalAddBulk.call(this, jobs.map((job) => {
|
|
82
|
-
|
|
83
|
-
|
|
163
|
+
// What is no job is the driver's to refuse, as it does without
|
|
164
|
+
// the agent: stamped, a null entry became an empty job.
|
|
165
|
+
if (typeof job !== "object" || job === null) {
|
|
166
|
+
return job;
|
|
167
|
+
}
|
|
168
|
+
const stamped = stamp(job.opts);
|
|
169
|
+
return stamped
|
|
170
|
+
? readableByName({ ...job, opts: stamped }, job, BULK_ENTRY_KEYS_READ_BY_NAME)
|
|
171
|
+
: job;
|
|
84
172
|
}));
|
|
85
173
|
};
|
|
86
174
|
}
|
|
@@ -100,8 +188,10 @@ export class JobTraceRunner {
|
|
|
100
188
|
*/
|
|
101
189
|
stampTraceId(opts) {
|
|
102
190
|
const store = this.asyncLocalStorage.getStore();
|
|
103
|
-
|
|
104
|
-
|
|
191
|
+
// A job a finished operation's timer enqueues, past the grace period,
|
|
192
|
+
// is no part of that operation's trace.
|
|
193
|
+
const traceId = liveTraceId(store, this.options.traceIdKey);
|
|
194
|
+
if (traceId === undefined) {
|
|
105
195
|
return undefined;
|
|
106
196
|
}
|
|
107
197
|
if (opts !== undefined && (typeof opts !== "object" || opts === null)) {
|
|
@@ -111,10 +201,7 @@ export class JobTraceRunner {
|
|
|
111
201
|
if (current["repeat"] || current[JOB_TRACE_OPTION_KEY] !== undefined) {
|
|
112
202
|
return undefined;
|
|
113
203
|
}
|
|
114
|
-
const stamped = {
|
|
115
|
-
...current,
|
|
116
|
-
[JOB_TRACE_OPTION_KEY]: traceId,
|
|
117
|
-
};
|
|
204
|
+
const stamped = readableByName({ ...current, [JOB_TRACE_OPTION_KEY]: traceId }, current, JOB_OPTION_KEYS_READ_BY_NAME);
|
|
118
205
|
if (this.openTelemetryInteropOn() &&
|
|
119
206
|
current[JOB_TRACE_CONTEXT_OPTION_KEY] === undefined) {
|
|
120
207
|
stamped[JOB_TRACE_CONTEXT_OPTION_KEY] = traceparentToHandOn(store, traceId);
|
|
@@ -172,9 +259,10 @@ export class JobTraceRunner {
|
|
|
172
259
|
* Runs one job under a trace.
|
|
173
260
|
*
|
|
174
261
|
* `invoke` is handed `settle` for drivers whose handlers finish through a
|
|
175
|
-
* callback; pass `settlesItself` for those, and
|
|
176
|
-
* read as
|
|
177
|
-
* here either way
|
|
262
|
+
* callback; pass `settlesItself` for those, and what the handler returns,
|
|
263
|
+
* a promise included, is then not read as the outcome. A throwing handler
|
|
264
|
+
* is settled here either way, and a promise goes back to the driver as the
|
|
265
|
+
* handler returned it.
|
|
178
266
|
*/
|
|
179
267
|
run(job, invoke, settlesItself = false) {
|
|
180
268
|
const outerStore = this.asyncLocalStorage.getStore();
|
|
@@ -188,7 +276,14 @@ export class JobTraceRunner {
|
|
|
188
276
|
isSameJob(outerStore?.get(ACTIVE_JOB_KEY), activeJob)) {
|
|
189
277
|
return invoke(() => undefined);
|
|
190
278
|
}
|
|
191
|
-
|
|
279
|
+
// Any other run opens a store and a trace of its own, whatever store it
|
|
280
|
+
// starts in. A trace id there is no proof that an operation is still open
|
|
281
|
+
// around the run: a store outlives its operation in whatever the
|
|
282
|
+
// operation left running - the timer chain of a cron job a request
|
|
283
|
+
// rescheduled, a Redis connection a request opened - and a run read as
|
|
284
|
+
// nested in it used to run in an id-less store, unreported, with
|
|
285
|
+
// `TracerService.createSpan()` throwing in its handler.
|
|
286
|
+
//
|
|
192
287
|
// The same map `run` is given, rather than `getStore()` inside the
|
|
193
288
|
// callback: identical object, one lookup fewer, and it is known to exist.
|
|
194
289
|
const store = new Map();
|
|
@@ -196,14 +291,6 @@ export class JobTraceRunner {
|
|
|
196
291
|
store.set(ACTIVE_JOB_KEY, activeJob);
|
|
197
292
|
}
|
|
198
293
|
return this.asyncLocalStorage.run(store, () => {
|
|
199
|
-
if (hasOuterContext) {
|
|
200
|
-
// If the outer context already has a trace ID
|
|
201
|
-
// ignore the inner context
|
|
202
|
-
if (this.options.debug) {
|
|
203
|
-
this.logger.debug(`Outer context already has a trace ID. Skipping inner context for job "${job.name}" job.id: ${job.id}`);
|
|
204
|
-
}
|
|
205
|
-
return invoke(() => undefined);
|
|
206
|
-
}
|
|
207
294
|
// The registry key is always this run's own. The inherited id may belong
|
|
208
295
|
// to a request still open in this process, and a retry reuses it.
|
|
209
296
|
const registryKey = uuidv7();
|
|
@@ -211,6 +298,8 @@ export class JobTraceRunner {
|
|
|
211
298
|
const traceId = inheritedTraceId ?? registryKey;
|
|
212
299
|
store.set(this.options.traceIdKey, traceId);
|
|
213
300
|
store.set(TRACE_REGISTRY_KEY, registryKey);
|
|
301
|
+
// Ended as the run settles, recorded or not: see `liveTraceId`.
|
|
302
|
+
const operation = openOperation(store);
|
|
214
303
|
// With OpenTelemetry interop on, the job runs in the W3C trace context
|
|
215
304
|
// it was enqueued in, for an OpenTelemetry SDK in this process - see
|
|
216
305
|
// `continueHandedOnTrace`. Recorded or not, as an outbound call carries
|
|
@@ -230,26 +319,65 @@ export class JobTraceRunner {
|
|
|
230
319
|
name: job.name,
|
|
231
320
|
id: typeof job.id === "number" ? `${job.id}` : job.id,
|
|
232
321
|
};
|
|
233
|
-
setAttributesSafely(this.options.jobs?.setAttributes, [context], this.options.jobs, store, this.logger, "jobs");
|
|
322
|
+
setAttributesSafely(this.options.jobs?.setAttributes, [context], this.options.jobs, store, this.logger, "jobs", this.options.traceIdKey);
|
|
234
323
|
if (this.isIgnored(context)) {
|
|
235
324
|
// The trace id stays in the store so logs and jobs enqueued from here
|
|
236
325
|
// still correlate; nothing is registered under the registry key, so
|
|
237
326
|
// its spans have no trace to join.
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
327
|
+
const end = () => endOperation(operation);
|
|
328
|
+
let result;
|
|
329
|
+
try {
|
|
330
|
+
result =
|
|
331
|
+
handedOn === undefined
|
|
332
|
+
? invoke(end)
|
|
333
|
+
: continueHandedOnTrace(handedOn, traceId, () => invoke(end));
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
end();
|
|
337
|
+
throw error;
|
|
338
|
+
}
|
|
339
|
+
if (!settlesItself) {
|
|
340
|
+
// Its driver takes the promise as the outcome and consumes it, so
|
|
341
|
+
// watching it here changes nothing about how a rejection surfaces.
|
|
342
|
+
if (result instanceof Promise) {
|
|
343
|
+
result.then(end, end);
|
|
344
|
+
}
|
|
345
|
+
else {
|
|
346
|
+
end();
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
return result;
|
|
241
350
|
}
|
|
242
351
|
this.operationTraceRegistry.startTrace(registryKey, {
|
|
243
352
|
tags: this.options.jobs?.tags,
|
|
244
353
|
...context,
|
|
245
354
|
...job.metadata,
|
|
246
355
|
}, traceId, traceContext);
|
|
247
|
-
let
|
|
356
|
+
let outcome;
|
|
357
|
+
// The promise a callback-style handler returned, which its driver
|
|
358
|
+
// drops - see where it is handed back, below.
|
|
359
|
+
let dropped;
|
|
360
|
+
let completed = false;
|
|
361
|
+
let deadline;
|
|
248
362
|
const settle = (status) => {
|
|
249
|
-
if (
|
|
363
|
+
if (outcome) {
|
|
250
364
|
return;
|
|
251
365
|
}
|
|
252
|
-
|
|
366
|
+
outcome = status;
|
|
367
|
+
if (status === "failed") {
|
|
368
|
+
dropped?.then(undefined, ignoreRejection);
|
|
369
|
+
}
|
|
370
|
+
complete(status);
|
|
371
|
+
};
|
|
372
|
+
// Apart from `settle`, which is the handler's: the deadline ends the
|
|
373
|
+
// run, not what its handler reports later.
|
|
374
|
+
const complete = (status) => {
|
|
375
|
+
if (completed) {
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
completed = true;
|
|
379
|
+
clearTimeout(deadline);
|
|
380
|
+
endOperation(operation);
|
|
253
381
|
deferTraceCompletion(async () => {
|
|
254
382
|
this.operationTraceRegistry.endTrace(registryKey, { status });
|
|
255
383
|
const snapshot = (await this.operationTraceRegistry.pluckSnapshot(registryKey));
|
|
@@ -271,16 +399,47 @@ export class JobTraceRunner {
|
|
|
271
399
|
const returnValue = handedOn === undefined
|
|
272
400
|
? invoke(settle)
|
|
273
401
|
: continueHandedOnTrace(handedOn, traceId, () => invoke(settle));
|
|
402
|
+
// Armed as the driver arms its own, once the handler has returned:
|
|
403
|
+
// Bull fails a job past its `timeout` and takes the next one, and a
|
|
404
|
+
// handler that never finishes left its trace in the registry for the
|
|
405
|
+
// life of the process, one per job, never reported. Unref'd, as it
|
|
406
|
+
// must not keep a worker alive that is done otherwise.
|
|
407
|
+
if (job.timeout !== undefined && !completed) {
|
|
408
|
+
deadline = setTimeout(() => complete("failed"), job.timeout);
|
|
409
|
+
deadline.unref?.();
|
|
410
|
+
}
|
|
274
411
|
if (returnValue instanceof Promise) {
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
412
|
+
// Handed back as the handler returned it, never as a promise
|
|
413
|
+
// chained onto it: a chained promise has none of the members of the
|
|
414
|
+
// handler's own (Bull calls `cancel()` on it when a job times out,
|
|
415
|
+
// and hands it to `active` listeners), and it rejects on its own.
|
|
416
|
+
if (settlesItself) {
|
|
417
|
+
// Bull drops what a callback-style processor returns, and `done`
|
|
418
|
+
// is the outcome. One that reports its failure through `done` and
|
|
419
|
+
// returns the promise it handled that way -
|
|
420
|
+
// `redis.hincrby(key, field, n, done)` - left a chained rejection
|
|
421
|
+
// nobody listened to, and the `unhandledRejection` ended a worker
|
|
422
|
+
// that carries on without the agent.
|
|
423
|
+
//
|
|
424
|
+
// So it is not watched either: watching marks it handled, and an
|
|
425
|
+
// `async (job, done)` processor that throws before it calls
|
|
426
|
+
// `done` has to raise `unhandledRejection` as it does without the
|
|
427
|
+
// agent. Only once `done` has reported a failure is the rejection
|
|
428
|
+
// marked handled: an instrumented provider's `@Process()` method
|
|
429
|
+
// hands back a promise chained onto its method's, and that one
|
|
430
|
+
// rejects again after the method's own was handled.
|
|
431
|
+
dropped = returnValue;
|
|
432
|
+
if (outcome === "failed") {
|
|
433
|
+
returnValue.then(undefined, ignoreRejection);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
else {
|
|
437
|
+
// A driver that takes the promise as the outcome consumes it, so
|
|
438
|
+
// the run is settled from a side branch. Attached before the
|
|
439
|
+
// driver's own reactions, it still settles the run first.
|
|
440
|
+
returnValue.then(() => settle("completed"), () => settle("failed"));
|
|
441
|
+
}
|
|
442
|
+
return returnValue;
|
|
284
443
|
}
|
|
285
444
|
if (!settlesItself) {
|
|
286
445
|
settle("completed");
|
|
@@ -294,3 +453,5 @@ export class JobTraceRunner {
|
|
|
294
453
|
});
|
|
295
454
|
}
|
|
296
455
|
}
|
|
456
|
+
/** Marks a rejection handled, where it has already been reported. */
|
|
457
|
+
function ignoreRejection() { }
|
|
@@ -16,8 +16,15 @@ import { AsyncLocalStorage } from "async_hooks";
|
|
|
16
16
|
import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
|
|
17
17
|
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
18
18
|
import { OBSERVE_OPTIONS } from "../observe.constants.js";
|
|
19
|
-
import { JobTraceRunner } from "./job-trace-runner.js";
|
|
19
|
+
import { JobTraceRunner, readJobTimes, } from "./job-trace-runner.js";
|
|
20
20
|
import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
|
|
21
|
+
/**
|
|
22
|
+
* On the agent's `decorate`: the one it stands in front of, so a second
|
|
23
|
+
* agent wraps that rather than the first agent's. Kept on the wrapper, not
|
|
24
|
+
* the prototype, so an override the application installs after an agent is
|
|
25
|
+
* never mistaken for what that agent found.
|
|
26
|
+
*/
|
|
27
|
+
const DECORATE_IT_WRAPS = Symbol.for("nestjs.observe.bullmq.decorateItWraps");
|
|
21
28
|
const ORIGINAL_CALL_PROCESS_JOB = Symbol.for("nestjs.observe.bullmqPro.callProcessJob");
|
|
22
29
|
/**
|
|
23
30
|
* Job tracing for BullMQ: through `@nestjs/bullmq`'s processor decorator, and
|
|
@@ -49,23 +56,7 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
|
|
|
49
56
|
* omitted rather than reported as zero.
|
|
50
57
|
*/
|
|
51
58
|
readQueueMetadata(job) {
|
|
52
|
-
const metadata =
|
|
53
|
-
if (typeof job.timestamp === "number") {
|
|
54
|
-
metadata.enqueuedAt = new Date(job.timestamp).toISOString();
|
|
55
|
-
// processedOn is set by the worker immediately before the processor runs.
|
|
56
|
-
// Falling back to now() keeps the measurement honest if it is missing.
|
|
57
|
-
const startedAt = typeof job.processedOn === "number" ? job.processedOn : Date.now();
|
|
58
|
-
// `timestamp` is when the job was created, not when it became runnable, so
|
|
59
|
-
// for a delayed job the gap between the two is a schedule the caller asked
|
|
60
|
-
// for - not a queue that fell behind. Counting it would report a job dated
|
|
61
|
-
// a week out as a week of backlog and drag `job_wait_p95` with it.
|
|
62
|
-
//
|
|
63
|
-
// Read off the options when `job.delay` is zero: BullMQ resets that
|
|
64
|
-
// field as it promotes a delayed job, so by the time a worker holds the
|
|
65
|
-
// job it says 0 whatever was asked for.
|
|
66
|
-
const availableAt = job.timestamp + (job.delay || job.opts?.delay || 0);
|
|
67
|
-
metadata.waitDuration = Math.max(0, startedAt - availableAt);
|
|
68
|
-
}
|
|
59
|
+
const metadata = readJobTimes(job);
|
|
69
60
|
if (typeof job.attemptsMade === "number") {
|
|
70
61
|
metadata.attemptsMade = job.attemptsMade;
|
|
71
62
|
}
|
|
@@ -108,11 +99,44 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
|
|
|
108
99
|
this.logger.warn("ProcessorDecoratorService is not available. Please, update to the latest version of @nestjs/bullmq. Skipping patching.");
|
|
109
100
|
return;
|
|
110
101
|
}
|
|
102
|
+
// `decorate` is documented as the place to override, and the application
|
|
103
|
+
// may have: a check that refuses a job, a wrapper of its own. What is
|
|
104
|
+
// there is called, as the explorer would call it, and the job is traced
|
|
105
|
+
// around what it returns. An earlier agent's wrapper is seen through, to
|
|
106
|
+
// what that agent found.
|
|
107
|
+
const prototype = ProcessorDecoratorService.prototype;
|
|
108
|
+
const found = prototype.decorate;
|
|
109
|
+
const original = typeof found === "function" &&
|
|
110
|
+
Object.prototype.hasOwnProperty.call(found, DECORATE_IT_WRAPS)
|
|
111
|
+
? found[DECORATE_IT_WRAPS]
|
|
112
|
+
: found;
|
|
113
|
+
const runner = this.runner;
|
|
114
|
+
const describeJob = (job) => this.describeJob(job);
|
|
111
115
|
// The worker calls the processor with `(job, token, signal)`, and all of it
|
|
112
116
|
// is passed on: a processor that moves its own job (`moveToDelayed`,
|
|
113
117
|
// `extendLock`) needs the token to prove it holds the lock.
|
|
114
|
-
|
|
115
|
-
|
|
118
|
+
//
|
|
119
|
+
// And the wrapper declares as many parameters as the processor it stands
|
|
120
|
+
// in for does: the worker builds a job's abort signal only for a
|
|
121
|
+
// processor that declares three, so a rest parameter, whose `length` is
|
|
122
|
+
// 1, left every `process(job, token, signal)` without one and
|
|
123
|
+
// `cancelJob()` with nothing to abort.
|
|
124
|
+
const decorate = function (processor) {
|
|
125
|
+
const decorated = typeof original === "function"
|
|
126
|
+
? original.call(this, processor)
|
|
127
|
+
: processor;
|
|
128
|
+
if (typeof decorated !== "function") {
|
|
129
|
+
return decorated;
|
|
130
|
+
}
|
|
131
|
+
const traced = (job, ...rest) => runner.run(describeJob(job), () => decorated(job, ...rest));
|
|
132
|
+
Object.defineProperty(traced, "length", {
|
|
133
|
+
value: decorated.length,
|
|
134
|
+
configurable: true,
|
|
135
|
+
});
|
|
136
|
+
return traced;
|
|
137
|
+
};
|
|
138
|
+
Object.defineProperty(decorate, DECORATE_IT_WRAPS, { value: original });
|
|
139
|
+
prototype.decorate = decorate;
|
|
116
140
|
this.patchQueue();
|
|
117
141
|
}
|
|
118
142
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { OnModuleDestroy
|
|
1
|
+
import { OnModuleDestroy } from "@nestjs/common";
|
|
2
2
|
import { ModulesContainer } from "@nestjs/core";
|
|
3
3
|
import type { BaseRpcContext, Server, Transport } from "@nestjs/microservices";
|
|
4
4
|
import { AsyncLocalStorage } from "async_hooks";
|
|
@@ -12,7 +12,7 @@ interface GrpcCall<TRequest = any, TMetadata = any> {
|
|
|
12
12
|
metadata: TMetadata;
|
|
13
13
|
operationId: string;
|
|
14
14
|
}
|
|
15
|
-
export declare class RpcObserveAgentService<Store extends Record<string, unknown>> implements
|
|
15
|
+
export declare class RpcObserveAgentService<Store extends Record<string, unknown>> implements OnModuleDestroy {
|
|
16
16
|
private readonly asyncLocalStorage;
|
|
17
17
|
private readonly options;
|
|
18
18
|
private readonly modulesContainer;
|
|
@@ -22,23 +22,98 @@ export declare class RpcObserveAgentService<Store extends Record<string, unknown
|
|
|
22
22
|
private readonly logger;
|
|
23
23
|
private rpcTargetAddedSubscription;
|
|
24
24
|
/**
|
|
25
|
-
* Assigned in
|
|
25
|
+
* Assigned in the constructor. Every use below is reached only through the
|
|
26
26
|
* hooks registered there, after a successful load - a service without the
|
|
27
27
|
* package has no RPC target to hook.
|
|
28
28
|
*/
|
|
29
29
|
private microservices;
|
|
30
|
+
/**
|
|
31
|
+
* The registry key each operation was started under, by the context Nest
|
|
32
|
+
* hands its end hook. That hook cannot ask the async store: Nest runs it
|
|
33
|
+
* from the teardown of the handler's reply stream, in the async context of
|
|
34
|
+
* whatever ended the stream - a TCP socket's `close`, a gRPC cancellation,
|
|
35
|
+
* a subject another message's handler emitted into. As
|
|
36
|
+
* `HttpObserveAgentService` keeps its keys by request.
|
|
37
|
+
*/
|
|
38
|
+
private readonly registryKeys;
|
|
39
|
+
/** The operation each context was started for - see `rememberOperation`. */
|
|
40
|
+
private readonly operations;
|
|
41
|
+
/**
|
|
42
|
+
* The gRPC calls of a request stream, by their metadata - see
|
|
43
|
+
* `rememberGrpcCalls`.
|
|
44
|
+
*/
|
|
45
|
+
private readonly grpcCalls;
|
|
46
|
+
/** The gRPC servers whose calls `rememberGrpcCalls` already notes. */
|
|
47
|
+
private readonly grpcServers;
|
|
30
48
|
constructor(asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>, options: ObserveModuleOptionsWithDefaults, modulesContainer: ModulesContainer, operationTraceRegistry: OperationTraceRegistry, observeAgentSharedBuffer: ObserveAgentSharedBuffer, traceSamplerService: TraceSamplerService);
|
|
31
|
-
onModuleInit(): void;
|
|
32
49
|
onModuleDestroy(): void;
|
|
33
50
|
/**
|
|
34
51
|
* Loads `@nestjs/microservices` without a static import, so a service that
|
|
35
52
|
* exposes no microservice need not install the package. Loaded here rather
|
|
36
|
-
* than lazily because the target registry is subscribed from
|
|
37
|
-
* and a dynamic `import()` would resolve after a target may
|
|
38
|
-
* been announced.
|
|
53
|
+
* than lazily because the target registry is subscribed from the
|
|
54
|
+
* constructor, and a dynamic `import()` would resolve after a target may
|
|
55
|
+
* already have been announced.
|
|
39
56
|
*/
|
|
40
57
|
private loadMicroservices;
|
|
58
|
+
/**
|
|
59
|
+
* Sets the agent's processing hooks on a server, beside any the application
|
|
60
|
+
* sets on it - see `composeStartHook`.
|
|
61
|
+
*/
|
|
41
62
|
registerRpcHooks(target: Server): void;
|
|
63
|
+
/**
|
|
64
|
+
* Notes each call of a gRPC request stream by its metadata, for
|
|
65
|
+
* `startGrpcRequestTracing` to find the call itself by.
|
|
66
|
+
*
|
|
67
|
+
* The start hook is handed a copy of the call, its fields spread onto a new
|
|
68
|
+
* object (`{ ...call }`), and a copy emits nothing: the messages of the
|
|
69
|
+
* request stream are emitted on the call. The copy shares the call's
|
|
70
|
+
* `metadata`, so the call is kept by that, from the method grpc-js runs for
|
|
71
|
+
* it - the only place the call itself passes before the hook. That method
|
|
72
|
+
* is built by `createServiceMethod`, wrapped here on this server alone as
|
|
73
|
+
* Nest calls it once per method when the server starts to listen, after
|
|
74
|
+
* this hook was set. Unary and server-streaming calls are left alone: they
|
|
75
|
+
* have no later messages to run anywhere. A server without the method keeps
|
|
76
|
+
* its calls' events where grpc-js emits them.
|
|
77
|
+
*/
|
|
78
|
+
private rememberGrpcCalls;
|
|
79
|
+
/** The call `ctx` is a copy of, if `rememberGrpcCalls` noted it. */
|
|
80
|
+
private takeGrpcCall;
|
|
81
|
+
/**
|
|
82
|
+
* Drops the trace of a `@GrpcStreamCall` call that is cancelled while its
|
|
83
|
+
* handler is still running, as the HTTP agent drops an aborted request's.
|
|
84
|
+
*
|
|
85
|
+
* Nest ends a call's operation when its handler settles, and for a
|
|
86
|
+
* `@GrpcStreamCall` handler it waits on that alone. On a deadline or a
|
|
87
|
+
* client's cancellation grpc-js emits `cancelled` and destroys the stream,
|
|
88
|
+
* with no `end` and no `error`, so a handler that waits for either never
|
|
89
|
+
* settles: its trace stayed in the registry for the life of the process,
|
|
90
|
+
* one per call, and was never reported. Unary and `@GrpcStreamMethod` calls
|
|
91
|
+
* are left to Nest, which ends them on `cancelled` itself.
|
|
92
|
+
*
|
|
93
|
+
* Dropped a turn after `cancelled`, not at once: a handler that settles on
|
|
94
|
+
* it is ended by Nest, from microtasks, before then, and reported as ever.
|
|
95
|
+
* One that settles later outlived its client, and the registry already
|
|
96
|
+
* lets it end its spans on a trace that is gone.
|
|
97
|
+
*/
|
|
98
|
+
private dropTraceOnCancel;
|
|
99
|
+
/**
|
|
100
|
+
* Runs the events of a gRPC request stream in the call's store.
|
|
101
|
+
*
|
|
102
|
+
* A listener runs in the async context of whatever emits its event. The
|
|
103
|
+
* messages already queued when the handler subscribes are emitted from
|
|
104
|
+
* within `done`, inside the store; every later one from grpc-js's callback
|
|
105
|
+
* on the HTTP/2 stream, which belongs to the connection and has no store.
|
|
106
|
+
* So the second message of an ordinary stream was handled outside its call:
|
|
107
|
+
* no spans, no trace id on its log lines, and `TracerService.createSpan()`
|
|
108
|
+
* threw - a status 2 for a `@GrpcStreamMethod` handler, and for a
|
|
109
|
+
* `@GrpcStreamCall` handler's `data` listener an uncaught rejection that
|
|
110
|
+
* ended the process.
|
|
111
|
+
*
|
|
112
|
+
* An event emitted from within the call - a span of it writing to the
|
|
113
|
+
* stream - keeps the context it is emitted in, the span's, which carries
|
|
114
|
+
* the call's key.
|
|
115
|
+
*/
|
|
116
|
+
private emitCallEventsInStore;
|
|
42
117
|
/**
|
|
43
118
|
* Names the transport for the snapshot's `protocol` field.
|
|
44
119
|
*
|
|
@@ -47,7 +122,9 @@ export declare class RpcObserveAgentService<Store extends Record<string, unknown
|
|
|
47
122
|
* transport used to arrive with no protocol at all.
|
|
48
123
|
*/
|
|
49
124
|
private toProtocolName;
|
|
50
|
-
startRpcRequestTracing(transportId: Transport | symbol, ctx: BaseRpcContext, done: () => Promise<any
|
|
125
|
+
startRpcRequestTracing(transportId: Transport | symbol, ctx: BaseRpcContext, done: () => Promise<any>,
|
|
126
|
+
/** The server the message arrived at. */
|
|
127
|
+
target?: Server): Promise<unknown>;
|
|
51
128
|
/**
|
|
52
129
|
* Whether OpenTelemetry interop runs now: `openTelemetry` on, beside
|
|
53
130
|
* reporting to NestJS Observe - see `ObserveAgentSharedBuffer.isReporting`.
|
|
@@ -55,6 +132,32 @@ export declare class RpcObserveAgentService<Store extends Record<string, unknown
|
|
|
55
132
|
private openTelemetryInteropOn;
|
|
56
133
|
startGrpcRequestTracing(transportId: Transport | symbol, call: GrpcCall, done: () => Promise<any>): Promise<unknown>;
|
|
57
134
|
endRpcRequestTracing(transportId: Transport | symbol, ctx: BaseRpcContext | GrpcCall): void;
|
|
135
|
+
/**
|
|
136
|
+
* Keeps `registryKey` for the end hook to find by `ctx`. A custom
|
|
137
|
+
* transporter delivers a context of its own making, and a gRPC call need not
|
|
138
|
+
* carry a request message: what cannot key a `WeakMap` is left to the store.
|
|
139
|
+
*/
|
|
140
|
+
private rememberRegistryKey;
|
|
141
|
+
/** As `rememberRegistryKey`, for the operation the end hook ends. */
|
|
142
|
+
private rememberOperation;
|
|
143
|
+
/**
|
|
144
|
+
* The route a message's handler is registered under, for the pattern or
|
|
145
|
+
* topic as its sender wrote it. Nest parses a pattern that is JSON and finds
|
|
146
|
+
* the handler by the normalised outcome, so one handler answers to any
|
|
147
|
+
* number of texts - other whitespace, an escape, a key given twice. Named by
|
|
148
|
+
* the text, each was an operation of the sender's choosing, and a route an
|
|
149
|
+
* `@Objective` on the handler was declared for anew.
|
|
150
|
+
*
|
|
151
|
+
* The route is taken only where the server finds that route's handler for
|
|
152
|
+
* the text: a handler reached through a wildcard keeps the text it was
|
|
153
|
+
* reached on, and so does anything the server cannot be asked about.
|
|
154
|
+
*/
|
|
155
|
+
private toRoute;
|
|
156
|
+
/**
|
|
157
|
+
* Kafka, MQTT, RabbitMQ and TCP find a message's handler by the text its
|
|
158
|
+
* context carries - see `toRoute`. NATS and Redis find it by the
|
|
159
|
+
* subscription the message came in on.
|
|
160
|
+
*/
|
|
58
161
|
private getOperationIdFromContext;
|
|
59
162
|
}
|
|
60
163
|
export {};
|