Files
MikrotikManager/backend/src/services/server-poll-error-provenance.ts
T

111 lines
8.5 KiB
TypeScript

/** Error-path provenance only. Never authority, public payload or raw cause. */
import { types } from "node:util"
import { DatabaseError } from "pg"
const sites = ["probe.query", "poll.meta", "poll.sql", "poll.connect", "storage", "journal.auth", "journal.tx", "native.fence", "poll.exec", "poll.safe"] as const
type Site = typeof sites[number]
const sqlStates = new Set(["40001", "40P01", "57014", "53300", "08003", "08006", "57P01", "23505", "23503", "23514", "22P02", "42P01", "42501", "25P02", "55P03", "53200", "53100", "XX000"])
const nodeCategories: Readonly<Record<string, string>> = Object.freeze({ ECONNRESET: "reset", ECONNREFUSED: "refused", ETIMEDOUT: "timeout", ENOTFOUND: "dns", EAI_AGAIN: "dns", EPIPE: "pipe", ERR_STREAM_DESTROYED: "stream" })
const probeBranches = ["deadline", "abort", "driver-throw", "driver-reject", "closed", "busy", "input", "inactive", "lease-error", "lease-abort", "lease-timeout", "lease-closed", "result-closed", "result-inactive", "result-shape", "commit-ack", "result-access"] as const
const probeKinds = ["principal", "meta", "storage-lock", "commit", "other"] as const
export interface PollProbeGuard { readonly phase: "checkout" | "query"; readonly queryKind: typeof probeKinds[number]; readonly branch: typeof probeBranches[number] }
const executionPhases = ["native", "server.name", "flow-cache.invalidate", "snapshot.insert", "snapshot.raw.clear",
"partition.drop", "partition.ensure", "partition.storage", "partition.atomic", "receipt"] as const
const executionBoundaries = ["gate", "journal-intent", "dispatch-fence", "effect", "precommit", "after-precommit",
"independent-readback", "journal-ack", "receipt-write", "receipt-authority"] as const
export interface PollExecutionProgress {
readonly phase: typeof executionPhases[number]
readonly boundary: typeof executionBoundaries[number]
readonly confirmedPublications: number
readonly completedPublications: number
}
export interface PollErrorDiagnostic {
readonly version: 1
readonly origin: Readonly<{ kind: "pg" | "node" | "other"; sqlState: string | null; nodeCategory: string | null }>
readonly sites: readonly Site[]
readonly truncated: boolean
readonly probe?: Readonly<PollProbeGuard>
readonly execution?: PollExecutionProgress
}
const errors = new WeakMap<Error, PollErrorDiagnostic>()
const unknownDiagnostic: PollErrorDiagnostic = Object.freeze({ version: 1, origin: Object.freeze({ kind: "other", sqlState: null, nodeCategory: null }), sites: Object.freeze([]), truncated: false })
const own = (value: object, key: string): unknown => Object.getOwnPropertyDescriptor(value, key)?.value
const key = (value: unknown): value is Error => !!value && typeof value === "object" && !types.isProxy(value) && types.isNativeError(value)
function closedProbe(raw: unknown): Readonly<PollProbeGuard> | undefined {
if (!raw || typeof raw !== "object" || types.isProxy(raw)) return undefined
const phase = own(raw, "phase"), queryKind = own(raw, "queryKind"), branch = own(raw, "branch")
if ((phase !== "checkout" && phase !== "query") || !probeKinds.includes(queryKind as PollProbeGuard["queryKind"]) || !probeBranches.includes(branch as PollProbeGuard["branch"])) return undefined
return Object.freeze({ phase, queryKind: queryKind as PollProbeGuard["queryKind"], branch: branch as PollProbeGuard["branch"] })
}
function closedExecution(raw: unknown): PollExecutionProgress | undefined {
if (!raw || typeof raw !== "object" || types.isProxy(raw)) return undefined
const phase = own(raw, "phase") as PollExecutionProgress["phase"]
const boundary = own(raw, "boundary") as PollExecutionProgress["boundary"]
const confirmedPublications = own(raw, "confirmedPublications"), completedPublications = own(raw, "completedPublications")
if (!executionPhases.includes(phase) || !executionBoundaries.includes(boundary) ||
typeof confirmedPublications !== "number" || !Number.isSafeInteger(confirmedPublications) || confirmedPublications > 2004 ||
typeof completedPublications !== "number" || !Number.isSafeInteger(completedPublications) ||
completedPublications < 0 || completedPublications > confirmedPublications) return undefined
return Object.freeze({ phase, boundary, confirmedPublications, completedPublications })
}
/** Error-path annotation only. It never changes the error, stores a raw cause,
* or adds a site; the existing replacement pipeline adds its original site. */
export function tagPollProbeGuard<T extends Error>(replacement: T, original: unknown, detail: PollProbeGuard): T {
try {
const probe = closedProbe(detail)
if (!key(replacement) || !probe) return replacement
const captured = capturePollError(original)
const value: PollErrorDiagnostic = Object.freeze({ ...captured, probe })
if (Buffer.byteLength(JSON.stringify(value)) <= 768) errors.set(replacement, value)
} catch { /* Diagnostics cannot replace/throw/retry. */ }
return replacement
}
export function capturePollError(error: unknown): PollErrorDiagnostic {
try {
if (key(error)) {
const previous = errors.get(error)
if (previous) return previous
const code = own(error, "code")
const pg = Object.getPrototypeOf(error) === DatabaseError.prototype
const nodeCategory = typeof code === "string" && Object.hasOwn(nodeCategories, code) ? nodeCategories[code] : null
return Object.freeze({ version: 1, origin: Object.freeze({ kind: pg ? "pg" : nodeCategory ? "node" : "other", sqlState: pg && typeof code === "string" && sqlStates.has(code) ? code : null, nodeCategory: pg ? null : nodeCategory }), sites: Object.freeze([]), truncated: false })
}
} catch { /* Diagnostic projection cannot change the original outcome. */ }
return unknownDiagnostic
}
export function carryCapturedPollError<T extends Error>(replacement: T, captured: PollErrorDiagnostic | undefined, site: Site): T {
try {
if (!key(replacement) || !sites.includes(site)) return replacement
// Rebuild only closed fields: never spread caller objects or retain errors.
const value = captured && !types.isProxy(captured) ? captured : undefined
const rawOrigin = value ? own(value, "origin") : undefined
const origin = rawOrigin && typeof rawOrigin === "object" && !types.isProxy(rawOrigin) ? rawOrigin : undefined
const kind = origin ? own(origin, "kind") : undefined, sql = origin ? own(origin, "sqlState") : undefined, node = origin ? own(origin, "nodeCategory") : undefined
const old = value ? own(value, "sites") : undefined
const previous = Array.isArray(old) && !types.isProxy(old) ? old.filter((item): item is Site => sites.includes(item)).slice(0, 8) : []
const probe = value ? closedProbe(own(value, "probe")) : undefined
const execution = value ? closedExecution(own(value, "execution")) : undefined
const diagnostic: PollErrorDiagnostic = Object.freeze({ version: 1, origin: Object.freeze({ kind: kind === "pg" || kind === "node" ? kind : "other", sqlState: kind === "pg" && typeof sql === "string" && sqlStates.has(sql) ? sql : null, nodeCategory: kind === "node" && typeof node === "string" && Object.values(nodeCategories).includes(node) ? node : null }), sites: Object.freeze([...previous.slice(0, 7), site]), truncated: previous.length >= 8 || !!value && own(value, "truncated") === true, ...(probe ? { probe } : {}), ...(execution ? { execution } : {}) })
if (Buffer.byteLength(JSON.stringify(diagnostic)) <= 768) errors.set(replacement, diagnostic)
} catch { /* No retry, raw logging, property mutation or replacement error. */ }
return replacement
}
export function carryPollError<T extends Error>(replacement: T, original: unknown, site: Site): T {
return carryCapturedPollError(replacement, capturePollError(original), site)
}
export function recordPollExecutionError<T extends Error>(replacement: T, original: unknown, execution: PollExecutionProgress): T {
return carryCapturedPollError(replacement, { ...capturePollError(original), execution }, "poll.exec")
}
export function pollErrorLog(error: unknown, operationId: string, operationType: string): Readonly<{ event: "mcp.poll.error-origin"; operationId: string; provenance: PollErrorDiagnostic }> | null {
try {
if (operationType !== "servers.poll" || typeof operationId !== "string" || !key(error) || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(operationId)) return null
const provenance = errors.get(error)
if (!provenance) return null
const result = Object.freeze({ event: "mcp.poll.error-origin" as const, operationId, provenance })
return Buffer.byteLength(JSON.stringify(result)) <= 1024 ? result : null
} catch { return null }
}