Website 1.5.0: back up the photos and files too
The nightly backup (and Back up now) snapshots backend/uploads after the database, into backups/uploads-YYYYMMDD-HHMMSS/. Unchanged files are hard links to the last snapshot, so after the first full copy a night costs only the new files. Built in a partial folder and renamed when complete, refused up front when the disk hasn't room, kept to the same count as the database backups, with its own switch on Admin -> Backups. crosscode script: an uninstall keeps the Website's backups with rsync -aH, so the snapshots' shared files stay shared. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -7,6 +7,7 @@ import express from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { requireRole } from '../auth/sessions.js';
|
||||
import { backupPath, listBackups, retainCount, rotate, runBackup } from '../backups/backups.js';
|
||||
import { listUploadsSnapshots, rotateUploads, runUploadsBackup } from '../backups/uploads.js';
|
||||
import { ApiError, handle, sendError } from '../http.js';
|
||||
import { audit } from '../lib/audit.js';
|
||||
import { JobError, jobStatus, runNow, setOverride } from '../jobs.js';
|
||||
@@ -29,6 +30,12 @@ export function maintenanceRouter(ctx: Ctx, who: (req: express.Request) => Who)
|
||||
nightly: await ctx.settings.bool('backup_nightly', true),
|
||||
retain: await retainCount(ctx),
|
||||
lastError: await ctx.settings.get('backup_last_error'),
|
||||
// 1.5.0: the photos and files.
|
||||
uploads: {
|
||||
enabled: await ctx.settings.bool('backup_uploads', true),
|
||||
lastError: await ctx.settings.get('backup_uploads_last_error'),
|
||||
items: (await listUploadsSnapshots(ctx)).map((s) => ({ name: s.name, createdAt: s.createdAt, files: s.files, bytes: s.bytes, newFiles: s.newFiles, newBytes: s.newBytes })),
|
||||
},
|
||||
})));
|
||||
|
||||
r.post('/backups/run', admin, handle(async (req) => {
|
||||
@@ -38,20 +45,31 @@ export function maintenanceRouter(ctx: Ctx, who: (req: express.Request) => Who)
|
||||
} catch (e) {
|
||||
throw new ApiError(502, 'BACKUP_FAILED', `The backup didn't work: ${(e as Error).message}`);
|
||||
}
|
||||
let uploads: { name: string; newFiles: number } | null = null;
|
||||
let uploadsError: string | null = null;
|
||||
if (await ctx.settings.bool('backup_uploads', true)) {
|
||||
try {
|
||||
const s = await runUploadsBackup(ctx);
|
||||
uploads = { name: s.name, newFiles: s.newFiles };
|
||||
} catch (e) {
|
||||
uploadsError = (e as Error).message;
|
||||
}
|
||||
}
|
||||
const me = who(req);
|
||||
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_made', targetType: 'backup', targetId: b.filename });
|
||||
return { filename: b.filename, size: b.size, createdAt: b.createdAt };
|
||||
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_made', targetType: 'backup', targetId: b.filename, metadata: { uploads: uploads?.name ?? null } });
|
||||
return { filename: b.filename, size: b.size, createdAt: b.createdAt, uploads, uploadsError };
|
||||
}));
|
||||
|
||||
r.put('/backups/settings', admin, json, handle(async (req) => {
|
||||
const retain = Number(req.body?.retain);
|
||||
if (!Number.isInteger(retain) || retain < 1 || retain > 365) throw new ApiError(400, 'VALIDATION', 'Keep between 1 and 365 backups.', { retain: 'Between 1 and 365' });
|
||||
const nightly = req.body?.nightly !== false;
|
||||
await ctx.settings.setMany({ backup_retain_count: String(retain), backup_nightly: nightly ? 'true' : 'false' });
|
||||
const deleted = await rotate(ctx);
|
||||
const uploadsOn = req.body?.uploads !== false;
|
||||
await ctx.settings.setMany({ backup_retain_count: String(retain), backup_nightly: nightly ? 'true' : 'false', backup_uploads: uploadsOn ? 'true' : 'false' });
|
||||
const deleted = (await rotate(ctx)) + (await rotateUploads(ctx));
|
||||
const me = who(req);
|
||||
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_settings_changed', targetType: 'setting', targetId: 'backup_retain_count', metadata: { retain, nightly, deleted } });
|
||||
return { retain, nightly, deleted };
|
||||
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_settings_changed', targetType: 'setting', targetId: 'backup_retain_count', metadata: { retain, nightly, uploads: uploadsOn, deleted } });
|
||||
return { retain, nightly, uploads: uploadsOn, deleted };
|
||||
}));
|
||||
|
||||
// A download holds the whole site's content and its editors: audited, never cached.
|
||||
|
||||
@@ -93,7 +93,13 @@ export async function rotate(ctx: Ctx): Promise<number> {
|
||||
* 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<Backup> {
|
||||
let defaultDumper: Dumper = pgDump;
|
||||
/** Tests: the dump the job and the admin's button use, instead of pg_dump. */
|
||||
export function useDumperForTest(d: Dumper | null): void {
|
||||
defaultDumper = d ?? pgDump;
|
||||
}
|
||||
|
||||
export async function runBackup(ctx: Ctx, dumper: Dumper = defaultDumper): Promise<Backup> {
|
||||
const url = ctx.config.databaseUrl;
|
||||
try {
|
||||
if (!url) throw new Error('DATABASE_URL isn\'t set, so there\'s no database to back up.');
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* Backups of the uploads (1.5.0): the photos and files of the media library, which the database
|
||||
* backups (backups.ts) don't hold. Each is a folder `backups/uploads-YYYYMMDD-HHMMSS/` with the
|
||||
* uploads as they were, made right after the nightly database backup (and with "Back up now").
|
||||
*
|
||||
* Snapshots, not archives: a file that's the same as in the last snapshot (same size and time) is
|
||||
* a hard link to it, so after the first full copy a night costs only the files added since. An
|
||||
* uploaded file never changes (a new upload is a new file), so this is cheap and still a real
|
||||
* copy: deleting or damaging a file in uploads/ doesn't touch the snapshots. Deleting an old
|
||||
* snapshot frees only what no newer one shares.
|
||||
*
|
||||
* A snapshot is built in a `.uploads-…-partial` folder and renamed when complete, so a failed one
|
||||
* never looks like a backup. `.thumbnails` (made again on demand) and other dot entries are left
|
||||
* out. Kept: the same number as the database backups (`backup_retain_count`). Off with
|
||||
* `backup_uploads` = false. To restore: copy a snapshot's contents back into backend/uploads as
|
||||
* the site's user (`cp -a backups/uploads-…/. uploads/`).
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { uploadDir } from '../admin/media.js';
|
||||
import { DEFAULT_BACKUP_DIR, retainCount, runBackupJob } from './backups.js';
|
||||
|
||||
export const UPLOADS_SNAPSHOT = /^uploads-\d{8}-\d{6}$/;
|
||||
const MANIFEST = '.snapshot.json';
|
||||
|
||||
export type UploadsSnapshot = { name: string; createdAt: Date; files: number; bytes: number; newFiles: number; newBytes: number };
|
||||
|
||||
const dir = (ctx: Ctx) => ctx.config.backupDir ?? DEFAULT_BACKUP_DIR;
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
|
||||
/** uploads-20261127-022000, in the server's local time, as the database backups are named. */
|
||||
export function snapshotName(at: Date): string {
|
||||
return `uploads-${at.getFullYear()}${pad(at.getMonth() + 1)}${pad(at.getDate())}-${pad(at.getHours())}${pad(at.getMinutes())}${pad(at.getSeconds())}`;
|
||||
}
|
||||
|
||||
/** Every complete snapshot, newest first, with what its manifest says. */
|
||||
export async function listUploadsSnapshots(ctx: Ctx): Promise<UploadsSnapshot[]> {
|
||||
let names: string[];
|
||||
try {
|
||||
names = await fs.promises.readdir(dir(ctx));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const out: UploadsSnapshot[] = [];
|
||||
for (const name of names.filter((n) => UPLOADS_SNAPSHOT.test(n))) {
|
||||
const p = path.join(dir(ctx), name);
|
||||
const st = await fs.promises.stat(p).catch(() => null);
|
||||
if (!st?.isDirectory()) continue;
|
||||
const m = await fs.promises.readFile(path.join(p, MANIFEST), 'utf8').then((t) => JSON.parse(t) as Partial<UploadsSnapshot>).catch(() => ({} as Partial<UploadsSnapshot>));
|
||||
out.push({ name, createdAt: m.createdAt ? new Date(m.createdAt) : st.mtime, files: m.files ?? 0, bytes: m.bytes ?? 0, newFiles: m.newFiles ?? 0, newBytes: m.newBytes ?? 0 });
|
||||
}
|
||||
return out.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || b.name.localeCompare(a.name));
|
||||
}
|
||||
|
||||
/** The uploads' files, relative to the folder: no dot entries (.thumbnails), no links. */
|
||||
async function filesIn(root: string, rel = ''): Promise<{ rel: string; size: number; mtimeMs: number }[]> {
|
||||
let entries: fs.Dirent[];
|
||||
try {
|
||||
entries = await fs.promises.readdir(path.join(root, rel), { withFileTypes: true });
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code === 'ENOENT' && !rel) return [];
|
||||
throw e;
|
||||
}
|
||||
const out: { rel: string; size: number; mtimeMs: number }[] = [];
|
||||
for (const e of entries) {
|
||||
if (e.name.startsWith('.')) continue;
|
||||
const r = path.join(rel, e.name);
|
||||
if (e.isDirectory()) out.push(...(await filesIn(root, r)));
|
||||
else if (e.isFile()) {
|
||||
const st = await fs.promises.stat(path.join(root, r));
|
||||
out.push({ rel: r, size: st.size, mtimeMs: st.mtimeMs });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Deletes the oldest snapshots beyond the number kept, and any partial one left by a crash. */
|
||||
export async function rotateUploads(ctx: Ctx): Promise<number> {
|
||||
const old = (await listUploadsSnapshots(ctx)).slice(await retainCount(ctx));
|
||||
for (const s of old) await fs.promises.rm(path.join(dir(ctx), s.name), { recursive: true, force: true });
|
||||
const names = await fs.promises.readdir(dir(ctx)).catch(() => [] as string[]);
|
||||
for (const n of names.filter((x) => /^\.uploads-\d{8}-\d{6}-partial$/.test(x))) await fs.promises.rm(path.join(dir(ctx), n), { recursive: true, force: true });
|
||||
return old.length;
|
||||
}
|
||||
|
||||
/** Free bytes on the backups' disk, or null where the system can't say. */
|
||||
async function freeBytes(p: string): Promise<number | null> {
|
||||
try {
|
||||
const s = await fs.promises.statfs(p);
|
||||
return Number(s.bavail) * Number(s.bsize);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Makes a snapshot of the uploads now. Records the outcome for the admin page. */
|
||||
export async function runUploadsBackup(ctx: Ctx): Promise<UploadsSnapshot> {
|
||||
try {
|
||||
const source = uploadDir(ctx);
|
||||
await fs.promises.mkdir(dir(ctx), { recursive: true, mode: 0o700 });
|
||||
const at = ctx.now().getTime();
|
||||
let name = snapshotName(new Date(at));
|
||||
for (let s = 1; fs.existsSync(path.join(dir(ctx), name)); s++) name = snapshotName(new Date(at + s * 1000));
|
||||
const partial = path.join(dir(ctx), `.${name}-partial`);
|
||||
const previous = (await listUploadsSnapshots(ctx))[0];
|
||||
const prevDir = previous ? path.join(dir(ctx), previous.name) : null;
|
||||
|
||||
const files = await filesIn(source);
|
||||
// What's the same as last time is linked; the rest is copied. Check there's room for that first.
|
||||
const same = async (f: { rel: string; size: number; mtimeMs: number }) => {
|
||||
if (!prevDir) return false;
|
||||
const st = await fs.promises.stat(path.join(prevDir, f.rel)).catch(() => null);
|
||||
return !!st && st.isFile() && st.size === f.size && Math.abs(st.mtimeMs - f.mtimeMs) < 1;
|
||||
};
|
||||
const plan = await Promise.all(files.map(async (f) => ({ ...f, link: await same(f) })));
|
||||
const needed = plan.filter((f) => !f.link).reduce((n, f) => n + f.size, 0);
|
||||
const free = await freeBytes(dir(ctx));
|
||||
if (free !== null && needed > free * 0.9) {
|
||||
throw new Error(`Not enough disk space for the photos and files: ${Math.ceil(needed / 1e6)} MB to copy, ${Math.floor(free / 1e6)} MB free.`);
|
||||
}
|
||||
|
||||
await fs.promises.rm(partial, { recursive: true, force: true });
|
||||
await fs.promises.mkdir(partial, { recursive: true, mode: 0o700 });
|
||||
let newFiles = 0;
|
||||
let newBytes = 0;
|
||||
try {
|
||||
for (const f of plan) {
|
||||
const dest = path.join(partial, f.rel);
|
||||
await fs.promises.mkdir(path.dirname(dest), { recursive: true });
|
||||
let linked = false;
|
||||
if (f.link) {
|
||||
linked = await fs.promises.link(path.join(prevDir!, f.rel), dest).then(() => true, () => false);
|
||||
}
|
||||
if (!linked) {
|
||||
await fs.promises.copyFile(path.join(source, f.rel), dest);
|
||||
// The source's time, so tomorrow's run sees it as the same file.
|
||||
const t = new Date(f.mtimeMs);
|
||||
await fs.promises.utimes(dest, t, t);
|
||||
newFiles++;
|
||||
newBytes += f.size;
|
||||
}
|
||||
}
|
||||
const snapshot: UploadsSnapshot = { name, createdAt: new Date(at), files: plan.length, bytes: plan.reduce((n, f) => n + f.size, 0), newFiles, newBytes };
|
||||
await fs.promises.writeFile(path.join(partial, MANIFEST), JSON.stringify(snapshot), { mode: 0o600 });
|
||||
await fs.promises.rename(partial, path.join(dir(ctx), name));
|
||||
await rotateUploads(ctx);
|
||||
await ctx.settings.set('backup_uploads_last_error', null);
|
||||
return snapshot;
|
||||
} catch (e) {
|
||||
await fs.promises.rm(partial, { recursive: true, force: true }).catch(() => {});
|
||||
throw e;
|
||||
}
|
||||
} catch (e) {
|
||||
await ctx.settings.set('backup_uploads_last_error', `${ctx.now().toISOString()} ${(e as Error).message}`.slice(0, 600));
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The nightly `backup` job (1.5.0): the database (skipped when nightly backups are off), then the
|
||||
* uploads (unless `backup_uploads` is off). The database backup is made even when the uploads'
|
||||
* fails; the job then fails too, so the run shows it (and the Hub's "jobs failing").
|
||||
*/
|
||||
export async function runNightlyBackups(ctx: Ctx) {
|
||||
const database = await runBackupJob(ctx);
|
||||
if ('skipped' in database) return { database };
|
||||
if (!(await ctx.settings.bool('backup_uploads', true))) return { database, uploads: { skipped: true } };
|
||||
const s = await runUploadsBackup(ctx);
|
||||
return { database, uploads: { name: s.name, files: s.files, newFiles: s.newFiles, newBytes: s.newBytes } };
|
||||
}
|
||||
@@ -11,7 +11,7 @@
|
||||
import { CronExpressionParser } from 'cron-parser';
|
||||
import PgBoss from 'pg-boss';
|
||||
import type { Ctx } from './context.js';
|
||||
import { runBackupJob } from './backups/backups.js';
|
||||
import { runNightlyBackups } from './backups/uploads.js';
|
||||
import { syncAll } from './feed/feed.js';
|
||||
import { heartbeat } from './hub/client.js';
|
||||
import { syncYoutube } from './site/youtube.js';
|
||||
@@ -19,8 +19,9 @@ import { syncYoutube } from './site/youtube.js';
|
||||
export type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise<unknown> };
|
||||
|
||||
export const JOBS: Job[] = [
|
||||
// A database backup every night (Settings → Backups), after Accounts' at 02:00 on the same server.
|
||||
{ name: 'backup', label: 'Database backup', cron: '20 2 * * *', env: 'BACKUP_ENABLED', run: (ctx) => runBackupJob(ctx) },
|
||||
// A backup every night (Settings → Backups), after Accounts' at 02:00 on the same server: the
|
||||
// database, then (1.5.0) the photos and files.
|
||||
{ name: 'backup', label: 'Backup: the database, and the photos and files', cron: '20 2 * * *', env: 'BACKUP_ENABLED', run: (ctx) => runNightlyBackups(ctx) },
|
||||
{ name: 'hub-heartbeat', label: 'Cross Code Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED', run: (ctx) => heartbeat(ctx) },
|
||||
// ROADMAP-v3 §4: "consumers also poll every 15 minutes as a fallback".
|
||||
{ name: 'event-feed', label: 'Events from the church\'s other sites (Cross Events)', cron: '*/15 * * * *', env: 'FEED_JOB_ENABLED', run: (ctx) => syncAll(ctx) },
|
||||
|
||||
Reference in New Issue
Block a user