openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5 lines • 15.9 kB
JavaScript
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{c as sha256File,l as syncDirectory,s as requireDirectorySync}from"./directory-durability-o_aQCRBZ.mjs";import{n as ignoreMissingPath}from"./errno-DUBt6SQQ.mjs";import{l as quoteSqliteIdentifier}from"./sqlite-schema-sql-XrfUK8rp.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{r as resolvePreferredOpenClawTmpDir}from"./tmp-openclaw-dir-DapBruir.mjs";import{a as readPostgresCatalog,i as postgresCatalogQuery,t as assertPostgresCatalog}from"./postgres-catalog-DLo1qY5z.mjs";import{n as openNodeSqliteDatabase}from"./node-sqlite-DXyF1fBG.mjs";import{t as copyFileHandle}from"./file-descriptor-CRkf5tcV.mjs";import{r as getScopedDatabaseEngineSelection}from"./context-DZjni16e.mjs";import{t as INSTALLED_PLUGIN_INDEX_STATE_KEY}from"./plugin-metadata-state.kernel-B4HP-_P3.mjs";import{a as DEFERRED_PLUGIN_MIGRATION_RUN_PREFIX,n as assertPluginCohortDatabaseRestoreRecords,t as assertPluginCohortDatabaseRestoreMigrations}from"./update-plugin-cohort-records-Bo-GWAMM.mjs";import{C as PLUGIN_COHORT_RECOVERY_KEY_PREFIX,r as decodePluginCohortRecoveryPairRows}from"./update-run-recovery-store-k_2_R9pM.mjs";import{n as UPDATE_RECOVERY_KEY_PREFIX}from"./update-run-recovery-keys-BitmNsnI.mjs";import{n as readBackupEngineImage}from"./physical-store-inspection-BHEZGfsf.mjs";import{a as withDatabasePortPostgres,i as withDatabasePortConnection}from"./port-provider-CdqIxw1H.mjs";import{t as admitDatabasePortDescriptor}from"./port-descriptor-CEPvy_gf.mjs";import{i as readDatabasePortAllocations,n as materializeDatabasePort,t as inspectDatabasePort}from"./port.worker-L-VIbCDt.mjs";import{i as writePostgresExportEnvelope,n as readSnapshotExportEnvelope,r as verifyPostgresExportEnvelope}from"./export-envelope-Dwkiigow.mjs";import{t as createGitBackupRowTransform}from"./git-backup-sanitizer-DX1895e0.mjs";import{n as inspectPostgresGeneration,t as fingerprintPostgresGeneration}from"./postgres-generation-XnBAvuMJ.mjs";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import fs from"node:fs/promises";import{isDeepStrictEqual}from"node:util";import{withTempWorkspace}from"@openclaw/fs-safe/temp";
//!src/snapshot/database-backup-core.worker.ts
async function captureDatabaseArtifact(e){try{var t=_usingCtx();const n=t.a(await fs.open(e,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW));const r=await n.stat();if(!r.isFile()||r.nlink!==1)throw new Error(`Database artifact must be an unaliased regular file: ${e}`);const{digest:i,bytes:a}=await sha256File(n);return{path:e,sha256:i,size:a}}catch(e){t.e=e}finally{await t.d()}}async function artifact(e){const{sha256:t,size:n}=await captureDatabaseArtifact(e);return{sha256:t,sizeBytes:n}}async function assertDatabaseArtifact(e){if(!isDeepStrictEqual(await captureDatabaseArtifact(e.path),e))throw new Error(`Database artifact changed: ${e.path}`)}async function exportPostgresBackup(e){const{client:t,descriptor:n,anchor:r}=e;const i=path.join(e.directory,`.export.sqlite`);const a=path.join(e.directory,`database.sqlite`);const o=path.join(e.directory,`anchor.sqlite`);let s;try{var c=_usingCtx();e.assertCurrent();await fs.writeFile(i,``,{flag:`wx`,mode:384});const a=c.u(openNodeSqliteDatabase(i,{readBigInts:true}));const o={engine:`postgres`,db:t,namespace:r.namespace};s=await materializeDatabasePort({source:o,destination:{engine:`sqlite`,db:a},descriptor:n,storeId:r.storeId,assertCurrent:e.assertCurrent,transformRow:e.gitIdentity?createGitBackupRowTransform(e.gitIdentity,n.id,new Set(n.tables.map(({name:e})=>e))):void 0});s.allocations=await readDatabasePortAllocations(o,n)}catch(e){c.e=e}finally{c.d()}const l=[];e.assertCurrent();if(e.profile===`exact`)await fs.rename(i,a);else{const{createVerifiedSqliteSnapshot:t}=await import(`./sqlite-snapshot-C6LLrZkv.mjs`);const{sanitizeOpenClawGlobalStateSnapshot:r}=await import(`./openclaw-state-snapshot-sanitizer-4LF_eTfk.mjs`);await t({sourcePath:i,targetPath:a,sourceAcquisition:{mode:`isolated-process`,stagingRoot:e.directory,preserveSourceArtifacts:true},preserveRowIds:true,async transform(t){if(e.gitIdentity)l.push(`git-exclude-secrets`);const i=t.prepare(`SELECT total_changes() AS n`).get()?.n;r(t);const{embedSessionColdArchivesInSnapshotInWorker:a}=await import(`./session-cold-storage-backup.worker-M9tZkVbf.mjs`);await a({database:t,sourceStorePath:e.sourcePath});if(t.prepare(`SELECT total_changes() AS n`).get()?.n!==i)l.push(`transient-state`);if(e.gitIdentity)s.tables=(await inspectDatabasePort({engine:`sqlite`,db:t},n)).tables}});await fs.unlink(i)}const u={schemaVersion:2,snapshotId:path.basename(e.directory),createdAt:(/* @__PURE__ */ new Date()).toISOString(),profile:e.profile,source:{...r,owner:n.id,schemaVersion:n.version},exportSchemaVersion:n.version,activeFragments:[...n.activeFragments],verification:s,artifacts:{"database.sqlite":await artifact(a),"anchor.sqlite":await artifact(o)},sanitizedDifferences:l};e.assertCurrent();await writePostgresExportEnvelope(e.directory,u);return u}async function capturePostgresSchema(e){const{client:t,descriptor:n,anchor:r}=e;const i=`restore_${randomUUID().replaceAll(`-`,``)}`;const a=e.prune?JSON.stringify({openclawCapture:{prefixHash:createHash(`sha256`).update(e.prune.directoryPrefix).digest(`hex`),captureId:e.prune.captureId}}):void 0;try{e.assertCurrent();const o=await materializeDatabasePort({source:{engine:`postgres`,db:t,namespace:r.namespace},destination:{engine:`postgres`,db:t,namespace:i},descriptor:{...n,postgresPostData:e=>`${n.postgresPostData?.(e)??``}\n;\n`+(a?`COMMENT ON SCHEMA "${e}" IS ${t.escapeLiteral(a)}`:``)},storeId:r.storeId,assertCurrent:e.assertCurrent});const s={schemaVersion:2,snapshotId:path.basename(e.directory),createdAt:(/* @__PURE__ */ new Date()).toISOString(),profile:`exact`,source:{...r,owner:n.id,schemaVersion:n.version},exportSchemaVersion:n.version,activeFragments:[...n.activeFragments],verification:o,carrier:`postgres-schema`,schema:i,artifacts:{"anchor.sqlite":await artifact(path.join(e.directory,`anchor.sqlite`))},sanitizedDifferences:[]};e.assertCurrent();await writePostgresExportEnvelope(e.directory,s);return s}catch(e){await discardPostgresNamespace(t,i);throw e}}async function restorePostgresBackup(e){const{client:t,descriptor:n,manifest:r}=e;if(n.version!==r.exportSchemaVersion||n.version!==r.source.schemaVersion)throw new Error(`PostgreSQL backup requires its matching family schema version.`);const i=`restore_${randomUUID().replaceAll(`-`,``)}`;try{try{var a=_usingCtx();const s=a.u(r.schema?void 0:openNodeSqliteDatabase(path.join(e.directory,`database.sqlite`),{readOnly:true,readBigInts:true}));e.assertCurrent();const c=await materializeDatabasePort({source:s?{engine:`sqlite`,db:s}:{engine:`postgres`,db:t,namespace:r.schema},destination:{engine:`postgres`,db:t,namespace:i},descriptor:n,storeId:r.source.storeId,sourceAllocations:r.verification.allocations,activeFragments:r.activeFragments,assertCurrent:e.assertCurrent});if(e.profile===`exact`&&!isDeepStrictEqual(c,r.verification))throw new Error(`Exact PostgreSQL export verification differs from its manifest.`);e.assertCurrent();await fs.copyFile(path.join(e.directory,`anchor.sqlite`),e.anchorPath,fs.constants.COPYFILE_EXCL);if(!isDeepStrictEqual(await artifact(e.anchorPath),r.artifacts[`anchor.sqlite`]))throw new Error(`PostgreSQL restore anchor changed during preparation.`);try{var o=_usingCtx();o.u(openNodeSqliteDatabase(e.anchorPath)).prepare(`UPDATE openclaw_engine_anchor SET schema = ?`).run(i)}catch(e){o.e=e}finally{o.d()}return{namespace:i}}catch(e){a.e=e}finally{a.d()}}catch(e){await discardPostgresNamespace(t,i);throw e}}async function discardPostgresNamespace(e,t){if(!/^restore_[a-f0-9]{32}$/.test(t))throw new Error(`Refusing to discard a namespace not allocated by PostgreSQL restore.`);await e.query(`DROP SCHEMA IF EXISTS "${t}" CASCADE`)}async function pruneOrphanedPostgresCaptures(e,t){const n=await e.query(`SELECT nspname AS schema, obj_description(oid, 'pg_namespace') AS note FROM pg_namespace WHERE nspname ~ '^restore_[a-f0-9]{32}$' AND pg_has_role(nspowner, 'USAGE') AND obj_description(oid, 'pg_namespace') IS NOT NULL`);const r=[];const i=createHash(`sha256`).update(t.directoryPrefix).digest(`hex`);for(const{schema:a,note:o}of n.rows){let n;try{n=JSON.parse(o)}catch{continue}const s=isRecord(n)?n.openclawCapture:void 0;if(!isRecord(s)||s.prefixHash!==i||typeof s.captureId!==`string`||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(s.captureId))continue;const c=`${t.directoryPrefix}${s.captureId}.postgres.bak`;if(await fs.lstat(c).catch(ignoreMissingPath))continue;const l=await e.query(`SELECT store_id FROM "${a}".openclaw_schema_meta`);if(l.rows.length===1&&l.rows[0].store_id===t.storeId){await discardPostgresNamespace(e,a);r.push(a)}}return r}async function fingerprintPostgresDatabase(e){const{client:t,anchor:n}=e;await t.query(`BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY`);try{return fingerprintPostgresGeneration(n,await inspectPostgresGeneration(t,n))}finally{await t.query(`ROLLBACK`)}}
//!src/snapshot/database-backup.operations.ts
async function verifyMatchedPostgresBackup(e,t,n){if((await fs.readdir(e)).includes(`.pending`))throw new Error(`PostgreSQL backup is incomplete.`);const r=await readSnapshotExportEnvelope(e);if(r.engine!==`postgres`)throw new Error(`Expected a matched PostgreSQL export.`);await verifyPostgresExportEnvelope(e,r.manifest,inspectHeldAnchor,t);if(n&&(r.manifest.source.storeId!==n.storeId||r.manifest.source.namespace!==n.namespace))throw new Error(`PostgreSQL backup belongs to a different store.`);return r.manifest}async function inspectHeldAnchor(e){const t={rootDir:resolvePreferredOpenClawTmpDir(),prefix:`openclaw-anchor-`};return await withTempWorkspace(t,async({dir:t})=>{const n=path.join(t,`anchor.sqlite`);try{var r=_usingCtx();const t=r.a(await fs.open(n,`wx`,384));await copyFileHandle(e,t)}catch(e){r.e=e}finally{await r.d()}const i=readBackupEngineImage(n,n);if(i.engine!==`postgres`)throw new Error(`Export artifact is not a PostgreSQL anchor.`);return i})}async function capturePostgresBackupInWorker(e){const{createVerifiedSqliteSnapshot:t}=await import(`./sqlite-snapshot-C6LLrZkv.mjs`);e.assertCurrent();await fs.mkdir(e.directory,{mode:448});await fs.writeFile(path.join(e.directory,`.pending`),``,{flag:`wx`,mode:384});const n=path.join(e.directory,`anchor.sqlite`);await t({sourcePath:e.sourcePath,targetPath:n,preserveRowIds:true});const r=readBackupEngineImage(n,e.sourcePath);if(r.engine!==`postgres`)throw new Error(`A PostgreSQL backup requires its original anchor.`);return await withDatabasePortPostgres(e.config,r,async(t,n)=>{const i=await admitDatabasePortDescriptor({engine:`postgres`,db:t,namespace:r.namespace},n);e.assertCurrent();const a=e.carrier?await capturePostgresSchema({...e,client:t,descriptor:i,anchor:r}):await exportPostgresBackup({...e,client:t,descriptor:i,anchor:r});try{await verifyPostgresExportEnvelope(e.directory,a,inspectHeldAnchor,e.profile);await fs.unlink(path.join(e.directory,`.pending`))}catch(e){if(a.schema)await discardPostgresNamespace(t,a.schema);throw e}requireDirectorySync(await syncDirectory(e.directory),`PostgreSQL backup`);requireDirectorySync(await syncDirectory(path.dirname(e.directory)),`PostgreSQL backup parent`);return a},e.pluginOwners)}async function preparePostgresRestoreInWorker(e){const t=await verifyMatchedPostgresBackup(e.directory,e.profile,e.expectedSource);return await withDatabasePortConnection(e.config,async n=>{const{loadDatabasePortDescriptor:r}=await import(`./port-provider-descriptor-_PSiTG9D.mjs`);const i=await r(t.source.owner,e.config,{version:t.source.schemaVersion,pluginOwners:e.pluginOwners});const{namespace:a}=await restorePostgresBackup({...e,client:n,descriptor:i,manifest:t});try{const r=getScopedDatabaseEngineSelection()?.postgres;e.assertCurrent();await i.admit?.(e.anchorPath,r);if(e.preserveUpdateHistory){if(!e.expectedSource)throw new Error(`PostgreSQL update rollback requires its captured source identity.`);const r=e.expectedSource.namespace;const o=[i,...i.fragments??[]].find(e=>e.tables.some(e=>e.name===`update_runs`));const s=o?.tables.find(e=>e.name===`update_runs`);if(!o||!s)throw new Error(`PostgreSQL rollback cannot preserve the current update history contract.`);const c=o.expectedCatalog.filter(e=>e.table===s.name);const l=readPostgresCatalog((await n.query(postgresCatalogQuery(r))).rows[0].catalog);assertPostgresCatalog(l.filter(e=>e.table===s.name),c);if(e.pluginCohortRecovery){const e=[i,...i.fragments??[]].find(e=>e.tables.some(e=>e.name===`config_machine_state`));if(!e)throw new Error(`PostgreSQL rollback cannot preserve plugin cohort recovery storage.`);assertPostgresCatalog(l.filter(e=>e.table===`config_machine_state`),e.expectedCatalog.filter(e=>e.table===`config_machine_state`))}const u=s.columns.map(({name:e})=>quoteSqliteIdentifier(e)).join(`, `);const d=e.pluginCohortRecovery;const f=d?[UPDATE_RECOVERY_KEY_PREFIX+d.runId,PLUGIN_COHORT_RECOVERY_KEY_PREFIX+d.runId]:[];e.assertCurrent();await n.query(`BEGIN; SET LOCAL synchronous_commit = on`);try{if(d){const e=await n.query(`SELECT state_key,value_json FROM ${quoteSqliteIdentifier(r)}.config_machine_state WHERE state_key = ANY($1::text[]) FOR SHARE`,[f]);const i=decodePluginCohortRecoveryPairRows(e.rows,d);if(!i)throw new Error(`PostgreSQL rollback lost its live plugin cohort recovery pair.`);const o=(await n.query(`SELECT (SELECT value_json FROM ${quoteSqliteIdentifier(a)}.config_machine_state WHERE state_key=$1) AS baseline_value,(SELECT value_json FROM ${quoteSqliteIdentifier(r)}.config_machine_state WHERE state_key=$1) AS current_value`,[INSTALLED_PLUGIN_INDEX_STATE_KEY])).rows[0];if(!o)throw new Error(`PostgreSQL rollback did not read its canonical plugin records.`);assertPluginCohortDatabaseRestoreRecords(i.cohort.publications,o.baseline_value??void 0,o.current_value??void 0);const migrationRows=async(e,t)=>t?(await n.query(`SELECT id,started_at::float8 AS started_at,finished_at::float8 AS finished_at,status,report_json FROM ${quoteSqliteIdentifier(e)}.migration_runs WHERE id LIKE $1`,[DEFERRED_PLUGIN_MIGRATION_RUN_PREFIX+`%`])).rows:[];assertPluginCohortDatabaseRestoreMigrations(i.cohort.publications,await migrationRows(a,Object.hasOwn(t.verification.tables,`migration_runs`)),await migrationRows(r,l.some(e=>e.table===`migration_runs`)))}e.assertCurrent();await n.query(`DELETE FROM ${quoteSqliteIdentifier(a)}.update_runs`);e.assertCurrent();await n.query(`INSERT INTO ${quoteSqliteIdentifier(a)}.update_runs (${u}) SELECT ${u} FROM ${quoteSqliteIdentifier(r)}.update_runs`);if(d){e.assertCurrent();await n.query(`DELETE FROM ${quoteSqliteIdentifier(a)}.config_machine_state WHERE state_key = ANY($1::text[])`,[f]);e.assertCurrent();await n.query(`INSERT INTO ${quoteSqliteIdentifier(a)}.config_machine_state (state_key,value_json,updated_at_ms) SELECT state_key,value_json,updated_at_ms FROM ${quoteSqliteIdentifier(r)}.config_machine_state WHERE state_key = ANY($1::text[])`,[f]);const t=await n.query(`SELECT state_key,value_json FROM ${quoteSqliteIdentifier(a)}.config_machine_state WHERE state_key = ANY($1::text[]) FOR SHARE`,[f]);if(!decodePluginCohortRecoveryPairRows(t.rows,d))throw new Error(`PostgreSQL rollback did not preserve its plugin cohort recovery pair.`)}e.assertCurrent();await n.query(`COMMIT`)}catch(e){await n.query(`ROLLBACK`);throw e}}const{sha256:o,size:s}=await captureDatabaseArtifact(e.anchorPath);return{namespace:a,sha256:o,sizeBytes:s}}catch(e){await discardPostgresNamespace(n,a);throw e}})}export{captureDatabaseArtifact as a,pruneOrphanedPostgresCaptures as c,assertDatabaseArtifact as i,preparePostgresRestoreInWorker as n,discardPostgresNamespace as o,verifyMatchedPostgresBackup as r,fingerprintPostgresDatabase as s,capturePostgresBackupInWorker as t};