diff --git a/ops/systemd/sokko-g-cards-backup.service b/ops/systemd/sokko-g-cards-backup.service new file mode 100644 index 0000000..6ddfdb4 --- /dev/null +++ b/ops/systemd/sokko-g-cards-backup.service @@ -0,0 +1,11 @@ +# Rôle : sauvegarde la base Sokko TCG et garde les 14 dernières copies quotidiennes, seulement si le jeu a déjà une base. +[Unit] +Description=Sokko G Cards database backup +ConditionPathExists=/var/lib/sokko-g/cards/nebula-cards.sqlite + +[Service] +Type=oneshot +User=shinuwa +WorkingDirectory=/data/webapps/sites/sokko-g +Environment=NODE_ENV=production +ExecStart=/home/shinuwa/.nvm/versions/node/v24.11.1/bin/node scripts/backup-nebula-cards.mjs scheduled /var/lib/sokko-g/cards/nebula-cards.sqlite /var/backups/sokko-g --keep 14 diff --git a/ops/systemd/sokko-g-cards-backup.timer b/ops/systemd/sokko-g-cards-backup.timer new file mode 100644 index 0000000..ac237a0 --- /dev/null +++ b/ops/systemd/sokko-g-cards-backup.timer @@ -0,0 +1,10 @@ +# Rôle : déclenche chaque nuit la sauvegarde Sokko TCG et rattrape une exécution manquée au redémarrage. +[Unit] +Description=Daily Sokko G Cards database backup + +[Timer] +OnCalendar=*-*-* 04:00:00 +Persistent=true + +[Install] +WantedBy=timers.target diff --git a/scripts/backup-nebula-cards.mjs b/scripts/backup-nebula-cards.mjs index bcf1a8a..01cb183 100644 --- a/scripts/backup-nebula-cards.mjs +++ b/scripts/backup-nebula-cards.mjs @@ -1,11 +1,14 @@ // Rôle : sauvegarde ou vérifie la base Sokko TCG depuis les tâches d'exploitation. import { resolve } from "node:path"; -import { backupCardsDatabase, restoreCardsDatabase, verifyCardsDatabase } from "../services/cards/backup.js"; +import { backupCardsDatabase, restoreCardsDatabase, runScheduledBackup, verifyCardsDatabase } from "../services/cards/backup.js"; -const [mode, source, destination] = process.argv.slice(2); +const [mode, source, destination, keepFlag, keepValue] = process.argv.slice(2); if (mode === "backup" && source && destination) { await backupCardsDatabase(resolve(source), resolve(destination)); console.log(`Sokko TCG backup written to ${resolve(destination)}`); +} else if (mode === "scheduled" && source && destination && (!keepFlag || keepFlag === "--keep")) { + const written = await runScheduledBackup(resolve(source), resolve(destination), keepFlag ? { keep: Number(keepValue) } : {}); + console.log(`Sokko TCG scheduled backup written to ${written}`); } else if (mode === "verify" && source) { verifyCardsDatabase(resolve(source)); console.log(`Sokko TCG backup verified: ${resolve(source)}`); @@ -13,6 +16,6 @@ if (mode === "backup" && source && destination) { restoreCardsDatabase(resolve(source), resolve(destination)); console.log(`Sokko TCG database restored to ${resolve(destination)}`); } else { - console.error("Usage: node scripts/backup-nebula-cards.mjs backup | verify | restore "); + console.error("Usage: node scripts/backup-nebula-cards.mjs backup | scheduled [--keep ] | verify | restore "); process.exitCode = 1; } diff --git a/services/cards/backup.js b/services/cards/backup.js index c57d4c7..1dd42ce 100644 --- a/services/cards/backup.js +++ b/services/cards/backup.js @@ -1,20 +1,38 @@ -// Rôle : crée, vérifie et restaure des sauvegardes cohérentes de la base Sokko TCG. -import { copyFileSync, mkdirSync, renameSync, rmSync } from "node:fs"; -import { dirname } from "node:path"; +// 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; } @@ -30,13 +48,30 @@ export function verifyCardsDatabase(path) { } } +// 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; +} diff --git a/tests/nebula-cards.test.mjs b/tests/nebula-cards.test.mjs index 5814525..1966976 100644 --- a/tests/nebula-cards.test.mjs +++ b/tests/nebula-cards.test.mjs @@ -1,10 +1,11 @@ // Rôle : vérifie les règles, la persistance et les mutations protégées de Sokko TCG. import assert from "node:assert/strict"; -import { access, readdir, readFile } from "node:fs/promises"; +import { access, readdir, readFile, writeFile } from "node:fs/promises"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { test } from "node:test"; +import { spawnSync } from "node:child_process"; import { assertVersionedCatalogScope, buildPublishedCatalog, prepareVersionedCatalog, validateCardsCatalog, withGeneratedFinishes } from "../services/cards/catalog.js"; import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES, INITIAL_RECHARGE_SETTING, INITIAL_SHOP_SETTING } from "../services/cards/admin-seed.js"; import { planRecycling } from "../services/cards/stardust.js"; @@ -14,7 +15,7 @@ import { CardsDatabase } from "../services/cards/database.js"; import { calculateRecharge, drawPack, drawShopPack } from "../services/cards/game-rules.js"; import { CardsService, DEV_DISCORD_ID } from "../services/cards/service.js"; import { visibleCollections } from "../website/src/features/cards/collectionState.js"; -import { backupCardsDatabase, restoreCardsDatabase, verifyCardsDatabase } from "../services/cards/backup.js"; +import { backupCardsDatabase, restoreCardsDatabase, runScheduledBackup, verifyCardsDatabase } from "../services/cards/backup.js"; // Catalogue versionné (finitions générées, sans variation mythique) et catalogue publié avec une variation de test. const rawCatalog = JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8")); @@ -653,6 +654,56 @@ test("database backup passes integrity checks and restores ownership", async () } }); +test("restoring replaces the database even when the stopped service left a write-ahead log", async () => { + const directory = await mkdtemp(join(tmpdir(), "sokko-cards-restore-wal-")); + const live = join(directory, "live.sqlite"); + const backup = join(directory, "backup.sqlite"); + const countPlayers = (database) => database.db.prepare("SELECT COUNT(*) AS count FROM players").get().count; + try { + const database = new CardsDatabase(live); + new CardsService({ database, catalog: baseCatalog }).upsertPlayer({ discordId: "before-backup", displayName: "Avant" }); + database.close(); + await backupCardsDatabase(live, backup); + // Un process tué sans fermer la base laisse ses écritures dans le WAL : la restauration ne doit pas les rejouer. + const killedWriter = `import { DatabaseSync } from "node:sqlite"; + const db = new DatabaseSync(${JSON.stringify(live)}); + db.exec("PRAGMA journal_mode = WAL"); + db.prepare("INSERT INTO players(id, discord_id, display_name, created_at) VALUES ('after', 'after', 'Après', 0)").run(); + process.kill(process.pid, "SIGKILL");`; + const writer = spawnSync(process.execPath, ["--no-warnings", "--input-type=module", "-e", killedWriter]); + assert.equal(writer.signal, "SIGKILL", String(writer.stderr)); + await access(`${live}-wal`); + restoreCardsDatabase(backup, live); + assert.deepEqual((await readdir(directory)).sort(), ["backup.sqlite", "live.sqlite"]); + const restored = new CardsDatabase(live); + assert.equal(countPlayers(restored), 1); + restored.close(); + } finally { + await rm(directory, { recursive: true, force: true }); + } +}); + +test("scheduled backups are dated, verified and pruned without touching other files", async () => { + const directory = await mkdtemp(join(tmpdir(), "sokko-cards-scheduled-")); + const source = join(directory, "source.sqlite"); + const backups = join(directory, "backups"); + try { + const database = new CardsDatabase(source); + database.close(); + const written = []; + for (const day of ["2026-11-01", "2026-11-02", "2026-11-03", "2026-11-03"]) written.push(await runScheduledBackup(source, backups, { keep: 2, now: new Date(`${day}T04:00:00Z`) })); + assert.equal(written.at(-1), join(backups, "nebula-cards-2026-11-03.sqlite")); + assert.deepEqual((await readdir(backups)).sort(), ["nebula-cards-2026-11-02.sqlite", "nebula-cards-2026-11-03.sqlite"]); + await writeFile(join(backups, "nebula-cards-before-cleanup.sqlite"), ""); + await runScheduledBackup(source, backups, { keep: 1, now: new Date("2026-11-04T04:00:00Z") }); + assert.deepEqual((await readdir(backups)).sort(), ["nebula-cards-2026-11-04.sqlite", "nebula-cards-before-cleanup.sqlite"]); + assert.equal(verifyCardsDatabase(join(backups, "nebula-cards-2026-11-04.sqlite")), true); + await assert.rejects(runScheduledBackup(source, backups, { keep: 0 }), /keep/); + } finally { + await rm(directory, { recursive: true, force: true }); + } +}); + test("published catalog adds mythic variations and opening settings stored in the database", () => { const legendary = baseCatalog.editions.find((edition) => edition.cardId === "starvoid-dragon" && edition.rarity === "legendary"); const published = buildPublishedCatalog(baseCatalog, {