Hub 2.6.0: paged lists, job status filters, one-product updates, installs found on servers
- Jobs: Succeeded/Cancelled filters, product, type and church search, paged on the server; audit log and alerts paged on the server with search; every other list paged. - Updates: one product at a time with its own releases; an Events update pins the church's Accounts (or updates it when the release needs it, or installs it first); fixes the requirement check comparing an object. - A status job adds installs found on a server and ties them to their registration; unlinked registered sites trigger one (daily); heartbeats tie install records too; the install page shows its registration. 13 new tests (209). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+180
-10
@@ -19,7 +19,8 @@ const { sendMail } = require('./mail');
|
||||
const { getSettings } = require('./settings');
|
||||
const { PRODUCT_NAMES } = require('./products');
|
||||
const { generateLicence } = require('./licences');
|
||||
const { unmetRequirementsFor } = require('./releases');
|
||||
const { unmetRequirements, unmetRequirementsFor } = require('./releases');
|
||||
const { searchTerm } = require('./paging');
|
||||
const { compareVersions } = require('./alerts');
|
||||
const servers = require('./servers');
|
||||
const { missingFor, invalidFor } = require('./envTemplates');
|
||||
@@ -208,6 +209,9 @@ async function afterJob(job, { exportKey }, now) {
|
||||
case 'check-ports':
|
||||
if (!ok) await emailJoshua('Central server check: ports not ready', `${job.message || ''}\n\n${JSON.stringify(job.report?.result || {}, null, 2)}`);
|
||||
break;
|
||||
case 'status':
|
||||
if (ok) await linkFromStatus(job, now);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
@@ -520,6 +524,109 @@ async function requiredFirst({ release, product, siblings, input, domain, server
|
||||
return { release: accountsRelease, domain: accountsDomain };
|
||||
}
|
||||
|
||||
/**
|
||||
* Sites on a server the Hub has no install record for (Hub 2.6.0), from a `status` job's report
|
||||
* (`crosscode status --json`: each church's products with their domain, ports and checkout):
|
||||
* added as live installs on that server, tied to the site registered at that domain, with their
|
||||
* ports on the port list. The customer comes from the registered site, or from the church's other
|
||||
* products here. A product neither tells is left alone (and named in the job's message).
|
||||
*/
|
||||
async function linkFromStatus(job, now = new Date()) {
|
||||
const churches = Array.isArray(job.report?.result?.churches) ? job.report.result.churches : [];
|
||||
const linked = [];
|
||||
const unknown = [];
|
||||
for (const c of churches) {
|
||||
if (!c || !SHORT_NAME.test(String(c.church || ''))) continue;
|
||||
for (const p of Array.isArray(c.products) ? c.products : []) {
|
||||
const product = String(p?.product || '');
|
||||
if (!PRODUCT_NAMES[product] || !p.domain) continue;
|
||||
const known = await prisma.deployment.findFirst({ where: { shortName: c.church, product, status: { notIn: ['removed', 'failed'] } } });
|
||||
if (known) {
|
||||
if (known.serverId === job.serverId && !known.installId) await tieToRegistration(known);
|
||||
continue;
|
||||
}
|
||||
const domain = String(p.domain).toLowerCase();
|
||||
const install = await prisma.install.findFirst({ where: { product, releasedAt: null, url: { contains: `//${domain}` } }, include: { deployment: true } });
|
||||
const sibling = await prisma.deployment.findFirst({ where: { shortName: c.church, serverId: job.serverId, status: { notIn: ['removed', 'failed'] } } });
|
||||
const customerId = install?.customerId || sibling?.customerId;
|
||||
const [api, web] = String(p.ports || '').trim().split(/\s+/).map(n => parseInt(n, 10));
|
||||
if (!customerId || !(web > 0 && api > 0) || install?.deployment) { unknown.push(`${c.church}/${product}`); continue; }
|
||||
const version = /@(\d+\.\d+\.\d+.*)$/.exec(String(p.ref || ''))?.[1] || install?.version || null;
|
||||
const d = await prisma.$transaction(async tx => {
|
||||
const made = await tx.deployment.create({
|
||||
data: { serverId: job.serverId, customerId, licenceId: install?.licenceId || null, installId: install?.id || null, product, shortName: c.church, domain, webPort: web, apiPort: api, version, timezone: install?.timezone || sibling?.timezone || null, status: 'live', liveAt: now, adminName: install?.adminContact?.name || sibling?.adminName || null, adminEmail: install?.adminContact?.email || sibling?.adminEmail || null },
|
||||
});
|
||||
for (const [port, role] of [[web, 'web'], [api, 'api']]) {
|
||||
await tx.port.upsert({ where: { port }, update: { serverId: job.serverId, deploymentId: made.id, role, releasedAt: null, note: 'found on the server' }, create: { port, serverId: job.serverId, deploymentId: made.id, role, note: 'found on the server' } });
|
||||
}
|
||||
return made;
|
||||
});
|
||||
linked.push(`${d.shortName} (${PRODUCT_NAMES[product]}, ${domain})`);
|
||||
}
|
||||
}
|
||||
if (linked.length || unknown.length) {
|
||||
const text = [linked.length ? `Added: ${linked.join(', ')}.` : '', unknown.length ? `Not added (no registered site or other product of the church tells the customer, or no ports): ${unknown.join(', ')}.` : ''].filter(Boolean).join(' ');
|
||||
await prisma.job.update({ where: { id: job.id }, data: { message: [job.message, text].filter(Boolean).join(' ') } });
|
||||
if (linked.length) await emailJoshua(`Installs found on a server`, `${text}\n\n${hubUrl()}/jobs/${job.id}`);
|
||||
}
|
||||
return { linked, unknown };
|
||||
}
|
||||
|
||||
/** Ties an install record to the site registered with its licence (if it has registered). */
|
||||
async function tieToRegistration(d) {
|
||||
if (!d.licenceId) return;
|
||||
const install = await prisma.install.findFirst({ where: { licenceId: d.licenceId, releasedAt: null }, include: { deployment: true } });
|
||||
if (install && !install.deployment) await prisma.deployment.update({ where: { id: d.id }, data: { installId: install.id } });
|
||||
}
|
||||
|
||||
/**
|
||||
* A registered site the Hub has no install record for, of a customer with a product on a server:
|
||||
* ask that server what's on it (a `status` job, at most one a day per server), so the site is added by
|
||||
* itself (linkFromStatus). Called after a heartbeat; never fails it.
|
||||
*/
|
||||
async function lookForUnlinked(install, now = new Date()) {
|
||||
try {
|
||||
if (!install || install.releasedAt) return null;
|
||||
const own = await prisma.deployment.findFirst({ where: { installId: install.id } });
|
||||
if (own) return null;
|
||||
const sibling = await prisma.deployment.findFirst({ where: { customerId: install.customerId, status: { in: ['live', 'waiting_for_proxy'] } }, include: { server: true } });
|
||||
if (!sibling || sibling.server.removedAt || sibling.server.mode !== 'church') return null;
|
||||
const recent = await prisma.job.findFirst({ where: { serverId: sibling.serverId, type: 'status', createdAt: { gt: new Date(now.getTime() - 24 * HOUR) } } });
|
||||
if (recent) return null;
|
||||
return await makeJob(prisma, { serverId: sibling.serverId, type: 'status', args: { church: sibling.shortName }, notBefore: now });
|
||||
} catch (e) {
|
||||
console.warn('[jobs] looking for an unlinked install failed:', e?.message || e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const JOB_STATUSES = ['queued', 'scheduled', 'delivered', 'succeeded', 'failed', 'rolled_back', 'refused', 'missed', 'cancelled', 'timed_out'];
|
||||
|
||||
/** The jobs list's filters (Hub 2.6.0, GET /api/admin/jobs). */
|
||||
async function listWhere(q = {}) {
|
||||
const and = [];
|
||||
if (q.upcoming === 'true') and.push({ status: { in: ['queued', 'scheduled', 'delivered'] } });
|
||||
else if (q.status) {
|
||||
const list = String(q.status).split(',').filter(s => JOB_STATUSES.includes(s));
|
||||
if (!list.length) throw fail(400, 'BAD_REQUEST', 'Unknown job status.');
|
||||
and.push({ status: { in: list } });
|
||||
}
|
||||
if (q.type) and.push({ type: String(q.type) });
|
||||
if (q.serverId) and.push({ serverId: String(q.serverId) });
|
||||
if (q.deploymentId) and.push({ deploymentId: String(q.deploymentId) });
|
||||
// By product or church: the matching installs first, then their jobs.
|
||||
const term = searchTerm(q.q);
|
||||
if (q.product || term) {
|
||||
const dWhere = { AND: [
|
||||
...(q.product ? [{ product: String(q.product) }] : []),
|
||||
...(term ? [{ OR: [{ shortName: { contains: term, mode: 'insensitive' } }, { domain: { contains: term, mode: 'insensitive' } }] }] : []),
|
||||
] };
|
||||
const ids = (await prisma.deployment.findMany({ where: dWhere, select: { id: true } })).map(d => d.id);
|
||||
and.push({ deploymentId: { in: ids } });
|
||||
}
|
||||
return and.length ? { AND: and } : {};
|
||||
}
|
||||
|
||||
/** Proxy done (§7.8): check the public addresses, then Live and the welcome email. */
|
||||
async function proxyDone(deploymentId, now = new Date(), fetcher = fetch) {
|
||||
const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { install: true, customer: true } });
|
||||
@@ -559,7 +666,36 @@ function scheduleWarnings(at, deployment) {
|
||||
* runs them one at a time from `at` and stops at the first failure. Each church gets one email
|
||||
* and a banner now, and a reminder an hour before.
|
||||
*/
|
||||
async function scheduleUpdate({ deploymentIds, version, at, emergency = false, reason = null, totp = null }, admin, now = new Date()) {
|
||||
/**
|
||||
* What an update of a product (not Accounts) does to the church's Accounts (Hub 2.6.0).
|
||||
* `crosscode deploy` always updates Accounts too, to its latest release unless told a version, so
|
||||
* the Hub always tells it one:
|
||||
* - the release needs a newer Accounts: the newest Accounts release (refused if none is new enough)
|
||||
* - the church has no Accounts and the release needs it: installed first, in the same batch
|
||||
* - 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) {
|
||||
if (d.product === 'accounts') return { version: null, 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 } });
|
||||
const from = d.install?.version || d.version || null;
|
||||
const need = unmetRequirements({ releases, from, target: release.version, siblings: running ? [{ product: 'accounts', version: running }] : [] }).find(u => u.product === 'accounts');
|
||||
if (!need) return { version: running ? `accounts@${running}` : null, install: null, note: null };
|
||||
if (!accountsRelease || compareVersions(accountsRelease.version, need.version) < 0) {
|
||||
throw fail(409, 'REQUIREMENT_NOT_MET', `${d.shortName}: ${PRODUCT_NAMES[d.product]} ${release.version} needs Accounts ${need.version}, and there's no Accounts release that new yet.`);
|
||||
}
|
||||
if (acc) {
|
||||
if (acc.status !== 'live') throw fail(409, 'NOT_LIVE', `${d.shortName}: its Accounts isn't live (${acc.status}).`);
|
||||
return { version: `accounts@${accountsRelease.version}`, install: null, note: `${d.shortName}: Accounts is updated from ${running || 'an unknown version'} to ${accountsRelease.version} first (${PRODUCT_NAMES[d.product]} ${release.version} needs ${need.version}).` };
|
||||
}
|
||||
const domain = accountsDomainFor(d.domain);
|
||||
if (!DOMAIN.test(domain)) throw fail(400, 'BAD_REQUEST', `${d.shortName}: no Accounts domain could be made from ${d.domain}; install Accounts first (New install).`);
|
||||
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);
|
||||
if (Number.isNaN(when.getTime())) throw fail(400, 'BAD_REQUEST', 'Pick a time.');
|
||||
if (emergency) {
|
||||
@@ -574,15 +710,21 @@ async function scheduleUpdate({ deploymentIds, version, at, emergency = false, r
|
||||
const deployments = await prisma.deployment.findMany({ where: { id: { in: ids } }, include: { server: true, install: true, customer: true } });
|
||||
if (deployments.length !== ids.length) throw fail(404, 'NOT_FOUND', 'One of the installs wasn\'t found.');
|
||||
const products = new Set(deployments.map(d => d.product));
|
||||
if (products.size !== 1) throw fail(400, 'BAD_REQUEST', 'A batch is for one product.');
|
||||
if (products.size !== 1) throw fail(400, 'BAD_REQUEST', 'A batch is for one product: choose Cross Events or Accounts installs, not both.');
|
||||
const product = [...products][0];
|
||||
const release = await releaseFor(product, version);
|
||||
// Hub 2.6.0: the page says which product it's updating; a mismatch is refused, never guessed.
|
||||
if (wanted && wanted !== product) throw fail(400, 'WRONG_PRODUCT', `These installs are ${PRODUCT_NAMES[product]}, not ${PRODUCT_NAMES[wanted] || wanted}.`);
|
||||
if (version && /@/.test(String(version)) && !String(version).startsWith(`${product}@`)) throw fail(400, 'WRONG_PRODUCT', `${version} isn't a ${PRODUCT_NAMES[product]} release.`);
|
||||
const release = await releaseFor(product, version ? String(version).replace(/^[a-z]+@/, '') : null);
|
||||
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 = [];
|
||||
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.`);
|
||||
if (d.install) {
|
||||
const unmet = await unmetRequirementsFor(d.install, release);
|
||||
// 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');
|
||||
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());
|
||||
@@ -590,18 +732,46 @@ async function scheduleUpdate({ deploymentIds, version, at, emergency = false, r
|
||||
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);
|
||||
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);
|
||||
}
|
||||
const batchId = deployments.length > 1 ? servers.newId('batch') : null;
|
||||
const installsFirst = [...plans.values()].filter(p => p.install).length;
|
||||
const batchId = deployments.length + installsFirst > 1 ? servers.newId('batch') : null;
|
||||
const name = PRODUCT_NAMES[product];
|
||||
const jobs = [];
|
||||
for (const [i, d] of deployments.entries()) {
|
||||
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' });
|
||||
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 => {
|
||||
let licence = await tx.licence.findFirst({ where: { customerId: d.customerId, product: 'accounts', status: { not: 'revoked' } }, include: { install: true } });
|
||||
if (licence?.install && !licence.install.releasedAt) throw fail(409, 'LICENCE_IN_USE', `${d.shortName}: its Accounts licence is already used by ${licence.install.url}. Link that install (Installs → Link existing) instead.`);
|
||||
if (!licence) licence = (await generateLicence(tx, { customerId: d.customerId, product: 'accounts', now })).licence;
|
||||
const ports = await servers.allocatePorts(tx, d.serverId, now);
|
||||
const a = await tx.deployment.create({ data: { serverId: d.serverId, customerId: d.customerId, licenceId: licence.id, product: 'accounts', shortName: d.shortName, domain: plan.install.domain, webPort: ports.web, apiPort: ports.api, timezone: d.timezone, adminName: d.adminName, adminEmail: d.adminEmail, status: 'installing' } });
|
||||
await tx.port.updateMany({ where: { port: { in: [ports.web, ports.api] } }, data: { deploymentId: a.id } });
|
||||
const o = next();
|
||||
const job = await makeJob(tx, {
|
||||
serverId: d.serverId, type: 'add-product', deploymentId: a.id, createdById: admin?.id || null, notBefore: when, ...o,
|
||||
args: { church: d.shortName, product: 'accounts', version: `accounts@${plan.install.release.version}`, domain: plan.install.domain, ports },
|
||||
});
|
||||
return job;
|
||||
});
|
||||
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 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}`];
|
||||
jobs.push(await makeJob(prisma, {
|
||||
serverId: d.serverId, type: 'deploy', deploymentId: d.id, createdById: admin?.id || null, scheduled: true, emergency, reason,
|
||||
batchId, batchOrder: batchId ? i : null, status: !batchId || i === 0 ? 'queued' : 'scheduled', notBefore: when, noticeId,
|
||||
args: { church: d.shortName, products: [product], versions: [`${product}@${release.version}`] },
|
||||
...next(), notBefore: when, noticeId,
|
||||
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}`);
|
||||
@@ -777,6 +947,6 @@ async function seedDemo({ deploymentId, profile, confirm }, admin, now = new Dat
|
||||
module.exports = {
|
||||
WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES, setDemo, seedDemo,
|
||||
makeJob, signedJob, jobConfig, poll, receiveReport, finish, tick, advanceBatch,
|
||||
newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, neverInstalled, removeFailedInstall, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow,
|
||||
linkFromStatus, listWhere, lookForUnlinked, newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, neverInstalled, removeFailedInstall, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow,
|
||||
fastPanelText, jobReportText, scheduleWarnings, requireTotp, agentOnline, siteAdminEmail,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user