backup.ts

8.4 KB · raw

1import { Database } from "bun:sqlite";2import { cpSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync } from "node:fs";3import { join, relative } from "node:path";4import { streamTarball } from "../tarball/tar.ts";5import type { BackupBucket, Config } from "./config.ts";6import { notify, setting } from "./db.ts";78const KEEP = 14;9const DAY_MS = 24 * 3600 * 1000;10const CHECK_MS = 3600 * 1000;11const NAME = /^\d{8}T\d{6}Z$/;1213/** A backup's name: its UTC time, `20260926T031500Z`, so names sort in time order. */14function stamp(ms: number): string {15	return new Date(ms).toISOString().replace(/[-:]|\.\d{3}/g, "");16}1718/** The backups in `data/backups/`, oldest first. */19export function backups(dataDir: string): string[] {20	const root = join(dataDir, "backups");21	// Not a folder is no backups, so the console still shows why the next one fails.22	return existsSync(root) && statSync(root).isDirectory()23		? readdirSync(root)24				.filter((name) => NAME.test(name))25				.sort()26		: [];27}2829/**30 * §19's backup: `VACUUM INTO` of kepr.db and a copy of `assets/`, built in a hidden folder and31 * renamed into `data/backups/<time>/`, so a half-made backup is never the newest. Keeps the last 14.32 */33export function makeBackup(kepr: Database, dataDir: string, now = Date.now()): string {34	const root = join(dataDir, "backups");35	const name = stamp(now);36	const tmp = join(root, `.${name}`);37	rmSync(tmp, { recursive: true, force: true });38	// It holds reporters' contact emails, so only Kepr's user may read it.39	mkdirSync(tmp, { recursive: true, mode: 0o700 });40	// Synchronous from here to the rename: no request can change kepr.db or assets/ in between.41	kepr.query("VACUUM INTO ?").run(join(tmp, "kepr.db"));42	// A restored backup must not bring live sign-ins with it.43	const copy = new Database(join(tmp, "kepr.db"));44	copy.run("DELETE FROM sessions");45	copy.run("VACUUM");46	copy.close();47	const assets = join(dataDir, "assets");48	if (existsSync(assets)) cpSync(assets, join(tmp, "assets"), { recursive: true });49	rmSync(join(root, name), { recursive: true, force: true });50	renameSync(tmp, join(root, name));51	for (const old of backups(dataDir).slice(0, -KEEP)) {52		rmSync(join(root, old), { recursive: true, force: true });53	}54	return name;55}5657/** Makes a backup when the newest is a day old or there is none; returns its name, else null. */58export function backupIfDue(kepr: Database, dataDir: string, now = Date.now()): string | null {59	const newest = backups(dataDir).at(-1);60	return newest && newest > stamp(now - DAY_MS) ? null : makeBackup(kepr, dataDir, now);61}6263/** Makes the backup a request asks for: one now, or the one that is due. */64export function backupWhen(kepr: Database, dataDir: string, when: "due" | "now"): string | null {65	return when === "due" ? backupIfDue(kepr, dataDir) : makeBackup(kepr, dataDir);66}6768/**69 * Daily backups: checked at startup and every hour, so a restart never skips a day, and an upload70 * to the backup bucket that failed is retried. `config` is the live one the console edits, and71 * `make` builds the backup, on the sync's thread when the app has one.72 */73export function startBackupLoop(74	kepr: Database,75	config: Config,76	make: () => unknown = () => backupWhen(kepr, config.dataDir, "due"),77): void {78	const tick = async () => {79		await attemptBackup(kepr, make);80		attemptUpload(kepr, config.dataDir, config.backup).catch((error) =>81			console.error(`kepr: backup upload failed: ${error}`),82		);83	};84	tick();85	setInterval(tick, CHECK_MS);86}8788/**89 * One backup attempt. A failure is kept for the console until a backup succeeds (§24), and only a90 * backup that starts failing is told, not every hourly retry. Returns the failure, or null.91 */92export async function attemptBackup(kepr: Database, make: () => unknown): Promise<string | null> {93	try {94		await make();95		kepr.query("DELETE FROM settings WHERE key = 'backup_error'").run();96		return null;97	} catch (error) {98		return keepFailure(kepr, "backup_error", "Backup failed", error);99	}100}101102/** Keeps a failure under `key` for the console, telling the operator only when it starts. */103function keepFailure(kepr: Database, key: string, what: string, error: unknown): string {104	const message = String(error);105	console.error(`kepr: ${what.toLowerCase()}: ${message}`);106	if (!setting(kepr, key)) {107		notify(kepr, "backup_failed", `${what}: ${message}`, "/admin?section=backups");108	}109	kepr.query("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)").run(key, message);110	return message;111}112113const OFFSITE = /^kepr-backup-(\d{8}T\d{6}Z)\.tar\.gz$/;114const offsiteKey = (name: string) => `kepr-backup-${name}.tar.gz`;115116function backupClient(bucket: BackupBucket): Bun.S3Client {117	return new Bun.S3Client({118		endpoint: bucket.endpoint,119		bucket: bucket.name,120		region: bucket.region,121		accessKeyId: bucket.accessKeyId,122		secretAccessKey: bucket.secretAccessKey,123	});124}125126/** The backups in the backup bucket, oldest first, with their sizes. */127export async function offsiteBackups(128	bucket: BackupBucket,129): Promise<{ name: string; size: number }[]> {130	const found: { name: string; size: number }[] = [];131	const client = backupClient(bucket);132	let continuationToken: string | undefined;133	do {134		const page = await client.list({ prefix: "kepr-backup-", continuationToken });135		for (const object of page.contents ?? []) {136			const name = OFFSITE.exec(object.key)?.[1];137			if (name) found.push({ name, size: object.size ?? 0 });138		}139		continuationToken = page.isTruncated ? page.nextContinuationToken : undefined;140	} while (continuationToken);141	return found.sort((a, b) => a.name.localeCompare(b.name));142}143144/** Tried before a backup bucket is saved: a test file must write, list and delete. Returns what failed. */145export async function checkBackupBucket(bucket: BackupBucket): Promise<string | null> {146	const client = backupClient(bucket);147	try {148		await client.write("kepr-backup-test", "test", { type: "text/plain" });149		await offsiteBackups(bucket);150		await client.delete("kepr-backup-test");151		return null;152	} catch (error) {153		return `The backup bucket did not take a test file: ${error instanceof Error ? error.message : String(error)}`;154	}155}156157/**158 * Copies the newest local backup to the backup bucket unless it is there already, then keeps the159 * newest 14 there. A failure is kept and told once, as a local one is; null when all is well.160 */161export async function attemptUpload(162	kepr: Database,163	dataDir: string,164	bucket: BackupBucket | undefined,165): Promise<string | null> {166	const newest = backups(dataDir).at(-1);167	if (!bucket || !newest || setting(kepr, "backup_uploaded") === newest) return null;168	try {169		const tarball = backupTarball(dataDir, newest);170		if (!tarball) return null;171		const client = backupClient(bucket);172		const body = new Response(tarball.stream);173		await client.write(offsiteKey(newest), body, { type: "application/gzip" });174		for (const old of (await offsiteBackups(bucket)).slice(0, -KEEP)) {175			await client.delete(offsiteKey(old.name));176		}177		kepr178			.query("INSERT OR REPLACE INTO settings (key, value) VALUES ('backup_uploaded', ?)")179			.run(newest);180		kepr.query("DELETE FROM settings WHERE key = 'backup_upload_error'").run();181		return null;182	} catch (error) {183		return keepFailure(kepr, "backup_upload_error", "Backup upload failed", error);184	}185}186187function backupFiles(dataDir: string, name: string): { path: string; full: string }[] {188	const dir = join(dataDir, "backups", name);189	return readdirSync(dir, { recursive: true, withFileTypes: true })190		.filter((entry) => entry.isFile())191		.map((entry) => {192			const full = join(entry.parentPath, entry.name);193			return { path: relative(dir, full), full };194		});195}196197/** What one backup takes on disk. */198export function backupBytes(dataDir: string, name: string): number {199	return backupFiles(dataDir, name).reduce((sum, file) => sum + statSync(file.full).size, 0);200}201202/**203 * A kept backup as a `.tar.gz` for the console's downloads (§24), the newest when no name is204 * given; null when there is no such backup. The archive is streamed, never held whole.205 */206export function backupTarball(207	dataDir: string,208	wanted?: string,209): { name: string; stream: ReadableStream<Uint8Array> } | null {210	const kept = backups(dataDir);211	// Only a name from the list, so a request can never reach outside data/backups/.212	const name = wanted === undefined ? kept.at(-1) : kept.find((known) => known === wanted);213	if (!name) return null;214	const files = backupFiles(dataDir, name);215	// Owner-only once unpacked: kepr.db holds reporters' contact emails.216	return { name, stream: streamTarball(`kepr-backup-${name}`, files, 0o600) };217}