import type { PGlite } from '@electric-sql/pglite'; export const CACHE_MAINTENANCE_INTERVAL = 60_000; export async function startCacheMaintenance( db: Pick & Partial>, interval = CACHE_MAINTENANCE_INTERVAL ): Promise { await db.exec('VACUUM (ANALYZE, PROCESS_TOAST)'); let stopped = false; let failure: Error | undefined; let timer: ReturnType; let pending: Promise | undefined; const execProtocol = db.execProtocol.bind(db); const close = db.close.bind(db); if (db.execProtocolRaw) { const raw = db.execProtocolRaw.bind(db); db.execProtocolRaw = (...args) => { if (failure) return Promise.reject(failure); return raw(...args); }; } if (db.execProtocolStream) { const stream = db.execProtocolStream.bind(db); db.execProtocolStream = (...args) => { if (failure) return Promise.reject(failure); return stream(...args); }; } db.execProtocol = (...args) => { if (failure) return Promise.reject(failure); return execProtocol(...args); }; const schedule = () => { timer = setTimeout(() => { pending = maintain(); }, interval); }; const maintain = async () => { try { await db.exec('VACUUM (ANALYZE, PROCESS_TOAST)'); } catch (cause) { failure = new Error('Cache maintenance failed; persistent cache is disabled', { cause }); stopped = true; } if (!stopped) schedule(); }; db.close = async () => { stopped = true; clearTimeout(timer); await pending; await close(); }; schedule(); }