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:
2026-11-19 20:09:31 +02:00
co-authored by Claude Opus 5.5
parent ff176681a7
commit de6a14c229
24 changed files with 641 additions and 130 deletions
+37
View File
@@ -5,6 +5,43 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [2.6.0] - 2026-11-19
### Added
- **Jobs: every status and a page at a time.** Filters for Succeeded and Cancelled (with Planned and
running, Failed, Rolled back, Missed and Refused), a product, a job type and a search on the
church or domain; paged on the server (`?page`, `?pageSize`, at most 200), instead of the last 200.
- **Everything is paged.** The audit log and alerts on the server (with a search there), instead of
the last 300 / 200; releases, installs on servers, servers, the port list, and each server's and
install's jobs a page at a time. Installs on servers show each install's product, with a filter
and a search.
- **Installs added on a server are found.** A `status` job (Servers → a server → Check status and
find installs) adds any church product it reports that the Hub has no install record for (its
domain, ports and version from the server), tied to the site registered at that domain, with its
ports on the port list. A registered site with no install record has its customer's server asked
by itself, at most once a day.
- An install's page shows its registered site and last heartbeat, or that it hasn't registered.
### Changed
- **Updates are for one product at a time.** The Updates page asks for Cross Events or Accounts
first, then shows only that product's live installs and its own releases (a list, not a text
box), and every install page offers only its product's releases. The server refuses installs of
more than one product, a release of another product (`accounts@…` for Events), and a product that
doesn't match the page.
- **A Cross Events update says what happens to Accounts.** `crosscode deploy` always updates a
church's Accounts too, to its newest release unless told otherwise; the Hub now always tells it:
the version it runs (nothing changes), or the newest Accounts when the Events release needs a
newer one (and the confirmation says so). A church without Accounts gets it installed first in the
same batch (`add-product`, on `accounts.<the rest of the domain>`) when the release needs it.
- A site the Hub installed is tied to its registration on every heartbeat, not only the first.
### Fixed
- The update check compared the release object, not its version, with the church's other products,
so a requirement could be missed.
## [2.5.0] - 2026-11-19
For Cross Events 3.0 (crosscode-platform `docs/EVENTS-3.0-PLAN.md` §9), which signs in through the
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-backend",
"version": "2.5.0",
"version": "2.6.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-backend",
"version": "2.5.0",
"version": "2.6.0",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-backend",
"version": "2.5.0",
"version": "2.6.0",
"private": true,
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
"main": "src/index.js",
+23 -7
View File
@@ -3,6 +3,7 @@
const express = require('express');
const rateLimit = require('express-rate-limit');
const prisma = require('../config/db');
const { pageOf, paged, searchTerm } = require('../utils/paging');
const { protect } = require('../middleware/auth');
const { generateLicence, checkReopen } = require('../utils/licences');
const { PRODUCTS, isProduct, PRODUCT_NAMES } = require('../utils/products');
@@ -288,17 +289,32 @@ router.post('/installs/:id/public-key/clear', wrap(async (req, res) => {
// ─── Alerts and history ───────────────────────────────────────────────────────
// Hub 2.6.0: both paged (?page, ?pageSize) with a search (?q), instead of the last 200 / 300.
router.get('/events', wrap(async (req, res) => {
const where = req.query.open === 'true' ? { resolvedAt: null, level: { not: 'info' } } : {};
const events = await prisma.installEvent.findMany({
where, orderBy: { createdAt: 'desc' }, take: 200,
include: { install: { select: { id: true, name: true, url: true } } },
});
res.json(events);
const and = [];
if (req.query.open === 'true') and.push({ resolvedAt: null, level: { not: 'info' } });
const term = searchTerm(req.query.q);
if (term) {
and.push({ OR: [
{ message: { contains: term, mode: 'insensitive' } },
{ level: { contains: term, mode: 'insensitive' } },
{ install: { name: { contains: term, mode: 'insensitive' } } },
{ install: { url: { contains: term, mode: 'insensitive' } } },
] });
}
const out = await paged(prisma.installEvent, { where: and.length ? { AND: and } : {}, orderBy: { createdAt: 'desc' }, include: { install: { select: { id: true, name: true, url: true } } } }, pageOf(req.query));
res.json({ events: out.rows, total: out.total, page: out.page, pageSize: out.pageSize, pages: out.pages });
}));
router.get('/audit', wrap(async (req, res) => {
res.json(await prisma.auditLog.findMany({ orderBy: { createdAt: 'desc' }, take: 300, include: { actor: { select: { name: true } } } }));
const term = searchTerm(req.query.q);
const where = term ? { OR: [
{ action: { contains: term.replace(/s+/g, '_'), mode: 'insensitive' } },
{ target: { contains: term, mode: 'insensitive' } },
{ actor: { name: { contains: term, mode: 'insensitive' } } },
] } : {};
const out = await paged(prisma.auditLog, { where, orderBy: { createdAt: 'desc' }, include: { actor: { select: { name: true } } } }, pageOf(req.query));
res.json({ entries: out.rows, total: out.total, page: out.page, pageSize: out.pageSize, pages: out.pages });
}));
// ─── Releases ─────────────────────────────────────────────────────────────────
+9
View File
@@ -224,6 +224,15 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => {
prisma.heartbeat.create({ data: { installId: install.id, receivedAt: now, version, health: health || undefined, stats: stats || undefined } }),
prisma.install.update({ where: { id: install.id }, data: { lastHeartbeatAt: now, version, protocolVersion: body.protocolVersion, health: health || undefined, stats: stats || undefined } }),
]);
// Hub 2.6.0: a site the Hub installed is tied to its registration on every heartbeat too, not
// only when it first registers (so a missed one is mended). A site with no install record at
// all has its server asked what's on it (a status job), which adds it. Neither fails the heartbeat.
try {
const tied = await prisma.deployment.updateMany({ where: { licenceId: install.licenceId, installId: null, status: { notIn: ['removed', 'failed'] } }, data: { installId: install.id } });
if (!tied.count) await require('../utils/jobs').lookForUnlinked(install, now);
} catch (e) {
console.warn('[hub] tying the install record to its site failed:', e?.message || e);
}
if (version && install.version && version !== install.version) {
await prisma.installEvent.create({ data: { installId: install.id, type: 'version', level: 'info', message: `Updated from ${install.version} to ${version}`, resolvedAt: now } });
// An update the church asked for is done once the install runs a newer version.
+8 -6
View File
@@ -11,6 +11,7 @@ const { audit } = require('../utils/audit');
const { getSettings, setSettings } = require('../utils/settings');
const servers = require('../utils/servers');
const jobs = require('../utils/jobs');
const { pageOf, paged } = require('../utils/paging');
const router = express.Router();
router.use(protect);
@@ -216,15 +217,16 @@ router.post('/updates', wrap(async (req, res) => {
// ─── Jobs ─────────────────────────────────────────────────────────────────────
// Hub 2.6.0: paged (?page, ?pageSize), with filters for every status (succeeded too), a job type,
// a product, a server, an install, and a search on the church's short name or domain.
router.get('/jobs', wrap(async (req, res) => {
const where = {};
if (req.query.status) where.status = String(req.query.status);
if (req.query.serverId) where.serverId = String(req.query.serverId);
if (req.query.upcoming === 'true') where.status = { in: ['queued', 'scheduled', 'delivered'] };
const list = await prisma.job.findMany({ where, orderBy: [{ notBefore: 'desc' }], take: 200, include: { server: { select: { id: true, name: true } }, deployment: { select: { id: true, shortName: true, domain: true } } } });
res.json({ jobs: list.map(j => ({ ...j, report: undefined, hasReport: !!j.report })) });
const where = await jobs.listWhere(req.query);
const p = pageOf(req.query);
const out = await paged(prisma.job, { where, orderBy: [{ notBefore: 'desc' }, { createdAt: 'desc' }], include: { server: { select: { id: true, name: true } }, deployment: { select: { id: true, shortName: true, domain: true, product: true } } } }, p);
res.json({ jobs: out.rows.map(j => ({ ...j, report: undefined, hasReport: !!j.report })), total: out.total, page: out.page, pageSize: out.pageSize, pages: out.pages });
}));
router.get('/jobs/:id', wrap(async (req, res) => {
const job = await prisma.job.findUnique({ where: { id: req.params.id }, include: { server: { select: { id: true, name: true } }, deployment: { select: { id: true, shortName: true, domain: true } } } });
if (!job) throw bad('Not found.', 404);
+180 -10
View File
@@ -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,
};
+30
View File
@@ -0,0 +1,30 @@
/**
* Paging for lists that grow without end (Hub 2.6.0): jobs, the audit log, alerts. `?page=` (from
* 1) and `?pageSize=` (default 50, at most 200); the answer has the page's rows plus `total`,
* `page`, `pageSize` and `pages`, so the list never stops at a fixed number of rows.
*/
const DEFAULT_SIZE = 50;
const MAX_SIZE = 200;
function pageOf(query = {}, { defaultSize = DEFAULT_SIZE } = {}) {
const size = Math.min(MAX_SIZE, Math.max(1, parseInt(query.pageSize, 10) || defaultSize));
const page = Math.max(1, parseInt(query.page, 10) || 1);
return { page, pageSize: size, skip: (page - 1) * size, take: size };
}
/** Runs the page's query and the count together. */
async function paged(model, { where, orderBy, include, select }, p) {
const [rows, total] = await Promise.all([
model.findMany({ where, orderBy, include, select, skip: p.skip, take: p.take }),
model.count({ where }),
]);
return { rows, total, page: p.page, pageSize: p.pageSize, pages: Math.max(1, Math.ceil(total / p.pageSize)) };
}
/** A search term for `contains` filters (trimmed, at most 100 characters), or null. */
function searchTerm(q) {
const s = String(q ?? '').trim().slice(0, 100);
return s || null;
}
module.exports = { pageOf, paged, searchTerm, MAX_SIZE };
+3 -1
View File
@@ -39,6 +39,7 @@ function matches(row, where = {}) {
if ('gt' in cond && !(v != null && cmp(v, cond.gt) > 0)) return false;
if ('gte' in cond && !(v != null && cmp(v, cond.gte) >= 0)) return false;
if ('equals' in cond && v !== cond.equals) return false;
if ('contains' in cond && !(typeof v === 'string' && (cond.mode === 'insensitive' ? v.toLowerCase().includes(String(cond.contains).toLowerCase()) : v.includes(cond.contains)))) return false;
}
return true;
}
@@ -107,8 +108,9 @@ function createFakeDb() {
return {
findUnique: async ({ where, include: inc, select }) => include(name, t(name).find(r => matches(r, where)) || null, inc || select),
findFirst: async ({ where, include: inc, orderBy } = {}) => include(name, sort(t(name).filter(r => matches(r, where)), orderBy)[0] || null, inc),
findMany: async ({ where, include: inc, orderBy, take, select } = {}) => {
findMany: async ({ where, include: inc, orderBy, take, skip, select } = {}) => {
let list = sort(t(name).filter(r => matches(r, where)), orderBy);
if (skip) list = list.slice(skip);
if (take) list = list.slice(0, take);
return list.map(r => include(name, r, inc || select));
},
+115
View File
@@ -289,6 +289,61 @@ describe('scheduled updates (§8)', () => {
});
});
describe('updates never mix products, and say what happens to Accounts (2.6.0)', () => {
const at = () => new Date(NOW.getTime() + 5 * H);
async function church(shortName, { accounts = null } = {}) {
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 ev = await db.deployment.create({ data: { id: `ev-${shortName}`, serverId: server.id, customerId: 'cust-1', product: 'events', shortName, domain: `events.${shortName}.co.za`, webPort: 21000 + n, apiPort: 21001 + n, status: 'live', version: '2.4.0' } });
let acc = null;
if (accounts) acc = await db.deployment.create({ data: { id: `acc-${shortName}`, serverId: server.id, customerId: 'cust-1', product: 'accounts', shortName, domain: `accounts.${shortName}.co.za`, webPort: 21100 + n, apiPort: 21101 + n, status: 'live', version: accounts } });
return { server, ev, acc };
}
beforeEach(async () => {
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 } });
});
test('Events and Accounts installs in one update are refused, and so is the wrong product\'s release', async () => {
const { ev, acc } = await church('mix', { accounts: '1.1.0' });
await expect(jobs.scheduleUpdate({ deploymentIds: [ev.id, acc.id], at: at() }, admin, NOW)).rejects.toMatchObject({ message: expect.stringContaining('one product') });
await expect(jobs.scheduleUpdate({ deploymentIds: [ev.id], product: 'accounts', at: at() }, admin, NOW)).rejects.toMatchObject({ code: 'WRONG_PRODUCT' });
await expect(jobs.scheduleUpdate({ deploymentIds: [ev.id], version: 'accounts@1.1.0', at: at() }, admin, NOW)).rejects.toMatchObject({ code: 'WRONG_PRODUCT' });
await expect(jobs.scheduleUpdate({ deploymentIds: [acc.id], version: '3.0.0', at: at() }, admin, NOW)).rejects.toMatchObject({ code: 'NO_RELEASE' });
});
test('an Events update keeps Accounts on the version it runs when nothing needs more', async () => {
const { ev } = await church('keep', { accounts: '1.0.0' });
const { jobs: [job], warnings } = await jobs.scheduleUpdate({ deploymentIds: [ev.id], version: '2.4.0', at: at() }, admin, NOW);
expect(job.args).toEqual({ church: 'keep', products: ['events'], versions: ['accounts@1.0.0', 'events@2.4.0'] });
expect(warnings.join(' ')).not.toContain('Accounts is updated');
});
test('Events 3.0 updates an older Accounts in the same deploy, and says so', async () => {
const { ev } = await church('older', { accounts: '1.0.0' });
const { jobs: [job], warnings } = await jobs.scheduleUpdate({ deploymentIds: [ev.id], version: '3.0.0', at: at() }, admin, NOW);
expect(job.args.versions).toEqual(['accounts@1.1.0', 'events@3.0.0']);
expect(warnings.join(' ')).toContain('Accounts is updated from 1.0.0 to 1.1.0');
});
test('a church without Accounts gets it installed first, then the update, in one batch', async () => {
const { ev } = await church('none');
const { jobs: made, batchId, warnings } = await jobs.scheduleUpdate({ deploymentIds: [ev.id], version: '3.0.0', at: at() }, admin, NOW);
expect(batchId).toMatch(/^batch_/);
expect(made.map(j => [j.type, j.status])).toEqual([['add-product', 'queued'], ['deploy', 'scheduled']]);
expect(made[0].args).toMatchObject({ church: 'none', product: 'accounts', version: 'accounts@1.1.0', domain: 'accounts.none.co.za' });
expect(made[1].args.versions).toEqual(['events@3.0.0']);
expect(warnings.join(' ')).toContain('installed first at accounts.none.co.za');
expect(await db.deployment.findFirst({ where: { shortName: 'none', product: 'accounts' } })).toMatchObject({ status: 'installing' });
});
});
describe('ports and alerts', () => {
test('ports are unique, and a released one is reused only after 30 days', async () => {
const { server } = await joinServer();
@@ -556,3 +611,63 @@ describe('demo sites (2.4.0)', () => {
expect(await db.job.findMany({})).toEqual([]);
});
});
describe('sites added on a server are found and tied to their registration (2.6.0)', () => {
const statusResult = (domain = 'accounts.found.co.za') => ({ churches: [{ church: 'found', address: 'found.co.za', products: [
{ product: 'events', ref: 'events@2.4.1', domain: 'events.found.co.za', ports: '21201 21200' },
{ product: 'accounts', ref: 'accounts@1.1.0', domain, ports: '21203 21202' },
] }] });
test('a status report adds the Accounts the Hub didn\'t know, tied to its registered site, with its ports', async () => {
const { server } = await joinServer();
await db.deployment.create({ data: { id: 'ev-found', serverId: server.id, customerId: 'cust-1', product: 'events', shortName: 'found', domain: 'events.found.co.za', webPort: 21200, apiPort: 21201, status: 'live' } });
const licence = await db.licence.create({ data: { id: 'lic-acc', customerId: 'cust-1', product: 'accounts', key: 'CCA-TEST', status: 'active' } });
await db.install.create({ data: { id: 'inst-acc', customerId: 'cust-1', licenceId: licence.id, product: 'accounts', name: 'Found Accounts', url: 'https://accounts.found.co.za', secret: 'x', version: '1.1.0' } });
const job = await jobs.runNow({ serverId: server.id, type: 'status', args: {} }, admin, NOW);
await jobs.receiveReport(server, signedReport(job, 'succeeded', { result: statusResult() }), NOW);
const acc = await db.deployment.findFirst({ where: { shortName: 'found', product: 'accounts' } });
expect(acc).toMatchObject({ serverId: server.id, customerId: 'cust-1', installId: 'inst-acc', licenceId: 'lic-acc', domain: 'accounts.found.co.za', webPort: 21202, apiPort: 21203, version: '1.1.0', status: 'live' });
expect((await db.port.findMany({ where: { deploymentId: acc.id } })).map(p => p.port).sort()).toEqual([21202, 21203]);
expect((await db.job.findUnique({ where: { id: job.id } })).message).toContain('Added: found (Accounts');
// A second report changes nothing.
const again = await jobs.runNow({ serverId: server.id, type: 'status', args: {} }, admin, NOW);
await jobs.receiveReport(server, signedReport(again, 'succeeded', { result: statusResult() }), NOW);
expect(await db.deployment.count({ where: { shortName: 'found', product: 'accounts' } })).toBe(1);
});
test('a registered site with no install record asks its customer\'s server what\'s on it, once a day', async () => {
const { server } = await joinServer();
await db.deployment.create({ data: { id: 'ev-ask', serverId: server.id, customerId: 'cust-1', product: 'events', shortName: 'ask', domain: 'events.ask.co.za', webPort: 21300, apiPort: 21301, status: 'live' } });
const install = await db.install.create({ data: { id: 'inst-ask', customerId: 'cust-1', product: 'accounts', name: 'Ask Accounts', url: 'https://accounts.ask.co.za', secret: 'x', version: '1.1.0', releasedAt: null } });
const job = await jobs.lookForUnlinked(install, NOW);
expect(job).toMatchObject({ type: 'status', serverId: server.id, status: 'queued' });
expect(await jobs.lookForUnlinked(install, new Date(NOW.getTime() + 3600e3))).toBeNull();
});
test('a site the Hub installed, tied already, asks nothing', async () => {
const { server } = await joinServer();
const install = await db.install.create({ data: { id: 'inst-own', customerId: 'cust-1', product: 'events', name: 'Own', url: 'https://events.own.co.za', secret: 'x', releasedAt: null } });
await db.deployment.create({ data: { id: 'ev-own', serverId: server.id, customerId: 'cust-1', installId: install.id, product: 'events', shortName: 'own', domain: 'events.own.co.za', webPort: 21400, apiPort: 21401, status: 'live' } });
expect(await jobs.lookForUnlinked(install, NOW)).toBeNull();
});
});
describe('the jobs list: every status, product, search and pages (2.6.0)', () => {
const { pageOf, paged } = require('../src/utils/paging');
const list = async (q) => paged(db.job, { where: await jobs.listWhere(q), orderBy: [{ notBefore: 'desc' }], include: { deployment: true } }, pageOf(q));
test('succeeded and cancelled can be listed, by product and church, a page at a time', async () => {
const { server } = await joinServer();
await db.deployment.create({ data: { id: 'd-ev', serverId: server.id, customerId: 'cust-1', product: 'events', shortName: 'hope', domain: 'events.hope.co.za', webPort: 22000, apiPort: 22001, status: 'live' } });
await db.deployment.create({ data: { id: 'd-acc', serverId: server.id, customerId: 'cust-1', product: 'accounts', shortName: 'hope', domain: 'accounts.hope.co.za', webPort: 22002, apiPort: 22003, status: 'live' } });
for (let i = 0; i < 7; i++) {
await db.job.create({ data: { id: `job_test${i}0000`, serverId: server.id, type: 'deploy', deploymentId: i % 2 ? 'd-acc' : 'd-ev', status: i < 5 ? 'succeeded' : 'cancelled', args: {}, notBefore: new Date(NOW.getTime() + i * 60e3), expiresAt: NOW } });
}
const ok = await list({ status: 'succeeded', pageSize: '2' });
expect([ok.total, ok.pages, ok.rows.length]).toEqual([5, 3, 2]);
expect((await list({ status: 'succeeded', pageSize: '2', page: '3' })).rows.map(j => j.id)).toEqual(['job_test00000']);
expect((await list({ status: 'cancelled' })).total).toBe(2);
expect((await list({ product: 'accounts' })).rows.every(j => j.deployment.product === 'accounts')).toBe(true);
expect((await list({ q: 'ACCOUNTS.hope' })).total).toBe(3);
await expect(jobs.listWhere({ status: 'nonsense' })).rejects.toThrow('Unknown job status.');
expect(pageOf({ pageSize: '100000' }).pageSize).toBe(200);
});
});
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-frontend",
"version": "2.5.0",
"version": "2.6.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-frontend",
"version": "2.5.0",
"version": "2.6.0",
"dependencies": {
"lucide-react": "^0.536.0",
"next": "^15.5.24",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-frontend",
"version": "2.5.0",
"version": "2.6.0",
"private": true,
"scripts": {
"dev": "next dev -p 3200",
+12 -18
View File
@@ -1,27 +1,21 @@
"use client";
import React, { useEffect, useMemo, useState } from "react";
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import { matches, usePaged } from "@/lib/paging";
import { useServerPaged } from "@/lib/paging";
import type { InstallEvent } from "@/lib/types";
import { Badge, Loading, PageTitle, Pager, SearchInput } from "@/components/ui";
/** Open alerts, and the history of everything that happened to installs. */
/** Open alerts, and the history of everything that happened to installs, a page at a time (Hub 2.6.0: paged on the server). */
export default function AlertsPage() {
const [openOnly, setOpenOnly] = useState(true);
const [events, setEvents] = useState<InstallEvent[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [query, setQuery] = useState("");
useEffect(() => {
setEvents(null);
api<InstallEvent[]>(`/api/admin/events${openOnly ? "?open=true" : ""}`).then(setEvents).catch(e => setError(errorText(e)));
}, [openOnly]);
const shown = useMemo(() => (events || []).filter(e => matches(query, e.message, e.level, e.install?.name, e.install?.url)), [events, query]);
const paged = usePaged(shown, `${query}|${openOnly}`);
const [q, setQ] = useState("");
useEffect(() => { const t = setTimeout(() => setQ(query.trim()), 300); return () => clearTimeout(t); }, [query]);
const paged = useServerPaged<InstallEvent>("/api/admin/events", { open: openOnly ? "true" : "", q }, r => r.events as InstallEvent[]);
const events = paged.rows;
const error = paged.error;
return (
<>
@@ -32,13 +26,13 @@ export default function AlertsPage() {
<SearchInput className="w-full sm:ml-auto sm:w-72" value={query} onChange={setQuery} placeholder="Search alerts or install" />
</div>
{error && <p className="text-sm text-red-700">{error}</p>}
{!events ? <Loading /> : events.length === 0 ? <p className="text-sm text-slate-500">{openOnly ? "No open alerts. 🎉" : "Nothing yet."}</p> : (
{!events ? <Loading /> : events.length === 0 && !q ? <p className="text-sm text-slate-500">{openOnly ? "No open alerts. 🎉" : "Nothing yet."}</p> : (
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><th className="p-3">When</th><th className="p-3">Install</th><th className="p-3">What</th><th className="p-3">State</th></tr></thead>
<tbody>
{paged.rows.length === 0 && <tr><td colSpan={4} className="p-3 text-slate-500">No alerts match.</td></tr>}
{paged.rows.map(e => (
{events.length === 0 && <tr><td colSpan={4} className="p-3 text-slate-500">No alerts match.</td></tr>}
{events.map(e => (
<tr key={e.id} className="border-t align-top">
<td className="p-3 whitespace-nowrap text-xs text-slate-500">{fmtDate(e.createdAt)}</td>
<td className="p-3">{e.install ? <Link href={`/installs/${e.install.id}`} className="text-indigo-700 hover:underline">{e.install.name}</Link> : "—"}</td>
@@ -48,7 +42,7 @@ export default function AlertsPage() {
))}
</tbody>
</table>
<Pager {...paged} />
<Pager page={paged.page} pages={paged.pages} setPage={paged.setPage} total={paged.total} pageSize={paged.pageSize} />
</div>
)}
</>
+34 -19
View File
@@ -2,49 +2,64 @@
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { api, errorText } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { useServerPaged } from "@/lib/paging";
import { Loading, Message, PageTitle, Pager, SearchInput } from "@/components/ui";
import { ServersNav, StatusPill, type Job } from "@/components/servers";
const FILTERS = [
{ key: "", label: "All" },
{ key: "upcoming", label: "Planned and running" },
{ key: "failed", label: "Failed" },
{ key: "succeeded", label: "Succeeded" },
{ key: "failed,timed_out", label: "Failed" },
{ key: "rolled_back", label: "Rolled back" },
{ key: "missed", label: "Missed" },
{ key: "refused", label: "Refused" },
{ key: "cancelled", label: "Cancelled" },
];
/** Every job sent to a server's agent, newest first (§11: the full report is on each job). */
const TYPES = ["", "install", "add-product", "deploy", "adopt", "adopt-undo", "export", "uninstall", "purge", "seed-demo", "restart", "status", "check-ports", "update-agent"];
const PRODUCTS = [{ key: "", label: "Every product" }, { key: "events", label: "Cross Events" }, { key: "accounts", label: "Accounts" }];
/** Every job sent to a server's agent, newest first, a page at a time (§11: the full report is on each job). */
export default function JobsPage() {
const [filter, setFilter] = useState("");
const [jobs, setJobs] = useState<Job[] | null>(null);
const [err, setErr] = useState<string | null>(null);
useEffect(() => {
const q = filter === "upcoming" ? "?upcoming=true" : filter ? `?status=${filter}` : "";
setJobs(null);
api<{ jobs: Job[] }>(`/api/admin/jobs${q}`).then(r => setJobs(r.jobs)).catch(e => setErr(errorText(e)));
}, [filter]);
const [type, setType] = useState("");
const [product, setProduct] = useState("");
const [query, setQuery] = useState("");
const [q, setQ] = useState("");
// Searching asks the server, so wait for a pause in typing.
useEffect(() => { const t = setTimeout(() => setQ(query.trim()), 300); return () => clearTimeout(t); }, [query]);
const params = { ...(filter === "upcoming" ? { upcoming: "true" } : filter ? { status: filter } : {}), type, product, q };
const paged = useServerPaged<Job>("/api/admin/jobs", params, r => r.jobs as Job[]);
const jobs = paged.rows;
return (
<div>
<PageTitle title="Jobs" subtitle="Installs, updates, adopts, exports, uninstalls and checks run by the agents." />
<ServersNav active="/jobs" />
{err && <Message msg={{ type: "err", text: err }} />}
<div className="mb-4 flex flex-wrap gap-2">{FILTERS.map(f => <button key={f.key} className={filter === f.key ? "btn-primary" : "btn-secondary"} onClick={() => setFilter(f.key)}>{f.label}</button>)}</div>
{paged.error && <Message msg={{ type: "err", text: paged.error }} />}
<div className="mb-3 flex flex-wrap gap-2">{FILTERS.map(f => <button key={f.key} className={filter === f.key ? "btn-primary" : "btn-secondary"} onClick={() => setFilter(f.key)}>{f.label}</button>)}</div>
<div className="mb-4 grid gap-2 md:grid-cols-3">
<SearchInput value={query} onChange={setQuery} placeholder="Search a church or domain" />
<select className="input" aria-label="Product" value={product} onChange={e => setProduct(e.target.value)}>{PRODUCTS.map(p => <option key={p.key} value={p.key}>{p.label}</option>)}</select>
<select className="input" aria-label="Job type" value={type} onChange={e => setType(e.target.value)}>{TYPES.map(t => <option key={t} value={t}>{t || "Every job type"}</option>)}</select>
</div>
{!jobs ? <Loading /> : (
<div className="card overflow-x-auto">
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Job</th><th>Server</th><th>Install</th><th>When</th><th>Status</th><th>Result</th></tr></thead>
<thead><tr className="text-left text-xs text-slate-500"><th className="px-4 py-2">Job</th><th>Server</th><th>Install</th><th>When</th><th>Status</th><th>Result</th></tr></thead>
<tbody>{jobs.map(j => (
<tr key={j.id} className="border-t">
<td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link>{j.emergency && <span className="ml-1 text-xs text-red-700">emergency</span>}</td>
<td>{j.server?.name}</td><td>{j.deployment?.shortName || String(j.args?.church || "–")}</td><td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td>
<td className="max-w-sm truncate text-xs text-slate-500">{j.message}</td>
<td className="px-4 py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link>{j.emergency && <span className="ml-1 text-xs text-red-700">emergency</span>}</td>
<td>{j.server?.name}</td>
<td>{j.deployment?.shortName || String(j.args?.church || "–")}{j.deployment?.product && <span className="ml-1 text-xs text-slate-500">{j.deployment.product}</span>}</td>
<td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td>
<td className="max-w-sm truncate pr-4 text-xs text-slate-500">{j.message}</td>
</tr>
))}</tbody>
</table>
{!jobs.length && <p className="mt-2 text-sm text-slate-500">No jobs.</p>}
{!jobs.length && <p className="px-4 py-3 text-sm text-slate-500">No jobs.</p>}
<Pager page={paged.page} pages={paged.pages} setPage={paged.setPage} total={paged.total} pageSize={paged.pageSize} />
</div>
)}
</div>
+6 -2
View File
@@ -6,7 +6,8 @@ import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import { PRODUCTS, PRODUCT_NAMES, type Product } from "@/lib/products";
import type { Release, ReleaseSource } from "@/lib/types";
import { Badge, Loading, Message, PageTitle, ReleaseNotes } from "@/components/ui";
import { usePaged } from "@/lib/paging";
import { Badge, Loading, Message, PageTitle, Pager, ReleaseNotes } from "@/components/ui";
type Msg = { type: "ok" | "err"; text: string } | null;
type Form = { product: Product; version: string; notes: string; urgent: boolean; releasedAt: string };
@@ -156,6 +157,8 @@ export default function ReleasesPage() {
const fromGit = useMemo(() => new Set((state?.releaseSources || []).map(s => s.product)), [state]);
const manual = PRODUCTS.filter(p => !fromGit.has(p));
const shown = (releases || []).filter(r => filter === "all" || r.product === filter);
// Hub 2.6.0: a page at a time.
const paged = usePaged(shown, filter, 15);
const body = (f: Form) => ({ product: f.product, version: f.version, notes: f.notes, urgent: f.urgent, releasedAt: f.releasedAt ? `${f.releasedAt}T12:00:00+02:00` : null });
@@ -207,7 +210,7 @@ export default function ReleasesPage() {
{!releases ? <Loading /> : shown.length === 0 ? <p className="text-sm text-slate-500">No releases yet{filter === "all" ? "" : ` for ${PRODUCT_NAMES[filter]}`}.</p> : (
<div className="space-y-4">
{shown.map(r => (
{paged.rows.map(r => (
<div key={r.id} className="card">
{editing === r.id ? (
<ReleaseForm initial={{ product: r.product, version: r.version, notes: r.notes, urgent: r.urgent, releasedAt: r.releasedAt.slice(0, 10) }} products={null} busy={busy} onSave={f => save(f, r.id)} onCancel={() => setEditing(null)} />
@@ -235,6 +238,7 @@ export default function ReleasesPage() {
)}
</div>
))}
<div className="card p-0"><Pager {...paged} /></div>
</div>
)}
</>
+11 -6
View File
@@ -6,7 +6,8 @@ import { useParams, useRouter } from "next/navigation";
import { Plus, Trash2 } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, bytes, fmtDate } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { useServerPaged } from "@/lib/paging";
import { Loading, Message, PageTitle, Pager } from "@/components/ui";
import { PercentChart, ServersNav, StatusPill, pct, type Deployment, type Job, type ServerSummary } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
@@ -66,6 +67,8 @@ export default function ServerPage() {
const { id } = useParams<{ id: string }>();
const router = useRouter();
const [d, setD] = useState<Detail | null>(null);
// Hub 2.6.0: every job on this server, a page at a time (it showed the last 25).
const jobsPaged = useServerPaged<Job>("/api/admin/jobs", { serverId: String(id) }, r => r.jobs as Job[], 20);
const [range, setRange] = useState<"24h" | "7d" | "90d">("24h");
const [msg, setMsg] = useState<Msg>(null);
const [agentVersion, setAgentVersion] = useState("");
@@ -126,7 +129,8 @@ export default function ServerPage() {
</div>
<div className="card space-y-2 text-sm">
<h2 className="font-medium">Actions</h2>
<button className="btn-secondary w-full" onClick={() => job("status")}>Check status now</button>
<button className="btn-secondary w-full" onClick={() => job("status")}>Check status and find installs</button>
<p className="text-xs text-slate-500">Asks the agent what&apos;s on the server. A site added there without the Hub (crosscode add, or by hand) is added to Installs and tied to its registration. It also runs by itself once a day when a registered site has no install record here.</p>
<div className="flex gap-2"><input className="input" placeholder="agent@1.0.1" value={agentVersion} onChange={e => setAgentVersion(e.target.value)} aria-label="Agent version" /><button className="btn-secondary" disabled={!agentVersion} onClick={() => job("update-agent", { version: agentVersion })}>Update agent</button></div>
<button className="btn-danger w-full" onClick={remove}><Trash2 className="h-4 w-4" /> Remove server</button>
</div>
@@ -157,12 +161,13 @@ export default function ServerPage() {
</div>
)}
<div className="card overflow-x-auto">
<h2 className="font-medium">Recent jobs</h2>
<div className="card overflow-x-auto p-0">
<h2 className="px-5 pt-5 font-medium">Jobs</h2>
<table className="mt-3 w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Job</th><th>When</th><th>Status</th><th>Result</th></tr></thead>
<tbody>{d.jobs.map(j => <tr key={j.id} className="border-t"><td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link> <span className="text-xs text-slate-500">{String(j.args?.church || "")}</span></td><td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td><td className="max-w-md truncate text-xs text-slate-500">{j.message}</td></tr>)}</tbody>
<thead><tr className="text-left text-xs text-slate-500"><th className="px-5 py-1">Job</th><th>When</th><th>Status</th><th>Result</th></tr></thead>
<tbody>{(jobsPaged.rows ?? d.jobs).map(j => <tr key={j.id} className="border-t"><td className="px-5 py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link> <span className="text-xs text-slate-500">{String(j.args?.church || "")}</span></td><td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td><td className="max-w-md truncate pr-5 text-xs text-slate-500">{j.message}</td></tr>)}</tbody>
</table>
<Pager page={jobsPaged.page} pages={jobsPaged.pages} setPage={jobsPaged.setPage} total={jobsPaged.total} pageSize={jobsPaged.pageSize} />
</div>
</div>
);
@@ -4,13 +4,16 @@ import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { api, errorText } from "@/lib/api";
import { bytes, fmtDate } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { ago, bytes, fmtDate } from "@/lib/format";
import { useServerPaged } from "@/lib/paging";
import { PRODUCT_NAMES } from "@/lib/products";
import type { Release } from "@/lib/types";
import { Loading, Message, PageTitle, Pager } from "@/components/ui";
import { ServersNav, StatusPill, toInput, fromInput, type Deployment, type Job, type ServerSummary } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
type Detail = {
deployment: Deployment & { server: ServerSummary; jobs: Job[]; exports: { id: string; bytes: number; expiresAt: string; downloadedAt: string | null; deletedAt: string | null }[]; install: { version: string | null; url: string } | null };
deployment: Deployment & { server: ServerSummary; jobs: Job[]; exports: { id: string; bytes: number; expiresAt: string; downloadedAt: string | null; deletedAt: string | null }[]; install: { version: string | null; url: string; lastHeartbeatAt: string | null } | null };
fastPanel: string;
canRemoveRecord: boolean;
};
@@ -30,8 +33,16 @@ export default function DeploymentPage() {
const [un, setUn] = useState({ at: toInput(new Date(Date.now() + 7 * 24 * H)), totp: "", confirm: "" });
const [demo, setDemo] = useState({ profile: "events", confirm: "", markConfirm: "" });
const load = useCallback(() => api<Detail>(`/api/admin/deployments/${id}`).then(setD).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]);
const [releases, setReleases] = useState<Release[]>([]);
// Hub 2.6.0: every job of this install, a page at a time (it showed the last 50).
const jobsPaged = useServerPaged<Job>("/api/admin/jobs", { deploymentId: String(id) }, r => r.jobs as Job[], 20);
const load = useCallback(() => {
jobsPaged.reload();
return api<Detail>(`/api/admin/deployments/${id}`).then(setD).catch(e => setMsg({ type: "err", text: errorText(e) }));
// eslint-disable-next-line react-hooks/exhaustive-deps -- reload is a fresh function each render
}, [id]);
useEffect(() => { load(); }, [load]);
useEffect(() => { api<Release[]>("/api/admin/releases").then(setReleases).catch(() => {}); }, []);
const act = async (path: string, body: unknown, ok: string) => {
setMsg(null);
@@ -70,6 +81,12 @@ export default function DeploymentPage() {
<PageTitle title={`${x.customer?.name} (${x.shortName})`} subtitle={<>{x.domain} · on <Link className="text-indigo-700 hover:underline" href={`/servers/${x.serverId}`}>{x.server.name}</Link> · ports web {x.webPort}, api {x.apiPort} · version {x.install?.version || x.version || "–"} <StatusPill status={x.status} /></>} />
<ServersNav active="/servers/installs" />
<Message msg={msg} />
{/* Hub 2.6.0: whether the site has registered with the Hub (its banners, licence and heartbeats need it). */}
<p className="mt-2 text-sm text-slate-600">
{x.install
? <>Registered site: <a className="text-indigo-700 hover:underline" href={x.install.url} target="_blank" rel="noreferrer">{x.install.url}</a>, last heartbeat {x.install.lastHeartbeatAt ? ago(x.install.lastHeartbeatAt) : "never"}.</>
: <span className="text-amber-800">The site hasn&apos;t registered with the Hub yet. It registers by itself with its licence key when it starts, and is tied to this record at its first heartbeat; if that doesn&apos;t happen, check its HUB_URL and HUB_LICENCE_KEY.</span>}
</p>
{!!problems.length && <ul className="mt-2 list-disc pl-6 text-sm text-red-800">{problems.map(p => <li key={p}>{p}</li>)}</ul>}
</div>
@@ -83,9 +100,15 @@ export default function DeploymentPage() {
)}
{x.status === "live" && (
<form className="card grid gap-3 md:grid-cols-2" onSubmit={e => { e.preventDefault(); act("/api/admin/updates", { deploymentIds: [x.id], version: upd.version || undefined, at: fromInput(upd.at), emergency: upd.emergency, reason: upd.reason || null, totp: upd.totp || null }, "Planned. The site admin was emailed and sees a banner."); }}>
<form className="card grid gap-3 md:grid-cols-2" onSubmit={e => { e.preventDefault(); act("/api/admin/updates", { deploymentIds: [x.id], product: x.product, version: upd.version || undefined, at: fromInput(upd.at), emergency: upd.emergency, reason: upd.reason || null, totp: upd.totp || null }, "Planned. The site admin was emailed and sees a banner."); }}>
<h2 className="font-medium md:col-span-2">Schedule an update</h2>
<div><label className="label" htmlFor="u-v">Release</label><input id="u-v" className="input" placeholder="latest" value={upd.version} onChange={e => setUpd({ ...upd, version: e.target.value })} /></div>
<div>
<label className="label" htmlFor="u-v">{PRODUCT_NAMES[x.product as keyof typeof PRODUCT_NAMES] || x.product} release</label>
<select id="u-v" className="input" value={upd.version} onChange={e => setUpd({ ...upd, version: e.target.value })}>
<option value="">Latest</option>
{releases.filter(r => r.product === x.product).map(r => <option key={r.id} value={r.version}>{r.version}{r.latest ? " (latest)" : ""}{r.requires?.length ? ` · needs ${r.requires.map(q => `${PRODUCT_NAMES[q.product]} ${q.version}`).join(", ")}` : ""}</option>)}
</select>
</div>
<div><label className="label" htmlFor="u-at">When</label><input id="u-at" type="datetime-local" className="input" value={upd.at} min={toInput(new Date(Date.now() + minAt))} onChange={e => setUpd({ ...upd, at: e.target.value })} /><p className="mt-1 text-xs text-slate-500">At least {upd.emergency ? "15 minutes" : "4 hours"} away, so the church gets notice.</p></div>
<label className="flex items-center gap-2 text-sm md:col-span-2"><input type="checkbox" checked={upd.emergency} onChange={e => setUpd({ ...upd, emergency: e.target.checked })} /> Emergency (security fix or broken release): 15 minutes&apos; notice, a reason and your two-factor code</label>
{upd.emergency && <>
@@ -138,18 +161,19 @@ export default function DeploymentPage() {
</div>
)}
<div className="card overflow-x-auto">
<h2 className="font-medium">Jobs</h2>
<div className="card overflow-x-auto p-0">
<h2 className="px-5 pt-5 font-medium">Jobs</h2>
<table className="mt-3 w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Job</th><th>When</th><th>Status</th><th>Result</th><th /></tr></thead>
<tbody>{x.jobs.map(j => (
<thead><tr className="text-left text-xs text-slate-500"><th className="px-5 py-1">Job</th><th>When</th><th>Status</th><th>Result</th><th /></tr></thead>
<tbody>{(jobsPaged.rows ?? x.jobs).map(j => (
<tr key={j.id} className="border-t">
<td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link>{j.emergency && <span className="ml-1 text-xs text-red-700">emergency</span>}</td>
<td className="px-5 py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link>{j.emergency && <span className="ml-1 text-xs text-red-700">emergency</span>}</td>
<td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td><td className="max-w-md truncate text-xs text-slate-500">{j.message}</td>
<td>{["queued", "scheduled"].includes(j.status) && <button className="btn-secondary px-2 py-1 text-xs" onClick={() => act(`/api/admin/jobs/${j.id}/cancel`, {}, "Cancelled; the church was told.")}>Cancel</button>}</td>
<td className="pr-5">{["queued", "scheduled"].includes(j.status) && <button className="btn-secondary px-2 py-1 text-xs" onClick={() => act(`/api/admin/jobs/${j.id}/cancel`, {}, "Cancelled; the church was told.")}>Cancel</button>}</td>
</tr>
))}</tbody>
</table>
<Pager page={jobsPaged.page} pages={jobsPaged.pages} setPage={jobsPaged.setPage} total={jobsPaged.total} pageSize={jobsPaged.pageSize} />
</div>
{!!x.exports.length && (
@@ -1,12 +1,14 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Link2, Plus } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { matches, usePaged } from "@/lib/paging";
import { PRODUCT_NAMES } from "@/lib/products";
import { Loading, Message, PageTitle, Pager, SearchInput } from "@/components/ui";
import { ServersNav, StatusPill, pct, type Deployment, type ServerSummary } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
@@ -20,6 +22,11 @@ const emptyLink = { installId: "", serverId: "", shortName: "", webPort: "", api
export default function InstallsPage() {
const router = useRouter();
const [list, setList] = useState<Deployment[] | null>(null);
// Hub 2.6.0: which product each install is, a filter for it, a search, and a page at a time.
const [product, setProduct] = useState("");
const [query, setQuery] = useState("");
const shown = useMemo(() => (list || []).filter(d => (!product || d.product === product) && matches(query, d.customer?.name, d.shortName, d.domain, d.server?.name)), [list, product, query]);
const paged = usePaged(shown, `${product}|${query}`);
const [srv, setSrv] = useState<ServerSummary[]>([]);
const [customers, setCustomers] = useState<Customer[]>([]);
const [installs, setInstalls] = useState<InstallRow[]>([]);
@@ -138,14 +145,23 @@ export default function InstallsPage() {
)}
{!list ? <Loading /> : (
<div className="card overflow-x-auto">
<div className="card overflow-x-auto p-0">
<div className="flex flex-wrap gap-2 p-4">
<select className="input w-48" aria-label="Product" value={product} onChange={e => setProduct(e.target.value)}>
<option value="">Every product</option>
<option value="events">{PRODUCT_NAMES.events}</option>
<option value="accounts">{PRODUCT_NAMES.accounts}</option>
</select>
<SearchInput className="w-full sm:w-72" value={query} onChange={setQuery} placeholder="Search a church, domain or server" />
</div>
<table className="w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Church</th><th>Domain</th><th>Server</th><th>Version</th><th>Last heartbeat</th><th>Status</th></tr></thead>
<tbody>{list.map(d => (
<tr key={d.id} className="border-t"><td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/servers/installs/${d.id}`}>{d.customer?.name} ({d.shortName})</Link>{d.isDemo && <span className="ml-1 rounded bg-sky-100 px-1.5 text-xs text-sky-800">demo</span>}</td><td>{d.domain}</td><td>{d.server?.name}</td><td>{d.install?.version || d.version || "–"}</td><td>{ago(d.install?.lastHeartbeatAt)}</td><td><StatusPill status={d.status} /></td></tr>
<thead><tr className="text-left text-xs text-slate-500"><th className="px-4 py-1">Church</th><th>Product</th><th>Domain</th><th>Server</th><th>Version</th><th>Last heartbeat</th><th>Status</th></tr></thead>
<tbody>{paged.rows.map(d => (
<tr key={d.id} className="border-t"><td className="px-4 py-1.5"><Link className="text-indigo-700 hover:underline" href={`/servers/installs/${d.id}`}>{d.customer?.name} ({d.shortName})</Link>{d.isDemo && <span className="ml-1 rounded bg-sky-100 px-1.5 text-xs text-sky-800">demo</span>}</td><td>{PRODUCT_NAMES[d.product as keyof typeof PRODUCT_NAMES] || d.product}</td><td>{d.domain}</td><td>{d.server?.name}</td><td>{d.install?.version || d.version || "–"}</td><td>{d.installId ? ago(d.install?.lastHeartbeatAt) : <span className="text-amber-800">not registered</span>}</td><td><StatusPill status={d.status} /></td></tr>
))}</tbody>
</table>
{!list.length && <p className="mt-2 text-sm text-slate-500">No installs on servers yet.</p>}
{!list.length ? <p className="px-4 py-3 text-sm text-slate-500">No installs on servers yet.</p> : !shown.length && <p className="px-4 py-3 text-sm text-slate-500">No installs match.</p>}
<Pager {...paged} />
</div>
)}
</div>
+5 -2
View File
@@ -5,7 +5,8 @@ import Link from "next/link";
import { Copy, Plus } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, bytes } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { usePaged } from "@/lib/paging";
import { Loading, Message, PageTitle, Pager } from "@/components/ui";
import { ServersNav, StatusPill, pct, type ServerSummary } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
@@ -13,6 +14,7 @@ type Msg = { type: "ok" | "err"; text: string } | null;
/** Hub → Servers: every server with its agent, resources and sites; Add server (§3, §10). */
export default function ServersPage() {
const [list, setList] = useState<ServerSummary[] | null>(null);
const paged = usePaged(list || [], null, 20);
const [msg, setMsg] = useState<Msg>(null);
const [adding, setAdding] = useState(false);
const [name, setName] = useState("");
@@ -67,7 +69,7 @@ export default function ServersPage() {
{!list ? <Loading /> : list.length === 0 ? <p className="text-sm text-slate-500">No servers yet. Add one to install churches from the Hub.</p> : (
<div className="grid gap-4 md:grid-cols-2">
{list.map(s => {
{paged.rows.map(s => {
const disk = s.disk.reduce((m, d) => Math.max(m, d.totalBytes ? (d.usedBytes / d.totalBytes) * 100 : 0), 0);
return (
<Link key={s.id} href={`/servers/${s.id}`} className="card block hover:border-indigo-300">
@@ -99,6 +101,7 @@ export default function ServersPage() {
})}
</div>
)}
{list && <div className="mt-4"><Pager {...paged} /></div>}
</div>
);
}
@@ -4,7 +4,8 @@ import React, { useCallback, useEffect, useState } from "react";
import { Plus, Trash2 } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { usePaged } from "@/lib/paging";
import { Loading, Message, PageTitle, Pager } from "@/components/ui";
import { ServersNav } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
@@ -13,6 +14,7 @@ type Port = { port: number; role: string; note: string | null; releasedAt: strin
/** The port list (§6) and the install defaults (§5): the same for every install. */
export default function ServerSettingsPage() {
const [ports, setPorts] = useState<Port[] | null>(null);
const portsPaged = usePaged(ports || [], null, 30);
const [range, setRange] = useState({ from: "20000", to: "29999" });
const [defaults, setDefaults] = useState<[string, string][]>([]);
const [ip, setIp] = useState("");
@@ -77,12 +79,13 @@ export default function ServerSettingsPage() {
{!ports ? <Loading /> : (
<table className="mt-3 w-full text-sm tabular-nums">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Port</th><th>Use</th><th>Server</th><th>Note</th><th /></tr></thead>
<tbody>{ports.map(p => (
<tbody>{portsPaged.rows.map(p => (
<tr key={p.port} className="border-t"><td className="py-1.5">{p.port}</td><td>{p.releasedAt ? `free from ${fmtDate(new Date(new Date(p.releasedAt).getTime() + 30 * 24 * 3600 * 1000), false)}` : p.role}</td><td>{p.server?.name || "–"}</td><td className="text-xs text-slate-500">{p.note}</td>
<td>{(p.role === "taken" || p.releasedAt) && <button className="btn-secondary px-2 py-1 text-xs" onClick={() => free(p.port)}>Remove</button>}</td></tr>
))}</tbody>
</table>
)}
{ports && <Pager {...portsPaged} />}
</div>
</div>
);
+60 -22
View File
@@ -4,68 +4,105 @@ import React, { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { api, errorText } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { usePaged } from "@/lib/paging";
import { PRODUCT_NAMES } from "@/lib/products";
import type { Release } from "@/lib/types";
import { Loading, Message, PageTitle, Pager, Tabs } from "@/components/ui";
import { ServersNav, StatusPill, toInput, fromInput, type Deployment, type Job } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
const H = 60 * 60 * 1000;
/** Products the Hub updates on servers. */
const UPDATABLE = ["events", "accounts"] as const;
type Updatable = (typeof UPDATABLE)[number];
const versionOf = (d: Deployment) => d.install?.version || d.version || "?";
/**
* Updates (§8): one release to several installs at one time with one notice. They run one at a
* time, and the batch stops at the first failure (the rest are told it's postponed).
* Updates (§8): one release of **one product** to several installs at one time with one notice.
* They run one at a time, and the batch stops at the first failure (the rest are told it's
* postponed). Hub 2.6.0: the product is chosen first, so only its installs and its own releases are
* offered; a Cross Events update says what happens to each church's Accounts.
*/
export default function UpdatesPage() {
const [deployments, setDeployments] = useState<Deployment[] | null>(null);
const [product, setProduct] = useState<Updatable>("events");
const [all, setAll] = useState<Deployment[] | null>(null);
const [releases, setReleases] = useState<Release[]>([]);
const [upcoming, setUpcoming] = useState<Job[]>([]);
const [chosen, setChosen] = useState<string[]>([]);
const [form, setForm] = useState({ version: "", at: toInput(new Date(Date.now() + 5 * H)), emergency: false, reason: "", totp: "" });
const [msg, setMsg] = useState<Msg>(null);
const load = useCallback(() => {
api<{ deployments: Deployment[] }>("/api/admin/deployments?status=live").then(r => setDeployments(r.deployments)).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<{ jobs: Job[] }>("/api/admin/jobs?upcoming=true").then(r => setUpcoming(r.jobs)).catch(() => {});
api<{ deployments: Deployment[] }>("/api/admin/deployments?status=live").then(r => setAll(r.deployments)).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<Release[]>("/api/admin/releases").then(setReleases).catch(() => {});
api<{ jobs: Job[] }>("/api/admin/jobs?upcoming=true&pageSize=200").then(r => setUpcoming(r.jobs)).catch(() => {});
}, []);
useEffect(() => { load(); }, [load]);
const byVersion = useMemo(() => [...new Set((deployments || []).map(d => d.install?.version || d.version || "?"))].sort(), [deployments]);
const deployments = useMemo(() => (all || []).filter(d => d.product === product), [all, product]);
const ownReleases = useMemo(() => releases.filter(r => r.product === product), [releases, product]);
const latest = ownReleases.find(r => r.latest)?.version;
const byVersion = useMemo(() => [...new Set(deployments.map(versionOf))].sort(), [deployments]);
const upcomingPaged = usePaged(upcoming, upcoming.length, 20);
// Another product: nothing chosen carries over, and the release starts at "latest".
const pick = (p: Updatable) => {
setProduct(p);
setChosen([]);
setForm(f => ({ ...f, version: "" }));
setMsg(null);
};
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setMsg(null);
try {
const r = await api<{ jobs: Job[]; warnings: string[] }>("/api/admin/updates", { method: "POST", body: { deploymentIds: chosen, version: form.version || undefined, at: fromInput(form.at), emergency: form.emergency, reason: form.reason || null, totp: form.totp || null } });
setMsg({ type: "ok", text: `Planned for ${r.jobs.length} install(s); each church was emailed and sees a banner.${r.warnings.length ? ` Note: ${r.warnings.join(" ")}` : ""}` });
const r = await api<{ jobs: Job[]; warnings: string[] }>("/api/admin/updates", { method: "POST", body: { deploymentIds: chosen, product, version: form.version || undefined, at: fromInput(form.at), emergency: form.emergency, reason: form.reason || null, totp: form.totp || null } });
const deploys = r.jobs.filter(j => j.type === "deploy").length;
const installs = r.jobs.length - deploys;
setMsg({ type: "ok", text: `Planned for ${deploys} install(s)${installs ? `, with ${installs} Accounts install(s) first` : ""}; each church was emailed and sees a banner.${r.warnings.length ? ` Note: ${r.warnings.join(" ")}` : ""}` });
setChosen([]);
load();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const name = PRODUCT_NAMES[product];
return (
<div className="space-y-6">
<div>
<PageTitle title="Updates" subtitle="Plan a release for one or more installs. Churches get an email and a banner now, and a reminder an hour before." />
<PageTitle title="Updates" subtitle="Plan a release for one or more installs of one product. Churches get an email and a banner now, and a reminder an hour before." />
<ServersNav active="/servers/updates" />
<Message msg={msg} />
</div>
{!deployments ? <Loading /> : (
{!all ? <Loading /> : (
<form className="card space-y-4" onSubmit={submit}>
<Tabs tabs={UPDATABLE.map(p => ({ key: p, label: `${PRODUCT_NAMES[p]} (${(all || []).filter(d => d.product === p).length})` }))} active={product} onChange={pick} />
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="text-slate-500">Select:</span>
<button type="button" className="btn-secondary px-2 py-1 text-xs" onClick={() => setChosen(deployments.map(d => d.id))}>All live ({deployments.length})</button>
{byVersion.map(v => <button key={v} type="button" className="btn-secondary px-2 py-1 text-xs" onClick={() => setChosen(deployments.filter(d => (d.install?.version || d.version || "?") === v).map(d => d.id))}>On {v}</button>)}
<button type="button" className="btn-secondary px-2 py-1 text-xs" onClick={() => setChosen(deployments.map(d => d.id))}>All live {name} ({deployments.length})</button>
{byVersion.map(v => <button key={v} type="button" className="btn-secondary px-2 py-1 text-xs" onClick={() => setChosen(deployments.filter(d => versionOf(d) === v).map(d => d.id))}>On {name} {v}</button>)}
<button type="button" className="btn-secondary px-2 py-1 text-xs" onClick={() => setChosen([])}>None</button>
</div>
<div className="max-h-72 space-y-1 overflow-y-auto rounded-lg border border-slate-200 p-3">
{deployments.map(d => (
<label key={d.id} className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={chosen.includes(d.id)} onChange={() => setChosen(chosen.includes(d.id) ? chosen.filter(x => x !== d.id) : [...chosen, d.id])} />
<span className="font-medium">{d.customer?.name}</span><span className="text-slate-500">{d.domain} · {d.install?.version || d.version || "?"} · {d.server?.name}</span>
<span className="font-medium">{d.customer?.name}</span><span className="text-slate-500">{d.domain} · {name} {versionOf(d)} · {d.server?.name}</span>
</label>
))}
{!deployments.length && <p className="text-sm text-slate-500">No live installs on servers.</p>}
{!deployments.length && <p className="text-sm text-slate-500">No live {name} installs on servers.</p>}
</div>
<div className="grid gap-3 md:grid-cols-2">
<div><label className="label" htmlFor="b-v">Release</label><input id="b-v" className="input" placeholder="latest" value={form.version} onChange={e => setForm({ ...form, version: e.target.value })} /></div>
<div>
<label className="label" htmlFor="b-v">{name} release</label>
<select id="b-v" className="input" value={form.version} onChange={e => setForm({ ...form, version: e.target.value })}>
<option value="">Latest{latest ? ` (${latest})` : ""}</option>
{ownReleases.map(r => <option key={r.id} value={r.version}>{r.version}{r.latest ? " (latest)" : ""}{r.requires?.length ? ` · needs ${r.requires.map(q => `${PRODUCT_NAMES[q.product]} ${q.version}`).join(", ")}` : ""}</option>)}
</select>
{product === "events" && <p className="mt-1 text-xs text-slate-500">Each church&apos;s Accounts stays on its version, unless this release needs a newer one: then it&apos;s updated first in the same deploy, or installed first if the church has none. The confirmation lists what happens.</p>}
</div>
<div><label className="label" htmlFor="b-at">When</label><input id="b-at" type="datetime-local" className="input" value={form.at} onChange={e => setForm({ ...form, at: e.target.value })} /><p className="mt-1 text-xs text-slate-500">At least {form.emergency ? "15 minutes" : "4 hours"} away. They run one at a time from then.</p></div>
<label className="flex items-center gap-2 text-sm md:col-span-2"><input type="checkbox" checked={form.emergency} onChange={e => setForm({ ...form, emergency: e.target.checked })} /> Emergency: 15 minutes&apos; notice, with a reason and your two-factor code</label>
{form.emergency && <>
@@ -73,17 +110,18 @@ export default function UpdatesPage() {
<div><label className="label" htmlFor="b-t">Two-factor code</label><input id="b-t" className="input" inputMode="numeric" autoComplete="one-time-code" required value={form.totp} onChange={e => setForm({ ...form, totp: e.target.value })} /></div>
</>}
</div>
<button className="btn-primary" disabled={!chosen.length}>Plan the update for {chosen.length} install(s)</button>
<button className="btn-primary" disabled={!chosen.length}>Plan the {name} update for {chosen.length} install(s)</button>
</form>
)}
<div className="card overflow-x-auto">
<h2 className="font-medium">Planned and running</h2>
<div className="card overflow-x-auto p-0">
<h2 className="px-5 pt-5 font-medium">Planned and running</h2>
<table className="mt-3 w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Job</th><th>Install</th><th>When</th><th>Status</th></tr></thead>
<tbody>{upcoming.map(j => <tr key={j.id} className="border-t"><td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link>{j.batchId && <span className="ml-1 text-xs text-slate-500">batch</span>}{j.emergency && <span className="ml-1 text-xs text-red-700">emergency</span>}</td><td>{j.deployment?.shortName || "–"}</td><td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td></tr>)}</tbody>
<thead><tr className="text-left text-xs text-slate-500"><th className="px-5 py-1">Job</th><th>Install</th><th>When</th><th>Status</th></tr></thead>
<tbody>{upcomingPaged.rows.map(j => <tr key={j.id} className="border-t"><td className="px-5 py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link>{j.batchId && <span className="ml-1 text-xs text-slate-500">batch</span>}{j.emergency && <span className="ml-1 text-xs text-red-700">emergency</span>}</td><td>{j.deployment?.shortName || "–"}{j.deployment?.product && <span className="ml-1 text-xs text-slate-500">{j.deployment.product}</span>}</td><td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td></tr>)}</tbody>
</table>
{!upcoming.length && <p className="mt-2 text-sm text-slate-500">Nothing planned.</p>}
{!upcoming.length && <p className="px-5 pb-5 text-sm text-slate-500">Nothing planned.</p>}
<Pager {...upcomingPaged} />
</div>
</div>
);
+10 -9
View File
@@ -1,10 +1,10 @@
"use client";
import React, { useEffect, useMemo, useState } from "react";
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { api, errorText, setToken } from "@/lib/api";
import { fmtDate, rand, randFine } from "@/lib/format";
import { matches, usePaged } from "@/lib/paging";
import { useServerPaged } from "@/lib/paging";
import type { AiInstallUse } from "@/lib/types";
import { Loading, Message, PageTitle, Pager, SearchInput, Tabs } from "@/components/ui";
import { BillingSettings } from "@/components/billing/BillingSettings";
@@ -173,8 +173,12 @@ export default function SettingsPage() {
const [publicKey, setPublicKey] = useState("");
const [smtp, setSmtp] = useState(false);
const [aiModels, setAiModels] = useState<AiModel[]>([]);
const [audit, setAudit] = useState<AuditRow[]>([]);
const [auditQuery, setAuditQuery] = useState("");
const [auditQ, setAuditQ] = useState("");
useEffect(() => { const t = setTimeout(() => setAuditQ(auditQuery.trim()), 300); return () => clearTimeout(t); }, [auditQuery]);
// Hub 2.6.0: paged on the server (every entry, not the last 300).
const auditPaged = useServerPaged<AuditRow>("/api/admin/audit", { q: auditQ }, r => r.entries as AuditRow[], 30);
const audit = auditPaged.rows ?? [];
const [pw, setPw] = useState({ currentPassword: "", newPassword: "" });
const [msg, setMsg] = useState<Msg>(null);
const [smtpPass, setSmtpPass] = useState({ value: "", clear: false });
@@ -183,14 +187,11 @@ export default function SettingsPage() {
useEffect(() => {
api<{ settings: Settings; publicKey: string; smtp: boolean; aiModels: AiModel[] }>("/api/admin/settings").then(r => { setSettings(r.settings); setPublicKey(r.publicKey); setSmtp(r.smtp); setAiModels(r.aiModels || []); }).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<AuditRow[]>("/api/admin/audit").then(setAudit).catch(() => {});
// Open the tab named in the address (#email), so a reload or a link lands in the same place.
const fromHash = window.location.hash.slice(1);
if (TABS.some(t => t.key === fromHash)) setTab(fromHash as Tab);
}, []);
const auditShown = useMemo(() => audit.filter(a => matches(auditQuery, a.action.replace(/_/g, " "), a.actor?.name, a.target, a.metadata ? JSON.stringify(a.metadata) : "")), [audit, auditQuery]);
const auditPaged = usePaged(auditShown, auditQuery, 30);
if (!settings) return msg ? <Message msg={msg} /> : <Loading />;
@@ -331,9 +332,9 @@ export default function SettingsPage() {
<>
<SearchInput className="mb-3 w-full sm:w-72" value={auditQuery} onChange={setAuditQuery} placeholder="Search who or what" />
<div className="card p-0">
{audit.length === 0 ? <p className="p-5 text-sm text-slate-500">Nothing yet.</p> : auditShown.length === 0 ? <p className="p-5 text-sm text-slate-500">Nothing matches.</p> : (
{!auditPaged.rows ? <p className="p-5 text-sm text-slate-500">Loading…</p> : audit.length === 0 ? <p className="p-5 text-sm text-slate-500">{auditQ ? "Nothing matches." : "Nothing yet."}</p> : (
<ul className="space-y-1 p-5 text-sm">
{auditPaged.rows.map(a => (
{audit.map(a => (
<li key={a.id} className="flex flex-wrap gap-2">
<span className="w-40 shrink-0 text-xs text-slate-500">{fmtDate(a.createdAt)}</span>
<span className="font-medium">{a.actor?.name || "—"}</span>
@@ -343,7 +344,7 @@ export default function SettingsPage() {
))}
</ul>
)}
<Pager {...auditPaged} />
<Pager page={auditPaged.page} pages={auditPaged.pages} setPage={auditPaged.setPage} total={auditPaged.total} pageSize={auditPaged.pageSize} />
</div>
</>
)}
+1 -1
View File
@@ -31,7 +31,7 @@ export type Job = {
id: string; serverId: string; type: string; args: Record<string, unknown>; status: string; notBefore: string; expiresAt: string;
scheduled: boolean; emergency: boolean; reason: string | null; batchId: string | null; deliveredAt: string | null; finishedAt: string | null;
message: string | null; createdAt: string; deploymentId: string | null;
server?: { id: string; name: string }; deployment?: { id: string; shortName: string; domain: string } | null;
server?: { id: string; name: string }; deployment?: { id: string; shortName: string; domain: string; product?: string } | null;
report?: { status: string; steps: { name: string; startedAt: string; finishedAt: string | null; outcome: string; detail?: string }[]; result: Record<string, unknown>; log: string[]; message?: string } | null;
};
+27
View File
@@ -1,4 +1,5 @@
import { useEffect, useMemo, useState } from "react";
import { api, errorText } from "@/lib/api";
/** True when every word of the query appears in one of the fields (case-insensitive). */
export function matches(query: string, ...fields: (string | number | null | undefined)[]) {
@@ -20,3 +21,29 @@ export function usePaged<T>(items: T[], resetKey: unknown, pageSize = 25) {
const rows = useMemo(() => items.slice((current - 1) * pageSize, current * pageSize), [items, current, pageSize]);
return { rows, page: current, pages, setPage, total: items.length, pageSize };
}
/**
* A list paged on the server (Hub 2.6.0: jobs, alerts, the audit log). `path` without paging;
* `params` are the filters, and a change in them goes back to the first page. `pick` takes the
* rows out of the answer. `reload()` fetches the same page again.
*/
export function useServerPaged<T>(path: string, params: Record<string, string>, pick: (r: Record<string, unknown>) => T[], pageSize = 50) {
const [page, setPage] = useState(1);
const [data, setData] = useState<{ rows: T[]; total: number; pages: number } | null>(null);
const [error, setError] = useState<string | null>(null);
const [tick, setTick] = useState(0);
const key = JSON.stringify(params);
useEffect(() => { setPage(1); }, [key]);
useEffect(() => {
let alive = true;
const q = new URLSearchParams({ ...Object.fromEntries(Object.entries(params).filter(([, v]) => v !== "")), page: String(page), pageSize: String(pageSize) });
setError(null);
api<Record<string, unknown> & { total: number; pages: number }>(`${path}?${q}`)
.then(r => { if (alive) setData({ rows: pick(r), total: r.total, pages: r.pages }); })
.catch(e => { if (alive) setError(errorText(e)); });
return () => { alive = false; };
// eslint-disable-next-line react-hooks/exhaustive-deps -- `key` stands for `params`; `pick` is a fixed accessor
}, [path, key, page, pageSize, tick]);
const reload = () => setTick(t => t + 1);
return { rows: data?.rows ?? null, total: data?.total ?? 0, pages: data?.pages ?? 1, page, setPage, pageSize, error, reload };
}