peppa/packages/core/src/backup.ts
Асель 3a282b8054 PEP-36 stage 2: SQLite (node:sqlite, WAL) instead of Postgres
- packages/db: schema on sqlite-core (timestamps as epoch ms → Date, JSON as text,
  booleans 0/1), one baseline migration; node:sqlite client under drizzle's
  better-sqlite3 session (busy_timeout first, WAL, BEGIN IMMEDIATE, retries on
  SQLITE_BUSY, lazy open, async transaction callbacks refused); PEPPA_DB
  (default ~/.peppa/peppa.db)
- live updates: notify() pokes the bot over a unix socket; the bot also watches
  PRAGMA data_version every second (writes by other processes)
- Postgres specifics ported: createTask transaction is synchronous, no
  `for update skip locked`, `count(*)`, json_extract instead of ->>, json_each
  instead of @>
- `peppa db migrate` and `peppa db migrate-to-sqlite <file>` (read-only
  snapshot of Postgres, FK order from the schema, row count + foreign key
  checks, file appears only when they pass); old Postgres schema kept in
  packages/cli/legacy-pg-migrations for the migration and its test
- daily VACUUM INTO backup from the watchdog (7 copies, admin alert on failure)
- tests: a temp SQLite file per test file; storage.test.ts (20 processes,
  per-project numbering across processes, socket/data_version, migration from
  Postgres incl. a dangling foreign key, backups); two test races fixed
- CI: no per-run Postgres database; PEPPA_TEST_PG only for the migration test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 17:23:24 +05:00

53 lines
2.1 KiB
TypeScript

import type { Db } from "@peppa/db";
import { peppaHome } from "@peppa/shared";
import { mkdirSync, readdirSync, rmSync } from "node:fs";
import { join } from "node:path";
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;
log?: (m: string) => void;
}
/**
* 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
* 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.force && last && now.getTime() - last.at < DAY_MS) return { skipped: true };
const dir = o.dir ?? join(peppaHome(), "backups");
const day = now.toLocaleDateString("sv-SE");
const 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);
} 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) ? "нет места на диске" : msg;
await alertAdmins(db, `backup:fail:${day}`, `⚠️ Резервная копия базы Пеппы не сделана: ${reason}`, log);
return { error: reason };
}
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 };
}