-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracer.js
181 lines (153 loc) · 4.73 KB
/
tracer.js
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import { AsyncLocalStorage } from "node:async_hooks";
import crypto from "node:crypto";
class Tracing {
static asyncLocalStorage = new AsyncLocalStorage();
static globalAttributes = new Map();
static name = "";
static exporter = (span) => {};
static getCurrentSpan = () => Tracing.asyncLocalStorage.getStore().span;
static getContext = () => Tracing.asyncLocalStorage.getStore();
static async setContext(ctx, cb, ...args) {
await Tracing.asyncLocalStorage.run(ctx, cb, ...args);
}
static async startSpan(name, lambda) {
let ctx = Tracing.asyncLocalStorage.getStore();
let span = new Span(name, ctx, new Map([["service.name", Tracing.name]]));
await Tracing.setContext(span.getContext(), lambda, span);
span.end();
Tracing.exporter(span);
}
}
const EMPTY_CONTEXT = {};
Tracing.asyncLocalStorage.enterWith(EMPTY_CONTEXT);
class Span {
constructor(name, context = {}, attributes = new Map()) {
this.startTime = new Date().getTime();
this.startTimestampMs = performance.now();
this.traceID = context.traceID ?? crypto.randomBytes(16).toString("hex");
this.parentSpanID = context.spanID ?? undefined;
this.name = name;
this.attributes = attributes;
this.spanID = crypto.randomBytes(8).toString("hex");
}
getContext() {
return { traceID: this.traceID, spanID: this.spanID, span: this };
}
setAttributes(keyValues) {
for (let [key, value] of Object.entries(keyValues)) {
this.attributes.set(key, value);
}
}
end() {
this.durationMs = performance.now() - this.startTimestampMs;
}
}
let getTraceParent = (ctx) => `00-${ctx.traceID}-${ctx.spanID}-01`;
let parseTraceParent = (header) => ({
traceID: header.split("-")[1],
spanID: header.split("-")[2],
});
async function honoMiddleware(c, next) {
let context = EMPTY_CONTEXT;
if (c.req.header("traceparent")) {
context = parseTraceParent(c.req.header("traceparent"));
}
await Tracing.setContext(context, async () => {
await Tracing.startSpan(`${c.req.method} ${c.req.path}`, async (span) => {
span.setAttributes({
"http.request.method": c.req.method,
"http.request.path": c.req.path,
});
await next();
span.setAttributes({
"http.response.status_code": c.res.status,
});
});
});
}
function patchFetch(originalFetch) {
return async function patchedFetch(resource, options = {}) {
let ctx = Tracing.getContext();
if (!options.headers) {
options.headers = {};
}
options.headers["traceparent"] = getTraceParent(ctx);
let resp;
await Tracing.startSpan("fetch", async (span) => {
span.setAttributes({ "http.url": resource });
resp = await originalFetch(resource, options);
span.setAttributes({ "http.response.status_code": resp.status });
});
return resp;
};
}
function toAnyValue(val) {
if (val instanceof Uint8Array) return { bytesValue: value };
if (Array.isArray(val))
return { arrayValue: { values: val.map(toAnyValue) } };
let t = typeof val;
if (t === "string") return { stringValue: val };
if (t === "number") return { doubleValue: val };
if (t === "boolean") return { boolValue: val };
if (t === "object" && val != null)
return {
kvlistValue: {
values: Object.entries(val).map(([k, v]) => toKeyValue(k, v)),
},
};
return {};
}
function toKeyValue(key, val) {
return { key, value: toAnyValue(val) };
}
function toAttributes(attributes) {
return Object.keys(attributes).map((key) => toKeyValue(key, attributes[key]));
}
function spanToOTLP(span) {
return {
resourceSpans: [
{
resource: {
attributes: toAttributes(
Object.fromEntries(Tracing.globalAttributes)
),
},
scopeSpans: [
{
scope: {
name: "minimal-tracer",
version: "0.0.1",
attributes: [],
},
spans: [
{
traceId: span.traceID,
spanId: span.spanID,
parentSpanId: span.parentSpanID,
name: span.name,
startTimeUnixNano: span.startTime * Math.pow(10, 6),
endTimeUnixNano:
(span.startTime + span.durationMs) * Math.pow(10, 6),
kind: 2,
attributes: toAttributes(Object.fromEntries(span.attributes)),
},
],
},
],
},
],
};
}
function otlpExporter(url, headers) {
return function (span) {
fetch(url, {
method: "POST",
headers: {
...headers,
"Content-Type": "application/json",
},
body: JSON.stringify(spanToOTLP(span)),
});
};
}
export { Tracing, Span, honoMiddleware, patchFetch, otlpExporter };