diff --git a/CHANGELOG.md b/CHANGELOG.md index 949346b..d2a98ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …). +## website@1.5.0 + crosscode script - 2026-11-27 + +The Church Website's nightly backup also backs up the photos and files. Details in +`apps/website/CHANGELOG.md`. No migration. + +- **Website 1.5.0:** each night after the database, a snapshot of `backend/uploads` in + `backend/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. On Admin → Backups, with its own + switch. Kept to the same count as the database backups. +- **crosscode script:** an uninstall keeps the Website's backups with `rsync -aH`, so the + snapshots' shared files stay shared instead of each becoming a full copy. + ## website@1.4.0 - 2026-11-27 Database backups and background jobs for the Church Website, as Accounts and Cross Events have. diff --git a/apps/website/CHANGELOG.md b/apps/website/CHANGELOG.md index 211f0d2..2fd6b5c 100644 --- a/apps/website/CHANGELOG.md +++ b/apps/website/CHANGELOG.md @@ -1,5 +1,32 @@ # Changelog — Church Website +## [1.5.0] — 2026-11-27 + +No migration, no new environment settings. + +### Added + +- **Backups of the photos and files** (`src/backups/uploads.ts`): the nightly `backup` job (and + Back up now) makes, after the database backup, a snapshot of the uploads in + `backend/backups/uploads-YYYYMMDD-HHMMSS/`. A file the same as in the last snapshot (size and + time) is a hard link to it; the rest is copied, keeping its time. Uploads never change once + made, so after the first full copy each night costs only the new files, and each snapshot is + still a real copy: deleting or damaging a file in `uploads/` leaves the snapshots alone. + `.thumbnails` and other dot entries are left out. Built in a `.uploads-…-partial` folder and + renamed when complete (a leftover partial is removed on the next run). Refused before copying + anything when the disk hasn't room for what's new. Each holds a `.snapshot.json` (files, bytes, + new files, new bytes). The newest `backup_retain_count` are kept, as the database backups. + Off with `backup_uploads` = false; the last failure in `backup_uploads_last_error`. To put + them back: `cp -a backups/uploads-…/. uploads/` as the site's user. +- **Admin → Backups:** "Include the photos and files" (saved with the other backup settings), the + snapshots (when, files, size, new since the one before), and their last failure. Back up now + makes both and says if only the database worked. + +### Changed + +- The `backup` job is "Backup: the database, and the photos and files". The database backup is + made even when the uploads' fails; the job then fails, so its run and the Hub show it. + ## [1.4.0] — 2026-11-27 No migration: pg-boss makes its own schema (`pgboss_website`) on first start, as in Accounts. New diff --git a/apps/website/WHATS-NEW.md b/apps/website/WHATS-NEW.md index 627913a..c62235b 100644 --- a/apps/website/WHATS-NEW.md +++ b/apps/website/WHATS-NEW.md @@ -3,6 +3,12 @@ What each version changes for the church, in plain language (read by the Hub like Cross Events' WHATS-NEW.md; a section shows once its version is tagged). +## 1.5.0 + +- **Your photos and files are backed up too.** Every night, after your site's content, your media + library is backed up on the server. After the first time, only new photos and files are copied. + Under **Backups** you see each one, and can switch it off. + ## 1.4.0 - **Your website is backed up every night.** A copy of your site's content is kept on the server diff --git a/apps/website/backend/package.json b/apps/website/backend/package.json index bffd96f..4d73cee 100644 --- a/apps/website/backend/package.json +++ b/apps/website/backend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/website-backend", - "version": "1.4.0", + "version": "1.5.0", "description": "Church Website: the public site's content API, the admin API, publishing and uploads", "private": true, "type": "module", diff --git a/apps/website/backend/src/admin/maintenance.ts b/apps/website/backend/src/admin/maintenance.ts index 05630e7..8dde4d4 100644 --- a/apps/website/backend/src/admin/maintenance.ts +++ b/apps/website/backend/src/admin/maintenance.ts @@ -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. diff --git a/apps/website/backend/src/backups/backups.ts b/apps/website/backend/src/backups/backups.ts index 49e2ac3..ae5a2f9 100644 --- a/apps/website/backend/src/backups/backups.ts +++ b/apps/website/backend/src/backups/backups.ts @@ -93,7 +93,13 @@ export async function rotate(ctx: Ctx): Promise { * 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 { +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 { const url = ctx.config.databaseUrl; try { if (!url) throw new Error('DATABASE_URL isn\'t set, so there\'s no database to back up.'); diff --git a/apps/website/backend/src/backups/uploads.ts b/apps/website/backend/src/backups/uploads.ts new file mode 100644 index 0000000..9f0484c --- /dev/null +++ b/apps/website/backend/src/backups/uploads.ts @@ -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 { + 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).catch(() => ({} as Partial)); + 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 { + 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 { + 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 { + 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 } }; +} diff --git a/apps/website/backend/src/jobs.ts b/apps/website/backend/src/jobs.ts index 067e101..92a4d98 100644 --- a/apps/website/backend/src/jobs.ts +++ b/apps/website/backend/src/jobs.ts @@ -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 }; 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) }, diff --git a/apps/website/backend/tests/maintenance.test.ts b/apps/website/backend/tests/maintenance.test.ts index 4fba8f3..4b7f8ae 100644 --- a/apps/website/backend/tests/maintenance.test.ts +++ b/apps/website/backend/tests/maintenance.test.ts @@ -8,7 +8,8 @@ import path from 'node:path'; import { Readable } from 'node:stream'; import zlib from 'node:zlib'; import request from 'supertest'; -import { BACKUP_FILE, backupName, backupPath, listBackups, runBackup, runBackupJob, type Dumper } from '../src/backups/backups.js'; +import { BACKUP_FILE, backupName, backupPath, listBackups, runBackup, runBackupJob, useDumperForTest, type Dumper } from '../src/backups/backups.js'; +import { listUploadsSnapshots, runNightlyBackups, runUploadsBackup, UPLOADS_SNAPSHOT } from '../src/backups/uploads.js'; import { health } from '../src/hub/client.js'; import { JOBS, cronFor, isEnabled, jobsHealth, runNow, useEnvForTest } from '../src/jobs.js'; import { hashToken } from '../src/lib/crypto.js'; @@ -19,7 +20,7 @@ type Role = 'owner' | 'admin' | 'editor'; const dumpOf = (sql: string): Dumper => () => ({ stdout: Readable.from([sql]), done: Promise.resolve() }); const failing: Dumper = () => ({ stdout: Readable.from(['-- half a dump']), done: Promise.reject(new Error('pg_dump stopped (exit 1): connection refused')) }); -after(() => useEnvForTest(process.env)); +after(() => { useEnvForTest(process.env); useDumperForTest(null); }); async function site() { const h = await harness({ linked: false }); @@ -103,7 +104,7 @@ describe('backups (1.4.0)', () => { assert.equal((await admin.put('/backups/settings', { retain: 0, nightly: true })).status, 400); const saved = await admin.put('/backups/settings', { retain: 30, nightly: false }); - assert.deepEqual(saved.body, { retain: 30, nightly: false, deleted: 0 }); + assert.deepEqual(saved.body, { retain: 30, nightly: false, uploads: true, deleted: 0 }); assert.equal(await h.ctx.settings.bool('backup_nightly', true), false); }); @@ -173,3 +174,80 @@ describe('background jobs (1.4.0)', () => { assert.deepEqual(ran.body, { queued: false, output: { added: 0, skipped: 'no source' } }); }); }); + +describe('backups of the photos and files (1.5.0)', () => { + useDumperForTest(dumpOf('-- the database\n')); + async function withUploads() { + const h = await site(); + const up = fs.mkdtempSync(path.join(os.tmpdir(), 'ccw-up-')); + h.ctx.config.uploadDir = up; + fs.mkdirSync(path.join(up, 'demo')); + fs.mkdirSync(path.join(up, '.thumbnails')); + fs.writeFileSync(path.join(up, 'a.jpg'), 'photo a'); + fs.writeFileSync(path.join(up, 'demo', 'b.svg'), ''); + fs.writeFileSync(path.join(up, '.thumbnails', 't.jpg'), 'made again on demand'); + return { ...h, up }; + } + const ino = (p: string) => fs.statSync(p).ino; + + it('a snapshot is a real copy of the uploads, without .thumbnails', async () => { + const h = await withUploads(); + const s = await runUploadsBackup(h.ctx); + assert.match(s.name, UPLOADS_SNAPSHOT); + const snap = path.join(h.dir, s.name); + assert.equal(fs.readFileSync(path.join(snap, 'a.jpg'), 'utf8'), 'photo a'); + assert.equal(fs.readFileSync(path.join(snap, 'demo', 'b.svg'), 'utf8'), ''); + assert.ok(!fs.existsSync(path.join(snap, '.thumbnails'))); + assert.deepEqual([s.files, s.newFiles], [2, 2]); + assert.notEqual(ino(path.join(snap, 'a.jpg')), ino(path.join(h.up, 'a.jpg')), 'not the live file itself'); + // Deleting the live file leaves the backup. + fs.rmSync(path.join(h.up, 'a.jpg')); + assert.equal(fs.readFileSync(path.join(snap, 'a.jpg'), 'utf8'), 'photo a'); + }); + + it('the next one links what\'s unchanged and copies only what\'s new', async () => { + const h = await withUploads(); + const first = await runUploadsBackup(h.ctx); + fs.writeFileSync(path.join(h.up, 'c.png'), 'new photo'); + const second = await runUploadsBackup(h.ctx); + assert.notEqual(second.name, first.name); + assert.deepEqual([second.files, second.newFiles, second.newBytes], [3, 1, 'new photo'.length]); + assert.equal(ino(path.join(h.dir, second.name, 'a.jpg')), ino(path.join(h.dir, first.name, 'a.jpg')), 'unchanged: a hard link'); + assert.equal((await listUploadsSnapshots(h.ctx))[0]!.name, second.name); + }); + + it('only the newest are kept, as the database backups; a crash leaves no half snapshot behind', async () => { + const h = await withUploads(); + await h.ctx.settings.set('backup_retain_count', '2'); + fs.mkdirSync(path.join(h.dir, '.uploads-20200101-000000-partial')); + for (let i = 0; i < 3; i++) await runUploadsBackup(h.ctx); + assert.equal((await listUploadsSnapshots(h.ctx)).length, 2); + assert.ok(!fs.existsSync(path.join(h.dir, '.uploads-20200101-000000-partial'))); + }); + + it('the nightly job backs up both, and leaves the uploads out when that\'s off', async () => { + const h = await withUploads(); + const ran = await runNightlyBackups(h.ctx) as { database: { filename?: string }; uploads: { name?: string; skipped?: boolean } }; + assert.ok(ran.database.filename && ran.uploads.name, JSON.stringify(ran)); + await h.ctx.settings.set('backup_uploads', 'false'); + assert.deepEqual((await runNightlyBackups(h.ctx) as { uploads: unknown }).uploads, { skipped: true }); + await h.ctx.settings.set('backup_nightly', 'false'); + assert.deepEqual(await runNightlyBackups(h.ctx), { database: { skipped: true } }); + }); + + it('Back up now makes both; the page lists the snapshots; the switch is saved', async () => { + const h = await withUploads(); + const admin = await h.as('admin'); + const made = await admin.post('/backups/run'); + assert.equal(made.status, 200, JSON.stringify(made.body)); + assert.equal(made.body.uploads.newFiles, 2); + assert.equal(made.body.uploadsError, null); + const list = await admin.get('/backups'); + assert.equal(list.body.uploads.enabled, true); + assert.equal(list.body.uploads.items.length, 1); + assert.equal(list.body.uploads.items[0].files, 2); + const off = await admin.put('/backups/settings', { retain: 14, nightly: true, uploads: false }); + assert.equal(off.body.uploads, false); + assert.equal(await h.ctx.settings.bool('backup_uploads', true), false); + }); +}); diff --git a/apps/website/frontend/package.json b/apps/website/frontend/package.json index 0bc851e..3eb11aa 100644 --- a/apps/website/frontend/package.json +++ b/apps/website/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/website-frontend", - "version": "1.4.0", + "version": "1.5.0", "private": true, "description": "Church Website: the church's public site in its template, and the admin", "scripts": { diff --git a/apps/website/frontend/src/app/admin/backups/page.tsx b/apps/website/frontend/src/app/admin/backups/page.tsx index edeb99a..45fadf6 100644 --- a/apps/website/frontend/src/app/admin/backups/page.tsx +++ b/apps/website/frontend/src/app/admin/backups/page.tsx @@ -2,15 +2,19 @@ /** * Settings → Backups (1.4.0, as Accounts and Cross Events): the database backups on this server, - * every night and before every update. Back up now, download one, how many to keep. Owners and - * Admins only. + * every night and before every update. Back up now, download one, how many to keep. 1.5.0: the + * photos and files too, as snapshots on the server. Owners and Admins only. */ import { useState } from "react"; import { DatabaseBackup, Download } from "lucide-react"; import { api } from "@/admin/api"; import { Btn, Field, Loading, Notice, Panel, Title, inputClass, useAction, useAdmin, when } from "@/admin/ui"; -type BackupList = { items: { filename: string; size: number; createdAt: string }[]; nightly: boolean; retain: number; lastError: string | null }; +type Snapshot = { name: string; createdAt: string; files: number; bytes: number; newFiles: number; newBytes: number }; +type BackupList = { + items: { filename: string; size: number; createdAt: string }[]; nightly: boolean; retain: number; lastError: string | null; + uploads: { enabled: boolean; lastError: string | null; items: Snapshot[] }; +}; const size = (n: number) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${(n / 1024).toFixed(1)} KB` : `${(n / (1024 * 1024)).toFixed(1)} MB`); @@ -20,38 +24,50 @@ export default function Backups() { const save = useAction(); const [nightly, setNightly] = useState(null); const [retain, setRetain] = useState(null); + const [withUploads, setWithUploads] = useState(null); if (!list.data) return ; const d = list.data; const nightlyOn = nightly ?? d.nightly; const keep = retain ?? String(d.retain); + const uploadsOn = withUploads ?? d.uploads.enabled; return ( <> Backups
- - {d.lastError &&
The last backup didn't work: {d.lastError}
} + + {d.lastError &&
The last database backup didn't work: {d.lastError}
} + {d.uploads.lastError &&
The last backup of the photos and files didn't work: {d.uploads.lastError}
} {now.message &&
{now.message.text}
} { - const b = await now.run(() => api<{ filename: string }>("/backups/run", { method: "POST" })); - if (b) now.setMessage({ tone: "success", text: `Backup made: ${b.filename}` }); + const b = await now.run(() => api<{ filename: string; uploads: { newFiles: number } | null; uploadsError: string | null }>("/backups/run", { method: "POST" })); + if (b) { + now.setMessage(b.uploadsError + ? { tone: "error", text: `The database was backed up (${b.filename}), but the photos and files weren't: ${b.uploadsError}` } + : { tone: "success", text: `Backup made: ${b.filename}${b.uploads ? `, and the photos and files (${b.uploads.newFiles} new since the last time)` : ""}.` }); + } list.reload(); }}>Back up now
{ e.preventDefault(); - const r = await save.run(() => api<{ deleted: number }>("/backups/settings", { method: "PUT", body: { retain: Number(keep), nightly: nightlyOn } })); + const r = await save.run(() => api<{ deleted: number }>("/backups/settings", { method: "PUT", body: { retain: Number(keep), nightly: nightlyOn, uploads: uploadsOn } })); if (r) save.setMessage({ tone: "success", text: r.deleted ? `Saved. ${r.deleted} older backup${r.deleted === 1 ? " was" : "s were"} deleted.` : "Saved." }); setNightly(null); setRetain(null); + setWithUploads(null); list.reload(); }}> +
- + setRetain(e.target.value)} />
@@ -60,7 +76,7 @@ export default function Backups() {
- +
@@ -81,6 +97,25 @@ export default function Backups() {
MadeSizeDownload
+ + +
+ + + + {d.uploads.items.map((s) => ( + + + + + + + ))} + {!d.uploads.items.length && } + +
MadeFilesSizeNew since the one before
{when(s.createdAt)}{s.files}{size(s.bytes)}{s.newFiles} ({size(s.newBytes)})
{uploadsOn ? "None yet: the first is made tonight, or with Back up now." : "Off: the photos and files aren't backed up."}
+
+
); diff --git a/package-lock.json b/package-lock.json index c837d54..6820579 100644 --- a/package-lock.json +++ b/package-lock.json @@ -360,7 +360,7 @@ }, "apps/website/backend": { "name": "@crosscode/website-backend", - "version": "1.4.0", + "version": "1.5.0", "hasInstallScript": true, "dependencies": { "@crosscode/auth-client": "*", @@ -389,7 +389,7 @@ }, "apps/website/frontend": { "name": "@crosscode/website-frontend", - "version": "1.4.0", + "version": "1.5.0", "dependencies": { "@crosscode/contracts": "*", "@crosscode/seo": "*", diff --git a/scripts/products/website.sh b/scripts/products/website.sh index 07f78f7..798445c 100644 --- a/scripts/products/website.sh +++ b/scripts/products/website.sh @@ -107,7 +107,8 @@ website_keep() { local app dest="$2" app="$(website_app "$1")" mkdir -p "$dest" - [ ! -d "$app/backend/backups" ] || rsync -a "$app/backend/backups/" "$dest/backups/" + # -H: the uploads snapshots (Website 1.5.0) share unchanged files as hard links; keep them shared. + [ ! -d "$app/backend/backups" ] || rsync -aH "$app/backend/backups/" "$dest/backups/" cp -p "$app/backend/.env" "$dest/backend.env" 2>/dev/null || true chmod -R go-rwx "$dest" }