75 lines
3.1 KiB
TypeScript
75 lines
3.1 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";
|
|
|
|
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; 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("⚠️ Резервная копия базы Peppa FACTORY не сделана: {reason}", { reason }), log);
|
|
return { error: reason };
|
|
}
|
|
if (o.file) {
|
|
log(`backup: ${file}`);
|
|
return { file };
|
|
}
|
|
const keep = o.keep ?? 7;
|
|
const copies = readdirSync(dir).filter((f) => /^peppa-\d{4}-\d{2}-\d{2}\.db$/.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 });
|
|
log(`backup: ${file}`);
|
|
return { file };
|
|
}
|