autotel-devtools 0.1.0
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 +156 -0
- package/dist/cli.cjs +889 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +886 -0
- package/dist/cli.js.map +1 -0
- package/dist/error-aggregator-BkO0l8ak.d.ts +147 -0
- package/dist/error-aggregator-CtZmjm-k.d.cts +147 -0
- package/dist/exporter-qIQPDw29.d.cts +159 -0
- package/dist/exporter-qIQPDw29.d.ts +159 -0
- package/dist/index.cjs +1242 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +29 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +1234 -0
- package/dist/index.js.map +1 -0
- package/dist/server/exporter.cjs +154 -0
- package/dist/server/exporter.cjs.map +1 -0
- package/dist/server/exporter.d.cts +4 -0
- package/dist/server/exporter.d.ts +4 -0
- package/dist/server/exporter.js +152 -0
- package/dist/server/exporter.js.map +1 -0
- package/dist/server/index.cjs +1237 -0
- package/dist/server/index.cjs.map +1 -0
- package/dist/server/index.d.cts +38 -0
- package/dist/server/index.d.ts +38 -0
- package/dist/server/index.js +1222 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/log-exporter.cjs +111 -0
- package/dist/server/log-exporter.cjs.map +1 -0
- package/dist/server/log-exporter.d.cts +50 -0
- package/dist/server/log-exporter.d.ts +50 -0
- package/dist/server/log-exporter.js +109 -0
- package/dist/server/log-exporter.js.map +1 -0
- package/dist/server/remote-exporter.cjs +219 -0
- package/dist/server/remote-exporter.cjs.map +1 -0
- package/dist/server/remote-exporter.d.cts +87 -0
- package/dist/server/remote-exporter.d.ts +87 -0
- package/dist/server/remote-exporter.js +217 -0
- package/dist/server/remote-exporter.js.map +1 -0
- package/dist/widget.global.js +2 -0
- package/package.json +96 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1234 @@
|
|
|
1
|
+
import { createServer } from 'http';
|
|
2
|
+
import { WebSocketServer, WebSocket } from 'ws';
|
|
3
|
+
import { readFileSync, existsSync } from 'fs';
|
|
4
|
+
import { resolve, dirname } from 'path';
|
|
5
|
+
import { fileURLToPath } from 'url';
|
|
6
|
+
import { ExportResultCode } from '@opentelemetry/core';
|
|
7
|
+
|
|
8
|
+
// src/index.ts
|
|
9
|
+
|
|
10
|
+
// src/server/error-aggregator.ts
|
|
11
|
+
var ErrorAggregator = class {
|
|
12
|
+
errorGroups = /* @__PURE__ */ new Map();
|
|
13
|
+
options;
|
|
14
|
+
constructor(options = {}) {
|
|
15
|
+
this.options = {
|
|
16
|
+
maxGroups: options.maxGroups ?? 100,
|
|
17
|
+
maxAffectedTraces: options.maxAffectedTraces ?? 10,
|
|
18
|
+
maxAffectedSpans: options.maxAffectedSpans ?? 5,
|
|
19
|
+
stackFramesForFingerprint: options.stackFramesForFingerprint ?? 5
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Add an error occurrence to the aggregator
|
|
24
|
+
*/
|
|
25
|
+
addError(occurrence) {
|
|
26
|
+
const fingerprint = this.generateFingerprint(occurrence);
|
|
27
|
+
const existing = this.errorGroups.get(fingerprint);
|
|
28
|
+
if (existing) {
|
|
29
|
+
existing.count++;
|
|
30
|
+
existing.lastSeen = occurrence.timestamp;
|
|
31
|
+
if (!existing.affectedTraces.includes(occurrence.traceId)) {
|
|
32
|
+
existing.affectedTraces.push(occurrence.traceId);
|
|
33
|
+
if (existing.affectedTraces.length > this.options.maxAffectedTraces) {
|
|
34
|
+
existing.affectedTraces.shift();
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (!existing.affectedSpans.includes(occurrence.spanName)) {
|
|
38
|
+
existing.affectedSpans.push(occurrence.spanName);
|
|
39
|
+
if (existing.affectedSpans.length > this.options.maxAffectedSpans) {
|
|
40
|
+
existing.affectedSpans.shift();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return existing;
|
|
44
|
+
}
|
|
45
|
+
const newGroup = {
|
|
46
|
+
fingerprint,
|
|
47
|
+
type: occurrence.error.type,
|
|
48
|
+
message: occurrence.error.message,
|
|
49
|
+
stackTrace: this.normalizeStackTrace(occurrence.error.stackTrace),
|
|
50
|
+
count: 1,
|
|
51
|
+
firstSeen: occurrence.timestamp,
|
|
52
|
+
lastSeen: occurrence.timestamp,
|
|
53
|
+
affectedTraces: [occurrence.traceId],
|
|
54
|
+
affectedSpans: [occurrence.spanName],
|
|
55
|
+
service: occurrence.service,
|
|
56
|
+
attributes: occurrence.attributes
|
|
57
|
+
};
|
|
58
|
+
if (this.errorGroups.size >= this.options.maxGroups) {
|
|
59
|
+
this.evictOldestGroup();
|
|
60
|
+
}
|
|
61
|
+
this.errorGroups.set(fingerprint, newGroup);
|
|
62
|
+
return newGroup;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Extract errors from a trace and add them to the aggregator
|
|
66
|
+
*/
|
|
67
|
+
addErrorsFromTrace(trace) {
|
|
68
|
+
const addedGroups = [];
|
|
69
|
+
for (const span of trace.spans) {
|
|
70
|
+
if (span.status.code === "ERROR") {
|
|
71
|
+
const occurrence = this.extractErrorFromSpan(span, trace);
|
|
72
|
+
if (occurrence) {
|
|
73
|
+
const group = this.addError(occurrence);
|
|
74
|
+
addedGroups.push(group);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return addedGroups;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Extract error occurrence from a span
|
|
82
|
+
*/
|
|
83
|
+
extractErrorFromSpan(span, trace) {
|
|
84
|
+
const exceptionEvent = span.events?.find((e) => e.name === "exception");
|
|
85
|
+
const errorType = span.attributes["exception.type"] || span.attributes["error.type"] || exceptionEvent?.attributes?.["exception.type"] || "Error";
|
|
86
|
+
const errorMessage = span.status.message || span.attributes["exception.message"] || span.attributes["error.message"] || "Unknown error";
|
|
87
|
+
const stackTrace = span.attributes["exception.stacktrace"] || span.attributes["exception.stack"] || this.extractStackFromEvents(span);
|
|
88
|
+
return {
|
|
89
|
+
traceId: trace.traceId,
|
|
90
|
+
spanId: span.spanId,
|
|
91
|
+
spanName: span.name,
|
|
92
|
+
service: trace.service,
|
|
93
|
+
timestamp: span.endTime,
|
|
94
|
+
error: {
|
|
95
|
+
type: errorType,
|
|
96
|
+
message: errorMessage,
|
|
97
|
+
stackTrace
|
|
98
|
+
},
|
|
99
|
+
attributes: this.extractRelevantAttributes(span.attributes)
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Extract stack trace from span events (exception events)
|
|
104
|
+
*/
|
|
105
|
+
extractStackFromEvents(span) {
|
|
106
|
+
if (!span.events) return void 0;
|
|
107
|
+
const exceptionEvent = span.events.find((e) => e.name === "exception");
|
|
108
|
+
if (exceptionEvent?.attributes) {
|
|
109
|
+
return exceptionEvent.attributes["exception.stacktrace"] || exceptionEvent.attributes["exception.stack"];
|
|
110
|
+
}
|
|
111
|
+
return void 0;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Extract relevant attributes for error context
|
|
115
|
+
*/
|
|
116
|
+
extractRelevantAttributes(attributes) {
|
|
117
|
+
const relevant = {};
|
|
118
|
+
const keepKeys = [
|
|
119
|
+
"http.method",
|
|
120
|
+
"http.url",
|
|
121
|
+
"http.route",
|
|
122
|
+
"http.status_code",
|
|
123
|
+
"db.system",
|
|
124
|
+
"db.operation",
|
|
125
|
+
"rpc.method",
|
|
126
|
+
"rpc.service",
|
|
127
|
+
"code.function",
|
|
128
|
+
"code.filepath",
|
|
129
|
+
"user.id",
|
|
130
|
+
"operation.name"
|
|
131
|
+
];
|
|
132
|
+
for (const key of keepKeys) {
|
|
133
|
+
if (key in attributes) {
|
|
134
|
+
relevant[key] = attributes[key];
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return relevant;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Generate a fingerprint for error grouping
|
|
141
|
+
*
|
|
142
|
+
* Uses error type + first N stack frames (normalized)
|
|
143
|
+
*/
|
|
144
|
+
generateFingerprint(occurrence) {
|
|
145
|
+
const parts = [occurrence.error.type];
|
|
146
|
+
if (occurrence.error.stackTrace) {
|
|
147
|
+
const frames = this.extractStackFrames(
|
|
148
|
+
occurrence.error.stackTrace,
|
|
149
|
+
this.options.stackFramesForFingerprint
|
|
150
|
+
);
|
|
151
|
+
parts.push(...frames);
|
|
152
|
+
} else {
|
|
153
|
+
parts.push(this.normalizeMessage(occurrence.error.message));
|
|
154
|
+
}
|
|
155
|
+
return this.simpleHash(parts.join("|"));
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Extract and normalize stack frames from a stack trace
|
|
159
|
+
*/
|
|
160
|
+
extractStackFrames(stackTrace, count) {
|
|
161
|
+
const lines = stackTrace.split("\n");
|
|
162
|
+
const frames = [];
|
|
163
|
+
for (const line of lines) {
|
|
164
|
+
if (frames.length >= count) break;
|
|
165
|
+
const trimmed = line.trim();
|
|
166
|
+
const nodeMatch = trimmed.match(/^at\s+(.+?)\s+\((.+?):(\d+):\d+\)$/);
|
|
167
|
+
if (nodeMatch) {
|
|
168
|
+
frames.push(`${nodeMatch[1]}@${this.normalizeFilePath(nodeMatch[2])}`);
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
const anonMatch = trimmed.match(/^at\s+(.+?):(\d+):\d+$/);
|
|
172
|
+
if (anonMatch) {
|
|
173
|
+
frames.push(`anonymous@${this.normalizeFilePath(anonMatch[1])}`);
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
const browserMatch = trimmed.match(/^(.+?)@(.+?):(\d+):\d+$/);
|
|
177
|
+
if (browserMatch) {
|
|
178
|
+
frames.push(
|
|
179
|
+
`${browserMatch[1]}@${this.normalizeFilePath(browserMatch[2])}`
|
|
180
|
+
);
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return frames;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Normalize file path by removing absolute path prefixes and node_modules paths
|
|
188
|
+
*/
|
|
189
|
+
normalizeFilePath(filePath) {
|
|
190
|
+
const nodeModulesMatch = filePath.match(
|
|
191
|
+
/node_modules\/(@[^/]+\/[^/]+|[^/]+)/
|
|
192
|
+
);
|
|
193
|
+
if (nodeModulesMatch) {
|
|
194
|
+
return `[npm]/${nodeModulesMatch[1]}`;
|
|
195
|
+
}
|
|
196
|
+
return filePath.replace(/^.*?\/src\//, "src/").replace(/^.*?\/dist\//, "dist/").replace(/^.*?\/lib\//, "lib/").replace(/^file:\/\//, "");
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Normalize error message by removing dynamic parts
|
|
200
|
+
*/
|
|
201
|
+
normalizeMessage(message) {
|
|
202
|
+
return message.replaceAll(
|
|
203
|
+
/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,
|
|
204
|
+
"[UUID]"
|
|
205
|
+
).replaceAll(/\b[0-9a-f]{16,}\b/gi, "[ID]").replaceAll(/\b\d+\b/g, "[N]").replaceAll(/"[^"]*"/g, '"[STR]"').replaceAll(/'[^']*'/g, "'[STR]'").slice(0, 200);
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Normalize stack trace for display
|
|
209
|
+
*/
|
|
210
|
+
normalizeStackTrace(stackTrace) {
|
|
211
|
+
if (!stackTrace) return void 0;
|
|
212
|
+
const lines = stackTrace.split("\n").slice(0, 10);
|
|
213
|
+
return lines.join("\n");
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Simple hash function for fingerprinting
|
|
217
|
+
*/
|
|
218
|
+
simpleHash(str) {
|
|
219
|
+
let hash = 0;
|
|
220
|
+
for (let i = 0; i < str.length; i++) {
|
|
221
|
+
const char = str.charCodeAt(i);
|
|
222
|
+
hash = (hash << 5) - hash + char;
|
|
223
|
+
hash = hash & hash;
|
|
224
|
+
}
|
|
225
|
+
return Math.abs(hash).toString(16).padStart(8, "0");
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Evict the oldest error group
|
|
229
|
+
*/
|
|
230
|
+
evictOldestGroup() {
|
|
231
|
+
let oldest = null;
|
|
232
|
+
for (const [fingerprint, group] of this.errorGroups) {
|
|
233
|
+
if (!oldest || group.lastSeen < oldest.lastSeen) {
|
|
234
|
+
oldest = { fingerprint, lastSeen: group.lastSeen };
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (oldest) {
|
|
238
|
+
this.errorGroups.delete(oldest.fingerprint);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Get all error groups, sorted by most recent
|
|
243
|
+
*/
|
|
244
|
+
getErrorGroups() {
|
|
245
|
+
return [...this.errorGroups.values()].sort(
|
|
246
|
+
(a, b) => b.lastSeen - a.lastSeen
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Get error groups sorted by count (most frequent first)
|
|
251
|
+
*/
|
|
252
|
+
getErrorGroupsByFrequency() {
|
|
253
|
+
return [...this.errorGroups.values()].sort(
|
|
254
|
+
(a, b) => b.count - a.count
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Get a specific error group by fingerprint
|
|
259
|
+
*/
|
|
260
|
+
getErrorGroup(fingerprint) {
|
|
261
|
+
return this.errorGroups.get(fingerprint);
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Get error groups for a specific service
|
|
265
|
+
*/
|
|
266
|
+
getErrorGroupsByService(service) {
|
|
267
|
+
return this.getErrorGroups().filter((g) => g.service === service);
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Get total error count across all groups
|
|
271
|
+
*/
|
|
272
|
+
getTotalErrorCount() {
|
|
273
|
+
let total = 0;
|
|
274
|
+
for (const group of this.errorGroups.values()) {
|
|
275
|
+
total += group.count;
|
|
276
|
+
}
|
|
277
|
+
return total;
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Get error statistics
|
|
281
|
+
*/
|
|
282
|
+
getStats() {
|
|
283
|
+
const now = Date.now();
|
|
284
|
+
const oneHourAgo = now - 60 * 60 * 1e3;
|
|
285
|
+
let recentErrors = 0;
|
|
286
|
+
const typeCount = /* @__PURE__ */ new Map();
|
|
287
|
+
for (const group of this.errorGroups.values()) {
|
|
288
|
+
if (group.lastSeen > oneHourAgo) {
|
|
289
|
+
recentErrors += group.count;
|
|
290
|
+
}
|
|
291
|
+
typeCount.set(group.type, (typeCount.get(group.type) || 0) + group.count);
|
|
292
|
+
}
|
|
293
|
+
const topErrorTypes = [...typeCount.entries()].map(([type, count]) => ({ type, count })).sort((a, b) => b.count - a.count).slice(0, 5);
|
|
294
|
+
return {
|
|
295
|
+
totalGroups: this.errorGroups.size,
|
|
296
|
+
totalErrors: this.getTotalErrorCount(),
|
|
297
|
+
recentErrors,
|
|
298
|
+
topErrorTypes
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Clear all error groups
|
|
303
|
+
*/
|
|
304
|
+
clear() {
|
|
305
|
+
this.errorGroups.clear();
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Clear old error groups (not seen in given time window)
|
|
309
|
+
*/
|
|
310
|
+
clearOlderThan(maxAgeMs) {
|
|
311
|
+
const cutoff = Date.now() - maxAgeMs;
|
|
312
|
+
let cleared = 0;
|
|
313
|
+
for (const [fingerprint, group] of this.errorGroups) {
|
|
314
|
+
if (group.lastSeen < cutoff) {
|
|
315
|
+
this.errorGroups.delete(fingerprint);
|
|
316
|
+
cleared++;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return cleared;
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
// src/server/telemetry-limits.ts
|
|
324
|
+
var defaultLimit = 100;
|
|
325
|
+
function parseLimit(value) {
|
|
326
|
+
if (!value) return void 0;
|
|
327
|
+
const parsed = Number.parseInt(value, 10);
|
|
328
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
|
|
329
|
+
}
|
|
330
|
+
function resolveTelemetryLimits(args = {}) {
|
|
331
|
+
const env = args.env ?? process.env;
|
|
332
|
+
const fallback = args.maxHistory ?? defaultLimit;
|
|
333
|
+
return {
|
|
334
|
+
maxTraceCount: args.maxTraceCount ?? parseLimit(env.AUTOTEL_MAX_TRACE_COUNT) ?? fallback,
|
|
335
|
+
maxLogCount: args.maxLogCount ?? parseLimit(env.AUTOTEL_MAX_LOG_COUNT) ?? fallback,
|
|
336
|
+
maxMetricCount: args.maxMetricCount ?? parseLimit(env.AUTOTEL_MAX_METRIC_COUNT) ?? fallback
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
function appendWithLimit(items, item, limit) {
|
|
340
|
+
if (limit <= 0) return [];
|
|
341
|
+
const next = [...items, item];
|
|
342
|
+
return next.length > limit ? next.slice(next.length - limit) : next;
|
|
343
|
+
}
|
|
344
|
+
function appendManyWithLimit(items, incoming, limit) {
|
|
345
|
+
if (limit <= 0 || incoming.length === 0) return limit <= 0 ? [] : items;
|
|
346
|
+
const next = [...items, ...incoming];
|
|
347
|
+
return next.length > limit ? next.slice(next.length - limit) : next;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// src/server/server.ts
|
|
351
|
+
var DevtoolsServer = class {
|
|
352
|
+
wss;
|
|
353
|
+
clients = /* @__PURE__ */ new Set();
|
|
354
|
+
httpServer;
|
|
355
|
+
traces = [];
|
|
356
|
+
logs = [];
|
|
357
|
+
metrics = [];
|
|
358
|
+
errorAggregator = new ErrorAggregator();
|
|
359
|
+
limits;
|
|
360
|
+
verbose;
|
|
361
|
+
_port;
|
|
362
|
+
constructor(options = {}) {
|
|
363
|
+
this.limits = resolveTelemetryLimits(options);
|
|
364
|
+
this.verbose = options.verbose ?? false;
|
|
365
|
+
this._port = options.port ?? 4318;
|
|
366
|
+
this.httpServer = options.server ?? createServer();
|
|
367
|
+
this.wss = new WebSocketServer({ server: this.httpServer, path: options.path ?? "/ws" });
|
|
368
|
+
this.wss.on("connection", (ws) => {
|
|
369
|
+
this.clients.add(ws);
|
|
370
|
+
this.log(`Client connected (${this.clients.size} total)`);
|
|
371
|
+
const data = this.getCurrentData();
|
|
372
|
+
if (data.traces.length > 0 || data.logs.length > 0 || data.errors.length > 0) {
|
|
373
|
+
ws.send(JSON.stringify(data));
|
|
374
|
+
}
|
|
375
|
+
ws.on("close", () => {
|
|
376
|
+
this.clients.delete(ws);
|
|
377
|
+
this.log(`Client disconnected (${this.clients.size} total)`);
|
|
378
|
+
});
|
|
379
|
+
});
|
|
380
|
+
if (!options.server) {
|
|
381
|
+
this.httpServer.listen(this._port, () => {
|
|
382
|
+
const addr = this.httpServer.address();
|
|
383
|
+
if (addr && typeof addr === "object") this._port = addr.port;
|
|
384
|
+
this.log(`WebSocket server listening on port ${this._port}`);
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
get port() {
|
|
389
|
+
const addr = this.httpServer.address();
|
|
390
|
+
if (addr && typeof addr === "object") return addr.port;
|
|
391
|
+
return this._port;
|
|
392
|
+
}
|
|
393
|
+
get clientCount() {
|
|
394
|
+
return this.clients.size;
|
|
395
|
+
}
|
|
396
|
+
addTrace(trace) {
|
|
397
|
+
const existing = this.traces.find((t) => t.traceId === trace.traceId);
|
|
398
|
+
if (existing) {
|
|
399
|
+
const existingSpanIds = new Set(existing.spans.map((s) => s.spanId));
|
|
400
|
+
for (const span of trace.spans) {
|
|
401
|
+
if (!existingSpanIds.has(span.spanId)) {
|
|
402
|
+
existing.spans.push(span);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
existing.startTime = Math.min(existing.startTime, trace.startTime);
|
|
406
|
+
existing.endTime = Math.max(existing.endTime, trace.endTime);
|
|
407
|
+
existing.duration = existing.endTime - existing.startTime;
|
|
408
|
+
if (trace.status === "ERROR") existing.status = "ERROR";
|
|
409
|
+
} else {
|
|
410
|
+
this.traces = appendWithLimit(
|
|
411
|
+
this.traces,
|
|
412
|
+
trace,
|
|
413
|
+
this.limits.maxTraceCount
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
this.errorAggregator.addErrorsFromTrace(trace);
|
|
417
|
+
this.broadcast({ traces: [trace], metrics: [], logs: [], errors: this.errorAggregator.getErrorGroups() });
|
|
418
|
+
}
|
|
419
|
+
addTraces(traces) {
|
|
420
|
+
for (const trace of traces) this.addTrace(trace);
|
|
421
|
+
}
|
|
422
|
+
addLog(log) {
|
|
423
|
+
this.logs = appendWithLimit(this.logs, log, this.limits.maxLogCount);
|
|
424
|
+
this.broadcast({ traces: [], metrics: [], logs: [log], errors: [] });
|
|
425
|
+
}
|
|
426
|
+
addLogs(logs) {
|
|
427
|
+
this.logs = appendManyWithLimit(this.logs, logs, this.limits.maxLogCount);
|
|
428
|
+
this.broadcast({ traces: [], metrics: [], logs, errors: [] });
|
|
429
|
+
}
|
|
430
|
+
addMetric(metric) {
|
|
431
|
+
this.metrics = appendWithLimit(
|
|
432
|
+
this.metrics,
|
|
433
|
+
metric,
|
|
434
|
+
this.limits.maxMetricCount
|
|
435
|
+
);
|
|
436
|
+
this.broadcast({ traces: [], metrics: [metric], logs: [], errors: [] });
|
|
437
|
+
}
|
|
438
|
+
getCurrentData() {
|
|
439
|
+
return {
|
|
440
|
+
traces: this.traces,
|
|
441
|
+
metrics: this.metrics,
|
|
442
|
+
logs: this.logs,
|
|
443
|
+
errors: this.errorAggregator.getErrorGroups()
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
clearData() {
|
|
447
|
+
this.traces = [];
|
|
448
|
+
this.logs = [];
|
|
449
|
+
this.metrics = [];
|
|
450
|
+
this.errorAggregator.clear();
|
|
451
|
+
}
|
|
452
|
+
broadcast(data) {
|
|
453
|
+
const msg = JSON.stringify(data);
|
|
454
|
+
for (const client of this.clients) {
|
|
455
|
+
if (client.readyState === WebSocket.OPEN) {
|
|
456
|
+
client.send(msg);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
log(message) {
|
|
461
|
+
if (this.verbose) console.log(`[autotel-devtools] ${message}`);
|
|
462
|
+
}
|
|
463
|
+
async close() {
|
|
464
|
+
for (const client of this.clients) client.close();
|
|
465
|
+
this.clients.clear();
|
|
466
|
+
this.wss.close();
|
|
467
|
+
await new Promise((resolve2) => this.httpServer.close(() => resolve2()));
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
// src/server/resource-utils.ts
|
|
472
|
+
function getResourceName(resource, fallback = "unknown") {
|
|
473
|
+
if (!resource) return fallback;
|
|
474
|
+
const candidates = [
|
|
475
|
+
resource["service.name"],
|
|
476
|
+
resource["service.namespace"],
|
|
477
|
+
resource["deployment.environment.name"],
|
|
478
|
+
resource["host.name"],
|
|
479
|
+
resource["container.name"],
|
|
480
|
+
resource["process.executable.name"]
|
|
481
|
+
];
|
|
482
|
+
for (const candidate of candidates) {
|
|
483
|
+
if (typeof candidate === "string" && candidate.trim().length > 0) {
|
|
484
|
+
return candidate;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
return fallback;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// src/server/otlp.ts
|
|
491
|
+
function resolveOtlpValue(v) {
|
|
492
|
+
if (!v) return void 0;
|
|
493
|
+
if (v.stringValue !== void 0) return v.stringValue;
|
|
494
|
+
if (v.boolValue !== void 0) return v.boolValue;
|
|
495
|
+
if (v.intValue !== void 0) return typeof v.intValue === "string" ? Number(v.intValue) : v.intValue;
|
|
496
|
+
if (v.doubleValue !== void 0) return v.doubleValue;
|
|
497
|
+
if (v.bytesValue !== void 0) return v.bytesValue;
|
|
498
|
+
if (v.arrayValue?.values) return v.arrayValue.values.map(resolveOtlpValue);
|
|
499
|
+
if (v.kvlistValue?.values) return flattenAttributes(v.kvlistValue.values);
|
|
500
|
+
return void 0;
|
|
501
|
+
}
|
|
502
|
+
function flattenAttributes(attrs) {
|
|
503
|
+
const out = {};
|
|
504
|
+
if (!attrs) return out;
|
|
505
|
+
for (const { key, value } of attrs) {
|
|
506
|
+
out[key] = resolveOtlpValue(value);
|
|
507
|
+
}
|
|
508
|
+
return out;
|
|
509
|
+
}
|
|
510
|
+
function nanoToMs(nano) {
|
|
511
|
+
if (!nano) return 0;
|
|
512
|
+
return Number(BigInt(nano) / 1000000n);
|
|
513
|
+
}
|
|
514
|
+
var SPAN_KIND_MAP = {
|
|
515
|
+
0: "INTERNAL",
|
|
516
|
+
1: "INTERNAL",
|
|
517
|
+
2: "SERVER",
|
|
518
|
+
3: "CLIENT",
|
|
519
|
+
4: "PRODUCER",
|
|
520
|
+
5: "CONSUMER",
|
|
521
|
+
SPAN_KIND_INTERNAL: "INTERNAL",
|
|
522
|
+
SPAN_KIND_SERVER: "SERVER",
|
|
523
|
+
SPAN_KIND_CLIENT: "CLIENT",
|
|
524
|
+
SPAN_KIND_PRODUCER: "PRODUCER",
|
|
525
|
+
SPAN_KIND_CONSUMER: "CONSUMER"
|
|
526
|
+
};
|
|
527
|
+
function normalizeHexId(id) {
|
|
528
|
+
if (!id) return "";
|
|
529
|
+
const isBase64Like = /^[A-Za-z0-9+/=]+$/.test(id) && !/^[0-9a-f]+$/i.test(id);
|
|
530
|
+
const isLikelyBase64Id = isBase64Like && (id.length === 24 || id.length === 28 || id.length === 44 || id.length === 48);
|
|
531
|
+
if (isLikelyBase64Id) {
|
|
532
|
+
try {
|
|
533
|
+
const bytes = Buffer.from(id, "base64");
|
|
534
|
+
return bytes.toString("hex");
|
|
535
|
+
} catch {
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
return id;
|
|
539
|
+
}
|
|
540
|
+
function parseOtlpTraces(payload) {
|
|
541
|
+
if (!payload || typeof payload !== "object") return [];
|
|
542
|
+
const { resourceSpans } = payload;
|
|
543
|
+
if (!Array.isArray(resourceSpans) || resourceSpans.length === 0) return [];
|
|
544
|
+
const traceMap = /* @__PURE__ */ new Map();
|
|
545
|
+
for (const rs of resourceSpans) {
|
|
546
|
+
const resourceAttrs = flattenAttributes(rs.resource?.attributes);
|
|
547
|
+
const service = String(resourceAttrs["service.name"] || "unknown");
|
|
548
|
+
const scopeSpans = rs.scopeSpans || [];
|
|
549
|
+
for (const ss of scopeSpans) {
|
|
550
|
+
for (const span of ss.spans || []) {
|
|
551
|
+
const traceId = normalizeHexId(span.traceId);
|
|
552
|
+
if (!traceId) continue;
|
|
553
|
+
const startMs = nanoToMs(span.startTimeUnixNano);
|
|
554
|
+
const endMs = nanoToMs(span.endTimeUnixNano);
|
|
555
|
+
const statusCode = span.status?.code;
|
|
556
|
+
let status = "UNSET";
|
|
557
|
+
if (statusCode === 1 || statusCode === "STATUS_CODE_OK") status = "OK";
|
|
558
|
+
if (statusCode === 2 || statusCode === "STATUS_CODE_ERROR") status = "ERROR";
|
|
559
|
+
const spanData = {
|
|
560
|
+
traceId,
|
|
561
|
+
spanId: normalizeHexId(span.spanId),
|
|
562
|
+
parentSpanId: normalizeHexId(span.parentSpanId) || void 0,
|
|
563
|
+
name: span.name || "unknown",
|
|
564
|
+
kind: SPAN_KIND_MAP[span.kind ?? 0] || "INTERNAL",
|
|
565
|
+
startTime: startMs,
|
|
566
|
+
endTime: endMs,
|
|
567
|
+
duration: endMs - startMs,
|
|
568
|
+
attributes: { ...resourceAttrs, ...flattenAttributes(span.attributes) },
|
|
569
|
+
status: { code: status, message: span.status?.message },
|
|
570
|
+
events: (span.events || []).map((e) => ({
|
|
571
|
+
name: e.name || "",
|
|
572
|
+
timestamp: nanoToMs(e.timeUnixNano),
|
|
573
|
+
attributes: flattenAttributes(e.attributes)
|
|
574
|
+
}))
|
|
575
|
+
};
|
|
576
|
+
const existing = traceMap.get(traceId);
|
|
577
|
+
if (existing) {
|
|
578
|
+
existing.spans.push(spanData);
|
|
579
|
+
} else {
|
|
580
|
+
traceMap.set(traceId, { spans: [spanData], service });
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
const traces = [];
|
|
586
|
+
for (const [traceId, { spans, service }] of traceMap) {
|
|
587
|
+
const sorted = spans.sort((a, b) => a.startTime - b.startTime);
|
|
588
|
+
const rootSpan = sorted.find((s) => !s.parentSpanId) || sorted[0];
|
|
589
|
+
const startTime = Math.min(...sorted.map((s) => s.startTime));
|
|
590
|
+
const endTime = Math.max(...sorted.map((s) => s.endTime));
|
|
591
|
+
const hasError = sorted.some((s) => s.status.code === "ERROR");
|
|
592
|
+
traces.push({
|
|
593
|
+
traceId,
|
|
594
|
+
correlationId: traceId.slice(0, 16),
|
|
595
|
+
rootSpan,
|
|
596
|
+
spans: sorted,
|
|
597
|
+
startTime,
|
|
598
|
+
endTime,
|
|
599
|
+
duration: endTime - startTime,
|
|
600
|
+
status: hasError ? "ERROR" : "OK",
|
|
601
|
+
service
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
return traces;
|
|
605
|
+
}
|
|
606
|
+
function parseOtlpLogs(payload) {
|
|
607
|
+
if (!payload || typeof payload !== "object") return [];
|
|
608
|
+
const { resourceLogs } = payload;
|
|
609
|
+
if (!Array.isArray(resourceLogs)) return [];
|
|
610
|
+
const logs = [];
|
|
611
|
+
for (const rl of resourceLogs) {
|
|
612
|
+
const resourceAttrs = flattenAttributes(rl.resource?.attributes);
|
|
613
|
+
for (const sl of rl.scopeLogs || []) {
|
|
614
|
+
for (const rec of sl.logRecords || []) {
|
|
615
|
+
const timestamp = nanoToMs(rec.timeUnixNano || rec.observedTimeUnixNano);
|
|
616
|
+
const traceId = normalizeHexId(rec.traceId) || void 0;
|
|
617
|
+
const spanId = normalizeHexId(rec.spanId) || void 0;
|
|
618
|
+
const body = rec.body ? resolveOtlpValue(rec.body) : "";
|
|
619
|
+
logs.push({
|
|
620
|
+
id: `${traceId || "no-trace"}:${spanId || "no-span"}:${timestamp}:${rec.severityNumber || 0}`,
|
|
621
|
+
traceId,
|
|
622
|
+
spanId,
|
|
623
|
+
resourceName: getResourceName(resourceAttrs),
|
|
624
|
+
severityText: rec.severityText,
|
|
625
|
+
severityNumber: rec.severityNumber,
|
|
626
|
+
body: typeof body === "string" ? body : body,
|
|
627
|
+
timestamp,
|
|
628
|
+
attributes: flattenAttributes(rec.attributes),
|
|
629
|
+
resource: resourceAttrs
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
return logs;
|
|
635
|
+
}
|
|
636
|
+
function countOtlpMetrics(payload) {
|
|
637
|
+
if (!payload || typeof payload !== "object") return 0;
|
|
638
|
+
const { resourceMetrics } = payload;
|
|
639
|
+
if (!Array.isArray(resourceMetrics)) return 0;
|
|
640
|
+
let count = 0;
|
|
641
|
+
for (const rm of resourceMetrics) {
|
|
642
|
+
for (const sm of rm.scopeMetrics || []) {
|
|
643
|
+
count += (sm.metrics || []).length;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
return count;
|
|
647
|
+
}
|
|
648
|
+
async function readJsonBody(req) {
|
|
649
|
+
return new Promise((resolve2, reject) => {
|
|
650
|
+
const chunks = [];
|
|
651
|
+
req.on("data", (chunk) => chunks.push(chunk));
|
|
652
|
+
req.on("end", () => {
|
|
653
|
+
try {
|
|
654
|
+
resolve2(JSON.parse(Buffer.concat(chunks).toString()));
|
|
655
|
+
} catch {
|
|
656
|
+
reject(new Error("Invalid JSON"));
|
|
657
|
+
}
|
|
658
|
+
});
|
|
659
|
+
req.on("error", reject);
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
function sendJson(res, status, data) {
|
|
663
|
+
const body = JSON.stringify(data);
|
|
664
|
+
res.writeHead(status, { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) });
|
|
665
|
+
res.end(body);
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
// src/server/http.ts
|
|
669
|
+
function findPackageRoot() {
|
|
670
|
+
let dir = dirname(fileURLToPath(import.meta.url));
|
|
671
|
+
for (let i = 0; i < 5; i++) {
|
|
672
|
+
if (existsSync(resolve(dir, "package.json"))) return dir;
|
|
673
|
+
dir = dirname(dir);
|
|
674
|
+
}
|
|
675
|
+
return dir;
|
|
676
|
+
}
|
|
677
|
+
var FULLPAGE_HTML = `<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>autotel-devtools</title><style>*{margin:0;padding:0;box-sizing:border-box}html,body{height:100%;width:100%;overflow:hidden}</style></head><body><script src="/widget.js?mode=fullpage"></script></body></html>`;
|
|
678
|
+
var cachedWidgetJs = null;
|
|
679
|
+
function getWidgetJs() {
|
|
680
|
+
if (!cachedWidgetJs) {
|
|
681
|
+
const pkgRoot = findPackageRoot();
|
|
682
|
+
const candidates = [
|
|
683
|
+
resolve(pkgRoot, "dist", "widget.global.js"),
|
|
684
|
+
resolve(pkgRoot, "widget.global.js")
|
|
685
|
+
];
|
|
686
|
+
for (const candidate of candidates) {
|
|
687
|
+
try {
|
|
688
|
+
cachedWidgetJs = readFileSync(candidate, "utf8");
|
|
689
|
+
break;
|
|
690
|
+
} catch {
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
if (!cachedWidgetJs) {
|
|
694
|
+
cachedWidgetJs = "// widget bundle not found - run pnpm build first";
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
return cachedWidgetJs;
|
|
698
|
+
}
|
|
699
|
+
function attachDevtoolsRoutes(httpServer, devtools) {
|
|
700
|
+
httpServer.on("request", async (req, res) => {
|
|
701
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
702
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
703
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
|
704
|
+
if (req.method === "OPTIONS") {
|
|
705
|
+
res.writeHead(204);
|
|
706
|
+
res.end();
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
const url = req.url || "/";
|
|
710
|
+
if (req.method === "GET" && url === "/") {
|
|
711
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Length": Buffer.byteLength(FULLPAGE_HTML) });
|
|
712
|
+
res.end(FULLPAGE_HTML);
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
if (req.method === "GET" && url.startsWith("/widget.js")) {
|
|
716
|
+
const js = getWidgetJs();
|
|
717
|
+
res.writeHead(200, { "Content-Type": "application/javascript; charset=utf-8", "Content-Length": Buffer.byteLength(js) });
|
|
718
|
+
res.end(js);
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
if (req.method === "GET" && url === "/healthz") {
|
|
722
|
+
sendJson(res, 200, { ok: true, clients: devtools.clientCount });
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
if (req.method === "POST" && url === "/v1/traces") {
|
|
726
|
+
try {
|
|
727
|
+
const payload = await readJsonBody(req);
|
|
728
|
+
const traces = parseOtlpTraces(payload);
|
|
729
|
+
devtools.addTraces(traces);
|
|
730
|
+
sendJson(res, 200, { acceptedTraces: traces.length });
|
|
731
|
+
} catch (e) {
|
|
732
|
+
sendJson(res, 400, { error: "Invalid OTLP JSON", message: e instanceof Error ? e.message : String(e) });
|
|
733
|
+
}
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
if (req.method === "POST" && url === "/v1/logs") {
|
|
737
|
+
try {
|
|
738
|
+
const payload = await readJsonBody(req);
|
|
739
|
+
const logs = parseOtlpLogs(payload);
|
|
740
|
+
devtools.addLogs(logs);
|
|
741
|
+
sendJson(res, 200, { acceptedLogs: logs.length });
|
|
742
|
+
} catch (e) {
|
|
743
|
+
sendJson(res, 400, { error: "Invalid OTLP JSON", message: e instanceof Error ? e.message : String(e) });
|
|
744
|
+
}
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
if (req.method === "POST" && url === "/v1/metrics") {
|
|
748
|
+
try {
|
|
749
|
+
const payload = await readJsonBody(req);
|
|
750
|
+
const count = countOtlpMetrics(payload);
|
|
751
|
+
sendJson(res, 200, { acceptedMetrics: count });
|
|
752
|
+
} catch (e) {
|
|
753
|
+
sendJson(res, 400, { error: "Invalid OTLP JSON", message: e instanceof Error ? e.message : String(e) });
|
|
754
|
+
}
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
sendJson(res, 404, { error: "Not found" });
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
// src/server/exporter.ts
|
|
762
|
+
var DevtoolsSpanExporter = class {
|
|
763
|
+
server;
|
|
764
|
+
serviceName;
|
|
765
|
+
constructor(server, serviceName = "unknown-service") {
|
|
766
|
+
this.server = server;
|
|
767
|
+
this.serviceName = serviceName;
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* Export spans to the WebSocket server
|
|
771
|
+
*/
|
|
772
|
+
async export(spans, resultCallback) {
|
|
773
|
+
resultCallback({ code: 0 });
|
|
774
|
+
Promise.resolve().then(() => {
|
|
775
|
+
try {
|
|
776
|
+
console.log(`[Autotel Exporter] Exporting ${spans.length} span(s)`);
|
|
777
|
+
const traceMap = /* @__PURE__ */ new Map();
|
|
778
|
+
for (const span of spans) {
|
|
779
|
+
const traceId = span.spanContext().traceId;
|
|
780
|
+
if (!traceMap.has(traceId)) {
|
|
781
|
+
traceMap.set(traceId, []);
|
|
782
|
+
}
|
|
783
|
+
traceMap.get(traceId).push(span);
|
|
784
|
+
}
|
|
785
|
+
for (const [traceId, traceSpans] of traceMap) {
|
|
786
|
+
const trace = this.convertToTraceData(traceId, traceSpans);
|
|
787
|
+
console.log(
|
|
788
|
+
`[Autotel Exporter] Adding trace ${traceId.slice(0, 16)} with ${traceSpans.length} spans`
|
|
789
|
+
);
|
|
790
|
+
this.server.addTrace(trace);
|
|
791
|
+
}
|
|
792
|
+
} catch (error) {
|
|
793
|
+
console.error("[Autotel Exporter] Export error:", error);
|
|
794
|
+
}
|
|
795
|
+
});
|
|
796
|
+
}
|
|
797
|
+
/**
|
|
798
|
+
* Shutdown the exporter
|
|
799
|
+
*/
|
|
800
|
+
async shutdown() {
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* Force flush any buffered spans
|
|
804
|
+
*/
|
|
805
|
+
async forceFlush() {
|
|
806
|
+
}
|
|
807
|
+
/**
|
|
808
|
+
* Convert OpenTelemetry spans to TraceData
|
|
809
|
+
*/
|
|
810
|
+
convertToTraceData(traceId, spans) {
|
|
811
|
+
const spanData = spans.map((span) => this.convertSpan(span));
|
|
812
|
+
const rootSpan = spanData.find((s) => !s.parentSpanId) || spanData[0];
|
|
813
|
+
spanData.sort((a, b) => a.startTime - b.startTime);
|
|
814
|
+
const startTime = Math.min(...spanData.map((s) => s.startTime));
|
|
815
|
+
const endTime = Math.max(...spanData.map((s) => s.endTime));
|
|
816
|
+
const hasError = spanData.some((s) => s.status.code === "ERROR");
|
|
817
|
+
const status = hasError ? "ERROR" : "OK";
|
|
818
|
+
return {
|
|
819
|
+
traceId,
|
|
820
|
+
correlationId: traceId.slice(0, 16),
|
|
821
|
+
// First 16 chars
|
|
822
|
+
rootSpan,
|
|
823
|
+
spans: spanData,
|
|
824
|
+
startTime,
|
|
825
|
+
endTime,
|
|
826
|
+
duration: endTime - startTime,
|
|
827
|
+
status,
|
|
828
|
+
service: this.serviceName
|
|
829
|
+
};
|
|
830
|
+
}
|
|
831
|
+
/**
|
|
832
|
+
* Convert OpenTelemetry span to SpanData
|
|
833
|
+
*/
|
|
834
|
+
convertSpan(span) {
|
|
835
|
+
const spanContext = span.spanContext();
|
|
836
|
+
const startTime = span.startTime[0] * 1e3 + span.startTime[1] / 1e6;
|
|
837
|
+
const endTime = span.endTime[0] * 1e3 + span.endTime[1] / 1e6;
|
|
838
|
+
const attributes = {};
|
|
839
|
+
for (const [key, value] of Object.entries(span.attributes)) {
|
|
840
|
+
attributes[key] = value;
|
|
841
|
+
}
|
|
842
|
+
const statusCode = span.status.code;
|
|
843
|
+
let status;
|
|
844
|
+
switch (statusCode) {
|
|
845
|
+
case 0: {
|
|
846
|
+
status = "UNSET";
|
|
847
|
+
break;
|
|
848
|
+
}
|
|
849
|
+
case 1: {
|
|
850
|
+
status = "OK";
|
|
851
|
+
break;
|
|
852
|
+
}
|
|
853
|
+
case 2: {
|
|
854
|
+
status = "ERROR";
|
|
855
|
+
break;
|
|
856
|
+
}
|
|
857
|
+
default: {
|
|
858
|
+
status = "UNSET";
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
const events = span.events.map((event) => ({
|
|
862
|
+
name: event.name,
|
|
863
|
+
timestamp: event.time[0] * 1e3 + event.time[1] / 1e6,
|
|
864
|
+
attributes: event.attributes ? Object.fromEntries(Object.entries(event.attributes)) : void 0
|
|
865
|
+
}));
|
|
866
|
+
return {
|
|
867
|
+
traceId: spanContext.traceId,
|
|
868
|
+
spanId: spanContext.spanId,
|
|
869
|
+
parentSpanId: span.parentSpanId,
|
|
870
|
+
name: span.name,
|
|
871
|
+
kind: this.convertSpanKind(span.kind),
|
|
872
|
+
startTime,
|
|
873
|
+
endTime,
|
|
874
|
+
duration: endTime - startTime,
|
|
875
|
+
attributes,
|
|
876
|
+
status: {
|
|
877
|
+
code: status,
|
|
878
|
+
message: span.status.message
|
|
879
|
+
},
|
|
880
|
+
events: events.length > 0 ? events : void 0
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Convert OpenTelemetry SpanKind to string
|
|
885
|
+
*/
|
|
886
|
+
convertSpanKind(kind) {
|
|
887
|
+
switch (kind) {
|
|
888
|
+
case 0: {
|
|
889
|
+
return "INTERNAL";
|
|
890
|
+
}
|
|
891
|
+
case 1: {
|
|
892
|
+
return "SERVER";
|
|
893
|
+
}
|
|
894
|
+
case 2: {
|
|
895
|
+
return "CLIENT";
|
|
896
|
+
}
|
|
897
|
+
case 3: {
|
|
898
|
+
return "PRODUCER";
|
|
899
|
+
}
|
|
900
|
+
case 4: {
|
|
901
|
+
return "CONSUMER";
|
|
902
|
+
}
|
|
903
|
+
default: {
|
|
904
|
+
return "INTERNAL";
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
};
|
|
909
|
+
var defaultTimeout = 5e3;
|
|
910
|
+
function hrTimeToMs(hrTime) {
|
|
911
|
+
return hrTime[0] * 1e3 + hrTime[1] / 1e6;
|
|
912
|
+
}
|
|
913
|
+
function bodyToPayload(body) {
|
|
914
|
+
if (body === void 0) return "";
|
|
915
|
+
if (typeof body === "string") return body;
|
|
916
|
+
if (typeof body === "object" && body !== null) return body;
|
|
917
|
+
return String(body);
|
|
918
|
+
}
|
|
919
|
+
function recordToLogData(record, index) {
|
|
920
|
+
const id = `log-${Date.now()}-${index}-${Math.random().toString(36).slice(2, 9)}`;
|
|
921
|
+
const timestamp = hrTimeToMs(record.hrTime);
|
|
922
|
+
const body = bodyToPayload(record.body);
|
|
923
|
+
const attributes = record.attributes && Object.keys(record.attributes).length > 0 ? record.attributes : void 0;
|
|
924
|
+
const resource = record.resource?.attributes && Object.keys(record.resource.attributes).length > 0 ? record.resource.attributes : void 0;
|
|
925
|
+
const log = {
|
|
926
|
+
id,
|
|
927
|
+
resourceName: getResourceName(resource),
|
|
928
|
+
severityText: record.severityText,
|
|
929
|
+
severityNumber: record.severityNumber,
|
|
930
|
+
body,
|
|
931
|
+
timestamp,
|
|
932
|
+
attributes,
|
|
933
|
+
resource
|
|
934
|
+
};
|
|
935
|
+
if (record.spanContext) {
|
|
936
|
+
log.traceId = record.spanContext.traceId;
|
|
937
|
+
log.spanId = record.spanContext.spanId;
|
|
938
|
+
}
|
|
939
|
+
return log;
|
|
940
|
+
}
|
|
941
|
+
var DevtoolsLogExporter = class {
|
|
942
|
+
endpoint;
|
|
943
|
+
apiKey;
|
|
944
|
+
timeout;
|
|
945
|
+
isShutdown = false;
|
|
946
|
+
constructor(options) {
|
|
947
|
+
this.endpoint = options.endpoint.replace(/\/$/, "");
|
|
948
|
+
this.apiKey = options.apiKey ?? "";
|
|
949
|
+
this.timeout = options.timeout ?? defaultTimeout;
|
|
950
|
+
}
|
|
951
|
+
export(logs, resultCallback) {
|
|
952
|
+
if (this.isShutdown || logs.length === 0) {
|
|
953
|
+
resultCallback({ code: ExportResultCode.SUCCESS });
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
const payload = { logs: logs.map((r, i) => recordToLogData(r, i)) };
|
|
957
|
+
const url = `${this.endpoint}/ingest/logs`;
|
|
958
|
+
const headers = {
|
|
959
|
+
"Content-Type": "application/json"
|
|
960
|
+
};
|
|
961
|
+
if (this.apiKey) {
|
|
962
|
+
headers["Authorization"] = `Bearer ${this.apiKey}`;
|
|
963
|
+
}
|
|
964
|
+
const controller = new AbortController();
|
|
965
|
+
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
966
|
+
fetch(url, {
|
|
967
|
+
method: "POST",
|
|
968
|
+
headers,
|
|
969
|
+
body: JSON.stringify(payload),
|
|
970
|
+
signal: controller.signal
|
|
971
|
+
}).then((res) => {
|
|
972
|
+
clearTimeout(timeoutId);
|
|
973
|
+
if (!res.ok) {
|
|
974
|
+
throw new Error(`Devtools log ingest failed: ${res.status} ${res.statusText}`);
|
|
975
|
+
}
|
|
976
|
+
resultCallback({ code: ExportResultCode.SUCCESS });
|
|
977
|
+
}).catch((err) => {
|
|
978
|
+
clearTimeout(timeoutId);
|
|
979
|
+
resultCallback({
|
|
980
|
+
code: ExportResultCode.FAILED,
|
|
981
|
+
error: err instanceof Error ? err : new Error(String(err))
|
|
982
|
+
});
|
|
983
|
+
});
|
|
984
|
+
}
|
|
985
|
+
shutdown() {
|
|
986
|
+
this.isShutdown = true;
|
|
987
|
+
return Promise.resolve();
|
|
988
|
+
}
|
|
989
|
+
};
|
|
990
|
+
|
|
991
|
+
// src/server/remote-exporter.ts
|
|
992
|
+
var DevtoolsRemoteExporter = class {
|
|
993
|
+
options;
|
|
994
|
+
pendingExports = [];
|
|
995
|
+
constructor(options) {
|
|
996
|
+
this.options = {
|
|
997
|
+
endpoint: options.endpoint.replace(/\/$/, ""),
|
|
998
|
+
// Remove trailing slash
|
|
999
|
+
apiKey: options.apiKey ?? "",
|
|
1000
|
+
serviceName: options.serviceName ?? "unknown-service",
|
|
1001
|
+
timeout: options.timeout ?? 5e3,
|
|
1002
|
+
retry: options.retry ?? true,
|
|
1003
|
+
retryCount: options.retryCount ?? 3,
|
|
1004
|
+
retryDelay: options.retryDelay ?? 1e3,
|
|
1005
|
+
verbose: options.verbose ?? false
|
|
1006
|
+
};
|
|
1007
|
+
}
|
|
1008
|
+
/**
|
|
1009
|
+
* Export spans to the remote server
|
|
1010
|
+
*/
|
|
1011
|
+
async export(spans, resultCallback) {
|
|
1012
|
+
const exportPromise = this.doExport(spans).then(() => {
|
|
1013
|
+
resultCallback({ code: 0 });
|
|
1014
|
+
}).catch((error) => {
|
|
1015
|
+
this.log(`Export failed: ${error.message}`);
|
|
1016
|
+
resultCallback({ code: 1 });
|
|
1017
|
+
});
|
|
1018
|
+
this.pendingExports.push(exportPromise);
|
|
1019
|
+
exportPromise.finally(() => {
|
|
1020
|
+
const index = this.pendingExports.indexOf(exportPromise);
|
|
1021
|
+
if (index !== -1) {
|
|
1022
|
+
this.pendingExports.splice(index, 1);
|
|
1023
|
+
}
|
|
1024
|
+
});
|
|
1025
|
+
}
|
|
1026
|
+
async doExport(spans) {
|
|
1027
|
+
if (spans.length === 0) return;
|
|
1028
|
+
this.log(`Exporting ${spans.length} span(s) to ${this.options.endpoint}`);
|
|
1029
|
+
const traceMap = /* @__PURE__ */ new Map();
|
|
1030
|
+
for (const span of spans) {
|
|
1031
|
+
const traceId = span.spanContext().traceId;
|
|
1032
|
+
if (!traceMap.has(traceId)) {
|
|
1033
|
+
traceMap.set(traceId, []);
|
|
1034
|
+
}
|
|
1035
|
+
traceMap.get(traceId).push(span);
|
|
1036
|
+
}
|
|
1037
|
+
const traces = [];
|
|
1038
|
+
for (const [traceId, traceSpans] of traceMap) {
|
|
1039
|
+
traces.push(this.convertToTraceData(traceId, traceSpans));
|
|
1040
|
+
}
|
|
1041
|
+
await this.sendWithRetry({ traces });
|
|
1042
|
+
}
|
|
1043
|
+
async sendWithRetry(payload) {
|
|
1044
|
+
let lastError = null;
|
|
1045
|
+
const maxAttempts = this.options.retry ? this.options.retryCount : 1;
|
|
1046
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
1047
|
+
try {
|
|
1048
|
+
await this.send(payload);
|
|
1049
|
+
return;
|
|
1050
|
+
} catch (error) {
|
|
1051
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
1052
|
+
this.log(
|
|
1053
|
+
`Attempt ${attempt}/${maxAttempts} failed: ${lastError.message}`
|
|
1054
|
+
);
|
|
1055
|
+
if (attempt < maxAttempts) {
|
|
1056
|
+
await this.sleep(this.options.retryDelay * attempt);
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
throw lastError || new Error("Export failed");
|
|
1061
|
+
}
|
|
1062
|
+
async send(payload) {
|
|
1063
|
+
const controller = new AbortController();
|
|
1064
|
+
const timeoutId = setTimeout(
|
|
1065
|
+
() => controller.abort(),
|
|
1066
|
+
this.options.timeout
|
|
1067
|
+
);
|
|
1068
|
+
try {
|
|
1069
|
+
const headers = {
|
|
1070
|
+
"Content-Type": "application/json"
|
|
1071
|
+
};
|
|
1072
|
+
if (this.options.apiKey) {
|
|
1073
|
+
headers["Authorization"] = `Bearer ${this.options.apiKey}`;
|
|
1074
|
+
}
|
|
1075
|
+
const response = await fetch(`${this.options.endpoint}/ingest/traces`, {
|
|
1076
|
+
method: "POST",
|
|
1077
|
+
headers,
|
|
1078
|
+
body: JSON.stringify(payload),
|
|
1079
|
+
signal: controller.signal
|
|
1080
|
+
});
|
|
1081
|
+
if (!response.ok) {
|
|
1082
|
+
const text = await response.text();
|
|
1083
|
+
throw new Error(`HTTP ${response.status}: ${text}`);
|
|
1084
|
+
}
|
|
1085
|
+
const result = await response.json();
|
|
1086
|
+
this.log(`Successfully sent ${result.processed} trace(s)`);
|
|
1087
|
+
} finally {
|
|
1088
|
+
clearTimeout(timeoutId);
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
/**
|
|
1092
|
+
* Shutdown the exporter, waiting for pending exports
|
|
1093
|
+
*/
|
|
1094
|
+
async shutdown() {
|
|
1095
|
+
this.log("Shutting down, waiting for pending exports...");
|
|
1096
|
+
await Promise.allSettled(this.pendingExports);
|
|
1097
|
+
this.log("Shutdown complete");
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* Force flush pending exports
|
|
1101
|
+
*/
|
|
1102
|
+
async forceFlush() {
|
|
1103
|
+
await Promise.allSettled(this.pendingExports);
|
|
1104
|
+
}
|
|
1105
|
+
convertToTraceData(traceId, spans) {
|
|
1106
|
+
const spanData = spans.map((span) => this.convertSpan(span));
|
|
1107
|
+
const rootSpan = spanData.find((s) => !s.parentSpanId) || spanData[0];
|
|
1108
|
+
spanData.sort((a, b) => a.startTime - b.startTime);
|
|
1109
|
+
const startTime = Math.min(...spanData.map((s) => s.startTime));
|
|
1110
|
+
const endTime = Math.max(...spanData.map((s) => s.endTime));
|
|
1111
|
+
const hasError = spanData.some((s) => s.status.code === "ERROR");
|
|
1112
|
+
const status = hasError ? "ERROR" : "OK";
|
|
1113
|
+
return {
|
|
1114
|
+
traceId,
|
|
1115
|
+
correlationId: traceId.slice(0, 16),
|
|
1116
|
+
rootSpan,
|
|
1117
|
+
spans: spanData,
|
|
1118
|
+
startTime,
|
|
1119
|
+
endTime,
|
|
1120
|
+
duration: endTime - startTime,
|
|
1121
|
+
status,
|
|
1122
|
+
service: this.options.serviceName
|
|
1123
|
+
};
|
|
1124
|
+
}
|
|
1125
|
+
convertSpan(span) {
|
|
1126
|
+
const spanContext = span.spanContext();
|
|
1127
|
+
const startTime = span.startTime[0] * 1e3 + span.startTime[1] / 1e6;
|
|
1128
|
+
const endTime = span.endTime[0] * 1e3 + span.endTime[1] / 1e6;
|
|
1129
|
+
const attributes = {};
|
|
1130
|
+
for (const [key, value] of Object.entries(span.attributes)) {
|
|
1131
|
+
attributes[key] = value;
|
|
1132
|
+
}
|
|
1133
|
+
let status;
|
|
1134
|
+
switch (span.status.code) {
|
|
1135
|
+
case 0: {
|
|
1136
|
+
status = "UNSET";
|
|
1137
|
+
break;
|
|
1138
|
+
}
|
|
1139
|
+
case 1: {
|
|
1140
|
+
status = "OK";
|
|
1141
|
+
break;
|
|
1142
|
+
}
|
|
1143
|
+
case 2: {
|
|
1144
|
+
status = "ERROR";
|
|
1145
|
+
break;
|
|
1146
|
+
}
|
|
1147
|
+
default: {
|
|
1148
|
+
status = "UNSET";
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
const events = span.events.map((event) => ({
|
|
1152
|
+
name: event.name,
|
|
1153
|
+
timestamp: event.time[0] * 1e3 + event.time[1] / 1e6,
|
|
1154
|
+
attributes: event.attributes ? Object.fromEntries(Object.entries(event.attributes)) : void 0
|
|
1155
|
+
}));
|
|
1156
|
+
return {
|
|
1157
|
+
traceId: spanContext.traceId,
|
|
1158
|
+
spanId: spanContext.spanId,
|
|
1159
|
+
parentSpanId: span.parentSpanId,
|
|
1160
|
+
name: span.name,
|
|
1161
|
+
kind: this.convertSpanKind(span.kind),
|
|
1162
|
+
startTime,
|
|
1163
|
+
endTime,
|
|
1164
|
+
duration: endTime - startTime,
|
|
1165
|
+
attributes,
|
|
1166
|
+
status: {
|
|
1167
|
+
code: status,
|
|
1168
|
+
message: span.status.message
|
|
1169
|
+
},
|
|
1170
|
+
events: events.length > 0 ? events : void 0
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
convertSpanKind(kind) {
|
|
1174
|
+
switch (kind) {
|
|
1175
|
+
case 0: {
|
|
1176
|
+
return "INTERNAL";
|
|
1177
|
+
}
|
|
1178
|
+
case 1: {
|
|
1179
|
+
return "SERVER";
|
|
1180
|
+
}
|
|
1181
|
+
case 2: {
|
|
1182
|
+
return "CLIENT";
|
|
1183
|
+
}
|
|
1184
|
+
case 3: {
|
|
1185
|
+
return "PRODUCER";
|
|
1186
|
+
}
|
|
1187
|
+
case 4: {
|
|
1188
|
+
return "CONSUMER";
|
|
1189
|
+
}
|
|
1190
|
+
default: {
|
|
1191
|
+
return "INTERNAL";
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
sleep(ms) {
|
|
1196
|
+
return new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
1197
|
+
}
|
|
1198
|
+
log(message) {
|
|
1199
|
+
if (this.options.verbose) {
|
|
1200
|
+
console.log(`[Devtools Remote Exporter] ${message}`);
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
};
|
|
1204
|
+
|
|
1205
|
+
// src/index.ts
|
|
1206
|
+
function createDevtools(options = {}) {
|
|
1207
|
+
const port = options.port ?? 4318;
|
|
1208
|
+
const host = options.host ?? "127.0.0.1";
|
|
1209
|
+
const httpServer = createServer();
|
|
1210
|
+
const wsServer = new DevtoolsServer({
|
|
1211
|
+
server: httpServer,
|
|
1212
|
+
verbose: options.verbose,
|
|
1213
|
+
maxHistory: options.maxHistory,
|
|
1214
|
+
maxTraceCount: options.maxTraceCount,
|
|
1215
|
+
maxLogCount: options.maxLogCount,
|
|
1216
|
+
maxMetricCount: options.maxMetricCount
|
|
1217
|
+
});
|
|
1218
|
+
attachDevtoolsRoutes(httpServer, wsServer);
|
|
1219
|
+
httpServer.listen(port, host);
|
|
1220
|
+
const exporter = new DevtoolsSpanExporter(wsServer);
|
|
1221
|
+
return {
|
|
1222
|
+
server: wsServer,
|
|
1223
|
+
httpServer,
|
|
1224
|
+
exporter,
|
|
1225
|
+
port,
|
|
1226
|
+
close: async () => {
|
|
1227
|
+
await wsServer.close();
|
|
1228
|
+
}
|
|
1229
|
+
};
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
export { DevtoolsLogExporter, DevtoolsRemoteExporter, DevtoolsServer, DevtoolsSpanExporter, ErrorAggregator, createDevtools };
|
|
1233
|
+
//# sourceMappingURL=index.js.map
|
|
1234
|
+
//# sourceMappingURL=index.js.map
|