openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
428 lines (427 loc) • 20 kB
JavaScript
import { t as runWithAsyncStore } from "./async-store-C6naia_Y.mjs";
import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import { i as getActiveGatewayRootWorkCount, n as createShutdownCleanupController, o as reloadWaitingRoots, r as currentRootWork, s as subscriptionRootWork, t as GATEWAY_WORK_ADMISSION_STATE } from "./gateway-work-admission-state-X3ZM0tLe.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { o as getAsyncWorkSignal, t as AsyncWorkScope } from "./async-work-scope-BXagjUap.mjs";
import { n as notifyListeners, r as registerListener } from "./listeners-Cb2-CnP8.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
//#region src/process/gateway-work-admission.ts
var GatewayDrainingError = class extends Error {
constructor(e = gatewayWorkAdmissionMessage()) {
super(e);
this.name = "GatewayDrainingError";
}
};
const admissionLog = createSubsystemLogger("gateway/admission");
/** This root awaits the same reload transaction; retain admission while excluding its wait. */
function runWithGatewayReloadWaitingRoot(e) {
const t = currentRootWork.getStore();
return t ? runWithAsyncStore(reloadWaitingRoots, /* @__PURE__ */ new Set([...reloadWaitingRoots.getStore() ?? [], t]), e) : e();
}
function gatewayWorkAdmissionMessage() {
if (GATEWAY_WORK_ADMISSION_STATE.restartDrainReason?.startsWith("stop (")) return "Gateway is shutting down. Please try again once it is back online.";
if (isGatewayRestartDraining()) return "Gateway is restarting. Please try again shortly.";
if (GATEWAY_WORK_ADMISSION_STATE.suspendPhase !== "accepting") return "Gateway is temporarily paused. Please try again shortly.";
return "Gateway is temporarily unavailable. Please try again shortly.";
}
const GATEWAY_ROOT_WORK_ORIGIN_MAX_CHARS = 80;
function createGatewayRootWorkAdmission(e, t = false) {
const n = {
origin: e.trim().replaceAll(/\s+/g, " ").slice(0, GATEWAY_ROOT_WORK_ORIGIN_MAX_CHARS) || "gateway",
references: 1,
released: false,
...subscriptionRootWork.getStore() ? { subscription: true } : {}
};
GATEWAY_WORK_ADMISSION_STATE.activeRootWork.add(n);
return {
ownsRoot: true,
release: createGatewayRootWorkRelease(n),
run: async (e) => await runWithAsyncStore(currentRootWork, n, () => t ? runWithDetachedAsyncWork(n, e) : e())
};
}
function createGatewayRootWorkRelease(e) {
let t = false;
return () => {
if (t || e.released) return;
t = true;
e.references -= 1;
if (e.references > 0) return;
e.released = true;
GATEWAY_WORK_ADMISSION_STATE.activeRootWork.delete(e);
notifyGatewayRootWorkRelease(e, "settled");
};
}
function notifyGatewayRootWorkRelease(e, t) {
const n = e.releaseObservers;
delete e.releaseObservers;
if (n) notifyListeners([...n], t, (e) => {
admissionLog.warn(`root work release observer failed: ${String(e)}`);
});
}
/** Observes the exact root's final release without extending its lifetime. */
function captureGatewayRootWorkReleaseObserver() {
const e = currentRootWork.getStore();
if (!e || e.released || !GATEWAY_WORK_ADMISSION_STATE.activeRootWork.has(e)) return null;
return (t) => {
if (e.released) {
t(e.retiredByReset ? "reset" : "settled");
return () => {};
}
return registerListener(e.releaseObservers ??= /* @__PURE__ */ new Set(), t);
};
}
async function runWithDetachedAsyncWork(e, t) {
e.references += 1;
const n = createGatewayRootWorkRelease(e);
const r = createDeferredCore();
const i = new AsyncWorkScope();
i.run(async () => {
try {
r.resolve(await i.track(t));
} catch (e) {
r.reject(e);
} finally {
try {
await AsyncWorkScope.runWhenAllIdle(() => [i], () => i.drain());
} finally {
n();
}
}
}).catch(r.reject);
return await r.promise;
}
function invalidateSuspendAdmission() {
const e = GATEWAY_WORK_ADMISSION_STATE.suspendInvalidated;
GATEWAY_WORK_ADMISSION_STATE.suspendInvalidated = void 0;
GATEWAY_WORK_ADMISSION_STATE.suspendPhase = "accepting";
GATEWAY_WORK_ADMISSION_STATE.suspendGeneration += 1;
resolveSuspendOpenWaiters();
if (GATEWAY_WORK_ADMISSION_STATE.restartDrainReason === void 0) admissionLog.info(`admission reopened: suspend phase ${GATEWAY_WORK_ADMISSION_STATE.suspendAttribution} exit=invalidated`);
else admissionLog.info(`suspension superseded: ${GATEWAY_WORK_ADMISSION_STATE.suspendAttribution} exit=restart`);
GATEWAY_WORK_ADMISSION_STATE.suspendAttribution = void 0;
e?.();
notifyGatewaySuspendAdmission();
}
/** Reopens a reversible restart-signal fence; one-way restart drain retains admission. */
function rollbackGatewayRestartSignalFence() {
if (GATEWAY_WORK_ADMISSION_STATE.restartDrainReason !== void 0 || !GATEWAY_WORK_ADMISSION_STATE.restartSignalPending) return false;
GATEWAY_WORK_ADMISSION_STATE.restartSignalPending = false;
GATEWAY_WORK_ADMISSION_STATE.restartSignalGeneration += 1;
resolveSuspendOpenWaiters();
if (GATEWAY_WORK_ADMISSION_STATE.suspendPhase === "accepting") admissionLog.info("admission reopened: restart-signal fence");
else admissionLog.info("restart-signal fence cleared; suspension remains closed");
return true;
}
function resolveSuspendOpenWaiters() {
const e = Array.from(GATEWAY_WORK_ADMISSION_STATE.suspendOpenWaiters);
GATEWAY_WORK_ADMISSION_STATE.suspendOpenWaiters.clear();
for (const t of e) t();
}
/** True while restart signal/drain or host suspension rejects new process work. */
function isGatewayWorkAdmissionClosed() {
return isGatewayRestartDraining() || GATEWAY_WORK_ADMISSION_STATE.suspendPhase !== "accepting";
}
/** Existing admitted roots may finish spawning subordinate command/session work.
* New async chains still see the global fence, preserving refuse-only suspension. */
function isGatewaySubordinateWorkAdmissionClosed() {
if (isGatewayRestartDraining()) return true;
const e = currentRootWork.getStore();
if (e) return e.released;
return GATEWAY_WORK_ADMISSION_STATE.suspendPhase !== "accepting";
}
function getGatewaySuspendAdmissionPhase() {
return GATEWAY_WORK_ADMISSION_STATE.suspendPhase;
}
function onGatewaySuspendAdmissionChange(e) {
return registerListener(GATEWAY_WORK_ADMISSION_STATE.suspendListeners, e);
}
function notifyGatewaySuspendAdmission() {
const e = getGatewaySuspendAdmissionPhase();
const t = Array.from(GATEWAY_WORK_ADMISSION_STATE.suspendListeners);
notifyListeners(t, e, (e) => {
admissionLog.warn(`suspension observer failed: ${String(e)}`);
});
}
function isGatewayRestartDraining() {
return GATEWAY_WORK_ADMISSION_STATE.restartDrainReason !== void 0 || GATEWAY_WORK_ADMISSION_STATE.restartSignalPending;
}
/** Resolves when one-way drain commits or the reversible signal fence clears. */
async function waitForGatewayRestartFenceSettlement() {
if (!GATEWAY_WORK_ADMISSION_STATE.restartSignalPending) return;
await new Promise((e) => {
GATEWAY_WORK_ADMISSION_STATE.suspendOpenWaiters.add(e);
});
await waitForGatewayRestartFenceSettlement();
}
function getGatewayRestartDrainSignal() {
return GATEWAY_WORK_ADMISSION_STATE.restartDrainController.signal;
}
/** Grace has settled; release idle retention without revoking accepted cleanup work. */
function getGatewayShutdownCleanupSignal() {
return GATEWAY_WORK_ADMISSION_STATE.shutdownCleanupController.signal;
}
function beginGatewayShutdownCleanup() {
if (GATEWAY_WORK_ADMISSION_STATE.restartDrainReason !== void 0) GATEWAY_WORK_ADMISSION_STATE.shutdownCleanupController.abort();
}
function isGatewayRestartDrainError(e) {
if (!isGatewayRestartDraining()) return false;
try {
return e instanceof GatewayDrainingError;
} catch {
return false;
}
}
/** Restart drain is one-way until the in-process restart resets runtime state. */
function markGatewayRestartDraining(e = "restart") {
if (GATEWAY_WORK_ADMISSION_STATE.restartDrainReason !== void 0) {
if (e.startsWith("stop (")) GATEWAY_WORK_ADMISSION_STATE.restartDrainReason = e;
return;
}
GATEWAY_WORK_ADMISSION_STATE.restartSignalPending = false;
GATEWAY_WORK_ADMISSION_STATE.restartSignalGeneration += 1;
GATEWAY_WORK_ADMISSION_STATE.restartDrainReason = e;
GATEWAY_WORK_ADMISSION_STATE.restartDrainController.abort(new GatewayDrainingError());
resolveSuspendOpenWaiters();
admissionLog.info(`admission closed: ${e}`);
if (GATEWAY_WORK_ADMISSION_STATE.suspendPhase !== "accepting") invalidateSuspendAdmission();
}
/**
* Blocks suspension across signal emission until the run loop starts restart drain.
* Returns null when another owner already holds the fence or one-way drain is active.
* Callers must not invent a stand-in lease: a dead rollback handle is how the fence
* can stay closed after the real owner is lost.
*/
function beginGatewayRestartSignalAdmission() {
if (isGatewayRestartDraining()) return null;
GATEWAY_WORK_ADMISSION_STATE.restartSignalPending = true;
const e = ++GATEWAY_WORK_ADMISSION_STATE.restartSignalGeneration;
admissionLog.info("admission closed: restart-signal fence");
return { rollback: () => {
if (!GATEWAY_WORK_ADMISSION_STATE.restartSignalPending || GATEWAY_WORK_ADMISSION_STATE.restartSignalGeneration !== e) return false;
return rollbackGatewayRestartSignalFence();
} };
}
/** Root RPC/timer admission. Nested work in the same async chain counts once. */
function tryBeginGatewayRootWorkAdmission(e = "gateway") {
const t = currentRootWork.getStore();
if (t && !t.released) return {
ownsRoot: false,
release: () => {},
run: async (e) => await e()
};
return tryBeginGatewayIndependentRootWorkAdmission(e);
}
/**
* Tracks a host-selected restart-startup recovery handshake without reopening admission.
* The caller still owns frame/auth validation; this lease grants no method authority.
*/
function tryBeginGatewayRestartStartupRootWorkAdmission() {
if (!isGatewayRestartDraining() || GATEWAY_WORK_ADMISSION_STATE.suspendPhase !== "accepting") return null;
return createGatewayRootWorkAdmission("restart-startup");
}
/**
* Admits only the exact predecessor-bound restart selected by the RPC router.
* The held root preserves signal-to-drain ordering without reopening suspension.
*/
function tryBeginGatewayPreparedRestartRootWorkAdmission() {
if (isGatewayRestartDraining() || GATEWAY_WORK_ADMISSION_STATE.suspendPhase !== "prepared" || getActiveGatewayRootWorkCount() > 0) return null;
return createGatewayRootWorkAdmission("restart-prepared");
}
/** Independent roots count separately even when launched by an admitted parent. */
function tryBeginGatewayIndependentRootWorkAdmission(e = "independent", t = {}) {
if (isGatewayWorkAdmissionClosed()) return null;
return createGatewayRootWorkAdmission(e, t.detachedWork === true);
}
async function waitForGatewayWorkAdmissionChange(e) {
const t = createDeferredCore();
GATEWAY_WORK_ADMISSION_STATE.suspendOpenWaiters.add(t.resolve);
try {
await racePromiseWithAbortSignal(t.promise, e);
} finally {
GATEWAY_WORK_ADMISSION_STATE.suspendOpenWaiters.delete(t.resolve);
}
}
/** Waits through a prepared lease, then joins the root-work set atomically. */
async function beginGatewayRootWorkAdmissionWhenOpen(e = "gateway", t) {
while (true) {
t?.throwIfAborted();
if (GATEWAY_WORK_ADMISSION_STATE.restartDrainReason !== void 0) throw new GatewayDrainingError();
const n = tryBeginGatewayRootWorkAdmission(e);
if (n) return n;
await waitForGatewayWorkAdmissionChange(t);
}
}
/** Keeps the caller's async-resource owner, including server shutdown cancellation. */
function runWithGatewayIndependentRootWorkAdmission(e, t, n) {
return runWithGatewayNewRootWorkAdmission(e, t, n, false);
}
/** Delayed producers outlive their triggering request and own their async cleanup. */
function runWithGatewayDetachedWorkAdmission(e, t, n) {
return runWithGatewayNewRootWorkAdmission(e, t, n, true);
}
async function runWithGatewayNewRootWorkAdmission(e, t, n, r) {
while (true) {
n?.throwIfAborted();
if (GATEWAY_WORK_ADMISSION_STATE.restartDrainReason !== void 0) throw new GatewayDrainingError();
const i = isGatewayWorkAdmissionClosed() ? null : createGatewayRootWorkAdmission(t ?? "independent", r);
if (i) try {
return await i.run(e);
} finally {
i.release();
}
await waitForGatewayWorkAdmissionChange(n);
}
}
/** Re-admits preserved work whose inherited root was retired before it could run. */
const runWithGatewayRootWorkReadmission = (e) => currentRootWork.getStore()?.retiredByReset ? runWithGatewayIndependentRootWorkAdmission(e, "runtime:readmission") : e();
/**
* Detaches required follow-up from the current admitted transaction.
* A live parent synchronously reserves a tracked root even after restart or
* suspension closes admission. The detached root keeps its caller origin
* because it can outlive the parent; otherwise the normal fence applies.
*/
function runWithGatewayIndependentRootWorkContinuation(e, t = "independent") {
return runWithGatewayRootWorkContinuation(e, t, false);
}
/**
* Detached continuations own their async lifetime: like the independent
* continuation, a live parent synchronously reserves a tracked root even
* across closed admission fences, but the callback runs inside a fresh
* detached async work scope so deferred work survives the caller's scope
* closing instead of inheriting it.
*/
function runWithGatewayDetachedWorkContinuation(e, t = "independent") {
return runWithGatewayRootWorkContinuation(e, t, true);
}
function runWithGatewayRootWorkContinuation(e, t, n) {
const r = currentRootWork.getStore();
if (!r || r.released) return n ? runWithGatewayDetachedWorkAdmission(e, t) : runWithGatewayIndependentRootWorkAdmission(e, t, getAsyncWorkSignal());
const i = createGatewayRootWorkAdmission(t, n);
return i.run(e).finally(i.release);
}
function createGatewayRootWorkAdmissionContinuationScope(e) {
const t = currentRootWork.getStore();
if (!t || t.released || !GATEWAY_WORK_ADMISSION_STATE.activeRootWork.has(t)) return null;
if (e) t.references += 1;
const n = e ? createGatewayRootWorkRelease(t) : void 0;
let r = false;
const enter = () => {
if (r || t.released || !GATEWAY_WORK_ADMISSION_STATE.activeRootWork.has(t)) throw new GatewayDrainingError("gateway root work continuation is no longer active");
t.references += 1;
return createGatewayRootWorkRelease(t);
};
return {
release: () => {
r = true;
n?.();
},
run: async (e) => {
const n = enter();
try {
return await runWithAsyncStore(currentRootWork, t, e);
} finally {
n();
}
},
runSync: (e) => {
const n = enter();
try {
return runWithAsyncStore(currentRootWork, t, e);
} finally {
n();
}
}
};
}
/** Borrows exact root ownership without extending the creating request's lifetime. */
function captureGatewayRootWorkAdmissionContinuationScope() {
return createGatewayRootWorkAdmissionContinuationScope(false);
}
/** Retains exact root ownership for work that intentionally outlives its handler. */
function retainGatewayRootWorkAdmissionContinuationScope() {
return createGatewayRootWorkAdmissionContinuationScope(true);
}
/** Transfers an admitted request root to work that intentionally outlives its handler. */
function retainGatewayRootWorkAdmissionContinuation() {
return retainGatewayRootWorkAdmissionContinuationScope()?.release ?? null;
}
/** Retains an existing root for started effects without admitting or parking unrooted work. */
async function runWithRetainedGatewayRootWork(e) {
const t = retainGatewayRootWorkAdmissionContinuation();
try {
return await e();
} finally {
t?.();
}
}
/**
* Opens a long-lived subscription whose roots do not defer restart or suspension.
* The caller must retire it on the restart drain signal; drain then waits for its close.
*/
function runAsGatewaySubscription(e) {
return subscriptionRootWork.run(true, e);
}
/** Starts process-lifetime work without inheriting the request root that created it. */
function runOutsideGatewayRootWorkAdmission(e) {
return currentRootWork.getStore() === void 0 ? e() : currentRootWork.exit(e);
}
/** Atomically closes new suspension admission before synchronous inspection. */
function tryBeginGatewaySuspendAdmission(e, t) {
if (isGatewayWorkAdmissionClosed()) return null;
GATEWAY_WORK_ADMISSION_STATE.suspendPhase = "preparing";
const n = ++GATEWAY_WORK_ADMISSION_STATE.suspendGeneration;
GATEWAY_WORK_ADMISSION_STATE.suspendInvalidated = e;
const r = JSON.stringify(t ?? {
owner: "internal",
leaseId: String(n),
caller: "in-process",
reason: "suspend"
});
GATEWAY_WORK_ADMISSION_STATE.suspendAttribution = r;
admissionLog.info(`admission closed: suspend phase ${r}`);
notifyGatewaySuspendAdmission();
const transition = (e, t, i) => {
if (GATEWAY_WORK_ADMISSION_STATE.suspendGeneration !== n || GATEWAY_WORK_ADMISSION_STATE.suspendPhase !== e) return false;
GATEWAY_WORK_ADMISSION_STATE.suspendPhase = t;
if (t === "accepting") {
GATEWAY_WORK_ADMISSION_STATE.suspendInvalidated = void 0;
resolveSuspendOpenWaiters();
GATEWAY_WORK_ADMISSION_STATE.suspendAttribution = void 0;
admissionLog.info(`admission reopened: suspend phase ${r} exit=${i}`);
}
notifyGatewaySuspendAdmission();
return true;
};
return {
drain: () => transition("preparing", "draining"),
commit: () => transition("preparing", "prepared") || transition("draining", "prepared"),
rollback: (e = "rollback") => transition("preparing", "accepting", e),
release: (e = "released") => transition("draining", "accepting", e) || transition("prepared", "accepting", e)
};
}
/** Clears restart/suspend admission during SIGUSR2 and isolated tests. */
function resetGatewayWorkAdmission() {
GATEWAY_WORK_ADMISSION_STATE.restartDrainController.abort(new GatewayDrainingError("gateway runtime reset"));
for (const e of GATEWAY_WORK_ADMISSION_STATE.activeRootWork) {
e.references = 0;
e.retiredByReset = true;
e.released = true;
notifyGatewayRootWorkRelease(e, "reset");
}
GATEWAY_WORK_ADMISSION_STATE.activeRootWork.clear();
GATEWAY_WORK_ADMISSION_STATE.restartDrainReason = void 0;
GATEWAY_WORK_ADMISSION_STATE.restartDrainController = new AbortController();
GATEWAY_WORK_ADMISSION_STATE.shutdownCleanupController.abort();
GATEWAY_WORK_ADMISSION_STATE.shutdownCleanupController = createShutdownCleanupController();
GATEWAY_WORK_ADMISSION_STATE.restartSignalPending = false;
GATEWAY_WORK_ADMISSION_STATE.restartSignalGeneration += 1;
if (GATEWAY_WORK_ADMISSION_STATE.suspendPhase !== "accepting") invalidateSuspendAdmission();
else {
GATEWAY_WORK_ADMISSION_STATE.suspendGeneration += 1;
GATEWAY_WORK_ADMISSION_STATE.suspendInvalidated = void 0;
}
resolveSuspendOpenWaiters();
}
//#endregion
export { tryBeginGatewayPreparedRestartRootWorkAdmission as A, runWithGatewayDetachedWorkContinuation as C, runWithGatewayRootWorkReadmission as D, runWithGatewayReloadWaitingRoot as E, tryBeginGatewayRootWorkAdmission as M, tryBeginGatewaySuspendAdmission as N, runWithRetainedGatewayRootWork as O, waitForGatewayRestartFenceSettlement as P, runWithGatewayDetachedWorkAdmission as S, runWithGatewayIndependentRootWorkContinuation as T, retainGatewayRootWorkAdmissionContinuation as _, captureGatewayRootWorkAdmissionContinuationScope as a, runAsGatewaySubscription as b, getGatewayShutdownCleanupSignal as c, isGatewayRestartDraining as d, isGatewaySubordinateWorkAdmissionClosed as f, resetGatewayWorkAdmission as g, onGatewaySuspendAdmissionChange as h, beginGatewayShutdownCleanup as i, tryBeginGatewayRestartStartupRootWorkAdmission as j, tryBeginGatewayIndependentRootWorkAdmission as k, getGatewaySuspendAdmissionPhase as l, markGatewayRestartDraining as m, beginGatewayRestartSignalAdmission as n, captureGatewayRootWorkReleaseObserver as o, isGatewayWorkAdmissionClosed as p, beginGatewayRootWorkAdmissionWhenOpen as r, getGatewayRestartDrainSignal as s, GatewayDrainingError as t, isGatewayRestartDrainError as u, retainGatewayRootWorkAdmissionContinuationScope as v, runWithGatewayIndependentRootWorkAdmission as w, runOutsideGatewayRootWorkAdmission as x, rollbackGatewayRestartSignalFence as y };