UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

419 lines (418 loc) • 13.5 kB
import { h as extractErrorCode } from "./paths-0xDagtub.mjs"; import { W as resolveGlobalSingleton } from "./path-guards-quCEQx1i.mjs"; import { v as resolveIdentityPathViaExistingAncestorSync } from "./redact-BRF0hr6G.mjs"; import { f as readDatabasePathIdentitySync, i as findChangedDatabasePaths, o as inspectDatabasePathIdentitySync } from "./sqlite-worker-identity-CiWdPbPl.mjs"; import { r as resolveDatabasePath } from "./openclaw-state-db.paths-5PCLNGIM.mjs"; import { u as throwSqliteLifecycleErrors } from "./sqlite-lifecycle-errors-D4bxhyEQ.mjs"; import { AsyncLocalStorage } from "node:async_hooks"; import fsSync from "node:fs"; //#region src/state/openclaw-state-maintenance-context.ts const liveAuthorityReads = resolveGlobalSingleton(Symbol.for("openclaw.maintenanceLiveAuthorityReads"), () => /* @__PURE__ */ new WeakMap()); function allowsMaintenanceLiveAuthorityReads(e, t) { const n = resolveIdentityPathViaExistingAncestorSync(t); for (let t = e; t; t = maintenanceResources.parents.get(t)) if (liveAuthorityReads.get(t)?.has(n)) return true; return false; } /** Raw source descriptor closes are safe only before maintenance admits native source reads. */ function maintenanceOwnerHasSourceCustody(e, t) { if (!e?.ownsSchemaMaintenance) return false; e.assertReadAdmission(); return !allowsMaintenanceLiveAuthorityReads(e, t); } const maintenanceResources = resolveGlobalSingleton(Symbol.for("openclaw.databaseMaintenanceResources"), () => ({ current: new AsyncLocalStorage(), claims: /* @__PURE__ */ new WeakMap(), parents: /* @__PURE__ */ new WeakMap() })); function getOpenClawDatabaseMaintenanceScope() { return maintenanceResources.current.getStore()?.scope; } /** Background work retains command custody without borrowing its native execution path. */ function isOpenClawDatabaseMaintenanceWorkerAccess() { return maintenanceResources.current.getStore()?.workerAccess === true; } function isOpenClawDatabaseMaintenanceResourceOwned(e, t) { return maintenanceResources.claims.get(e)?.scope === t; } function getOpenClawDatabaseMaintenanceResourceScope(e) { return maintenanceResources.claims.get(e)?.scope; } function runMaintenance(e, t, n = isOpenClawDatabaseMaintenanceWorkerAccess()) { const r = { scope: e, active: true, workerAccess: n }; try { const n = maintenanceResources.current.run(r, t); if (n instanceof Promise) { const settled = () => { r.active = false; }; n.then(settled, settled); e.track(n); } else r.active = false; return n; } catch (e) { r.active = false; throw e; } } /** Retain one exact resource claim for finite commands while its maintenance scope drains. */ function captureOpenClawDatabaseMaintenanceResource(e, t) { const n = maintenanceResources.claims.get(e); const assertCurrent = () => { t.assertOwnerCurrent(); if (n?.scope !== t || maintenanceResources.claims.get(e) !== n) throw new Error("Database maintenance resource owner changed"); }; assertCurrent(); return { assertCurrent, async run(e) { assertCurrent(); return runMaintenance(t, e); }, async runWorker(e) { assertCurrent(); return runMaintenance(t, e, true); } }; } /** A cached handle used by an independent caller remains with the ordinary cache owner. */ function observeOpenClawDatabaseMaintenanceResource(e) { if (!e) return; const t = maintenanceResources.claims.get(e); const n = getOpenClawDatabaseMaintenanceScope(); if (!t) return; const r = commonMaintenanceAncestor(t.scope, n); if (r === t.scope) return; t.scope.assertAdmission(); t.release(); maintenanceResources.claims.delete(e); if (r) r.own(e, t.phase, t.close); } function commonMaintenanceAncestor(e, t) { const n = /* @__PURE__ */ new Set(); for (let t = e; t; t = maintenanceResources.parents.get(t)) n.add(t); for (let e = t; e; e = maintenanceResources.parents.get(e)) if (n.has(e)) return e; } //#endregion //#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; } /** 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 { captureOpenClawDatabaseMaintenanceResource as a, isOpenClawDatabaseMaintenanceResourceOwned as c, allowsMaintenanceLiveAuthorityReads as i, maintenanceOwnerHasSourceCustody as l, createOpenClawStateDatabaseAsyncLifecycle as n, getOpenClawDatabaseMaintenanceResourceScope as o, isStateDatabaseReadAdmissionInvalidatedError as r, getOpenClawDatabaseMaintenanceScope as s, StateDatabaseReadAdmissionInvalidatedError as t, observeOpenClawDatabaseMaintenanceResource as u };