Website 1.4.0: nightly database backups and background jobs

As Accounts and Cross Events: a gzipped pg_dump every night (02:20) into
backend/backups/, the same website-*.sql.gz files crosscode makes before
updates, with Admin -> Backups (back up now, download, how many to keep).
The heartbeat, event feed and YouTube move from plain timers onto pg-boss
with the backup, and Admin -> Background jobs switches each on or off,
changes its schedule or runs it now. The heartbeat now reports the newest
backup (before: always none, so the Hub warned) and the real job state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 09:47:30 +02:00
co-authored by Claude Opus 5.5
parent 8e52bd2d33
commit a3ac3da5a5
20 changed files with 1050 additions and 52 deletions
@@ -0,0 +1,93 @@
/**
* Settings → Backups and Settings → Background jobs (1.4.0, as Accounts and Cross Events). Admins
* only: a backup holds the whole site, and a job switched off stops the heartbeat or the backups.
*/
import fs from 'node:fs';
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 { ApiError, handle, sendError } from '../http.js';
import { audit } from '../lib/audit.js';
import { JobError, jobStatus, runNow, setOverride } from '../jobs.js';
type Who = { id: string; role: string };
export function maintenanceRouter(ctx: Ctx, who: (req: express.Request) => Who) {
const r = express.Router();
const json = express.json({ limit: '16kb' });
// On each route, not r.use: this router is mounted on the admin API's root.
const admin = requireRole(ctx, 'admin');
const jobError = (e: unknown) => {
if (e instanceof JobError) throw new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : e.status === 400 ? 'VALIDATION' : 'JOB_FAILED', e.message);
throw e;
};
// ─── Backups ───
r.get('/backups', admin, handle(async () => ({
items: (await listBackups(ctx)).map((b) => ({ filename: b.filename, size: b.size, createdAt: b.createdAt })),
nightly: await ctx.settings.bool('backup_nightly', true),
retain: await retainCount(ctx),
lastError: await ctx.settings.get('backup_last_error'),
})));
r.post('/backups/run', admin, handle(async (req) => {
let b;
try {
b = await runBackup(ctx);
} catch (e) {
throw new ApiError(502, 'BACKUP_FAILED', `The backup didn't work: ${(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 };
}));
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 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 };
}));
// A download holds the whole site's content and its editors: audited, never cached.
r.get('/backups/:file/download', admin, async (req, res) => {
try {
const file = backupPath(ctx, String(req.params.file));
if (!file) throw new ApiError(404, 'NOT_FOUND', 'That backup isn\'t there any more.');
const me = who(req);
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_downloaded', targetType: 'backup', targetId: String(req.params.file) });
res.setHeader('Content-Type', 'application/gzip');
res.setHeader('Cache-Control', 'no-store');
res.setHeader('Content-Disposition', `attachment; filename="${String(req.params.file)}"`);
fs.createReadStream(file).pipe(res);
} catch (e) {
sendError(res, e);
}
});
// ─── Background jobs ───
r.get('/jobs', admin, handle(() => jobStatus(ctx)));
r.put('/jobs/:name', admin, json, handle(async (req) => {
const name = String(req.params.name);
const out = await setOverride(ctx, name, { enabled: req.body?.enabled, cron: req.body?.cron }).catch(jobError);
const me = who(req);
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'job_settings_changed', targetType: 'job', targetId: name, metadata: out });
return { name, override: out };
}));
r.post('/jobs/:name/run', admin, handle(async (req) => {
const name = String(req.params.name);
const out = await runNow(ctx, name).catch(jobError);
const me = who(req);
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'job_run', targetType: 'job', targetId: name, metadata: { queued: out.queued } });
return out;
}));
return r;
}
+4
View File
@@ -24,6 +24,7 @@ import { connectTo, disconnectFrom } from '../links/connect.js';
import { linkedProducts } from '../links/store.js';
import { MAX_UPLOAD_BYTES, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js';
import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js';
import { maintenanceRouter } from './maintenance.js';
const who = (req: Request) => ({ id: req.signed!.user.id, role: req.signed!.user.role });
const param = (req: Request, name: string) => String(req.params[name] ?? '');
@@ -213,5 +214,8 @@ export function adminRouter(ctx: Ctx) {
r.post('/preview-links', editor, handle((req) => createPreviewLink(ctx, who(req))));
r.delete('/preview-links/:id', editor, handle(async (req) => { await revokePreviewLink(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
// ─── Backups and background jobs (1.4.0, admins only) ───
r.use(maintenanceRouter(ctx, who));
return r;
}