UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

373 lines (372 loc) • 13.2 kB
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs"; import { n as ok, t as err } from "./result-CV1-31DB.mjs"; import { N as tryBeginGatewaySuspendAdmission, d as isGatewayRestartDraining, l as getGatewaySuspendAdmissionPhase, s as getGatewayRestartDrainSignal } from "./gateway-work-admission-79pid1hQ.mjs"; import { t as createGatewayActiveWorkSnapshot } from "./gateway-active-work-2EmwaczJ.mjs"; import { randomUUID } from "node:crypto"; //#region src/infra/gateway-suspend-coordinator.ts const GATEWAY_SUSPEND_TTL_MS = 12e4; const GATEWAY_SUSPEND_DRAIN_BUDGET_MS = 45e3; const GATEWAY_SUSPEND_BUSY_RETRY_AFTER_MS = 2e4; const GATEWAY_SUSPEND_DRAIN_POLL_MS = 5e3; const COORDINATOR_STATE = resolveGlobalSingleton(Symbol.for("openclaw.gatewaySuspendCoordinatorState"), () => ({ current: null, retiredForLifecycleReset: null })); function clearEntryTimer(e) { if (e.timer) { clearTimeout(e.timer); e.timer = void 0; } } function scheduleResume(e, t) { clearEntryTimer(e); e.timer = setTimeout(() => { if (COORDINATOR_STATE.current === e) resumeAndReopen(e, "expired"); }, t); e.timer.unref?.(); } function resumeAndReopen(e, t = "resume") { if (t === "expired") e.warn?.(`gateway suspension ${e.drain ? "drain deadline" : "lease"} expired owner=${JSON.stringify(e.requestId)} leaseId=${JSON.stringify(e.suspensionId)}; reopening admission`); clearEntryTimer(e); resumeSchedulingBeforeReopen({ resumeScheduling: e.resumeScheduling, reopenAdmission: () => e.reopenAdmission(t), isInvalidated: () => COORDINATOR_STATE.current !== e, warn: e.warn }); if (COORDINATOR_STATE.current === e) COORDINATOR_STATE.current = null; } function normalizeExpiredHeldSuspension(e) { if (e.nowMs() < e.expiresAtMs && performance.now() < e.deadlineAtMs) return e; resumeAndReopen(e, "expired"); return COORDINATOR_STATE.current; } function currentSuspension() { const e = COORDINATOR_STATE.current; return e ? normalizeExpiredHeldSuspension(e) : null; } function resumeSchedulingBeforeReopen(e) { if (e.isInvalidated()) return; try { e.resumeScheduling(); } catch (t) { e.warn?.("gateway scheduler resume failed; retry scheduling through cron: " + String(t)); } if (!e.isInvalidated()) e.reopenAdmission(); } function armExpiry(e) { const t = Math.min(e.expiresAtMs - e.nowMs(), e.deadlineAtMs - performance.now()); if (t <= 0) throw new Error("gateway suspension expired during preparation"); scheduleResume(e, Math.ceil(t)); return e; } function renewHeldSuspension(e, t) { e.expiresAtMs = t + GATEWAY_SUSPEND_TTL_MS; e.deadlineAtMs = performance.now() + GATEWAY_SUSPEND_TTL_MS; scheduleResume(e, GATEWAY_SUSPEND_TTL_MS); } function suspensionReady(e, t) { return e ? t.writeCustody.every(({ count: e }) => e === 0) : t.idle; } function refreshHeldSuspension(e) { const t = createGatewayActiveWorkSnapshot(e.inspect, { ignoreTerminalSessions: e.terminalPolicy === "terminate" }); if (COORDINATOR_STATE.current !== e || normalizeExpiredHeldSuspension(e) !== e) return; if (suspensionReady(e.drain, t)) { if (e.commitAdmission?.() === false) throw new Error("gateway suspension admission changed during drain completion"); e.commitAdmission = void 0; } return t; } function heldPrepareResult(e, t) { const n = { suspensionId: e.suspensionId, expiresAtMs: e.expiresAtMs, activeCount: t.counts.totalActive, blockers: t.blockers, writeCustody: t.writeCustody }; return suspensionReady(e.drain, t) ? { status: "ready", ...n } : { status: "draining", ...n, retryAfterMs: GATEWAY_SUSPEND_DRAIN_POLL_MS }; } /** Freeze only idle work; drain preparation leaves running work for committed shutdown. */ function prepareGatewaySuspend(e) { const t = e.terminalPolicy ?? "preserve"; const n = e.drain === true; const r = { ignoreTerminalSessions: t === "terminate" }; const i = (e.nowMs ?? Date.now)(); const a = n ? GATEWAY_SUSPEND_DRAIN_BUDGET_MS : GATEWAY_SUSPEND_TTL_MS; const o = performance.now() + a; const s = currentSuspension(); if (s) { if (s.requestId !== e.requestId || s.terminalPolicy !== t || s.drain !== n) return { status: "conflict", expiresAtMs: s.expiresAtMs }; if (!s.drain && !s.handoff) { s.nowMs = e.nowMs ?? Date.now; renewHeldSuspension(s, i); } const r = refreshHeldSuspension(s); if (!r) throw new Error("gateway suspension changed during preparation"); return heldPrepareResult(s, r); } const c = {}; const l = (e.createSuspensionId ?? randomUUID)(); let u = false; const d = tryBeginGatewaySuspendAdmission(() => { u = true; const e = COORDINATOR_STATE.current; if (e?.owner !== c) return; clearEntryTimer(e); COORDINATOR_STATE.current = null; COORDINATOR_STATE.retiredForLifecycleReset = e; const t = getGatewayRestartDrainSignal(); if (t.aborted) { e.handoff = void 0; e.shutdown = { signal: t, phase: "interrupting" }; } }, { owner: e.requestId, leaseId: l, caller: e.caller ?? "in-process", reason: n ? "drain" : "freeze" }); if (!d) { const t = createGatewayActiveWorkSnapshot(e.inspect, r); return { status: "busy", reason: "gateway-draining", retryAfterMs: GATEWAY_SUSPEND_BUSY_RETRY_AFTER_MS, activeCount: t.counts.totalActive, blockers: t.blockers, writeCustody: t.writeCustody }; } let f = false; let p = d.rollback; const resume = () => resumeSchedulingBeforeReopen({ resumeScheduling: e.resumeScheduling, reopenAdmission: p, isInvalidated: () => u, warn: e.warn }); try { e.pauseScheduling(); f = true; const s = createGatewayActiveWorkSnapshot(e.inspect, r); if ((e.nowMs ?? Date.now)() >= i + a || performance.now() >= o) throw new Error("gateway suspension expired during preparation"); if (!s.idle && !n) { resume(); f = false; return { status: "busy", reason: "active-work", retryAfterMs: GATEWAY_SUSPEND_BUSY_RETRY_AFTER_MS, activeCount: s.counts.totalActive, blockers: s.blockers, writeCustody: s.writeCustody }; } const u = suspensionReady(n, s); if (!(u ? d.commit : d.drain)()) throw new Error("gateway suspension admission changed during preparation"); p = d.release; const m = i + a; const h = armExpiry({ owner: c, requestId: e.requestId, terminalPolicy: t, drain: n, suspensionId: l, expiresAtMs: m, deadlineAtMs: o, inspect: e.inspect, commitAdmission: u ? void 0 : d.commit, reopenAdmission: p, resumeScheduling: e.resumeScheduling, nowMs: e.nowMs ?? Date.now, warn: e.warn }); COORDINATOR_STATE.current = h; return heldPrepareResult(h, s); } catch (e) { if (f) resume(); else p(); throw e; } } /** Late final writes share the original 30-second drain budget, never its cleanup grace. */ async function requestGatewaySuspendHandoff(e) { e.assertCurrent(); const t = armGatewaySuspendHandoff(e); if (t.ok || !t.error.details?.terminalPersistence) return t; const n = COORDINATOR_STATE.current; if (!n?.drain) return t; while (COORDINATOR_STATE.current === n && e.owner.isCurrent() && (n.inspect?.getTerminalPersistence?.() ?? 0) > 0) { const e = Math.min(n.expiresAtMs - n.nowMs(), n.deadlineAtMs - performance.now()) - 15e3; if (e <= 0) break; await new Promise((t) => { setTimeout(t, Math.min(250, e)); }); } e.assertCurrent(); return armGatewaySuspendHandoff(e); } function handoffRefusal(e, t) { if (COORDINATOR_STATE.current !== e || e.nowMs() >= e.expiresAtMs || performance.now() >= e.deadlineAtMs || !t.isCurrent()) return { message: "gateway suspension or host iteration changed" }; if (!e.inspect?.getTerminalPersistence) return { message: "gateway terminal persistence inspection is unavailable" }; const n = createGatewayActiveWorkSnapshot(e.inspect, { ignoreTerminalSessions: e.terminalPolicy === "terminate" }); if (n.counts.terminalPersistence > 0) { const t = { count: n.counts.terminalPersistence, ...e.inspect.getTerminalPersistenceDiagnostics?.() ?? { oldestAgeMs: null, runIds: [] } }; return { message: `gateway terminal persistence is still pending: ${JSON.stringify(t)}`, details: { terminalPersistence: t } }; } if (n.writeCustody.some(({ count: e }) => e > 0)) return { message: "gateway write custody is still pending" }; } /** The authenticated handler verifies the process target before this synchronous commit. */ function armGatewaySuspendHandoff(e) { const t = e.commit ? getRestartingSuspension() : void 0; if (t?.suspensionId === e.suspensionId && t.committedStopOwner === e.owner) return ok({ status: "committed", suspensionId: t.suspensionId, expiresAtMs: t.expiresAtMs }); const n = COORDINATOR_STATE.current; if (!n || n.suspensionId !== e.suspensionId) return err({ message: "gateway suspension id does not match" }); const r = handoffRefusal(n, e.owner); if (r) return err(r); if (n.handoff && n.handoff !== e.owner) return err({ message: "gateway suspension already belongs to another host iteration" }); if (e.commit) { if (!e.owner.commitStop) return err({ message: "gateway host does not support committed suspension stop" }); const t = handoffRefusal(n, e.owner); if (t) return err(t); n.handoff = e.owner; try { e.owner.commitStop(); } catch { return err({ message: "gateway suspension stop commitment outcome is uncertain" }); } const r = getGatewayRestartDrainSignal(); if (COORDINATOR_STATE.retiredForLifecycleReset !== n || !r.aborted || n.shutdown?.signal !== r || !isGatewayRestartDraining()) return err({ message: "gateway suspension stop commitment outcome is uncertain" }); n.committedStopOwner = e.owner; return ok({ status: "committed", suspensionId: n.suspensionId, expiresAtMs: n.expiresAtMs }); } n.handoff = e.owner; return ok({ status: "armed", suspensionId: n.suspensionId, expiresAtMs: n.expiresAtMs }); } /** Consume synchronously before restart drain invalidates suspension or retires the host. */ function consumeGatewaySuspendHandoff(e) { const t = COORDINATOR_STATE.current; if (!t || !e || t.handoff !== e) return ok(false); t.handoff = void 0; const n = handoffRefusal(t, e); return n ? err(n.message) : ok(true); } function disarmGatewaySuspendHandoff(e) { const t = COORDINATOR_STATE.current; if (t?.handoff === e) t.handoff = void 0; } function getRestartingSuspension() { const e = COORDINATOR_STATE.retiredForLifecycleReset; return e?.shutdown?.signal === getGatewayRestartDrainSignal() ? e : void 0; } /** Control reconnects retain authentication and never admit node or worker work. */ function isGatewaySuspendControlAvailable() { const e = getGatewaySuspendAdmissionPhase(); return getRestartingSuspension()?.shutdown?.phase === "interrupting" || !isGatewayRestartDraining() && (e === "draining" || e === "prepared"); } /** Records teardown without renewing the retired lease or restoring its authority. */ function markGatewaySuspendExiting() { const e = getRestartingSuspension(); if (e?.shutdown) e.shutdown.phase = "exiting"; } function getGatewaySuspendStatus(e, t = false) { const n = getRestartingSuspension(); const r = n ?? currentSuspension(); if (!r) return { status: "running" }; if (r.suspensionId !== e) return { status: "conflict", expiresAtMs: r.expiresAtMs }; const i = n ? createGatewayActiveWorkSnapshot(r.inspect, { ignoreTerminalSessions: r.terminalPolicy === "terminate" }) : refreshHeldSuspension(r); if (!i) return getGatewaySuspendStatus(e, t); if (n || !suspensionReady(r.drain, i)) return { status: "draining", ...t ? { ownerId: r.requestId, phase: n ? n.shutdown.phase : "draining" } : {}, expiresAtMs: r.expiresAtMs, activeCount: i.counts.totalActive, blockers: i.blockers, writeCustody: i.writeCustody, retryAfterMs: GATEWAY_SUSPEND_DRAIN_POLL_MS }; return { status: "ready", ...t ? { ownerId: r.requestId } : {}, expiresAtMs: r.expiresAtMs, writeCustody: i.writeCustody }; } function resumeGatewaySuspend(e) { const t = getRestartingSuspension(); if (t) return { ok: false, reason: t.suspensionId === e ? "gateway-restarting" : "suspension-mismatch" }; const n = currentSuspension(); if (n && n.suspensionId !== e) return { ok: false, reason: "suspension-mismatch" }; if (n) resumeAndReopen(n); return { ok: true, status: "running", resumed: n !== null }; } function resetGatewaySuspendCoordinatorForLifecycleRestart() { const e = COORDINATOR_STATE.current; const t = COORDINATOR_STATE.retiredForLifecycleReset; COORDINATOR_STATE.current = null; COORDINATOR_STATE.retiredForLifecycleReset = null; const n = e && e !== t ? [e, t] : [e ?? t]; for (const e of n) { if (!e) continue; clearEntryTimer(e); try { e.resumeScheduling(); } catch (t) { e.warn?.(`gateway scheduler resume failed during lifecycle reset: ${String(t)}`); } e.reopenAdmission("lifecycle-reset"); } } //#endregion export { markGatewaySuspendExiting as a, resetGatewaySuspendCoordinatorForLifecycleRestart as c, isGatewaySuspendControlAvailable as i, resumeGatewaySuspend as l, disarmGatewaySuspendHandoff as n, prepareGatewaySuspend as o, getGatewaySuspendStatus as r, requestGatewaySuspendHandoff as s, consumeGatewaySuspendHandoff as t };