@nestjs/observe 0.3.20 → 0.3.22
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/LICENSE +105 -22
- package/NOTICE +31 -0
- package/README.md +138 -21
- package/dist/agent/degraded-ingest.protocol.d.ts +20 -0
- package/dist/agent/degraded-ingest.protocol.js +25 -0
- package/dist/agent/detached-observe-worker.assembly.js +2 -1
- package/dist/agent/detached-observe-worker.d.ts +2 -0
- package/dist/agent/detached-observe-worker.js +7 -0
- package/dist/agent/observe-agent.shared-buffer.d.ts +36 -0
- package/dist/agent/observe-agent.shared-buffer.js +56 -1
- package/dist/agent/observe-agent.worker.d.ts +12 -0
- package/dist/agent/observe-agent.worker.js +63 -8
- package/dist/instrument/create-instance-decorator.instrument.js +99 -86
- package/dist/interfaces/observe-options.interface.d.ts +42 -3
- package/dist/interfaces/trace-events.interfaces.d.ts +11 -5
- package/dist/observe.constants.d.ts +15 -5
- package/dist/observe.constants.js +15 -5
- package/dist/observe.module.js +3 -0
- package/dist/outgoing/http.integration.d.ts +34 -3
- package/dist/outgoing/http.integration.js +84 -17
- package/dist/outgoing/outgoing-observe-agent.service.d.ts +14 -1
- package/dist/outgoing/outgoing-observe-agent.service.js +24 -9
- package/dist/outgoing/outgoing-span.recorder.d.ts +11 -1
- package/dist/outgoing/outgoing-span.recorder.js +8 -2
- package/dist/protocols/deferred-trace-completion.d.ts +13 -2
- package/dist/protocols/deferred-trace-completion.js +27 -4
- package/dist/protocols/graphql-observe-agent.service.js +1 -1
- package/dist/protocols/http-observe-agent.service.js +45 -30
- package/dist/protocols/job-trace-runner.js +2 -2
- package/dist/protocols/rpc-observe-agent.service.js +19 -10
- package/dist/protocols/ws-observe-agent.service.js +1 -1
- package/dist/services/collapse-repeated-spans.util.js +41 -37
- package/dist/services/operation-trace.registry.d.ts +32 -11
- package/dist/services/operation-trace.registry.js +102 -33
- package/dist/services/tracer.service.d.ts +6 -0
- package/dist/services/tracer.service.js +11 -2
- package/dist/utils/default-trace-id-generator.util.d.ts +18 -0
- package/dist/utils/default-trace-id-generator.util.js +33 -0
- package/dist/utils/opentelemetry.util.d.ts +31 -0
- package/dist/utils/opentelemetry.util.js +52 -0
- package/dist/utils/trace-context.util.d.ts +91 -0
- package/dist/utils/trace-context.util.js +219 -0
- package/dist/utils/trace-id-generator-origin.util.d.ts +11 -0
- package/dist/utils/trace-id-generator-origin.util.js +26 -0
- package/dist/utils/uuid-v7.util.js +53 -15
- package/package.json +18 -4
|
@@ -11,7 +11,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
11
11
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
12
|
};
|
|
13
13
|
var ObserveAgentSharedBuffer_1;
|
|
14
|
-
import { countTraceNodes, DEGRADED_TTL_MS, isNotableSnapshot, isServerErrorSnapshot, } from "./degraded-ingest.protocol.js";
|
|
14
|
+
import { countTraceNodes, DEGRADED_TTL_MS, isNotableSnapshot, isServerErrorSnapshot, NOT_INGESTED_GRACE_MS, } from "./degraded-ingest.protocol.js";
|
|
15
15
|
import { MAX_BATCH_ITEMS } from "./telemetry-wire-contract.js";
|
|
16
16
|
import { Inject, Injectable, Logger, Optional } from "@nestjs/common";
|
|
17
17
|
import { Counter, Summary } from "../custom-metrics/index.js";
|
|
@@ -209,6 +209,17 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
209
209
|
* not a moment longer.
|
|
210
210
|
*/
|
|
211
211
|
errorsOnly = false;
|
|
212
|
+
/**
|
|
213
|
+
* Whether the collector is taking this app's telemetry - see `isIngesting`.
|
|
214
|
+
* False until it accepts a first batch: what has not been shown to reach
|
|
215
|
+
* NestJS Observe does not count as reaching it.
|
|
216
|
+
*/
|
|
217
|
+
ingesting = false;
|
|
218
|
+
/**
|
|
219
|
+
* When batches began failing to get in, since the last one that did; zero
|
|
220
|
+
* while they get in.
|
|
221
|
+
*/
|
|
222
|
+
failingSince = 0;
|
|
212
223
|
/**
|
|
213
224
|
* Requests and jobs that errors-only ingest withheld from the batch being
|
|
214
225
|
* built, cleared with it.
|
|
@@ -247,6 +258,50 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
247
258
|
isErrorsOnly() {
|
|
248
259
|
return this.errorsOnly && this.isDegraded();
|
|
249
260
|
}
|
|
261
|
+
/**
|
|
262
|
+
* Whether the collector is taking this app's telemetry: from the first
|
|
263
|
+
* batch it accepts, until it refuses the app's credentials, the worker
|
|
264
|
+
* stops, or batches have kept failing to get in for
|
|
265
|
+
* `NOT_INGESTED_GRACE_MS` - and again from the next batch it accepts.
|
|
266
|
+
*
|
|
267
|
+
* OpenTelemetry interop runs on it (see `openTelemetry`): the agent reads
|
|
268
|
+
* and sends `traceparent`, and follows an OpenTelemetry SDK in the process,
|
|
269
|
+
* only while it is also reporting to NestJS Observe. So an agent that sends
|
|
270
|
+
* Observe nothing - `enabled: false`, no credentials, credentials the
|
|
271
|
+
* collector refuses - never turns it on.
|
|
272
|
+
*/
|
|
273
|
+
isIngesting() {
|
|
274
|
+
return this.ingesting;
|
|
275
|
+
}
|
|
276
|
+
/** The collector accepted a batch, whatever it then kept of it. */
|
|
277
|
+
recordAccepted() {
|
|
278
|
+
this.ingesting = true;
|
|
279
|
+
this.failingSince = 0;
|
|
280
|
+
}
|
|
281
|
+
/** The collector refused the app's credentials. */
|
|
282
|
+
recordRefused() {
|
|
283
|
+
this.ingesting = false;
|
|
284
|
+
this.failingSince = 0;
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* A batch did not get in - see `NotIngestedReason`. `pausedUntil` is when a
|
|
288
|
+
* paused worker sends again: nothing gets in before then, so a pause longer
|
|
289
|
+
* than the grace ends ingesting at once rather than after it.
|
|
290
|
+
*/
|
|
291
|
+
recordFailed(pausedUntil = 0, now = Date.now()) {
|
|
292
|
+
if (this.failingSince === 0) {
|
|
293
|
+
this.failingSince = now;
|
|
294
|
+
}
|
|
295
|
+
if (Math.max(now, pausedUntil) - this.failingSince >=
|
|
296
|
+
NOT_INGESTED_GRACE_MS) {
|
|
297
|
+
this.ingesting = false;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
/** The worker stopped; a restarted one has to get a batch in again. */
|
|
301
|
+
recordStopped() {
|
|
302
|
+
this.ingesting = false;
|
|
303
|
+
this.failingSince = 0;
|
|
304
|
+
}
|
|
250
305
|
/**
|
|
251
306
|
* What errors-only ingest makes of one execution: whether it is sent.
|
|
252
307
|
*
|
|
@@ -164,6 +164,18 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
|
|
|
164
164
|
/** The worker's messages, errors, and the restart when it dies. */
|
|
165
165
|
private watchWorker;
|
|
166
166
|
handleMessage(msg: string): void;
|
|
167
|
+
/**
|
|
168
|
+
* Whether OpenTelemetry interop was last said to be on - see
|
|
169
|
+
* `reportOpenTelemetryInterop`. It starts off, as the buffer's state does.
|
|
170
|
+
*/
|
|
171
|
+
private reportedOpenTelemetry;
|
|
172
|
+
/**
|
|
173
|
+
* Says when OpenTelemetry interop turns on or off, with `openTelemetry` on:
|
|
174
|
+
* it runs only while the collector takes this app's telemetry (see
|
|
175
|
+
* `ObserveAgentSharedBuffer.isIngesting`), and a `traceparent` that stops
|
|
176
|
+
* going out with no word would read as a bug in the agent.
|
|
177
|
+
*/
|
|
178
|
+
private reportOpenTelemetryInterop;
|
|
167
179
|
/** Whether this process has said the collector accepted its first batch. */
|
|
168
180
|
private reportedConnection;
|
|
169
181
|
/**
|
|
@@ -21,7 +21,7 @@ import { ProfileUploader } from "../profiling/profile-uploader.js";
|
|
|
21
21
|
import { setActiveSliceRecorder, SpanSliceRecorder, } from "../profiling/span-slice-recorder.js";
|
|
22
22
|
import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.service.js";
|
|
23
23
|
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
24
|
-
import { parseDegradedMessage, parseOveragePauseReason, parsePausedMessage, } from "./degraded-ingest.protocol.js";
|
|
24
|
+
import { NOT_INGESTED_GRACE_MS, parseDegradedMessage, parseNotIngestedMessage, parseOveragePauseReason, parsePausedMessage, } from "./degraded-ingest.protocol.js";
|
|
25
25
|
import { detachedWorkerData, detachedWorkerSource, } from "./detached-observe-worker.assembly.js";
|
|
26
26
|
import { describeMissingCredentials, SIGN_UP_URL, } from "./credentials-notice.js";
|
|
27
27
|
import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
|
|
@@ -155,6 +155,10 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
155
155
|
else {
|
|
156
156
|
this.initializeWorker();
|
|
157
157
|
}
|
|
158
|
+
if (this.options.openTelemetry === true && this.sendsNothing) {
|
|
159
|
+
this.logger.warn("openTelemetry is on, but this agent reports nothing to NestJS Observe, so OpenTelemetry interop stays off: " +
|
|
160
|
+
"it runs only beside reporting to Observe.");
|
|
161
|
+
}
|
|
158
162
|
this.flushInterval = setInterval(() => this.flush(), flushIntervalTime);
|
|
159
163
|
if (!this.sendsNothing) {
|
|
160
164
|
this.startRuntimeMetrics();
|
|
@@ -351,13 +355,14 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
351
355
|
};
|
|
352
356
|
worker.once("exit", onExit);
|
|
353
357
|
try {
|
|
354
|
-
// Every protocol records its snapshot
|
|
355
|
-
//
|
|
356
|
-
//
|
|
357
|
-
//
|
|
358
|
-
//
|
|
359
|
-
//
|
|
360
|
-
//
|
|
358
|
+
// Every protocol records its snapshot after the response or job has
|
|
359
|
+
// finished - in a microtask, or from a `setTimeout(0)` when a span was
|
|
360
|
+
// still open - so the last requests a process served may not be in the
|
|
361
|
+
// buffer yet, and an empty buffer would end this before they land. A
|
|
362
|
+
// zero timer set now fires after the microtasks and the timers already
|
|
363
|
+
// queued, and after the microtasks each of those starts. A trace whose
|
|
364
|
+
// spans were still open waits a further second in the registry; the
|
|
365
|
+
// loop below waits for those too.
|
|
361
366
|
await sleep(0);
|
|
362
367
|
for (;;) {
|
|
363
368
|
if (exited) {
|
|
@@ -551,6 +556,10 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
551
556
|
this.logger.debug("Worker exited on shutdown.");
|
|
552
557
|
return;
|
|
553
558
|
}
|
|
559
|
+
// Whatever comes next, this worker gets nothing in any more: a
|
|
560
|
+
// restarted one has to get a batch in again first.
|
|
561
|
+
this.observeAgentSharedBuffer.recordStopped();
|
|
562
|
+
this.reportOpenTelemetryInterop("stopped");
|
|
554
563
|
if (code !== 0) {
|
|
555
564
|
this.logger.error(`Worker stopped with exit code ${code}. Restarting worker...`);
|
|
556
565
|
this.initializeWorker(); // Restart the worker
|
|
@@ -566,8 +575,22 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
566
575
|
this.sendsPausedUntil = pausedUntil;
|
|
567
576
|
return;
|
|
568
577
|
}
|
|
578
|
+
const notIngested = parseNotIngestedMessage(msg);
|
|
579
|
+
if (notIngested !== null) {
|
|
580
|
+
if (notIngested === "refused") {
|
|
581
|
+
this.observeAgentSharedBuffer.recordRefused();
|
|
582
|
+
}
|
|
583
|
+
else {
|
|
584
|
+
// After the paused line, when the worker pauses: it posts that first.
|
|
585
|
+
this.observeAgentSharedBuffer.recordFailed(this.sendsPausedUntil);
|
|
586
|
+
}
|
|
587
|
+
this.reportOpenTelemetryInterop(notIngested);
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
569
590
|
const mode = parseDegradedMessage(msg);
|
|
570
591
|
if (mode !== null) {
|
|
592
|
+
this.observeAgentSharedBuffer.recordAccepted();
|
|
593
|
+
this.reportOpenTelemetryInterop();
|
|
571
594
|
this.reportFirstAcceptedBatch();
|
|
572
595
|
this.applyIngestMode(mode, parseOveragePauseReason(msg));
|
|
573
596
|
return;
|
|
@@ -580,6 +603,38 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
580
603
|
this.logger.debug(msg);
|
|
581
604
|
}
|
|
582
605
|
}
|
|
606
|
+
/**
|
|
607
|
+
* Whether OpenTelemetry interop was last said to be on - see
|
|
608
|
+
* `reportOpenTelemetryInterop`. It starts off, as the buffer's state does.
|
|
609
|
+
*/
|
|
610
|
+
reportedOpenTelemetry = false;
|
|
611
|
+
/**
|
|
612
|
+
* Says when OpenTelemetry interop turns on or off, with `openTelemetry` on:
|
|
613
|
+
* it runs only while the collector takes this app's telemetry (see
|
|
614
|
+
* `ObserveAgentSharedBuffer.isIngesting`), and a `traceparent` that stops
|
|
615
|
+
* going out with no word would read as a bug in the agent.
|
|
616
|
+
*/
|
|
617
|
+
reportOpenTelemetryInterop(why) {
|
|
618
|
+
if (this.options.openTelemetry !== true) {
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
const on = this.observeAgentSharedBuffer.isIngesting();
|
|
622
|
+
if (on === this.reportedOpenTelemetry) {
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
625
|
+
this.reportedOpenTelemetry = on;
|
|
626
|
+
if (on) {
|
|
627
|
+
this.logger.log("OpenTelemetry interop is on: the collector is taking this app's telemetry, so traceparent is read and sent.");
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
const reason = why === "refused"
|
|
631
|
+
? "the collector refused this app's credentials"
|
|
632
|
+
: why === "stopped"
|
|
633
|
+
? "the telemetry worker stopped"
|
|
634
|
+
: `no batch has reached the collector for ${NOT_INGESTED_GRACE_MS / 1000} seconds`;
|
|
635
|
+
this.logger.warn(`OpenTelemetry interop is paused: ${reason}. It runs only while the agent is reporting to NestJS Observe, ` +
|
|
636
|
+
`and resumes with the next batch the collector accepts.`);
|
|
637
|
+
}
|
|
583
638
|
/** Whether this process has said the collector accepted its first batch. */
|
|
584
639
|
reportedConnection = false;
|
|
585
640
|
/**
|
|
@@ -80,8 +80,64 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
80
80
|
// "Object.<name>".
|
|
81
81
|
const call = spec.call;
|
|
82
82
|
const callUntraced = spec.callUntraced;
|
|
83
|
+
const endStep = (requestId, stepId) => operationTraceRegistry.internalEndTraceStep(requestId, spanId, className, methodName, stepId);
|
|
84
|
+
const recordError = (requestId, stepId, err) => {
|
|
85
|
+
// Before the registry records the step: `internalEndTraceStep` copies
|
|
86
|
+
// `err.stack` into the span payload (and, on a root span, into the
|
|
87
|
+
// snapshot that becomes the error group's sample), so relabelling
|
|
88
|
+
// afterwards would leave that copy carrying this frame's `Proxy.`.
|
|
89
|
+
relabelProxyFrame(err, className, methodName);
|
|
90
|
+
operationTraceRegistry.internalEndTraceStep(requestId, spanId, className, methodName, stepId, err);
|
|
91
|
+
};
|
|
92
|
+
// Runs the call inside the span's own async context. Made once per
|
|
93
|
+
// wrapper rather than once per call: `als.run` hands it the receiver, the
|
|
94
|
+
// arguments and the span's ids, so a traced call allocates no closure for
|
|
95
|
+
// it - and does not rename one, which cost as much again.
|
|
96
|
+
const callTraced = named(frameName, (thisArg, args, requestId, stepId) => {
|
|
97
|
+
try {
|
|
98
|
+
const result = call(thisArg, args);
|
|
99
|
+
if (result instanceof Promise) {
|
|
100
|
+
// Closing the span is a side effect: a registry failure must
|
|
101
|
+
// leave the caller with the value or rejection it would have
|
|
102
|
+
// seen without the span.
|
|
103
|
+
const settled = (value) => {
|
|
104
|
+
ignoreFailure(() => endStep(requestId, stepId));
|
|
105
|
+
return value;
|
|
106
|
+
};
|
|
107
|
+
const failed = (err) => {
|
|
108
|
+
ignoreFailure(() => recordError(requestId, stepId, err));
|
|
109
|
+
throw err;
|
|
110
|
+
};
|
|
111
|
+
// A plain native promise is swapped for a chained one, just as
|
|
112
|
+
// the caller's own `.then` would: a rejection the caller drops
|
|
113
|
+
// still raises `unhandledRejection`, as without the span.
|
|
114
|
+
if (isPlainPromise(result)) {
|
|
115
|
+
return result.then(settled, failed);
|
|
116
|
+
}
|
|
117
|
+
// A promise carrying more than its value (`json()` on a `got`
|
|
118
|
+
// request, `kill()` on an `execa` child, a subclass and its own
|
|
119
|
+
// members) is handed back as-is, or the caller loses all that.
|
|
120
|
+
// It is watched on a side branch instead, the way
|
|
121
|
+
// `OutgoingSpanRecorder.endWhenSettled` watches outgoing calls.
|
|
122
|
+
// Watching marks it handled, so a rejection the caller drops no
|
|
123
|
+
// longer raises `unhandledRejection`; the span still records it.
|
|
124
|
+
result.then(settled, (err) => ignoreFailure(() => recordError(requestId, stepId, err)));
|
|
125
|
+
return result;
|
|
126
|
+
}
|
|
127
|
+
endStep(requestId, stepId);
|
|
128
|
+
return result;
|
|
129
|
+
}
|
|
130
|
+
catch (err) {
|
|
131
|
+
recordError(requestId, stepId, err);
|
|
132
|
+
// Re-throw the error to maintain original behavior
|
|
133
|
+
throw err;
|
|
134
|
+
}
|
|
135
|
+
finally {
|
|
136
|
+
spec.setActive(false);
|
|
137
|
+
}
|
|
138
|
+
});
|
|
83
139
|
// A function expression, not an arrow: the wrapper has to forward whatever
|
|
84
|
-
// `this` the caller invoked it with.
|
|
140
|
+
// `this` the caller invoked it with.
|
|
85
141
|
return named(frameName, function (...args) {
|
|
86
142
|
// Already tracing this callable, invoke it as-is
|
|
87
143
|
if (spec.isActive()) {
|
|
@@ -108,66 +164,12 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
108
164
|
spec.setActive(false);
|
|
109
165
|
}
|
|
110
166
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
// `err.stack` into the span payload (and, on a root span, into the
|
|
118
|
-
// snapshot that becomes the error group's sample), so relabelling
|
|
119
|
-
// afterwards would leave that copy carrying this frame's `Proxy.`.
|
|
120
|
-
relabelProxyFrame(err, className, methodName);
|
|
121
|
-
operationTraceRegistry.internalEndTraceStep(requestId, spanId, className, methodName, newStepId, err);
|
|
122
|
-
};
|
|
123
|
-
const onError = (err) => {
|
|
124
|
-
recordError(err);
|
|
125
|
-
// Re-throw the error to maintain original behavior
|
|
126
|
-
throw err;
|
|
127
|
-
};
|
|
128
|
-
return als.run(new Map([
|
|
129
|
-
...(store?.entries() ?? []),
|
|
130
|
-
[CALLER_METADATA_KEY, newStepId],
|
|
131
|
-
]), named(frameName, () => {
|
|
132
|
-
try {
|
|
133
|
-
const result = call(this, args);
|
|
134
|
-
if (result instanceof Promise) {
|
|
135
|
-
// Closing the span is a side effect: a registry failure must
|
|
136
|
-
// leave the caller with the value or rejection it would have
|
|
137
|
-
// seen without the span.
|
|
138
|
-
const settled = (value) => {
|
|
139
|
-
ignoreFailure(() => onReturnValue(value));
|
|
140
|
-
return value;
|
|
141
|
-
};
|
|
142
|
-
const failed = (err) => {
|
|
143
|
-
ignoreFailure(() => recordError(err));
|
|
144
|
-
throw err;
|
|
145
|
-
};
|
|
146
|
-
// A plain native promise is swapped for a chained one, just as
|
|
147
|
-
// the caller's own `.then` would: a rejection the caller drops
|
|
148
|
-
// still raises `unhandledRejection`, as without the span.
|
|
149
|
-
if (isPlainPromise(result)) {
|
|
150
|
-
return result.then(settled, failed);
|
|
151
|
-
}
|
|
152
|
-
// A promise carrying more than its value (`json()` on a `got`
|
|
153
|
-
// request, `kill()` on an `execa` child, a subclass and its own
|
|
154
|
-
// members) is handed back as-is, or the caller loses all that.
|
|
155
|
-
// It is watched on a side branch instead, the way
|
|
156
|
-
// `OutgoingSpanRecorder.endWhenSettled` watches outgoing calls.
|
|
157
|
-
// Watching marks it handled, so a rejection the caller drops no
|
|
158
|
-
// longer raises `unhandledRejection`; the span still records it.
|
|
159
|
-
result.then(settled, (err) => ignoreFailure(() => recordError(err)));
|
|
160
|
-
return result;
|
|
161
|
-
}
|
|
162
|
-
return onReturnValue(result);
|
|
163
|
-
}
|
|
164
|
-
catch (err) {
|
|
165
|
-
onError(err);
|
|
166
|
-
}
|
|
167
|
-
finally {
|
|
168
|
-
spec.setActive(false);
|
|
169
|
-
}
|
|
170
|
-
}));
|
|
167
|
+
// Everything the caller's context holds, with this span as the caller
|
|
168
|
+
// of whatever it calls. A copy, so the caller's context still names the
|
|
169
|
+
// caller once this call returns.
|
|
170
|
+
const spanStore = new Map(store);
|
|
171
|
+
spanStore.set(CALLER_METADATA_KEY, newStepId);
|
|
172
|
+
return als.run(spanStore, callTraced, this, args, requestId, newStepId);
|
|
171
173
|
});
|
|
172
174
|
};
|
|
173
175
|
const instrumentFunction = (fn) => {
|
|
@@ -247,16 +249,33 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
247
249
|
const requiresRawReceiver = hasPrivateMembers || slotBacked;
|
|
248
250
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
249
251
|
const methodRefsCache = new WeakMap();
|
|
250
|
-
|
|
252
|
+
// Functions read off the instance that are handed out as they are:
|
|
253
|
+
// constructors and callable objects.
|
|
254
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
255
|
+
const passedThrough = new WeakSet();
|
|
251
256
|
return new Proxy(instance, {
|
|
257
|
+
// Runs for every property read through the proxy - each `this.field`
|
|
258
|
+
// and `this.dependency.method` inside a traced call - so the common
|
|
259
|
+
// answers come first: a value that is no method, then a method already
|
|
260
|
+
// wrapped.
|
|
252
261
|
get: (target, prop, receiver) => {
|
|
253
262
|
const attributeValue = Reflect.get(target, prop);
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
263
|
+
if (typeof attributeValue !== "function" || prop === "constructor") {
|
|
264
|
+
return attributeValue;
|
|
265
|
+
}
|
|
266
|
+
// When "originalMethod" is already proxied, return the cached version
|
|
267
|
+
const cached = methodRefsCache.get(attributeValue);
|
|
268
|
+
if (cached) {
|
|
269
|
+
return cached;
|
|
270
|
+
}
|
|
271
|
+
if (passedThrough.has(attributeValue)) {
|
|
272
|
+
return attributeValue;
|
|
273
|
+
}
|
|
274
|
+
const shouldProxy =
|
|
275
|
+
// A constructor held in a field - pg-pool's `this.Promise` - is
|
|
276
|
+
// invoked with `new` and read for statics (`this.Promise.reject`);
|
|
277
|
+
// the traced wrapper supports neither.
|
|
278
|
+
!isConstructor(attributeValue) &&
|
|
260
279
|
// A callable *object* - a Mongoose model, an Axios instance, an
|
|
261
280
|
// EventEmitter-backed client - is a field, not a method. The traced
|
|
262
281
|
// wrapper is a fresh bound function, so wrapping one silently drops
|
|
@@ -266,15 +285,15 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
266
285
|
// own properties.
|
|
267
286
|
!isCallableObject(attributeValue);
|
|
268
287
|
if (!shouldProxy) {
|
|
269
|
-
|
|
288
|
+
// Remembered, as a wrapped method is: telling them apart reads the
|
|
289
|
+
// function's source and its prototype's keys, which a Mongoose
|
|
290
|
+
// model read on every query would otherwise pay each time.
|
|
291
|
+
passedThrough.add(attributeValue);
|
|
292
|
+
return attributeValue;
|
|
270
293
|
}
|
|
271
294
|
const className = classNameOf(target);
|
|
272
295
|
const methodName = String(prop);
|
|
273
296
|
const frameName = `${className}.${methodName}`;
|
|
274
|
-
// When "originalMethod" is already proxied, return the cached version
|
|
275
|
-
if (methodRefsCache.has(attributeValue)) {
|
|
276
|
-
return methodRefsCache.get(attributeValue);
|
|
277
|
-
}
|
|
278
297
|
// For a private-member class, `Reflect.get` with the proxy as receiver
|
|
279
298
|
// would already throw on an accessor that touches `this.#x`, so the
|
|
280
299
|
// value fetched against the target above is reused instead.
|
|
@@ -282,23 +301,17 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
282
301
|
? attributeValue
|
|
283
302
|
: Reflect.get(target, prop, receiver);
|
|
284
303
|
const tracedReceiver = requiresRawReceiver ? target : receiver;
|
|
304
|
+
// The wrapper is made once per method of this instance and cached
|
|
305
|
+
// below, so a flag of its own guards exactly that callable - checked
|
|
306
|
+
// and flipped on every traced call, where a lookup keyed by instance
|
|
307
|
+
// and name used to be.
|
|
308
|
+
let active = false;
|
|
285
309
|
const proxyFn = createTracedWrapper({
|
|
286
310
|
className,
|
|
287
311
|
methodName,
|
|
288
312
|
spanId: generateSpanId(target, methodName),
|
|
289
|
-
isActive: () =>
|
|
290
|
-
setActive: (
|
|
291
|
-
if (!currentlyTracing.has(target)) {
|
|
292
|
-
currentlyTracing.set(target, new Set());
|
|
293
|
-
}
|
|
294
|
-
const activeMethods = currentlyTracing.get(target);
|
|
295
|
-
if (active) {
|
|
296
|
-
activeMethods.add(methodName);
|
|
297
|
-
}
|
|
298
|
-
else {
|
|
299
|
-
activeMethods.delete(methodName);
|
|
300
|
-
}
|
|
301
|
-
},
|
|
313
|
+
isActive: () => active,
|
|
314
|
+
setActive: (value) => (active = value),
|
|
302
315
|
// Traced calls run against the proxy so that a method calling into
|
|
303
316
|
// itself (`this.other()`) is instrumented as a nested step - except
|
|
304
317
|
// for private-member classes, whose brand checks only the raw
|
|
@@ -61,8 +61,16 @@ export interface CreateObserveModuleOptions {
|
|
|
61
61
|
* For HTTP protocols, the request object is passed to the function.
|
|
62
62
|
* For non-HTTP protocols, the request object will be contextual and may not be available.
|
|
63
63
|
* The default implementation uses the 'x-request-id' header if available,
|
|
64
|
-
* or mints a time-ordered UUID (version 7) if
|
|
65
|
-
*
|
|
64
|
+
* or mints a time-ordered UUID (version 7) if not - an id the collector can
|
|
65
|
+
* locate in time without a scan.
|
|
66
|
+
*
|
|
67
|
+
* With `openTelemetry` on, the default names a request in a W3C trace after
|
|
68
|
+
* that trace instead: the trace id of its `traceparent`, written as a UUID,
|
|
69
|
+
* or of the span an OpenTelemetry SDK in the same process opened for it.
|
|
70
|
+
* An 'x-request-id' that names the same trace is kept. Whatever this
|
|
71
|
+
* returns, the W3C trace is then still read alongside it: outbound calls
|
|
72
|
+
* carry it on, so the request stays in the OpenTelemetry trace its caller
|
|
73
|
+
* is in.
|
|
66
74
|
* @default (req) => req.headers['x-request-id'] || uuidv7()
|
|
67
75
|
*/
|
|
68
76
|
traceIdGenerator?: (req: unknown) => string;
|
|
@@ -183,7 +191,8 @@ export interface ObserveOptions {
|
|
|
183
191
|
* One setting for telemetry and profiles both, so the two can never point at
|
|
184
192
|
* different places. Defaults to the hosted collector; set `OBSERVE_ENDPOINT`
|
|
185
193
|
* in the environment to override that without touching this config, which is
|
|
186
|
-
* how a
|
|
194
|
+
* how a proxy or gateway that forwards to NestJS Observe is usually pointed
|
|
195
|
+
* at.
|
|
187
196
|
*
|
|
188
197
|
* @default 'https://observe-api.nestjs.com'
|
|
189
198
|
*/
|
|
@@ -589,6 +598,36 @@ export interface ObserveOptions {
|
|
|
589
598
|
*/
|
|
590
599
|
getUserId?: (call: any) => string;
|
|
591
600
|
};
|
|
601
|
+
/**
|
|
602
|
+
* Interoperates with OpenTelemetry. Off by default, and off, the agent
|
|
603
|
+
* reads and sends `x-request-id` alone, as it always has.
|
|
604
|
+
*
|
|
605
|
+
* On:
|
|
606
|
+
* - A request that arrives in a W3C trace (`traceparent`) is reported under
|
|
607
|
+
* that trace's id, written as a UUID, so it has the id the rest of the
|
|
608
|
+
* trace has in the caller's OpenTelemetry backend. An `x-request-id` is
|
|
609
|
+
* kept when it names the same trace, which is what another service
|
|
610
|
+
* running the agent sends.
|
|
611
|
+
* - Outbound `fetch` and `node:http` calls carry a `traceparent` beside
|
|
612
|
+
* `x-request-id` - see `outgoing.http.traceContext`.
|
|
613
|
+
* - With an OpenTelemetry SDK running in the same process - or an SDK
|
|
614
|
+
* built on it, as Sentry's Node SDK is from version 8 - a request is
|
|
615
|
+
* reported under the trace of the server span the SDK opened for it, the
|
|
616
|
+
* request that starts a trace included, and `traceparent` on outbound
|
|
617
|
+
* calls is left to the SDK.
|
|
618
|
+
*
|
|
619
|
+
* A `traceIdGenerator` passed to `createObserveModule()` still names the
|
|
620
|
+
* trace; the W3C one is carried on beside it.
|
|
621
|
+
*
|
|
622
|
+
* It works only beside reporting to NestJS Observe: from the first batch
|
|
623
|
+
* the collector accepts, and paused - each time with a line in the log -
|
|
624
|
+
* while the collector refuses the app's credentials, once batches have
|
|
625
|
+
* failed to get in for a minute, or while the agent's worker is down. It
|
|
626
|
+
* resumes with the next batch the collector accepts. With `enabled: false`,
|
|
627
|
+
* or without credentials for the hosted collector, it never turns on.
|
|
628
|
+
* @default false
|
|
629
|
+
*/
|
|
630
|
+
openTelemetry?: boolean;
|
|
592
631
|
/**
|
|
593
632
|
* Spans for what leaves the process: database queries (`pg`, `mysql2`, `mssql`,
|
|
594
633
|
* `mongodb` - and so every ORM built on them) and outbound HTTP requests
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { TraceSpan } from "./trace-span.interface.js";
|
|
2
2
|
export interface OngoingTraceEventNode extends TraceSpan {
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* `"start"` while the call runs, `"end"` once it has returned. A node that
|
|
5
|
+
* has ended keeps its other fields where they are - `startTime`, an empty
|
|
6
|
+
* `children` - until its trace is handed off, when the tree is rebuilt into
|
|
7
|
+
* `CompleteTraceEventNode`s holding only what is shipped.
|
|
8
|
+
*/
|
|
9
|
+
type: "start" | "end";
|
|
4
10
|
/**
|
|
5
11
|
* Represents the host class name, which is the class where the method being traced is defined.
|
|
6
12
|
*/
|
|
@@ -17,9 +23,9 @@ export interface OngoingTraceEventNode extends TraceSpan {
|
|
|
17
23
|
/**
|
|
18
24
|
* Milliseconds between the start of the trace root and the start of this span.
|
|
19
25
|
*
|
|
20
|
-
* Captured when the span opens and carried through to the completed node,
|
|
21
|
-
*
|
|
22
|
-
*
|
|
26
|
+
* Captured when the span opens and carried through to the completed node,
|
|
27
|
+
* which has no `startTime`. Undefined when the parent snapshot has already
|
|
28
|
+
* been cleaned up.
|
|
23
29
|
*/
|
|
24
30
|
startOffset?: number;
|
|
25
31
|
/**
|
|
@@ -31,7 +37,7 @@ export interface OngoingTraceEventNode extends TraceSpan {
|
|
|
31
37
|
children: Array<CompleteTraceEventNode | OngoingTraceEventNode>;
|
|
32
38
|
/**
|
|
33
39
|
* Optional parent node for ongoing trace events.
|
|
34
|
-
* Undefined for root nodes.
|
|
40
|
+
* Undefined for root nodes, and once the node has ended.
|
|
35
41
|
*/
|
|
36
42
|
parent?: OngoingTraceEventNode;
|
|
37
43
|
}
|
|
@@ -3,13 +3,23 @@ export declare const CALLER_METADATA_KEY = "#caller";
|
|
|
3
3
|
/**
|
|
4
4
|
* Where a store keeps the registry key when it differs from the trace id.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
6
|
+
* Queued jobs and RPC calls can share the trace id of the operation that
|
|
7
|
+
* dispatched them, including one still open in this process. The registry is
|
|
8
|
+
* keyed per execution, so each gets a key of its own here while `traceIdKey`
|
|
9
|
+
* keeps the id everything user-facing reads: logs, `currentTraceId()`, the
|
|
10
|
+
* snapshot.
|
|
11
11
|
*/
|
|
12
12
|
export declare const TRACE_REGISTRY_KEY = "#registryKey";
|
|
13
|
+
/**
|
|
14
|
+
* Where a store keeps the W3C trace context its operation arrived with - see
|
|
15
|
+
* `readTraceContext`. Absent when none came in; outbound calls then derive
|
|
16
|
+
* their `traceparent` from the trace id instead.
|
|
17
|
+
*
|
|
18
|
+
* Apart from `traceIdKey` because the two can disagree: an `x-request-id`
|
|
19
|
+
* from a proxy names the Observe trace, while the `traceparent` beside it
|
|
20
|
+
* names the OpenTelemetry trace the caller is in, and both are passed on.
|
|
21
|
+
*/
|
|
22
|
+
export declare const TRACE_CONTEXT_KEY = "#traceContext";
|
|
13
23
|
/**
|
|
14
24
|
* The job option the enqueuing side stamps the active trace id into. Both
|
|
15
25
|
* BullMQ and Bull persist unknown options verbatim, so it survives the trip
|
|
@@ -3,13 +3,23 @@ export const CALLER_METADATA_KEY = "#caller";
|
|
|
3
3
|
/**
|
|
4
4
|
* Where a store keeps the registry key when it differs from the trace id.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
6
|
+
* Queued jobs and RPC calls can share the trace id of the operation that
|
|
7
|
+
* dispatched them, including one still open in this process. The registry is
|
|
8
|
+
* keyed per execution, so each gets a key of its own here while `traceIdKey`
|
|
9
|
+
* keeps the id everything user-facing reads: logs, `currentTraceId()`, the
|
|
10
|
+
* snapshot.
|
|
11
11
|
*/
|
|
12
12
|
export const TRACE_REGISTRY_KEY = "#registryKey";
|
|
13
|
+
/**
|
|
14
|
+
* Where a store keeps the W3C trace context its operation arrived with - see
|
|
15
|
+
* `readTraceContext`. Absent when none came in; outbound calls then derive
|
|
16
|
+
* their `traceparent` from the trace id instead.
|
|
17
|
+
*
|
|
18
|
+
* Apart from `traceIdKey` because the two can disagree: an `x-request-id`
|
|
19
|
+
* from a proxy names the Observe trace, while the `traceparent` beside it
|
|
20
|
+
* names the OpenTelemetry trace the caller is in, and both are passed on.
|
|
21
|
+
*/
|
|
22
|
+
export const TRACE_CONTEXT_KEY = "#traceContext";
|
|
13
23
|
/**
|
|
14
24
|
* The job option the enqueuing side stamps the active trace id into. Both
|
|
15
25
|
* BullMQ and Bull persist unknown options verbatim, so it survives the trip
|
package/dist/observe.module.js
CHANGED
|
@@ -37,6 +37,7 @@ import { TraceSamplerService } from "./services/trace-sampler.service.js";
|
|
|
37
37
|
import { TracerService } from "./services/tracer.service.js";
|
|
38
38
|
import { assertModuleOptions } from "./utils/assert-module-options.util.js";
|
|
39
39
|
import { defaultTraceIdGenerator } from "./utils/default-trace-id-generator.util.js";
|
|
40
|
+
import { recordTraceIdGeneratorOrigin } from "./utils/trace-id-generator-origin.util.js";
|
|
40
41
|
import { fitServiceVersion, MAX_SERVICE_VERSION_LENGTH, } from "./utils/fit-service-version.util.js";
|
|
41
42
|
import { fitToLength } from "./utils/fit-to-length.util.js";
|
|
42
43
|
import { inferServiceVersion } from "./utils/infer-service-version.util.js";
|
|
@@ -125,6 +126,8 @@ export function createObserveModule(options = {}) {
|
|
|
125
126
|
options.traceIdKey ??= "traceId";
|
|
126
127
|
options.attachTraceIdToLogs ??= true;
|
|
127
128
|
options.traceIdGenerator ??= defaultTraceIdGenerator;
|
|
129
|
+
// While the options are a plain object - see the function.
|
|
130
|
+
recordTraceIdGeneratorOrigin(options);
|
|
128
131
|
options.skipInstrumentation ??= () => false;
|
|
129
132
|
// Inert until the agent starts with `outgoing.llm` on - see the function.
|
|
130
133
|
// `forRoot` puts the original back if its options turn model calls off.
|