UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

19 lines • 24.1 kB
import{i as extractErrorCode,t as coerceErrorMessage}from"./error-coercion-B-1Loz4b.mjs";import{a as isRecord}from"./record-coerce-DwDZngEy.mjs";import{l as resolveGlobalSingleton}from"./string-coerce-BBqv4GXj.mjs";import{m as recordSqliteSnapshotFailure,y as withSqliteNativeOpen}from"./sql-connection-D2qSU3Um.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{c as isPathInside}from"./state-dir-C22DK7p0.mjs";import{r as getChildLogger,s as registerProcessExitCleanup,u as registerSignalExitFinalizer}from"./subsystem-BMw5Czn-.mjs";import{i as throwSettledAggregate,n as materializeErrorStack,t as collectSynchronousErrors}from"./error-graph-internal-CZk3K2nJ.mjs";import{i as runWithAsyncStore}from"./plugin-instance-invocation-D2U32-yV.mjs";import{o as executeWithCachedStatement}from"./kysely-sync-cache-state-CObqh5XE.mjs";import{t as assertDatabaseFileIdentity}from"./sqlite-worker-identity-gGA4fE_R.mjs";import{t as AsyncContext}from"./async-context-BikFC1Fp.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{a as SqliteSnapshotCleanupError,c as createSqliteLifecycleAggregateError,o as SqliteSnapshotDirectoryBusyError,s as classifyRetiredSqliteSnapshotRemovalError}from"./sqlite-lifecycle-errors-BKA8AtC6.mjs";import{A as retireSqliteDatabaseAdmissionForPath,mt as readSqliteDatabaseAdmissionIdentity,q as withSqliteDatabaseAdmissionSettlement,r as captureSqliteDatabaseDescriptorCustodyLocations,st as captureSqliteDatabaseAdmissions}from"./sqlite-database-admission-BikxIIFA.mjs";import{n as resolveExistingSqliteFileUri,t as openNodeSqliteDatabase}from"./node-sqlite-CX_zY7OF.mjs";import{i as createRetainedOperation,s as mapRetainedOperation}from"./runtime-worker-generation-CkIyHyJk.mjs";import fsSync from"node:fs";import path from"node:path";import{copyRootFileSync,sameFileIdentity}from"@openclaw/fs-safe/advanced";import{FsSafeError}from"@openclaw/fs-safe/errors";import fsPromises from"node:fs/promises";import{sha256FileSync,syncDirectorySync}from"@openclaw/fs-safe/durability"; //!src/infra/private-directory-creation.ts const refusedCreations=/* @__PURE__ */ new WeakSet;function markPrivateDirectoryCreationRefused(e){if(e!==null&&typeof e===`object`)refusedCreations.add(e);return e}function isPrivateDirectoryCreationRefused(e){return e!==null&&typeof e===`object`&&refusedCreations.has(e)} //!src/infra/sqlite-snapshot-capacity-error.ts const SQLITE_SNAPSHOT_CAPACITY_ERROR_NAME=`SqliteSnapshotCapacityError`;var SqliteSnapshotCapacityError=class extends Error{constructor(e,t){super(e,t);this.name=SQLITE_SNAPSHOT_CAPACITY_ERROR_NAME}};function hasSqliteSnapshotCapacityCode(e){const{code:t,errcode:n}=e;return t===`ENOSPC`||t===`EDQUOT`||n===13} //!src/infra/directory-durability.ts function requireDirectorySync(e,t){if(e.status!==`unsupported`||process.platform===`win32`)return;const n=e.code?` (${e.code})`:``;throw new Error(`${t} does not support crash-durable directory synchronization${n}.`)} //!src/infra/file-descriptor.ts function sameFileMutationFingerprint(e,t){return e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.dev===t.dev&&e.ino===t.ino&&e.mtimeNs===t.mtimeNs&&e.size===t.size}function hashFileDescriptorSync(e,t){const{digest:n,bytes:r}=sha256FileSync(e,{maxBytes:t});return{sha256:n,sizeBytes:r}}function flushAndHashFileSync(e){const t=fsSync.openSync(e,`r+`);try{fsSync.fsyncSync(t);return hashFileDescriptorSync(t)}finally{fsSync.closeSync(t)}} //!src/infra/sqlite-snapshot-file.ts function assertExpectedContent(e,t,n){if(e.sizeBytes!==t.sizeBytes)throw new Error(`SQLite snapshot size mismatch for ${n}: expected ${t.sizeBytes}, got ${e.sizeBytes}`);if(e.sha256!==t.sha256)throw new Error(`SQLite snapshot hash mismatch for ${n}: expected ${t.sha256}, got ${e.sha256}`)}function assertOpenFileIdentitySync(e,t,n){const r=fsSync.fstatSync(e,{bigint:true});const i=fsSync.lstatSync(t,{bigint:true});if(!r.isFile()||!i.isFile()||!sameFileIdentity(n,r)||!sameFileIdentity(n,i))throw new Error(`SQLite snapshot file changed: ${t}`)}function hashPublishedFileSync(e,t,n=hashFileDescriptorSync){const r=fsSync.openSync(e,`r`);try{assertOpenFileIdentitySync(r,e,t);const i=fsSync.fstatSync(r,{bigint:true});const a=n(r);const o=fsSync.fstatSync(r,{bigint:true});if(!sameFileMutationFingerprint(i,o)){if(!sameFileStatFingerprint(i,o))throw new Error(`SQLite snapshot file changed while reading: ${e}`);assertExpectedContent(n(r),a,e)}assertOpenFileIdentitySync(r,e,t);return a}finally{fsSync.closeSync(r)}}function sameFileStatFingerprint(e,t){return sameFileIdentity(e,t)&&e.size===t.size} //!src/infra/sqlite-staging-token.ts const SQLITE_STAGING_TOKEN_FILES=[`owner.sqlite`,`owner.sqlite-journal`,`owner.sqlite-wal`,`owner.sqlite-shm`];var SqliteStagingRetiredError=class extends Error{constructor(){super(`SQLite snapshot parent retired; aborting snapshot allocation`)}};function acquireSqliteStagingToken(e,t,n={}){const r=withSqliteDatabaseAdmissionSettlement;const acquire=()=>acquireStagingToken(e,t,n);const i=t===`create`?acquire():r(acquire);const a=Object.assign(e=>r(()=>i(e)),{beginRetirement:()=>{r(()=>i.beginRetirement());return a}});return a}function acquireStagingToken(e,t,n){const r=path.join(e,SQLITE_STAGING_TOKEN_FILES[0]);const readIdentity=(e,t)=>{const n=fsSync.lstatSync(e,{bigint:true});if(!(t===`directory`?n.isDirectory():n.isFile())||process.platform===`win32`&&(n.dev===0n||n.ino===0n))throw new Error(`SQLite staging ownership is unknown`);return n};const i=readIdentity(e,`directory`);const a=SQLITE_STAGING_TOKEN_FILES.map(t=>fsSync.lstatSync(path.join(e,t),{throwIfNoEntry:false}));const o=a[0];if(a.some(e=>e&&(!e.isFile()||process.getuid&&e.uid!==process.getuid()))||!o&&t!==`create`&&!n.allowMissing)throw new Error(`SQLite snapshot token ownership is unknown`);if(t===`create`&&!o)fsSync.writeFileSync(r,``,{flag:`wx`,mode:420});const s=o!==void 0||t===`create`;const c=s?readIdentity(r,`file`):void 0;if(n.expectedIdentity){if(!c)throw new Error(`SQLite staging ownership is unknown`);assertDatabaseFileIdentity(c,n.expectedIdentity)}const l=withSqliteNativeOpen(()=>openNodeSqliteDatabase(s?resolveExistingSqliteFileUri(r):r,{timeout:0},c&&readSqliteDatabaseAdmissionIdentity(c)));let u;const read=e=>executeWithCachedStatement(l,e,[],e=>e.get());let d=t===`reclaim`||t===`create`&&n.exclusiveCreate===true;let f=false;const assertIdentity=()=>{const t=readIdentity(e,`directory`);if(i.dev!==t.dev||i.ino!==t.ino)throw new Error(`SQLite staging ownership changed before retirement`);const n=readIdentity(r,`file`);if(u.dev!==n.dev||u.ino!==n.ino)throw new Error(`SQLite staging ownership changed before retirement`)};const beginRetirement=()=>{assertIdentity();if(!l.isTransaction||!d){if(l.isTransaction)l.exec(`ROLLBACK`);l.exec(`BEGIN EXCLUSIVE`);d=true}return p};const release=(e=false)=>{if(!l.isOpen)return;if(e){beginRetirement();if(!f)l.exec(`PRAGMA user_version=1`);l.exec(`COMMIT`);f=true}else if(l.isTransaction)l.exec(`ROLLBACK`);l.close();if(e)retireSqliteDatabaseAdmissionForPath(r)};const p=Object.assign(release,{beginRetirement});try{u=c??readIdentity(r,`file`);if(d)l.exec(`BEGIN EXCLUSIVE`);else if(t===`create`)l.exec(`BEGIN IMMEDIATE`);else l.exec(`BEGIN`);if(t!==`create`||o){const e=read(`PRAGMA journal_mode`);if(!isRecord(e)||e.journal_mode!==`delete`)throw new Error(`SQLite snapshot token journal mode is unknown`);const n=read(`PRAGMA user_version`);const r=isRecord(n)?n.user_version:void 0;if(r!==0&&(t!==`reclaim`||r!==1))throw new SqliteStagingRetiredError;f=r===1}assertIdentity();return p}catch(e){release();throw e}} //!src/infra/sqlite-snapshot-retirement.ts const SQLITE_SNAPSHOT_PREFIX=`openclaw-sqlite-readonly-v2-`;const SCHEMA_DISCOVERY_OWNERSHIP_FILENAME=`schema-discovery-ownership.json`;const suffix=`(?:[A-Za-z0-9]{6}|[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12})$`;const SQLITE_SNAPSHOT_LEGACY_MARKER=new RegExp(`^openclaw-sqlite-readonly-[1-9]\\d*-${suffix}`,`u`);const tokenMarker=new RegExp(`^${SQLITE_SNAPSHOT_PREFIX}${suffix}`,`u`);const fsSafeTemporaryPayload=/^\.fs-safe-[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}\.tmp$/u;const SQLITE_SNAPSHOT_LEGACY_AGE_MS=864e5;function releaseTokens(e){const t=collectSynchronousErrors(e,e=>e());if(t.length)throw new AggregateError(t,`SQLite snapshot retirement token release failed`)}const isSqliteSnapshotStagingName=e=>SQLITE_SNAPSHOT_LEGACY_MARKER.test(e)||tokenMarker.test(e);function acquireSqliteSnapshotToken(e,t){return acquireSqliteStagingToken(e,t,{allowMissing:SQLITE_SNAPSHOT_LEGACY_MARKER.test(path.basename(e))})}function beginSqliteSnapshotRetirement(e,t={}){const n=[];const r=[];const release=()=>releaseTokens(n.filter(e=>e!==t.token));if(!fsSync.existsSync(e)){t.token?.();return{bytes:0,payload:r,release,retire:()=>{}}}function inspect(i,a,o=``,s=true){const c=fsSync.lstatSync(i);if(!c.isDirectory()||process.getuid&&c.uid!==process.getuid())throw new Error(`Snapshot directory ownership is unknown`);const l=!o&&SQLITE_SNAPSHOT_LEGACY_MARKER.test(path.basename(i));if(!o&&t.allowLegacy===false&&!tokenMarker.test(path.basename(i)))throw new Error(`Legacy or unrecognized snapshot requires offline operator cleanup`);const u=t.cutoff!==void 0&&l?Math.min(a,Date.now()-SQLITE_SNAPSHOT_LEGACY_AGE_MS):a;const d=l?`Legacy snapshot contains activity newer than 24 hours`:`Snapshot contains activity within the reclamation grace period`;if(c.mtimeMs>=u)throw new Error(d);if(l&&s&&t.cutoff!==void 0)inspect(i,u,o,false);if(!o&&s)n.push(i===e&&t.token?t.token.beginRetirement():acquireSqliteSnapshotToken(i,`reclaim`));let f=0;let p=c.mtimeMs;for(const e of fsSync.readdirSync(i,{withFileTypes:true})){const n=path.join(i,e.name);const a=fsSync.lstatSync(n);if(process.getuid&&a.uid!==process.getuid())throw new Error(`Snapshot file ownership is unknown`);if((!o||t.cutoff===void 0)&&a.isFile()&&SQLITE_STAGING_TOKEN_FILES.some(t=>t===e.name))continue;p=Math.max(p,a.mtimeMs);if(a.isDirectory()){const r=isSqliteSnapshotStagingName(e.name);const i=r?``:[o,e.name].filter(Boolean).join(`/`);if(t.cutoff!==void 0&&(!r&&![`openclaw`,`openclaw-state`,`openclaw-state/state`].includes(i)&&!/^openclaw\/sqlite-[a-f0-9]{24}$/u.test(i)||r&&o!==``&&o!==`openclaw`&&!/^openclaw\/sqlite-[a-f0-9]{24}$/u.test(o)))throw new Error(`Unrecognized snapshot directory`);const a=inspect(n,u,i,s);f+=a.bytes;p=Math.max(p,a.newest)}else if(t.cutoff===void 0||a.isFile()&&(o===`openclaw-state/state`?/^openclaw\.sqlite(?:-wal|-shm|-journal)?$/u.test(e.name):!o&&(/^(?:first|database\.sqlite(?:\.partial)?(?:-wal|-shm|-journal)?)$/u.test(e.name)||e.name===`schema-discovery-ownership.json`||fsSafeTemporaryPayload.test(e.name)||/^inspection-result-[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}\.json$/u.test(e.name)))){f+=a.size;if(s)r.push(n)}else throw new Error(`Unrecognized snapshot artifact`)}if(p>=u)throw new Error(d);return{bytes:f,newest:p}}try{const{bytes:i}=inspect(e,t.cutoff??Number.POSITIVE_INFINITY);return{bytes:i,payload:r,release,retire:()=>{for(const e of n)e(true)}}}catch(e){release();throw e}} //!src/infra/sqlite-readonly-location-cleanup.ts function deferSqliteSnapshotCleanupAfterRead(e,t){const n=e instanceof SqliteSnapshotDirectoryBusyError?e:e instanceof SqliteSnapshotCleanupError?e.cause:void 0;if(!(n instanceof SqliteSnapshotDirectoryBusyError))return false;try{getChildLogger({subsystem:`infra/sqlite-snapshot`}).warn({path:t,errorCode:extractErrorCode(n.cause)},`SQLite snapshot cleanup deferred until open files are released.`)}catch{}return true}function settleSqliteSnapshotRequest(e){return e.result.catch(async t=>{let n=t;try{await e.startClose().result}catch(e){if(e!==t){const r=createSqliteLifecycleAggregateError([t,e],`SQLite snapshot allocation and cleanup failed`,t);n=t instanceof SqliteSnapshotCleanupError?new SqliteSnapshotCleanupError(t.message,{cause:r}):r}}recordSqliteSnapshotFailure(n);throw n})}const cleanupState=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteSnapshotCleanup`),()=>({directories:/* @__PURE__ */ new Map,activeWork:/* @__PURE__ */ new Map,exitHandlerInstalled:false,pendingSignalCleanup:void 0,signalCleanup:cleanupSnapshotOperations}));const snapshotDirectories=cleanupState.directories;const activeSnapshotWork=cleanupState.activeWork;function snapshotDirectory(e){let t=snapshotDirectories.get(e);if(!t){t={readers:/* @__PURE__ */ new Set};snapshotDirectories.set(e,t)}return t}function completeSnapshotDirectoryRemoval(e){snapshotDirectories.delete(e);return true}function cleanupSnapshotOperations(){cleanupState.pendingSignalCleanup??=(async()=>{const e=snapshotDirectories.entries();while(true){while(activeSnapshotWork.size>0){for(const e of activeSnapshotWork.values())e();await Promise.allSettled(activeSnapshotWork.keys())}const t=e.next();if(t.done)break;const[n]=t.value;await removeTempDirectoryAsync(n,e=>emitSnapshotCleanupFailure({cleanupRoot:n,operation:`rm`,code:extractErrorCode(e)}))}})().finally(()=>{cleanupState.pendingSignalCleanup=void 0});return cleanupState.pendingSignalCleanup}function retainSnapshotWork(e,t=()=>{}){registerSnapshotCleanup();activeSnapshotWork.set(e,t);const release=()=>activeSnapshotWork.delete(e);e.then(release,release);return e}function registerSnapshotTempDirectory(e,t){const n=snapshotDirectory(e);n.release=t??n.release;registerSnapshotCleanup()}function registerSnapshotCleanup(){if(!cleanupState.exitHandlerInstalled){cleanupState.exitHandlerInstalled=true;registerProcessExitCleanup(()=>{for(const e of activeSnapshotWork.values())e();if(activeSnapshotWork.size===0)for(const e of snapshotDirectories.keys())removeTempDirectory(e)})}registerSignalExitFinalizer(cleanupState.signalCleanup)}function registerRetainedSnapshotTempDirectory(e,t){snapshotDirectory(e).releaseRetained=t;registerSnapshotCleanup()}function retainSnapshotTempDirectory(e){registerSnapshotTempDirectory(e);const t=snapshotDirectory(e);if(t.retirementStarted)throw new SqliteSnapshotCleanupError(`SQLite snapshot retirement has started`);const n=Symbol(`sqlite.snapshot.reader`);t.readers.add(n);return()=>t.readers.delete(n)}const tempDirectoryRemovalOptions={force:true,maxRetries:3,recursive:true,retryDelay:20};function emitSnapshotCleanupFailure(e,t){if(t)try{t(e);return}catch{}try{getChildLogger({subsystem:`infra/sqlite-snapshot`}).warn({path:e.cleanupRoot,operation:e.operation,errorCode:e.code},`SQLite read-only snapshot cleanup failed. Check directory permissions and available storage before retrying.`)}catch{}}function assertSnapshotReadersRetired(e){if(e?.readers.size)throw new SqliteSnapshotCleanupError(`SQLite snapshot still belongs to an active reader`)}function prepareSnapshotRetirement(e,t){assertSnapshotReadersRetired(t);if(t?.releaseRetained)throw new SqliteSnapshotCleanupError(`SQLite snapshot requires asynchronous cleanup`);if(t?.retired||!t?.release&&!fsSync.existsSync(path.join(e,SQLITE_STAGING_TOKEN_FILES[0])))return;if(t)t.retirementStarted=true;return beginSqliteSnapshotRetirement(e,{token:t?.release})}function*shrinkSnapshotPayload(e){const t=fsSync.lstatSync(e,{throwIfNoEntry:false});if(t?.isDirectory())for(const t of fsSync.readdirSync(e))yield*shrinkSnapshotPayload(path.join(e,t));else if(t?.isFile()&&t.nlink>1)fsSync.unlinkSync(e);else if(t?.isFile()&&t.nlink===1&&t.size>64*1024**2){const n=fsSync.openSync(e,fsSync.constants.O_RDWR|fsSync.constants.O_NOFOLLOW);try{for(let e=t.size;e>64*1024**2;){e-=64*1024**2;yield{fd:n,size:e}}}finally{fsSync.closeSync(n)}}}async function shrinkSnapshotPayloadAsync(e){for(const{fd:t,size:n}of shrinkSnapshotPayload(e))await retainSnapshotWork(new Promise((e,r)=>{fsSync.ftruncate(t,n,t=>t?r(t):e())}))}function*retireSqliteSnapshotPayload(e){for(const t of e.payload){retireSqliteDatabaseAdmissionForPath(t);for(const{fd:e,size:n}of shrinkSnapshotPayload(t)){fsSync.ftruncateSync(e,n);yield}fsSync.rmSync(t,tempDirectoryRemovalOptions)}e.retire()}function removeTempDirectory(e,t){let n=snapshotDirectories.get(e);if(n)n.cleanupFailure=void 0;try{const t=prepareSnapshotRetirement(e,n);try{if(t){for(const e of retireSqliteSnapshotPayload(t));n=snapshotDirectory(e);n.release=void 0;n.retired=true}else if(!n?.retired)for(const{fd:t,size:n}of shrinkSnapshotPayload(e))fsSync.ftruncateSync(t,n);try{fsSync.rmSync(e,tempDirectoryRemovalOptions)}catch(t){throw classifyRetiredSqliteSnapshotRemovalError(e,t)}}finally{t?.release()}return completeSnapshotDirectoryRemoval(e)}catch(n){registerSnapshotTempDirectory(e);snapshotDirectory(e).cleanupFailure=n;t?.(n);return false}}async function removeTempDirectoryAsync(e,t){let n=snapshotDirectories.get(e);if(n?.releaseRetained){const r=await startRemoveTempDirectory(e,t,n).result;if(r)snapshotDirectories.delete(e);return r}if(n)n.cleanupFailure=void 0;try{const t=prepareSnapshotRetirement(e,n);try{for(const e of t?.payload??[]){retireSqliteDatabaseAdmissionForPath(e);await shrinkSnapshotPayloadAsync(e);await retainSnapshotWork(fsSync.promises.rm(e,tempDirectoryRemovalOptions))}if(t){t.retire();n=snapshotDirectory(e);n.release=void 0;n.retired=true}else if(!n?.retired)await shrinkSnapshotPayloadAsync(e);try{await retainSnapshotWork(fsSync.promises.rm(e,tempDirectoryRemovalOptions))}catch(t){throw classifyRetiredSqliteSnapshotRemovalError(e,t)}}finally{t?.release()}return completeSnapshotDirectoryRemoval(e)}catch(n){registerSnapshotTempDirectory(e);snapshotDirectory(e).cleanupFailure=n;t?.(n);return false}}function startRemoveTempDirectory(e,t,n=snapshotDirectories.get(e)){if(n?.retiringRetained)return n.retiringRetained;let r;const i=createRetainedOperation(()=>{if(!r||i.operation.read().status!==`pending`)return;r.service();const a=r.read();if(a.status===`pending`)return;if(n)n.retiringRetained=void 0;if(a.status===`rejected`){snapshotDirectory(e).cleanupFailure=a.error;t?.(a.error);i.resolve(false)}else i.resolve(completeSnapshotDirectoryRemoval(e))});try{if(n)n.cleanupFailure=void 0;sealRetainedSnapshotTempDirectory(e);if(!n?.releaseRetained)throw new SqliteSnapshotCleanupError(`SQLite snapshot has no retained cleanup owner`);n.retiringRetained=i.operation;r=n.releaseRetained();r.result.then(()=>i.operation.service(),()=>i.operation.service());i.operation.service()}catch(r){snapshotDirectory(e).cleanupFailure=r;if(n)n.retiringRetained=void 0;t?.(r);i.resolve(false)}return i.operation}function sealRetainedSnapshotTempDirectory(e,t){const n=snapshotDirectories.get(e);if(!n?.releaseRetained)throw new SqliteSnapshotCleanupError(`SQLite snapshot has no retained cleanup owner`);if(t?.requireRequested&&!n.retirementStarted)throw new SqliteSnapshotCleanupError(`SQLite snapshot is still owned; cleanup has not been requested`);const r=[...snapshotDirectories].filter(([t])=>isPathInside(e,t));for(const[,e]of r)assertSnapshotReadersRetired(e);for(const[,e]of r)e.retirementStarted=true;const i=/* @__PURE__ */ new Set([...captureSqliteDatabaseAdmissions().map(({location:e})=>e),...captureSqliteDatabaseDescriptorCustodyLocations()]);for(const t of i)if(isPathInside(e,t))retireSqliteDatabaseAdmissionForPath(t)}function preparationCleanupError(e,t){return createSqliteLifecycleAggregateError(e,`${t} and cleanup failed: ${coerceErrorMessage(e[0])}`,e[0])}function discardPreparedCopyPayload(e,t){try{for(const t of[`database.sqlite`,`database.sqlite.partial`])for(const n of[``,`-wal`,`-shm`,`-journal`]){const r=path.join(e,`${t}${n}`);retireSqliteDatabaseAdmissionForPath(r);for(const{fd:e,size:t}of shrinkSnapshotPayload(r))fsSync.ftruncateSync(e,t);fsSync.rmSync(r,{force:true})}}catch(e){throw preparationCleanupError([t,e],`SQLite snapshot preparation`)}}async function cleanupFailedSnapshotPreparation(e,t,n,r){if(r)discardPreparedCopyPayload(e,t);else{const r=[t];if(!await removeTempDirectoryAsync(e,e=>r.push(e)))throw preparationCleanupError(r,n)}throw t}function publishPreparedCopy(e,t){const n=path.join(e,`database.sqlite`);for(const t of[`-wal`,`-shm`,`-journal`,``]){const i=`${n}.partial${t}`;if(fsSync.existsSync(i)){const a=`${n}${t}`;try{fsSync.renameSync(i,a)}catch(t){try{var r=_usingCtx();if(!hasErrnoCode(t,`EXDEV`))throw t;const n=r.u(copyRootFileSync({source:{rootPath:e,absolutePath:i},destination:{rootPath:e,absolutePath:a},mode:384}));fsSync.fsyncSync(n.fd);for(const{fd:e,size:t}of shrinkSnapshotPayload(i))fsSync.ftruncateSync(e,t);fsSync.rmSync(i,{force:true})}catch(e){r.e=e}finally{r.d()}}}}let i;if(t){const e=fsSync.lstatSync(n,{bigint:true});assertExpectedContent(hashPublishedFileSync(n,e),t,n);i={...t,identity:e}}return{...adoptPreparedLocation(n,e),journalFreeContent:i}}function adoptPreparedLocation(e,t,n=false,r){const i=t??path.dirname(e);registerSnapshotTempDirectory(i);let a=true;let o;let s;let c=false;const reportFailure=e=>{if(!n&&!c){c=true;emitSnapshotCleanupFailure({cleanupRoot:i,operation:`rm`,code:extractErrorCode(e)},r)}};const complete=e=>{if(e){a=false;snapshotDirectories.delete(i)}else if(n)throw new SqliteSnapshotCleanupError(`SQLite read-only worker snapshot cleanup failed: ${i}`,{cause:snapshotDirectories.get(i)?.cleanupFailure});return e};const startCleanup=()=>{if(s?.read().status===`pending`)return s;if(!a){const e=createRetainedOperation(()=>{});e.resolve(complete(true));return s=e.operation}return s=mapRetainedOperation(startRemoveTempDirectory(i,reportFailure),complete)};return{location:e,cleanupRoot:i,cleanup:()=>{if(o||s?.read().status===`pending`)return n?complete(false):false;if(!a)return complete(true);return complete(removeTempDirectory(i,reportFailure))},cleanupAsync:()=>{if(snapshotDirectories.get(i)?.releaseRetained||s)return startCleanup().result;if(o)return o;if(!a)return Promise.resolve(complete(true));o=Promise.resolve().then(()=>removeTempDirectoryAsync(i,reportFailure)).then(complete).finally(()=>{o=void 0});return o},startCleanup}} //!src/infra/sqlite-readonly-worker-context.ts const readOnlyWorkerScope=new AsyncContext(Symbol(`sqliteReadOnlyWorkerScope`));function resolveSqliteInspectionSignal(e){const t=readOnlyWorkerScope.getStore();return t?e?AbortSignal.any([e,t.controller.signal]):t.controller.signal:e}var SqliteReadOnlyWorkerScopeClosedError=class extends Error{constructor(){super(`SQLite read-only worker scope closed`);this.code=`SQLITE_READONLY_WORKER_SCOPE_CLOSED`}};function createSqliteReadOnlyWorkerScope(e){const t={active:true,busy:false,controller:new AbortController,pending:/* @__PURE__ */ new Set,deadlineOwnedByCaller:e?.deadlineOwnedByCaller??false};const abort=()=>t.controller.abort(e?.signal.reason);e?.signal.addEventListener(`abort`,abort,{once:true});if(e?.signal.aborted)abort();let n;return{run(e){return runWithAsyncStore(readOnlyWorkerScope,t,e)},close(){n??=(async()=>{e?.signal.removeEventListener(`abort`,abort);t.active=false;t.controller.abort(new SqliteReadOnlyWorkerScopeClosedError);materializeErrorStack(t.controller.signal.reason);await Promise.allSettled(t.pending);const n=await Promise.allSettled([t.worker?.close(),t.releaseReadWorker?.()]);throwSettledAggregate(n,`SQLite read-only worker scope cleanup failed`)})();return n}}}export{hasSqliteSnapshotCapacityCode as A,acquireSqliteStagingToken as C,requireDirectorySync as D,hashFileDescriptorSync as E,markPrivateDirectoryCreationRefused as M,syncDirectorySync as O,SQLITE_STAGING_TOKEN_FILES as S,flushAndHashFileSync as T,sealRetainedSnapshotTempDirectory as _,adoptPreparedLocation as a,SQLITE_SNAPSHOT_PREFIX as b,discardPreparedCopyPayload as c,registerRetainedSnapshotTempDirectory as d,registerSnapshotTempDirectory as f,retainSnapshotWork as g,retainSnapshotTempDirectory as h,resolveSqliteInspectionSignal as i,isPrivateDirectoryCreationRefused as j,SqliteSnapshotCapacityError as k,preparationCleanupError as l,removeTempDirectoryAsync as m,createSqliteReadOnlyWorkerScope as n,cleanupFailedSnapshotPreparation as o,removeTempDirectory as p,readOnlyWorkerScope as r,deferSqliteSnapshotCleanupAfterRead as s,SqliteReadOnlyWorkerScopeClosedError as t,publishPreparedCopy as u,settleSqliteSnapshotRequest as v,sameFileStatFingerprint as w,acquireSqliteSnapshotToken as x,startRemoveTempDirectory as y};