fix(backup): snapshot the core DB and swap restores atomically

createBackup archived travel.db via the archiver's lazy live-file read, so a WAL
auto-checkpoint firing mid-stream could write a torn database into the zip. It now
VACUUM INTOs a point-in-time snapshot and archives that, the same guarantee plugin
DBs already get. restoreFromZip swapped the DB by unlink-then-copy, which on an
interrupted restore could leave no valid travel.db; it now copies to a temp file and
renames it into place (atomic), dropping the stale -wal/-shm sidecars first.
This commit is contained in:
Maurice
2026-07-11 21:52:53 +02:00
parent 512fc51f3e
commit 6584696894
2 changed files with 33 additions and 7 deletions
+29 -5
View File
@@ -169,6 +169,7 @@ export async function createBackup(): Promise<BackupInfo> {
const filename = `backup-${timestamp}.zip`;
const outputPath = path.join(backupsDir, filename);
const pdataSnap = path.join(backupsDir, `.plugins-snap-${timestamp}`);
const dbSnap = path.join(backupsDir, `.travel-snap-${timestamp}.db`);
try {
try { db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
@@ -184,7 +185,21 @@ export async function createBackup(): Promise<BackupInfo> {
const dbPath = path.join(dataDir, 'travel.db');
if (fs.existsSync(dbPath)) {
archive.file(dbPath, { name: 'travel.db' });
// Archive a point-in-time snapshot, not the live file. The archiver reads entries
// lazily during finalize(), so a WAL auto-checkpoint writing pages back into
// travel.db mid-stream would tear the archived copy — and the -wal that would make
// it recoverable isn't in the zip. VACUUM INTO takes a consistent snapshot even
// under concurrent writes — the same guarantee the plugin DBs get below.
let dbToArchive = dbPath;
try {
if (fs.existsSync(dbSnap)) fs.rmSync(dbSnap, { force: true });
db.exec(`VACUUM INTO '${dbSnap.replace(/'/g, "''")}'`);
dbToArchive = dbSnap;
} catch (e) {
// Snapshot failed (disk/lock) — fall back to the checkpointed live file rather
// than drop the core DB from the backup entirely.
}
archive.file(dbToArchive, { name: 'travel.db' });
}
// Bundle the at-rest encryption key so the backup is self-contained: the
@@ -267,9 +282,11 @@ export async function createBackup(): Promise<BackupInfo> {
if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath);
throw err;
} finally {
// The snapshot was a staging copy for the archiver only; drop it once streaming is done
// (the await above resolves on the output stream's 'close', so the archive is complete).
// The snapshots were staging copies for the archiver only; drop them once streaming is
// done (the await above resolves on the output stream's 'close', so the archive is
// complete).
fs.rmSync(pdataSnap, { recursive: true, force: true });
fs.rmSync(dbSnap, { force: true });
}
}
@@ -374,10 +391,17 @@ export async function restoreFromZip(zipPath: string): Promise<RestoreResult> {
try {
const dbDest = path.join(dataDir, 'travel.db');
for (const ext of ['', '-wal', '-shm']) {
// Swap the core DB atomically: copy the restored DB to a temp file on the SAME
// filesystem, drop the old -wal/-shm sidecars (they belong to the DB being replaced
// and would corrupt the new one if left), then rename into place. A rename is atomic,
// so a crash mid-swap leaves either the old or the new travel.db intact — never the
// deleted-and-not-yet-copied gap that a plain unlink-then-copy could leave.
const dbTmp = dbDest + '.restore-tmp';
fs.copyFileSync(extractedDb, dbTmp);
for (const ext of ['-wal', '-shm']) {
try { fs.unlinkSync(dbDest + ext); } catch (e) {}
}
fs.copyFileSync(extractedDb, dbDest);
fs.renameSync(dbTmp, dbDest);
// Restore the bundled at-rest encryption key (if the archive carries one)
// so the restored DB's encrypted secrets can be decrypted. Only the file
@@ -18,6 +18,7 @@ const fsMock = vi.hoisted(() => ({
createReadStream: vi.fn(),
rmSync: vi.fn(),
copyFileSync: vi.fn(),
renameSync: vi.fn(),
cpSync: vi.fn(),
// Identity by default: when uploadsDir is a plain directory, realpathSync
// returns it unchanged. Tests that exercise the symlink case override this.
@@ -466,9 +467,10 @@ describe('BACKUP-036 createBackup', () => {
await createBackup();
// archive.file should have been called with the db path
// the core DB is snapshotted (VACUUM INTO) and archived under the name travel.db
expect(dbMock.db.exec).toHaveBeenCalledWith(expect.stringContaining('VACUUM INTO'));
expect(archiverInstanceMock.file).toHaveBeenCalledWith(
expect.stringContaining('travel.db'),
expect.any(String),
{ name: 'travel.db' }
);
});