Compare commits

...
Author SHA1 Message Date
joshua 22d7e54008 Merge branch 'feat/website-uploads-backup' 2026-11-27 10:04:39 +02:00
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
joshua 48abc06db7 Merge branch 'docs/released-website-1.4.0' 2026-11-27 09:51:00 +02:00
joshuaandClaude Opus 5.5 da283f3cbb docs: Website 1.4.0 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:50:59 +02:00
14 changed files with 392 additions and 30 deletions
+12
View File
@@ -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.
+27
View File
@@ -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
+6
View File
@@ -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
+1 -1
View File
@@ -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",
+24 -6
View File
@@ -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.
+7 -1
View File
@@ -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.');
+171
View File
@@ -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 } };
}
+4 -3
View File
@@ -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) },
+81 -3
View File
@@ -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'), '<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'), '<svg/>');
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);
});
});
+1 -1
View File
@@ -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": {
@@ -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<boolean | null>(null);
const [retain, setRetain] = useState<string | null>(null);
const [withUploads, setWithUploads] = useState<boolean | null>(null);
if (!list.data) return <Loading error={list.error} />;
const d = list.data;
const nightlyOn = nightly ?? d.nightly;
const keep = retain ?? String(d.retain);
const uploadsOn = withUploads ?? d.uploads.enabled;
return (
<>
<Title icon={DatabaseBackup} sub="Copies of your website's database, kept on this server only and never sent anywhere.">Backups</Title>
<div className="space-y-6">
<Panel title="Database backups" sub="Every night at 02:20, and before every update of your website. Your photos and files (the media library) aren't in them.">
{d.lastError && <div className="mb-4"><Notice tone="warning">The last backup didn&apos;t work: {d.lastError}</Notice></div>}
<Panel title="Backups" sub="Every night at 02:20: your website's database, and your photos and files (the media library). The database is also backed up before every update.">
{d.lastError && <div className="mb-4"><Notice tone="warning">The last database backup didn&apos;t work: {d.lastError}</Notice></div>}
{d.uploads.lastError && <div className="mb-4"><Notice tone="warning">The last backup of the photos and files didn&apos;t work: {d.uploads.lastError}</Notice></div>}
{now.message && <div className="mb-4"><Notice tone={now.message.tone}>{now.message.text}</Notice></div>}
<Btn kind="primary" busy={now.busy} onClick={async () => {
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</Btn>
<form className="mt-6 space-y-4 border-t border-gray-200 pt-4" onSubmit={async (e) => {
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();
}}>
<label className="flex items-start gap-3">
<input type="checkbox" className="mt-1 h-4 w-4 rounded border-gray-300" checked={nightlyOn} onChange={(e) => setNightly(e.target.checked)} />
<span><span className="block text-sm font-medium text-gray-800">Back up every night</span><span className="block text-xs text-gray-500">Backups before each update are made either way.</span></span>
</label>
<label className="flex items-start gap-3">
<input type="checkbox" className="mt-1 h-4 w-4 rounded border-gray-300" checked={uploadsOn} onChange={(e) => setWithUploads(e.target.checked)} />
<span><span className="block text-sm font-medium text-gray-800">Include the photos and files</span><span className="block text-xs text-gray-500">The first backup copies them all; after that, only what&apos;s new is copied.</span></span>
</label>
<div className="max-w-xs">
<Field label="Keep the newest" hint="Older backups are deleted (1 to 365)." error={save.fields.retain}>
<Field label="Keep the newest" hint="Of each kind; older backups are deleted (1 to 365)." error={save.fields.retain}>
<input type="number" min={1} max={365} className={inputClass} value={keep} onChange={(e) => setRetain(e.target.value)} />
</Field>
</div>
@@ -60,7 +76,7 @@ export default function Backups() {
</form>
</Panel>
<Panel title="Backups on this server" sub="A backup holds your whole site and the names and email addresses of its editors: keep a downloaded copy somewhere safe, and delete it when you're done.">
<Panel title="Database backups on this server" sub="A backup holds your whole site and the names and email addresses of its editors: keep a downloaded copy somewhere safe, and delete it when you're done.">
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<thead className="text-gray-600"><tr><th className="py-2 pr-4 font-medium">Made</th><th className="py-2 pr-4 font-medium">Size</th><th className="py-2 font-medium"><span className="sr-only">Download</span></th></tr></thead>
@@ -81,6 +97,25 @@ export default function Backups() {
</table>
</div>
</Panel>
<Panel title="Photos and files" sub="Kept on this server. To put them back, Cross Code copies a backup into your media library.">
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<thead className="text-gray-600"><tr><th className="py-2 pr-4 font-medium">Made</th><th className="py-2 pr-4 font-medium">Files</th><th className="py-2 pr-4 font-medium">Size</th><th className="py-2 font-medium">New since the one before</th></tr></thead>
<tbody className="divide-y divide-gray-200">
{d.uploads.items.map((s) => (
<tr key={s.name}>
<td className="whitespace-nowrap py-2 pr-4">{when(s.createdAt)}</td>
<td className="py-2 pr-4">{s.files}</td>
<td className="py-2 pr-4 text-gray-600">{size(s.bytes)}</td>
<td className="py-2 text-gray-600">{s.newFiles} ({size(s.newBytes)})</td>
</tr>
))}
{!d.uploads.items.length && <tr><td colSpan={4} className="py-3 text-gray-600">{uploadsOn ? "None yet: the first is made tonight, or with Back up now." : "Off: the photos and files aren't backed up."}</td></tr>}
</tbody>
</table>
</div>
</Panel>
</div>
</>
);
+9 -2
View File
@@ -11,7 +11,7 @@ separately below; the two often differ.
| What | Repo | Latest | Tag | Released |
|------|------|--------|-----|----------|
| Cross Events | `crosscode-platform` (`apps/events`) | **3.7.1** | `events@3.7.1` | 2026-11-26 |
| Church Website | `crosscode-platform` (`apps/website`) | **1.3.0** | `website@1.3.0` | 2026-11-27 |
| Church Website | `crosscode-platform` (`apps/website`) | **1.4.0** | `website@1.4.0` | 2026-11-27 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.8.0** | `accounts@1.8.0` | 2026-11-26 |
| Server agent | `crosscode-platform` (`apps/agent`) | **1.6.0** | `agent@1.6.0` | 2026-11-27 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.19.0** | `contracts@1.19.0` | 2026-11-27 |
@@ -30,7 +30,7 @@ on each run, so merging to `main` and pushing releases it. Its changes are liste
| `@crosscode/auth-client` | `packages/auth-client` | 1.1.0 (released with Events 3.0.0 and Accounts 1.1.0) |
| `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) |
| `@crosscode/ui` | `packages/ui` | 0.3.0 (fonts, `ChurchFooter`; 0.2.0 with Accounts 1.7.0, 0.3.0 with Events 3.7.0) |
| Website | `apps/website` | 1.3.0 (1.0.0–1.1.0 released 2026-11-26, 1.2.0 and 1.3.0 on 2026-11-27; installed for the demo church cross-demo2 (1.2.0) only, Hope Family Church next) |
| Website | `apps/website` | 1.4.0 (1.0.0–1.1.0 released 2026-11-26, 1.2.0–1.4.0 on 2026-11-27; installed for the demo church cross-demo2 (1.2.0) only, Hope Family Church next) |
| App | `apps/app` | 0.0.0 (not started, phase 6) |
These shared packages ship inside the apps that use them, from the same checkout, so they don't
@@ -38,6 +38,13 @@ need their own tags until something outside this repo depends on them.
## What each latest release was for
- **Church Website 1.4.0 (2026-11-27):** nightly database backups (02:20, `backend/backups/`, the
same files crosscode makes before updates) with Admin → Backups, and background jobs on pg-boss
(backup, Hub heartbeat, event feed, YouTube; before: plain timers) with Admin → Background jobs
to switch each on or off, reschedule or run it. The heartbeat reports the newest backup (before:
always none, so the Hub warned "No backup reported") and the real job state. No migration.
Uploads aren't in the backups yet (1.5.0). Checked: backend tests (125), the admin e2e (10, axe
on both new pages), both builds, typecheck and lint. **Not deployed yet.**
- **Hub 2.25.0 + Church Website 1.3.0 + agent 1.6.0 + contracts 1.19.0 + crosscode script
(2026-11-27):** demo clients and demo data for the Website. Hub: a customer can be a demo client:
every install a demo site (Accounts included, and any it gets later) and never billed (billing
+2 -2
View File
@@ -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": "*",
+2 -1
View File
@@ -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"
}