UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

239 lines (238 loc) • 11 kB
import { i as withEngineStoreAdmission } from "./admission-scope-DmxaPNhm.mjs"; import { n as OPENCLAW_STATE_SCHEMA_VERSION } from "./openclaw-schema-versions-E_10NoI6.mjs"; import { n as clearNodeSqliteKyselyCacheForDatabase } from "./kysely-sync-cache-state-Bb1gOqQO.mjs"; import { t as assertNoActiveSqliteReaders } from "./sqlite-reader-lifecycle-Cug3fDqm.mjs"; import { t as admitSqliteSchema, w as getPostgresPhysicalFacts } from "./sqlite-schema-facts-B1bVE8IB.mjs"; import { l as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS } from "./openclaw-state-db-contract-DfPjvL0M.mjs"; import { n as createStateSchemaAdmission, t as adoptPeerPublishedStateSchemaVersion } from "./openclaw-state-db-admission-Bw1Mtc4x.mjs"; import { a as setSqliteBusyTimeout } from "./sqlite-busy-timeout-BEDmnGR_.mjs"; import { t as assertTransactionUsable } from "./sqlite-transaction-BHHu6P5-.mjs"; import { r as resolveDatabasePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; import { k as assertStateDatabaseIntegrityOnce, m as openClawStateDatabaseCache } from "./openclaw-state-db-cache-CkwtTqzF.mjs"; import { a as isExistingOpenClawStateSchema, n as assertOpenClawStateSchemaRepairAllowed } from "./openclaw-state-db-schema-policy-DvHzXD76.mjs"; import { n as closeTrackedStateDatabase, r as openTrackedStateDatabase } from "./openclaw-state-db-handle-BxpEWiaT.mjs"; import { n as SqliteRepairableForeignKeyError, r as assertSqliteIntegrity } from "./sqlite-integrity-CCmEgO_m.mjs"; import { c as runUpdateSqliteMigration } from "./update-doctor-migration-attribution-Dp_N9vmd.mjs"; import { a as isStatePostgres, o as openExistingStatePostgresConnection, r as ensureStatePostgresFragment } from "./openclaw-state-db-engine-sM0tpxNy.mjs"; import { i as assertSupportedStateSchemaVersion, r as admitStateSchemaFacts } from "./openclaw-state-db-schema-version-uNbDFl6T.mjs"; import { o as getCanonicalSqliteNamedIndexNames, s as getCanonicalSqliteTableNames, t as assertSqliteSchemaContains } from "./sqlite-schema-contract-D3pR9vZs.mjs"; import { t as assertExistingOpenClawStateRuntimeSchema } from "./openclaw-state-db-existing-schema-C1h5v6Xh.mjs"; import { r as assertOpenClawStateDatabaseOwner } from "./openclaw-state-db-maintenance-Dvr7ztmv.mjs"; import { n as withStateDatabaseSchemaMaintenance } from "./state-database-maintenance-Z49n3wcg.mjs"; import { n as assertOpenClawStateWriteAllowed } from "./openclaw-state-ownership-Wv4JBQVJ.mjs"; import { n as runManagedStateTransaction } from "./openclaw-state-db-transaction-Bho3XfIN.mjs"; import { t as createSqliteSchemaEnsurer } from "./sqlite-schema-ensure-B6yDrFvM.mjs"; import { t as recoverOrphanTaskDeliveryRows } from "./openclaw-state-db-task-delivery-recovery-BhaIXO-A.mjs"; import fs from "node:fs"; import { createHash } from "node:crypto"; //#region src/state/openclaw-state-db-existing-write.ts function assertExistingOpenClawStateSchemaMetadata(e, t, n) { const r = assertOpenClawStateDatabaseOwner(e, { pathname: t }); if (n >= 1 && r?.schema_version === n) return n; if (n >= 1 && adoptPeerPublishedStateSchemaVersion(e, r)) return 36; throw new Error("Existing-state schema metadata is inconsistent."); } /** Validate only the stable storage subset used by an existing-schema owner. * This read neither repairs nor grants write authority; callers retain their * actual handle, generation, lease and publication checks. */ function assertExistingOpenClawStateSchema(e, t, n, r, i = "full") { const a = assertExistingOpenClawStateSchemaMetadata(e, t, assertSupportedStateSchemaVersion(e, t)); if (i === "quick") assertSqliteIntegrity(e, t, { check: "quick", tables: n === void 0 ? void 0 : getCanonicalSqliteTableNames(n) }); else assertStateDatabaseIntegrityOnce(e, t); if (n !== void 0) assertSqliteSchemaContains(e, t, n, r); return a; } /** A synchronous write to an already-compatible, caller-owned schema subset. * No database bootstrap, schema repair, journal-mode setup, cached publication or WAL timer. * First-use owners may install their declared additive tables; existing objects * must already match. This never opens or migrates the full runtime schema. * The admitted native connection owns transaction serialization. */ function runExistingOpenClawStateWriteTransaction(e, t, n) { const r = prepareExistingOpenClawStateWriter(t, n); const write = () => { const i = createExistingOpenClawStateWriter(r, n); try { return i.run(e, t); } finally { i.close(); } }; return n.recoverTaskDeliveryOrphans ? withStateDatabaseSchemaMaintenance({ databasePath: r.pathname }, write) : write(); } /** Retain the admitted subset connection without bootstrapping the runtime schema. */ function openExistingOpenClawStateWriter(e, t) { return createExistingOpenClawStateWriter(prepareExistingOpenClawStateWriter(e, t), t); } function prepareExistingOpenClawStateWriter(e, t) { if (e.database || e.readOnly) throw new Error("Existing-state writes require their own tracked writable connection."); const n = e.env ?? process.env; const r = resolveDatabasePath({ path: e.path, env: n }); isExistingOpenClawStateSchema(r); if (t.recoverTaskDeliveryOrphans) assertOpenClawStateSchemaRepairAllowed(r); const i = fs.lstatSync(r); if (!i.isFile()) throw new Error("Existing-state write requires a regular database file."); return { env: n, pathname: r, original: i }; } function createExistingOpenClawStateWriter({ env: e, pathname: t, original: n }, r) { const assertSameFile = () => { const e = fs.lstatSync(t); if (!e.isFile() || e.dev !== n.dev || e.ino !== n.ino) throw new Error("Existing-state database generation changed."); }; assertSameFile(); openClawStateDatabaseCache.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(t, e); if (isStatePostgres()) return createExistingPostgresStateWriter(t, r, assertSameFile); const i = openTrackedStateDatabase(t, { existingOnly: true, ...r.recoverTaskDeliveryOrphans ? { enableForeignKeyConstraints: false } : {} }); const a = createStateSchemaAdmission(`state.subset:${createHash("sha256").update(JSON.stringify([ r.schemaSql, r.schemaCompatibility, r.integrityCheck ])).digest("hex")}`, (e) => typeof e === "number" ? e : void 0, r.integrityCheck === void 0 ? "process" : void 0); const o = r.initializeAdditiveSchema ? createSqliteSchemaEnsurer(() => r.schemaSql, { tables: getCanonicalSqliteTableNames(r.schemaSql), indexes: getCanonicalSqliteNamedIndexNames(r.schemaSql) }) : void 0; let s = false; const close = () => { s = true; clearNodeSqliteKyselyCacheForDatabase(i); closeTrackedStateDatabase(i); }; return { run(e, n) { if (s || !i.isOpen) throw new Error("Existing-state writer is closed."); if (n.database || n.readOnly) throw new Error("Existing-state writes require their own tracked writable connection."); const c = n.env ?? process.env; if (resolveDatabasePath({ path: n.path, env: c }) !== t) throw new Error("Existing-state writer cannot change its database path."); assertSameFile(); const l = isExistingOpenClawStateSchema(t); const u = n.busyTimeoutMs ?? r.busyTimeoutMs ?? 5e3; setSqliteBusyTimeout(i, u); admitStateSchemaFacts(i, t); const write = () => runManagedStateTransaction(i, () => { assertSameFile(); assertOpenClawStateWriteAllowed({ database: i, databasePath: t, env: c }); const n = a.get(i); const s = n === void 0; if (l) assertExistingOpenClawStateRuntimeSchema(i, t); const validate = () => assertExistingOpenClawStateSchema(i, t, s && r.initializeAdditiveSchema ? void 0 : r.schemaSql, r.schemaCompatibility, r.integrityCheck); let u; let d = []; if (r.recoverTaskDeliveryOrphans) { try { validate(); } catch (e) { if (!(e instanceof SqliteRepairableForeignKeyError)) throw e; } d = recoverOrphanTaskDeliveryRows(i, t); u = validate(); } else u = n ?? validate(); if (s && r.initializeAdditiveSchema) { assertSqliteSchemaContains(i, t, r.schemaSql, { ...r.schemaCompatibility, allowedMissingTables: getCanonicalSqliteTableNames(r.schemaSql) }); admitSqliteSchema(i); o?.(i); assertSqliteSchemaContains(i, t, r.schemaSql, r.schemaCompatibility); } if (s) { admitSqliteSchema(i); a.publish(i, u); } const f = e({ db: i, path: t, recoveryChanges: d }); assertSameFile(); if (r.recoverTaskDeliveryOrphans) assertSqliteIntegrity(i, t); return f; }, { beginLockFailureReporting: r.beginLockFailureReporting, busyTimeoutMs: u, databaseLabel: t, operationLabel: r.operationLabel }); return r.attributeUpdateWrite ? runUpdateSqliteMigration(i, t, write, { close }) : write(); }, assertSettled() { assertSameFile(); assertTransactionUsable(i); if (i.isOpen && i.isTransaction) throw new Error("Existing-state writer retained an unsettled transaction"); if (i.isOpen) assertNoActiveSqliteReaders(i, "Existing-state writer"); }, close }; } /** Reuse the admitted physical schema without running the candidate's version migrations. */ function createExistingPostgresStateWriter(e, t, n) { const r = withEngineStoreAdmission(() => openExistingStatePostgresConnection(e)); if (!r) throw new Error("Existing PostgreSQL state writer requires its selected engine"); const { db: i } = r.database; const a = getCanonicalSqliteTableNames(t.schemaSql); return { run(r, o) { if (!i.isOpen) throw new Error("Existing-state writer is closed."); if (o.database || o.readOnly) throw new Error("Existing-state writes require their own tracked writable connection."); const s = o.env ?? process.env; if (resolveDatabasePath({ path: o.path, env: s }) !== e) throw new Error("Existing-state writer cannot change its database path."); return withEngineStoreAdmission(() => runManagedStateTransaction(i, () => { n(); assertOpenClawStateWriteAllowed({ database: i, databasePath: e, env: s }); const o = getPostgresPhysicalFacts(i).catalog; for (const e of a) if (t.initializeAdditiveSchema) ensureStatePostgresFragment(i, e); else if (!o.some((t) => t.kind === "table" && t.table === e)) throw new Error(`Existing PostgreSQL state schema is missing ${e}`); const c = r({ db: i, path: e, recoveryChanges: [] }); n(); return c; }, { databaseLabel: e, operationLabel: t.operationLabel, beginLockFailureReporting: t.beginLockFailureReporting })); }, assertSettled() { n(); assertTransactionUsable(i); if (!i.isOpen) throw new Error("Existing-state writer retained a closed PostgreSQL connection"); if (i.isTransaction) throw new Error("Existing-state writer retained an unsettled transaction"); }, close() { r.close(); } }; } //#endregion export { runExistingOpenClawStateWriteTransaction as n, openExistingOpenClawStateWriter as t };