/** * Catalog backups without stopping the server. * * `VACUUM INTO` writes a consistent copy of the live SQLite database (including * everything still in the WAL), so a backup is safe while people are editing. * Originals are large, so copying them is opt-in: previews, thumbnails and * denoise renders are all regenerable, originals are not. * * npm run backup # database only, keep 14 * npm run backup -- --with-originals # also copy originals/ (can be huge) * npm run backup -- --keep 30 --dir /mnt/backups * * Restore: stop the server, put the `catalog-*.db` snapshot back as lumenroom.db * (delete the old -wal/-shm files) and copy the originals snapshot back into the * storage root. */ import fs from 'node:fs'; import fsp from 'node:fs/promises'; import path from 'node:path'; import { DatabaseSync } from 'node:sqlite'; import { fileURLToPath } from 'node:url'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); function argValue(name, fallback) { const index = process.argv.indexOf(`--${name}`); if (index < 0) return fallback; const value = process.argv[index + 1]; return value && !value.startsWith('--') ? value : fallback; } const DATA_DIR = path.resolve( process.env.LUMINARY_DATA || process.env.LUMENROOM_DATA || path.join(ROOT, 'server', 'data'), ); const DB_PATH = path.join(DATA_DIR, 'lumenroom.db'); const BACKUP_DIR = path.resolve( argValue('dir', process.env.LUMINARY_BACKUP_DIR || path.join(DATA_DIR, 'backups')), ); const KEEP = Math.max(1, Number(argValue('keep', process.env.LUMINARY_BACKUP_KEEP || '14')) || 14); const WITH_ORIGINALS = process.argv.includes('--with-originals'); const pad = (value) => String(value).padStart(2, '0'); const now = new Date(); const stamp = [ now.getFullYear(), pad(now.getMonth() + 1), pad(now.getDate()), '-', pad(now.getHours()), pad(now.getMinutes()), pad(now.getSeconds()), ].join(''); const fmt = (bytes) => { if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(2)} GB`; if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`; if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`; return `${bytes} B`; }; /** The admin may have moved image files out of DATA_DIR; the catalog knows. */ function storageRoot() { const db = new DatabaseSync(DB_PATH, { readOnly: true }); try { const row = db.prepare("SELECT value FROM kv WHERE key = 'storageRoot'").get(); if (!row?.value) return DATA_DIR; const parsed = JSON.parse(row.value); return typeof parsed === 'string' && parsed.trim() ? path.resolve(parsed) : DATA_DIR; } catch { return DATA_DIR; } finally { db.close(); } } async function prune(prefix, keep) { let names = []; try { names = (await fsp.readdir(BACKUP_DIR)).filter((name) => name.startsWith(prefix)); } catch { return 0; } names.sort(); const stale = names.slice(0, Math.max(0, names.length - keep)); for (const name of stale) { await fsp.rm(path.join(BACKUP_DIR, name), { recursive: true, force: true }); } return stale.length; } if (!fs.existsSync(DB_PATH)) { console.error(`backup: no catalog at ${DB_PATH}`); process.exit(1); } await fsp.mkdir(BACKUP_DIR, { recursive: true }); /* --------------------------------------------------------- database snapshot */ const snapshot = path.join(BACKUP_DIR, `catalog-${stamp}.db`); const db = new DatabaseSync(DB_PATH); let counts; try { // VACUUM INTO is a consistent point-in-time copy and also compacts it. db.exec(`VACUUM INTO '${snapshot.replaceAll("'", "''")}'`); counts = { users: Number(db.prepare('SELECT COUNT(*) AS n FROM users').get()?.n ?? 0), events: Number(db.prepare('SELECT COUNT(*) AS n FROM events').get()?.n ?? 0), photos: Number(db.prepare('SELECT COUNT(*) AS n FROM photos').get()?.n ?? 0), }; } catch (err) { console.error(`backup: could not snapshot the catalog: ${err.message}`); process.exit(1); } finally { db.close(); } /* Verify the copy opens and is internally consistent before trusting it. */ const check = new DatabaseSync(snapshot, { readOnly: true }); let integrity = 'unknown'; try { integrity = String(check.prepare('PRAGMA integrity_check').get()?.integrity_check ?? 'unknown'); } finally { check.close(); } if (integrity !== 'ok') { console.error(`backup: snapshot failed its integrity check (${integrity})`); process.exit(1); } const dbBytes = (await fsp.stat(snapshot)).size; let copiedOriginals = null; let originalsBytes = 0; /* ---------------------------------------------------------------- originals */ if (WITH_ORIGINALS) { const source = path.join(storageRoot(), 'originals'); const target = path.join(BACKUP_DIR, `originals-${stamp}`); try { await fsp.cp(source, target, { recursive: true, force: true }); for (const name of await fsp.readdir(target)) { const stat = await fsp.stat(path.join(target, name)).catch(() => null); if (stat?.isFile()) originalsBytes += stat.size; } copiedOriginals = target; } catch (err) { console.error(`backup: catalog saved, but copying originals failed: ${err.message}`); process.exitCode = 1; } } await fsp.writeFile( path.join(BACKUP_DIR, `manifest-${stamp}.json`), `${JSON.stringify( { kind: 'luminary-backup', version: 1, createdAt: now.toISOString(), catalog: path.basename(snapshot), counts, bytes: dbBytes, originals: copiedOriginals ? { path: path.basename(copiedOriginals), bytes: originalsBytes } : null, storageRoot: storageRoot(), }, null, 2, )}\n`, ); const prunedDb = await prune('catalog-', KEEP); const prunedOriginals = WITH_ORIGINALS ? await prune('originals-', KEEP) : 0; const prunedManifests = await prune('manifest-', KEEP); console.log(`backup: ${snapshot}`); console.log( ` ${fmt(dbBytes)} ยท ${counts.users} user(s), ${counts.events} event(s), ${counts.photos} photo record(s)`, ); if (copiedOriginals) console.log(` originals: ${copiedOriginals} (${fmt(originalsBytes)})`); const pruned = prunedDb + prunedOriginals + prunedManifests; if (pruned) console.log(` pruned ${pruned} old file(s), keeping ${KEEP}`); if (!WITH_ORIGINALS) { console.log( ` note: original files were not copied; run with --with-originals or rsync ${path.join(storageRoot(), 'originals')}`, ); }