openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5 lines • 10.5 kB
JavaScript
import{a as publishFileExclusive,c as sha256File,n as getPublishFileExclusiveFailureDetails}from"./directory-durability-o_aQCRBZ.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{t as resolvePathViaExistingAncestorSync}from"./boundary-path-BeuXNL_4.mjs";import{n as ignoreMissingPath}from"./errno-DUBt6SQQ.mjs";import"./paths-D_FOvGon.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{c as createSqliteLifecycleAggregateError}from"./sqlite-lifecycle-errors-DMaudCZS.mjs";import{Fn as object,Jn as string,Pn as number}from"./schemas-DuCQi-Qb.mjs";import{n as openNodeSqliteDatabase}from"./node-sqlite-DXyF1fBG.mjs";import{s as resolveOpenClawStateSqlitePath}from"./openclaw-state-db.paths-CbgXfEg1.mjs";import{n as formatDiskSpaceBytes,r as tryReadDiskSpace}from"./disk-space-D746MnLp.mjs";import{d as releaseSnapshotTempDirectory,t as adoptPreparedLocation}from"./sqlite-readonly-location-cleanup-CwHFt3tW.mjs";import{n as createSqliteSnapshotStagingDirectory}from"./sqlite-snapshot-staging-DUZ7pEYA.mjs";import{n as drainAgentDatabaseResources}from"./openclaw-agent-db-resources-KCMTIo4b.mjs";import{a as hasCommandProcessCleanupError}from"./exec-result-TD4w1Z1i.mjs";import{_ as prepareOpenClawStateDatabaseRemoval}from"./openclaw-state-db-cache-uycu-8uy.mjs";import{o as enableSqliteWalJournalMode}from"./sqlite-wal-BDqYXlcm.mjs";import{a as prepareVerifiedSqliteFile}from"./sqlite-snapshot-D4gm3rAo.mjs";import{i as resolvePathJournalPolicy}from"./sqlite-wal-filesystem-D27amDrp.mjs";import{t as resolveClientCredentialStorePath}from"./client-credential-paths-D__QHGyH.mjs";import{a as closeOpenClawAgentDatabaseByPathAsync}from"./openclaw-agent-db-lifecycle-CWZDU3Sk.mjs";import{r as acquireGatewayLock}from"./gateway-lock-CQoO1usb.mjs";import{i as isNeverActivatedFailedUpdate}from"./update-run-verification-DdmEDFW6.mjs";import"./update-run-ledger-De5a4xOk.mjs";import{i as getUpdateRun}from"./update-run-reader-Nkn3I5Fr.mjs";import{a as runUpdateStateInspectionWorker,r as readUpdateDatabaseGenerationsIsolated,t as parseUpdateStateInspectionWorker}from"./update-candidate-state.inspection-CZefYmrZ.mjs";import{t as readUpdateStateDatabaseSizes}from"./update-candidate-state.sizes-Cj__-I8y.mjs";import"./update-candidate-state-CF8SlkPu.mjs";import{l as withOwnedManagedUpdateEnv}from"./update-command-service-env-DPYOjBrd.mjs";import{t as runWithLocalStateOwner}from"./local-state-owner-fjzTarAw.mjs";import{i as recordAutomaticRecoveryCleanup,n as automaticRecoveryCleanupWarning}from"./update-automatic-cleanup-result-Cz-mDUxx.mjs";import{t as cleanupCompletedUpdateRecovery}from"./update-automatic-cleanup-CiAvyysM.mjs";import path from"node:path";import{randomUUID}from"node:crypto";import fs from"node:fs/promises";import{isDeepStrictEqual}from"node:util";
//!src/infra/update-database-restore.ts
async function existingFile(e){try{const t=await fs.lstat(e,{bigint:true});if(!t.isFile()||t.nlink!==1n)throw new Error(`Database recovery requires a regular, unaliased file: ${e}`);return t}catch(e){return ignoreMissingPath(e)}}async function withDatabaseExclusion(e,t,n,r,i){r();const a=await acquireGatewayLock({env:e,role:`sqlite-maintenance`,allowInTests:true,timeoutMs:0});if(!a)throw new Error(`Database rollback requires exclusive state ownership`);const o=[];const assertOwned=()=>{r();a.assertCurrent();for(const e of o)e.assertCurrent()};const drain=async e=>{const a=n[e];if(a===void 0){for(const e of t){o.push(await prepareOpenClawStateDatabaseRemoval(e,r));assertOwned()}return i(assertOwned)}return drainAgentDatabaseResources({path:a},async()=>{await closeOpenClawAgentDatabaseByPathAsync(a);assertOwned();return drain(e+1)})};let s;try{s={value:await a.run(()=>drain(0))}}catch(e){s={error:e}}if(`error`in s&&hasCommandProcessCleanupError(s.error))throw s.error;try{await a.release();for(const e of o.toReversed())e.release()}catch(e){if(`error`in s)throw createSqliteLifecycleAggregateError([s.error,e],`Database rollback and ownership cleanup both failed`,s.error);throw e}if(`error`in s)throw s.error;return s.value}async function reestablishRestoredDatabaseJournalMode(e){if(resolvePathJournalPolicy(e)!==`wal`)return;const t=openNodeSqliteDatabase(e);try{enableSqliteWalJournalMode(t,0,{databasePath:e})}finally{t.close()}}async function restoreUpdateDatabaseBackup(e){if(!/^[a-zA-Z0-9_-]{1,128}$/u.test(e.runId))throw new Error(`Database rollback requires its original update run identity.`);const{backup:t,assertCurrent:n}=e;const r=[.../* @__PURE__ */ new Set([...t.databases.map(e=>e.path),...t.missingPaths])].toSorted();const i=[];let a;let o=false;let s;const c=[];try{const l=await withDatabaseExclusion(e.env,r,[.../* @__PURE__ */ new Set([...t.sourcePaths,...r])],n,async n=>{if(e.expectedGenerations){n();const i=await readUpdateDatabaseGenerationsIsolated(r,{env:e.env,pluginOwners:t.pluginOwners});n();if(!isDeepStrictEqual(i,e.expectedGenerations)){const n=r.filter(t=>i[t]!==e.expectedGenerations?.[t]);t.restoreRefusal=`Databases changed after ${t.migration?.name??`snapshot capture`}: ${n.join(`, `)}; restoring the backup would discard later writes`;return null}}n();for(const e of t.databases){const t=await fs.open(e.snapshotPath,`r`);try{const n=await sha256File(t);if(n.digest!==e.sha256||n.bytes!==e.sizeBytes)throw new Error(`Database snapshot changed: ${e.snapshotPath}`)}finally{await t.close()}n()}const s=resolvePathViaExistingAncestorSync(resolveOpenClawStateSqlitePath(e.env));const l=t.databases.find(e=>e.path===s);const{prepareUpdateClientCredentialRestore:u}=await import(`./client-credential-restore-Dqmf-B7X.mjs`);const d=u({backup:t,env:e.env});n();const f=[...t.databases];for(const r of f){if(r.engine!==`postgres`)continue;if(!r.exportDirectory||!r.storeId||!r.namespace)throw new Error(`PostgreSQL rollback is missing its matched capture identity.`);const{createConfigIO:a}=await import(`./io-Daz-kTPd.mjs`);const{config:o}=await a({env:e.env,observe:false,pluginValidation:`core-only`,shellEnvFallback:`defer`}).readConfigFileSnapshot();e.onLiveMutation?.();const{preparePostgresRestore:c}=await import(`./database-backup-uv1npbi6.mjs`);const l=`${r.snapshotPath}.restored-${e.runId}-${randomUUID()}`;const u=await c({directory:r.exportDirectory,anchorPath:l,config:o,pluginOwners:t.pluginOwners,profile:`exact`,assertCurrent:n,preserveUpdateHistory:r.path===s,pluginCohortRecovery:r.path===s?e.pluginCohortRecovery:void 0,expectedSource:{storeId:r.storeId,namespace:r.namespace}});f[f.indexOf(r)]={...r,...u,snapshotPath:l};i.push(`PostgreSQL namespace ${r.namespace}`)}if(r.includes(s)&&l?.engine!==`postgres`){if(!l)throw new Error(`Database rollback cannot preserve update history without its shared snapshot.`);const r=await createSqliteSnapshotStagingDirectory(t.directory);const i=path.join(r,`shared.sqlite`);a=adoptPreparedLocation(i,r);const o={nodeRunner:process.execPath,sourceEnv:e.env,stagingRoot:r};n();const c=await readUpdateStateDatabaseSizes([s,l.snapshotPath],o);n();const u=parseUpdateStateInspectionWorker(await runUpdateStateInspectionWorker({...o,databases:c,input:{mode:`database-restore-preparation`,stateDir:resolveStateDir(e.env),config:{},baseline:l,currentPath:s,targetPath:i,stagingRoot:r,pluginCohortRecovery:e.pluginCohortRecovery}}),object({sha256:string().regex(/^[a-f0-9]{64}$/u),sizeBytes:number().int().nonnegative(),userVersion:number().int().nonnegative()}));n();f[f.indexOf(l)]={...l,...u,snapshotPath:i}}const p=[];for(const t of r)for(const n of[``,`-wal`,`-shm`,`-journal`]){const r=`${t}${n}`;const i=`${t}.migrated-${e.runId}${n}`;if(await existingFile(i))throw new Error(`Migrated database recovery file already exists: ${i}`);const a=await existingFile(r);if(a)p.push({source:r,target:i,identity:a})}for(const e of f){n();const t=await fs.lstat(e.snapshotPath,{bigint:true});n();c.push(await prepareVerifiedSqliteFile({sourcePath:e.snapshotPath,sourceIdentity:t,targetPath:e.path,expectedContent:{sha256:e.sha256,sizeBytes:e.sizeBytes},requireAtomicPublication:true,beforeByteCopy:t=>{const r=path.dirname(e.path);const i=tryReadDiskSpace(r);const a=t+67108864;if(!i||i.availableBytes<a)throw new Error(`Database rollback needs ${formatDiskSpaceBytes(a)} near ${r} for a writable copy; ${i?`${formatDiskSpaceBytes(i.availableBytes)} is available`:`available space could not be measured`}. Current databases have not been moved.`);n()},beforePublish:n,afterPublish:e=>e.assertTargetMatchesExpectedContent(n)}));n()}e.onLiveMutation?.();for(const e of p){n();try{await publishFileExclusive({sourcePath:e.source,targetPath:e.target,expectedSourceIdentity:e.identity,strategy:`rename-noreplace`})}catch(e){o||=getPublishFileExclusiveFailureDetails(e)?.targetCreated===true;throw e}o=true;i.push(e.target);n()}for(const e of c){n();o=true;await e.publish();n()}const m=resolvePathViaExistingAncestorSync(resolveClientCredentialStorePath(e.env));const h=[];for(const e of f){n();if(e.path===m)continue;try{await reestablishRestoredDatabaseJournalMode(e.path)}catch(t){h.push(`${e.path}: ${formatErrorMessage(t)}`)}}d?.();n();if(h.length>0)e.onJournalReconciliationFailures?.(h);n();return i});o=false;s={value:l}}catch(e){s={error:e};o||=hasCommandProcessCleanupError(e)}if(o){if(a)releaseSnapshotTempDirectory(path.dirname(a.location))}else{const e=(await Promise.allSettled([...c.map(e=>e.cleanup()),...a?[a.cleanupAsync()]:[]])).filter(e=>e.status===`rejected`);if(e.length>0){const t=[...`error`in s?[s.error]:[],...e.map(e=>e.reason)];throw createSqliteLifecycleAggregateError(t,`Database rollback output cleanup failed`,t[0])}}if(`error`in s)throw s.error;return s.value}
//!src/cli/update-cli/automatic-cleanup.ts
function failedBeforeActivation(e,t){try{const n=getUpdateRun(e,{env:t});return n!==void 0&&isNeverActivatedFailedUpdate(n)}catch{return false}}async function automaticallyCleanUpdateRecovery(e,t){const n=performance.now();let r;try{r=await withOwnedManagedUpdateEnv(t,()=>runWithLocalStateOwner({method:`update.recovery.cleanup`,params:{runId:e},target:`completed update recovery artifacts`,recoveryCommand:`openclaw update cleanup --dry-run`,timeoutMs:3e5,runLocal:async({env:t,assertCurrent:n})=>recordAutomaticRecoveryCleanup(e,await cleanupCompletedUpdateRecovery(e,t,n),t,n)}))}catch(e){r=automaticRecoveryCleanupWarning(e)}if(r)r.durationMs=Math.round(performance.now()-n);return r}export{failedBeforeActivation as n,restoreUpdateDatabaseBackup as r,automaticallyCleanUpdateRecovery as t};