Hub 2.24.0: update everything at a church to latest

A customer's Sites card has "Update everything to latest": every product
that's behind, in one batch (Accounts first, one at a time, stopping at the
first failure), scheduled or as an emergency, planned whole or not at all.
Later products keep Accounts at the version the batch updates it to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 08:20:21 +02:00
co-authored by Claude Opus 5.5
parent 6ccf492810
commit 2f2e7138ba
11 changed files with 314 additions and 19 deletions
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-backend",
"version": "2.23.1",
"version": "2.24.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-backend",
"version": "2.23.1",
"version": "2.24.0",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-backend",
"version": "2.23.1",
"version": "2.24.0",
"private": true,
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
"main": "src/index.js",
+11
View File
@@ -293,6 +293,17 @@ router.post('/updates', wrap(async (req, res) => {
res.status(201).json(out);
}));
// Hub 2.24.0: a whole church (customer) to the latest release of each product, in one batch.
router.get('/customers/:id/update-plan', wrap(async (req, res) => {
res.json({ products: await jobs.churchUpdatePlan(req.params.id) });
}));
router.post('/customers/:id/update-all', wrap(async (req, res) => {
const out = await jobs.scheduleChurchUpdate(req.params.id, req.body || {}, req.admin);
await audit(req, req.body?.emergency ? 'emergency_church_update_scheduled' : 'church_update_scheduled', out.batchId, { customerId: req.params.id, updates: out.updates, at: req.body?.asap ? 'as soon as possible' : req.body?.at, reason: req.body?.reason || null, ...(req.body?.confirmLive ? { duringLiveEvent: true } : {}) });
res.status(201).json(out);
}));
// ─── Jobs ─────────────────────────────────────────────────────────────────────
// Hub 2.6.0: paged (?page, ?pageSize), with filters for every status (succeeded too), a job type,
+89 -8
View File
@@ -1139,8 +1139,10 @@ function scheduleWarnings(at, deployment) {
* - otherwise: the version it runs, so it isn't changed
* Returns { version: 'accounts@x' | null, install: { domain, release } | null, note }.
*/
async function accountsPlan(d, release, accountsRelease) {
async function accountsPlan(d, release, accountsRelease, upcomingAccounts = null) {
if (d.product === 'accounts') return { version: null, install: null, note: null };
// Hub 2.24.0: Accounts is updated earlier in the same church update, so this deploy keeps it there.
if (upcomingAccounts) return { version: `accounts@${upcomingAccounts}`, install: null, note: null };
const acc = await prisma.deployment.findFirst({ where: { shortName: d.shortName, product: 'accounts', status: { notIn: ['removed', 'failed'] } }, include: { install: true } });
const running = acc ? (acc.install?.version || acc.version || null) : null;
const releases = await prisma.release.findMany({ where: { product: d.product } });
@@ -1172,7 +1174,15 @@ async function liveAt(d, now = new Date()) {
return { eventsNow: Number(live.eventsNow) || 0, checkInsLastHour: Number(live.checkInsLastHour) || 0 };
}
async function scheduleUpdate({ deploymentIds, product: wanted = null, version, at, emergency = false, asap = false, confirmLive = false, reason = null, totp = null }, admin, now = new Date()) {
/**
* `opts` (Hub 2.24.0, never from a request): for a whole church's update (scheduleChurchUpdate).
* upcoming { product: version } updated earlier in the same batch: their requirements count as met
* batch { id, order } shared by every product's jobs; only the batch's first job is queued
* dryRun every check, nothing made
* totpChecked the two-factor code was checked once already
*/
async function scheduleUpdate({ deploymentIds, product: wanted = null, version, at, emergency = false, asap = false, confirmLive = false, reason = null, totp = null }, admin, now = new Date(), opts = {}) {
const upcoming = opts.upcoming || {};
// Hub 2.7.0: an emergency update can run as soon as possible (the agent's next poll, within a
// minute) instead of at a time at least 15 minutes away (decision 30, changed 2026-11-19).
if (asap && !emergency) throw fail(400, 'BAD_REQUEST', 'Only an emergency update runs as soon as possible.');
@@ -1180,7 +1190,7 @@ async function scheduleUpdate({ deploymentIds, product: wanted = null, version,
if (Number.isNaN(when.getTime())) throw fail(400, 'BAD_REQUEST', 'Pick a time.');
if (emergency) {
if (!reason || !String(reason).trim()) throw fail(400, 'BAD_REQUEST', 'An emergency update needs a reason (it goes in the email and banner).');
requireTotp(admin, totp);
if (!opts.totpChecked) requireTotp(admin, totp);
if (!asap && when - now < EMERGENCY_MIN_MINUTES * MIN) throw fail(400, 'TOO_SOON', `An emergency update at a time needs at least ${EMERGENCY_MIN_MINUTES} minutes' notice (or choose as soon as possible).`);
} else if (when - now < SCHEDULE_MIN_HOURS * HOUR) {
throw fail(400, 'TOO_SOON', `Updates are planned at least ${SCHEDULE_MIN_HOURS} hours ahead (or as an emergency update).`);
@@ -1222,7 +1232,8 @@ async function scheduleUpdate({ deploymentIds, product: wanted = null, version,
if (d.server.removedAt) throw fail(409, 'SERVER_REMOVED', `${d.shortName}'s server was removed.`);
if (d.install) {
// Accounts is handled below (kept, updated, or installed first); anything else must be met.
const unmet = (await unmetRequirementsFor(d.install, release.version)).filter(u => u.product !== 'accounts');
const unmet = (await unmetRequirementsFor(d.install, release.version))
.filter(u => u.product !== 'accounts' && !(upcoming[u.product] && compareVersions(upcoming[u.product], u.version) >= 0));
if (unmet.length) throw fail(409, 'REQUIREMENT_NOT_MET', `${d.shortName}: ${release.version} needs ${unmet.map(u => `${u.product} ${u.version}`).join(', ')} first.`);
}
const missing = await missingFor(product, release.version, servers.serverConfig(d.server), await servers.installDefaults());
@@ -1230,19 +1241,23 @@ async function scheduleUpdate({ deploymentIds, product: wanted = null, version,
const invalid = invalidFor(servers.serverConfig(d.server), await servers.installDefaults());
if (invalid.length) throw fail(409, 'CONFIG_INVALID', `${d.shortName}: fix ${d.server.name}'s configuration first. ${invalid.join(' ')}`);
warnings.push(...scheduleWarnings(when, d));
const plan = await accountsPlan(d, release, accountsRelease);
const plan = await accountsPlan(d, release, accountsRelease, upcoming.accounts || null);
if (plan.install) await preflight(d.server, 'accounts', plan.install.release.version, now);
if (plan.note) warnings.push(plan.note);
plans.set(d.id, plan);
}
if (opts.dryRun) return { jobs: [], batchId: null, warnings: [...new Set(warnings)] };
const installsFirst = [...plans.values()].filter(p => p.install).length;
const batchId = deployments.length + installsFirst > 1 ? servers.newId('batch') : null;
const batchId = opts.batch ? opts.batch.id : deployments.length + installsFirst > 1 ? servers.newId('batch') : null;
const name = PRODUCT_NAMES[product];
const jobs = [];
let order = 0;
for (const d of deployments) {
const plan = plans.get(d.id);
const next = () => ({ batchId, batchOrder: batchId ? order : null, status: !batchId || order++ === 0 ? 'queued' : 'scheduled' });
const next = () => {
if (opts.batch) { const o = opts.batch.order++; return { batchId, batchOrder: o, status: o === 0 ? 'queued' : 'scheduled' }; }
return { batchId, batchOrder: batchId ? order : null, status: !batchId || order++ === 0 ? 'queued' : 'scheduled' };
};
if (plan.install) {
// The church's Accounts, installed just before its update (a licence, ports, an add-product job).
const acc = await prisma.$transaction(async tx => {
@@ -1287,6 +1302,72 @@ async function scheduleUpdate({ deploymentIds, product: wanted = null, version,
return { jobs, batchId, warnings: [...new Set(warnings)] };
}
/**
* Hub 2.24.0: a church's products and their latest releases, for "Update everything to latest".
* In update order (Accounts first: the others sign in through it). `behind`: a newer release
* exists; `ready`: it's behind, live, and has no update planned or running (else `why` says).
*/
async function churchUpdatePlan(customerId) {
const deployments = await prisma.deployment.findMany({ where: { customerId, status: { notIn: ['removed', 'failed'] } }, include: { install: true } });
deployments.sort((a, b) => PRODUCT_ORDER.indexOf(a.product) - PRODUCT_ORDER.indexOf(b.product) || a.domain.localeCompare(b.domain));
const latest = {};
const out = [];
for (const d of deployments) {
if (!(d.product in latest)) {
const releases = await prisma.release.findMany({ where: { product: d.product } });
latest[d.product] = releases.sort((a, b) => compareVersions(b.version, a.version))[0]?.version || null;
}
const to = latest[d.product];
const current = d.install?.version || d.version || null;
const pending = await prisma.job.findFirst({ where: { deploymentId: d.id, type: 'deploy', status: { in: ['scheduled', 'queued', 'delivered'] } } });
const behind = !!to && (!current || compareVersions(current, to) < 0);
let why = null;
if (!behind) why = to ? 'On the latest release.' : 'No releases yet.';
else if (d.status !== 'live') why = `Not live (${d.status}).`;
else if (pending) why = pending.status === 'delivered' ? 'An update is running.' : `An update is planned for ${sast(pending.notBefore)}.`;
out.push({ id: d.id, product: d.product, shortName: d.shortName, domain: d.domain, status: d.status, current, latest: to, behind, ready: behind && !why, why });
}
return out;
}
/**
* Hub 2.24.0: every product of a church that's behind, to its latest release, in one batch: one
* at a time from `at` (or as soon as possible for an emergency), Accounts first, stopping at the
* first failure. Each product is checked as its own update would be, all before anything is made,
* so it's planned whole or not at all. Each site gets its email and banner as for its own update.
*/
async function scheduleChurchUpdate(customerId, { at, emergency = false, asap = false, confirmLive = false, reason = null, totp = null }, admin, now = new Date()) {
const plan = await churchUpdatePlan(customerId);
if (!plan.length) throw fail(404, 'NOT_FOUND', 'This customer has nothing installed.');
const blocked = plan.filter(p => p.behind && !p.ready);
if (blocked.length) throw fail(409, 'NOT_READY', blocked.map(p => `${PRODUCT_NAMES[p.product]} (${p.domain}): ${p.why}`).join(' '));
const todo = plan.filter(p => p.ready);
if (!todo.length) throw fail(409, 'UP_TO_DATE', 'Everything at this church is on its latest release already.');
// Checked once here (the per-product checks below are told it was); the reason first, as scheduleUpdate does.
if (emergency) {
if (!reason || !String(reason).trim()) throw fail(400, 'BAD_REQUEST', 'An emergency update needs a reason (it goes in the email and banner).');
requireTotp(admin, totp);
}
const input = p => ({ deploymentIds: [p.id], product: p.product, version: p.latest, at, emergency, asap, confirmLive, reason });
// Every product checked in update order, each counting the ones before it as done.
const upcoming = {};
for (const p of todo) {
await scheduleUpdate(input(p), admin, now, { upcoming: { ...upcoming }, dryRun: true, totpChecked: true });
upcoming[p.product] = p.latest;
}
const batch = { id: servers.newId('batch'), order: 0 };
const made = [];
const warnings = [];
const done = {};
for (const p of todo) {
const r = await scheduleUpdate(input(p), admin, now, { upcoming: { ...done }, batch, totpChecked: true });
made.push(...r.jobs);
warnings.push(...r.warnings);
done[p.product] = p.latest;
}
return { jobs: made, batchId: batch.id, warnings: [...new Set(warnings)], updates: todo.map(p => ({ product: p.product, domain: p.domain, from: p.current, to: p.latest })) };
}
/** Cancel a job that hasn't been handed out yet; the church is told and the banner ends. */
async function cancelJob(jobId, admin, now = new Date()) {
const job = await prisma.job.findUnique({ where: { id: jobId }, include: { deployment: { include: { install: true } } } });
@@ -1684,7 +1765,7 @@ async function setEnv(deploymentId, { file, set, unset, restart }, admin, now =
module.exports = {
readEnv, setEnv, envState, readFrp, writeFrp, listFrpcTunnels, portsProbed, probeServers, PROBE_SPARE,
WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES, setDemo, seedDemo,
WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES, setDemo, seedDemo, churchUpdatePlan, scheduleChurchUpdate,
makeJob, signedJob, jobConfig, poll, receiveReport, finish, tick, advanceBatch,
JOB_STATUSES, linkFromStatus, listWhere, lookForUnlinked, newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, neverInstalled, removeFailedInstall, staleness, forgetStale, uninstallPlan, STALE_MS, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow,
fastPanelText, fastPanelSteps, notesBlocks, jobReportText, scheduleWarnings, requireTotp, agentOnline, siteAdminEmail,
+74
View File
@@ -1236,3 +1236,77 @@ describe('frps allow_ports and port labels (Hub 2.20.0)', () => {
expect((await db.serverAlert.findFirst({ where: { serverId: central.id, type: 'allow_ports' } })).resolvedAt).toEqual(NOW);
});
});
describe('a whole church to latest in one go (2.24.0)', () => {
const at = () => new Date(NOW.getTime() + 5 * H);
async function church() {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
await db.release.create({ data: { id: 'r30', product: 'events', version: '3.0.0', notes: '- Accounts', requires: [{ product: 'accounts', version: '1.1.0' }], releasedAt: NOW } });
await db.release.create({ data: { id: 'ra10', product: 'accounts', version: '1.0.0', releasedAt: NOW } });
await db.release.create({ data: { id: 'ra11', product: 'accounts', version: '1.1.0', releasedAt: NOW } });
await db.release.create({ data: { id: 'rw10', product: 'website', version: '1.0.0', releasedAt: NOW } });
const dep = (id, product, version, port) => db.deployment.create({ data: { id, serverId: server.id, customerId: 'cust-1', product, shortName: 'hope', domain: `${product}.hope.co.za`, webPort: port, apiPort: port + 1, status: 'live', version } });
const ev = await dep('ev-hope', 'events', '2.4.0', 22000);
const acc = await dep('acc-hope', 'accounts', '1.0.0', 22010);
const web = await dep('web-hope', 'website', '1.0.0', 22020);
return { server, ev, acc, web };
}
test('the plan lists every product in update order, Accounts first, and says which are behind', async () => {
await church();
const plan = await jobs.churchUpdatePlan('cust-1');
expect(plan.map(p => [p.product, p.current, p.latest, p.ready])).toEqual([
['accounts', '1.0.0', '1.1.0', true], ['events', '2.4.0', '3.0.0', true], ['website', '1.0.0', '1.0.0', false],
]);
expect(plan[2].why).toBe('On the latest release.');
});
test('one batch: Accounts first, then Events, which keeps the new Accounts; up to date products are left alone', async () => {
const { server } = await church();
const out = await jobs.scheduleChurchUpdate('cust-1', { at: at() }, admin, NOW);
expect(out.batchId).toMatch(/^batch_/);
expect(out.jobs.map(j => [j.deploymentId, j.status, j.batchOrder, j.batchId])).toEqual([
['acc-hope', 'queued', 0, out.batchId], ['ev-hope', 'scheduled', 1, out.batchId],
]);
expect(out.jobs[0].args.versions).toEqual(['accounts@1.1.0']);
// Not accounts@1.0.0: that would undo the update just before it.
expect(out.jobs[1].args.versions).toEqual(['accounts@1.1.0', 'events@3.0.0']);
expect(out.updates).toEqual([
{ product: 'accounts', domain: 'accounts.hope.co.za', from: '1.0.0', to: '1.1.0' },
{ product: 'events', domain: 'events.hope.co.za', from: '2.4.0', to: '3.0.0' },
]);
// The batch runs on: Accounts succeeds, so Events is queued.
const poll = when => jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, when);
const first = (await poll(at())).jobs[0];
expect(first.id).toBe(out.jobs[0].id);
await jobs.receiveReport(server, signedReport(first, 'succeeded'), at());
expect((await db.job.findUnique({ where: { id: out.jobs[1].id } })).status).toBe('queued');
// Everything is planned now: a second click is refused.
await expect(jobs.scheduleChurchUpdate('cust-1', { at: at() }, admin, NOW)).rejects.toMatchObject({ code: 'NOT_READY' });
});
test('planned whole or not at all, and refused when there is nothing to update', async () => {
const { ev } = await church();
await jobs.scheduleUpdate({ deploymentIds: [ev.id], version: '2.4.0', at: at() }, admin, NOW).catch(() => null);
const { jobs: [planned] } = await jobs.scheduleUpdate({ deploymentIds: ['acc-hope'], version: '1.1.0', at: at() }, admin, NOW);
const before = await db.job.count();
await expect(jobs.scheduleChurchUpdate('cust-1', { at: at() }, admin, NOW)).rejects.toMatchObject({ code: 'NOT_READY', message: expect.stringContaining('Accounts (accounts.hope.co.za): An update is planned') });
expect(await db.job.count()).toBe(before);
expect(planned.status).toBe('queued');
await db.deployment.update({ where: { id: 'ev-hope' }, data: { version: '3.0.0' } });
await db.deployment.update({ where: { id: 'acc-hope' }, data: { version: '1.1.0' } });
await db.job.update({ where: { id: planned.id }, data: { status: 'cancelled' } });
await expect(jobs.scheduleChurchUpdate('cust-1', { at: at() }, admin, NOW)).rejects.toMatchObject({ code: 'UP_TO_DATE' });
});
test('an emergency runs as soon as possible, with a reason and one two-factor code', async () => {
await church();
await expect(jobs.scheduleChurchUpdate('cust-1', { emergency: true, asap: true, reason: 'Security fix', totp: '000000' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_TOTP' });
await expect(jobs.scheduleChurchUpdate('cust-1', { emergency: true, asap: true, totp: totpNow() }, admin, NOW)).rejects.toMatchObject({ message: expect.stringContaining('reason') });
const out = await jobs.scheduleChurchUpdate('cust-1', { emergency: true, asap: true, reason: 'Security fix', totp: totpNow() }, admin, NOW);
expect(out.jobs.map(j => [j.emergency, j.reason, j.status])).toEqual([[true, 'Security fix', 'queued'], [true, 'Security fix', 'scheduled']]);
expect(out.jobs[0].notBefore).toEqual(NOW);
});
});