@mastra/core
Version:
58 lines (57 loc) • 2.61 kB
JavaScript
// src/observability/error-count.ts
let currentAttemptResolver;
const origins = /* @__PURE__ */ new WeakMap();
const key = "__mastraSpanErrorOrigin";
function retryScope(attemptId) {
const boundary = attemptId?.lastIndexOf(":attempt:") ?? -1;
return boundary < 0 ? void 0 : attemptId.slice(0, boundary);
}
/** @internal Register the server-only retry context without importing Node APIs here. */
function setSpanErrorAttemptResolver(resolver) {
currentAttemptResolver = resolver;
}
/** @internal Read through wrappers without retaining errors or traversing span trees. */
function getSpanErrorOrigin(error) {
const seen = /* @__PURE__ */ new Set();
let current = error;
while (current && typeof current === "object" && !seen.has(current) && seen.size < 32) {
seen.add(current);
let candidate;
try {
candidate = origins.get(current) ?? current[key];
} catch {
return;
}
if (candidate && typeof candidate === "object") {
const origin = candidate;
if (typeof origin.traceId === "string" && typeof origin.spanId === "string" && typeof origin.occurrenceId === "string" && (origin.attemptId === void 0 || typeof origin.attemptId === "string")) return origin;
}
try {
current = current.cause;
} catch {
return;
}
}
}
/** @internal Keep origin available to forwarding and explicit serializers without mutating user errors. */
function setSpanErrorOrigin(error, origin) {
origins.set(error, origin);
}
/** @internal Return an occurrence only to the span where it originated. */
function claimSpanError(error, traceId, spanId, options) {
if (options?.origin === "propagated") return void 0;
if (error === null || typeof error !== "object" && typeof error !== "function") return void 0;
const attemptId = currentAttemptResolver?.();
let origin = getSpanErrorOrigin(error);
const scope = retryScope(attemptId);
if (options?.origin === "new" || !origin || origin.traceId !== traceId || scope !== void 0 && scope === retryScope(origin.attemptId) && attemptId !== origin.attemptId || origin.spanId === spanId && options?.occurrenceId !== void 0 && origin.occurrenceId !== options.occurrenceId && attemptId !== void 0 && origin.attemptId !== attemptId) origin = {
traceId,
spanId,
occurrenceId: options?.occurrenceId ?? globalThis.crypto.randomUUID(),
...attemptId !== void 0 ? { attemptId } : {}
};
setSpanErrorOrigin(error, origin);
return origin.spanId === spanId ? origin.occurrenceId : void 0;
}
export { setSpanErrorOrigin as i, getSpanErrorOrigin as n, setSpanErrorAttemptResolver as r, claimSpanError as t };
//# sourceMappingURL=error-count-BH-rJW7q.js.map