autotel
Version:
Write Once, Observe Anywhere
85 lines (82 loc) • 2.74 kB
JavaScript
;
require('./chunk-JEQ2X3Z6.cjs');
var api = require('@opentelemetry/api');
var ExportResultCode = { SUCCESS: 0};
var TestSpanCollector = class {
traces = /* @__PURE__ */ new Map();
export(spans, callback) {
for (const span of spans) {
const traceId = span.spanContext().traceId;
let list = this.traces.get(traceId);
if (!list) {
list = [];
this.traces.set(traceId, list);
}
list.push(span);
}
callback({ code: ExportResultCode.SUCCESS });
}
/**
* Drain and serialize spans that are descendants of `rootSpanId` within `traceId`.
* Filters to the subtree rooted at the test span to prevent cross-test mixing.
* Removes the entire traceId entry from the collector.
*/
drainTrace(traceId, rootSpanId) {
const allSpans = this.traces.get(traceId);
this.traces.delete(traceId);
if (!allSpans?.length) return [];
const byId = /* @__PURE__ */ new Map();
for (const s of allSpans) byId.set(s.spanContext().spanId, s);
const included = allSpans.filter((s) => {
let id = s.spanContext().spanId;
while (id) {
if (id === rootSpanId) return true;
const parent = byId.get(id);
const parentId = parent?.parentSpanContext?.spanId || void 0;
if (parentId === id) break;
id = parentId;
}
return false;
});
return included.map((s) => serializeSpan(s));
}
shutdown() {
this.traces.clear();
return Promise.resolve();
}
forceFlush() {
return Promise.resolve();
}
};
function hrTimeToMs(hr) {
return hr[0] * 1e3 + hr[1] / 1e6;
}
function isSerializable(v) {
if (typeof v === "string" || typeof v === "number" || typeof v === "boolean")
return true;
if (Array.isArray(v) && v.length > 0) {
const t = typeof v[0];
return (t === "string" || t === "number" || t === "boolean") && v.every((e) => typeof e === t);
}
return false;
}
function serializeSpan(span) {
const attrs = {};
for (const [k, v] of Object.entries(span.attributes)) {
if (isSerializable(v)) attrs[k] = v;
}
return {
spanId: span.spanContext().spanId,
parentSpanId: span.parentSpanContext?.spanId || void 0,
name: span.name,
startTimeMs: hrTimeToMs(span.startTime),
durationMs: hrTimeToMs(span.duration),
status: span.status.code === api.SpanStatusCode.ERROR ? "error" : span.status.code === api.SpanStatusCode.OK ? "ok" : "unset",
statusMessage: span.status.message || void 0,
attributes: Object.keys(attrs).length > 0 ? attrs : void 0
};
}
exports.TestSpanCollector = TestSpanCollector;
exports.serializeSpan = serializeSpan;
//# sourceMappingURL=test-span-collector.cjs.map
//# sourceMappingURL=test-span-collector.cjs.map