@nestjs/observe 0.3.21 → 0.3.23
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 +100 -14
- package/dist/agent/degraded-ingest.protocol.d.ts +14 -0
- package/dist/agent/degraded-ingest.protocol.js +19 -0
- package/dist/agent/detached-observe-worker.assembly.d.ts +2 -0
- package/dist/agent/detached-observe-worker.assembly.js +5 -1
- package/dist/agent/detached-observe-worker.d.ts +10 -0
- package/dist/agent/detached-observe-worker.js +27 -2
- package/dist/agent/observe-agent.shared-buffer.d.ts +63 -1
- package/dist/agent/observe-agent.shared-buffer.js +117 -2
- package/dist/agent/observe-agent.worker.d.ts +27 -20
- package/dist/agent/observe-agent.worker.js +109 -62
- package/dist/agent/observe-reporting.util.d.ts +35 -0
- package/dist/agent/observe-reporting.util.js +69 -0
- package/dist/interfaces/observe-options.interface.d.ts +100 -8
- package/dist/observe.constants.d.ts +17 -0
- package/dist/observe.constants.js +17 -0
- package/dist/observe.module.js +53 -4
- package/dist/otlp/otlp-encoders.d.ts +26 -0
- package/dist/otlp/otlp-encoders.js +296 -0
- package/dist/otlp/otlp-export-grant.d.ts +34 -0
- package/dist/otlp/otlp-export-grant.js +22 -0
- package/dist/otlp/otlp-options.interface.d.ts +59 -0
- package/dist/otlp/otlp-options.interface.js +1 -0
- package/dist/otlp/otlp-settings.util.d.ts +38 -0
- package/dist/otlp/otlp-settings.util.js +154 -0
- package/dist/otlp/otlp-span.mapper.d.ts +73 -0
- package/dist/otlp/otlp-span.mapper.js +345 -0
- package/dist/otlp/otlp-trace-exporter.service.d.ts +130 -0
- package/dist/otlp/otlp-trace-exporter.service.js +497 -0
- package/dist/outgoing/http.integration.d.ts +36 -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/outgoing/sql-statement.util.js +2 -2
- package/dist/protocols/http-observe-agent.service.d.ts +1 -8
- package/dist/protocols/http-observe-agent.service.js +44 -14
- package/dist/protocols/job-trace-runner.d.ts +11 -0
- package/dist/protocols/job-trace-runner.js +42 -8
- package/dist/protocols/rpc-observe-agent.service.d.ts +5 -0
- package/dist/protocols/rpc-observe-agent.service.js +43 -3
- package/dist/services/operation-trace.registry.d.ts +46 -3
- package/dist/services/operation-trace.registry.js +69 -13
- 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 +39 -2
- package/dist/utils/opentelemetry.util.d.ts +57 -0
- package/dist/utils/opentelemetry.util.js +100 -0
- package/dist/utils/trace-context.util.d.ts +91 -0
- package/dist/utils/trace-context.util.js +219 -0
- package/dist/utils/trace-handoff.util.d.ts +45 -0
- package/dist/utils/trace-handoff.util.js +90 -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/package.json +26 -13
|
@@ -7,6 +7,7 @@ import { OngoingTraceEventNode } from "../interfaces/trace-events.interfaces.js"
|
|
|
7
7
|
import { TraceSpanDelegate } from "../trace-span.delegate.js";
|
|
8
8
|
import { KeyOf } from "../types/key-of.type.js";
|
|
9
9
|
import { LogRedactor } from "../utils/log-redactor.js";
|
|
10
|
+
import type { TraceContext } from "../utils/trace-context.util.js";
|
|
10
11
|
import { CALLER_METADATA_KEY } from "../observe.constants.js";
|
|
11
12
|
import { SpanCollapseSettings } from "./collapse-repeated-spans.util.js";
|
|
12
13
|
import { SkipSpansPredicate } from "./skip-spans.util.js";
|
|
@@ -59,6 +60,16 @@ export declare class OperationTraceRegistry {
|
|
|
59
60
|
* switched off explicitly.
|
|
60
61
|
*/
|
|
61
62
|
private redactor;
|
|
63
|
+
/**
|
|
64
|
+
* The W3C trace context each operation arrived with, by snapshot.
|
|
65
|
+
*
|
|
66
|
+
* Beside the snapshot rather than on it: both encoders map every key a
|
|
67
|
+
* snapshot has onto the wire, and the collector refuses a batch carrying a
|
|
68
|
+
* key it does not know. The snapshot object `startTrace` builds is the one
|
|
69
|
+
* `pluckSnapshot` hands out, so whoever receives it can still look its
|
|
70
|
+
* context up - and the entry goes when the snapshot does.
|
|
71
|
+
*/
|
|
72
|
+
private readonly traceContexts;
|
|
62
73
|
constructor(als: AsyncLocalStorage<Map<KeyOf<{
|
|
63
74
|
[CALLER_METADATA_KEY]: string;
|
|
64
75
|
}>, unknown>>, sourceContext?: CreateObserveModuleOptions["sourceContext"]);
|
|
@@ -108,7 +119,14 @@ export declare class OperationTraceRegistry {
|
|
|
108
119
|
* The trace id the snapshot reports under, when it is not the registry
|
|
109
120
|
* key - a job inheriting the id of the operation that enqueued it.
|
|
110
121
|
*/
|
|
111
|
-
reportedTraceId?: string
|
|
122
|
+
reportedTraceId?: string,
|
|
123
|
+
/** The `traceparent` the operation arrived with, when it had one. */
|
|
124
|
+
traceContext?: TraceContext): void;
|
|
125
|
+
/**
|
|
126
|
+
* The `traceparent` a snapshot's operation arrived with, if it had one -
|
|
127
|
+
* for the exporter, which puts the operation under the caller's span.
|
|
128
|
+
*/
|
|
129
|
+
traceContextOf(snapshot: object): TraceContext | undefined;
|
|
112
130
|
endTrace(traceId: string): void;
|
|
113
131
|
endTrace(traceId: string, opts?: {
|
|
114
132
|
statusCode?: number;
|
|
@@ -135,7 +153,12 @@ export declare class OperationTraceRegistry {
|
|
|
135
153
|
*/
|
|
136
154
|
private toErrorStatusCode;
|
|
137
155
|
private setStatusCode;
|
|
138
|
-
internalStartTraceStep(traceId: TraceId, className: string, methodKey: string, callerId: string | undefined
|
|
156
|
+
internalStartTraceStep(traceId: TraceId, className: string, methodKey: string, callerId: string | undefined,
|
|
157
|
+
/**
|
|
158
|
+
* An id minted ahead of the span - by an outbound call that had to name
|
|
159
|
+
* its span in a `traceparent` before the span could be opened.
|
|
160
|
+
*/
|
|
161
|
+
spanId?: string): string | undefined;
|
|
139
162
|
/**
|
|
140
163
|
* Nests a freshly opened node under its caller when that caller is still
|
|
141
164
|
* live, and at the trace root otherwise.
|
|
@@ -192,7 +215,23 @@ export declare class OperationTraceRegistry {
|
|
|
192
215
|
* async call) would otherwise lose its offset entirely.
|
|
193
216
|
*/
|
|
194
217
|
private toStartOffset;
|
|
195
|
-
captureError(traceId: string, callerId: string | undefined, error: Error | string, tags: Record<string, string | number | boolean
|
|
218
|
+
captureError(traceId: string, callerId: string | undefined, error: Error | string, tags: Record<string, string | number | boolean>,
|
|
219
|
+
/**
|
|
220
|
+
* The trace id the warnings below name, when it is not the registry key:
|
|
221
|
+
* the one the operation's logs carry. The key itself appears nowhere a
|
|
222
|
+
* reader could look it up.
|
|
223
|
+
*/
|
|
224
|
+
reportedTraceId?: string): void;
|
|
225
|
+
/**
|
|
226
|
+
* Reports the trace even if it ends with no span recorded under it.
|
|
227
|
+
*
|
|
228
|
+
* `endTrace` drops such a trace, as a request no handler ran for. A CORS
|
|
229
|
+
* preflight that `http.tracePreflights` asked for is the one operation that
|
|
230
|
+
* is complete without a handler: the CORS layer answers it before any
|
|
231
|
+
* route, and - on Fastify from `@nestjs/platform-fastify` 12.1.3 - before
|
|
232
|
+
* any middleware that could record a span for it.
|
|
233
|
+
*/
|
|
234
|
+
keepWithoutSpans(traceId: TraceId): void;
|
|
196
235
|
/**
|
|
197
236
|
* Drops a trace that will never be plucked, freeing both maps.
|
|
198
237
|
*
|
|
@@ -227,6 +266,10 @@ export declare class OperationTraceRegistry {
|
|
|
227
266
|
* One line per trace `pluckSnapshot` ships without its open spans, naming
|
|
228
267
|
* them. Their late ends are silent: one un-awaited call usually holds a
|
|
229
268
|
* whole chain of spans open, and a line per span said the same thing N times.
|
|
269
|
+
*
|
|
270
|
+
* The line names the trace id the snapshot reports under, which the
|
|
271
|
+
* operation's logs and its trace carry too - not the registry key, which
|
|
272
|
+
* appears nowhere a reader could look it up.
|
|
230
273
|
*/
|
|
231
274
|
private reportUnfinishedSpans;
|
|
232
275
|
/**
|
|
@@ -126,6 +126,16 @@ export class OperationTraceRegistry {
|
|
|
126
126
|
* switched off explicitly.
|
|
127
127
|
*/
|
|
128
128
|
redactor = new LogRedactor();
|
|
129
|
+
/**
|
|
130
|
+
* The W3C trace context each operation arrived with, by snapshot.
|
|
131
|
+
*
|
|
132
|
+
* Beside the snapshot rather than on it: both encoders map every key a
|
|
133
|
+
* snapshot has onto the wire, and the collector refuses a batch carrying a
|
|
134
|
+
* key it does not know. The snapshot object `startTrace` builds is the one
|
|
135
|
+
* `pluckSnapshot` hands out, so whoever receives it can still look its
|
|
136
|
+
* context up - and the entry goes when the snapshot does.
|
|
137
|
+
*/
|
|
138
|
+
traceContexts = new WeakMap();
|
|
129
139
|
constructor(als, sourceContext = true) {
|
|
130
140
|
this.als = als;
|
|
131
141
|
this.sourceContext = sourceContext;
|
|
@@ -229,7 +239,9 @@ export class OperationTraceRegistry {
|
|
|
229
239
|
* The trace id the snapshot reports under, when it is not the registry
|
|
230
240
|
* key - a job inheriting the id of the operation that enqueued it.
|
|
231
241
|
*/
|
|
232
|
-
reportedTraceId = traceId
|
|
242
|
+
reportedTraceId = traceId,
|
|
243
|
+
/** The `traceparent` the operation arrived with, when it had one. */
|
|
244
|
+
traceContext) {
|
|
233
245
|
if (this.traceSnapshots.has(traceId)) {
|
|
234
246
|
this.logger.warn(`Trace already started for traceId: "${traceId}". Overwriting existing trace.`);
|
|
235
247
|
this.traceSnapshots.delete(traceId);
|
|
@@ -245,6 +257,16 @@ export class OperationTraceRegistry {
|
|
|
245
257
|
refsMarkedAsComplete: 0,
|
|
246
258
|
};
|
|
247
259
|
this.traceSnapshots.set(traceId, snapshot);
|
|
260
|
+
if (traceContext) {
|
|
261
|
+
this.traceContexts.set(snapshot, traceContext);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* The `traceparent` a snapshot's operation arrived with, if it had one -
|
|
266
|
+
* for the exporter, which puts the operation under the caller's span.
|
|
267
|
+
*/
|
|
268
|
+
traceContextOf(snapshot) {
|
|
269
|
+
return this.traceContexts.get(snapshot);
|
|
248
270
|
}
|
|
249
271
|
endTrace(traceId, opts = {}) {
|
|
250
272
|
const snapshot = this.traceSnapshots.get(traceId);
|
|
@@ -262,9 +284,12 @@ export class OperationTraceRegistry {
|
|
|
262
284
|
return;
|
|
263
285
|
}
|
|
264
286
|
// Ignore snapshots that have no traces as that means
|
|
265
|
-
// the request didnt even have a handler in the first place
|
|
266
|
-
|
|
267
|
-
|
|
287
|
+
// the request didnt even have a handler in the first place - unless
|
|
288
|
+
// the transport said the operation is complete without one.
|
|
289
|
+
if (!snapshot.keptWithoutSpans) {
|
|
290
|
+
this.traceSnapshots.delete(traceId);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
268
293
|
}
|
|
269
294
|
// Set by `startTrace` and deleted a few lines below, so it is always there
|
|
270
295
|
// for a snapshot still in the registry. The fallback keeps a duration of 0
|
|
@@ -372,13 +397,18 @@ export class OperationTraceRegistry {
|
|
|
372
397
|
}
|
|
373
398
|
requestSnapshot.attributes.statusCode = statusCode;
|
|
374
399
|
}
|
|
375
|
-
internalStartTraceStep(traceId, className, methodKey, callerId
|
|
400
|
+
internalStartTraceStep(traceId, className, methodKey, callerId,
|
|
401
|
+
/**
|
|
402
|
+
* An id minted ahead of the span - by an outbound call that had to name
|
|
403
|
+
* its span in a `traceparent` before the span could be opened.
|
|
404
|
+
*/
|
|
405
|
+
spanId) {
|
|
376
406
|
const snapshot = this.traceSnapshots.get(traceId);
|
|
377
407
|
if (!snapshot) {
|
|
378
408
|
return undefined;
|
|
379
409
|
}
|
|
380
410
|
snapshot.refsCounter += 1;
|
|
381
|
-
const newNodeId = uuidv7();
|
|
411
|
+
const newNodeId = spanId ?? uuidv7();
|
|
382
412
|
const startTime = performance.now();
|
|
383
413
|
// Records which span owns the thread from here. A no-op unless continuous
|
|
384
414
|
// profiling is on, and the only way profile samples can be attributed to a
|
|
@@ -571,20 +601,26 @@ export class OperationTraceRegistry {
|
|
|
571
601
|
}
|
|
572
602
|
return startTime - snapshot.startTimestamp;
|
|
573
603
|
}
|
|
574
|
-
captureError(traceId, callerId, error, tags
|
|
604
|
+
captureError(traceId, callerId, error, tags,
|
|
605
|
+
/**
|
|
606
|
+
* The trace id the warnings below name, when it is not the registry key:
|
|
607
|
+
* the one the operation's logs carry. The key itself appears nowhere a
|
|
608
|
+
* reader could look it up.
|
|
609
|
+
*/
|
|
610
|
+
reportedTraceId = traceId) {
|
|
575
611
|
const snapshot = this.traceSnapshots.get(traceId);
|
|
576
612
|
if (!snapshot) {
|
|
577
|
-
this.logger.warn(`No request snapshot found for traceId: "${
|
|
613
|
+
this.logger.warn(`No request snapshot found for traceId: "${reportedTraceId}". Cannot capture error.`);
|
|
578
614
|
return;
|
|
579
615
|
}
|
|
580
616
|
if (!snapshot.traces || snapshot.traces.length === 0) {
|
|
581
|
-
this.logger.warn(`No traces found for traceId: "${
|
|
617
|
+
this.logger.warn(`No traces found for traceId: "${reportedTraceId}". Cannot capture error.`);
|
|
582
618
|
return;
|
|
583
619
|
}
|
|
584
620
|
const refsByCaller = this.callerIdsByTraceId.get(traceId);
|
|
585
621
|
const targetSpan = refsByCaller?.get(callerId);
|
|
586
622
|
if (!targetSpan) {
|
|
587
|
-
this.logger.warn(`No active span found for traceId: "${
|
|
623
|
+
this.logger.warn(`No active span found for traceId: "${reportedTraceId}". Cannot capture error.`);
|
|
588
624
|
return;
|
|
589
625
|
}
|
|
590
626
|
if (!targetSpan.tags) {
|
|
@@ -594,6 +630,21 @@ export class OperationTraceRegistry {
|
|
|
594
630
|
Object.assign(targetSpan.tags, tags);
|
|
595
631
|
targetSpan.error = this.toErrorPayload(error);
|
|
596
632
|
}
|
|
633
|
+
/**
|
|
634
|
+
* Reports the trace even if it ends with no span recorded under it.
|
|
635
|
+
*
|
|
636
|
+
* `endTrace` drops such a trace, as a request no handler ran for. A CORS
|
|
637
|
+
* preflight that `http.tracePreflights` asked for is the one operation that
|
|
638
|
+
* is complete without a handler: the CORS layer answers it before any
|
|
639
|
+
* route, and - on Fastify from `@nestjs/platform-fastify` 12.1.3 - before
|
|
640
|
+
* any middleware that could record a span for it.
|
|
641
|
+
*/
|
|
642
|
+
keepWithoutSpans(traceId) {
|
|
643
|
+
const snapshot = this.traceSnapshots.get(traceId);
|
|
644
|
+
if (snapshot) {
|
|
645
|
+
snapshot.keptWithoutSpans = true;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
597
648
|
/**
|
|
598
649
|
* Drops a trace that will never be plucked, freeing both maps.
|
|
599
650
|
*
|
|
@@ -642,7 +693,7 @@ export class OperationTraceRegistry {
|
|
|
642
693
|
}
|
|
643
694
|
}
|
|
644
695
|
cleanup();
|
|
645
|
-
// These
|
|
696
|
+
// These five are what distinguish the registry's working copy from the
|
|
646
697
|
// snapshot the API receives, so removing them is the hand-off.
|
|
647
698
|
const bookkeeping = snapshot;
|
|
648
699
|
const customOperationId = bookkeeping.customOperationId;
|
|
@@ -650,6 +701,7 @@ export class OperationTraceRegistry {
|
|
|
650
701
|
delete bookkeeping.refsMarkedAsComplete;
|
|
651
702
|
delete bookkeeping.errorStatusCode;
|
|
652
703
|
delete bookkeeping.customOperationId;
|
|
704
|
+
delete bookkeeping.keptWithoutSpans;
|
|
653
705
|
// Before `skipSpans`, which judges the operation by the name it is
|
|
654
706
|
// reported under.
|
|
655
707
|
if (customOperationId !== undefined && "protocol" in snapshot) {
|
|
@@ -714,6 +766,10 @@ export class OperationTraceRegistry {
|
|
|
714
766
|
* One line per trace `pluckSnapshot` ships without its open spans, naming
|
|
715
767
|
* them. Their late ends are silent: one un-awaited call usually holds a
|
|
716
768
|
* whole chain of spans open, and a line per span said the same thing N times.
|
|
769
|
+
*
|
|
770
|
+
* The line names the trace id the snapshot reports under, which the
|
|
771
|
+
* operation's logs and its trace carry too - not the registry key, which
|
|
772
|
+
* appears nowhere a reader could look it up.
|
|
717
773
|
*/
|
|
718
774
|
reportUnfinishedSpans(traceId, snapshot) {
|
|
719
775
|
const open = [];
|
|
@@ -724,8 +780,8 @@ export class OperationTraceRegistry {
|
|
|
724
780
|
}
|
|
725
781
|
const operation = ("operationId" in snapshot && snapshot.operationId) ||
|
|
726
782
|
("name" in snapshot && snapshot.name) ||
|
|
727
|
-
traceId;
|
|
728
|
-
this.logger.warn(`Trace "${traceId}" (${operation}) was reported without ${open.join(", ") || "a span"}, which had not ended ${SNAPSHOT_COMPLETION_TIMEOUT_MS}ms after the operation did. Some of your async operations were not awaited and outlived the operation that started them. Ignore if this is the desired behavior.`);
|
|
783
|
+
snapshot.traceId;
|
|
784
|
+
this.logger.warn(`Trace "${snapshot.traceId}" (${operation}) was reported without ${open.join(", ") || "a span"}, which had not ended ${SNAPSHOT_COMPLETION_TIMEOUT_MS}ms after the operation did. Some of your async operations were not awaited and outlived the operation that started them. Ignore if this is the desired behavior.`);
|
|
729
785
|
}
|
|
730
786
|
/**
|
|
731
787
|
* Whether `skipSpans` claims a finished operation. Only request snapshots
|
|
@@ -153,6 +153,12 @@ export declare class TracerService<Store extends object = Record<string | symbol
|
|
|
153
153
|
* methods with no async context at all - and is reported the same way.
|
|
154
154
|
*/
|
|
155
155
|
private requireTraceId;
|
|
156
|
+
/**
|
|
157
|
+
* The trace id a message names: the one the operation's logs and
|
|
158
|
+
* `currentTraceId()` carry, rather than the registry key its trace is kept
|
|
159
|
+
* under, which a reader has no way to look up.
|
|
160
|
+
*/
|
|
161
|
+
private reportedTraceId;
|
|
156
162
|
private registerCounterChangeHandler;
|
|
157
163
|
private registerGaugeChangeHandler;
|
|
158
164
|
private registerSummaryChangeHandler;
|
|
@@ -81,7 +81,7 @@ let TracerService = TracerService_1 = class TracerService {
|
|
|
81
81
|
return new TraceSpanDelegate("", undefined, {});
|
|
82
82
|
}
|
|
83
83
|
if (!activeOngoingEvent) {
|
|
84
|
-
throw new Error(`No active span found for traceId: ${traceId}. Ensure that a span is created before calling "activeSpan".`);
|
|
84
|
+
throw new Error(`No active span found for traceId: ${this.reportedTraceId(store, traceId)}. Ensure that a span is created before calling "activeSpan".`);
|
|
85
85
|
}
|
|
86
86
|
let tags = activeOngoingEvent.tags;
|
|
87
87
|
if (!tags) {
|
|
@@ -116,7 +116,7 @@ let TracerService = TracerService_1 = class TracerService {
|
|
|
116
116
|
return;
|
|
117
117
|
}
|
|
118
118
|
const callerId = store.get(CALLER_METADATA_KEY);
|
|
119
|
-
this.operationTraceRegistry.captureError(traceId, callerId, error, tags ?? {});
|
|
119
|
+
this.operationTraceRegistry.captureError(traceId, callerId, error, tags ?? {}, this.reportedTraceId(store, traceId));
|
|
120
120
|
}
|
|
121
121
|
counter(name, attributes) {
|
|
122
122
|
const existingRef = this.counters.get(name);
|
|
@@ -279,6 +279,15 @@ let TracerService = TracerService_1 = class TracerService {
|
|
|
279
279
|
}
|
|
280
280
|
return traceId;
|
|
281
281
|
}
|
|
282
|
+
/**
|
|
283
|
+
* The trace id a message names: the one the operation's logs and
|
|
284
|
+
* `currentTraceId()` carry, rather than the registry key its trace is kept
|
|
285
|
+
* under, which a reader has no way to look up.
|
|
286
|
+
*/
|
|
287
|
+
reportedTraceId(store, registryKey) {
|
|
288
|
+
const traceId = store.get(this.options.traceIdKey);
|
|
289
|
+
return typeof traceId === "string" ? traceId : registryKey;
|
|
290
|
+
}
|
|
282
291
|
registerCounterChangeHandler(counter) {
|
|
283
292
|
counter["_onChange"] = (self) => {
|
|
284
293
|
this.observeAgentSharedBuffer.upsertCustomMetric(self);
|
|
@@ -11,3 +11,21 @@
|
|
|
11
11
|
*/
|
|
12
12
|
export declare const REQUEST_ID_PATTERN: RegExp;
|
|
13
13
|
export declare function defaultTraceIdGenerator(req: unknown): string;
|
|
14
|
+
/**
|
|
15
|
+
* The default `traceIdGenerator` with `openTelemetry` on.
|
|
16
|
+
*
|
|
17
|
+
* A request in a W3C trace is named after that trace, so it has the id the
|
|
18
|
+
* rest of the trace has in the caller's OpenTelemetry backend: the trace a
|
|
19
|
+
* caller's `traceparent` names - a service in another language, a mesh, a
|
|
20
|
+
* load balancer that starts traces - or, when an OpenTelemetry SDK runs in
|
|
21
|
+
* this process, the one it continued or started for the request (see
|
|
22
|
+
* `inboundTraceContext`). Anything else is named as `defaultTraceIdGenerator`
|
|
23
|
+
* names it.
|
|
24
|
+
*
|
|
25
|
+
* An `x-request-id` beside the trace names some other one when a mesh or a
|
|
26
|
+
* router stamped it (Envoy and Heroku's router stamp every request), and gives
|
|
27
|
+
* way. It stays only when it names this same trace: another service running
|
|
28
|
+
* this agent sends both, and its id may be one `traceparent` cannot carry - a
|
|
29
|
+
* custom id, or a UUIDv7 whose mint time the collector reads.
|
|
30
|
+
*/
|
|
31
|
+
export declare function openTelemetryTraceIdGenerator(req: unknown): string;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { inboundTraceId, w3cTraceIdOf } from "./trace-context.util.js";
|
|
1
2
|
import { uuidv7 } from "./uuid-v7.util.js";
|
|
2
3
|
/**
|
|
3
4
|
* What an inbound `x-request-id` must look like to be adopted as the trace id.
|
|
@@ -19,8 +20,12 @@ export function defaultTraceIdGenerator(req) {
|
|
|
19
20
|
}
|
|
20
21
|
}
|
|
21
22
|
// A microservice context, on a transport whose packets carry metadata: the
|
|
22
|
-
// id the calling service's client attached.
|
|
23
|
-
//
|
|
23
|
+
// id the calling service's client attached. TCP and Redis carry it inside
|
|
24
|
+
// the packet, from @nestjs/microservices 12.0.4. NATS, Kafka, RabbitMQ,
|
|
25
|
+
// MQTT 5 and gRPC carry it as a header, from 12.3.3 (nestjs/nest#18386),
|
|
26
|
+
// which gave their contexts - and the context gRPC hands the processing
|
|
27
|
+
// hooks - the same `getMetadata()`. Held to the same shape as the header - a
|
|
28
|
+
// packet is no more trustworthy than a request.
|
|
24
29
|
const getMetadata = req?.getMetadata;
|
|
25
30
|
if (typeof getMetadata === "function") {
|
|
26
31
|
const metadata = getMetadata.call(req);
|
|
@@ -32,3 +37,35 @@ export function defaultTraceIdGenerator(req) {
|
|
|
32
37
|
// Minted here, so it can carry its time - see uuidv7.
|
|
33
38
|
return uuidv7();
|
|
34
39
|
}
|
|
40
|
+
/**
|
|
41
|
+
* The default `traceIdGenerator` with `openTelemetry` on.
|
|
42
|
+
*
|
|
43
|
+
* A request in a W3C trace is named after that trace, so it has the id the
|
|
44
|
+
* rest of the trace has in the caller's OpenTelemetry backend: the trace a
|
|
45
|
+
* caller's `traceparent` names - a service in another language, a mesh, a
|
|
46
|
+
* load balancer that starts traces - or, when an OpenTelemetry SDK runs in
|
|
47
|
+
* this process, the one it continued or started for the request (see
|
|
48
|
+
* `inboundTraceContext`). Anything else is named as `defaultTraceIdGenerator`
|
|
49
|
+
* names it.
|
|
50
|
+
*
|
|
51
|
+
* An `x-request-id` beside the trace names some other one when a mesh or a
|
|
52
|
+
* router stamped it (Envoy and Heroku's router stamp every request), and gives
|
|
53
|
+
* way. It stays only when it names this same trace: another service running
|
|
54
|
+
* this agent sends both, and its id may be one `traceparent` cannot carry - a
|
|
55
|
+
* custom id, or a UUIDv7 whose mint time the collector reads.
|
|
56
|
+
*/
|
|
57
|
+
export function openTelemetryTraceIdGenerator(req) {
|
|
58
|
+
if (typeof req === "object" && req !== null && "headers" in req) {
|
|
59
|
+
const headers = req.headers;
|
|
60
|
+
const fromTraceContext = inboundTraceId(headers);
|
|
61
|
+
if (fromTraceContext) {
|
|
62
|
+
const requestId = headers?.["x-request-id"];
|
|
63
|
+
return typeof requestId === "string" &&
|
|
64
|
+
REQUEST_ID_PATTERN.test(requestId) &&
|
|
65
|
+
w3cTraceIdOf(requestId) === w3cTraceIdOf(fromTraceContext)
|
|
66
|
+
? requestId
|
|
67
|
+
: fromTraceContext;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return defaultTraceIdGenerator(req);
|
|
71
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A span's identity as `@opentelemetry/api` hands it out - the slice of
|
|
3
|
+
* `SpanContext` the agent reads.
|
|
4
|
+
*/
|
|
5
|
+
export interface OpenTelemetrySpanContext {
|
|
6
|
+
traceId: string;
|
|
7
|
+
spanId: string;
|
|
8
|
+
traceFlags: number;
|
|
9
|
+
traceState?: {
|
|
10
|
+
serialize(): string;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A span in another process, or in the operation that handed this work on,
|
|
15
|
+
* for an OpenTelemetry SDK here to continue - what its propagator reads off
|
|
16
|
+
* a `traceparent`.
|
|
17
|
+
*/
|
|
18
|
+
export interface RemoteParent {
|
|
19
|
+
/** 32 lowercase hex digits. */
|
|
20
|
+
traceId: string;
|
|
21
|
+
/** 16 lowercase hex digits. */
|
|
22
|
+
spanId: string;
|
|
23
|
+
sampled: boolean;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The span an OpenTelemetry SDK in this process has open in the current
|
|
27
|
+
* context - for an incoming request, the server span its HTTP instrumentation
|
|
28
|
+
* opened - or `undefined` when none runs.
|
|
29
|
+
*
|
|
30
|
+
* Read so that a service running both reports to Observe under the trace id
|
|
31
|
+
* the SDK gave the request, including when the request started the trace.
|
|
32
|
+
* Never throws: an SDK this cannot read is treated as absent.
|
|
33
|
+
*/
|
|
34
|
+
export declare function activeOpenTelemetrySpanContext(): OpenTelemetrySpanContext | undefined;
|
|
35
|
+
/**
|
|
36
|
+
* Whether an OpenTelemetry SDK in this process propagates W3C Trace Context,
|
|
37
|
+
* and so writes `traceparent` on the outbound calls it instruments.
|
|
38
|
+
*
|
|
39
|
+
* The agent then leaves the header to it, whichever of the two sees a call
|
|
40
|
+
* first: two `traceparent` headers on one request are not a valid one, and
|
|
41
|
+
* the SDK's names the span the rest of its trace nests under.
|
|
42
|
+
*/
|
|
43
|
+
export declare function openTelemetryWritesTraceparent(): boolean;
|
|
44
|
+
/**
|
|
45
|
+
* Runs `run` with `parent` as the span an OpenTelemetry SDK in this process
|
|
46
|
+
* continues, as its propagator continues a `traceparent` read off an
|
|
47
|
+
* incoming request: the spans its instrumentations open inside `run` join
|
|
48
|
+
* `parent`'s trace, under it, and the calls they cover carry that trace on.
|
|
49
|
+
*
|
|
50
|
+
* For work that reaches this process by a way no OpenTelemetry
|
|
51
|
+
* instrumentation covers - a queue job, a microservice message - and that
|
|
52
|
+
* would otherwise run in no trace at all. Without `@opentelemetry/api`, or
|
|
53
|
+
* with no SDK registered on it, `run` just runs. Never the reason `run`
|
|
54
|
+
* fails: an API this cannot use is treated as absent, and what `run` itself
|
|
55
|
+
* throws is thrown as it is.
|
|
56
|
+
*/
|
|
57
|
+
export declare function withRemoteOpenTelemetryParent<T>(parent: RemoteParent, run: () => T): T;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { loadOptionalPeer } from "./optional-peer.util.js";
|
|
2
|
+
/** `undefined` until first asked for, `null` when the package is absent. */
|
|
3
|
+
let api;
|
|
4
|
+
/**
|
|
5
|
+
* `@opentelemetry/api`, as the application installed it, or `null`.
|
|
6
|
+
*
|
|
7
|
+
* Any copy will do: every copy of the package keeps its state on one global,
|
|
8
|
+
* so the one resolved from here sees the SDK the application registered
|
|
9
|
+
* through its own. With the package installed and no SDK registered, it
|
|
10
|
+
* answers as a no-op - no active span, no propagated fields - which is the
|
|
11
|
+
* agent's own behaviour anyway.
|
|
12
|
+
*/
|
|
13
|
+
function openTelemetryApi() {
|
|
14
|
+
if (api === undefined) {
|
|
15
|
+
const loaded = loadOptionalPeer("@opentelemetry/api");
|
|
16
|
+
api = (loaded.installed && loaded.module) || null;
|
|
17
|
+
}
|
|
18
|
+
return api;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The span an OpenTelemetry SDK in this process has open in the current
|
|
22
|
+
* context - for an incoming request, the server span its HTTP instrumentation
|
|
23
|
+
* opened - or `undefined` when none runs.
|
|
24
|
+
*
|
|
25
|
+
* Read so that a service running both reports to Observe under the trace id
|
|
26
|
+
* the SDK gave the request, including when the request started the trace.
|
|
27
|
+
* Never throws: an SDK this cannot read is treated as absent.
|
|
28
|
+
*/
|
|
29
|
+
export function activeOpenTelemetrySpanContext() {
|
|
30
|
+
try {
|
|
31
|
+
return openTelemetryApi()?.trace.getActiveSpan()?.spanContext();
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Whether an OpenTelemetry SDK in this process propagates W3C Trace Context,
|
|
39
|
+
* and so writes `traceparent` on the outbound calls it instruments.
|
|
40
|
+
*
|
|
41
|
+
* The agent then leaves the header to it, whichever of the two sees a call
|
|
42
|
+
* first: two `traceparent` headers on one request are not a valid one, and
|
|
43
|
+
* the SDK's names the span the rest of its trace nests under.
|
|
44
|
+
*/
|
|
45
|
+
export function openTelemetryWritesTraceparent() {
|
|
46
|
+
try {
|
|
47
|
+
return (openTelemetryApi()?.propagation.fields().includes("traceparent") ?? false);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Runs `run` with `parent` as the span an OpenTelemetry SDK in this process
|
|
55
|
+
* continues, as its propagator continues a `traceparent` read off an
|
|
56
|
+
* incoming request: the spans its instrumentations open inside `run` join
|
|
57
|
+
* `parent`'s trace, under it, and the calls they cover carry that trace on.
|
|
58
|
+
*
|
|
59
|
+
* For work that reaches this process by a way no OpenTelemetry
|
|
60
|
+
* instrumentation covers - a queue job, a microservice message - and that
|
|
61
|
+
* would otherwise run in no trace at all. Without `@opentelemetry/api`, or
|
|
62
|
+
* with no SDK registered on it, `run` just runs. Never the reason `run`
|
|
63
|
+
* fails: an API this cannot use is treated as absent, and what `run` itself
|
|
64
|
+
* throws is thrown as it is.
|
|
65
|
+
*/
|
|
66
|
+
export function withRemoteOpenTelemetryParent(parent, run) {
|
|
67
|
+
let enter;
|
|
68
|
+
try {
|
|
69
|
+
const otel = openTelemetryApi();
|
|
70
|
+
if (otel) {
|
|
71
|
+
const parentContext = otel.trace.setSpanContext(otel.context.active(), {
|
|
72
|
+
traceId: parent.traceId,
|
|
73
|
+
spanId: parent.spanId,
|
|
74
|
+
traceFlags: parent.sampled ? 0x01 : 0x00,
|
|
75
|
+
isRemote: true,
|
|
76
|
+
});
|
|
77
|
+
enter = (fn) => otel.context.with(parentContext, fn);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
enter = undefined;
|
|
82
|
+
}
|
|
83
|
+
if (!enter) {
|
|
84
|
+
return run();
|
|
85
|
+
}
|
|
86
|
+
let entered = false;
|
|
87
|
+
try {
|
|
88
|
+
return enter(() => {
|
|
89
|
+
entered = true;
|
|
90
|
+
return run();
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
if (entered) {
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
// The SDK's context manager failed before `run` started.
|
|
98
|
+
return run();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* W3C Trace Context (https://www.w3.org/TR/trace-context/): the `traceparent`
|
|
3
|
+
* and `tracestate` headers every OpenTelemetry SDK, most proxies and meshes,
|
|
4
|
+
* and the major clouds' load balancers read and write.
|
|
5
|
+
*
|
|
6
|
+
* Observe's own propagation is `x-request-id`, which only another service
|
|
7
|
+
* running this agent understands. Speaking `traceparent` as well is what
|
|
8
|
+
* lets a call through a Go, Python or Java service - or an OpenTelemetry
|
|
9
|
+
* backend reading what `otlp` exports - stay one trace.
|
|
10
|
+
*/
|
|
11
|
+
export interface TraceContext {
|
|
12
|
+
/** 32 lowercase hex digits, never all zeros. */
|
|
13
|
+
traceId: string;
|
|
14
|
+
/**
|
|
15
|
+
* The caller's span, 16 lowercase hex digits: the parent of the span this
|
|
16
|
+
* process opens for the operation.
|
|
17
|
+
*/
|
|
18
|
+
parentSpanId: string;
|
|
19
|
+
/** The caller's `sampled` flag: whether it may be recording the trace. */
|
|
20
|
+
sampled: boolean;
|
|
21
|
+
/**
|
|
22
|
+
* `tracestate`, as received with it. Vendors keep their own entries there,
|
|
23
|
+
* and the spec asks every hop to pass the list on.
|
|
24
|
+
*/
|
|
25
|
+
traceState?: string;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The trace context a request arrived with, or `undefined` when it carried
|
|
29
|
+
* no `traceparent` the spec would accept.
|
|
30
|
+
*
|
|
31
|
+
* Headers are client-supplied, so anything malformed is ignored rather than
|
|
32
|
+
* repaired - an array (a repeated header), the wrong case, a zero id. The
|
|
33
|
+
* spec's answer to an invalid `traceparent` is to start a new trace, and its
|
|
34
|
+
* `tracestate` goes with it.
|
|
35
|
+
*/
|
|
36
|
+
export declare function readTraceContext(headers: Record<string, unknown> | undefined): TraceContext | undefined;
|
|
37
|
+
/**
|
|
38
|
+
* The trace id a `traceparent` header carries, written as a UUID - the
|
|
39
|
+
* shape of every id this agent mints - or `undefined` when it carries none
|
|
40
|
+
* the spec would accept.
|
|
41
|
+
*
|
|
42
|
+
* Written that way rather than as 32 bare digits so the id reads the same
|
|
43
|
+
* in the dashboard, in logs and in `currentTraceId()` whichever side minted
|
|
44
|
+
* it, and so `w3cTraceIdOf` turns it back into exactly the trace id the
|
|
45
|
+
* caller sent.
|
|
46
|
+
*/
|
|
47
|
+
export declare function traceIdFromTraceparent(headers: Record<string, unknown> | undefined): string | undefined;
|
|
48
|
+
/**
|
|
49
|
+
* The W3C trace context an operation runs in: the span an OpenTelemetry SDK
|
|
50
|
+
* in this process opened for it, when one runs, else the `traceparent` it
|
|
51
|
+
* arrived with.
|
|
52
|
+
*
|
|
53
|
+
* The SDK's span first, because the SDK has already decided the trace: it
|
|
54
|
+
* continued the caller's, through whichever propagator it was given, or
|
|
55
|
+
* started one when there was nothing to continue. Taking that decision is
|
|
56
|
+
* what makes a service running both report one trace id to both, the
|
|
57
|
+
* service at the root of a trace included.
|
|
58
|
+
*/
|
|
59
|
+
export declare function inboundTraceContext(headers: Record<string, unknown> | undefined): TraceContext | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* `inboundTraceContext`'s trace id, written as a UUID - as
|
|
62
|
+
* `traceIdFromTraceparent` writes it.
|
|
63
|
+
*/
|
|
64
|
+
export declare function inboundTraceId(headers: Record<string, unknown> | undefined): string | undefined;
|
|
65
|
+
/**
|
|
66
|
+
* The W3C trace id an Observe trace id goes out under.
|
|
67
|
+
*
|
|
68
|
+
* Every id the agent mints is a UUID, which is a 128-bit W3C trace id with
|
|
69
|
+
* dashes in it, so those - and any 32-digit hex id - map onto one by
|
|
70
|
+
* dropping the dashes. An adopted `x-request-id` can be anything at all
|
|
71
|
+
* (`req_8f2c`), and becomes the first 128 bits of its SHA-256 instead: the
|
|
72
|
+
* same id always gives the same trace id, so every hop that derives it -
|
|
73
|
+
* this process's outbound calls, another service running this agent, the
|
|
74
|
+
* spans `otlp` exports - lands in one trace.
|
|
75
|
+
*/
|
|
76
|
+
export declare function w3cTraceIdOf(traceId: string): string;
|
|
77
|
+
/**
|
|
78
|
+
* The W3C span id an Observe span id goes out under: the low 64 bits of its
|
|
79
|
+
* UUID.
|
|
80
|
+
*
|
|
81
|
+
* The low half rather than the high one because in a UUIDv7 the high half
|
|
82
|
+
* is mostly the mint time, which every span opened in the same millisecond
|
|
83
|
+
* shares; the low half is 62 random bits under the variant, which also keeps
|
|
84
|
+
* it from ever being all zeros. Anything that is not a UUID is hashed, as
|
|
85
|
+
* `w3cTraceIdOf` does.
|
|
86
|
+
*/
|
|
87
|
+
export declare function w3cSpanIdOf(spanId: string): string;
|
|
88
|
+
/** A fresh W3C span id, for a span that has no Observe id to derive one from. */
|
|
89
|
+
export declare function randomSpanId(): string;
|
|
90
|
+
/** A version-00 `traceparent`. Only the `sampled` flag is ever set. */
|
|
91
|
+
export declare function formatTraceparent(traceId: string, spanId: string, sampled: boolean): string;
|