/** * Database backups (1.3.0, as Cross Events' Settings → Backups): a gzipped `pg_dump` into * backend/backups/ every night at 02:00 and whenever an admin asks, kept on this server only. * The `crosscode` script makes the same files before every deploy and uninstall * (scripts/products/accounts.sh), so the admin's list shows both, newest first. * * Settings: `backup_nightly` (default on), `backup_retain_count` (default 14), and what the last * run did (`backup_last_error`). Needs the `pg_dump` program on the server (Postgres client). */ import { spawn } from 'node:child_process'; import fs from 'node:fs'; import path from 'node:path'; import type { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import { fileURLToPath } from 'node:url'; import zlib from 'node:zlib'; import type { Ctx } from '../context.js'; /** backend/backups, from src/ and dist/ alike (never relative to where the process started). */ export const DEFAULT_BACKUP_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'backups'); /** The names this module and the crosscode script give a backup: accounts-YYYYMMDD-HHMMSS.sql.gz. */ export const BACKUP_FILE = /^accounts-\d{8}-\d{6}\.sql\.gz$/; export const DEFAULT_RETAIN = 14; const MAX_RETAIN = 365; export type Backup = { filename: string; size: number; createdAt: Date }; /** Something that writes a plain-SQL dump of the database to a stream (tests pass their own). */ export type Dumper = (databaseUrl: string) => { stdout: Readable; done: Promise }; const dir = (ctx: Ctx) => ctx.config.backupDir ?? DEFAULT_BACKUP_DIR; /** `pg_dump`, plain SQL, without owners or privileges (restores into any database user). */ export const pgDump: Dumper = (databaseUrl) => { const child = spawn('pg_dump', ['--no-owner', '--no-privileges', databaseUrl], { stdio: ['ignore', 'pipe', 'pipe'] }); let stderr = ''; child.stderr.on('data', (d) => { stderr += String(d); }); const done = new Promise((resolve, reject) => { child.on('error', (e) => reject(new Error(`pg_dump couldn't start (${e.message}). Install the PostgreSQL client on this server.`))); child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`pg_dump stopped (exit ${code}): ${stderr.trim().slice(0, 400)}`)))); }); return { stdout: child.stdout, done }; }; const pad = (n: number) => String(n).padStart(2, '0'); /** accounts-20261120-020000.sql.gz in the server's local time, as the crosscode script names them. */ export function backupName(at: Date): string { return `accounts-${at.getFullYear()}${pad(at.getMonth() + 1)}${pad(at.getDate())}-${pad(at.getHours())}${pad(at.getMinutes())}${pad(at.getSeconds())}.sql.gz`; } export async function retainCount(ctx: Ctx): Promise { const n = Number(await ctx.settings.get('backup_retain_count')); return Number.isInteger(n) && n >= 1 ? Math.min(n, MAX_RETAIN) : DEFAULT_RETAIN; } /** Every backup in the folder, newest first. */ export async function listBackups(ctx: Ctx): Promise { let names: string[]; try { names = await fs.promises.readdir(dir(ctx)); } catch { return []; } const items = await Promise.all(names.filter((n) => BACKUP_FILE.test(n)).map(async (filename) => { const st = await fs.promises.stat(path.join(dir(ctx), filename)); return { filename, size: st.size, createdAt: st.mtime }; })); return items.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || b.filename.localeCompare(a.filename)); } /** The newest backup's time, for the Hub heartbeat. */ export async function lastBackupAt(ctx: Ctx): Promise { return (await listBackups(ctx))[0]?.createdAt ?? null; } /** The full path of a backup to download, or null if there's no such backup (or a bad name). */ export function backupPath(ctx: Ctx, filename: string): string | null { if (!BACKUP_FILE.test(filename)) return null; const p = path.join(dir(ctx), filename); return fs.existsSync(p) ? p : null; } /** Deletes the oldest backups beyond the number kept. */ export async function rotate(ctx: Ctx): Promise { const old = (await listBackups(ctx)).slice(await retainCount(ctx)); await Promise.all(old.map((b) => fs.promises.unlink(path.join(dir(ctx), b.filename)).catch(() => {}))); return old.length; } /** * Makes a backup now. A dump that fails part-way leaves no file behind (a truncated one would * look like a real backup). Records the outcome for the admin page. */ export async function runBackup(ctx: Ctx, dumper: Dumper = pgDump): Promise { const url = ctx.config.databaseUrl; try { if (!url) throw new Error('DATABASE_URL isn\'t set, so there\'s no database to back up.'); await fs.promises.mkdir(dir(ctx), { recursive: true, mode: 0o700 }); // Two in the same second (the button pressed twice): the next free second's name. const at = ctx.now().getTime(); let filename = backupName(new Date(at)); for (let s = 1; fs.existsSync(path.join(dir(ctx), filename)); s++) filename = backupName(new Date(at + s * 1000)); const file = path.join(dir(ctx), filename); const { stdout, done } = dumper(url); // Both must finish: pg_dump exiting cleanly, and the file written. Wait for both either way, // so a failed one's file is deleted after the last write, not before it. const [dumped, written] = await Promise.allSettled([done, pipeline(stdout, zlib.createGzip(), fs.createWriteStream(file, { mode: 0o600 }))]); const failed = [dumped, written].find((r): r is PromiseRejectedResult => r.status === 'rejected'); if (failed) { await fs.promises.unlink(file).catch(() => {}); throw failed.reason; } await rotate(ctx); await ctx.settings.set('backup_last_error', null); const st = await fs.promises.stat(file); return { filename, size: st.size, createdAt: st.mtime }; } catch (e) { await ctx.settings.set('backup_last_error', `${ctx.now().toISOString()} ${(e as Error).message}`.slice(0, 600)); throw e; } } /** The nightly `backup` job: skipped when an admin has turned nightly backups off. */ export async function runBackupJob(ctx: Ctx) { if (!(await ctx.settings.bool('backup_nightly', true))) return { skipped: true }; const b = await runBackup(ctx); return { filename: b.filename, size: b.size }; }