Hub 2.0 step 3: releases per product, with requirements

- Release.product and requires; unique (product, version); latest version
  per product (latest_version stays Cross Events' latest)
- Release sources per product (Releases page): repository, tag prefix,
  notes file. Defaults: every product from crosscode-platform plus Cross
  Events' v1.2.3 tags from hope-events. A product's releases are only
  removed when all its sources were read and found tags
- "— requires accounts 1.2.0" in a notes heading: Request update answers
  409 REQUIREMENT_NOT_MET until the church's install of that product is new
  enough; install page and Releases page show it; v2 replies carry requires
- @crosscode/contracts 1.1.0 vendored (optional requires on releases)
- Alerts, dashboard and install lists compare against each product's latest

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-04 15:57:46 +02:00
co-authored by Claude Opus 5.5
parent 0318b4f6f4
commit 816452e1c2
21 changed files with 821 additions and 201 deletions
+15 -3
View File
@@ -70,15 +70,27 @@ function problems(install, settings, now = new Date()) {
else if (left <= s.expiryDays * DAY) out.push({ type: 'licence_expiring', level: 'warning', message: `Licence expires ${new Date(lic.expiresAt).toISOString().slice(0, 10)}` });
}
if (settings.latest_version && install.version && compareVersions(install.version, settings.latest_version) < 0) {
out.push({ type: 'behind', level: 'info', message: `Runs ${install.version}; latest is ${settings.latest_version}` });
// Hub 2.0: the latest version of the install's product (settings.latest_versions, a map); before
// that, latest_version was Cross Events'.
const latest = settings.latest_versions ? settings.latest_versions[install.product || 'events'] : settings.latest_version;
if (latest && install.version && compareVersions(install.version, latest) < 0) {
out.push({ type: 'behind', level: 'info', message: `Runs ${install.version}; latest is ${latest}` });
}
return out;
}
/** Run the checks for every install: open new alerts (emailed unless info), resolve cleared ones. */
/** The latest version of each product ({ events: '2.1.1', … }), read here rather than from releases.js (which needs this file). */
async function latestVersionsNow() {
const out = {};
for (const r of await prisma.release.findMany({ select: { product: true, version: true } })) {
if (!out[r.product] || compareVersions(r.version, out[r.product]) > 0) out[r.product] = r.version;
}
return out;
}
async function runAlerts(now = new Date()) {
const settings = await getSettings();
const settings = { ...(await getSettings()), latest_versions: await latestVersionsNow() };
const installs = await prisma.install.findMany({
where: { releasedAt: null },
include: { licence: true, customer: { select: { name: true } }, events: { where: { resolvedAt: null } } },
+176 -46
View File
@@ -1,18 +1,24 @@
/**
* Releases from git (Gitea): every v1.2.3 tag of the Cross Events repo is a release, dated by its
* commit, and the notes come from the repo's WHATS-NEW.md on its default branch ("## 1.2.3" sections;
* "urgent" or "security" in the heading marks an urgent release). Notes only attach to tagged
* versions, so a section written ahead of a release stays hidden until it's tagged, and a note can be
* corrected after release without a new version. Runs every 15 minutes and from
* "Sync now" on the Releases page, when a repo is set; git is then the only source of releases.
* Releases from git (Gitea), per product (Hub 2.0). Each product has one or more release sources
* (Releases page): a repository, a tag prefix and a notes file. Every tag `<prefix>1.2.3` is a
* release of that product, dated by its commit; the notes come from the notes file on the
* repository's default branch ("## 1.2.3" sections; "urgent" or "security" in the heading marks an
* urgent release, "requires accounts 1.2.0" a requirement). Notes only attach to tagged versions,
* so a section written ahead of a release stays hidden until it's tagged, and a note can be
* corrected after release without a new version. Runs every 15 minutes and from "Sync now".
*
* A product's releases are the tags of all its sources. Releases of a product are only removed
* when every one of its sources was read and at least one tag was found, so an unreachable git
* server (or a mistyped address) never wipes releases. A product with no source is managed by hand.
*/
const prisma = require('../config/db');
const { getSettings, setSettings, releaseRepoToken } = require('./settings');
const { syncLatestVersion } = require('./releases');
const { PRODUCTS, PRODUCT_NAMES, isProduct } = require('./products');
const TIMEOUT_MS = 20000;
const TAG_RE = /^v?(\d+\.\d+\.\d+)$/;
const PLATFORM_REPO = 'https://c-git.crosscode.co.za/joshua/crosscode-platform';
/** https://git.example.com/owner/repo(.git) → { api, owner, repo }, or null. */
function parseRepoUrl(url) {
@@ -27,6 +33,61 @@ function parseRepoUrl(url) {
}
}
/**
* The default sources: every product from the platform monorepo (`events@1.2.3`, `accounts@…`,
* with notes in `apps/<product>/WHATS-NEW.md`), plus Cross Events before the move, from the
* repository set before Hub 2.0 (`release_repo_url`, `v1.2.3` tags).
*/
function defaultSources(settings = {}) {
const platform = product => ({ product, repo: PLATFORM_REPO, tagPrefix: `${product}@`, notesPath: `apps/${product}/WHATS-NEW.md` });
const legacy = parseRepoUrl(settings.release_repo_url)
? [{ product: 'events', repo: String(settings.release_repo_url).trim(), tagPrefix: 'v', notesPath: settings.release_notes_path || 'WHATS-NEW.md' }]
: [];
return [platform('events'), ...legacy, platform('accounts'), platform('website'), platform('app')];
}
const bad = message => Object.assign(new Error(message), { status: 400 });
/** Checked and tidied sources from the Releases page. Throws (status 400) on a bad one. */
function cleanSources(list) {
if (!Array.isArray(list)) throw bad('Release sources must be a list.');
if (list.length > 20) throw bad('At most 20 release sources.');
const seen = new Set();
return list.map((s, i) => {
const n = `Source ${i + 1}`;
if (!isProduct(s?.product)) throw bad(`${n}: choose a product.`);
const repo = String(s.repo || '').trim();
if (!parseRepoUrl(repo)) throw bad(`${n}: the repository address looks like https://git.example.com/owner/repo.`);
const tagPrefix = String(s.tagPrefix ?? '').trim();
if (!/^[A-Za-z0-9._@/-]{0,40}$/.test(tagPrefix)) throw bad(`${n}: the tag prefix can only have letters, digits and . _ @ / -.`);
const notesPath = String(s.notesPath || 'WHATS-NEW.md').trim().replace(/^\/+/, '');
if (!notesPath || notesPath.includes('..') || notesPath.length > 200) throw bad(`${n}: give the notes file's path in the repository.`);
const key = `${parseRepoUrl(repo).api}#${tagPrefix}`;
if (seen.has(key)) throw bad(`${n}: the same repository and tag prefix are listed twice.`);
seen.add(key);
return { product: s.product, repo, tagPrefix, notesPath };
});
}
/** The sources in use: the saved list (release_sources), or the defaults when none is saved. */
function releaseSources(settings = {}) {
const raw = String(settings.release_sources || '').trim();
if (!raw) return defaultSources(settings);
try {
return cleanSources(JSON.parse(raw));
} catch {
return defaultSources(settings);
}
}
const escapeRegExp = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
/** The tag pattern for a prefix: `v` also accepts a bare 1.2.3 (as before Hub 2.0). */
function tagPattern(prefix) {
if (prefix === 'v') return /^v?(\d+\.\d+\.\d+)$/;
return new RegExp(`^${escapeRegExp(prefix)}(\\d+\\.\\d+\\.\\d+)$`);
}
/** Markdown to the plain notes installs show: list lines stay "- ", the rest loses its markup. */
function plainNotes(lines) {
const out = [];
@@ -50,9 +111,27 @@ function plainNotes(lines) {
return out.join('\n').replace(/\n{3,}/g, '\n\n').trim();
}
const REQUIREMENT_RE = new RegExp(`\\b(${PRODUCTS.join('|')})\\s+v?(\\d+\\.\\d+\\.\\d+)`, 'gi');
/**
* The sections of WHATS-NEW.md: { "1.46.2": { notes, urgent } }. A section is a "## 1.46.2" heading
* (optionally "[1.46.2]", "v1.46.2", a date or "— urgent" after it) up to the next "## ".
* What a heading needs: "— requires accounts 1.2.0, website 1.1.0 — urgent" →
* [{ product: 'accounts', version: '1.2.0' }, { product: 'website', version: '1.1.0' }].
*/
function parseRequirements(heading) {
const at = String(heading || '').search(/\brequires?\b/i);
if (at < 0) return [];
const out = [];
for (const m of heading.slice(at).matchAll(REQUIREMENT_RE)) {
const product = m[1].toLowerCase();
if (!out.some(r => r.product === product)) out.push({ product, version: m[2] });
}
return out;
}
/**
* The sections of a notes file: { "1.46.2": { notes, urgent, requires } }. A section is a
* "## 1.46.2" heading (optionally "[1.46.2]", "v1.46.2", a date, "— urgent" or "— requires
* accounts 1.2.0" after it) up to the next "## ".
*/
function parseNotes(markdown) {
const text = String(markdown || '').replace(/<!--[\s\S]*?-->/g, '');
@@ -62,14 +141,16 @@ function parseNotes(markdown) {
const heading = /^##\s+(.*)$/.exec(line);
if (heading) {
const v = /\[?v?(\d+\.\d+\.\d+)\]?/.exec(heading[1]);
current = v ? { version: v[1], urgent: /\b(urgent|security)\b/i.test(heading[1]), lines: [] } : null;
current = v
? { version: v[1], urgent: /\b(urgent|security)\b/i.test(heading[1]), requires: parseRequirements(heading[1].slice(v.index + v[0].length)), lines: [] }
: null;
if (current) sections[current.version] = current;
continue;
}
if (/^#\s/.test(line)) { current = null; continue; }
if (current) current.lines.push(line);
}
return Object.fromEntries(Object.values(sections).map(s => [s.version, { notes: plainNotes(s.lines), urgent: s.urgent }]));
return Object.fromEntries(Object.values(sections).map(s => [s.version, { notes: plainNotes(s.lines), urgent: s.urgent, requires: s.requires }]));
}
async function get(url, token, { raw = false } = {}) {
@@ -85,65 +166,114 @@ async function get(url, token, { raw = false } = {}) {
return raw ? res.text() : res.json();
}
/** Every v1.2.3 tag: [{ version, date }]. */
/** Every tag of a repository: [{ name, date }]. */
async function fetchTags(repo, token) {
const tags = [];
for (let page = 1; page <= 20; page++) {
const batch = await get(`${repo.api}/tags?limit=50&page=${page}`, token);
if (batch === null) throw new Error('The repository was not found. Check its address (and the token if it is private).');
for (const t of batch) {
const m = TAG_RE.exec(t.name || '');
if (m) tags.push({ version: m[1], date: t.commit?.created || null });
}
for (const t of batch) if (t?.name) tags.push({ name: t.name, date: t.commit?.created || null });
if (batch.length < 50) break;
}
return tags;
}
const sameRequires = (a, b) => JSON.stringify(a || []) === JSON.stringify(b || []);
const sourceLabel = s => `${PRODUCT_NAMES[s.product]} (${parseRepoUrl(s.repo)?.repo || s.repo}, ${s.tagPrefix || 'no prefix'}1.2.3)`;
/**
* Bring the releases in line with git: add new tags, update notes and urgency from WHATS-NEW.md, and
* remove releases that have no tag. Returns { tags, added, updated, removed, latest }.
* Read every source: { found: { product: Map(version → { date, notes, urgent, requires }) },
* failed: Set(product), problems: [message], counts: [{ source, tags }] }. A repository's tags and
* notes files are fetched once per sync, however many sources use them.
*/
async function readSources(sources, token) {
const found = {};
const failed = new Set();
const problems = [];
const counts = [];
const tagCache = new Map();
const notesCache = new Map();
for (const source of sources) {
try {
const repo = parseRepoUrl(source.repo);
if (!tagCache.has(repo.api)) tagCache.set(repo.api, fetchTags(repo, token));
const pattern = tagPattern(source.tagPrefix);
const tags = (await tagCache.get(repo.api)).map(t => ({ ...t, m: pattern.exec(t.name) })).filter(t => t.m);
let notes = {};
if (tags.length) {
const url = `${repo.api}/raw/${source.notesPath.split('/').map(encodeURIComponent).join('/')}`;
if (!notesCache.has(url)) notesCache.set(url, get(url, token, { raw: true }));
const markdown = await notesCache.get(url);
if (markdown === null) problems.push(`${sourceLabel(source)}: ${source.notesPath} was not found on the default branch, so there are no notes.`);
notes = parseNotes(markdown || '');
}
const map = found[source.product] || (found[source.product] = new Map());
for (const t of tags) {
const version = t.m[1];
// The first source listed wins if two tag the same version.
if (map.has(version)) continue;
const n = notes[version] || { notes: '', urgent: false, requires: [] };
map.set(version, { date: t.date, notes: n.notes, urgent: n.urgent, requires: n.requires.filter(r => r.product !== source.product) });
}
counts.push({ source: sourceLabel(source), tags: tags.length });
} catch (e) {
failed.add(source.product);
problems.push(`${sourceLabel(source)}: ${e.message}`);
}
}
return { found, failed, problems, counts };
}
/**
* Bring each product's releases in line with its sources: add new tags, update notes, urgency and
* requirements, and remove releases that have no tag (only when all the product's sources were
* read and found tags). Returns { sources, added, updated, removed, latest, problems }; throws when
* no source could be read at all.
*/
async function syncReleases() {
const settings = await getSettings();
const repo = parseRepoUrl(settings.release_repo_url);
if (!repo) return { skipped: 'no repository set' };
try {
const token = await releaseRepoToken();
const tags = await fetchTags(repo, token);
if (!tags.length) throw new Error('The repository has no version tags (v1.2.3) yet.');
const path = (settings.release_notes_path || 'WHATS-NEW.md').replace(/^\/+/, '').split('/').map(encodeURIComponent).join('/');
const markdown = await get(`${repo.api}/raw/${path}`, token, { raw: true });
const notes = parseNotes(markdown || '');
const sources = releaseSources(settings);
if (!sources.length) return { skipped: 'no release sources' };
const { found, failed, problems, counts } = await readSources(sources, await releaseRepoToken());
if (counts.length === 0) {
await setSettings({ release_sync_error: `${new Date().toISOString()} ${problems.join(' · ')}`.slice(0, 2000) });
throw new Error(problems.join(' · '));
}
const existing = new Map((await prisma.release.findMany()).map(r => [r.version, r]));
const tagged = new Set(tags.map(t => t.version));
let added = 0;
let updated = 0;
for (const tag of tags) {
const n = notes[tag.version] || { notes: '', urgent: false };
const had = existing.get(tag.version);
let added = 0;
let updated = 0;
let removed = 0;
for (const product of new Set(sources.map(s => s.product))) {
const tagged = found[product] || new Map();
const existing = new Map((await prisma.release.findMany({ where: { product } })).map(r => [r.version, r]));
for (const [version, t] of tagged) {
const had = existing.get(version);
if (!had) {
await prisma.release.create({ data: { version: tag.version, notes: n.notes, urgent: n.urgent, releasedAt: tag.date ? new Date(tag.date) : new Date() } });
await prisma.release.create({ data: { product, version, notes: t.notes, urgent: t.urgent, requires: t.requires, releasedAt: t.date ? new Date(t.date) : new Date() } });
added++;
} else {
// Releases added by hand (or from the old latest_version setting) take the tag's date.
const date = tag.date ? new Date(tag.date) : had.releasedAt;
if (had.notes !== n.notes || had.urgent !== n.urgent || date.getTime() !== new Date(had.releasedAt).getTime()) {
await prisma.release.update({ where: { id: had.id }, data: { notes: n.notes, urgent: n.urgent, releasedAt: date } });
const date = t.date ? new Date(t.date) : had.releasedAt;
if (had.notes !== t.notes || had.urgent !== t.urgent || !sameRequires(had.requires, t.requires) || date.getTime() !== new Date(had.releasedAt).getTime()) {
await prisma.release.update({ where: { id: had.id }, data: { notes: t.notes, urgent: t.urgent, requires: t.requires, releasedAt: date } });
updated++;
}
}
}
if (failed.has(product)) continue;
if (!tagged.size) {
if (existing.size) problems.push(`${PRODUCT_NAMES[product]}: no version tags found in its sources, so its ${existing.size} release(s) were kept. Check the sources.`);
continue;
}
const gone = [...existing.values()].filter(r => !tagged.has(r.version)).map(r => r.id);
if (gone.length) await prisma.release.deleteMany({ where: { id: { in: gone } } });
const latest = await syncLatestVersion();
await setSettings({ release_synced_at: new Date().toISOString(), release_sync_error: markdown === null ? `${settings.release_notes_path} was not found on the default branch, so there are no notes.` : '' });
return { tags: tags.length, added, updated, removed: gone.length, latest };
} catch (e) {
await setSettings({ release_sync_error: `${new Date().toISOString()} ${e.message}`.slice(0, 500) });
throw e;
if (gone.length) {
await prisma.release.deleteMany({ where: { id: { in: gone } } });
removed += gone.length;
}
}
const latest = await syncLatestVersion();
await setSettings({ release_synced_at: new Date().toISOString(), release_sync_error: problems.join('\n').slice(0, 2000) });
return { sources: counts, added, updated, removed, latest, problems };
}
module.exports = { parseRepoUrl, parseNotes, plainNotes, syncReleases };
module.exports = { PLATFORM_REPO, parseRepoUrl, parseNotes, parseRequirements, plainNotes, tagPattern, defaultSources, cleanSources, releaseSources, syncReleases };
+82 -13
View File
@@ -1,11 +1,17 @@
/**
* Cross Events releases and their notes (Releases page). The highest version is the latest one,
* kept in the latest_version setting so alerts and the install API read it as before.
* Releases per product (Hub 2.0) and their notes (Releases page). The highest version of a product
* is its latest. `latest_version` keeps the Cross Events latest for older code paths and the
* Settings page.
*
* Requirements: a release can need a minimum version of a sibling product (`requires`, from
* "— requires accounts 1.2.0" in WHATS-NEW.md). An install can't ask for an update until the
* church's install of each required product runs that version or later.
*/
const prisma = require('../config/db');
const { compareVersions } = require('./alerts');
const { setSettings } = require('./settings');
const { PRODUCT_NAMES } = require('./products');
const VERSION_RE = /^\d+\.\d+\.\d+$/;
const MAX_SENT = 20;
@@ -15,27 +21,90 @@ function sortReleases(releases) {
return [...releases].sort((a, b) => compareVersions(b.version, a.version));
}
const requirementsOf = r => (Array.isArray(r.requires) ? r.requires.filter(q => q && q.product && VERSION_RE.test(q.version)) : []);
/**
* What an install on `version` is told (§3): every release newer than it, newest first — at most
* 20, so a long-neglected install still gets a reply of sensible size.
* 20, so a long-neglected install still gets a reply of sensible size. `withRequires` (protocol v2)
* adds each release's requirements (contracts 1.1.0); v1 replies stay as they were.
*/
function releasesFor(releases, version) {
function releasesFor(releases, version, { withRequires = false } = {}) {
return sortReleases(releases)
.filter(r => !version || compareVersions(r.version, version) > 0)
.slice(0, MAX_SENT)
.map(r => ({ version: r.version, releasedAt: new Date(r.releasedAt).toISOString(), urgent: !!r.urgent, notes: r.notes || '' }));
.map(r => {
const out = { version: r.version, releasedAt: new Date(r.releasedAt).toISOString(), urgent: !!r.urgent, notes: r.notes || '' };
const requires = requirementsOf(r);
return withRequires && requires.length ? { ...out, requires } : out;
});
}
/** Point latest_version at the highest release (blank when there are none). */
async function syncLatestVersion() {
const releases = await prisma.release.findMany({ select: { version: true } });
const latest = sortReleases(releases)[0]?.version || '';
await setSettings({ latest_version: latest });
/** { events: '2.1.1', website: '1.0.0', … } — the highest release of each product that has any. */
function latestByProduct(releases) {
const out = {};
for (const r of releases) {
const p = r.product || 'events';
if (!out[p] || compareVersions(r.version, out[p]) > 0) out[p] = r.version;
}
return out;
}
async function latestVersions(db = prisma) {
return latestByProduct(await db.release.findMany({ select: { product: true, version: true } }));
}
/** Keep latest_version on the Cross Events latest (blank when there are none). Returns the map. */
async function syncLatestVersion(db = prisma) {
const latest = await latestVersions(db);
await setSettings({ latest_version: latest.events || '' });
return latest;
}
async function releasesForInstall(version) {
return releasesFor(await prisma.release.findMany(), version);
async function releasesForInstall(product, version, options = {}, db = prisma) {
return releasesFor(await db.release.findMany({ where: { product } }), version, options);
}
module.exports = { VERSION_RE, sortReleases, releasesFor, releasesForInstall, syncLatestVersion };
/**
* What updating `install` from its version to `target` needs from its siblings: the highest
* required version per product over every release it would get (so a requirement in a skipped
* release still counts). `siblings` are the church's other installs in use: [{ product, version }].
* Returns [{ product, version, current }] for the ones not met (current: null = not installed).
*/
function unmetRequirements({ releases, from, target, siblings }) {
const needed = {};
for (const r of releases) {
if (from && compareVersions(r.version, from) <= 0) continue;
if (compareVersions(r.version, target) > 0) continue;
for (const q of requirementsOf(r)) {
if (!needed[q.product] || compareVersions(q.version, needed[q.product]) > 0) needed[q.product] = q.version;
}
}
const out = [];
for (const [product, version] of Object.entries(needed)) {
const running = siblings.filter(s => s.product === product && s.version).map(s => s.version).sort((a, b) => compareVersions(b, a))[0] || null;
if (!running || compareVersions(running, version) < 0) out.push({ product, version, current: running });
}
return out;
}
/** "Accounts must be updated to 1.2.0 first (it runs 1.1.0)." for each unmet requirement. */
function requirementMessage(unmet) {
return unmet.map(u => (u.current
? `${PRODUCT_NAMES[u.product] || u.product} must be updated to ${u.version} first (it runs ${u.current}).`
: `${PRODUCT_NAMES[u.product] || u.product} ${u.version} or later must be installed first.`)).join(' ');
}
/** The requirements `install` hasn't met for updating to `target` (database version). */
async function unmetRequirementsFor(install, target, db = prisma) {
if (!target) return [];
const [releases, siblings] = await Promise.all([
db.release.findMany({ where: { product: install.product } }),
db.install.findMany({ where: { customerId: install.customerId, id: { not: install.id }, releasedAt: null }, select: { product: true, version: true } }),
]);
return unmetRequirements({ releases, from: install.version, target, siblings });
}
module.exports = {
VERSION_RE, sortReleases, releasesFor, releasesForInstall, latestByProduct, latestVersions, syncLatestVersion,
unmetRequirements, unmetRequirementsFor, requirementMessage,
};
+4 -1
View File
@@ -18,7 +18,10 @@ const DEFAULTS = {
smtp_user: '',
smtp_pass: '',
smtp_from: '',
// Releases and their notes are read from git (utils/releaseSync.js) when a repo is set.
// Releases and their notes are read from git (utils/releaseSync.js). Hub 2.0: release_sources
// is the list of sources per product (JSON, Releases page); blank = the defaults, which include
// release_repo_url (Cross Events before the monorepo, v1.2.3 tags) and release_notes_path.
release_sources: '',
release_repo_url: 'https://c-git.crosscode.co.za/joshua/hope-events',
release_notes_path: 'WHATS-NEW.md',
release_repo_token: '',