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
+10 -2
View File
@@ -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);
@@ -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<BackupList>("/backups");
const now = useAction();
const save = useAction();
const [nightly, setNightly] = useState<boolean | null>(null);
const [retain, setRetain] = useState<string | 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);
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>}
{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}` });
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 } }));
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();
}}>
<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>
<div className="max-w-xs">
<Field label="Keep the newest" hint="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>
{save.message && <Notice tone={save.message.tone}>{save.message.text}</Notice>}
<Btn type="submit" busy={save.busy}>Save</Btn>
</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.">
<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>
<tbody className="divide-y divide-gray-200">
{d.items.map((b) => (
<tr key={b.filename}>
<td className="whitespace-nowrap py-2 pr-4">{when(b.createdAt)}</td>
<td className="py-2 pr-4 text-gray-600">{size(b.size)}</td>
<td className="py-2 text-right">
<a href={`/api/v1/admin/backups/${encodeURIComponent(b.filename)}/download`} download className="inline-flex items-center gap-1.5 text-brand-text underline-offset-4 hover:underline">
<Download className="h-3.5 w-3.5" aria-hidden /> Download<span className="sr-only"> the backup made {when(b.createdAt)}</span>
</a>
</td>
</tr>
))}
{!d.items.length && <tr><td colSpan={3} className="py-3 text-gray-600">No backups yet.</td></tr>}
</tbody>
</table>
</div>
</Panel>
</div>
</>
);
}
@@ -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<string, string> = {
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 (
<button type="button" role="switch" aria-checked={on} aria-label={label} disabled={disabled} onClick={() => onChange(!on)}
className={cx("relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 disabled:cursor-not-allowed disabled:opacity-50", on ? "bg-brand" : "bg-gray-400")}>
<span className={cx("inline-block h-5 w-5 rounded-full bg-white shadow transition-transform", on ? "translate-x-5" : "translate-x-0.5")} />
</button>
);
}
export default function Jobs() {
const list = useAdmin<JobList>("/jobs");
const act = useAction();
const [busy, setBusy] = useState<string | null>(null);
const [open, setOpen] = useState<string | null>(null);
const [editing, setEditing] = useState<{ name: string; cron: string } | null>(null);
if (!list.data) return <Loading error={list.error} />;
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 (
<>
<Title icon={Timer} sub="What the server does on a schedule. Your choice here wins over the server's settings and applies straight away."
actions={<Btn onClick={() => list.reload()}><RefreshCw className="h-4 w-4" aria-hidden /> Refresh</Btn>}>Background jobs</Title>
<Panel sub={`Times are ${d.timezone}. Each job runs once per schedule, however many server processes there are.`}>
<div className="space-y-3">
{off && <Notice tone="warning">All background jobs are switched off in the server&apos;s settings (JOBS_ENABLED=false), so nothing here runs. Cross Code can change that from the Hub.</Notice>}
{d.mode === "timers" && <Notice tone="warning">The job queue couldn&apos;t start, so jobs run on simple timers in this process (history only since the last restart).</Notice>}
{act.message && <Notice tone={act.message.tone}>{act.message.text}</Notice>}
</div>
<ul className="mt-3 divide-y divide-gray-200 rounded-lg border border-gray-200">
{d.jobs.map((job) => {
const last = job.recent[0];
const mine = busy === job.name;
const isEditing = editing?.name === job.name;
return (
<li key={job.name} className="p-3">
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<Toggle on={job.enabled} disabled={mine || off} label={`${job.label}: ${job.enabled ? "on" : "off"}`}
onChange={(on) => void save(job, { enabled: on }, `"${job.label}" is ${on ? "on" : "off"}.`)} />
<div className="mr-auto min-w-0">
<div className={cx("text-sm font-medium", job.enabled ? "text-gray-900" : "text-gray-600")}>{job.label}</div>
<div className="text-xs text-gray-600">
{job.enabled ? `${describeCron(job.cron)}${job.nextRun ? ` · next ${when(job.nextRun)}` : ""}` : "Off"}
{job.override.enabled !== null
? <> · {job.enabled ? "switched on" : "switched off"} here · <button type="button" disabled={mine} className="underline hover:text-gray-900" onClick={() => void save(job, { enabled: null }, `"${job.label}" follows the server's settings again.`)}>use the server&apos;s setting ({job.envEnabled ? "on" : "off"})</button></>
: !job.envEnabled && job.envFlag ? ` (${job.envFlag}=false in the server's settings)` : ""}
</div>
</div>
{last && (
<button type="button" onClick={() => setOpen(open === job.name ? null : job.name)} aria-expanded={open === job.name}
className={cx("rounded px-2 py-0.5 text-xs", RUN_STATE[last.state] ?? "bg-gray-100 text-gray-700")}>
Last run: {last.state}{last.completedOn ? `, ${when(last.completedOn)}` : ""}
</button>
)}
<Btn disabled={mine} onClick={() => setEditing(isEditing ? null : { name: job.name, cron: job.cron })}>Schedule</Btn>
<Btn disabled={mine || off} busy={mine} onClick={() => void runNow(job)}>Run now</Btn>
</div>
{isEditing && (
<form className="mt-3 flex flex-wrap items-end gap-2 rounded-lg bg-gray-50 p-3" onSubmit={(e) => { e.preventDefault(); void save(job, { cron: editing.cron }, `"${job.label}": ${describeCron(editing.cron)}.`); }}>
<label className="block">
<span className="block text-xs font-medium text-gray-700">When it runs</span>
<select className={cx(inputClass, "mt-1 w-48")} value={SCHEDULES.some((s) => s.cron === editing.cron) ? editing.cron : ""} onChange={(e) => e.target.value && setEditing({ name: job.name, cron: e.target.value })}>
<option value="">Custom</option>
{SCHEDULES.map((s) => <option key={s.cron} value={s.cron}>{s.label}</option>)}
</select>
</label>
<label className="block">
<span className="block text-xs font-medium text-gray-700">Cron (minute hour day month weekday)</span>
<input className={cx(inputClass, "mt-1 w-48 font-mono")} value={editing.cron} onChange={(e) => setEditing({ name: job.name, cron: e.target.value })} />
</label>
<Btn type="submit" kind="primary" busy={mine}>Save</Btn>
{job.override.cron !== null && <Btn kind="link" disabled={mine} onClick={() => void save(job, { cron: null }, `"${job.label}" is back on ${describeCron(job.envCron)}.`)}>Back to {describeCron(job.envCron)}</Btn>}
</form>
)}
{open === job.name && (
<table className="mt-3 w-full text-left text-xs">
<thead className="text-gray-600"><tr><th className="py-1 pr-3 font-medium">Started</th><th className="py-1 pr-3 font-medium">Result</th><th className="py-1 font-medium">Details</th></tr></thead>
<tbody className="divide-y divide-gray-100">
{job.recent.map((r, i) => (
<tr key={i}>
<td className="whitespace-nowrap py-1 pr-3">{when(r.startedOn ?? r.createdOn ?? null)}</td>
<td className="py-1 pr-3"><span className={cx("rounded px-1.5 py-0.5", RUN_STATE[r.state] ?? "bg-gray-100 text-gray-700")}>{r.state}</span></td>
<td className="break-all py-1 font-mono text-gray-700">{runText(r)}</td>
</tr>
))}
</tbody>
</table>
)}
</li>
);
})}
</ul>
</Panel>
</>
);
}