Hub 2.7.0: emergency updates as soon as possible; events on now need a second yes

asap (emergency only, reason + 2FA) queues the update now; the church is
told it's happening now. A church whose Events heartbeat reports an event
on now (stats.live, Events 3.2.0) refuses an emergency update with
LIVE_EVENT until confirmLive. Both update forms offer "As soon as possible"
and ask again for a live event. Contracts 1.10.0 vendored. 4 new tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 22:01:28 +02:00
co-authored by Claude Opus 5.5
parent 3893fb91e0
commit dd5612fb2a
12 changed files with 156 additions and 34 deletions
+6 -6
View File
@@ -1,16 +1,16 @@
{
"name": "events-hub-backend",
"version": "2.6.1",
"version": "2.7.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-backend",
"version": "2.6.1",
"version": "2.7.0",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.8.0.tgz",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.10.0.tgz",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
@@ -609,9 +609,9 @@
"license": "MIT"
},
"node_modules/@crosscode/contracts": {
"version": "1.8.0",
"resolved": "file:vendor/crosscode-contracts-1.8.0.tgz",
"integrity": "sha512-OJb/egG9duMnN1D3AEpoLpYXtzeVpqU6SuXDbVcBKYARGNC9VOwfDsLwxbThR6igRtByuMhJ+jJEkFPlTRFHdg==",
"version": "1.10.0",
"resolved": "file:vendor/crosscode-contracts-1.10.0.tgz",
"integrity": "sha512-FUm5qrZcyhM7JW7H1DNHifY9IFaxCJhVsLVed++gag65RO+EFnAjlPLw2bJqPIX/9e2CD1OBtHmNKxc9NjBCWA==",
"license": "UNLICENSED",
"dependencies": {
"zod": "^4.6.7"
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-backend",
"version": "2.6.1",
"version": "2.7.0",
"private": true,
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
"main": "src/index.js",
@@ -20,7 +20,7 @@
},
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.8.0.tgz",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.10.0.tgz",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
+1 -1
View File
@@ -211,7 +211,7 @@ router.post('/deployments/:id/uninstall', wrap(async (req, res) => {
router.post('/updates', wrap(async (req, res) => {
const out = await jobs.scheduleUpdate(req.body || {}, req.admin);
await audit(req, req.body?.emergency ? 'emergency_update_scheduled' : 'update_scheduled', out.batchId || out.jobs[0]?.id, { deployments: req.body?.deploymentIds, version: req.body?.version, at: req.body?.at, reason: req.body?.reason || null });
await audit(req, req.body?.emergency ? 'emergency_update_scheduled' : 'update_scheduled', out.batchId || out.jobs[0]?.id, { deployments: req.body?.deploymentIds, version: req.body?.version, 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);
}));
+38 -5
View File
@@ -700,13 +700,29 @@ async function accountsPlan(d, release, accountsRelease) {
return { version: `accounts@${accountsRelease.version}`, install: { domain, release: accountsRelease }, note: `${d.shortName}: Accounts ${accountsRelease.version} is installed first at ${domain} (${PRODUCT_NAMES[d.product]} ${release.version} needs it).` };
}
async function scheduleUpdate({ deploymentIds, product: wanted = null, version, at, emergency = false, reason = null, totp = null }, admin, now = new Date()) {
const when = new Date(at);
/**
* What's happening at a church now (Hub 2.7.0), from its Cross Events install's last heartbeat
* (`stats.live`, Events 3.2.0+; a heartbeat older than 30 minutes doesn't count). An Accounts update
* takes Events' sign-in down too, so it looks at the church's Events. Null when nothing is known.
*/
async function liveAt(d, now = new Date()) {
const ev = d.product === 'events' ? d : await prisma.deployment.findFirst({ where: { shortName: d.shortName, product: 'events', status: { notIn: ['removed', 'failed'] } }, include: { install: true } });
const install = ev?.install;
const live = install?.stats?.live;
if (!live || !install.lastHeartbeatAt || now - new Date(install.lastHeartbeatAt) > 30 * MIN) return null;
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()) {
// 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.');
const when = asap ? now : new Date(at);
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 (when - now < EMERGENCY_MIN_MINUTES * MIN) throw fail(400, 'TOO_SOON', `An emergency update needs at least ${EMERGENCY_MIN_MINUTES} minutes' notice.`);
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).`);
}
@@ -724,6 +740,21 @@ async function scheduleUpdate({ deploymentIds, product: wanted = null, version,
const accountsRelease = product === 'accounts' ? null : await prisma.release.findMany({ where: { product: 'accounts' } }).then(rs => rs.sort((a, b) => compareVersions(b.version, a.version))[0] || null);
const plans = new Map();
const warnings = [];
// An emergency update takes a site down with little or no notice: a church with an event on now
// (people checking in, a session running) is named, and the update waits for a second "yes".
if (emergency) {
const busy = [];
for (const d of deployments) {
const live = await liveAt(d, now);
if (live && (live.eventsNow > 0 || live.checkInsLastHour > 0)) {
busy.push(`${d.shortName} (${[live.eventsNow ? `${live.eventsNow} event(s) on now` : '', live.checkInsLastHour ? `${live.checkInsLastHour} check-in(s) in the last hour` : ''].filter(Boolean).join(', ')})`);
}
}
if (busy.length && !confirmLive) {
throw fail(409, 'LIVE_EVENT', `An event is on now at ${busy.join('; ')}. The site will be down for a few minutes during the update: people checking in or registering will be interrupted. Update anyway?`);
}
if (busy.length) warnings.push(`Updated while an event was on: ${busy.join('; ')}.`);
}
for (const d of deployments) {
if (d.status !== 'live') throw fail(409, 'NOT_LIVE', `${d.shortName} isn't live (${d.status}).`);
if (d.server.removedAt) throw fail(409, 'SERVER_REMOVED', `${d.shortName}'s server was removed.`);
@@ -769,7 +800,9 @@ async function scheduleUpdate({ deploymentIds, product: wanted = null, version,
jobs.push(acc);
}
const title = emergency ? `Urgent ${name} update` : `Planned ${name} update`;
const message = `${name} will be updated on ${sast(when)}. The site will be unavailable for a few minutes.${emergency ? ` Why: ${reason}` : ''}`;
const message = asap
? `${name} is being updated now. The site will be unavailable for a few minutes. Why: ${reason}`
: `${name} will be updated on ${sast(when)}. The site will be unavailable for a few minutes.${emergency ? ` Why: ${reason}` : ''}`;
const noticeId = await addNotice(d, { title, message, endsAt: new Date(when.getTime() + 2 * HOUR), level: emergency ? 'warning' : 'maintenance' }, now);
// Accounts goes first in the same deploy: told its version, so it's never changed by surprise.
const versions = [...(plan.version && !plan.install ? [plan.version] : []), `${product}@${release.version}`];
@@ -779,7 +812,7 @@ async function scheduleUpdate({ deploymentIds, product: wanted = null, version,
args: { church: d.shortName, products: [product], versions },
}));
const notes = release.notes ? `\n\nWhat's new in ${release.version}:\n${release.notes}` : '';
await emailSiteAdmin(d, `${emergency ? 'Urgent: ' : ''}${name} will be updated on ${sast(when)}`, `${message}${notes}`);
await emailSiteAdmin(d, asap ? `Urgent: ${name} is being updated now` : `${emergency ? 'Urgent: ' : ''}${name} will be updated on ${sast(when)}`, `${message}${notes}`);
}
return { jobs, batchId, warnings: [...new Set(warnings)] };
}
+48
View File
@@ -682,3 +682,51 @@ describe('the jobs list only asks for statuses the database knows (2.6.1)', () =
expect(await jobs.listWhere({ status: 'failed,expired' })).toEqual({ AND: [{ status: { in: ['failed', 'expired'] } }] });
});
});
describe('emergency updates as soon as possible, and events on now (2.7.0)', () => {
async function liveChurch(shortName, live = null, heardMinutesAgo = 5) {
let server = await db.server.findFirst({ where: { name: 'church-1' } });
if (!server) {
server = (await joinServer()).server;
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
}
const n = (await db.deployment.count()) * 2;
const install = await db.install.create({ data: { id: `inst-${shortName}`, customerId: 'cust-1', product: 'events', name: shortName, url: `https://events.${shortName}.co.za`, secret: 'x', version: '2.3.0', lastHeartbeatAt: new Date(NOW.getTime() - heardMinutesAgo * 60e3), stats: live ? { live } : {}, adminContact: { name: 'Admin', email: `admin@${shortName}.test` } } });
return db.deployment.create({ data: { id: `dep-${shortName}`, serverId: server.id, customerId: 'cust-1', installId: install.id, product: 'events', shortName, domain: `events.${shortName}.co.za`, webPort: 23000 + n, apiPort: 23001 + n, status: 'live' } });
}
const urgent = (ids, extra = {}) => jobs.scheduleUpdate({ deploymentIds: ids, version: '2.4.0', emergency: true, reason: 'Broken release', totp: totpNow(), ...extra }, admin, NOW);
test('as soon as possible: queued now for the agent\'s next poll, with the church told it\'s happening now', async () => {
const d = await liveChurch('quick');
const { jobs: [job] } = await urgent([d.id], { asap: true });
expect(job).toMatchObject({ status: 'queued', emergency: true });
expect(new Date(job.notBefore).getTime()).toBe(NOW.getTime());
expect(mockMails.find(m => m.to === 'admin@quick.test')?.subject).toBe('Urgent: Cross Events is being updated now');
const notice = await db.notice.findUnique({ where: { id: job.noticeId } });
expect(notice.message).toContain('is being updated now');
});
test('still an emergency only, with a reason and two-factor; at a time it\'s still 15 minutes', async () => {
const d = await liveChurch('rules');
await expect(jobs.scheduleUpdate({ deploymentIds: [d.id], version: '2.4.0', asap: true }, admin, NOW)).rejects.toMatchObject({ message: expect.stringContaining('Only an emergency') });
await expect(urgent([d.id], { asap: true, reason: '' })).rejects.toMatchObject({ message: expect.stringContaining('reason') });
await expect(urgent([d.id], { asap: true, totp: '000000' })).rejects.toMatchObject({ code: 'BAD_TOTP' });
await expect(urgent([d.id], { at: new Date(NOW.getTime() + 5 * 60e3) })).rejects.toMatchObject({ code: 'TOO_SOON' });
});
test('a church with an event on now is named, and the update waits for a second yes', async () => {
const busy = await liveChurch('busy', { eventsNow: 1, checkInsLastHour: 37 });
const calm = await liveChurch('calm', { eventsNow: 0, checkInsLastHour: 0 });
await expect(urgent([busy.id, calm.id], { asap: true })).rejects.toMatchObject({ code: 'LIVE_EVENT', message: expect.stringContaining('busy (1 event(s) on now, 37 check-in(s) in the last hour)') });
expect(await db.job.count()).toBe(0);
const out = await urgent([busy.id, calm.id], { asap: true, confirmLive: true });
expect(out.jobs).toHaveLength(2);
expect(out.warnings.join(' ')).toContain('Updated while an event was on: busy');
});
test('an old heartbeat, or one without live stats, doesn\'t hold an update back', async () => {
const stale = await liveChurch('stale', { eventsNow: 3, checkInsLastHour: 0 }, 90);
const older = await liveChurch('older');
expect((await urgent([stale.id, older.id], { asap: true })).jobs).toHaveLength(2);
});
});
Binary file not shown.
Binary file not shown.