diff --git a/CHANGELOG.md b/CHANGELOG.md index 72073a4..4aa05fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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.`) 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 diff --git a/backend/package-lock.json b/backend/package-lock.json index d08e0fb..59e9c11 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -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", diff --git a/backend/package.json b/backend/package.json index 13ea089..4517802 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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", diff --git a/backend/src/routes/admin.js b/backend/src/routes/admin.js index 2e94002..6bc26c2 100644 --- a/backend/src/routes/admin.js +++ b/backend/src/routes/admin.js @@ -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 ───────────────────────────────────────────────────────────────── diff --git a/backend/src/routes/installApi.js b/backend/src/routes/installApi.js index 0ba4dd5..a08ccca 100644 --- a/backend/src/routes/installApi.js +++ b/backend/src/routes/installApi.js @@ -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. diff --git a/backend/src/routes/servers.js b/backend/src/routes/servers.js index 51be17d..3f3cdcb 100644 --- a/backend/src/routes/servers.js +++ b/backend/src/routes/servers.js @@ -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); diff --git a/backend/src/utils/jobs.js b/backend/src/utils/jobs.js index eac9799..6cc7070 100644 --- a/backend/src/utils/jobs.js +++ b/backend/src/utils/jobs.js @@ -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, }; diff --git a/backend/src/utils/paging.js b/backend/src/utils/paging.js new file mode 100644 index 0000000..c0c5c6d --- /dev/null +++ b/backend/src/utils/paging.js @@ -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 }; diff --git a/backend/tests/fakeDb.js b/backend/tests/fakeDb.js index 9861946..1c73b5c 100644 --- a/backend/tests/fakeDb.js +++ b/backend/tests/fakeDb.js @@ -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)); }, diff --git a/backend/tests/servers.test.js b/backend/tests/servers.test.js index f073b5f..aec28d2 100644 --- a/backend/tests/servers.test.js +++ b/backend/tests/servers.test.js @@ -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); + }); +}); diff --git a/frontend/package-lock.json b/frontend/package-lock.json index d9776c8..110b9d5 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -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", diff --git a/frontend/package.json b/frontend/package.json index adf248c..764d69d 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-frontend", - "version": "2.5.0", + "version": "2.6.0", "private": true, "scripts": { "dev": "next dev -p 3200", diff --git a/frontend/src/app/(hub)/alerts/page.tsx b/frontend/src/app/(hub)/alerts/page.tsx index d62bb1f..f682950 100644 --- a/frontend/src/app/(hub)/alerts/page.tsx +++ b/frontend/src/app/(hub)/alerts/page.tsx @@ -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(null); - const [error, setError] = useState(null); const [query, setQuery] = useState(""); - - useEffect(() => { - setEvents(null); - api(`/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("/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() { {error &&

{error}

} - {!events ? : events.length === 0 ?

{openOnly ? "No open alerts. 🎉" : "Nothing yet."}

: ( + {!events ? : events.length === 0 && !q ?

{openOnly ? "No open alerts. 🎉" : "Nothing yet."}

: (
- {paged.rows.length === 0 && } - {paged.rows.map(e => ( + {events.length === 0 && } + {events.map(e => ( @@ -48,7 +42,7 @@ export default function AlertsPage() { ))}
WhenInstallWhatState
No alerts match.
No alerts match.
{fmtDate(e.createdAt)} {e.install ? {e.install.name} : "—"}
- +
)} diff --git a/frontend/src/app/(hub)/jobs/page.tsx b/frontend/src/app/(hub)/jobs/page.tsx index 728e810..f4df554 100644 --- a/frontend/src/app/(hub)/jobs/page.tsx +++ b/frontend/src/app/(hub)/jobs/page.tsx @@ -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(null); - const [err, setErr] = useState(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("/api/admin/jobs", params, r => r.jobs as Job[]); + const jobs = paged.rows; return (
- {err && } -
{FILTERS.map(f => )}
+ {paged.error && } +
{FILTERS.map(f => )}
+
+ + + +
{!jobs ? : ( -
+
- + {jobs.map(j => ( - - - + + + + + ))}
JobServerInstallWhenStatusResult
JobServerInstallWhenStatusResult
{j.type}{j.emergency && emergency}{j.server?.name}{j.deployment?.shortName || String(j.args?.church || "–")}{fmtDate(j.notBefore)}{j.message}{j.type}{j.emergency && emergency}{j.server?.name}{j.deployment?.shortName || String(j.args?.church || "–")}{j.deployment?.product && {j.deployment.product}}{fmtDate(j.notBefore)}{j.message}
- {!jobs.length &&

No jobs.

} + {!jobs.length &&

No jobs.

} +
)}
diff --git a/frontend/src/app/(hub)/releases/page.tsx b/frontend/src/app/(hub)/releases/page.tsx index 2e1bfc6..3718ea8 100644 --- a/frontend/src/app/(hub)/releases/page.tsx +++ b/frontend/src/app/(hub)/releases/page.tsx @@ -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 ? : shown.length === 0 ?

No releases yet{filter === "all" ? "" : ` for ${PRODUCT_NAMES[filter]}`}.

: (
- {shown.map(r => ( + {paged.rows.map(r => (
{editing === r.id ? ( save(f, r.id)} onCancel={() => setEditing(null)} /> @@ -235,6 +238,7 @@ export default function ReleasesPage() { )}
))} +
)} diff --git a/frontend/src/app/(hub)/servers/[id]/page.tsx b/frontend/src/app/(hub)/servers/[id]/page.tsx index 5f0a641..b45c6fd 100644 --- a/frontend/src/app/(hub)/servers/[id]/page.tsx +++ b/frontend/src/app/(hub)/servers/[id]/page.tsx @@ -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(null); + // Hub 2.6.0: every job on this server, a page at a time (it showed the last 25). + const jobsPaged = useServerPaged("/api/admin/jobs", { serverId: String(id) }, r => r.jobs as Job[], 20); const [range, setRange] = useState<"24h" | "7d" | "90d">("24h"); const [msg, setMsg] = useState(null); const [agentVersion, setAgentVersion] = useState(""); @@ -126,7 +129,8 @@ export default function ServerPage() {

Actions

- + +

Asks the agent what'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.

setAgentVersion(e.target.value)} aria-label="Agent version" />
@@ -157,12 +161,13 @@ export default function ServerPage() { )} -
-

Recent jobs

+
+

Jobs

- - {d.jobs.map(j => )} + + {(jobsPaged.rows ?? d.jobs).map(j => )}
JobWhenStatusResult
{j.type} {String(j.args?.church || "")}{fmtDate(j.notBefore)}{j.message}
JobWhenStatusResult
{j.type} {String(j.args?.church || "")}{fmtDate(j.notBefore)}{j.message}
+
); diff --git a/frontend/src/app/(hub)/servers/installs/[id]/page.tsx b/frontend/src/app/(hub)/servers/installs/[id]/page.tsx index cf3c718..467c634 100644 --- a/frontend/src/app/(hub)/servers/installs/[id]/page.tsx +++ b/frontend/src/app/(hub)/servers/installs/[id]/page.tsx @@ -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(`/api/admin/deployments/${id}`).then(setD).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]); + const [releases, setReleases] = useState([]); + // Hub 2.6.0: every job of this install, a page at a time (it showed the last 50). + const jobsPaged = useServerPaged("/api/admin/jobs", { deploymentId: String(id) }, r => r.jobs as Job[], 20); + const load = useCallback(() => { + jobsPaged.reload(); + return api(`/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("/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() { {x.domain} · on {x.server.name} · ports web {x.webPort}, api {x.apiPort} · version {x.install?.version || x.version || "–"} } /> + {/* Hub 2.6.0: whether the site has registered with the Hub (its banners, licence and heartbeats need it). */} +

+ {x.install + ? <>Registered site: {x.install.url}, last heartbeat {x.install.lastHeartbeatAt ? ago(x.install.lastHeartbeatAt) : "never"}. + : The site hasn'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't happen, check its HUB_URL and HUB_LICENCE_KEY.} +

{!!problems.length &&
    {problems.map(p =>
  • {p}
  • )}
} @@ -83,9 +100,15 @@ export default function DeploymentPage() { )} {x.status === "live" && ( -
{ 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."); }}> + { 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."); }}>

Schedule an update

-
setUpd({ ...upd, version: e.target.value })} />
+
+ + +
setUpd({ ...upd, at: e.target.value })} />

At least {upd.emergency ? "15 minutes" : "4 hours"} away, so the church gets notice.

{upd.emergency && <> @@ -138,18 +161,19 @@ export default function DeploymentPage() { )} -
-

Jobs

+
+

Jobs

- - {x.jobs.map(j => ( + + {(jobsPaged.rows ?? x.jobs).map(j => ( - + - + ))}
JobWhenStatusResult
JobWhenStatusResult
{j.type}{j.emergency && emergency}{j.type}{j.emergency && emergency} {fmtDate(j.notBefore)}{j.message}{["queued", "scheduled"].includes(j.status) && }{["queued", "scheduled"].includes(j.status) && }
+
{!!x.exports.length && ( diff --git a/frontend/src/app/(hub)/servers/installs/page.tsx b/frontend/src/app/(hub)/servers/installs/page.tsx index e71c0ad..d559f3f 100644 --- a/frontend/src/app/(hub)/servers/installs/page.tsx +++ b/frontend/src/app/(hub)/servers/installs/page.tsx @@ -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(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([]); const [customers, setCustomers] = useState([]); const [installs, setInstalls] = useState([]); @@ -138,14 +145,23 @@ export default function InstallsPage() { )} {!list ? : ( -
+
+
+ + +
- - {list.map(d => ( - + + {paged.rows.map(d => ( + ))}
ChurchDomainServerVersionLast heartbeatStatus
{d.customer?.name} ({d.shortName}){d.isDemo && demo}{d.domain}{d.server?.name}{d.install?.version || d.version || "–"}{ago(d.install?.lastHeartbeatAt)}
ChurchProductDomainServerVersionLast heartbeatStatus
{d.customer?.name} ({d.shortName}){d.isDemo && demo}{PRODUCT_NAMES[d.product as keyof typeof PRODUCT_NAMES] || d.product}{d.domain}{d.server?.name}{d.install?.version || d.version || "–"}{d.installId ? ago(d.install?.lastHeartbeatAt) : not registered}
- {!list.length &&

No installs on servers yet.

} + {!list.length ?

No installs on servers yet.

: !shown.length &&

No installs match.

} +
)}
diff --git a/frontend/src/app/(hub)/servers/page.tsx b/frontend/src/app/(hub)/servers/page.tsx index 39f502c..07fcd45 100644 --- a/frontend/src/app/(hub)/servers/page.tsx +++ b/frontend/src/app/(hub)/servers/page.tsx @@ -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(null); + const paged = usePaged(list || [], null, 20); const [msg, setMsg] = useState(null); const [adding, setAdding] = useState(false); const [name, setName] = useState(""); @@ -67,7 +69,7 @@ export default function ServersPage() { {!list ? : list.length === 0 ?

No servers yet. Add one to install churches from the Hub.

: (
- {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 ( @@ -99,6 +101,7 @@ export default function ServersPage() { })}
)} + {list &&
}
); } diff --git a/frontend/src/app/(hub)/servers/settings/page.tsx b/frontend/src/app/(hub)/servers/settings/page.tsx index 2b85fe3..73740fc 100644 --- a/frontend/src/app/(hub)/servers/settings/page.tsx +++ b/frontend/src/app/(hub)/servers/settings/page.tsx @@ -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(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 ? : ( - {ports.map(p => ( + {portsPaged.rows.map(p => ( ))}
PortUseServerNote
{p.port}{p.releasedAt ? `free from ${fmtDate(new Date(new Date(p.releasedAt).getTime() + 30 * 24 * 3600 * 1000), false)}` : p.role}{p.server?.name || "–"}{p.note} {(p.role === "taken" || p.releasedAt) && }
)} + {ports && } ); diff --git a/frontend/src/app/(hub)/servers/updates/page.tsx b/frontend/src/app/(hub)/servers/updates/page.tsx index 550e25d..9392c99 100644 --- a/frontend/src/app/(hub)/servers/updates/page.tsx +++ b/frontend/src/app/(hub)/servers/updates/page.tsx @@ -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(null); + const [product, setProduct] = useState("events"); + const [all, setAll] = useState(null); + const [releases, setReleases] = useState([]); const [upcoming, setUpcoming] = useState([]); const [chosen, setChosen] = useState([]); const [form, setForm] = useState({ version: "", at: toInput(new Date(Date.now() + 5 * H)), emergency: false, reason: "", totp: "" }); const [msg, setMsg] = useState(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("/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 (
- +
- {!deployments ? : ( + {!all ? : ( + ({ key: p, label: `${PRODUCT_NAMES[p]} (${(all || []).filter(d => d.product === p).length})` }))} active={product} onChange={pick} />
Select: - - {byVersion.map(v => )} + + {byVersion.map(v => )}
{deployments.map(d => ( ))} - {!deployments.length &&

No live installs on servers.

} + {!deployments.length &&

No live {name} installs on servers.

}
-
setForm({ ...form, version: e.target.value })} />
+
+ + + {product === "events" &&

Each church's Accounts stays on its version, unless this release needs a newer one: then it's updated first in the same deploy, or installed first if the church has none. The confirmation lists what happens.

} +
setForm({ ...form, at: e.target.value })} />

At least {form.emergency ? "15 minutes" : "4 hours"} away. They run one at a time from then.

{form.emergency && <> @@ -73,17 +110,18 @@ export default function UpdatesPage() {
setForm({ ...form, totp: e.target.value })} />
}
- + )} -
-

Planned and running

+
+

Planned and running

- - {upcoming.map(j => )} + + {upcomingPaged.rows.map(j => )}
JobInstallWhenStatus
{j.type}{j.batchId && batch}{j.emergency && emergency}{j.deployment?.shortName || "–"}{fmtDate(j.notBefore)}
JobInstallWhenStatus
{j.type}{j.batchId && batch}{j.emergency && emergency}{j.deployment?.shortName || "–"}{j.deployment?.product && {j.deployment.product}}{fmtDate(j.notBefore)}
- {!upcoming.length &&

Nothing planned.

} + {!upcoming.length &&

Nothing planned.

} +
); diff --git a/frontend/src/app/(hub)/settings/page.tsx b/frontend/src/app/(hub)/settings/page.tsx index c489ae1..8e668ca 100644 --- a/frontend/src/app/(hub)/settings/page.tsx +++ b/frontend/src/app/(hub)/settings/page.tsx @@ -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([]); - const [audit, setAudit] = useState([]); 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("/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(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("/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 ? : ; @@ -331,9 +332,9 @@ export default function SettingsPage() { <>
- {audit.length === 0 ?

Nothing yet.

: auditShown.length === 0 ?

Nothing matches.

: ( + {!auditPaged.rows ?

Loading…

: audit.length === 0 ?

{auditQ ? "Nothing matches." : "Nothing yet."}

: (
    - {auditPaged.rows.map(a => ( + {audit.map(a => (
  • {fmtDate(a.createdAt)} {a.actor?.name || "—"} @@ -343,7 +344,7 @@ export default function SettingsPage() { ))}
)} - +
)} diff --git a/frontend/src/components/servers.tsx b/frontend/src/components/servers.tsx index f121eff..286716a 100644 --- a/frontend/src/components/servers.tsx +++ b/frontend/src/components/servers.tsx @@ -31,7 +31,7 @@ export type Job = { id: string; serverId: string; type: string; args: Record; 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; log: string[]; message?: string } | null; }; diff --git a/frontend/src/lib/paging.ts b/frontend/src/lib/paging.ts index 22b7613..4dd23c4 100644 --- a/frontend/src/lib/paging.ts +++ b/frontend/src/lib/paging.ts @@ -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(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(path: string, params: Record, pick: (r: Record) => T[], pageSize = 50) { + const [page, setPage] = useState(1); + const [data, setData] = useState<{ rows: T[]; total: number; pages: number } | null>(null); + const [error, setError] = useState(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 & { 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 }; +}