Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22d7e54008 | ||
|
|
8c213d6d84 | ||
|
|
48abc06db7 | ||
|
|
da283f3cbb | ||
|
|
2a4cf7acab | ||
|
|
a3ac3da5a5 | ||
|
|
8e52bd2d33 | ||
|
|
7b49ec2b70 |
@@ -2,6 +2,31 @@
|
||||
|
||||
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.
|
||||
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
|
||||
|
||||
@@ -1,5 +1,67 @@
|
||||
# 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
|
||||
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_<NAME>`.
|
||||
- **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).
|
||||
|
||||
@@ -3,6 +3,20 @@
|
||||
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
|
||||
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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/website-backend",
|
||||
"version": "1.3.0",
|
||||
"version": "1.5.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"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* 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 { 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';
|
||||
|
||||
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'),
|
||||
// 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) => {
|
||||
let b;
|
||||
try {
|
||||
b = await runBackup(ctx);
|
||||
} 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, 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;
|
||||
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, uploads: uploadsOn, deleted } });
|
||||
return { retain, nightly, uploads: uploadsOn, 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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* 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<void> };
|
||||
|
||||
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<void>((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<number> {
|
||||
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<Backup[]> {
|
||||
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<Date | null> {
|
||||
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<number> {
|
||||
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.
|
||||
*/
|
||||
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.');
|
||||
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 };
|
||||
}
|
||||
@@ -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 } };
|
||||
}
|
||||
@@ -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); };
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
/**
|
||||
* 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_<NAME>) 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 { runNightlyBackups } from './backups/uploads.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<unknown> };
|
||||
|
||||
export const JOBS: Job[] = [
|
||||
// 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) },
|
||||
{ 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<string, NodeJS.Timeout>;
|
||||
history: Map<string, Run[]>;
|
||||
overrides: Record<string, Override>;
|
||||
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<Record<string, Override>> {
|
||||
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_<NAME>, 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<void>> {
|
||||
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<string, Run[]>();
|
||||
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 };
|
||||
}
|
||||
@@ -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<string, string | undefined> = 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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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); };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
// 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, 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';
|
||||
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); useDumperForTest(null); });
|
||||
|
||||
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, uploads: true, 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' } });
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/website-frontend",
|
||||
"version": "1.3.0",
|
||||
"version": "1.5.0",
|
||||
"private": true,
|
||||
"description": "Church Website: the church's public site in its template, and the admin",
|
||||
"scripts": {
|
||||
|
||||
@@ -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,122 @@
|
||||
"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. 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 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`);
|
||||
|
||||
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);
|
||||
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="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'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'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; 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, 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's new is copied.</span></span>
|
||||
</label>
|
||||
<div className="max-w-xs">
|
||||
<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>
|
||||
{save.message && <Notice tone={save.message.tone}>{save.message.text}</Notice>}
|
||||
<Btn type="submit" busy={save.busy}>Save</Btn>
|
||||
</form>
|
||||
</Panel>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
|
||||
<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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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'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'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'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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+24
-6
@@ -11,13 +11,13 @@ 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.2.0** | `website@1.2.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.5.0** | `agent@1.5.0` | 2026-11-23 |
|
||||
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.18.0** | `contracts@1.18.0` | 2026-11-25 |
|
||||
| Cross Code Hub | `events-hub` | **2.24.1** | `v2.24.1` | 2026-11-27 |
|
||||
| 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 |
|
||||
| Cross Code Hub | `events-hub` | **2.25.0** | `v2.25.0` | 2026-11-27 |
|
||||
| crosscode.co.za | `crosscode-site` | **1.7.0** | `v1.7.0` | 2026-11-26 |
|
||||
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-23 (last change: uninstall, export and purge one product of a church) |
|
||||
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-27 (last change: `crosscode demo <church> website`) |
|
||||
|
||||
The `crosscode` script has no version: every server's copy (`/opt/crosscode/tools`) pulls `main`
|
||||
on each run, so merging to `main` and pushing releases it. Its changes are listed in
|
||||
@@ -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.2.0 (1.0.0–1.1.0 released 2026-11-26, 1.2.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,24 @@ 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
|
||||
off and locked, no invoice drafted, sent or made by hand). Any install can be marked as a demo
|
||||
site; Events and the Website have demo data. One migration (`Customer.isDemo`, `demoSince`).
|
||||
Website: eight demo churches, two per template, that replace the content only (the church's
|
||||
profile from Accounts, the site settings, the site icon and the admins stay). Agent and script:
|
||||
`crosscode demo <church> website --profile <p>`. No migrations outside the Hub. Checked:
|
||||
contracts (271), agent (58), the Website's backend tests (115) and build, the script's bats
|
||||
tests (107), the Hub's backend tests (283), frontend typecheck and lint. **Not deployed yet**:
|
||||
the Hub needs `prisma migrate deploy`; demo sites need agent 1.6.0 and Website 1.3.0.
|
||||
- **Hub 2.24.1 (2026-11-27):** Servers → Updates offers every product. Its tabs were a fixed list of
|
||||
Cross Events and Accounts from before the Church Website, so Website installs couldn't be updated
|
||||
in a batch there; now Events, Accounts, the Church Website, and the App once it has an install.
|
||||
|
||||
Generated
+4
-2
@@ -360,15 +360,17 @@
|
||||
},
|
||||
"apps/website/backend": {
|
||||
"name": "@crosscode/website-backend",
|
||||
"version": "1.3.0",
|
||||
"version": "1.5.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.5.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/seo": "*",
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user