sokko-g/services/cards/backup.js
Shinuwa 115e62d5b2 Make Cards database restores reliable and schedule backups
A restore left the replaced database's write-ahead log in place, so SQLite
replayed it and the restored file silently kept later writes. Restores now
remove it, backups stay single files, and a systemd timer keeps 14 daily copies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 17:54:17 +01:00

77 lines
3.3 KiB
JavaScript

// Rôle : crée, vérifie, fait tourner et restaure des sauvegardes cohérentes de la base Sokko TCG.
import { copyFileSync, mkdirSync, readdirSync, renameSync, rmSync } from "node:fs";
import { dirname, join } from "node:path";
import { backup, DatabaseSync } from "node:sqlite";
const SCHEDULED_BACKUP_NAME = /^nebula-cards-\d{4}-\d{2}-\d{2}\.sqlite$/;
// Fichiers annexes du mode WAL : ceux d'une ancienne base seraient rejoués par SQLite sur le fichier qui la remplace.
function removeSidecars(path) {
rmSync(`${path}-wal`, { force: true });
rmSync(`${path}-shm`, { force: true });
}
export async function backupCardsDatabase(sourcePath, destinationPath) {
mkdirSync(dirname(destinationPath), { recursive: true });
const temporaryPath = `${destinationPath}.tmp`;
rmSync(temporaryPath, { force: true });
removeSidecars(temporaryPath);
const source = new DatabaseSync(sourcePath, { readOnly: true });
try {
await backup(source, temporaryPath);
} finally {
source.close();
}
// Une sauvegarde reste un fichier unique : sa lecture ne doit pas créer de fichiers annexes à côté d'elle.
const copy = new DatabaseSync(temporaryPath);
try {
copy.exec("PRAGMA journal_mode = DELETE");
} finally {
copy.close();
}
verifyCardsDatabase(temporaryPath);
removeSidecars(temporaryPath);
renameSync(temporaryPath, destinationPath);
removeSidecars(destinationPath);
return destinationPath;
}
export function verifyCardsDatabase(path) {
const database = new DatabaseSync(path, { readOnly: true });
try {
const result = database.prepare("PRAGMA integrity_check").get();
if (result.integrity_check !== "ok") throw new Error(`SQLite integrity check failed: ${result.integrity_check}`);
database.prepare("SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1").get();
return true;
} finally {
database.close();
}
}
// Le service doit être arrêté : le journal WAL de la base remplacée est supprimé avec elle.
export function restoreCardsDatabase(backupPath, destinationPath) {
verifyCardsDatabase(backupPath);
mkdirSync(dirname(destinationPath), { recursive: true });
const temporaryPath = `${destinationPath}.restore`;
rmSync(temporaryPath, { force: true });
removeSidecars(temporaryPath);
copyFileSync(backupPath, temporaryPath);
verifyCardsDatabase(temporaryPath);
removeSidecars(temporaryPath);
removeSidecars(destinationPath);
renameSync(temporaryPath, destinationPath);
return destinationPath;
}
// Sauvegarde quotidienne : un fichier par jour, seuls les `keep` plus récents sont conservés. Les sauvegardes nommées à la main ne sont jamais purgées.
export async function runScheduledBackup(sourcePath, directory, { keep = 14, now = new Date() } = {}) {
if (!Number.isInteger(keep) || keep < 1) throw new TypeError("Scheduled backups need a positive keep count.");
const destinationPath = join(directory, `nebula-cards-${now.toISOString().slice(0, 10)}.sqlite`);
await backupCardsDatabase(sourcePath, destinationPath);
const expired = readdirSync(directory).filter((name) => SCHEDULED_BACKUP_NAME.test(name)).sort().reverse().slice(keep);
for (const name of expired) {
rmSync(join(directory, name), { force: true });
removeSidecars(join(directory, name));
}
return destinationPath;
}