- 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>
143 lines
7.1 KiB
JavaScript
143 lines
7.1 KiB
JavaScript
/**
|
|
* Install alerts: which problems an install has right now (pure, testable), and the job
|
|
* that opens an InstallEvent (and emails Joshua) when a problem starts, and resolves it when
|
|
* it clears — so each problem is emailed once.
|
|
*/
|
|
|
|
const prisma = require('../config/db');
|
|
const { getSettings } = require('./settings');
|
|
const { sendMail } = require('./mail');
|
|
|
|
const MIN = 60 * 1000;
|
|
const HOUR = 60 * MIN;
|
|
const DAY = 24 * HOUR;
|
|
|
|
/** Compare "1.40.2" with "1.41.0": negative, 0 or positive. */
|
|
function compareVersions(a, b) {
|
|
const pa = String(a || '').split(/[.-]/).map(n => parseInt(n, 10) || 0);
|
|
const pb = String(b || '').split(/[.-]/).map(n => parseInt(n, 10) || 0);
|
|
for (let i = 0; i < 3; i++) if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) - (pb[i] || 0);
|
|
return 0;
|
|
}
|
|
|
|
/**
|
|
* The problems an install has now: [{ type, level, message }]. `install` needs
|
|
* lastHeartbeatAt, health, version, registeredAt, licence (status, expiresAt, graceDays).
|
|
*/
|
|
function problems(install, settings, now = new Date()) {
|
|
const out = [];
|
|
const s = {
|
|
offlineMin: parseInt(settings.offline_minutes, 10) || 60,
|
|
backupHours: parseInt(settings.backup_max_age_hours, 10) || 48,
|
|
diskPercent: parseFloat(settings.disk_min_free_percent) || 10,
|
|
errorsPerDay: parseInt(settings.errors_per_day, 10) || 50,
|
|
expiryDays: parseInt(settings.licence_expiry_warning_days, 10) || 14,
|
|
};
|
|
const health = install.health || {};
|
|
|
|
const lastSeen = install.lastHeartbeatAt ? new Date(install.lastHeartbeatAt) : null;
|
|
const since = lastSeen || new Date(install.registeredAt);
|
|
if (now - since > s.offlineMin * MIN) {
|
|
out.push({ type: 'offline', level: 'critical', message: lastSeen ? `No heartbeat since ${lastSeen.toISOString()}` : 'Never sent a heartbeat since registering' });
|
|
}
|
|
|
|
// Health from the last heartbeat (skipped when there is none yet).
|
|
if (lastSeen) {
|
|
if (health.db === false) out.push({ type: 'database', level: 'critical', message: 'The install reports its database is not OK' });
|
|
const backup = health.lastBackupAt ? new Date(health.lastBackupAt) : null;
|
|
if (!backup || now - backup > s.backupHours * HOUR) {
|
|
out.push({ type: 'backup_stale', level: 'warning', message: backup ? `Last backup ${backup.toISOString()}` : 'No backup reported' });
|
|
}
|
|
const disk = health.disk;
|
|
if (disk && disk.totalBytes > 0 && (disk.freeBytes / disk.totalBytes) * 100 < s.diskPercent) {
|
|
out.push({ type: 'disk_low', level: 'warning', message: `Disk ${Math.round((disk.freeBytes / disk.totalBytes) * 100)}% free` });
|
|
}
|
|
if (Number.isFinite(health.errorsLast24h) && health.errorsLast24h > s.errorsPerDay) {
|
|
out.push({ type: 'errors_high', level: 'warning', message: `${health.errorsLast24h} errors in the last 24 hours` });
|
|
}
|
|
if (Number.isFinite(health.jobs?.failedLast24h) && health.jobs.failedLast24h > 0) {
|
|
out.push({ type: 'jobs_failing', level: 'warning', message: `${health.jobs.failedLast24h} background job run(s) failed in the last 24 hours` });
|
|
}
|
|
if (health.pendingMigrations > 0) {
|
|
out.push({ type: 'pending_migrations', level: 'warning', message: `${health.pendingMigrations} database migration(s) not applied` });
|
|
}
|
|
}
|
|
|
|
const lic = install.licence;
|
|
if (lic && lic.status === 'active' && lic.expiresAt) {
|
|
const left = new Date(lic.expiresAt) - now;
|
|
if (left <= 0) out.push({ type: 'licence_expired', level: 'critical', message: `Licence expired ${new Date(lic.expiresAt).toISOString().slice(0, 10)} (grace ${lic.graceDays} days)` });
|
|
else if (left <= s.expiryDays * DAY) out.push({ type: 'licence_expiring', level: 'warning', message: `Licence expires ${new Date(lic.expiresAt).toISOString().slice(0, 10)}` });
|
|
}
|
|
|
|
// 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()), latest_versions: await latestVersionsNow() };
|
|
const installs = await prisma.install.findMany({
|
|
where: { releasedAt: null },
|
|
include: { licence: true, customer: { select: { name: true } }, events: { where: { resolvedAt: null } } },
|
|
});
|
|
let opened = 0;
|
|
let resolved = 0;
|
|
const newAlerts = [];
|
|
for (const install of installs) {
|
|
const current = problems(install, settings, now);
|
|
// Update requests are opened by the install and resolved by its heartbeat, not by these checks.
|
|
const openByType = new Map(install.events.filter(e => !['registered', 'version', 'update_requested', 'update_request_withdrawn'].includes(e.type)).map(e => [e.type, e]));
|
|
for (const p of current) {
|
|
if (openByType.has(p.type)) continue;
|
|
await prisma.installEvent.create({ data: { installId: install.id, type: p.type, level: p.level, message: p.message, createdAt: now } });
|
|
opened++;
|
|
if (p.level !== 'info') newAlerts.push(`• ${install.customer?.name || install.name} (${install.url}): ${p.message}`);
|
|
}
|
|
const currentTypes = new Set(current.map(p => p.type));
|
|
for (const [type, event] of openByType) {
|
|
if (currentTypes.has(type)) continue;
|
|
await prisma.installEvent.update({ where: { id: event.id }, data: { resolvedAt: now } });
|
|
resolved++;
|
|
}
|
|
}
|
|
if (newAlerts.length && settings.alert_email) {
|
|
await sendMail({
|
|
to: settings.alert_email,
|
|
subject: `Cross Code Hub: ${newAlerts.length} new alert${newAlerts.length === 1 ? '' : 's'}`,
|
|
text: `${newAlerts.join('\n')}\n\n${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/`,
|
|
}).catch(e => console.warn('[alerts] email failed:', e?.message));
|
|
}
|
|
return { installs: installs.length, opened, resolved };
|
|
}
|
|
|
|
/** Keep every heartbeat for 30 days, then only the last one of each day per install. */
|
|
async function rollupHeartbeats(now = new Date(), db = prisma) {
|
|
const cutoff = new Date(now.getTime() - 30 * DAY);
|
|
const res = await db.$executeRawUnsafe(`
|
|
DELETE FROM "Heartbeat" h
|
|
WHERE h."receivedAt" < $1
|
|
AND h."id" NOT IN (
|
|
SELECT DISTINCT ON ("installId", date_trunc('day', "receivedAt")) "id"
|
|
FROM "Heartbeat" WHERE "receivedAt" < $1
|
|
ORDER BY "installId", date_trunc('day', "receivedAt"), "receivedAt" DESC
|
|
)`, cutoff);
|
|
return { deleted: res };
|
|
}
|
|
|
|
module.exports = { compareVersions, problems, runAlerts, rollupHeartbeats };
|