peppa/packages/core/src/backup.ts

107 lines
4.7 KiB
TypeScript

import { m as tr } from "@peppa/shared/i18n";
import type { Db } from "@peppa/db";
import { peppaHome } from "@peppa/shared";
import { mkdirSync, readdirSync, rmSync } from "node:fs";
import { dirname, join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { alertAdmins } from "./monitor.ts";
import { getSetting, setSetting } from "./settings.ts";
import { historyDb, historyDbPath } from "./history.ts";
import { existsSync } from "node:fs";
const DAY_MS = 24 * 3600_000;
const KEY = "backup:last";
export interface BackupOptions {
now?: Date;
dir?: string;
keep?: number;
/** Back up even if the last copy is younger than a day. */
force?: boolean;
/** One-off copy to this file (a release backup, PEP-18): no daily rotation or bookkeeping. */
file?: string;
log?: (m: string) => void;
}
/** A copy is only a backup if it opens and passes `quick_check`; throws otherwise. */
export function verifyBackup(file: string): void {
const copy = new DatabaseSync(file, { readOnly: true });
try {
const r = copy.prepare("PRAGMA quick_check").get() as { quick_check?: string } | undefined;
if (r?.quick_check !== "ok") throw new Error(tr("копия повреждена: {v}", { v: r?.quick_check ?? tr("нет ответа") }));
copy.prepare("select count(*) from settings").get();
} finally {
copy.close();
}
}
/**
* Daily consistent copy of the database (`VACUUM INTO`, no need to stop anything) into
* ~/.peppa/backups/peppa-YYYY-MM-DD.db, keeping the newest `keep` (7). A failed copy is
* checked (`verifyBackup`); a failed copy is removed and the platform admins are told; the
* services keep running either way.
*/
export async function backupDb(db: Db, o: BackupOptions = {}): Promise<{ file?: string; history?: string; error?: string; skipped?: boolean }> {
const now = o.now ?? new Date();
const log = o.log ?? (() => {});
const last = await getSetting<{ at: number }>(db, KEY);
if (!o.file && !o.force && last && now.getTime() - last.at < DAY_MS) return { skipped: true };
const dir = o.file ? dirname(o.file) : (o.dir ?? join(peppaHome(), "backups"));
const day = now.toLocaleDateString("sv-SE");
const file = o.file ?? join(dir, `peppa-${day}.db`);
try {
mkdirSync(dir, { recursive: true });
rmSync(file, { force: true }); // VACUUM INTO refuses to overwrite
db.$client.db.prepare("VACUUM INTO ?").run(file);
verifyBackup(file);
} catch (e) {
try {
rmSync(file, { force: true });
} catch {}
const msg = (e as Error).message;
const reason = /SQLITE_FULL|ENOSPC|disk is full/i.test(msg) ? tr("нет места на диске") : msg;
await alertAdmins(db, `backup:fail:${day}`, tr("⚠️ Резервная копия базы FORGE не сделана: {reason}", { reason }), log);
return { error: reason };
}
if (o.file) {
log(`backup: ${file}`);
return { file };
}
const keep = o.keep ?? 7;
// PEP-221: the archive (journal 90 days, metrics a year) is copied next to it; its failure does not
// spoil the copy of the main base. Log files of the archive are not copied (7 days, for analysis only).
let history: string | undefined;
if (existsSync(historyDbPath())) {
const hfile = join(dir, `history-${day}.db`);
try {
rmSync(hfile, { force: true });
historyDb().prepare("VACUUM INTO ?").run(hfile);
const copy = new DatabaseSync(hfile, { readOnly: true });
try {
const r = copy.prepare("PRAGMA quick_check").get() as { quick_check?: string } | undefined;
if (r?.quick_check !== "ok") throw new Error(tr("копия повреждена: {v}", { v: r?.quick_check ?? tr("нет ответа") }));
} finally {
copy.close();
}
history = hfile;
} catch (e) {
rmSync(hfile, { force: true });
await alertAdmins(db, `backup:history:fail:${day}`, tr("⚠️ Резервная копия архива FORGE не сделана: {reason}", { reason: (e as Error).message }), log);
}
}
for (const re of [/^peppa-\d{4}-\d{2}-\d{2}\.db$/, /^history-\d{4}-\d{2}-\d{2}\.db$/]) {
const copies = readdirSync(dir).filter((f) => re.test(f)).sort();
for (const old of copies.slice(0, Math.max(0, copies.length - keep))) rmSync(join(dir, old), { force: true });
}
await setSetting(db, KEY, { at: now.getTime(), file });
// PEP-214: statistics for the query planner next to the daily copy (0x10002 = also analyse
// tables that never had statistics). A failure here must not spoil the backup.
try {
db.$client.db.prepare("PRAGMA optimize(0x10002)").all();
} catch (e) {
log(`optimize failed: ${(e as Error).message}`);
}
log(`backup: ${file}${history ? ` + ${history}` : ""}`);
return { file, history };
}