sokko-g/services/cards/backup.js
Shinuwa 73bd5ae21c Give Sokko TCG's server files headers that explain their role, callers and pitfalls
Each core file of services/cards now says where it sits, its entry points,
who calls it and what to watch for: admin checks living in the service, the
methods added to ExpeditionService and TeamService by Object.assign, the
InTx suffix, settings defaults that do not change an existing database, and
rules shared with the browser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 09:47:18 +01:00

83 lines
3.4 KiB
JavaScript

/**
* @file Crée, vérifie, fait tourner et restaure des sauvegardes cohérentes de la base de Sokko TCG.
*
* Utilisé par : scripts/backup-nebula-cards.mjs, lancé chaque nuit par ops/systemd/sokko-g-cards-backup.timer.
* @see docs/DELIVERY.md
*/
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;
}