openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
204 lines (203 loc) • 8.3 kB
JavaScript
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { t as runInDetachedAsyncContext } from "./detached-async-context-D_mi-wUl.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { d as observeOpenClawDatabaseMaintenanceResource } from "./openclaw-state-maintenance-context-D6i7Zdhn.mjs";
import { n as isPostgresSqlConnection } from "./sql-connection-Beiyg5Dt.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { h as runSqliteReadOperationSync } from "./sqlite-schema-facts-B1bVE8IB.mjs";
import { o as registerSqliteCacheExitClose } from "./sqlite-wal-DGPrWPl6.mjs";
import "./openclaw-state-db-async-lifecycle-CH8q4Sdl.mjs";
import { c as registerOpenClawAgentDatabaseSyncResource } from "./openclaw-agent-db-resources-Dp8HvLsg.mjs";
import { t as SQLITE_IDLE_HANDLE_TTL_MS } from "./sqlite-handle-lifecycle-Dw0xPd8_.mjs";
import { i as isOpenClawAgentDatabasePathCurrent, n as createOpenClawAgentDatabaseClaim, r as findOpenClawAgentDatabaseIdentity } from "./openclaw-agent-db-identity-C8MGU8lp.mjs";
import { c as getOpenClawAgentDatabaseValidation, n as adoptOpenClawAgentDatabaseValidation } from "./openclaw-agent-db-validation-cache-lnjWuypr.mjs";
import { a as withFreshOpenClawAgentDatabaseReadOnly, i as readOpenClawAgentDatabaseSnapshot, n as openOpenClawAgentDatabaseReadOnly, o as assertAgentDatabaseTerminalOpenAllowed, r as readOpenClawAgentDatabase } from "./openclaw-agent-db-readonly-open-BzFUagBt.mjs";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/state/openclaw-agent-db-readonly-scope.ts
const readOnlyScope = new AsyncLocalStorage();
const log = createSubsystemLogger("state/agent-db");
const retainedScopes = resolveGlobalSingleton(Symbol.for("openclaw.agentDatabaseReadOnlyScopes"), () => ({
paths: /* @__PURE__ */ new Map(),
active: /* @__PURE__ */ new Set()
}));
/** One logical reader, revoked by its caller, database lifecycle, or idle expiry. */
var OpenClawAgentDatabaseReadOnlyScope = class {
constructor(e = false) {
this.cached = e;
this.borrowers = 0;
}
get hasRetainedConnection() {
return this.database !== void 0;
}
invalidateProjection(e, t) {
if (this.database && findOpenClawAgentDatabaseIdentity(this.database)?.identity === e) t(this.database.db);
}
closeIfIdle() {
if (this.borrowers === 0 && (!this.database?.db.isOpen || !this.database.db.isTransaction)) this.discardConnection();
}
close() {
clearTimeout(this.idleTimer);
this.idleTimer = void 0;
this.database?.close();
this.database = void 0;
this.retainedValidation = void 0;
this.borrowers = 0;
if (this.target && retainedScopes.paths.get(this.target.path) === this) retainedScopes.paths.delete(this.target.path);
this.target = void 0;
this.unregisterResource?.();
this.unregisterResource = void 0;
retainedScopes.active.delete(this);
if (retainedScopes.active.size === 0) {
retainedScopes.unregisterExit?.();
retainedScopes.unregisterExit = void 0;
}
}
discardConnection() {
const e = this.target;
this.close();
if (!this.cached) this.target = e;
}
touch() {
if (!this.database) return;
if (this.idleTimer) {
this.idleTimer.refresh();
return;
}
this.idleTimer = runInDetachedAsyncContext(() => setTimeout(() => {
this.idleTimer = void 0;
try {
this.closeIfIdle();
} catch (e) {
log.warn("Idle agent read-only database cleanup failed", {
path: this.database?.path,
error: e
});
} finally {
this.touch();
}
}, SQLITE_IDLE_HANDLE_TTL_MS));
this.idleTimer.unref();
}
run(e, t) {
if (this.target?.agentId !== e.agentId || this.target.path !== e.path) this.close();
this.target = e;
return readOnlyScope.run(this, t);
}
matches(e, t) {
return this.target?.agentId === e && this.target.path === t;
}
acquire(e) {
const finish = (t) => {
const n = normalizeAgentId(e.agentId);
if (t.agentId !== n) throw new Error(`OpenClaw agent database ${t.path} belongs to agent ${t.agentId}; requested agent ${n}.`);
observeOpenClawDatabaseMaintenanceResource(this.unregisterResource);
this.touch();
return {
found: true,
database: t
};
};
if (this.database && (this.retainedValidation && Atomics.load(new Int32Array(this.retainedValidation.valid), 0) !== 1 || !isOpenClawAgentDatabasePathCurrent(this.database))) this.discardConnection();
if (this.database) assertAgentDatabaseTerminalOpenAllowed(this.database.path);
if (!this.database) {
const t = openOpenClawAgentDatabaseReadOnly(e);
if (!t.found) {
this.discardConnection();
return t;
}
this.database = t.database;
this.target = {
...this.target,
agentId: this.database.agentId,
path: this.database.path
};
try {
this.unregisterResource = registerOpenClawAgentDatabaseSyncResource({
agentId: this.target.agentId,
path: this.target.path,
revoke: () => this.close(),
close: () => this.close()
});
retainedScopes.active.add(this);
if (this.cached) retainedScopes.paths.set(this.database.path, this);
retainedScopes.unregisterExit ??= registerSqliteCacheExitClose(() => {
for (const e of retainedScopes.active) e.close();
});
} catch (e) {
this.discardConnection();
throw e;
}
}
const t = this.database;
const n = this.target?.validation;
if (n && !adoptOpenClawAgentDatabaseValidation(t, n)) throw new Error("Session reader validation does not match its current physical owner");
this.retainedValidation ??= getOpenClawAgentDatabaseValidation(t);
return finish(t);
}
releaseBorrow(e) {
if (this.database !== e) return;
this.borrowers--;
if (this.borrowers === 0 && isPostgresSqlConnection(e.db)) e.db.releaseIdleTransport();
if (this.cached && this.borrowers === 0 && this.database && (!this.database.db.isOpen || this.database.db.isTransaction)) this.discardConnection();
else this.touch();
}
retain(e) {
const t = this.database?.db.isOpen && this.database.db.isTransaction ? openOpenClawAgentDatabaseReadOnly(e) : this.acquire(e);
if (!t.found) return t;
const { database: n } = t;
const r = n === this.database;
if (r) this.borrowers++;
return {
found: true,
database: n,
claim: createOpenClawAgentDatabaseClaim(n, () => {
if (r) this.releaseBorrow(n);
else n.close();
})
};
}
read(e, t, n = {}) {
if (this.database?.db.isOpen && this.database.db.isTransaction) return withFreshOpenClawAgentDatabaseReadOnly(e, t, n);
const r = this.acquire(t);
if (!r.found) return r;
const { database: i } = r;
this.borrowers++;
try {
return n.snapshot ? readOpenClawAgentDatabaseSnapshot(i, e) : runSqliteReadOperationSync(i.db, () => readOpenClawAgentDatabase(i, e));
} catch (e) {
if (this.cached && this.borrowers === 1) this.discardConnection();
throw e;
} finally {
this.releaseBorrow(i);
}
}
};
function cachedScope(e) {
let t = retainedScopes.paths.get(e.path);
if (!t) {
t = new OpenClawAgentDatabaseReadOnlyScope(true);
t.run(e, () => {});
retainedScopes.paths.set(e.path, t);
}
return t;
}
/** Committed worker receipts invalidate projections on retained readers without running SQL. */
function invalidateOpenClawAgentReadOnlyProjections(e, t) {
for (const n of retainedScopes.active) n.invalidateProjection(e, t);
}
/** Writable admission retires an idle reader before opening the same physical file. */
function closeIdleOpenClawAgentDatabaseReadOnly(e) {
retainedScopes.paths.get(e)?.closeIfIdle();
}
function retainCachedOpenClawAgentDatabaseReadOnly(e) {
const t = readOnlyScope.getStore();
return (t?.matches(e.agentId, e.path) ? t : cachedScope(e)).retain(e);
}
/** Reuse the caller's matching read scope, or this thread's idle-expiring reader. */
function withScopedOpenClawAgentDatabaseReadOnly(e, t, n = {}) {
if (n.allowExtension) return withFreshOpenClawAgentDatabaseReadOnly(e, t, n);
const r = readOnlyScope.getStore();
return (r?.matches(t.agentId, t.path) ? r : cachedScope(t)).read(e, t, n);
}
//#endregion
export { withScopedOpenClawAgentDatabaseReadOnly as a, retainCachedOpenClawAgentDatabaseReadOnly as i, closeIdleOpenClawAgentDatabaseReadOnly as n, invalidateOpenClawAgentReadOnlyProjections as r, OpenClawAgentDatabaseReadOnlyScope as t };