app: backups of the database and the uploaded images (APP-1.0-PLAN §10)
As the Website's: a gzipped pg_dump into backend/backups every night (02:40, after Accounts' and the Website's) and on Back up now, named as the crosscode script names them (app-YYYYMMDD-HHMMSS.sql.gz); a failed dump leaves no file; the newest kept (14 by default). After each, a snapshot of backend/uploads, hard-linking what hasn't changed. Settings → Backups lists both, backs up now, downloads (audited) and sets how many to keep and what's nightly; Owner and Church admin only. The heartbeat reports the newest backup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Settings → Backups (APP-1.0-PLAN §10, as Accounts', Events' and the Website's): the database
|
||||
* backups and the snapshots of the uploaded images, Back up now, how many are kept, nightly on or
|
||||
* off, and a download. Owner and Church admin only: a backup holds every prayer request.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import express, { type RequestHandler } from 'express';
|
||||
import type { Ctx } from '../context.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, clientIp } from '../lib/audit.js';
|
||||
|
||||
export function backupsRouter(ctx: Ctx, full: RequestHandler) {
|
||||
const r = express.Router();
|
||||
const actor = (req: express.Request) => ({ actorId: req.signed!.member.id, actorRole: req.signed!.member.roles.join(','), ip: clientIp(req) });
|
||||
|
||||
r.get('/backups', full, 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'),
|
||||
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', full, 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;
|
||||
}
|
||||
}
|
||||
await audit(ctx, { ...actor(req), 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', full, 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));
|
||||
await audit(ctx, { ...actor(req), 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 every prayer request and member: audited, never cached.
|
||||
r.get('/backups/:file/download', full, 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.');
|
||||
await audit(ctx, { ...actor(req), 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);
|
||||
}
|
||||
});
|
||||
return r;
|
||||
}
|
||||
@@ -13,6 +13,7 @@
|
||||
* GET /jobs, PUT /jobs/:name { enabled?, cron? }, POST /jobs/:name/run Background jobs
|
||||
* GET /audit?before= the audit log; GET /access?before= the access log
|
||||
* GET /share, POST /share the App's link (and the poster), and "shared" for the checklist
|
||||
* GET /backups, POST /backups/run, PUT /backups/settings, GET /backups/:file/download Backups
|
||||
* GET /media, POST /media?alt= (the image's bytes), DELETE /media/:id uploaded images (anyone who
|
||||
* writes content: Content admin, Devotional writer, Prayer coordinator)
|
||||
*/
|
||||
@@ -33,6 +34,7 @@ import { wallDay } from '../prayer/service.js';
|
||||
import { wallSettings } from '../prayer/wall.js';
|
||||
import { accessLogList, auditLog } from './logs.js';
|
||||
import { addMember, listMembers, setRoles } from './members.js';
|
||||
import { backupsRouter } from './backups.js';
|
||||
import { deleteMedia, listMedia, MAX_UPLOAD_BYTES, upload } from '../media/media.js';
|
||||
|
||||
const modulesBody = z.object(Object.fromEntries(APP_MODULES.map((m) => [m, z.boolean().optional()]))).strict();
|
||||
@@ -159,6 +161,8 @@ export function adminRouter(ctx: Ctx) {
|
||||
r.get('/audit', full, handle(async (req) => ({ entries: await auditLog(ctx, { before: before(req) }) })));
|
||||
r.get('/access', full, handle(async (req) => ({ entries: await accessLogList(ctx, { before: before(req) }) })));
|
||||
|
||||
r.use(backupsRouter(ctx, full));
|
||||
|
||||
// ─── Uploaded images ───
|
||||
const writers = requireRole(ctx, ['content_admin', 'devotional_writer', 'prayer_coordinator']);
|
||||
r.get('/media', writers, handle(() => listMedia(ctx)));
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* Database backups (APP-1.0-PLAN §10, as Accounts', Cross Events' and the Website's Settings → Backups): a gzipped
|
||||
* `pg_dump` into backend/backups/ every night (02:40, after Accounts' at 02:00 and the Website's at 02:20) and whenever an
|
||||
* admin asks, kept on this server only. The `crosscode` script makes the same files before every
|
||||
* deploy and uninstall (scripts/products/app.sh), so the admin's list shows both, newest first.
|
||||
* The database only: the uploaded images (backend/uploads) are snapshotted next to it (uploads.ts).
|
||||
*
|
||||
* 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: app-YYYYMMDD-HHMMSS.sql.gz. */
|
||||
export const BACKUP_FILE = /^app-\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');
|
||||
/** app-20261201-020000.sql.gz in the server's local time, as the crosscode script names them. */
|
||||
export function backupName(at: Date): string {
|
||||
return `app-${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 (APP-1.0-PLAN §10, as the Website's): the images uploaded in the admin, 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. 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 '../media/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, 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 uploaded images: ${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: 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 } };
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import { hubPublicKey, verifyToken } from './licence.js';
|
||||
import { prayerStats } from '../prayer/service.js';
|
||||
import { announcementsLast30d } from '../content/announcements.js';
|
||||
import { messagesLast30d } from '../messaging/send.js';
|
||||
import { lastBackupAt } from '../backups/backups.js';
|
||||
import { jobsHealth } from '../jobs.js';
|
||||
|
||||
export const PROTOCOL_VERSION = 2;
|
||||
@@ -68,8 +69,8 @@ export async function health(ctx: Ctx) {
|
||||
uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000),
|
||||
db: await dbUp(ctx),
|
||||
jobs: await jobsHealth(ctx),
|
||||
// The nightly backup comes with the App's backups (as the Website's, before 1.0.0).
|
||||
lastBackupAt: null,
|
||||
// The newest backup, the nightly one or one the crosscode script made (backups/backups.ts).
|
||||
lastBackupAt: (await lastBackupAt(ctx).catch(() => null))?.toISOString() ?? null,
|
||||
disk: null,
|
||||
errorsLast24h: null,
|
||||
pendingMigrations: 0,
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
* The Hub heartbeat, the event feed, Cross Code's devotionals (the next 2 weeks, today included, once
|
||||
* a night, §6), the House of Prayer's reminders and renewal notices (prayer/jobs.ts), tidying prayer
|
||||
* requests, and email and WhatsApp (§8, messaging/send.ts): sending what's queued, and queuing
|
||||
* announcements and the day's devotional. The nightly backup comes with the admin (§10).
|
||||
* announcements and the day's devotional; and the nightly backup of the database and the uploaded
|
||||
* images (§10, backups/).
|
||||
*
|
||||
* Settings → Background jobs (§10) 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
|
||||
@@ -23,6 +24,7 @@ import { nightlySync } from './content/devotionals.js';
|
||||
import { syncAll } from './events/feed.js';
|
||||
import { DELETE_AFTER_CLOSED_DAYS } from './requests/settings.js';
|
||||
import { queueAnnouncements, queueDevotionals, sendOutbox } from './messaging/send.js';
|
||||
import { runNightlyBackups } from './backups/uploads.js';
|
||||
|
||||
export type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise<unknown> };
|
||||
|
||||
@@ -35,6 +37,8 @@ export const JOBS: Job[] = [
|
||||
{ name: 'messages-send', label: 'Email and WhatsApp: send what\'s queued (reminders, notices, announcements, devotionals)', cron: '* * * * *', env: 'MESSAGES_ENABLED', run: (ctx) => sendOutbox(ctx) },
|
||||
{ name: 'announcement-sends', label: 'Announcements: queue "Also send it" at the publish time', cron: '* * * * *', env: null, run: (ctx) => queueAnnouncements(ctx) },
|
||||
{ name: 'devotional-sends', label: 'Today\'s devotional: queue it at each member\'s time', cron: '*/5 * * * *', env: null, run: (ctx) => queueDevotionals(ctx) },
|
||||
// After Accounts' (02:00) and the Website's (02:20) on the same server.
|
||||
{ name: 'backup', label: 'Backup: the database, and the uploaded images', cron: '40 2 * * *', env: 'BACKUP_ENABLED', run: (ctx) => runNightlyBackups(ctx) },
|
||||
{ name: 'prayer-renewals', label: 'House of Prayer: renewal notices (14 and 3 days before the end)', cron: '0 9 * * *', env: 'PRAYER_RENEWALS_ENABLED', run: (ctx) => sendRenewalNotices(ctx) },
|
||||
];
|
||||
|
||||
|
||||
Reference in New Issue
Block a user