Line data Source code
1 1 : export const TRACE_ID_KEY = "trace_id";
2 1 : export const SPAN_ID_KEY = "span_id";
3 1 : export const PARENT_SPAN_ID_KEY = "parent_span_id";
4 :
5 : export interface TraceContext {
6 : traceId: number;
7 : spanId: number;
8 : parentSpanId: number | null;
9 : }
10 :
11 1 : let traceCounter = 0;
12 1 : let spanCounter = 0;
13 :
14 1 : export function nextTraceId(): number {
15 1 : return ++traceCounter;
16 1 : }
17 :
18 1 : export function nextSpanId(): number {
19 1 : return ++spanCounter;
20 1 : }
21 :
22 1 : export function createTrace(traceId?: number): TraceContext {
23 1 : return {
24 1 : traceId: traceId ?? nextTraceId(),
25 1 : spanId: nextSpanId(),
26 1 : parentSpanId: null,
27 1 : };
28 1 : }
29 :
30 1 : export function createChildSpan(parent: TraceContext): TraceContext {
31 1 : return {
32 1 : traceId: parent.traceId,
33 1 : spanId: nextSpanId(),
34 1 : parentSpanId: parent.spanId,
35 1 : };
36 1 : }
37 :
38 1 : export function injectTraceContext(
39 1 : keyValues: Record<string, string | null | undefined>,
40 1 : ctx: TraceContext,
41 1 : ): void {
42 1 : keyValues[TRACE_ID_KEY] = ctx.traceId.toString();
43 1 : keyValues[SPAN_ID_KEY] = ctx.spanId.toString();
44 1 : if (ctx.parentSpanId !== null) {
45 1 : keyValues[PARENT_SPAN_ID_KEY] = ctx.parentSpanId.toString();
46 : }
47 1 : }
|