-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathmanager.ts
More file actions
79 lines (61 loc) · 2.13 KB
/
manager.ts
File metadata and controls
79 lines (61 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { Context, context, propagation, trace, TraceFlags } from "@opentelemetry/api";
import { TraceContextManager } from "./types.js";
import { parseTraceParent } from "@opentelemetry/core";
export class StandardTraceContextManager implements TraceContextManager {
public traceContext: Record<string, unknown> = {};
getTraceContext() {
return this.traceContext;
}
reset() {
this.traceContext = {};
}
getExternalTraceContext() {
return extractExternalTraceContext(this.traceContext?.external);
}
extractContext(): Context {
return propagation.extract(context.active(), this.traceContext ?? {});
}
withExternalTrace<T>(fn: () => T): T {
const externalTraceContext = this.getExternalTraceContext();
if (!externalTraceContext) {
return fn();
}
// Get the current active span context to extract the span ID
const currentSpanContext = trace.getActiveSpan()?.spanContext();
if (!currentSpanContext) {
throw new Error(
"No active span found. withExternalSpan must be called within an active span context."
);
}
const spanContext = {
traceId: externalTraceContext.traceId,
spanId: currentSpanContext.spanId,
traceFlags: externalTraceContext.traceFlags,
isRemote: true,
};
const contextWithSpan = trace.setSpanContext(context.active(), spanContext);
return context.with(contextWithSpan, fn);
}
}
function extractExternalTraceContext(traceContext: unknown) {
if (typeof traceContext !== "object" || traceContext === null) {
return undefined;
}
const tracestate =
"tracestate" in traceContext && typeof traceContext.tracestate === "string"
? traceContext.tracestate
: undefined;
if ("traceparent" in traceContext && typeof traceContext.traceparent === "string") {
const externalSpanContext = parseTraceParent(traceContext.traceparent);
if (!externalSpanContext) {
return undefined;
}
return {
traceId: externalSpanContext.traceId,
spanId: externalSpanContext.spanId,
traceFlags: externalSpanContext.traceFlags,
tracestate: tracestate,
};
}
return undefined;
}