From a3ac3da5a5bfa105272a824bc27a3c43858f9308 Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Fri, 27 Nov 2026 09:47:30 +0200 Subject: [PATCH] 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 --- CHANGELOG.md | 13 + apps/website/CHANGELOG.md | 35 ++ apps/website/WHATS-NEW.md | 8 + apps/website/backend/package.json | 4 +- apps/website/backend/src/admin/maintenance.ts | 93 ++++++ apps/website/backend/src/admin/routes.ts | 4 + apps/website/backend/src/backups/backups.ts | 130 ++++++++ apps/website/backend/src/feed/feed.ts | 10 - apps/website/backend/src/hub/client.ts | 18 +- apps/website/backend/src/index.ts | 20 +- apps/website/backend/src/jobs.ts | 306 ++++++++++++++++++ apps/website/backend/src/lib/config.ts | 6 + apps/website/backend/src/site/youtube.ts | 10 - .../website/backend/tests/maintenance.test.ts | 175 ++++++++++ apps/website/e2e/admin.spec.ts | 4 +- apps/website/frontend/package.json | 2 +- apps/website/frontend/src/admin/nav.ts | 12 +- .../frontend/src/app/admin/backups/page.tsx | 87 +++++ .../frontend/src/app/admin/jobs/page.tsx | 159 +++++++++ package-lock.json | 6 +- 20 files changed, 1050 insertions(+), 52 deletions(-) create mode 100644 apps/website/backend/src/admin/maintenance.ts create mode 100644 apps/website/backend/src/backups/backups.ts create mode 100644 apps/website/backend/src/jobs.ts create mode 100644 apps/website/backend/tests/maintenance.test.ts create mode 100644 apps/website/frontend/src/app/admin/backups/page.tsx create mode 100644 apps/website/frontend/src/app/admin/jobs/page.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index e016ad1..949346b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …). +## website@1.4.0 - 2026-11-27 + +Database backups and background jobs for the Church Website, as Accounts and Cross Events have. +Details in `apps/website/CHANGELOG.md`. No migration (pg-boss makes its own `pgboss_website` +schema on first start). + +- **Backups:** a gzipped `pg_dump` every night at 02:20 into `backend/backups/`, the same + `website-*.sql.gz` files the crosscode script makes before updates; Admin → Backups. +- **Background jobs** on pg-boss: the backup, the Hub heartbeat, the event feed and YouTube (before: + plain timers); Admin → Background jobs switches each on or off, changes its schedule, runs one now. +- **The heartbeat tells the Hub the truth:** the newest backup (before: always none, so the Hub + warned "No backup reported") and the real job mode and failures. + ## contracts@1.19.0 + agent@1.6.0 + website@1.3.0 + crosscode script - 2026-11-27 Demo data for the Church Website, from the Hub (Hub 2.25.0). Additive: an Events `seed-demo` job diff --git a/apps/website/CHANGELOG.md b/apps/website/CHANGELOG.md index b0d3116..211f0d2 100644 --- a/apps/website/CHANGELOG.md +++ b/apps/website/CHANGELOG.md @@ -1,5 +1,40 @@ # Changelog — Church Website +## [1.4.0] — 2026-11-27 + +No migration: pg-boss makes its own schema (`pgboss_website`) on first start, as in Accounts. New +dependencies `pg-boss` and `cron-parser`. Needs `pg_dump` on the server (it's there: the +crosscode script uses it for the backups before updates). + +### Added + +- **Database backups** (`src/backups/backups.ts`, as Accounts 1.3.0): a gzipped `pg_dump` into + `backend/backups/` every night at 02:20 (after Accounts' at 02:00 on the same server) and when an + admin asks; the newest 14 kept (`backup_retain_count`), nightly on by default + (`backup_nightly`), the last failure in `backup_last_error`. Same names as the crosscode + script's backups before updates (`website-YYYYMMDD-HHMMSS.sql.gz`), so the list shows both. A + dump that fails part-way leaves no file. The database only: the uploads aren't in it (as Events). +- **Admin → Backups** (Owners and Admins): back up now, download one (audited, never cached), turn + nightly backups off, how many to keep. `GET /api/v1/admin/backups`, `POST …/backups/run`, + `PUT …/backups/settings`, `GET …/backups/:file/download`. +- **Background jobs on pg-boss** (`src/jobs.ts`, as Accounts 1.4.0): `backup`, `hub-heartbeat` + (every 15 minutes), `event-feed` (every 15 minutes) and `youtube` (hourly). One run per + schedule however many processes run; timers in the process if the queue can't start; + `JOBS_ENABLED=false` turns them all off. Per job: its .env flag (`BACKUP_ENABLED`, + `HUB_HEARTBEAT_ENABLED`, `FEED_JOB_ENABLED`, `YOUTUBE_JOB_ENABLED`) and `JOB_SCHEDULE_`. +- **Admin → Background jobs** (Owners and Admins): each job's schedule, next run and last runs; + switch it on or off, change its schedule (kept in `job_overrides`, winning over the .env, live + at once), or run it now. Audited (`job_settings_changed`, `job_run`). + +### Changed + +- **The heartbeat reports the newest backup** (`lastBackupAt`; before always null, so the Hub + showed "No backup reported" on every Website) **and the real job mode and failed runs in the + last 24 hours** (before always "queue" and 0). +- The heartbeat, the event feed and YouTube were plain timers (`startHeartbeats`, + `startFeedSync`, `startYoutubeSync`, removed); they're jobs now. The first event-feed and + YouTube runs are on their schedule rather than 20 and 30 seconds after a start. + ## [1.3.0] — 2026-11-27 No migration, no new environment settings. Needs contracts 1.19.0 (in this checkout). diff --git a/apps/website/WHATS-NEW.md b/apps/website/WHATS-NEW.md index b8ed93c..627913a 100644 --- a/apps/website/WHATS-NEW.md +++ b/apps/website/WHATS-NEW.md @@ -3,6 +3,14 @@ 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.4.0 + +- **Your website is backed up every night.** A copy of your site's content is kept on the server + every night, and before every update. Owners and Admins find them under **Backups**: make one + now, download one, or choose how many to keep. Your photos and files aren't in them. +- **Background jobs:** under **Background jobs**, see what your site does on a schedule (backups, + your events from Cross Events, new videos from YouTube), and switch each one on or off. + ## 1.3.0 - Nothing changes on your site. Behind the scenes, Cross Code can now load demo content on the diff --git a/apps/website/backend/package.json b/apps/website/backend/package.json index f249c19..bffd96f 100644 --- a/apps/website/backend/package.json +++ b/apps/website/backend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/website-backend", - "version": "1.3.0", + "version": "1.4.0", "description": "Church Website: the public site's content API, the admin API, publishing and uploads", "private": true, "type": "module", @@ -22,8 +22,10 @@ "@crosscode/contracts": "*", "@prisma/adapter-pg": "^7.10.1", "@prisma/client": "^7.10.1", + "cron-parser": "^5.10.2", "dotenv": "^16.3.1", "express": "^5.3.0", + "pg-boss": "^11.1.2", "sharp": "^0.35.5", "zod": "^4.6.7" }, diff --git a/apps/website/backend/src/admin/maintenance.ts b/apps/website/backend/src/admin/maintenance.ts new file mode 100644 index 0000000..05630e7 --- /dev/null +++ b/apps/website/backend/src/admin/maintenance.ts @@ -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; +} diff --git a/apps/website/backend/src/admin/routes.ts b/apps/website/backend/src/admin/routes.ts index 0bb2139..79904bc 100644 --- a/apps/website/backend/src/admin/routes.ts +++ b/apps/website/backend/src/admin/routes.ts @@ -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; } diff --git a/apps/website/backend/src/backups/backups.ts b/apps/website/backend/src/backups/backups.ts new file mode 100644 index 0000000..49e2ac3 --- /dev/null +++ b/apps/website/backend/src/backups/backups.ts @@ -0,0 +1,130 @@ +/** + * Database backups (1.4.0, as Accounts' and Cross Events' Settings → Backups): a gzipped + * `pg_dump` into backend/backups/ every night (02:20, after Accounts' at 02:00) and whenever an + * admin asks, kept on this server only. The `crosscode` script makes the same files before every + * deploy and uninstall (scripts/products/website.sh), so the admin's list shows both, newest first. + * The database only: the uploads (backend/uploads) aren't in it, as in Events. + * + * Settings: `backup_nightly` (default on), `backup_retain_count` (default 14), and what the last + * run did (`backup_last_error`). Needs the `pg_dump` program on the server (Postgres client). + */ +import { spawn } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import type { Readable } from 'node:stream'; +import { pipeline } from 'node:stream/promises'; +import { fileURLToPath } from 'node:url'; +import zlib from 'node:zlib'; +import type { Ctx } from '../context.js'; + +/** backend/backups, from src/ and dist/ alike (never relative to where the process started). */ +export const DEFAULT_BACKUP_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'backups'); + +/** The names this module and the crosscode script give a backup: website-YYYYMMDD-HHMMSS.sql.gz. */ +export const BACKUP_FILE = /^website-\d{8}-\d{6}\.sql\.gz$/; +export const DEFAULT_RETAIN = 14; +const MAX_RETAIN = 365; + +export type Backup = { filename: string; size: number; createdAt: Date }; + +/** Something that writes a plain-SQL dump of the database to a stream (tests pass their own). */ +export type Dumper = (databaseUrl: string) => { stdout: Readable; done: Promise }; + +const dir = (ctx: Ctx) => ctx.config.backupDir ?? DEFAULT_BACKUP_DIR; + +/** `pg_dump`, plain SQL, without owners or privileges (restores into any database user). */ +export const pgDump: Dumper = (databaseUrl) => { + const child = spawn('pg_dump', ['--no-owner', '--no-privileges', databaseUrl], { stdio: ['ignore', 'pipe', 'pipe'] }); + let stderr = ''; + child.stderr.on('data', (d) => { stderr += String(d); }); + const done = new Promise((resolve, reject) => { + child.on('error', (e) => reject(new Error(`pg_dump couldn't start (${e.message}). Install the PostgreSQL client on this server.`))); + child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`pg_dump stopped (exit ${code}): ${stderr.trim().slice(0, 400)}`)))); + }); + return { stdout: child.stdout, done }; +}; + +const pad = (n: number) => String(n).padStart(2, '0'); +/** website-20261120-020000.sql.gz in the server's local time, as the crosscode script names them. */ +export function backupName(at: Date): string { + return `website-${at.getFullYear()}${pad(at.getMonth() + 1)}${pad(at.getDate())}-${pad(at.getHours())}${pad(at.getMinutes())}${pad(at.getSeconds())}.sql.gz`; +} + +export async function retainCount(ctx: Ctx): Promise { + const n = Number(await ctx.settings.get('backup_retain_count')); + return Number.isInteger(n) && n >= 1 ? Math.min(n, MAX_RETAIN) : DEFAULT_RETAIN; +} + +/** Every backup in the folder, newest first. */ +export async function listBackups(ctx: Ctx): Promise { + let names: string[]; + try { + names = await fs.promises.readdir(dir(ctx)); + } catch { + return []; + } + const items = await Promise.all(names.filter((n) => BACKUP_FILE.test(n)).map(async (filename) => { + const st = await fs.promises.stat(path.join(dir(ctx), filename)); + return { filename, size: st.size, createdAt: st.mtime }; + })); + return items.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || b.filename.localeCompare(a.filename)); +} + +/** The newest backup's time, for the Hub heartbeat. */ +export async function lastBackupAt(ctx: Ctx): Promise { + return (await listBackups(ctx))[0]?.createdAt ?? null; +} + +/** The full path of a backup to download, or null if there's no such backup (or a bad name). */ +export function backupPath(ctx: Ctx, filename: string): string | null { + if (!BACKUP_FILE.test(filename)) return null; + const p = path.join(dir(ctx), filename); + return fs.existsSync(p) ? p : null; +} + +/** Deletes the oldest backups beyond the number kept. */ +export async function rotate(ctx: Ctx): Promise { + const old = (await listBackups(ctx)).slice(await retainCount(ctx)); + await Promise.all(old.map((b) => fs.promises.unlink(path.join(dir(ctx), b.filename)).catch(() => {}))); + return old.length; +} + +/** + * 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 { + const url = ctx.config.databaseUrl; + try { + if (!url) throw new Error('DATABASE_URL isn\'t set, so there\'s no database to back up.'); + await fs.promises.mkdir(dir(ctx), { recursive: true, mode: 0o700 }); + // Two in the same second (the button pressed twice): the next free second's name. + const at = ctx.now().getTime(); + let filename = backupName(new Date(at)); + for (let s = 1; fs.existsSync(path.join(dir(ctx), filename)); s++) filename = backupName(new Date(at + s * 1000)); + const file = path.join(dir(ctx), filename); + const { stdout, done } = dumper(url); + // Both must finish: pg_dump exiting cleanly, and the file written. Wait for both either way, + // so a failed one's file is deleted after the last write, not before it. + const [dumped, written] = await Promise.allSettled([done, pipeline(stdout, zlib.createGzip(), fs.createWriteStream(file, { mode: 0o600 }))]); + const failed = [dumped, written].find((r): r is PromiseRejectedResult => r.status === 'rejected'); + if (failed) { + await fs.promises.unlink(file).catch(() => {}); + throw failed.reason; + } + await rotate(ctx); + await ctx.settings.set('backup_last_error', null); + const st = await fs.promises.stat(file); + return { filename, size: st.size, createdAt: st.mtime }; + } catch (e) { + await ctx.settings.set('backup_last_error', `${ctx.now().toISOString()} ${(e as Error).message}`.slice(0, 600)); + throw e; + } +} + +/** The nightly `backup` job: skipped when an admin has turned nightly backups off. */ +export async function runBackupJob(ctx: Ctx) { + if (!(await ctx.settings.bool('backup_nightly', true))) return { skipped: true }; + const b = await runBackup(ctx); + return { filename: b.filename, size: b.size }; +} diff --git a/apps/website/backend/src/feed/feed.ts b/apps/website/backend/src/feed/feed.ts index a021568..8168cbd 100644 --- a/apps/website/backend/src/feed/feed.ts +++ b/apps/website/backend/src/feed/feed.ts @@ -161,13 +161,3 @@ export async function syncAll(ctx: Ctx) { return { links: links.length, failed }; } -/** Every 15 minutes (ROADMAP-v3 §4: "consumers also poll every 15 minutes as a fallback"). */ -export function startFeedSync(ctx: Ctx): () => void { - if (!ctx.config.jobsEnabled) return () => {}; - const run = () => syncAll(ctx).catch((e) => console.warn('[feed]', (e as Error).message)); - const first = setTimeout(run, 20_000); - const timer = setInterval(run, 15 * 60 * 1000); - first.unref?.(); - timer.unref?.(); - return () => { clearTimeout(first); clearInterval(timer); }; -} diff --git a/apps/website/backend/src/hub/client.ts b/apps/website/backend/src/hub/client.ts index 51de13c..4106e69 100644 --- a/apps/website/backend/src/hub/client.ts +++ b/apps/website/backend/src/hub/client.ts @@ -15,6 +15,8 @@ import { connectAccountsIfListed } from '../links/connect.js'; import { keyPair, saveLinkedProducts } from '../links/store.js'; import { hubPublicKey, verifyToken } from './licence.js'; import { storage } from '../admin/media.js'; +import { lastBackupAt } from '../backups/backups.js'; +import { jobsHealth } from '../jobs.js'; export const PROTOCOL_VERSION = 2; const TIMEOUT_MS = 15000; @@ -62,8 +64,10 @@ export async function health(ctx: Ctx) { return { uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000), db: await dbUp(ctx), - jobs: { mode: ctx.config.jobsEnabled ? 'queue' : 'off', failedLast24h: 0 }, - lastBackupAt: null, + // 1.4.0: the real job mode and failures, and the newest backup (before: always null, so the + // Hub warned "No backup reported"). + jobs: await jobsHealth(ctx), + lastBackupAt: (await lastBackupAt(ctx).catch(() => null))?.toISOString() ?? null, disk: null, errorsLast24h: null, pendingMigrations: 0, @@ -190,16 +194,6 @@ export async function connectFromEnv(ctx: Ctx, { attempts = 5, delayMs = 60_000 return { connected: false, reason: 'unreachable' }; } -/** Heartbeats every 15 minutes until stopped (pg-boss comes with the Website's other jobs). */ -export function startHeartbeats(ctx: Ctx): () => void { - if (!ctx.config.jobsEnabled) return () => {}; - const timer = setInterval(() => { - heartbeat(ctx).catch((e) => console.warn('[hub] Heartbeat failed:', (e as Error).message)); - }, 15 * 60 * 1000); - timer.unref?.(); - return () => clearInterval(timer); -} - /** * "Get more storage" (WEBSITE-1.0-PLAN §10, decision 12; contracts 1.18.0): asks the Hub for more * 5 GB steps. The Hub emails Cross Code; the new limit arrives with a later heartbeat answer. diff --git a/apps/website/backend/src/index.ts b/apps/website/backend/src/index.ts index 7c0f75d..da9d7ed 100644 --- a/apps/website/backend/src/index.ts +++ b/apps/website/backend/src/index.ts @@ -1,19 +1,18 @@ /** * Starts the Church Website's backend: database, HTTP server, and (on a Hub install) registering - * with the Hub from HUB_LICENCE_KEY, then heartbeats, which also link the site to the church's - * Accounts once the Hub lists it, and the hourly YouTube feed (§7). The other jobs (storage emails, - * the event feed) come with their features (docs/WEBSITE-1.0-PLAN.md §1). + * with the Hub from HUB_LICENCE_KEY, then the background jobs (src/jobs.ts, 1.4.0): heartbeats, + * which also link the site to the church's Accounts once the Hub lists it, the event feed, the + * hourly YouTube feed (§7) and the nightly database backup. */ import 'dotenv/config'; import { PrismaPg } from '@prisma/adapter-pg'; import { PrismaClient } from './generated/prisma/client.js'; import { createApp } from './app.js'; import { createCtx } from './context.js'; -import { connectFromEnv, heartbeat, startHeartbeats } from './hub/client.js'; +import { connectFromEnv, heartbeat } from './hub/client.js'; +import { startJobs } from './jobs.js'; import { loadConfig } from './lib/config.js'; import { ensureStarterPages } from './site/starter.js'; -import { startYoutubeSync } from './site/youtube.js'; -import { startFeedSync } from './feed/feed.js'; async function main() { const config = loadConfig(); @@ -27,18 +26,15 @@ async function main() { .catch((e) => console.error('[website] Couldn\'t add the starter pages:', (e as Error).message)); const app = createApp(ctx); const server = app.listen(config.port, () => console.log(`[website] Listening on ${config.port} (${config.publicUrl}).`)); - const stopHeartbeats = startHeartbeats(ctx); - const stopYoutube = startYoutubeSync(ctx); - const stopFeed = startFeedSync(ctx); + // 1.4.0: the heartbeat, the event feed, YouTube and the nightly backup, on pg-boss. + const stopJobs = await startJobs(ctx, url); connectFromEnv(ctx).then((r) => { if (r.connected || r.reason === 'already') heartbeat(ctx).catch(() => {}); }).catch(() => {}); const stop = async () => { - stopHeartbeats(); - stopYoutube(); - stopFeed(); + await stopJobs(); server.close(); await db.$disconnect(); process.exit(0); diff --git a/apps/website/backend/src/jobs.ts b/apps/website/backend/src/jobs.ts new file mode 100644 index 0000000..067e101 --- /dev/null +++ b/apps/website/backend/src/jobs.ts @@ -0,0 +1,306 @@ +/** + * Background jobs on pg-boss (1.4.0, as Accounts and Cross Events): one run per schedule however + * many processes run, and timers in this process if the queue can't start. JOBS_ENABLED=false + * turns them all off. Before 1.4.0 the heartbeat, the event feed and YouTube were plain timers. + * + * Admin → Background jobs shows each job's schedule and last runs, runs one now, and switches one + * on or off or changes its schedule. That choice is kept in the database (`job_overrides`), wins + * over the .env (a job's own flag, e.g. BACKUP_ENABLED=false, and JOB_SCHEDULE_) and takes + * effect straight away (in other processes within 30 seconds). + */ +import { CronExpressionParser } from 'cron-parser'; +import PgBoss from 'pg-boss'; +import type { Ctx } from './context.js'; +import { runBackupJob } from './backups/backups.js'; +import { syncAll } from './feed/feed.js'; +import { heartbeat } from './hub/client.js'; +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) }, + { 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) }, + { name: 'youtube', label: 'Messages: new videos from the church\'s YouTube channel', cron: '7 * * * *', env: 'YOUTUBE_JOB_ENABLED', run: (ctx) => syncYoutube(ctx) }, +]; + +const SCHEMA = 'pgboss_website'; +const OVERRIDES_KEY = 'job_overrides'; +const OVERRIDES_TTL_MS = 30_000; + +export type Override = { enabled?: boolean; cron?: string }; +type Run = { state: string; createdOn?: Date | null; startedOn: Date | null; completedOn: Date | null; output: unknown }; + +/** The running queue or timers, the admin's choices (cached), and a short history for timer mode. */ +type State = { + mode: 'queue' | 'timers' | 'off'; + boss: PgBoss | null; + timers: Map; + history: Map; + overrides: Record; + overridesAt: number; + env: NodeJS.ProcessEnv; +}; + +const state: State = { mode: 'off', boss: null, timers: new Map(), history: new Map(), overrides: {}, overridesAt: 0, env: process.env }; + +/** Tests: a different environment for the env flags and schedules. */ +export function useEnvForTest(env: NodeJS.ProcessEnv): void { + state.env = env; +} + +const flag = (name: string | null) => { + if (!name) return true; + const v = state.env[name]; + return v === undefined || v === '' ? true : String(v).toLowerCase() !== 'false'; +}; + +export function isCron(cron: unknown, tz = 'Africa/Johannesburg'): cron is string { + if (typeof cron !== 'string' || cron.trim().split(/\s+/).length !== 5) return false; + try { + CronExpressionParser.parse(cron, { tz }); + return true; + } catch { + return false; + } +} + +export async function loadOverrides(ctx: Ctx, force = false): Promise> { + if (!force && state.overridesAt && Date.now() - state.overridesAt < OVERRIDES_TTL_MS) return state.overrides; + try { + // Straight from the table: Settings caches for 30 s too, and a save must show at once here. + const row = await ctx.db.appSetting.findUnique({ where: { key: OVERRIDES_KEY } }); + const parsed = row?.value ? JSON.parse(row.value) : {}; + state.overrides = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}; + state.overridesAt = Date.now(); + } catch (e) { + if (force) console.warn('[jobs] Could not read the job overrides:', (e as Error).message); + } + return state.overrides; +} + +/** Whether the .env switches a job on (its own flag; JOBS_ENABLED aside). */ +export const envEnabled = (job: Job) => flag(job.env); + +/** JOBS_ENABLED=false turns all off; then the admin's choice; then the job's env flag. */ +export function isEnabled(ctx: Ctx, job: Job): boolean { + if (!ctx.config.jobsEnabled) return false; + const o = state.overrides[job.name]; + if (o && typeof o.enabled === 'boolean') return o.enabled; + return envEnabled(job); +} + +/** The .env's schedule (JOB_SCHEDULE_, checked) or the job's own. */ +export function envCronFor(ctx: Ctx, job: Job): string { + const v = state.env[`JOB_SCHEDULE_${job.name.toUpperCase().replace(/-/g, '_')}`]; + if (v && isCron(v, ctx.config.timezone)) return v; + if (v) console.warn(`[jobs] Ignoring invalid schedule for ${job.name}: "${v}"`); + return job.cron; +} + +export function cronFor(ctx: Ctx, job: Job): string { + const o = state.overrides[job.name]; + if (o && isCron(o.cron, ctx.config.timezone)) return o.cron; + return envCronFor(ctx, job); +} + +export const nextRun = (cron: string, tz: string, from = new Date()) => CronExpressionParser.parse(cron, { tz, currentDate: from }).next().toDate(); + +function remember(name: string, run: Run) { + state.history.set(name, [run, ...(state.history.get(name) ?? [])].slice(0, 10)); +} + +async function runJob(ctx: Ctx, job: Job) { + return (await job.run(ctx)) ?? null; +} + +function startTimer(ctx: Ctx, job: Job) { + const tz = ctx.config.timezone; + const scheduleNext = () => { + if (!isEnabled(ctx, job)) { state.timers.delete(job.name); return; } + const delay = Math.max(1000, nextRun(cronFor(ctx, job), tz).getTime() - Date.now()); + state.timers.set(job.name, setTimeout(async () => { + await loadOverrides(ctx); + if (!isEnabled(ctx, job)) { state.timers.delete(job.name); return; } + const entry: Run = { state: 'active', startedOn: new Date(), completedOn: null, output: null }; + try { + entry.output = await runJob(ctx, job); + entry.state = 'completed'; + } catch (e) { + entry.state = 'failed'; + entry.output = { message: (e as Error).message }; + console.warn(`[jobs] ${job.name}:`, (e as Error).message); + } finally { + entry.completedOn = new Date(); + remember(job.name, entry); + scheduleNext(); + } + }, Math.min(delay, 2 ** 31 - 1))); + }; + scheduleNext(); +} + +async function applyJob(ctx: Ctx, job: Job) { + if (state.mode === 'queue' && state.boss) { + if (isEnabled(ctx, job)) await state.boss.schedule(job.name, cronFor(ctx, job), undefined, { tz: ctx.config.timezone }); + else await state.boss.unschedule(job.name).catch(() => {}); + } else if (state.mode === 'timers') { + clearTimeout(state.timers.get(job.name)); + state.timers.delete(job.name); + startTimer(ctx, job); + } +} + +export async function startJobs(ctx: Ctx, connectionString: string): Promise<() => Promise> { + if (!ctx.config.jobsEnabled) { + state.mode = 'off'; + return async () => {}; + } + await loadOverrides(ctx, true); + const tz = ctx.config.timezone; + try { + const boss = new PgBoss({ connectionString, schema: SCHEMA, application_name: 'crosscode-website-jobs' }); + boss.on('error', (e: Error) => console.warn('[jobs]', e.message)); + await boss.start(); + state.boss = boss; + state.mode = 'queue'; + for (const job of JOBS) { + await boss.createQueue(job.name, { policy: 'stately' }).catch(() => {}); + // Every job has a worker (an admin can switch one on later); only those on are scheduled. + await boss.work(job.name, async (batch) => { + await loadOverrides(ctx); + const manual = (Array.isArray(batch) ? batch : [batch]).some((j) => (j as { data?: { manual?: boolean } })?.data?.manual); + if (!manual && !isEnabled(ctx, job)) return { skipped: 'switched off' }; + return runJob(ctx, job); + }); + if (isEnabled(ctx, job)) await boss.schedule(job.name, cronFor(ctx, job), undefined, { tz }); + else await boss.unschedule(job.name).catch(() => {}); + } + const off = JOBS.filter((j) => !isEnabled(ctx, j)).map((j) => j.name); + console.log(`[jobs] Job queue started: ${JOBS.filter((j) => isEnabled(ctx, j)).map((j) => j.name).join(', ')}${off.length ? ` (off: ${off.join(', ')})` : ''}.`); + return async () => { await boss.stop({ graceful: true }); state.boss = null; state.mode = 'off'; }; + } catch (e) { + console.warn('[jobs] Job queue unavailable, using timers:', (e as Error).message); + state.boss = null; + state.mode = 'timers'; + for (const job of JOBS) startTimer(ctx, job); + return async () => { state.timers.forEach(clearTimeout); state.timers.clear(); state.mode = 'off'; }; + } +} + +export class JobError extends Error { + constructor(public status: number, message: string) { super(message); } +} + +/** + * Saves an admin's choice for one job and applies it. `enabled` / `cron`: a value wins over the + * .env, null goes back to it, undefined leaves it. + */ +export async function setOverride(ctx: Ctx, name: string, change: { enabled?: unknown; cron?: unknown }): Promise<{ enabled: boolean | null; cron: string | null }> { + const job = JOBS.find((j) => j.name === name); + if (!job) throw new JobError(404, 'There\'s no such job.'); + const { enabled, cron } = change; + if (enabled !== undefined && enabled !== null && typeof enabled !== 'boolean') throw new JobError(400, '"enabled" must be true, false or null.'); + if (cron !== undefined && cron !== null && cron !== '' && (typeof cron !== 'string' || cron.length > 100 || !isCron(cron.trim(), ctx.config.timezone))) { + throw new JobError(400, 'That schedule isn\'t a cron expression with five fields (minute hour day month weekday), e.g. "*/10 * * * *".'); + } + const all = { ...(await loadOverrides(ctx, true)) }; + const entry: Override = { ...(all[name] ?? {}) }; + if (enabled !== undefined) { if (enabled === null) delete entry.enabled; else entry.enabled = enabled as boolean; } + if (cron !== undefined) { if (cron === null || cron === '') delete entry.cron; else entry.cron = (cron as string).trim(); } + if (Object.keys(entry).length) all[name] = entry; else delete all[name]; + const value = JSON.stringify(all); + await ctx.db.appSetting.upsert({ where: { key: OVERRIDES_KEY }, update: { value }, create: { key: OVERRIDES_KEY, value } }); + ctx.settings.forget(); + state.overrides = all; + state.overridesAt = Date.now(); + await applyJob(ctx, job); + return { enabled: typeof entry.enabled === 'boolean' ? entry.enabled : null, cron: entry.cron ?? null }; +} + +/** Runs a job now: queued in queue mode (it runs even when switched off), here otherwise. */ +export async function runNow(ctx: Ctx, name: string): Promise<{ queued: boolean; output?: unknown }> { + const job = JOBS.find((j) => j.name === name); + if (!job) throw new JobError(404, 'There\'s no such job.'); + if (state.mode === 'queue' && state.boss) { + await state.boss.send(job.name, { manual: true }, { singletonKey: `${job.name}-manual` }); + return { queued: true }; + } + const entry: Run = { state: 'active', startedOn: new Date(), completedOn: null, output: null }; + try { + entry.output = await runJob(ctx, job); + entry.state = 'completed'; + return { queued: false, output: entry.output }; + } catch (e) { + entry.state = 'failed'; + entry.output = { message: (e as Error).message }; + throw new JobError(502, `The job failed: ${(e as Error).message}`); + } finally { + entry.completedOn = new Date(); + remember(job.name, entry); + } +} + +/** Each job with its switch, schedule, what the .env says, the admin's choice, and its last runs. */ +export async function jobStatus(ctx: Ctx) { + await loadOverrides(ctx, true); + const tz = ctx.config.timezone; + const recent = new Map(); + if (state.mode === 'queue') { + try { + // As in Cross Events: timestamptz as plain UTC, so Prisma's pg adapter doesn't drop the offset. + const rows = await ctx.db.$queryRawUnsafe<(Run & { name: string })[]>(` + SELECT name, state, created_on AT TIME ZONE 'UTC' AS "createdOn", started_on AT TIME ZONE 'UTC' AS "startedOn", + completed_on AT TIME ZONE 'UTC' AS "completedOn", output + FROM ( + SELECT name, state::text, created_on, started_on, completed_on, output, + row_number() OVER (PARTITION BY name ORDER BY created_on DESC) AS rn + FROM ${SCHEMA}.job WHERE name = ANY($1::text[]) + ) ranked WHERE rn <= 10 ORDER BY "createdOn" DESC`, JOBS.map((j) => j.name)); + for (const r of rows) recent.set(r.name, [...(recent.get(r.name) ?? []), r]); + } catch (e) { + console.warn('[jobs] Could not read the run history:', (e as Error).message); + } + } else { + for (const [name, list] of state.history) recent.set(name, list); + } + return { + mode: state.mode, + timezone: tz, + jobsEnabledEnv: ctx.config.jobsEnabled, + jobs: JOBS.map((job) => { + const cron = cronFor(ctx, job); + const enabled = isEnabled(ctx, job); + const o = state.overrides[job.name] ?? {}; + return { + name: job.name, label: job.label, cron, enabled, envFlag: job.env, + envEnabled: envEnabled(job), envCron: envCronFor(ctx, job), defaultCron: job.cron, + override: { enabled: typeof o.enabled === 'boolean' ? o.enabled : null, cron: isCron(o.cron, tz) ? o.cron : null }, + nextRun: enabled && state.mode !== 'off' ? nextRun(cron, tz) : null, + recent: recent.get(job.name) ?? [], + }; + }), + }; +} + +/** What the Hub's heartbeat reports (hub.healthSchema `jobs`): the real mode and failed runs in 24 hours. */ +export async function jobsHealth(ctx: Ctx): Promise<{ mode: 'queue' | 'timers' | 'off'; failedLast24h: number }> { + const since = ctx.now().getTime() - 24 * 3600e3; + if (state.mode === 'queue') { + try { + const rows = await ctx.db.$queryRawUnsafe<{ n: number | bigint }[]>( + `SELECT count(*)::int AS n FROM ${SCHEMA}.job WHERE state = 'failed' AND name = ANY($1::text[]) AND completed_on > now() - interval '24 hours'`, + JOBS.map((j) => j.name), + ); + return { mode: 'queue', failedLast24h: Number(rows[0]?.n ?? 0) }; + } catch { + return { mode: 'queue', failedLast24h: 0 }; + } + } + let failed = 0; + for (const runs of state.history.values()) failed += runs.filter((r) => r.state === 'failed' && (r.completedOn?.getTime() ?? 0) > since).length; + return { mode: state.mode, failedLast24h: failed }; +} diff --git a/apps/website/backend/src/lib/config.ts b/apps/website/backend/src/lib/config.ts index 745880b..dcd2562 100644 --- a/apps/website/backend/src/lib/config.ts +++ b/apps/website/backend/src/lib/config.ts @@ -27,6 +27,10 @@ export type Config = { allowPrivateLinks: boolean; /** How long an admin stays signed in (days). */ sessionDays: number; + /** 1.4.0: for the backups' pg_dump (DATABASE_URL, as Prisma uses). */ + databaseUrl: string | null; + /** 1.4.0: where backups go; default backend/backups (tests use their own folder). */ + backupDir: string | null; }; const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true'); @@ -62,5 +66,7 @@ export function loadConfig(env: Record = process.env uploadDir: env.UPLOAD_DIR?.trim() || null, allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false), sessionDays: Math.min(90, Math.max(1, Number(env.SESSION_DAYS) || 14)), + databaseUrl: env.DATABASE_URL?.trim() || null, + backupDir: null, }; } diff --git a/apps/website/backend/src/site/youtube.ts b/apps/website/backend/src/site/youtube.ts index 6d1463e..d589203 100644 --- a/apps/website/backend/src/site/youtube.ts +++ b/apps/website/backend/src/site/youtube.ts @@ -99,13 +99,3 @@ export async function syncYoutube(ctx: Ctx, fetcher: Fetcher = (u) => fetch(u, { return { added }; } -/** Every hour while the site runs (pg-boss comes with the other jobs). */ -export function startYoutubeSync(ctx: Ctx): () => void { - if (!ctx.config.jobsEnabled) return () => {}; - const run = () => syncYoutube(ctx).catch((e) => console.warn('[youtube]', (e as Error).message)); - const first = setTimeout(run, 30_000); - const timer = setInterval(run, 60 * 60 * 1000); - first.unref?.(); - timer.unref?.(); - return () => { clearTimeout(first); clearInterval(timer); }; -} diff --git a/apps/website/backend/tests/maintenance.test.ts b/apps/website/backend/tests/maintenance.test.ts new file mode 100644 index 0000000..4fba8f3 --- /dev/null +++ b/apps/website/backend/tests/maintenance.test.ts @@ -0,0 +1,175 @@ +// 1.4.0: database backups (Settings → Backups) and the background jobs (Settings → Background +// jobs), as Accounts and Cross Events; the heartbeat reports both to the Hub. +import { after, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +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 { health } from '../src/hub/client.js'; +import { JOBS, cronFor, isEnabled, jobsHealth, runNow, useEnvForTest } from '../src/jobs.js'; +import { hashToken } from '../src/lib/crypto.js'; +import { harness, SITE } from './support/harness.js'; + +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)); + +async function site() { + const h = await harness({ linked: false }); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ccw-backups-')); + h.ctx.config.backupDir = dir; + h.ctx.config.databaseUrl = 'postgresql://test@127.0.0.1/website_test'; + const as = async (role: Role) => { + const id = `00000000-0000-4000-8000-00000000000${['owner', 'admin', 'editor'].indexOf(role) + 1}`; + await h.db.websiteUser.create({ data: { id, name: `Sam the ${role}`, email: `${role}@hope.test`, role } }); + await h.db.session.create({ data: { tokenHash: hashToken(`token-${role}`), userId: id, expiresAt: new Date(Date.now() + 864e5) } }); + const cookie = `ccw_session=token-${role}`; + return { + get: (p: string) => request(h.app).get(`/api/v1/admin${p}`).set('Cookie', cookie), + put: (p: string, body: object) => request(h.app).put(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body), + post: (p: string, body: object = {}) => request(h.app).post(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body), + }; + }; + return { ...h, dir, as }; +} + +describe('backups (1.4.0)', () => { + it('a backup is the gzipped dump, named as the crosscode script names them', async () => { + const h = await site(); + const b = await runBackup(h.ctx, dumpOf('CREATE TABLE "Page" ();\n')); + assert.match(b.filename, BACKUP_FILE); + assert.equal(zlib.gunzipSync(fs.readFileSync(path.join(h.dir, b.filename))).toString(), 'CREATE TABLE "Page" ();\n'); + assert.equal(backupName(new Date(2026, 10, 27, 2, 20, 5)), 'website-20261127-022005.sql.gz'); + const again = await runBackup(h.ctx, dumpOf('-- again\n')); + assert.notEqual(again.filename, b.filename, 'a second one in the same second gets its own name'); + }); + + it('a dump that fails part-way leaves no file, and says why', async () => { + const h = await site(); + await assert.rejects(runBackup(h.ctx, failing), /connection refused/); + assert.equal((await listBackups(h.ctx)).length, 0); + assert.match(String(await h.ctx.settings.get('backup_last_error')), /connection refused/); + await runBackup(h.ctx, dumpOf('-- fine\n')); + assert.equal(await h.ctx.settings.get('backup_last_error'), null); + }); + + it('only the newest are kept; a download only by a backup\'s own name', async () => { + const h = await site(); + await h.ctx.settings.set('backup_retain_count', '2'); + for (const n of [1, 2, 3]) await runBackup(h.ctx, dumpOf(`-- ${n}\n`)); + const left = await listBackups(h.ctx); + assert.equal(left.length, 2); + assert.ok(backupPath(h.ctx, left[0]!.filename)); + assert.equal(backupPath(h.ctx, '../.env'), null); + assert.equal(backupPath(h.ctx, 'accounts-20200101-000000.sql.gz'), null); + }); + + it('the nightly backup is skipped while it\'s turned off', async () => { + const h = await site(); + await h.ctx.settings.set('backup_nightly', 'false'); + assert.deepEqual(await runBackupJob(h.ctx), { skipped: true }); + }); + + it('admins see, change and download them; editors can\'t', async () => { + const h = await site(); + await runBackup(h.ctx, dumpOf('-- a backup\n')); + const editor = await h.as('editor'); + assert.equal((await editor.get('/backups')).status, 403); + assert.equal((await editor.post('/backups/run')).status, 403); + assert.equal((await editor.get('/pages')).status, 200, 'the admin-only routes don\'t stop the others'); + + const admin = await h.as('admin'); + const list = await admin.get('/backups'); + assert.equal(list.status, 200, JSON.stringify(list.body)); + assert.equal(list.body.nightly, true); + assert.equal(list.body.retain, 14); + const file = await admin.get(`/backups/${list.body.items[0].filename}/download`).buffer(true).parse((res, cb) => { + const chunks: Buffer[] = []; + res.on('data', (c: Buffer) => chunks.push(c)); + res.on('end', () => cb(null, Buffer.concat(chunks))); + }); + assert.equal(file.status, 200); + assert.equal(file.headers['cache-control'], 'no-store'); + assert.equal(zlib.gunzipSync(file.body as Buffer).toString(), '-- a backup\n'); + assert.equal((await admin.get('/backups/nope.sql.gz/download')).status, 404); + assert.equal(await h.db.auditLog.count({ where: { action: 'backup_downloaded' } }), 1); + + 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.equal(await h.ctx.settings.bool('backup_nightly', true), false); + }); + + it('the heartbeat reports the newest backup and the real job mode (before: null, so the Hub warned)', async () => { + const h = await site(); + assert.equal((await health(h.ctx)).lastBackupAt, null); + await runBackup(h.ctx, dumpOf('-- x\n')); + const report = await health(h.ctx); + assert.ok(report.lastBackupAt && Date.parse(report.lastBackupAt) > Date.now() - 60e3); + assert.deepEqual(report.jobs, await jobsHealth(h.ctx)); + assert.equal(report.jobs.mode, 'off', 'no job system started in the tests'); + }); +}); + +describe('background jobs (1.4.0)', () => { + const backup = JOBS.find((j) => j.name === 'backup')!; + + it('the heartbeat, the event feed, YouTube and the backup are jobs', () => { + assert.deepEqual(JOBS.map((j) => j.name).sort(), ['backup', 'event-feed', 'hub-heartbeat', 'youtube']); + }); + + it('the .env flag and schedule apply until an admin chooses; their choice wins; null goes back', async () => { + const h = await site(); + useEnvForTest({ BACKUP_ENABLED: 'false', JOB_SCHEDULE_BACKUP: '30 1 * * *' }); + h.ctx.config.jobsEnabled = true; // nothing is started here either way + const admin = await h.as('admin'); + type Row = { name: string; enabled: boolean; envEnabled: boolean; cron: string; override: { enabled: boolean | null; cron: string | null } }; + let job = ((await admin.get('/jobs')).body.jobs as Row[]).find((j) => j.name === 'backup')!; + assert.equal(job.enabled, false); + assert.equal(job.cron, '30 1 * * *'); + assert.deepEqual(job.override, { enabled: null, cron: null }); + + const on = await admin.put('/jobs/backup', { enabled: true, cron: '0 3 * * *' }); + assert.equal(on.status, 200, JSON.stringify(on.body)); + assert.deepEqual(on.body.override, { enabled: true, cron: '0 3 * * *' }); + assert.equal(isEnabled(h.ctx, backup), true); + assert.equal(cronFor(h.ctx, backup), '0 3 * * *'); + job = ((await admin.get('/jobs')).body.jobs as Row[]).find((j) => j.name === 'backup')!; + assert.equal(job.enabled, true); + assert.equal(job.envEnabled, false); + + const back = await admin.put('/jobs/backup', { enabled: null, cron: null }); + assert.deepEqual(back.body.override, { enabled: null, cron: null }); + assert.equal(isEnabled(h.ctx, backup), false); + assert.equal(await h.db.auditLog.count({ where: { action: 'job_settings_changed' } }), 2); + useEnvForTest(process.env); + }); + + it('a bad schedule, a bad switch and an unknown job are refused; editors can\'t change jobs', async () => { + const h = await site(); + const admin = await h.as('admin'); + assert.equal((await admin.put('/jobs/backup', { cron: 'every night' })).status, 400); + assert.equal((await admin.put('/jobs/backup', { enabled: 'yes' })).status, 400); + assert.equal((await admin.put('/jobs/nope', { enabled: true })).status, 404); + const editor = await h.as('editor'); + assert.equal((await editor.get('/jobs')).status, 403); + assert.equal((await editor.put('/jobs/backup', { enabled: false })).status, 403); + }); + + it('running one now runs it here (no queue in the tests) and remembers the run', async () => { + const h = await site(); + h.ctx.config.databaseUrl = null; + await assert.rejects(runNow(h.ctx, 'backup'), /DATABASE_URL/); + const admin = await h.as('admin'); + const ran = await admin.post('/jobs/youtube/run'); + assert.equal(ran.status, 200, JSON.stringify(ran.body)); + assert.deepEqual(ran.body, { queued: false, output: { added: 0, skipped: 'no source' } }); + }); +}); diff --git a/apps/website/e2e/admin.spec.ts b/apps/website/e2e/admin.spec.ts index fbd14ad..5d8f8d3 100644 --- a/apps/website/e2e/admin.spec.ts +++ b/apps/website/e2e/admin.spec.ts @@ -169,10 +169,10 @@ test("an event added and published shows on the site at once (its own Publish)", }); test("the admin's screens are accessible", async ({ page, context }) => { - // Thirteen screens, each checked by axe. + // Fifteen screens, each checked by axe (1.4.0: Backups and Background jobs). test.setTimeout(240_000); await signIn(context, "owner"); - for (const path of ["/admin", "/admin/template", "/admin/pages", "/admin/ministries", "/admin/leaders", "/admin/messages", "/admin/events", "/admin/linked", "/admin/media", "/admin/publish", "/admin/settings", "/admin/people", "/admin/audit"]) { + for (const path of ["/admin", "/admin/template", "/admin/pages", "/admin/ministries", "/admin/leaders", "/admin/messages", "/admin/events", "/admin/linked", "/admin/media", "/admin/publish", "/admin/settings", "/admin/people", "/admin/audit", "/admin/backups", "/admin/jobs"]) { await page.goto(path); await expect(page.getByRole("heading", { level: 1 })).toBeVisible(); const axe = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]).analyze(); diff --git a/apps/website/frontend/package.json b/apps/website/frontend/package.json index fb0ab80..0bc851e 100644 --- a/apps/website/frontend/package.json +++ b/apps/website/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/website-frontend", - "version": "1.3.0", + "version": "1.4.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/admin/nav.ts b/apps/website/frontend/src/admin/nav.ts index 2f046be..be523cb 100644 --- a/apps/website/frontend/src/admin/nav.ts +++ b/apps/website/frontend/src/admin/nav.ts @@ -1,7 +1,7 @@ /** The admin's sections, in groups (the sidebar) with a line each (the dashboard's tiles). */ import { - Building2, CalendarDays, FileText, HandHeart, Image as ImageIcon, LayoutDashboard, Link2, Mic, Palette, ScrollText, - Send, Settings, UserCog, Users, type LucideIcon, + Building2, CalendarDays, DatabaseBackup, FileText, HandHeart, Image as ImageIcon, LayoutDashboard, Link2, Mic, Palette, ScrollText, + Send, Settings, Timer, UserCog, Users, type LucideIcon, } from "lucide-react"; export type NavItem = { href: string; label: string; description: string; icon: LucideIcon; managers?: boolean }; @@ -41,6 +41,14 @@ export const NAV_GROUPS: { title: string | null; items: NavItem[] }[] = [ { href: "/admin/audit", label: "Audit log", description: "Who changed what, and when", icon: ScrollText, managers: true }, ], }, + { + // 1.4.0, as Accounts and Cross Events. + title: "Looking after it", + items: [ + { href: "/admin/backups", label: "Backups", description: "Copies of your site's database: back up now, download, how many to keep", icon: DatabaseBackup, managers: true }, + { href: "/admin/jobs", label: "Background jobs", description: "What runs on a schedule, and when: switch each on or off", icon: Timer, managers: true }, + ], + }, ]; export const NAV: NavItem[] = NAV_GROUPS.flatMap((g) => g.items); diff --git a/apps/website/frontend/src/app/admin/backups/page.tsx b/apps/website/frontend/src/app/admin/backups/page.tsx new file mode 100644 index 0000000..edeb99a --- /dev/null +++ b/apps/website/frontend/src/app/admin/backups/page.tsx @@ -0,0 +1,87 @@ +"use client"; + +/** + * 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. + */ +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 }; + +const size = (n: number) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${(n / 1024).toFixed(1)} KB` : `${(n / (1024 * 1024)).toFixed(1)} MB`); + +export default function Backups() { + const list = useAdmin("/backups"); + const now = useAction(); + const save = useAction(); + const [nightly, setNightly] = useState(null); + const [retain, setRetain] = useState(null); + if (!list.data) return ; + const d = list.data; + const nightlyOn = nightly ?? d.nightly; + const keep = retain ?? String(d.retain); + + return ( + <> + Backups +
+ + {d.lastError &&
The last backup didn't work: {d.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}` }); + 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 } })); + 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); + list.reload(); + }}> + +
+ + setRetain(e.target.value)} /> + +
+ {save.message && {save.message.text}} + Save +
+
+ + +
+ + + + {d.items.map((b) => ( + + + + + + ))} + {!d.items.length && } + +
MadeSizeDownload
{when(b.createdAt)}{size(b.size)} + + Download the backup made {when(b.createdAt)} + +
No backups yet.
+
+
+
+ + ); +} diff --git a/apps/website/frontend/src/app/admin/jobs/page.tsx b/apps/website/frontend/src/app/admin/jobs/page.tsx new file mode 100644 index 0000000..e7334d4 --- /dev/null +++ b/apps/website/frontend/src/app/admin/jobs/page.tsx @@ -0,0 +1,159 @@ +"use client"; + +/** + * Settings → Background jobs (1.4.0, as Accounts and Cross Events): what the server does on a + * schedule. Switch a job on or off, change when it runs (that choice wins over the server's .env + * and applies straight away), run one now, and see its last runs. Owners and Admins only. + */ +import { useState } from "react"; +import { RefreshCw, Timer } from "lucide-react"; +import { api } from "@/admin/api"; +import { Btn, Loading, Notice, Panel, Title, cx, inputClass, useAction, useAdmin, when } from "@/admin/ui"; + +type JobRun = { state: string; createdOn?: string | null; startedOn: string | null; completedOn: string | null; output: unknown }; +type JobInfo = { + name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; nextRun: string | null; recent: JobRun[]; + envEnabled: boolean; envCron: string; defaultCron: string; override: { enabled: boolean | null; cron: string | null }; +}; +type JobList = { mode: "queue" | "timers" | "off"; timezone: string; jobsEnabledEnv: boolean; jobs: JobInfo[] }; + +const RUN_STATE: Record = { + completed: "bg-green-50 text-green-800", failed: "bg-red-50 text-red-800", active: "bg-blue-50 text-blue-800", + created: "bg-gray-100 text-gray-700", retry: "bg-amber-50 text-amber-900", cancelled: "bg-gray-100 text-gray-700", +}; +const SCHEDULES = [ + { label: "Every 5 minutes", cron: "*/5 * * * *" }, { label: "Every 15 minutes", cron: "*/15 * * * *" }, + { label: "Every hour", cron: "0 * * * *" }, { label: "Daily at 02:20", cron: "20 2 * * *" }, { label: "Daily at 07:00", cron: "0 7 * * *" }, +]; + +function describeCron(cron: string): string { + if (cron === "* * * * *") return "Every minute"; + const m = /^\*\/(\d+) \* \* \* \*$/.exec(cron); + if (m) return `Every ${m[1]} minutes`; + const h = /^(\d+) \* \* \* \*$/.exec(cron); + if (h) return `Every hour at :${h[1]!.padStart(2, "0")}`; + const d = /^(\d+) (\d+) \* \* \*$/.exec(cron); + if (d) return `Daily at ${d[2]!.padStart(2, "0")}:${d[1]!.padStart(2, "0")}`; + return cron; +} + +function runText(r: JobRun): string { + if (r.output === null || r.output === undefined) return ""; + if (r.state === "failed" && typeof r.output === "object" && r.output && "message" in r.output) return String((r.output as { message: unknown }).message); + try { return JSON.stringify(r.output); } catch { return ""; } +} + +/** An on/off switch (role="switch", so screen readers hear on and off). */ +function Toggle({ on, label, disabled, onChange }: { on: boolean; label: string; disabled?: boolean; onChange: (on: boolean) => void }) { + return ( + + ); +} + +export default function Jobs() { + const list = useAdmin("/jobs"); + const act = useAction(); + const [busy, setBusy] = useState(null); + const [open, setOpen] = useState(null); + const [editing, setEditing] = useState<{ name: string; cron: string } | null>(null); + if (!list.data) return ; + const d = list.data; + const off = d.mode === "off"; + + const save = async (job: JobInfo, change: { enabled?: boolean | null; cron?: string | null }, done: string) => { + setBusy(job.name); + const r = await act.run(() => api(`/jobs/${encodeURIComponent(job.name)}`, { method: "PUT", body: change }), done); + setBusy(null); + if (r) setEditing(null); + list.reload(); + }; + const runNow = async (job: JobInfo) => { + setBusy(job.name); + const r = await act.run(() => api<{ queued: boolean }>(`/jobs/${encodeURIComponent(job.name)}/run`, { method: "POST" })); + setBusy(null); + if (r) act.setMessage({ tone: "success", text: r.queued ? `"${job.label}" queued: it starts within a few seconds.` : `"${job.label}" ran.` }); + setTimeout(() => list.reload(), r?.queued ? 4000 : 0); + }; + + return ( + <> + list.reload()}><RefreshCw className="h-4 w-4" aria-hidden /> Refresh</Btn>}>Background jobs + +
+ {off && All background jobs are switched off in the server's settings (JOBS_ENABLED=false), so nothing here runs. Cross Code can change that from the Hub.} + {d.mode === "timers" && The job queue couldn't start, so jobs run on simple timers in this process (history only since the last restart).} + {act.message && {act.message.text}} +
+
    + {d.jobs.map((job) => { + const last = job.recent[0]; + const mine = busy === job.name; + const isEditing = editing?.name === job.name; + return ( +
  • +
    + void save(job, { enabled: on }, `"${job.label}" is ${on ? "on" : "off"}.`)} /> +
    +
    {job.label}
    +
    + {job.enabled ? `${describeCron(job.cron)}${job.nextRun ? ` · next ${when(job.nextRun)}` : ""}` : "Off"} + {job.override.enabled !== null + ? <> · {job.enabled ? "switched on" : "switched off"} here · + : !job.envEnabled && job.envFlag ? ` (${job.envFlag}=false in the server's settings)` : ""} +
    +
    + {last && ( + + )} + setEditing(isEditing ? null : { name: job.name, cron: job.cron })}>Schedule + void runNow(job)}>Run now +
    + + {isEditing && ( +
    { e.preventDefault(); void save(job, { cron: editing.cron }, `"${job.label}": ${describeCron(editing.cron)}.`); }}> + + + Save + {job.override.cron !== null && void save(job, { cron: null }, `"${job.label}" is back on ${describeCron(job.envCron)}.`)}>Back to {describeCron(job.envCron)}} +
    + )} + + {open === job.name && ( + + + + {job.recent.map((r, i) => ( + + + + + + ))} + +
    StartedResultDetails
    {when(r.startedOn ?? r.createdOn ?? null)}{r.state}{runText(r)}
    + )} +
  • + ); + })} +
+
+ + ); +} diff --git a/package-lock.json b/package-lock.json index d05993d..c837d54 100644 --- a/package-lock.json +++ b/package-lock.json @@ -360,15 +360,17 @@ }, "apps/website/backend": { "name": "@crosscode/website-backend", - "version": "1.3.0", + "version": "1.4.0", "hasInstallScript": true, "dependencies": { "@crosscode/auth-client": "*", "@crosscode/contracts": "*", "@prisma/adapter-pg": "^7.10.1", "@prisma/client": "^7.10.1", + "cron-parser": "^5.10.2", "dotenv": "^16.3.1", "express": "^5.3.0", + "pg-boss": "^11.1.2", "sharp": "^0.35.5", "zod": "^4.6.7" }, @@ -387,7 +389,7 @@ }, "apps/website/frontend": { "name": "@crosscode/website-frontend", - "version": "1.3.0", + "version": "1.4.0", "dependencies": { "@crosscode/contracts": "*", "@crosscode/seo": "*",