UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

472 lines (471 loc) • 14.1 kB
import { a as extractErrorCode } from "./error-coercion-hDrHOSGy.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { a as getOpenClawDatabaseMaintenanceScope, f as runMaintenance, u as maintenanceResources } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs"; import { c as inspectDatabasePathIdentitySync, m as readDatabasePathIdentitySync, o as findChangedDatabasePaths } from "./sqlite-worker-identity-BH8ZkJU9.mjs"; import { u as throwSqliteLifecycleErrors } from "./sqlite-lifecycle-errors-D8BU4VLa.mjs"; import { r as resolveDatabasePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; //#region src/state/openclaw-state-db-async-lifecycle.ts const STATE_DATABASE_READ_ADMISSION_INVALIDATED = "STATE_DATABASE_READ_ADMISSION_INVALIDATED"; var StateDatabaseReadAdmissionInvalidatedError = class extends Error { constructor(...e) { super(...e); this.code = STATE_DATABASE_READ_ADMISSION_INVALIDATED; } }; function isStateDatabaseReadAdmissionInvalidatedError(e) { return extractErrorCode(e) === STATE_DATABASE_READ_ADMISSION_INVALIDATED; } /** Associate lexical database work with exact resources, never all files beneath a root. */ function createOpenClawDatabaseMaintenanceScope(e) { const t = getOpenClawDatabaseMaintenanceScope(); const n = e?.assertOwnerCurrent; const r = e?.assertDatabaseAccess; const i = /* @__PURE__ */ new Set(); const a = /* @__PURE__ */ new Set(); const o = /* @__PURE__ */ new Map(); let s = false; let c = false; let l; const assertOpen = () => { if (s) throw new Error("Database maintenance resource scope is closed"); }; const assertAdmissionLifecycle = () => { assertOpen(); const e = maintenanceResources.current.getStore(); if (l && !(e?.scope === u && e.active)) throw new Error("Database maintenance resource admission is closed"); }; const u = { ownsSchemaMaintenance: e?.schemaMaintenance === true || t?.ownsSchemaMaintenance === true, sqliteIntegrityCheck: e?.sqliteIntegrityCheck ?? t?.sqliteIntegrityCheck, assertOwnerCurrent(e) { assertOpen(); if (c) { if (e === "read") return; const t = (/* @__PURE__ */ new Error()).stack?.split("\n").slice(2, 6).flatMap((e) => e.match(/^\s+at (?:async )?([\w$.]+) \(/u)?.[1] ?? []).join(" <- ").slice(0, 160); throw new Error(`Database maintenance authority check cannot admit a nested effect (access=effect; caller=${t || "unknown"})`); } c = true; try { t?.assertOwnerCurrent(e); n?.(e); } finally { c = false; } }, assertAdmission() { assertOpen(); u.assertOwnerCurrent(); assertAdmissionLifecycle(); }, assertReadAdmission() { assertAdmissionLifecycle(); u.assertOwnerCurrent("read"); assertAdmissionLifecycle(); }, assertDatabaseAccess(e) { u.assertAdmission(); if (r) r(e); else if (t) t.assertDatabaseAccess(e); else throw new Error("Database maintenance scope does not own this database"); }, assertCleanupDatabaseAccess(e) { assertOpen(); if (r) r(e); else if (t) t.assertCleanupDatabaseAccess(e); else throw new Error("Database maintenance scope does not own this database"); }, addAgentSchemaMigrationCheck(e) { u.assertAdmission(); a.add(e); }, assertAgentSchemaMigration(e) { assertOpen(); u.assertOwnerCurrent(); t?.assertAgentSchemaMigration(e); for (const t of a) t(e); }, run(e) { assertAdmissionLifecycle(); return runMaintenance(u, () => { u.assertAdmission(); return e(); }); }, track(e) { assertOpen(); i.add(e); const settled = () => i.delete(e); e.then(settled, settled); return e; }, own(e, t, n) { assertOpen(); o.set(e, { phase: t, close: n }); maintenanceResources.claims.set(e, { scope: u, phase: t, close: n, release: () => o.delete(e) }); }, close(e) { if (l) return l; const t = createDeferredCore(); l = t.promise; maintenanceResources.current.run({ scope: u, active: true }, async () => { let t = e; while (i.size || o.size || t) { while (i.size) await Promise.allSettled(i); for (const e of [ "agent-resources", "agent-handles", "shared-leases", "shared-resources", "shared-references", "shared-handles" ]) { if (e === "shared-leases" && t) { await t(); t = void 0; } while ([...o.values()].some((t) => t.phase === e)) { while (i.size) await Promise.allSettled(i); const t = [...o].filter(([, t]) => t.phase === e); const n = await Promise.allSettled(t.map(async ([e, t]) => { const n = maintenanceResources.claims.get(e); await t.close(); if (o.get(e) === t) o.delete(e); if (maintenanceResources.claims.get(e) === n) maintenanceResources.claims.delete(e); })); while (i.size) await Promise.allSettled(i); const r = n.flatMap((e) => e.status === "rejected" ? [e.reason] : []); throwSqliteLifecycleErrors(r, "Maintenance resource cleanup failed"); } } } a.clear(); s = true; }).then(t.resolve, (e) => { l = void 0; t.reject(e); }); return t.promise; } }; if (t) maintenanceResources.parents.set(u, t); return u; } /** The cache owns physical identity and admission across drainage and file exclusion. */ function createOpenClawStateDatabaseAsyncLifecycle() { const e = /* @__PURE__ */ new Set(); const t = /* @__PURE__ */ new Map(); const n = /* @__PURE__ */ new Map(); const r = /* @__PURE__ */ new Set(); const i = /* @__PURE__ */ new Map(); let a = Promise.resolve(); const proofFor = () => { const e = new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT); new BigInt64Array(e)[0] = -1n; return e; }; const generationFor = (e) => { const t = new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT); return { integrity: { identity: e, lifetime: { revision: new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT), epoch: 0n }, revision: t, epoch: 0n, proof: proofFor() } }; }; const publishCreatedIdentity = (e, n) => { Atomics.add(new BigInt64Array(e.generation.integrity.revision), 0, 1n); Atomics.add(new BigInt64Array(e.generation.integrity.lifetime.revision), 0, 1n); t.delete(e.identity.key); e.identity = n; e.generation.integrity.identity = n; t.set(n.key, e); }; const known = (e) => n.get(e) ?? n.get(resolveDatabasePath({ path: e })); const bindPath = (e, t) => { e.paths.add(t); if (!n.has(t)) n.set(t, e); }; const overlaps = (e, t) => { if (e.identity.key === t.identity.key) return true; for (const n of e.paths) if (t.paths.has(n)) return true; return false; }; const isSealed = (e) => { if (r.size === 0) return false; for (const t of r) if (t.record === void 0 || overlaps(t.record, e)) return true; return false; }; const hasCloseCustody = (e) => isSealed(e) || i.has(e); const assertOpen = (e) => { if (isSealed(e)) throw new StateDatabaseReadAdmissionInvalidatedError("OpenClaw state database read admission is closed"); }; const findPhysicalRecord = (e) => { const r = t.get(e.key); if (!r || !e.key.startsWith("file:") || hasCloseCustody(r)) return r; for (const t of findChangedDatabasePaths(r.paths, e)) { r.admissions.delete(t); r.paths.delete(t); if (n.get(t) === r) n.delete(t); } if (r.paths.size > 0) { if (!r.paths.has(r.identity.canonicalPath)) { r.identity = e; r.generation.integrity.identity = e; } return r; } invalidate(r); forget(r); }; const resolve = (e, r) => { const i = n.get(e); if (i && (!r || i.identity.key === r.key)) return !r && i.identity.key.startsWith("path:") ? resolve(e, readDatabasePathIdentitySync(e)) : i; const a = r ?? readDatabasePathIdentitySync(e); let o = findPhysicalRecord(a); if (!o && a.key.startsWith("file:")) { o = [...t.values()].find((e) => { if (!e.identity.key.startsWith("path:")) return false; try { return readDatabasePathIdentitySync(e.identity.canonicalPath).key === a.key; } catch { return false; } }); if (o) publishCreatedIdentity(o, a); } if (!o) { o = { coordinationKey: a.key, identity: a, paths: /* @__PURE__ */ new Set(), generation: generationFor(a), admissions: /* @__PURE__ */ new Map() }; t.set(a.key, o); } bindPath(o, e); bindPath(o, a.canonicalPath); return o; }; const resolveForNative = (e) => { const t = resolveDatabasePath({ path: e }); const r = n.get(t); if (r) return r; const i = inspectDatabasePathIdentitySync(t); return i ? resolve(t, i) : void 0; }; const invalidate = (e) => { for (const n of e ? [e] : t.values()) { Atomics.store(new BigInt64Array(n.generation.integrity.revision), 0, -1n); Atomics.store(new BigInt64Array(n.generation.integrity.lifetime.revision), 0, -1n); n.generation = generationFor(n.identity); n.admissions.clear(); } }; const seal = (e) => { invalidate(e); const t = { record: e }; r.add(t); return t; }; const release = (e) => { if (e.seal) { r.delete(e.seal); e.seal = void 0; } }; const forget = (e) => { if (!hasCloseCustody(e) && t.get(e.identity.key) === e) { t.delete(e.identity.key); for (const r of e.paths) if (n.get(r) === e) { n.delete(r); for (const e of t.values()) if (e.paths.has(r)) { n.set(r, e); break; } } } }; const captureRecord = (e, n) => { const r = e.admissions.get(n); if (r) return r; const i = e.generation; const a = Object.freeze({ databasePath: n, coordinationKey: e.coordinationKey, get identity() { return e.identity; }, captureIntegrity() { a.assertCurrent(); const t = i.integrity; const n = Atomics.load(new BigInt64Array(t.revision), 0); const r = Atomics.load(new BigInt64Array(t.lifetime.revision), 0); if (n !== t.epoch || r !== t.lifetime.epoch) i.integrity = { ...t, identity: e.identity, lifetime: { revision: t.lifetime.revision, epoch: r }, epoch: n, proof: proofFor() }; return i.integrity; }, assertCurrent() { assertOpen(e); if (t.get(e.identity.key) !== e || e.generation !== i || e.admissions.get(n) !== a) throw new StateDatabaseReadAdmissionInvalidatedError("OpenClaw state database read admission changed"); } }); e.admissions.set(n, a); return a; }; return { identity(e) { return known(e)?.identity ?? inspectDatabasePathIdentitySync(e); }, knownIdentity(e) { return known(e)?.identity; }, integrity(e) { const t = resolveForNative(e); return t && !isSealed(t) ? captureRecord(t, resolveDatabasePath({ path: e })).captureIntegrity?.() : void 0; }, publish(e, r) { const a = resolveDatabasePath({ path: e }); const o = r ?? readDatabasePathIdentitySync(a); const s = n.get(a); let c = r && s?.identity.key === o.key ? t.get(o.key) : findPhysicalRecord(o); if (s && s.identity.key !== o.key) { if (s.identity.key.startsWith("path:") && !c) { publishCreatedIdentity(s, o); c = s; } else { const e = i.get(s); if (e) { e.superseded = true; e.seal ??= seal(s); } else invalidate(s); forget(s); } } if (!c) c = resolve(a, o); bindPath(c, a); bindPath(c, r ? c.identity.canonicalPath : o.canonicalPath); return { identity: o, admission: captureRecord(c, a) }; }, invalidate(e) { if (e === void 0) invalidate(); else { const t = known(e); if (t) invalidate(t); } }, register(t) { e.add(t); for (const e of i.values()) e.queue?.add(t); return () => { e.delete(t); }; }, capture(e) { const t = n.get(e); const r = t?.admissions.get(e); if (t && r && t.identity.key.startsWith("file:")) { r.assertCurrent(); return r; } const i = resolveDatabasePath({ path: e }); const a = resolve(i); assertOpen(a); return captureRecord(a, i); }, holdExclusion(e) { const n = resolve(resolveDatabasePath({ path: e })); const i = seal(n); return () => { r.delete(i); for (const e of t.values()) if (overlaps(n, e)) forget(e); }; }, close(n, r) { const o = n === void 0 ? void 0 : resolveForNative(n); if (n !== void 0 && !o) return Promise.resolve(r()); let s = i.get(o); if (s?.pending) return s.pending; if (!s) { s = { retained: /* @__PURE__ */ new Set() }; i.set(o, s); } s.seal ??= seal(o); const c = s; const l = a.then(async () => { const n = /* @__PURE__ */ new Set([...e, ...c.retained]); for (const e of i.values()) for (const t of e.retained) n.add(t); c.queue = n; const a = []; while (c.queue.size) { const e = [...c.queue].filter((e) => e.phase !== "after-resources"); if (!e.length && a.length) { for (const e of c.queue) c.retained.add(e); break; } const t = e.length ? e : [...c.queue]; for (const e of t) c.queue.delete(e); await Promise.all(t.map(async (e) => { try { const t = o?.identity; if (!t || !e.admission || t.key === e.admission.identity.key) await e.close(t); c.retained.delete(e); } catch (t) { c.retained.add(e); a.push(t); } })); } if (a.length && !c.superseded) release(c); throwSqliteLifecycleErrors(a, "OpenClaw state resource drainage failed"); const s = await r(o?.identity); i.delete(o); release(c); if (o === void 0) { for (const [e, t] of i) if (!t.pending) { i.delete(e); release(t); } for (const e of t.values()) forget(e); } else forget(o); return s; }).finally(() => { c.queue = void 0; }); c.pending = l; a = l.then(() => void 0, () => void 0); l.catch(() => { c.pending = void 0; }); return l; } }; } //#endregion export { isStateDatabaseReadAdmissionInvalidatedError as i, createOpenClawDatabaseMaintenanceScope as n, createOpenClawStateDatabaseAsyncLifecycle as r, StateDatabaseReadAdmissionInvalidatedError as t };