UNPKG

@mastra/core

Version:
81 lines (80 loc) • 3.02 kB
// 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; } Object.defineProperty(exports, "claimSpanError", { enumerable: true, get: function() { return claimSpanError; } }); Object.defineProperty(exports, "getSpanErrorOrigin", { enumerable: true, get: function() { return getSpanErrorOrigin; } }); Object.defineProperty(exports, "setSpanErrorAttemptResolver", { enumerable: true, get: function() { return setSpanErrorAttemptResolver; } }); Object.defineProperty(exports, "setSpanErrorOrigin", { enumerable: true, get: function() { return setSpanErrorOrigin; } }); //# sourceMappingURL=error-count-DeDpeWU2.cjs.map