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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:47:30 +02:00

176 lines
9.1 KiB
TypeScript

// 1.4.0: database backups (Settings → Backups) and the background jobs (Settings → Background
// jobs), as Accounts and Cross Events; the heartbeat reports both to the Hub.
import { after, describe, it } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Readable } from 'node:stream';
import zlib from 'node:zlib';
import request from 'supertest';
import { BACKUP_FILE, backupName, backupPath, listBackups, runBackup, runBackupJob, type Dumper } from '../src/backups/backups.js';
import { health } from '../src/hub/client.js';
import { JOBS, cronFor, isEnabled, jobsHealth, runNow, useEnvForTest } from '../src/jobs.js';
import { hashToken } from '../src/lib/crypto.js';
import { harness, SITE } from './support/harness.js';
type Role = 'owner' | 'admin' | 'editor';
const dumpOf = (sql: string): Dumper => () => ({ stdout: Readable.from([sql]), done: Promise.resolve() });
const failing: Dumper = () => ({ stdout: Readable.from(['-- half a dump']), done: Promise.reject(new Error('pg_dump stopped (exit 1): connection refused')) });
after(() => useEnvForTest(process.env));
async function site() {
const h = await harness({ linked: false });
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ccw-backups-'));
h.ctx.config.backupDir = dir;
h.ctx.config.databaseUrl = 'postgresql://test@127.0.0.1/website_test';
const as = async (role: Role) => {
const id = `00000000-0000-4000-8000-00000000000${['owner', 'admin', 'editor'].indexOf(role) + 1}`;
await h.db.websiteUser.create({ data: { id, name: `Sam the ${role}`, email: `${role}@hope.test`, role } });
await h.db.session.create({ data: { tokenHash: hashToken(`token-${role}`), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
const cookie = `ccw_session=token-${role}`;
return {
get: (p: string) => request(h.app).get(`/api/v1/admin${p}`).set('Cookie', cookie),
put: (p: string, body: object) => request(h.app).put(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body),
post: (p: string, body: object = {}) => request(h.app).post(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body),
};
};
return { ...h, dir, as };
}
describe('backups (1.4.0)', () => {
it('a backup is the gzipped dump, named as the crosscode script names them', async () => {
const h = await site();
const b = await runBackup(h.ctx, dumpOf('CREATE TABLE "Page" ();\n'));
assert.match(b.filename, BACKUP_FILE);
assert.equal(zlib.gunzipSync(fs.readFileSync(path.join(h.dir, b.filename))).toString(), 'CREATE TABLE "Page" ();\n');
assert.equal(backupName(new Date(2026, 10, 27, 2, 20, 5)), 'website-20261127-022005.sql.gz');
const again = await runBackup(h.ctx, dumpOf('-- again\n'));
assert.notEqual(again.filename, b.filename, 'a second one in the same second gets its own name');
});
it('a dump that fails part-way leaves no file, and says why', async () => {
const h = await site();
await assert.rejects(runBackup(h.ctx, failing), /connection refused/);
assert.equal((await listBackups(h.ctx)).length, 0);
assert.match(String(await h.ctx.settings.get('backup_last_error')), /connection refused/);
await runBackup(h.ctx, dumpOf('-- fine\n'));
assert.equal(await h.ctx.settings.get('backup_last_error'), null);
});
it('only the newest are kept; a download only by a backup\'s own name', async () => {
const h = await site();
await h.ctx.settings.set('backup_retain_count', '2');
for (const n of [1, 2, 3]) await runBackup(h.ctx, dumpOf(`-- ${n}\n`));
const left = await listBackups(h.ctx);
assert.equal(left.length, 2);
assert.ok(backupPath(h.ctx, left[0]!.filename));
assert.equal(backupPath(h.ctx, '../.env'), null);
assert.equal(backupPath(h.ctx, 'accounts-20200101-000000.sql.gz'), null);
});
it('the nightly backup is skipped while it\'s turned off', async () => {
const h = await site();
await h.ctx.settings.set('backup_nightly', 'false');
assert.deepEqual(await runBackupJob(h.ctx), { skipped: true });
});
it('admins see, change and download them; editors can\'t', async () => {
const h = await site();
await runBackup(h.ctx, dumpOf('-- a backup\n'));
const editor = await h.as('editor');
assert.equal((await editor.get('/backups')).status, 403);
assert.equal((await editor.post('/backups/run')).status, 403);
assert.equal((await editor.get('/pages')).status, 200, 'the admin-only routes don\'t stop the others');
const admin = await h.as('admin');
const list = await admin.get('/backups');
assert.equal(list.status, 200, JSON.stringify(list.body));
assert.equal(list.body.nightly, true);
assert.equal(list.body.retain, 14);
const file = await admin.get(`/backups/${list.body.items[0].filename}/download`).buffer(true).parse((res, cb) => {
const chunks: Buffer[] = [];
res.on('data', (c: Buffer) => chunks.push(c));
res.on('end', () => cb(null, Buffer.concat(chunks)));
});
assert.equal(file.status, 200);
assert.equal(file.headers['cache-control'], 'no-store');
assert.equal(zlib.gunzipSync(file.body as Buffer).toString(), '-- a backup\n');
assert.equal((await admin.get('/backups/nope.sql.gz/download')).status, 404);
assert.equal(await h.db.auditLog.count({ where: { action: 'backup_downloaded' } }), 1);
assert.equal((await admin.put('/backups/settings', { retain: 0, nightly: true })).status, 400);
const saved = await admin.put('/backups/settings', { retain: 30, nightly: false });
assert.deepEqual(saved.body, { retain: 30, nightly: false, deleted: 0 });
assert.equal(await h.ctx.settings.bool('backup_nightly', true), false);
});
it('the heartbeat reports the newest backup and the real job mode (before: null, so the Hub warned)', async () => {
const h = await site();
assert.equal((await health(h.ctx)).lastBackupAt, null);
await runBackup(h.ctx, dumpOf('-- x\n'));
const report = await health(h.ctx);
assert.ok(report.lastBackupAt && Date.parse(report.lastBackupAt) > Date.now() - 60e3);
assert.deepEqual(report.jobs, await jobsHealth(h.ctx));
assert.equal(report.jobs.mode, 'off', 'no job system started in the tests');
});
});
describe('background jobs (1.4.0)', () => {
const backup = JOBS.find((j) => j.name === 'backup')!;
it('the heartbeat, the event feed, YouTube and the backup are jobs', () => {
assert.deepEqual(JOBS.map((j) => j.name).sort(), ['backup', 'event-feed', 'hub-heartbeat', 'youtube']);
});
it('the .env flag and schedule apply until an admin chooses; their choice wins; null goes back', async () => {
const h = await site();
useEnvForTest({ BACKUP_ENABLED: 'false', JOB_SCHEDULE_BACKUP: '30 1 * * *' });
h.ctx.config.jobsEnabled = true; // nothing is started here either way
const admin = await h.as('admin');
type Row = { name: string; enabled: boolean; envEnabled: boolean; cron: string; override: { enabled: boolean | null; cron: string | null } };
let job = ((await admin.get('/jobs')).body.jobs as Row[]).find((j) => j.name === 'backup')!;
assert.equal(job.enabled, false);
assert.equal(job.cron, '30 1 * * *');
assert.deepEqual(job.override, { enabled: null, cron: null });
const on = await admin.put('/jobs/backup', { enabled: true, cron: '0 3 * * *' });
assert.equal(on.status, 200, JSON.stringify(on.body));
assert.deepEqual(on.body.override, { enabled: true, cron: '0 3 * * *' });
assert.equal(isEnabled(h.ctx, backup), true);
assert.equal(cronFor(h.ctx, backup), '0 3 * * *');
job = ((await admin.get('/jobs')).body.jobs as Row[]).find((j) => j.name === 'backup')!;
assert.equal(job.enabled, true);
assert.equal(job.envEnabled, false);
const back = await admin.put('/jobs/backup', { enabled: null, cron: null });
assert.deepEqual(back.body.override, { enabled: null, cron: null });
assert.equal(isEnabled(h.ctx, backup), false);
assert.equal(await h.db.auditLog.count({ where: { action: 'job_settings_changed' } }), 2);
useEnvForTest(process.env);
});
it('a bad schedule, a bad switch and an unknown job are refused; editors can\'t change jobs', async () => {
const h = await site();
const admin = await h.as('admin');
assert.equal((await admin.put('/jobs/backup', { cron: 'every night' })).status, 400);
assert.equal((await admin.put('/jobs/backup', { enabled: 'yes' })).status, 400);
assert.equal((await admin.put('/jobs/nope', { enabled: true })).status, 404);
const editor = await h.as('editor');
assert.equal((await editor.get('/jobs')).status, 403);
assert.equal((await editor.put('/jobs/backup', { enabled: false })).status, 403);
});
it('running one now runs it here (no queue in the tests) and remembers the run', async () => {
const h = await site();
h.ctx.config.databaseUrl = null;
await assert.rejects(runNow(h.ctx, 'backup'), /DATABASE_URL/);
const admin = await h.as('admin');
const ran = await admin.post('/jobs/youtube/run');
assert.equal(ran.status, 200, JSON.stringify(ran.body));
assert.deepEqual(ran.body, { queued: false, output: { added: 0, skipped: 'no source' } });
});
});