@nestjs/observe 0.3.24 → 0.3.25
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 +9 -1
- package/dist/custom-metrics/gauge.js +2 -4
- package/dist/instrument/create-instance-decorator.instrument.js +86 -1
- package/dist/otlp/otlp-span.mapper.d.ts +4 -3
- package/dist/otlp/otlp-span.mapper.js +9 -5
- package/dist/otlp/otlp-trace-exporter.service.d.ts +3 -0
- package/dist/otlp/otlp-trace-exporter.service.js +8 -1
- package/dist/protocols/job-trace-runner.js +10 -2
- package/dist/protocols/rpc-observe-agent.service.js +39 -3
- package/dist/services/tracer.service.js +8 -2
- package/dist/utils/source-context.util.js +9 -4
- package/dist/utils/trace-context.util.d.ts +20 -0
- package/dist/utils/trace-context.util.js +29 -0
- package/package.json +4 -1
package/README.md
CHANGED
|
@@ -569,7 +569,7 @@ What a backend receives, for each operation:
|
|
|
569
569
|
|
|
570
570
|
- **A SERVER span** for every request, GraphQL operation, RPC message and gateway message, named like the dashboard names it (`GET /orders/:id`), with the HTTP semantic conventions - `http.request.method`, `http.route`, `http.response.status_code`, `url.path` - plus `enduser.id`, your `tags`, and the headers `http.capture` recorded. A queue job is a CONSUMER span, a scheduled run an INTERNAL one.
|
|
571
571
|
- **INTERNAL spans** for the provider methods and manual spans under it, named `OrdersService.findOne`, and **CLIENT spans** for queries and outbound HTTP calls, named for what they did (`SELECT orders`, `GET api.stripe.com`).
|
|
572
|
-
- **The same trace ids `traceparent` carries.** A request that arrived with a `traceparent` goes under the caller's span, and a call this service makes names its CLIENT span as the parent the callee sees - so services instrumented with OpenTelemetry, and other services running the agent, assemble into one trace in the backend.
|
|
572
|
+
- **The same trace ids `traceparent` carries.** A request that arrived with a `traceparent` goes under the caller's span, a queue job or microservice message under the span that handed it on, and a call this service makes names its CLIENT span as the parent the callee sees - so services instrumented with OpenTelemetry, and other services running the agent, assemble into one trace in the backend.
|
|
573
573
|
- **Errors** as span status and an `exception` event, with the class, message and stack the dashboard shows - redacted the same way.
|
|
574
574
|
|
|
575
575
|
What is exported is what is recorded: after `tracesSampleRate`, `skipSpans` and `spanCollapse`, and on Free after what NestJS Observe holds back. A request whose caller sampled its trace out (`traceparent` flags `00`) is not exported, as an OpenTelemetry SDK sampling by its parent would leave it out. Spans wait in a queue of at most 10,000 while an export is retried (429, 502, 503 and 504, honouring `Retry-After`); past that, whole operations are dropped and counted. Exports run on the application's thread, outside its traces, and whatever is queued is exported when the application closes, within `shutdownFlushTimeout`. Traces only, for now: runtime metrics, custom metrics and logs are not exported.
|
|
@@ -659,6 +659,14 @@ $ docker run -d -p 4318:4318 -p 16686:16686 jaegertracing/jaeger:2.22.0
|
|
|
659
659
|
|
|
660
660
|
To point them elsewhere, set `REDIS_HOST`/`REDIS_PORT`, `PGHOST`/`PGPORT`/`PGUSER`/`PGPASSWORD`/`PGDATABASE`, `MYSQL_HOST`/`MYSQL_PORT`/`MYSQL_USER`/`MYSQL_PASSWORD`/`MYSQL_DATABASE`, `MONGO_HOST`/`MONGO_PORT`, or `JAEGER_OTLP_ENDPOINT`/`JAEGER_QUERY_URL` for the suite that exports traces into Jaeger.
|
|
661
661
|
|
|
662
|
+
The suites run on the Nest the devDependencies pin. CI also runs them on Nest 12.0.1 and 11.2.8; to do the same locally, swap the dev tree first. The script rewrites `package.json` and the lockfile, so restore both afterwards:
|
|
663
|
+
|
|
664
|
+
```bash
|
|
665
|
+
$ node scripts/use-nest.cjs 11.2.8
|
|
666
|
+
$ npm test && npm run test:int
|
|
667
|
+
$ git checkout -- package.json package-lock.json && npm ci --legacy-peer-deps
|
|
668
|
+
```
|
|
669
|
+
|
|
662
670
|
## Module format
|
|
663
671
|
|
|
664
672
|
The package ships as ESM only. CommonJS consumers can still `require()` it
|
|
@@ -174,11 +174,9 @@ export class Gauge {
|
|
|
174
174
|
else if (typeof labelOrValue === "object") {
|
|
175
175
|
this.validateLabels(labelOrValue);
|
|
176
176
|
const stringifiedLabel = stringifyLabel(labelOrValue);
|
|
177
|
-
if (!(stringifiedLabel in this.value)) {
|
|
178
|
-
throw new Error(`Label "${stringifiedLabel}" does not exist in the gauge. Available labels: ${Object.keys(this.value).join(", ")}.`);
|
|
179
|
-
}
|
|
180
177
|
const newValue = value ?? this._initialValue;
|
|
181
|
-
if (!admitsFinite(this.name, newValue, this.nonFinite)
|
|
178
|
+
if (!admitsFinite(this.name, newValue, this.nonFinite) ||
|
|
179
|
+
!admitsSeries(this.name, this.value, stringifiedLabel, this.seriesLimit)) {
|
|
182
180
|
return;
|
|
183
181
|
}
|
|
184
182
|
this.value[stringifiedLabel] = newValue;
|
|
@@ -64,6 +64,86 @@ function isMongoDriverHandle(instance) {
|
|
|
64
64
|
return false;
|
|
65
65
|
}
|
|
66
66
|
}
|
|
67
|
+
/**
|
|
68
|
+
* Library classes traced only in part, each with a method only it has, which
|
|
69
|
+
* tells it from an application's own class of the same name - `ValidationPipe`
|
|
70
|
+
* is what Nest's documentation calls the pipe it has readers write themselves,
|
|
71
|
+
* and plenty of applications have a `ConfigService` of their own.
|
|
72
|
+
*
|
|
73
|
+
* - Nest's validating pipes keep only `validate`. `ValidationPipe` runs once
|
|
74
|
+
* per handler argument, and for each one `transform`, `toValidate` and
|
|
75
|
+
* `transformPrimitive` were spans, usually of a few microseconds and each
|
|
76
|
+
* one billed, on runs that mostly validate nothing: 82% of runs across the
|
|
77
|
+
* hosted platform on 2026-11-06, which made it the busiest class after
|
|
78
|
+
* `pg`, and 404,552 of 404,652 on one REST app.
|
|
79
|
+
* - `@nestjs/config`'s `ConfigService` keeps what an application calls. Each
|
|
80
|
+
* `get` made four or five more spans of its private helpers - 2.7M of its
|
|
81
|
+
* 4.6M a day, in 220 projects.
|
|
82
|
+
*
|
|
83
|
+
* Folding cannot reach any of them (`collapseRepeatedSpans`), because each
|
|
84
|
+
* repeats only a few times under its parent.
|
|
85
|
+
*
|
|
86
|
+
* By name, because `StandardSchemaValidationPipe` is not in every supported
|
|
87
|
+
* `@nestjs/common` and an application may carry a second copy of a package.
|
|
88
|
+
* A class that stops matching is simply traced like any other.
|
|
89
|
+
*/
|
|
90
|
+
const PARTLY_TRACED_CLASSES = new Map([
|
|
91
|
+
[
|
|
92
|
+
"ValidationPipe",
|
|
93
|
+
{ marker: "flattenValidationErrors", traced: new Set(["validate"]) },
|
|
94
|
+
],
|
|
95
|
+
[
|
|
96
|
+
"StandardSchemaValidationPipe",
|
|
97
|
+
{ marker: "formatIssueMessages", traced: new Set(["validate"]) },
|
|
98
|
+
],
|
|
99
|
+
[
|
|
100
|
+
"ParseFilePipe",
|
|
101
|
+
{ marker: "validateFilesOrFile", traced: new Set(["validate"]) },
|
|
102
|
+
],
|
|
103
|
+
[
|
|
104
|
+
"ConfigService",
|
|
105
|
+
{
|
|
106
|
+
marker: "getFromValidatedEnv",
|
|
107
|
+
traced: new Set(["get", "getOrThrow", "set", "setEnvFilePaths"]),
|
|
108
|
+
},
|
|
109
|
+
],
|
|
110
|
+
]);
|
|
111
|
+
/** The methods a prototype's class keeps traced, if it is one of those. */
|
|
112
|
+
function partlyTracedMethodsOf(proto) {
|
|
113
|
+
const candidate = proto;
|
|
114
|
+
const entry = PARTLY_TRACED_CLASSES.get(candidate.constructor?.name ?? "");
|
|
115
|
+
return entry !== undefined && typeof candidate[entry.marker] === "function"
|
|
116
|
+
? entry.traced
|
|
117
|
+
: null;
|
|
118
|
+
}
|
|
119
|
+
/** Whether an instance is one of those classes, or extends one. */
|
|
120
|
+
function extendsPartlyTracedClass(instance) {
|
|
121
|
+
for (let proto = Object.getPrototypeOf(instance); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
|
|
122
|
+
if (partlyTracedMethodsOf(proto) !== null) {
|
|
123
|
+
return true;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Whether a method is one of those classes' internals, and so makes no span.
|
|
130
|
+
*
|
|
131
|
+
* Asked of the class that holds the method, so what an application adds to or
|
|
132
|
+
* overrides in a subclass is still traced. An instance's own function - the
|
|
133
|
+
* `exceptionFactory` a constructor assigns - goes by the instance's class.
|
|
134
|
+
*/
|
|
135
|
+
function isLibraryInternal(target, methodName) {
|
|
136
|
+
let holder = target;
|
|
137
|
+
while (holder !== null && !Object.hasOwn(holder, methodName)) {
|
|
138
|
+
holder = Object.getPrototypeOf(holder);
|
|
139
|
+
}
|
|
140
|
+
if (holder === null) {
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
const traced = partlyTracedMethodsOf(holder === target ? Object.getPrototypeOf(target) : holder);
|
|
144
|
+
return (traced !== null &&
|
|
145
|
+
!(typeof methodName === "string" && traced.has(methodName)));
|
|
146
|
+
}
|
|
67
147
|
export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
68
148
|
/**
|
|
69
149
|
* Builds the tracing wrapper shared by methods and standalone functions.
|
|
@@ -220,6 +300,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
220
300
|
let hasPrivateMembers;
|
|
221
301
|
let slotBacked;
|
|
222
302
|
let bareBuiltIn;
|
|
303
|
+
let partlyTraced;
|
|
223
304
|
try {
|
|
224
305
|
// Inspected here, inside the guard, for the same reason as the checks
|
|
225
306
|
// below: reading a provider's constructor can run a trap that throws.
|
|
@@ -229,6 +310,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
229
310
|
hasPrivateMembers = usesNativePrivateMembers(instance);
|
|
230
311
|
slotBacked = isSlotBackedBuiltIn(instance);
|
|
231
312
|
bareBuiltIn = slotBacked && isNativeFunction(instance.constructor);
|
|
313
|
+
partlyTraced = extendsPartlyTracedClass(instance);
|
|
232
314
|
}
|
|
233
315
|
catch {
|
|
234
316
|
// Reading the prototype ran a trap that threw (nestjs-cls proxy
|
|
@@ -283,7 +365,10 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
283
365
|
// mid-trace). This subsumes the Axios special case that used to sit
|
|
284
366
|
// here: an Axios instance is a bound `request` carrying its API as
|
|
285
367
|
// own properties.
|
|
286
|
-
!isCallableObject(attributeValue)
|
|
368
|
+
!isCallableObject(attributeValue) &&
|
|
369
|
+
// Handed out as it is, so it still runs against the proxy: the
|
|
370
|
+
// `this.validate()` inside `transform` comes back through here.
|
|
371
|
+
!(partlyTraced && isLibraryInternal(target, prop));
|
|
287
372
|
if (!shouldProxy) {
|
|
288
373
|
// Remembered, as a wrapped method is: telling them apart reads the
|
|
289
374
|
// function's source and its prototype's keys, which a Mongoose
|
|
@@ -59,10 +59,11 @@ export declare function requestSnapshotSpans(snapshot: RequestSnapshot, context:
|
|
|
59
59
|
* A queue job or a scheduled run as OTLP spans: a CONSUMER span for the run
|
|
60
60
|
* - INTERNAL for a scheduled one, which nothing sent - and its tree under
|
|
61
61
|
* it. A job reports under the trace id of the operation that enqueued it,
|
|
62
|
-
* so it lands in that trace
|
|
63
|
-
*
|
|
62
|
+
* so it lands in that trace, and under the span that enqueued it when it was
|
|
63
|
+
* handed on with a `traceparent` - see `handedOnTraceContext`. Without
|
|
64
|
+
* `withTree`, the run's span alone.
|
|
64
65
|
*/
|
|
65
|
-
export declare function jobSnapshotSpans(snapshot: JobSnapshot, withTree?: boolean): OtlpSpan[];
|
|
66
|
+
export declare function jobSnapshotSpans(snapshot: JobSnapshot, context: TraceContext | undefined, withTree?: boolean): OtlpSpan[];
|
|
66
67
|
/**
|
|
67
68
|
* Attributes from a flat record, in its order, without the keys that hold
|
|
68
69
|
* nothing - and at most `MAX_ATTRIBUTES_PER_SPAN` of them, the rest counted.
|
|
@@ -115,11 +115,12 @@ export function requestSnapshotSpans(snapshot, context, withTree = true) {
|
|
|
115
115
|
* A queue job or a scheduled run as OTLP spans: a CONSUMER span for the run
|
|
116
116
|
* - INTERNAL for a scheduled one, which nothing sent - and its tree under
|
|
117
117
|
* it. A job reports under the trace id of the operation that enqueued it,
|
|
118
|
-
* so it lands in that trace
|
|
119
|
-
*
|
|
118
|
+
* so it lands in that trace, and under the span that enqueued it when it was
|
|
119
|
+
* handed on with a `traceparent` - see `handedOnTraceContext`. Without
|
|
120
|
+
* `withTree`, the run's span alone.
|
|
120
121
|
*/
|
|
121
|
-
export function jobSnapshotSpans(snapshot, withTree = true) {
|
|
122
|
-
const traceId = w3cTraceIdOf(snapshot.traceId);
|
|
122
|
+
export function jobSnapshotSpans(snapshot, context, withTree = true) {
|
|
123
|
+
const traceId = context?.traceId ?? w3cTraceIdOf(snapshot.traceId);
|
|
123
124
|
const startNs = epochNanos(snapshot.calledAt);
|
|
124
125
|
const scheduled = SCHEDULER_QUEUES.has(snapshot.queueName);
|
|
125
126
|
const tags = {
|
|
@@ -141,6 +142,9 @@ export function jobSnapshotSpans(snapshot, withTree = true) {
|
|
|
141
142
|
const run = {
|
|
142
143
|
traceId,
|
|
143
144
|
spanId: randomSpanId(),
|
|
145
|
+
...(context
|
|
146
|
+
? { parentSpanId: context.parentSpanId, traceState: context.traceState }
|
|
147
|
+
: {}),
|
|
144
148
|
name: `${snapshot.queueName} ${snapshot.name}`,
|
|
145
149
|
kind: scheduled ? SpanKind.INTERNAL : SpanKind.CONSUMER,
|
|
146
150
|
startTimeUnixNano: startNs,
|
|
@@ -148,7 +152,7 @@ export function jobSnapshotSpans(snapshot, withTree = true) {
|
|
|
148
152
|
...toAttributes(tags),
|
|
149
153
|
events: [],
|
|
150
154
|
...(failed ? { status: errorStatus(snapshot.error) } : {}),
|
|
151
|
-
flags: LOCAL_PARENT_FLAGS,
|
|
155
|
+
flags: context ? REMOTE_PARENT_FLAGS : LOCAL_PARENT_FLAGS,
|
|
152
156
|
};
|
|
153
157
|
const spans = [run];
|
|
154
158
|
for (const node of withTree ? snapshot.traces ?? [] : []) {
|
|
@@ -86,6 +86,9 @@ export declare class OtlpTraceExporter implements OnModuleInit, OnApplicationShu
|
|
|
86
86
|
/**
|
|
87
87
|
* Queues a finished job's spans - its own span, and with `withTree` the
|
|
88
88
|
* spans under it. Never throws into the caller.
|
|
89
|
+
*
|
|
90
|
+
* Left out, as a request is, when the trace it was handed on in is one an
|
|
91
|
+
* OpenTelemetry SDK in this process sampled out.
|
|
89
92
|
*/
|
|
90
93
|
exportJobSnapshot(snapshot: JobSnapshot, withTree?: boolean): void;
|
|
91
94
|
/**
|
|
@@ -210,13 +210,20 @@ let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
|
|
|
210
210
|
/**
|
|
211
211
|
* Queues a finished job's spans - its own span, and with `withTree` the
|
|
212
212
|
* spans under it. Never throws into the caller.
|
|
213
|
+
*
|
|
214
|
+
* Left out, as a request is, when the trace it was handed on in is one an
|
|
215
|
+
* OpenTelemetry SDK in this process sampled out.
|
|
213
216
|
*/
|
|
214
217
|
exportJobSnapshot(snapshot, withTree = true) {
|
|
215
218
|
if (!this.settings) {
|
|
216
219
|
return;
|
|
217
220
|
}
|
|
218
221
|
try {
|
|
219
|
-
this.
|
|
222
|
+
const context = this.operationTraceRegistry.traceContextOf(snapshot);
|
|
223
|
+
if (context && !context.sampled) {
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
this.enqueue(jobSnapshotSpans(snapshot, context, withTree));
|
|
220
227
|
}
|
|
221
228
|
catch (error) {
|
|
222
229
|
this.reportMappingFailure(error);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { JOB_TRACE_CONTEXT_OPTION_KEY, JOB_TRACE_OPTION_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
|
|
1
|
+
import { JOB_TRACE_CONTEXT_OPTION_KEY, JOB_TRACE_OPTION_KEY, TRACE_CONTEXT_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
|
|
2
2
|
import { REQUEST_ID_PATTERN } from "../utils/default-trace-id-generator.util.js";
|
|
3
|
+
import { handedOnTraceContext } from "../utils/trace-context.util.js";
|
|
3
4
|
import { continueHandedOnTrace, traceparentToHandOn, } from "../utils/trace-handoff.util.js";
|
|
4
5
|
import { uuidv7 } from "../utils/uuid-v7.util.js";
|
|
5
6
|
import { deferTraceCompletion, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
|
|
@@ -217,6 +218,13 @@ export class JobTraceRunner {
|
|
|
217
218
|
const handedOn = inheritedTraceId !== undefined && this.openTelemetryInteropOn()
|
|
218
219
|
? job.opts?.[JOB_TRACE_CONTEXT_OPTION_KEY]
|
|
219
220
|
: undefined;
|
|
221
|
+
// And the job's span goes under the span that handed it on, for `otlp`,
|
|
222
|
+
// while the calls it makes carry the caller's decision on - as a
|
|
223
|
+
// request's do with the `traceparent` it arrived with.
|
|
224
|
+
const traceContext = handedOnTraceContext(handedOn, traceId);
|
|
225
|
+
if (traceContext) {
|
|
226
|
+
store.set(TRACE_CONTEXT_KEY, traceContext);
|
|
227
|
+
}
|
|
220
228
|
const context = {
|
|
221
229
|
queueName: job.queueName,
|
|
222
230
|
name: job.name,
|
|
@@ -235,7 +243,7 @@ export class JobTraceRunner {
|
|
|
235
243
|
tags: this.options.jobs?.tags,
|
|
236
244
|
...context,
|
|
237
245
|
...job.metadata,
|
|
238
|
-
}, traceId);
|
|
246
|
+
}, traceId, traceContext);
|
|
239
247
|
let settled = false;
|
|
240
248
|
const settle = (status) => {
|
|
241
249
|
if (settled) {
|
|
@@ -17,7 +17,8 @@ import { AsyncLocalStorage } from "async_hooks";
|
|
|
17
17
|
import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
|
|
18
18
|
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
19
19
|
import { TraceSamplerService } from "../services/trace-sampler.service.js";
|
|
20
|
-
import { OBSERVE_OPTIONS, TRACE_REGISTRY_KEY } from "../observe.constants.js";
|
|
20
|
+
import { OBSERVE_OPTIONS, TRACE_CONTEXT_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
|
|
21
|
+
import { handedOnTraceContext } from "../utils/trace-context.util.js";
|
|
21
22
|
import { continueHandedOnTrace } from "../utils/trace-handoff.util.js";
|
|
22
23
|
import { uuidv7 } from "../utils/uuid-v7.util.js";
|
|
23
24
|
import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
|
|
@@ -129,6 +130,13 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
129
130
|
const handle = handedOn === undefined
|
|
130
131
|
? done
|
|
131
132
|
: () => continueHandedOnTrace(handedOn, traceId, done);
|
|
133
|
+
// And the handler's span goes under the span that sent the message, for
|
|
134
|
+
// `otlp`, while the calls it makes carry the caller's decision on - as
|
|
135
|
+
// a request's do with the `traceparent` it arrived with.
|
|
136
|
+
const traceContext = handedOnTraceContext(handedOn, traceId);
|
|
137
|
+
if (traceContext) {
|
|
138
|
+
store.set(TRACE_CONTEXT_KEY, traceContext);
|
|
139
|
+
}
|
|
132
140
|
setAttributesSafely(this.options.rpc?.setAttributes, [transportId, ctx], this.options.rpc, store, this.logger, "rpc");
|
|
133
141
|
if (shouldIgnoreSafely(this.options.rpc?.ignore, [transportId, ctx], this.options.rpc, this.logger, "rpc")) {
|
|
134
142
|
return handle();
|
|
@@ -144,7 +152,7 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
144
152
|
protocol: this.toProtocolName(transportId),
|
|
145
153
|
operationId: this.getOperationIdFromContext(ctx),
|
|
146
154
|
tags: this.options.rpc?.tags,
|
|
147
|
-
}, traceId);
|
|
155
|
+
}, traceId, traceContext);
|
|
148
156
|
return handle();
|
|
149
157
|
});
|
|
150
158
|
}
|
|
@@ -165,6 +173,17 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
165
173
|
// The key must precede callbacks here too, before the deferred startup.
|
|
166
174
|
const registryKey = uuidv7();
|
|
167
175
|
store.set(TRACE_REGISTRY_KEY, registryKey);
|
|
176
|
+
// As for a message: the call's span goes under the caller's for `otlp`,
|
|
177
|
+
// and the calls the handler makes carry its decision on. Read now, while
|
|
178
|
+
// the span a gRPC instrumentation opened for the call is the active one.
|
|
179
|
+
// Unlike a message's, the handler is not run in the caller's trace: the
|
|
180
|
+
// SDK's gRPC instrumentation carries it there.
|
|
181
|
+
const traceContext = this.openTelemetryInteropOn()
|
|
182
|
+
? handedOnTraceContext(grpcTraceparent(call), traceId)
|
|
183
|
+
: undefined;
|
|
184
|
+
if (traceContext) {
|
|
185
|
+
store.set(TRACE_CONTEXT_KEY, traceContext);
|
|
186
|
+
}
|
|
168
187
|
setAttributesSafely(this.options.grpc?.setAttributes, [call], this.options.grpc, store, this.logger, "grpc");
|
|
169
188
|
return new Promise((resolve) => {
|
|
170
189
|
// A throw in this timer escapes the promise: `done()` never runs, and
|
|
@@ -183,7 +202,7 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
|
|
|
183
202
|
protocol: this.toProtocolName(transportId),
|
|
184
203
|
operationId: call.operationId,
|
|
185
204
|
tags: this.options.grpc?.tags,
|
|
186
|
-
}, traceId);
|
|
205
|
+
}, traceId, traceContext);
|
|
187
206
|
resolve(done());
|
|
188
207
|
}, 0);
|
|
189
208
|
});
|
|
@@ -272,3 +291,20 @@ function handedOnTraceparent(ctx) {
|
|
|
272
291
|
return undefined;
|
|
273
292
|
}
|
|
274
293
|
}
|
|
294
|
+
/**
|
|
295
|
+
* The `traceparent` a gRPC call's metadata carries - a caller instrumented
|
|
296
|
+
* with OpenTelemetry sends one, and so does one running the agent with
|
|
297
|
+
* `openTelemetry` on - read off grpc-js's `Metadata`, whichever Nest release
|
|
298
|
+
* handed the call over.
|
|
299
|
+
*/
|
|
300
|
+
function grpcTraceparent(call) {
|
|
301
|
+
try {
|
|
302
|
+
const metadata = call.metadata;
|
|
303
|
+
const value = metadata?.get?.("traceparent")?.[0];
|
|
304
|
+
return typeof value === "string" ? value : undefined;
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
// Metadata that cannot be read carries nothing to continue.
|
|
308
|
+
return undefined;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
@@ -128,9 +128,12 @@ let TracerService = TracerService_1 = class TracerService {
|
|
|
128
128
|
if (attributes?.labels) {
|
|
129
129
|
overridableRef.labels = attributes.labels;
|
|
130
130
|
}
|
|
131
|
+
// `value` holds one reading per label, so the seed goes to the default
|
|
132
|
+
// one; a labelled metric has no unlabelled reading to seed.
|
|
131
133
|
if (attributes?.initialValue !== undefined &&
|
|
134
|
+
!existingRef.labels &&
|
|
132
135
|
existingRef.getValue() === 0) {
|
|
133
|
-
overridableRef
|
|
136
|
+
overridableRef.value.default = attributes.initialValue;
|
|
134
137
|
}
|
|
135
138
|
return existingRef;
|
|
136
139
|
}
|
|
@@ -149,9 +152,12 @@ let TracerService = TracerService_1 = class TracerService {
|
|
|
149
152
|
if (attributes?.labels) {
|
|
150
153
|
overridableRef.labels = attributes.labels;
|
|
151
154
|
}
|
|
155
|
+
// `value` holds one reading per label, so the seed goes to the default
|
|
156
|
+
// one; a labelled metric has no unlabelled reading to seed.
|
|
152
157
|
if (attributes?.initialValue !== undefined &&
|
|
158
|
+
!existingRef.labels &&
|
|
153
159
|
existingRef.getValue() === 0) {
|
|
154
|
-
overridableRef
|
|
160
|
+
overridableRef.value.default = attributes.initialValue;
|
|
155
161
|
}
|
|
156
162
|
if (attributes?.kind) {
|
|
157
163
|
overridableRef.kind = attributes.kind;
|
|
@@ -91,11 +91,16 @@ function frameLines(stack, message) {
|
|
|
91
91
|
headerEnd = stack.indexOf("\n");
|
|
92
92
|
}
|
|
93
93
|
else {
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
94
|
+
// The last match on the first line that runs to the end of a line: an
|
|
95
|
+
// earlier one can sit inside the name - `UnauthorizedException:
|
|
96
|
+
// Unauthorized` - and a later one ends past the real message, so whatever
|
|
97
|
+
// follows it is still what V8 wrote.
|
|
98
|
+
headerEnd = -1;
|
|
99
|
+
for (let at = stack.indexOf(message); at !== -1 && stack.lastIndexOf("\n", at) === -1; at = stack.indexOf(message, at + 1)) {
|
|
100
|
+
if (stack[at + message.length] === "\n") {
|
|
101
|
+
headerEnd = at + message.length;
|
|
102
|
+
}
|
|
97
103
|
}
|
|
98
|
-
headerEnd = at + message.length;
|
|
99
104
|
}
|
|
100
105
|
if (headerEnd === -1 || stack[headerEnd] !== "\n") {
|
|
101
106
|
return [];
|
|
@@ -62,6 +62,26 @@ export declare function inboundTraceContext(headers: Record<string, unknown> | u
|
|
|
62
62
|
* `traceIdFromTraceparent` writes it.
|
|
63
63
|
*/
|
|
64
64
|
export declare function inboundTraceId(headers: Record<string, unknown> | undefined): string | undefined;
|
|
65
|
+
/**
|
|
66
|
+
* The W3C trace context a queue job or a microservice message runs in -
|
|
67
|
+
* `inboundTraceContext`'s counterpart for work handed on with a `traceparent`
|
|
68
|
+
* (see `traceparentToHandOn`), whose span the exporter puts under it. That is
|
|
69
|
+
* the span an OpenTelemetry SDK in this process has open for the work, when
|
|
70
|
+
* it is in that trace - an instrumentation that covers the hop opens one:
|
|
71
|
+
* `bullmq-otel` for a job, the SDK's gRPC, Kafka or RabbitMQ instrumentation
|
|
72
|
+
* for a message - else the `traceparent` itself.
|
|
73
|
+
*
|
|
74
|
+
* Only a `traceparent` in the trace `traceId` - the Observe trace id the work
|
|
75
|
+
* runs under - maps onto, as `continueHandedOnTrace` takes it: job options and
|
|
76
|
+
* packet metadata are writable by anything that reaches Redis or the socket.
|
|
77
|
+
*
|
|
78
|
+
* And only a sampled one, which a request's `traceparent` need not be. The
|
|
79
|
+
* agent hands work on unsampled when the operation that sent it was not
|
|
80
|
+
* recorded, naming a span that exists nowhere; or its caller sampled the
|
|
81
|
+
* trace out, and nothing upstream exports it. Either way there is no parent
|
|
82
|
+
* to put the work's span under, so it stays as it was without one.
|
|
83
|
+
*/
|
|
84
|
+
export declare function handedOnTraceContext(traceparent: unknown, traceId: string): TraceContext | undefined;
|
|
65
85
|
/**
|
|
66
86
|
* The W3C trace id an Observe trace id goes out under.
|
|
67
87
|
*
|
|
@@ -126,6 +126,35 @@ export function inboundTraceId(headers) {
|
|
|
126
126
|
const traceId = inboundTraceContext(headers)?.traceId;
|
|
127
127
|
return traceId === undefined ? undefined : toUuid(traceId);
|
|
128
128
|
}
|
|
129
|
+
/**
|
|
130
|
+
* The W3C trace context a queue job or a microservice message runs in -
|
|
131
|
+
* `inboundTraceContext`'s counterpart for work handed on with a `traceparent`
|
|
132
|
+
* (see `traceparentToHandOn`), whose span the exporter puts under it. That is
|
|
133
|
+
* the span an OpenTelemetry SDK in this process has open for the work, when
|
|
134
|
+
* it is in that trace - an instrumentation that covers the hop opens one:
|
|
135
|
+
* `bullmq-otel` for a job, the SDK's gRPC, Kafka or RabbitMQ instrumentation
|
|
136
|
+
* for a message - else the `traceparent` itself.
|
|
137
|
+
*
|
|
138
|
+
* Only a `traceparent` in the trace `traceId` - the Observe trace id the work
|
|
139
|
+
* runs under - maps onto, as `continueHandedOnTrace` takes it: job options and
|
|
140
|
+
* packet metadata are writable by anything that reaches Redis or the socket.
|
|
141
|
+
*
|
|
142
|
+
* And only a sampled one, which a request's `traceparent` need not be. The
|
|
143
|
+
* agent hands work on unsampled when the operation that sent it was not
|
|
144
|
+
* recorded, naming a span that exists nowhere; or its caller sampled the
|
|
145
|
+
* trace out, and nothing upstream exports it. Either way there is no parent
|
|
146
|
+
* to put the work's span under, so it stays as it was without one.
|
|
147
|
+
*/
|
|
148
|
+
export function handedOnTraceContext(traceparent, traceId) {
|
|
149
|
+
const handedOn = typeof traceparent === "string"
|
|
150
|
+
? readTraceContext({ traceparent })
|
|
151
|
+
: undefined;
|
|
152
|
+
if (!handedOn?.sampled || handedOn.traceId !== w3cTraceIdOf(traceId)) {
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
const active = traceContextOfSpan(activeOpenTelemetrySpanContext());
|
|
156
|
+
return active?.traceId === handedOn.traceId ? active : handedOn;
|
|
157
|
+
}
|
|
129
158
|
/**
|
|
130
159
|
* An OpenTelemetry span context as the trace context an operation runs in,
|
|
131
160
|
* the span becoming the operation's parent - or `undefined` for one the spec
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nestjs/observe",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.25",
|
|
4
4
|
"description": "Observability and APM agent for NestJS - traces, runtime metrics and custom metrics",
|
|
5
5
|
"author": "Kamil Mysliwiec",
|
|
6
6
|
"homepage": "https://observe.nestjs.com",
|
|
@@ -163,6 +163,8 @@
|
|
|
163
163
|
"@types/supertest": "7.2.1",
|
|
164
164
|
"@types/ws": "8.18.1",
|
|
165
165
|
"@vitest/coverage-v8": "4.1.11",
|
|
166
|
+
"amqp-connection-manager": "5.0.0",
|
|
167
|
+
"amqplib": "2.2.0",
|
|
166
168
|
"bull": "4.16.5",
|
|
167
169
|
"bullmq": "6.2.0",
|
|
168
170
|
"bullmq-otel": "2.0.1",
|
|
@@ -172,6 +174,7 @@
|
|
|
172
174
|
"graphql": "16.14.2",
|
|
173
175
|
"husky": "9.1.7",
|
|
174
176
|
"ioredis": "6.0.0",
|
|
177
|
+
"kafkajs": "2.2.4",
|
|
175
178
|
"lint-staged": "17.6.0",
|
|
176
179
|
"mongodb": "7.6.0",
|
|
177
180
|
"mongoose": "9.10.1",
|