openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
397 lines (396 loc) • 16.5 kB
JavaScript
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { t as runInDetachedAsyncContext } from "./detached-async-context-D_mi-wUl.mjs";
import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs";
import { a as getOpenClawDatabaseMaintenanceScope, i as getOpenClawDatabaseMaintenanceResourceScope } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs";
import { n as isPostgresSqlConnection, r as sqlPublicationAnchor } from "./sql-connection-Beiyg5Dt.mjs";
import { c as inspectDatabasePathIdentitySync, u as normalizeDatabasePath } from "./sqlite-worker-identity-BH8ZkJU9.mjs";
import { B as revokeSqliteDatabaseAdmissionsForPath, y as prepareSqliteDatabaseCleanClose } from "./sqlite-database-admission-DQIqro3d.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { r as hasSqlitePostCommitScope, t as deferSqlitePostCommitPublication } from "./sqlite-post-commit-BrUVQObC.mjs";
import { r as disposeNodeSqliteDependents, t as assertNodeSqliteDisposalAllowed } from "./kysely-sync-cache-state-Bb1gOqQO.mjs";
import { a as setSqliteBusyTimeout } from "./sqlite-busy-timeout-BEDmnGR_.mjs";
import { o as registerSqliteCacheExitClose } from "./sqlite-wal-DGPrWPl6.mjs";
import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs";
import { a as matchesAgentDatabaseClose, b as releaseAgentCreationClaimHandle, l as revokeAgentDatabaseResources, n as drainAgentDatabaseResources, u as withAgentDatabaseCloseFence } from "./openclaw-agent-db-resources-Dp8HvLsg.mjs";
import { l as releaseAgentDeletionDatabaseCleanup } from "./agent-deletion-cleanup-BweMIhGD.mjs";
import { P as createSqliteTerminalOpenLatch } from "./openclaw-state-db-cache-CkwtTqzF.mjs";
import { n as resolveAgentDatabaseIdleHandleTtlMs } from "./sqlite-handle-lifecycle-Dw0xPd8_.mjs";
import { a as readOpenClawAgentDatabaseIdentity, i as isOpenClawAgentDatabasePathCurrent, r as findOpenClawAgentDatabaseIdentity } from "./openclaw-agent-db-identity-C8MGU8lp.mjs";
import { r as assertAgentDatabaseMaintenanceAuthority } from "./openclaw-agent-db-maintenance-authority-C4Yhyki9.mjs";
import { c as getGatewayShutdownCleanupSignal } from "./gateway-work-admission-79pid1hQ.mjs";
import { i as retainAgentDatabase, t as agentDatabaseBorrowers } from "./openclaw-agent-db-borrower-BrziJlyo.mjs";
import { c as hasAgentDatabaseMaintenanceAuthority, f as readOpenClawAgentDatabaseWorkerLeaseReceiptFromClaim, h as releaseOpenClawAgentDatabaseLease } from "./openclaw-agent-db-lease-BZhGt_sk.mjs";
import { m as invalidateOpenClawAgentDatabaseValidation, s as clearOpenClawAgentDatabaseValidationCache } from "./openclaw-agent-db-validation-cache-lnjWuypr.mjs";
import { statSync } from "node:fs";
import path from "node:path";
import { isMainThread, threadId } from "node:worker_threads";
import { performance } from "node:perf_hooks";
import { addAbortListener } from "node:events";
//#region src/state/openclaw-agent-db-close.ts
/** Native handle close uses the lifecycle owner's existing leases and validation. */
function createAgentDatabaseHandleCloser(e) {
return function closeCachedOpenClawAgentDatabase(t) {
try {
var n = _usingCtx();
const r = e.leases.get(t.path);
const i = !t.db.isOpen;
const a = t.walMaintenance.health?.state === "error";
const o = isPostgresSqlConnection(t.db);
const s = sqlPublicationAnchor(t.db);
assertNodeSqliteDisposalAllowed(s);
const c = n.u(!i && !o ? prepareSqliteDatabaseCleanClose(s) : void 0);
let l;
let u;
try {
if (!i && !o) setSqliteBusyTimeout(s, 0);
disposeNodeSqliteDependents(s);
t.walMaintenance.close({ checkpointMode: "TRUNCATE" });
const n = !e.failures.has(t.path) && !a && t.walMaintenance.health?.state !== "error";
const r = !i && n && isOpenClawAgentDatabasePathCurrent(t);
u = n && (i || r);
if (t.db.isOpen) t.db.close();
if (o && s.isOpen) s.close();
if (r && !o) {
const { canonicalPath: e } = readOpenClawAgentDatabaseIdentity(t);
const n = (statSync(`${e}-wal`, { throwIfNoEntry: false })?.size ?? 0) === 0;
if (c && n) l = {
path: t.path,
publishSeal: c.publish
};
}
} catch (e) {
if (r) {
invalidateOpenClawAgentDatabaseValidation(t.path);
revokeSqliteDatabaseAdmissionsForPath(t.path);
}
throw e;
}
if (r) {
releaseOpenClawAgentDatabaseLease(r.leaseId, {
env: r.env,
initializationAgentPaths: [t.path]
}, l ?? (u ? o ? "postgres-closed" : "uncheckpointed" : void 0));
e.leases.delete(t.path);
}
releaseAgentDeletionDatabaseCleanup(t);
releaseAgentCreationClaimHandle(t);
e.idleTimers.get(t.db)?.[Symbol.dispose]();
e.idleTimers.delete(t.db);
} catch (e) {
n.e = e;
} finally {
n.d();
}
};
}
//#endregion
//#region src/state/openclaw-agent-db-lifecycle.ts
const agentDbLog = createSubsystemLogger("state/agent-db");
const OPENCLAW_AGENT_DB_SLOW_OPEN_MS = 1e3;
const cache = resolveGlobalSingleton(Symbol.for("openclaw.agentDatabaseLifecycle"), () => ({
...agentDatabaseBorrowers,
leases: /* @__PURE__ */ new Map(),
terminal: createSqliteTerminalOpenLatch({ closeByPath: (e) => closeOpenClawAgentDatabaseByPath(e) }),
unregisterExitClose: null,
pending: /* @__PURE__ */ new Map(),
activePending: /* @__PURE__ */ new Set(),
retainedCloses: /* @__PURE__ */ new Set()
}));
agentDatabaseBorrowers.refreshIdleTimer = refreshAgentDatabaseIdleTimer;
const closeCachedOpenClawAgentDatabase = createAgentDatabaseHandleCloser(cache);
function registerAgentDatabaseHandle(e, t, n) {
cache.leases.set(e.path, {
leaseId: t,
env: n
});
cache.databases.set(e.path, e);
}
/** Queue a non-throwing runtime publication on the outer database commit edge. */
function deferOpenClawAgentPostCommitPublication(e, t) {
if (!hasSqlitePostCommitScope(e.db)) return false;
if (hasAgentDatabaseMaintenanceAuthority()) {
assertAgentDatabaseMaintenanceAuthority();
return false;
}
const n = cache.leases.get(e.path);
if (cache.databases.get(e.path) !== e || !n) throw new Error("Agent post-commit publication requires its admitted database owner");
const r = {
agentId: e.agentId,
path: e.path,
env: { ...n.env }
};
return deferSqlitePostCommitPublication(e.db, () => t(r));
}
function logResourceCloseFailure(e, t) {
agentDbLog.warn("Agent database resource close failed", {
path: e,
error: t
});
}
function unregisterUnusedAgentDatabaseExitClose() {
if (cache.databases.size === 0 && cache.retainedCloses.size === 0) {
cache.unregisterExitClose?.();
cache.unregisterExitClose = null;
}
}
/** Each physical-open generator owns these checkpoints across any integrity await. */
function startAgentDatabaseOpenTiming(e, t, n, r) {
const i = performance.now();
let a = 0;
const o = {
open: 0,
validation: 0,
configuration: 0,
schema: 0,
registration: 0
};
return (s) => {
const c = Math.floor(performance.now() - i);
o[s] = c - a;
a = c;
if (s === "validation" && r.integrityGateReason) agentDbLog.info("agent database integrity gate", {
agentId: e,
path: t,
pid: process.pid,
threadId,
isMainThread,
admissionMode: n,
...r
});
if (s === "registration" && a >= OPENCLAW_AGENT_DB_SLOW_OPEN_MS) agentDbLog.warn("slow OpenClaw agent database open", {
agentId: e,
elapsedMs: a,
path: t,
pid: process.pid,
threadId,
isMainThread,
admissionMode: n,
phaseDurationsMs: o,
...r,
thresholdMs: OPENCLAW_AGENT_DB_SLOW_OPEN_MS
});
};
}
function retainFailedAgentDatabaseClose(e, t, n) {
const r = {
agentId: e,
path: t,
close: () => {
n();
cache.retainedCloses.delete(r);
}
};
cache.retainedCloses.add(r);
getOpenClawDatabaseMaintenanceScope()?.own(r, "agent-handles", r.close);
cache.unregisterExitClose ??= registerSqliteCacheExitClose(closeOpenClawAgentDatabases);
}
function revokePendingAgentDatabaseOpen(e, t) {
for (const n of cache.activePending) if (n.path === e && (t === void 0 || n.agentId === t)) n.controller.abort(/* @__PURE__ */ new Error(`Agent database open was revoked: ${e}`));
}
/** Activity and final borrower release use the same idle or post-grace eviction. */
function refreshAgentDatabaseIdleTimer(e) {
const t = cache.idleTimers.get(e.db);
if (t) {
t.refresh();
return;
}
const n = getGatewayShutdownCleanupSignal();
const closeIdle = () => {
if (cache.databases.get(e.path) !== e) {
cache.idleTimers.get(e.db)?.[Symbol.dispose]();
cache.idleTimers.delete(e.db);
return;
}
if (getOpenClawDatabaseMaintenanceResourceScope(e.db)) return;
if (e.db.isOpen && cache.borrowers.get(e.db)?.size) return;
if (e.db.isOpen && e.db.isTransaction) {
r.refresh();
return;
}
try {
closeCachedOpenClawAgentDatabase(e);
cache.databases.delete(e.path);
cache.failures.delete(e.path);
unregisterUnusedAgentDatabaseExitClose();
} catch (t) {
logResourceCloseFailure(e.path, t);
r.refresh();
}
};
const refresh = () => {
if (n.aborted) runInDetachedAsyncContext(() => queueMicrotask(closeIdle));
else r.refresh();
};
const r = runInDetachedAsyncContext(() => setTimeout(closeIdle, resolveAgentDatabaseIdleHandleTtlMs()));
const i = addAbortListener(n, refresh);
r.unref();
cache.idleTimers.set(e.db, {
refresh,
[Symbol.dispose]() {
clearTimeout(r);
i[Symbol.dispose]();
}
});
}
/** Dispose only this publication; a later admission at the same path is independent. */
async function closeMaintenanceAgentDatabase(e) {
await e.walMaintenance.stop();
if (cache.databases.get(e.path) !== e) return;
closeCachedOpenClawAgentDatabase(e);
cache.databases.delete(e.path);
cache.failures.delete(e.path);
}
/** A lifecycle scope closes its exact connection and retains its borrow until disposal succeeds. */
function createAgentDatabaseScopeOwnedClose(e, t) {
const n = retainAgentDatabase(e.db);
return async () => {
if (cache.databases.get(e.path) === e) await closeOpenClawAgentDatabaseByPathAsync(e.path, e.agentId);
else if (e.db.isOpen) throw new Error(`${t} lost its database close owner.`);
n();
};
}
/** Close one cached agent database identified by its exact resolved pathname. */
function closeOpenClawAgentDatabaseByPath(e, t) {
const n = path.resolve(e);
revokeAgentDatabaseResources({
path: n,
agentId: t
}, logResourceCloseFailure);
revokePendingAgentDatabaseOpen(n, t);
for (const e of cache.retainedCloses) if (e.path === n && (t === void 0 || e.agentId === t)) e.close();
const r = cache.databases.get(n);
if (!r || t !== void 0 && r.agentId !== t) return false;
closeCachedOpenClawAgentDatabase(r);
cache.databases.delete(n);
cache.failures.delete(n);
unregisterUnusedAgentDatabaseExitClose();
return true;
}
/** Capture only the exact claim belonging to this admitted Worker connection. */
function readOpenClawAgentDatabaseWorkerLeaseReceipt(e) {
const t = path.resolve(e);
const n = cache.databases.get(t);
const r = cache.leases.get(t);
if (!n?.db.isOpen || !r || cache.failures.has(t)) throw new Error(`Agent database Worker has no admitted lease: ${t}`);
return readOpenClawAgentDatabaseWorkerLeaseReceiptFromClaim(r.leaseId, {
agentId: n.agentId,
path: n.path,
env: r.env
});
}
/**
* Converge a terminating worker's cached handle and durable lease without
* turning an already committed worker result into an operation failure.
* Callers own a bounded retry policy and must surface an unsettled result.
*/
async function settleOpenClawAgentDatabaseWorkerClose(e) {
const t = path.resolve(e);
const n = [];
const r = cache.databases.get(t);
if (r) {
try {
await r.walMaintenance.stop();
closeCachedOpenClawAgentDatabase(r);
} catch (e) {
n.push(e instanceof Error ? e : new Error(String(e)));
}
if (r.db.isOpen) try {
r.db.close();
} catch (e) {
n.push(e instanceof Error ? e : new Error(String(e)));
}
if (!r.db.isOpen) {
cache.idleTimers.get(r.db)?.[Symbol.dispose]();
cache.idleTimers.delete(r.db);
cache.databases.delete(t);
cache.failures.delete(t);
unregisterUnusedAgentDatabaseExitClose();
}
}
if (!cache.databases.get(t)?.db.isOpen) {
const e = cache.leases.get(t);
if (e) try {
releaseOpenClawAgentDatabaseLease(e.leaseId, {
env: e.env,
initializationAgentPaths: [t]
});
cache.leases.delete(t);
} catch (e) {
n.push(e instanceof Error ? e : new Error(String(e)));
}
}
return {
errors: n,
settled: !cache.databases.get(t)?.db.isOpen && !cache.leases.has(t)
};
}
function closeOpenClawAgentDatabases(e) {
revokeAgentDatabaseResources({ rootPath: e }, logResourceCloseFailure);
for (const t of cache.pending.keys()) if (e === void 0 || isPathInside(e, t)) revokePendingAgentDatabaseOpen(t);
for (const t of cache.retainedCloses) if (e === void 0 || isPathInside(e, t.path)) t.close();
for (const t of cache.databases.keys()) if (e === void 0 || isPathInside(e, t)) closeOpenClawAgentDatabaseByPath(t);
}
/** Latch integrity refusals so later opens fail without rescanning. */
function recordOpenClawAgentDatabaseOpenFailure(e, t) {
cache.terminal.record(e, t);
invalidateOpenClawAgentDatabaseValidation(e);
}
/** Release fixture handles and pathname trust before a test root is recreated. */
function closeOpenClawAgentDatabasesForTest(e) {
closeOpenClawAgentDatabases(e);
clearOpenClawAgentDatabaseValidationCache(e);
cache.terminal.clearAll(e);
}
/** Drain native opens before a lifecycle owner releases shared state or removes its root. */
async function closeOpenClawAgentDatabasesAsync(e) {
const t = { rootPath: e };
await withAgentDatabaseCloseFence(t, async (e) => {
const n = new Set([
...cache.databases.values(),
...cache.activePending,
...cache.retainedCloses
].filter((e) => matchesAgentDatabaseClose(t, e)).map((e) => e.path));
const r = /* @__PURE__ */ new Set([...n, ...e]);
const i = (await Promise.allSettled([...r].map((e) => n.has(e) ? closeOpenClawAgentDatabaseByPathAsync(e) : drainAgentDatabaseResources({
...t,
path: e
}, async () => {})))).flatMap((e) => e.status === "rejected" ? [e.reason] : []);
if (i.length > 0) throw new AggregateError(i, "Agent database close failed");
});
}
/** Drain the exact retained owner before deletion, quarantine, or file replacement. */
async function closeOpenClawAgentDatabaseByPathAsync(e, t) {
const n = {
path: path.resolve(e),
agentId: t
};
revokePendingAgentDatabaseOpen(n.path, t);
return drainAgentDatabaseResources(n, async () => {
const e = [...cache.activePending].filter((e) => matchesAgentDatabaseClose(n, e));
for (const n of e) revokePendingAgentDatabaseOpen(n.path, t);
await Promise.allSettled(e.map((e) => e.promise));
const r = cache.databases.get(n.path);
if (r && (t === void 0 || r.agentId === t)) await r.walMaintenance.stop();
return closeOpenClawAgentDatabaseByPath(n.path, t);
});
}
/** Drain physical aliases through their captured lexical close owners before rollback. */
async function closeOpenClawAgentDatabaseAliasesByPathAsync(e) {
const t = path.resolve(e);
const n = cache.databases.get(t);
const r = n && findOpenClawAgentDatabaseIdentity(n);
const i = r ? void 0 : inspectDatabasePathIdentitySync(t);
const a = typeof r?.identity === "string" ? {
key: `file:${r.identity}`,
birthtime: r.birthtime
} : i?.canonicalPath === normalizeDatabasePath(t) ? i : void 0;
const o = /* @__PURE__ */ new Set([t]);
for (const e of cache.databases.values()) {
const t = findOpenClawAgentDatabaseIdentity(e);
if (typeof t?.identity === "string" && a?.key === `file:${t.identity}` && a.birthtime === t.birthtime) o.add(e.path);
}
for (const e of o) await closeOpenClawAgentDatabaseByPathAsync(e);
}
//#endregion
export { revokePendingAgentDatabaseOpen as _, closeOpenClawAgentDatabaseByPath as a, closeOpenClawAgentDatabasesAsync as c, deferOpenClawAgentPostCommitPublication as d, readOpenClawAgentDatabaseWorkerLeaseReceipt as f, retainFailedAgentDatabaseClose as g, registerAgentDatabaseHandle as h, closeOpenClawAgentDatabaseAliasesByPathAsync as i, closeOpenClawAgentDatabasesForTest as l, refreshAgentDatabaseIdleTimer as m, closeCachedOpenClawAgentDatabase as n, closeOpenClawAgentDatabaseByPathAsync as o, recordOpenClawAgentDatabaseOpenFailure as p, closeMaintenanceAgentDatabase as r, closeOpenClawAgentDatabases as s, cache as t, createAgentDatabaseScopeOwnedClose as u, settleOpenClawAgentDatabaseWorkerClose as v, startAgentDatabaseOpenTiming as y };