Files
crosscode-platform/apps/website/backend/src/backups/uploads.ts
T
joshuaandClaude Opus 5.5 8c213d6d84 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>
2026-11-27 10:04:38 +02:00

172 lines
8.4 KiB
TypeScript

/**
* 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 } };
}