Merge branch 'fix/stuck-uninstall'

This commit is contained in:
2026-11-19 08:50:42 +02:00
9 changed files with 123 additions and 12 deletions
+14
View File
@@ -5,6 +5,20 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [2.3.2] - 2026-11-19
### Fixed
- **Installs stuck as "Uninstalling".** An uninstall runs the export first and is cancelled if the
export fails, but the install was left "uninstalling" for good. It now goes back to live (or
waiting for the proxy), as it does when an uninstall job fails or is cancelled by hand. Before,
those two always set it to live.
- **Uninstall was offered for a failed install.** A failed install has already removed what it made on
the server, so its export always failed ("church.env is missing"). Uninstall is now refused for a
failed install, and for one still installing. A failed install's page offers **Remove the record**
instead (`DELETE /api/admin/deployments/:id`), which frees the short name. This also clears
records already stuck "uninstalling" when their install had failed.
## [2.3.1] - 2026-11-18
### Fixed
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-backend",
"version": "2.3.1",
"version": "2.3.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-backend",
"version": "2.3.1",
"version": "2.3.2",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-backend",
"version": "2.3.1",
"version": "2.3.2",
"private": true,
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
"main": "src/index.js",
+8 -1
View File
@@ -161,7 +161,14 @@ router.post('/deployments/link', wrap(async (req, res) => {
router.get('/deployments/:id', wrap(async (req, res) => {
const d = await prisma.deployment.findUnique({ where: { id: req.params.id }, include: { server: true, customer: { select: { id: true, name: true } }, install: true, jobs: { orderBy: { createdAt: 'desc' }, take: 50 }, exports: { select: { id: true, bytes: true, expiresAt: true, downloadedAt: true, deletedAt: true, createdAt: true } } } });
if (!d) throw bad('Not found.', 404);
res.json({ deployment: { ...d, server: serverSummary(d.server) }, fastPanel: await jobs.fastPanelText(d) });
res.json({ deployment: { ...d, server: serverSummary(d.server) }, fastPanel: await jobs.fastPanelText(d), canRemoveRecord: await jobs.neverInstalled(d) });
}));
// A failed install's record (nothing of it is on the server, so there's nothing to uninstall).
router.delete('/deployments/:id', wrap(async (req, res) => {
const d = await jobs.removeFailedInstall(req.params.id);
await audit(req, 'install_record_removed', d.id, { shortName: d.shortName, server: d.serverId, status: d.status });
res.json({ ok: true });
}));
router.post('/deployments/:id/proxy-done', wrap(async (req, res) => {
+40 -3
View File
@@ -191,7 +191,7 @@ async function afterJob(job, { exportKey }, now) {
await makeJob(prisma, { serverId: deployment.serverId, type: 'purge', args: { church: deployment.shortName }, deploymentId: deployment.id, notBefore: new Date(now.getTime() + EXPORT_DAYS * DAY), windowMinutes: 3 * 24 * 60 });
await emailJoshua(`Uninstalled: ${deployment.shortName}`, `${jobReportText(job)}\n\nRemove the FastPanel site ${deployment.domain} (ports ${deployment.webPort}, ${deployment.apiPort}).\nThe final backup is kept on the server for ${EXPORT_DAYS} days, then purged.`);
} else {
await prisma.deployment.update({ where: { id: deployment.id }, data: { status: 'live' } });
await prisma.deployment.update({ where: { id: deployment.id }, data: { status: statusBeforeUninstall(deployment) } });
await emailJoshua(`Uninstall failed: ${deployment.shortName}`, jobReportText(job));
}
break;
@@ -223,6 +223,11 @@ async function advanceBatch(job, now) {
for (const j of rest) {
await prisma.job.update({ where: { id: j.id }, data: { status: 'cancelled', message: `Not run: ${job.id} before it in the same batch didn't succeed.`, finishedAt: now } });
if (j.noticeId) await endNotice(j.noticeId, now);
// An uninstall that won't run (its export failed): the install is still there. Before 2.3.2 it
// stayed "uninstalling" for good.
if (j.deployment && j.type === 'uninstall') {
await prisma.deployment.update({ where: { id: j.deployment.id }, data: { status: statusBeforeUninstall(j.deployment) } });
}
if (j.deployment && j.scheduled && j.type === 'deploy') {
await emailSiteAdmin(j.deployment, `${PRODUCT_NAMES[j.deployment.product]} update postponed`, `The planned update of ${PRODUCT_NAMES[j.deployment.product]} at ${j.deployment.domain} has been postponed. Your site keeps running as it is; we'll let you know the new time.`);
}
@@ -545,10 +550,40 @@ async function cancelJob(jobId, admin, now = new Date()) {
await emailSiteAdmin(job.deployment, `${PRODUCT_NAMES[job.deployment.product]} update cancelled`, `The update of ${PRODUCT_NAMES[job.deployment.product]} at ${job.deployment.domain} planned for ${sast(job.notBefore)} is cancelled. Your site keeps running as it is.`);
}
if (job.batchId) await advanceBatch(updated, now);
if (job.type === 'uninstall' && job.deploymentId) await prisma.deployment.update({ where: { id: job.deploymentId }, data: { status: 'live' } });
if (job.type === 'uninstall' && job.deployment) await prisma.deployment.update({ where: { id: job.deployment.id }, data: { status: statusBeforeUninstall(job.deployment) } });
return updated;
}
/** What an install goes back to when its uninstall doesn't happen: it's still on the server. */
function statusBeforeUninstall(d) {
return d.liveAt || d.installId ? 'live' : 'waiting_for_proxy';
}
/**
* Whether an install never made it onto the server, so its record can simply be removed: its
* install failed (the server already removed what it made) and nothing is planned for it. Also
* one that was planned for uninstall after its install failed, from before 2.3.2 (stuck as
* "uninstalling" when the export found nothing to export).
*/
async function neverInstalled(d) {
if (!['failed', 'uninstalling'].includes(d.status) || d.liveAt || d.installId) return false;
const open = await prisma.job.count({ where: { deploymentId: d.id, status: { in: ['scheduled', 'queued', 'delivered'] } } });
if (open) return false;
if (d.status === 'failed') return true;
const install = await prisma.job.findFirst({ where: { deploymentId: d.id, type: { in: ['install', 'add-product'] } }, orderBy: { createdAt: 'desc' } });
return !!install && install.status !== 'succeeded';
}
/** Remove a failed install's record: there's nothing on the server to export or uninstall. */
async function removeFailedInstall(deploymentId) {
const d = await prisma.deployment.findUnique({ where: { id: deploymentId } });
if (!d) throw fail(404, 'NOT_FOUND', 'Not found.');
if (!(await neverInstalled(d))) throw fail(409, 'NOT_FAILED', 'Only a failed install\'s record can be removed; a working install is uninstalled.');
await prisma.port.deleteMany({ where: { port: { in: [d.webPort, d.apiPort] }, deploymentId: d.id, releasedAt: null } });
await prisma.deployment.delete({ where: { id: d.id } });
return d;
}
/**
* Uninstall (§9): 2FA, typing the short name, at least 4 hours ahead. A batch of two: the export
* (encrypted, emailed to the site admin), then the uninstall, which only runs if the export worked.
@@ -559,6 +594,8 @@ async function scheduleUninstall({ deploymentId, at, totp, confirm }, admin, now
if (!d) throw fail(404, 'NOT_FOUND', 'Not found.');
if (confirm !== d.shortName) throw fail(400, 'CONFIRM', `Type ${d.shortName} to confirm.`);
if (['removed', 'uninstalling'].includes(d.status)) throw fail(409, 'ALREADY', `It's already ${d.status}.`);
if (d.status === 'failed') throw fail(409, 'NOT_INSTALLED', 'Its install failed, so nothing of it is on the server: remove the record instead.');
if (d.status === 'installing') throw fail(409, 'BUSY', 'Wait until the install has finished.');
const when = new Date(at || now.getTime() + 7 * DAY);
if (when - now < SCHEDULE_MIN_HOURS * HOUR) throw fail(400, 'TOO_SOON', `An uninstall is planned at least ${SCHEDULE_MIN_HOURS} hours ahead.`);
const exportId = servers.newId('exp');
@@ -639,6 +676,6 @@ async function runNow({ serverId, type, args, deploymentId = null }, admin, now
module.exports = {
WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES,
makeJob, signedJob, jobConfig, poll, receiveReport, finish, tick, advanceBatch,
newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow,
newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, neverInstalled, removeFailedInstall, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow,
fastPanelText, jobReportText, scheduleWarnings, requireTotp, agentOnline, siteAdminEmail,
};
+34
View File
@@ -243,6 +243,40 @@ describe('scheduled updates (§8)', () => {
expect((await db.install.findUnique({ where: { id: 'inst-0' } })).releasedAt).toEqual(at);
expect(await db.job.findFirst({ where: { type: 'purge', deploymentId: d.id } })).toBeTruthy();
});
test('uninstall: when the export fails the uninstall is cancelled and the install is live again, not stuck uninstalling', async () => {
const { server, deployments } = await liveDeployments(1);
const d = deployments[0];
const at = new Date(NOW.getTime() + 5 * H);
const { uninstallJob } = await jobs.scheduleUninstall({ deploymentId: d.id, totp: totpNow(), confirm: 'c0', at }, admin, NOW);
const job = (await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, at)).jobs[0];
await jobs.receiveReport(server, signedReport(job, 'failed'), at);
expect(await db.job.findUnique({ where: { id: uninstallJob.id } })).toMatchObject({ status: 'cancelled' });
expect(await db.deployment.findUnique({ where: { id: d.id } })).toMatchObject({ status: 'live' });
});
test('a failed install isn\'t uninstalled: its record is removed instead, and the short name is free', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const { deployment } = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
await expect(jobs.removeFailedInstall(deployment.id)).rejects.toMatchObject({ code: 'NOT_FAILED' });
const [job] = (await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, NOW)).jobs;
await jobs.receiveReport(server, signedReport(job, 'failed'), NOW);
await expect(jobs.scheduleUninstall({ deploymentId: deployment.id, totp: totpNow(), confirm: 'hope' }, admin, NOW)).rejects.toMatchObject({ code: 'NOT_INSTALLED' });
expect(await jobs.neverInstalled(await db.deployment.findUnique({ where: { id: deployment.id } }))).toBe(true);
await jobs.removeFailedInstall(deployment.id);
expect(await db.deployment.findUnique({ where: { id: deployment.id } })).toBeNull();
});
test('a failed install stuck "uninstalling" from before 2.3.2 can have its record removed; a live one can\'t', async () => {
const { server, deployments } = await liveDeployments(1);
await expect(jobs.removeFailedInstall(deployments[0].id)).rejects.toMatchObject({ code: 'NOT_FAILED' });
const stuck = await db.deployment.create({ data: { id: 'dep-stuck', serverId: server.id, customerId: 'cust-1', product: 'events', shortName: 'stuck', domain: 'events.stuck.co.za', webPort: 20010, apiPort: 20011, status: 'uninstalling' } });
await db.job.create({ data: { id: 'job-inst', serverId: server.id, type: 'install', deploymentId: stuck.id, status: 'failed', args: {}, notBefore: NOW, expiresAt: NOW, createdAt: NOW } });
await db.job.create({ data: { id: 'job-un', serverId: server.id, type: 'uninstall', deploymentId: stuck.id, status: 'cancelled', args: {}, notBefore: NOW, expiresAt: NOW, createdAt: new Date(NOW.getTime() + H) } });
await jobs.removeFailedInstall(stuck.id);
expect(await db.deployment.findUnique({ where: { id: stuck.id } })).toBeNull();
});
});
describe('ports and alerts', () => {
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-frontend",
"version": "2.3.1",
"version": "2.3.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-frontend",
"version": "2.3.1",
"version": "2.3.2",
"dependencies": {
"lucide-react": "^0.536.0",
"next": "^15.5.24",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-frontend",
"version": "2.3.1",
"version": "2.3.2",
"private": true,
"scripts": {
"dev": "next dev -p 3200",
@@ -2,7 +2,7 @@
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams, useSearchParams } from "next/navigation";
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";
@@ -12,6 +12,7 @@ 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 };
fastPanel: string;
canRemoveRecord: boolean;
};
const H = 60 * 60 * 1000;
@@ -19,6 +20,7 @@ const H = 60 * 60 * 1000;
/** One install on a server: proxy, updates, adopt, uninstall (§7–9). */
export default function DeploymentPage() {
const { id } = useParams<{ id: string }>();
const router = useRouter();
const warn = useSearchParams().get("warn");
const [d, setD] = useState<Detail | null>(null);
const [msg, setMsg] = useState<Msg>(warn ? { type: "err", text: warn } : null);
@@ -48,6 +50,15 @@ export default function DeploymentPage() {
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
const removeRecord = async () => {
if (!d || !window.confirm(`Remove the record of ${d.deployment.shortName}? Its install failed, so nothing of it is on the server.`)) return;
setMsg(null);
try {
await api(`/api/admin/deployments/${id}`, { method: "DELETE" });
router.push("/servers/installs");
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
if (!d) return <div><ServersNav active="/servers/installs" />{msg ? <Message msg={msg} /> : <Loading />}</div>;
const x = d.deployment;
const minAt = upd.emergency ? 15 * 60 * 1000 : 4 * H;
@@ -117,7 +128,15 @@ export default function DeploymentPage() {
</div>
)}
{x.status !== "removed" && x.status !== "uninstalling" && (
{d.canRemoveRecord && (
<div className="card border-red-200">
<h2 className="font-medium text-red-800">Remove the record</h2>
<p className="mt-1 text-sm text-slate-500">This install failed and the server already removed what it made, so there&apos;s nothing to export or uninstall. Removing the record frees the short name.</p>
<button className="btn-danger mt-3" onClick={removeRecord}>Remove the record</button>
</div>
)}
{["live", "waiting_for_proxy"].includes(x.status) && (
<form className="card grid gap-3 border-red-200 md:grid-cols-3" onSubmit={e => { e.preventDefault(); if (window.confirm(`Uninstall ${x.shortName} on ${un.at.replace("T", " ")}? The church gets its data first.`)) act(`/api/admin/deployments/${x.id}/uninstall`, { at: fromInput(un.at), totp: un.totp, confirm: un.confirm }, "Uninstall planned: the site admin was emailed and sees a banner. The export runs first."); }}>
<h2 className="font-medium text-red-800 md:col-span-3">Uninstall</h2>
<p className="text-sm text-slate-500 md:col-span-3">At the time: the church&apos;s data is exported (encrypted; the link goes to the site admin), then the site, its tunnels and database are removed. The final backup stays on the server for 30 days.</p>