From c8359c77e9cdcb8f07332a93b62fad5c7ae58a25 Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Tue, 17 Nov 2026 13:18:20 +0200 Subject: [PATCH] Servers and the agent, dashboard (2.1.0): servers, installs, updates, jobs, ports, download page - Servers: add with a one-time join command, each server's CPU / RAM charts (24 h, 7 days, 90 days, spikes over 85% marked, table view), configuration, PM2 processes, sites, jobs and alerts. - Installs: New install (server chooser with free RAM, CPU and sites), Link existing, FastPanel steps and Proxy done, schedule / emergency update, adopt, uninstall (2FA and the short name). - Updates: one release to many installs (a batch), planned jobs. - Jobs with their reports; Ports & defaults; the public download page that decrypts an export in the browser. Co-Authored-By: Claude Opus 5.5 --- backend/src/routes/servers.js | 2 +- backend/src/utils/jobs.js | 2 +- frontend/src/app/(hub)/jobs/[id]/page.tsx | 67 +++++++ frontend/src/app/(hub)/jobs/page.tsx | 52 ++++++ frontend/src/app/(hub)/layout.tsx | 5 +- frontend/src/app/(hub)/servers/[id]/page.tsx | 169 ++++++++++++++++++ .../app/(hub)/servers/installs/[id]/page.tsx | 130 ++++++++++++++ .../src/app/(hub)/servers/installs/page.tsx | 136 ++++++++++++++ frontend/src/app/(hub)/servers/page.tsx | 104 +++++++++++ .../src/app/(hub)/servers/settings/page.tsx | 89 +++++++++ .../src/app/(hub)/servers/updates/page.tsx | 90 ++++++++++ frontend/src/app/download/[id]/page.tsx | 77 ++++++++ frontend/src/components/servers.tsx | 156 ++++++++++++++++ 13 files changed, 1075 insertions(+), 4 deletions(-) create mode 100644 frontend/src/app/(hub)/jobs/[id]/page.tsx create mode 100644 frontend/src/app/(hub)/jobs/page.tsx create mode 100644 frontend/src/app/(hub)/servers/[id]/page.tsx create mode 100644 frontend/src/app/(hub)/servers/installs/[id]/page.tsx create mode 100644 frontend/src/app/(hub)/servers/installs/page.tsx create mode 100644 frontend/src/app/(hub)/servers/page.tsx create mode 100644 frontend/src/app/(hub)/servers/settings/page.tsx create mode 100644 frontend/src/app/(hub)/servers/updates/page.tsx create mode 100644 frontend/src/app/download/[id]/page.tsx create mode 100644 frontend/src/components/servers.tsx diff --git a/backend/src/routes/servers.js b/backend/src/routes/servers.js index 825e0be..cb9f6cb 100644 --- a/backend/src/routes/servers.js +++ b/backend/src/routes/servers.js @@ -91,7 +91,7 @@ router.get('/servers/:id', wrap(async (req, res) => { server: serverSummary(s), config: masked(servers.serverConfig(s)), processes: s.lastStats?.processes || [], - stats: stats.map(x => ({ at: x.at, cpu: x.cpuPercent, cpuPeak: x.cpuPeak, ram: x.ramUsedPercent, ramPeak: x.ramPeak, disk: x.diskUsedPercent })), + stats: stats.map(x => ({ at: x.at, cpuPercent: x.cpuPercent, cpuPeak: x.cpuPeak, ramUsedPercent: x.ramUsedPercent, ramPeak: x.ramPeak, diskUsedPercent: x.diskUsedPercent })), deployments: s.deployments, jobs: recentJobs, alerts: s.alerts, diff --git a/backend/src/utils/jobs.js b/backend/src/utils/jobs.js index 4b4bae9..9d3c7f5 100644 --- a/backend/src/utils/jobs.js +++ b/backend/src/utils/jobs.js @@ -317,7 +317,7 @@ async function fastPanelText(d) { ' Allow uploads up to 25 MB.', '3. Turn on Let\'s Encrypt for the site.', `4. DNS: ${d.domain} → ${ip || ''} (${dnsOk === true ? 'checked: points there' : dnsOk === false ? 'not yet' : 'not checked: set the central server IP in Settings'})`, - `5. Then click "Proxy done" in the Hub: ${hubUrl()}/servers/deployments/${d.id}`, + `5. Then click "Proxy done" in the Hub: ${hubUrl()}/servers/installs/${d.id}`, ].join('\n'); } diff --git a/frontend/src/app/(hub)/jobs/[id]/page.tsx b/frontend/src/app/(hub)/jobs/[id]/page.tsx new file mode 100644 index 0000000..4ae039d --- /dev/null +++ b/frontend/src/app/(hub)/jobs/[id]/page.tsx @@ -0,0 +1,67 @@ +"use client"; + +import React, { useCallback, useEffect, useState } from "react"; +import Link from "next/link"; +import { useParams } from "next/navigation"; +import { api, errorText } from "@/lib/api"; +import { fmtDate } from "@/lib/format"; +import { Loading, Message, PageTitle } from "@/components/ui"; +import { ServersNav, StatusPill, type Job } from "@/components/servers"; + +type Msg = { type: "ok" | "err"; text: string } | null; + +const OUTCOME: Record = { ok: "✓", failed: "✗", skipped: "–", "rolled-back": "↺" }; + +/** One job and its full report: steps, result and the last log lines (§11). */ +export default function JobPage() { + const { id } = useParams<{ id: string }>(); + const [job, setJob] = useState(null); + const [msg, setMsg] = useState(null); + const load = useCallback(() => api<{ job: Job }>(`/api/admin/jobs/${id}`).then(r => setJob(r.job)).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]); + useEffect(() => { + load(); + const t = setInterval(() => { if (!job || ["queued", "delivered", "scheduled"].includes(job.status)) load(); }, 10000); + return () => clearInterval(t); + }, [load, job]); + + const post = async (path: string, ok: string) => { + try { await api(path, { method: "POST", body: {} }); setMsg({ type: "ok", text: ok }); load(); } catch (e) { setMsg({ type: "err", text: errorText(e) }); } + }; + + if (!job) return
{msg ? : }
; + const r = job.report; + return ( +
+
+ on {job.server?.name} · {job.id} } + actions={
+ {["queued", "scheduled"].includes(job.status) && } + {job.type === "purge" && job.status === "queued" && job.message !== "extended" && } +
} /> + + +
+
+
Window: {fmtDate(job.notBefore)} – {fmtDate(job.expiresAt)}
+
Handed to the agent: {fmtDate(job.deliveredAt)}
+
Finished: {fmtDate(job.finishedAt)}
+ {job.reason &&
Reason: {job.reason}
} + {job.message &&
Result: {job.message}
} +
Arguments: {JSON.stringify(job.args)}
+
+ {r && ( + <> +
+

Steps

+
    + {r.steps.map((s, i) =>
  1. {OUTCOME[s.outcome] || "•"}{s.name}{s.detail && ({s.detail})}
  2. )} + {!r.steps.length &&
  3. No steps reported.
  4. } +
+
+ {Object.keys(r.result || {}).length > 0 &&

Result

{JSON.stringify(r.result, null, 2)}
} +

Last log lines

{(r.log || []).join("\n") || "(none)"}
+ + )} +
+ ); +} diff --git a/frontend/src/app/(hub)/jobs/page.tsx b/frontend/src/app/(hub)/jobs/page.tsx new file mode 100644 index 0000000..728e810 --- /dev/null +++ b/frontend/src/app/(hub)/jobs/page.tsx @@ -0,0 +1,52 @@ +"use client"; + +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 { ServersNav, StatusPill, type Job } from "@/components/servers"; + +const FILTERS = [ + { key: "", label: "All" }, + { key: "upcoming", label: "Planned and running" }, + { key: "failed", label: "Failed" }, + { key: "rolled_back", label: "Rolled back" }, + { key: "missed", label: "Missed" }, + { key: "refused", label: "Refused" }, +]; + +/** Every job sent to a server's agent, newest first (§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]); + return ( +
+ + + {err && } +
{FILTERS.map(f => )}
+ {!jobs ? : ( +
+ + + {jobs.map(j => ( + + + + + + ))} +
JobServerInstallWhenStatusResult
{j.type}{j.emergency && emergency}{j.server?.name}{j.deployment?.shortName || String(j.args?.church || "–")}{fmtDate(j.notBefore)}{j.message}
+ {!jobs.length &&

No jobs.

} +
+ )} +
+ ); +} diff --git a/frontend/src/app/(hub)/layout.tsx b/frontend/src/app/(hub)/layout.tsx index bac9a1b..801e939 100644 --- a/frontend/src/app/(hub)/layout.tsx +++ b/frontend/src/app/(hub)/layout.tsx @@ -3,7 +3,7 @@ import React, { useEffect, useState } from "react"; import Link from "next/link"; import { usePathname, useRouter } from "next/navigation"; -import { LayoutDashboard, Building2, BellRing, Settings, LogOut, Rocket, Megaphone, Receipt } from "lucide-react"; +import { LayoutDashboard, Building2, BellRing, Settings, LogOut, Rocket, Megaphone, Receipt, Server } from "lucide-react"; import { api, getToken, setToken } from "@/lib/api"; import { Logo } from "@/components/ui"; @@ -13,6 +13,7 @@ const NAV = [ { href: "/", label: "Installs", icon: LayoutDashboard }, { href: "/customers", label: "Customers", icon: Building2 }, { href: "/billing", label: "Billing", icon: Receipt }, + { href: "/servers", label: "Servers", icon: Server }, { href: "/alerts", label: "Alerts", icon: BellRing }, { href: "/releases", label: "Releases", icon: Rocket }, { href: "/notices", label: "Notices", icon: Megaphone }, @@ -32,7 +33,7 @@ export default function HubLayout({ children }: { children: React.ReactNode }) { if (!me) return
Loading…
; - const active = (href: string) => (href === "/" ? pathname === "/" || pathname.startsWith("/installs") : pathname.startsWith(href)); + const active = (href: string) => (href === "/" ? pathname === "/" || pathname.startsWith("/installs") : href === "/servers" ? pathname.startsWith("/servers") || pathname.startsWith("/jobs") : pathname.startsWith(href)); return (
diff --git a/frontend/src/app/(hub)/servers/[id]/page.tsx b/frontend/src/app/(hub)/servers/[id]/page.tsx new file mode 100644 index 0000000..c437525 --- /dev/null +++ b/frontend/src/app/(hub)/servers/[id]/page.tsx @@ -0,0 +1,169 @@ +"use client"; + +import React, { useCallback, useEffect, useState } from "react"; +import Link from "next/link"; +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 { PercentChart, ServersNav, StatusPill, pct, type Deployment, type Job, type ServerSummary } from "@/components/servers"; + +type Msg = { type: "ok" | "err"; text: string } | null; +type Detail = { + server: ServerSummary; + config: Record; + processes: { name: string; church: string | null; product: string | null; status: string; memoryBytes: number; cpuPercent: number; restarts: number; uptimeSeconds: number }[]; + stats: { at: string; cpuPercent: number; cpuPeak: number; ramUsedPercent: number; ramPeak: number; diskUsedPercent: number }[]; + deployments: (Deployment & { customer: { id: string; name: string } })[]; + jobs: Job[]; + alerts: { id: string; type: string; level: string; message: string; createdAt: string; resolvedAt: string | null }[]; + ports: { port: number; role: string; note: string | null; releasedAt: string | null }[]; +}; + +/** The settings a church server's jobs need (§5); others can be added. */ +const SUGGESTED: { key: string; hint: string }[] = [ + { key: "TRUST_PROXY", hint: "Behind frp: loopback" }, + { key: "DB_HOST", hint: "The PostgreSQL server the sites use (default localhost)" }, + { key: "DB_PORT", hint: "Default 5432" }, + { key: "DB_ADMIN_URL", hint: "postgresql://admin:…@host/postgres: may create databases and roles. Blank: the local PostgreSQL via sudo -u postgres" }, +]; + +function ConfigEditor({ id, config, onSaved }: { id: string; config: Record; onSaved: (m: Msg) => void }) { + const [rows, setRows] = useState<[string, string][]>(() => { + const keys = [...new Set([...SUGGESTED.map(s => s.key), ...Object.keys(config)])]; + return keys.map(k => [k, config[k] ?? (k === "TRUST_PROXY" ? "loopback" : "")]); + }); + const set = (i: number, j: 0 | 1, v: string) => setRows(rows.map((r, n) => (n === i ? (j === 0 ? [v.toUpperCase(), r[1]] : [r[0], v]) : r))); + const save = async () => { + try { + await api(`/api/admin/servers/${id}/config`, { method: "PUT", body: { values: Object.fromEntries(rows.filter(r => r[0].trim())) } }); + onSaved({ type: "ok", text: "Configuration saved. Jobs from now on carry it, sealed to this server's key." }); + } catch (e) { onSaved({ type: "err", text: errorText(e) }); } + }; + return ( +
+

Configuration

+

The server layer of every install's .env here. Stored encrypted; sent only inside jobs, sealed to this server. Values ending in _URL, KEY, SECRET or PASSWORD show as dots: leave them to keep them.

+
+ {rows.map(([k, v], i) => ( +
+ set(i, 0, e.target.value)} placeholder="NAME" aria-label="Name" /> + set(i, 1, e.target.value)} placeholder={SUGGESTED.find(s => s.key === k)?.hint || "value"} aria-label={`${k} value`} /> + +
+ ))} +
+
+ + +
+
+ ); +} + +export default function ServerPage() { + const { id } = useParams<{ id: string }>(); + const router = useRouter(); + const [d, setD] = useState(null); + const [range, setRange] = useState<"24h" | "7d" | "90d">("24h"); + const [msg, setMsg] = useState(null); + const [agentVersion, setAgentVersion] = useState(""); + + const load = useCallback(() => api(`/api/admin/servers/${id}?range=${range}`).then(setD).catch(e => setMsg({ type: "err", text: errorText(e) })), [id, range]); + useEffect(() => { load(); }, [load]); + + const job = async (type: string, args: Record = {}) => { + setMsg(null); + try { + const r = await api<{ job: Job }>(`/api/admin/servers/${id}/jobs`, { method: "POST", body: { type, args } }); + setMsg({ type: "ok", text: `Queued: the agent picks it up within 30 seconds.` }); + router.push(`/jobs/${r.job.id}`); + } catch (e) { setMsg({ type: "err", text: errorText(e) }); } + }; + const remove = async () => { + if (!d || !window.confirm(`Remove ${d.server.name} from the Hub? Its agent stops getting jobs. (Uninstall the agent on the server too.)`)) return; + try { await api(`/api/admin/servers/${id}`, { method: "DELETE" }); router.push("/servers"); } catch (e) { setMsg({ type: "err", text: errorText(e) }); } + }; + + if (!d) return
{msg ? : }
; + const s = d.server; + return ( +
+
+ {s.mode === "central" ? "Central server" : "Church server"} · {s.hostname} · agent {s.agentVersion} · last heard {ago(s.lastSeenAt)} } /> + + +
+ + {!!d.alerts.filter(a => !a.resolvedAt).length && ( +
+ {d.alerts.filter(a => !a.resolvedAt).map(a =>
⚠ {a.message} (since {fmtDate(a.createdAt)})
)} +
+ )} + +
+ {(["24h", "7d", "90d"] as const).map(r => )} +
+
+ ({ at: p.at, value: p.cpuPercent, peak: p.cpuPeak }))} /> + ({ at: p.at, value: p.ramUsedPercent, peak: p.ramPeak }))} /> +
+ +
+
+

Resources now

+

RAM {pct(s.ram?.usedPercent)} used, {bytes(s.ram?.availableBytes)} free of {bytes(s.ram?.totalBytes)}

+

CPU {pct(s.cpu?.percent)} · load {s.cpu?.load1?.toFixed(2)} on {s.cpu?.cores} cores

+ {s.disk.map(x =>

Disk {x.mount}: {pct((x.usedBytes / Math.max(1, x.totalBytes)) * 100)} used, {bytes(x.freeBytes)} free

)} +
+
+

Versions

+

{s.versions?.os}

+

Node {s.versions?.node} · PostgreSQL {s.versions?.postgres || "–"} · frpc {s.versions?.frpc || "–"}

+ {s.mode === "church" &&

frpc {s.frpcRunning === null ? "unknown" : s.frpcRunning ? "running" : not running}

} + {s.central &&

frps.ini: proxy_bind_addr {s.central.proxyBindAddr || not set}, allow_ports {s.central.allowPorts || "any"}

} +
+
+

Actions

+ +
setAgentVersion(e.target.value)} aria-label="Agent version" />
+ +
+
+ + {s.mode === "church" && { setMsg(m); load(); }} />} + + {s.mode === "church" && ( +
+

Sites on this server

+ + + {d.deployments.map(x => ( + + ))} +
ChurchDomainVersionPorts (web, api)Status
{x.customer?.name} ({x.shortName}){x.domain}{x.version || "–"}{x.webPort}, {x.apiPort}
+ {!d.deployments.length &&

None yet. New install

} +
+ )} + + {s.mode === "church" && ( +
+

Processes (PM2)

+ + + {d.processes.map(p => )} +
NameChurchStatusMemoryCPURestarts
{p.name}{p.church || "–"}{p.status}{bytes(p.memoryBytes)}{Math.round(p.cpuPercent)}%{p.restarts}
+
+ )} + +
+

Recent jobs

+ + + {d.jobs.map(j => )} +
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 new file mode 100644 index 0000000..a3e0833 --- /dev/null +++ b/frontend/src/app/(hub)/servers/installs/[id]/page.tsx @@ -0,0 +1,130 @@ +"use client"; + +import React, { useCallback, useEffect, useState } from "react"; +import Link from "next/link"; +import { useParams, useSearchParams } from "next/navigation"; +import { api, errorText } from "@/lib/api"; +import { bytes, fmtDate } from "@/lib/format"; +import { Loading, Message, PageTitle } 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 }; + fastPanel: string; +}; + +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 warn = useSearchParams().get("warn"); + const [d, setD] = useState(null); + const [msg, setMsg] = useState(warn ? { type: "err", text: warn } : null); + const [problems, setProblems] = useState([]); + const [upd, setUpd] = useState({ version: "", at: toInput(new Date(Date.now() + 5 * H)), emergency: false, reason: "", totp: "" }); + const [adopt, setAdopt] = useState({ eventsDir: "", version: "", at: toInput(new Date(Date.now() + 5 * H)) }); + const [un, setUn] = useState({ at: toInput(new Date(Date.now() + 7 * 24 * H)), totp: "", confirm: "" }); + + const load = useCallback(() => api(`/api/admin/deployments/${id}`).then(setD).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]); + useEffect(() => { load(); }, [load]); + + const act = async (path: string, body: unknown, ok: string) => { + setMsg(null); + try { + const r = await api<{ warnings?: string[] }>(path, { method: "POST", body }); + setMsg({ type: "ok", text: `${ok}${r?.warnings?.length ? ` Note: ${r.warnings.join(" ")}` : ""}` }); + load(); + } catch (e) { setMsg({ type: "err", text: errorText(e) }); } + }; + const proxyDone = async () => { + setMsg(null); + try { + const r = await api<{ live: boolean; problems: string[] }>(`/api/admin/deployments/${id}/proxy-done`, { method: "POST" }); + setProblems(r.problems); + setMsg(r.live ? { type: "ok", text: "Live. The site admin got the welcome email." } : { type: "err", text: "The site isn't answering as expected yet:" }); + load(); + } catch (e) { setMsg({ type: "err", text: errorText(e) }); } + }; + + if (!d) return
{msg ? : }
; + const x = d.deployment; + const minAt = upd.emergency ? 15 * 60 * 1000 : 4 * H; + + return ( +
+
+ {x.domain} · on {x.server.name} · ports web {x.webPort}, api {x.apiPort} · version {x.install?.version || x.version || "–"} } /> + + + {!!problems.length &&
    {problems.map(p =>
  • {p}
  • )}
} +
+ + {(x.status === "waiting_for_proxy" || x.status === "installing") && ( +
+

Set up the site in FastPanel

+
{d.fastPanel}
+ + {x.status === "installing" &&

Waiting for the install to finish (see its job below).

} +
+ )} + + {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."); }}> +

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 && <> +
setUpd({ ...upd, reason: e.target.value })} />
+
setUpd({ ...upd, totp: e.target.value })} />
+ } +
+
+ )} + + {x.status === "live" && x.install?.version?.startsWith("2.1.") && ( +
{ e.preventDefault(); act(`/api/admin/deployments/${x.id}/adopt`, { eventsDir: adopt.eventsDir, version: adopt.version || undefined, at: fromInput(adopt.at) }, "Adopt planned. The site admin was emailed."); }}> +

Move onto the monorepo (crosscode adopt)

+
setAdopt({ ...adopt, eventsDir: e.target.value })} />
+
setAdopt({ ...adopt, version: e.target.value })} />
+
setAdopt({ ...adopt, at: e.target.value })} />
+
+
+ )} + +
+

Jobs

+ + + {x.jobs.map(j => ( + + + + + + ))} +
JobWhenStatusResult
{j.type}{j.emergency && emergency}{fmtDate(j.notBefore)}{j.message}{["queued", "scheduled"].includes(j.status) && }
+
+ + {!!x.exports.length && ( +
+

Exports

+ {x.exports.map(e =>

{e.id}: {bytes(e.bytes)}, {e.deletedAt ? `deleted ${fmtDate(e.deletedAt)}` : `until ${fmtDate(e.expiresAt)}`}{e.downloadedAt ? `, downloaded ${fmtDate(e.downloadedAt)}` : ", not downloaded yet"}

)} +
+ )} + + {x.status !== "removed" && x.status !== "uninstalling" && ( +
{ 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."); }}> +

Uninstall

+

At the time: the church'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.

+
setUn({ ...un, at: e.target.value })} />
+
setUn({ ...un, confirm: e.target.value })} />
+
setUn({ ...un, totp: e.target.value })} />
+
+
+ )} +
+ ); +} diff --git a/frontend/src/app/(hub)/servers/installs/page.tsx b/frontend/src/app/(hub)/servers/installs/page.tsx new file mode 100644 index 0000000..a785e5c --- /dev/null +++ b/frontend/src/app/(hub)/servers/installs/page.tsx @@ -0,0 +1,136 @@ +"use client"; + +import React, { useCallback, useEffect, 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 { ServersNav, StatusPill, pct, type Deployment, type ServerSummary } from "@/components/servers"; + +type Msg = { type: "ok" | "err"; text: string } | null; +type Customer = { id: string; name: string; domain?: string | null }; +type InstallRow = { id: string; name: string; url: string; customer: { id: string; name: string } | null; version: string | null }; + +const emptyNew = { customerId: "", serverId: "", shortName: "", domain: "", timezone: "", adminName: "", adminEmail: "", version: "" }; +const emptyLink = { installId: "", serverId: "", shortName: "", webPort: "", apiPort: "" }; + +/** Installs on servers: New install (§7) and linking existing installs (§14). */ +export default function InstallsPage() { + const router = useRouter(); + const [list, setList] = useState(null); + const [srv, setSrv] = useState([]); + const [customers, setCustomers] = useState([]); + const [installs, setInstalls] = useState([]); + const [mode, setMode] = useState<"none" | "new" | "link">("none"); + const [form, setForm] = useState(emptyNew); + const [link, setLink] = useState(emptyLink); + const [msg, setMsg] = useState(null); + const [busy, setBusy] = useState(false); + + const load = useCallback(() => { + api<{ deployments: Deployment[] }>("/api/admin/deployments").then(r => setList(r.deployments)).catch(e => setMsg({ type: "err", text: errorText(e) })); + api<{ servers: ServerSummary[] }>("/api/admin/servers").then(r => setSrv(r.servers.filter(s => s.mode === "church"))).catch(() => {}); + }, []); + useEffect(() => { load(); }, [load]); + useEffect(() => { + if (mode === "new" && !customers.length) api("/api/admin/customers").then(setCustomers).catch(() => {}); + if (mode === "link" && !installs.length) api("/api/admin/installs").then(setInstalls).catch(() => {}); + }, [mode, customers.length, installs.length]); + + const submitNew = async (e: React.FormEvent) => { + e.preventDefault(); + setBusy(true); + setMsg(null); + try { + const r = await api<{ deployment: Deployment; warnings: string[] }>("/api/admin/deployments", { method: "POST", body: { ...form, product: "events", version: form.version || undefined } }); + router.push(`/servers/installs/${r.deployment.id}${r.warnings.length ? `?warn=${encodeURIComponent(r.warnings.join(" "))}` : ""}`); + } catch (err) { setMsg({ type: "err", text: errorText(err) }); } + setBusy(false); + }; + const submitLink = async (e: React.FormEvent) => { + e.preventDefault(); + setBusy(true); + setMsg(null); + try { + const r = await api<{ deployment: Deployment }>("/api/admin/deployments/link", { method: "POST", body: link }); + router.push(`/servers/installs/${r.deployment.id}`); + } catch (err) { setMsg({ type: "err", text: errorText(err) }); } + setBusy(false); + }; + const f = (k: keyof typeof emptyNew) => ({ value: form[k], onChange: (e: React.ChangeEvent) => setForm({ ...form, [k]: e.target.value }) }); + const l = (k: keyof typeof emptyLink) => ({ value: link[k], onChange: (e: React.ChangeEvent) => setLink({ ...link, [k]: e.target.value }) }); + + return ( +
+
} /> + + + + {mode === "new" && ( +
+

New Cross Events install

+
+

Folders, database and tunnels: a-z, 0-9 and -.

+
+
+
+

Gets the welcome email and update notices.

+
+ Server +
+ {srv.map(s => { + const low = (s.ram?.availableBytes ?? 0) < 1.5 * 1024 ** 3; + return ( + + ); + })} +
+
+
+
+ + +

The Hub makes the licence, picks two ports, and the agent installs within a minute. You get the report and the FastPanel steps by email.

+
+
+ )} + + {mode === "link" && ( +
+

Link an install that's already on a server

+

For sites installed by hand or moved with crosscode adopt. Nothing on the server changes; the Hub records the server, folder name and ports (see the server's church.env and frpc.ini).

+
+
+
+
+
+
+
+
+
+ )} + + {!list ? : ( +
+ + + {list.map(d => ( + + ))} +
ChurchDomainServerVersionLast heartbeatStatus
{d.customer?.name} ({d.shortName}){d.domain}{d.server?.name}{d.install?.version || d.version || "–"}{ago(d.install?.lastHeartbeatAt)}
+ {!list.length &&

No installs on servers yet.

} +
+ )} +
+ ); +} diff --git a/frontend/src/app/(hub)/servers/page.tsx b/frontend/src/app/(hub)/servers/page.tsx new file mode 100644 index 0000000..2ae5c38 --- /dev/null +++ b/frontend/src/app/(hub)/servers/page.tsx @@ -0,0 +1,104 @@ +"use client"; + +import React, { useCallback, useEffect, useState } from "react"; +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 { ServersNav, StatusPill, pct, type ServerSummary } from "@/components/servers"; + +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 [msg, setMsg] = useState(null); + const [adding, setAdding] = useState(false); + const [name, setName] = useState(""); + const [mode, setMode] = useState<"church" | "central">("church"); + const [joined, setJoined] = useState<{ command: string; expiresAt: string } | null>(null); + + const load = useCallback(() => api<{ servers: ServerSummary[] }>("/api/admin/servers").then(r => setList(r.servers)).catch(e => setMsg({ type: "err", text: errorText(e) })), []); + useEffect(() => { load(); const t = setInterval(load, 30000); return () => clearInterval(t); }, [load]); + + const add = async (e: React.FormEvent) => { + e.preventDefault(); + setMsg(null); + try { + const r = await api<{ command: string; expiresAt: string }>("/api/admin/servers/join-token", { method: "POST", body: { name, mode } }); + setJoined(r); + } catch (err) { setMsg({ type: "err", text: errorText(err) }); } + }; + + return ( +
+ { setAdding(true); setJoined(null); setName(""); }}> Add server} /> + + + + {adding && ( +
+ {!joined ? ( +
+
setName(e.target.value)} placeholder="church-server-2" required />
+
+ +
+ + +
+ ) : ( +
+

Run this on the new server as root. The token works once, until {new Date(joined.expiresAt).toLocaleTimeString()}:

+
{joined.command}
+
+ + +
+

The server shows here within a minute of joining. Then set its configuration (database, TRUST_PROXY) on its page.

+
+ )} +
+ )} + + {!list ? : list.length === 0 ?

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

: ( +
+ {list.map(s => { + const disk = s.disk.reduce((m, d) => Math.max(m, d.totalBytes ? (d.usedBytes / d.totalBytes) * 100 : 0), 0); + return ( + +
+
+
{s.name}
+
{s.mode === "central" ? "Central server" : "Church server"} · {s.hostname || "?"} · agent {s.agentVersion || "?"}
+
+ +
+
+
RAM used
{pct(s.ram?.usedPercent)} of {bytes(s.ram?.totalBytes)}
+
CPU now · day avg
{pct(s.cpu?.percent)} · {pct(s.lastDay?.cpuAvg)}
+
Fullest disk
{pct(disk)}
+
+
+ {s.mode === "church" && {s.deployments ?? 0} site(s)} + Last heard {ago(s.lastSeenAt)} + {s.mode === "church" && s.frpcRunning === false && frpc not running} + {s.central && !s.central.proxyBindAddr && proxy_bind_addr not set} +
+ {!!s.alerts?.length && ( +
    + {s.alerts.map(a =>
  • ⚠ {a.message}
  • )} +
+ )} + + ); + })} +
+ )} +
+ ); +} diff --git a/frontend/src/app/(hub)/servers/settings/page.tsx b/frontend/src/app/(hub)/servers/settings/page.tsx new file mode 100644 index 0000000..2b85fe3 --- /dev/null +++ b/frontend/src/app/(hub)/servers/settings/page.tsx @@ -0,0 +1,89 @@ +"use client"; + +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 { ServersNav } from "@/components/servers"; + +type Msg = { type: "ok" | "err"; text: string } | null; +type Port = { port: number; role: string; note: string | null; releasedAt: string | null; deploymentId: string | null; server: { id: string; name: string } | null }; + +/** The port list (§6) and the install defaults (§5): the same for every install. */ +export default function ServerSettingsPage() { + const [ports, setPorts] = useState(null); + const [range, setRange] = useState({ from: "20000", to: "29999" }); + const [defaults, setDefaults] = useState<[string, string][]>([]); + const [ip, setIp] = useState(""); + const [newPort, setNewPort] = useState({ port: "", note: "" }); + const [msg, setMsg] = useState(null); + + const load = useCallback(() => { + api<{ ports: Port[]; range: { from: number; to: number } }>("/api/admin/ports").then(r => { setPorts(r.ports); setRange({ from: String(r.range.from), to: String(r.range.to) }); }).catch(e => setMsg({ type: "err", text: errorText(e) })); + api<{ defaults: Record; centralServerIp: string }>("/api/admin/install-defaults").then(r => { setDefaults(Object.entries(r.defaults)); setIp(r.centralServerIp); }).catch(() => {}); + }, []); + useEffect(() => { load(); }, [load]); + + const saveDefaults = async () => { + try { + await api("/api/admin/install-defaults", { method: "PUT", body: { defaults: Object.fromEntries(defaults.filter(d => d[0].trim())), portRange: { from: range.from, to: range.to }, centralServerIp: ip } }); + setMsg({ type: "ok", text: "Saved." }); + } catch (e) { setMsg({ type: "err", text: errorText(e) }); } + }; + const take = async (e: React.FormEvent) => { + e.preventDefault(); + try { await api("/api/admin/ports", { method: "POST", body: { port: newPort.port, note: newPort.note } }); setNewPort({ port: "", note: "" }); load(); } catch (err) { setMsg({ type: "err", text: errorText(err) }); } + }; + const free = async (port: number) => { + try { await api(`/api/admin/ports/${port}`, { method: "DELETE" }); load(); } catch (err) { setMsg({ type: "err", text: errorText(err) }); } + }; + + return ( +
+
+ + + +
+ +
+

Install defaults

+

The defaults layer of every install's .env (HUB_URL, APP_TIMEZONE, job switches, SENTRY_DSN…). A server's own configuration is on its page.

+ {defaults.map(([k, v], i) => ( +
+ setDefaults(defaults.map((d, n) => (n === i ? [e.target.value.toUpperCase(), d[1]] : d)))} /> + setDefaults(defaults.map((d, n) => (n === i ? [d[0], e.target.value] : d)))} /> + +
+ ))} + +
+
setRange({ ...range, from: e.target.value })} />
+
setRange({ ...range, to: e.target.value })} />

Match allow_ports in frps.ini.

+
setIp(e.target.value)} />

To check a new install's DNS.

+
+ +
+ +
+

Port list

+

Every port frps opens on the central server must be unique across servers. Mark ports used by anything else (today's tunnels written by hand) as taken.

+
+ setNewPort({ ...newPort, port: e.target.value })} aria-label="Port" /> + setNewPort({ ...newPort, note: e.target.value })} aria-label="Note" /> + +
+ {!ports ? : ( + + + {ports.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) && }
+ )} +
+
+ ); +} diff --git a/frontend/src/app/(hub)/servers/updates/page.tsx b/frontend/src/app/(hub)/servers/updates/page.tsx new file mode 100644 index 0000000..550e25d --- /dev/null +++ b/frontend/src/app/(hub)/servers/updates/page.tsx @@ -0,0 +1,90 @@ +"use client"; + +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 { ServersNav, StatusPill, toInput, fromInput, type Deployment, type Job } from "@/components/servers"; + +type Msg = { type: "ok" | "err"; text: string } | null; +const H = 60 * 60 * 1000; + +/** + * 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). + */ +export default function UpdatesPage() { + const [deployments, setDeployments] = useState(null); + 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(() => {}); + }, []); + useEffect(() => { load(); }, [load]); + const byVersion = useMemo(() => [...new Set((deployments || []).map(d => d.install?.version || d.version || "?"))].sort(), [deployments]); + + 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(" ")}` : ""}` }); + setChosen([]); + load(); + } catch (err) { setMsg({ type: "err", text: errorText(err) }); } + }; + + return ( +
+
+ + + +
+ + {!deployments ? : ( +
+
+ Select: + + {byVersion.map(v => )} + +
+
+ {deployments.map(d => ( + + ))} + {!deployments.length &&

No live installs on servers.

} +
+
+
setForm({ ...form, version: e.target.value })} />
+
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 && <> +
setForm({ ...form, reason: e.target.value })} />
+
setForm({ ...form, totp: e.target.value })} />
+ } +
+ +
+ )} + +
+

Planned and running

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

Nothing planned.

} +
+
+ ); +} diff --git a/frontend/src/app/download/[id]/page.tsx b/frontend/src/app/download/[id]/page.tsx new file mode 100644 index 0000000..7d4a464 --- /dev/null +++ b/frontend/src/app/download/[id]/page.tsx @@ -0,0 +1,77 @@ +"use client"; + +import React, { useEffect, useState } from "react"; +import { useParams } from "next/navigation"; +import { Download, Lock } from "lucide-react"; +import { API_URL } from "@/lib/api"; +import { bytes, fmtDate } from "@/lib/format"; +import { Logo } from "@/components/ui"; + +/** + * A church's export (crosscode-platform AGENT-1.0-PLAN §9). The file on the Hub is encrypted; the + * key is the part of the link after #, which browsers never send to a server. This page fetches + * the encrypted bytes and decrypts them here (AES-256-GCM: 12-byte IV ‖ ciphertext ‖ tag). + */ +const fromB64u = (s: string) => Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((s.length + 3) % 4)), c => c.charCodeAt(0)); + +export default function DownloadPage() { + const { id } = useParams<{ id: string }>(); + const [meta, setMeta] = useState<{ bytes: number; expiresAt: string } | null>(null); + const [state, setState] = useState<"loading" | "ready" | "working" | "done" | "error">("loading"); + const [error, setError] = useState(""); + + useEffect(() => { + if (!window.location.hash.slice(1)) { setState("error"); setError("This link is missing its key (the part after #). Use the whole link from the email."); return; } + fetch(`${API_URL}/api/exports/${encodeURIComponent(id)}`).then(async r => { + if (!r.ok) throw new Error((await r.json().catch(() => null))?.message || "This download has expired or doesn't exist."); + setMeta(await r.json()); + setState("ready"); + }).catch(e => { setState("error"); setError(e.message); }); + }, [id]); + + const download = async () => { + setState("working"); + try { + const key = fromB64u(window.location.hash.slice(1)); + if (key.length !== 32) throw new Error("This link's key isn't complete. Copy the whole link from the email."); + const res = await fetch(`${API_URL}/api/exports/${encodeURIComponent(id)}/file`); + if (!res.ok) throw new Error("The file couldn't be downloaded. It may have expired."); + const data = new Uint8Array(await res.arrayBuffer()); + const cryptoKey = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["decrypt"]); + let zip: ArrayBuffer; + try { + zip = await crypto.subtle.decrypt({ name: "AES-GCM", iv: data.slice(0, 12) }, cryptoKey, data.slice(12)); + } catch { + throw new Error("The file couldn't be opened with this link's key. Check you used the whole link."); + } + const url = URL.createObjectURL(new Blob([zip], { type: "application/zip" })); + const a = document.createElement("a"); + a.href = url; + a.download = "church-data.zip"; + a.click(); + setTimeout(() => URL.revokeObjectURL(url), 60000); + setState("done"); + } catch (e) { + setState("error"); + setError(e instanceof Error ? e.message : "Something went wrong."); + } + }; + + return ( +
+ +
+

Your church's data

+

One ZIP file with your events, people, registrations, payments, check-ins and rosters (export.json, explained in README.txt) and the uploaded files.

+

The file is encrypted. It's opened here in your browser with the key in your link; we can't read it.

+ {state === "loading" &&

Checking the link…

} + {meta && state !== "error" &&

{bytes(meta.bytes)} · available until {fmtDate(meta.expiresAt)}

} + {(state === "ready" || state === "working" || state === "done") && ( + + )} + {state === "done" &&

Saved as church-data.zip.

} + {state === "error" &&

{error}

} +
+
+ ); +} diff --git a/frontend/src/components/servers.tsx b/frontend/src/components/servers.tsx new file mode 100644 index 0000000..3c5d12d --- /dev/null +++ b/frontend/src/components/servers.tsx @@ -0,0 +1,156 @@ +"use client"; + +import React, { useMemo, useRef, useState } from "react"; +import { fmtDate } from "@/lib/format"; + +/** Shared pieces for the servers pages (2.1.0). */ + +export type ServerSummary = { + id: string; name: string; mode: "church" | "central"; hostname: string | null; agentVersion: string | null; + lastSeenAt: string | null; joinedAt: string; removedAt: string | null; notes: string | null; online: boolean; + ram: { totalBytes: number; availableBytes: number; usedPercent: number } | null; + cpu: { percent: number; load1: number; cores: number } | null; + disk: { mount: string; totalBytes: number; usedBytes: number; freeBytes: number }[]; + versions: { os: string; node: string; postgres: string | null; frpc: string | null; agent: string } | null; + frpcRunning: boolean | null; + central: { proxyBindAddr: string | null; allowPorts: string | null; frpsRunning: boolean | null } | null; + deployments?: number; + alerts?: { type: string; level: string; message: string; createdAt: string }[]; + lastDay?: { cpuAvg: number | null; ramAvg: number | null; cpuPeak: number | null; ramPeak: number | null } | null; +}; + +export type Deployment = { + id: string; serverId: string; customerId: string; installId: string | null; product: string; shortName: string; domain: string; + webPort: number; apiPort: number; status: string; version: string | null; adminName: string | null; adminEmail: string | null; + liveAt: string | null; createdAt: string; + server?: { id: string; name: string }; customer?: { id: string; name: string }; + install?: { id: string; version: string | null; lastHeartbeatAt: string | null; url: string } | null; +}; + +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; + report?: { status: string; steps: { name: string; startedAt: string; finishedAt: string | null; outcome: string; detail?: string }[]; result: Record; log: string[]; message?: string } | null; +}; + +const TONE: Record = { + green: "bg-green-50 text-green-700 ring-green-600/20", + amber: "bg-amber-50 text-amber-800 ring-amber-600/20", + red: "bg-red-50 text-red-700 ring-red-600/20", + blue: "bg-indigo-50 text-indigo-700 ring-indigo-600/20", + grey: "bg-slate-100 text-slate-600 ring-slate-500/20", +}; + +const STATUS: Record = { + // deployments + installing: ["Installing", "blue"], waiting_for_proxy: ["Waiting for proxy", "amber"], live: ["Live", "green"], failed: ["Failed", "red"], + uninstalling: ["Uninstalling", "amber"], removed: ["Removed", "grey"], + // jobs + scheduled: ["Waiting its turn", "grey"], queued: ["Due", "blue"], delivered: ["Running", "blue"], succeeded: ["Succeeded", "green"], + rolled_back: ["Rolled back", "amber"], refused: ["Refused", "red"], expired: ["Expired", "red"], missed: ["Missed", "red"], cancelled: ["Cancelled", "grey"], + // servers + online: ["Online", "green"], offline: ["Offline", "red"], +}; + +/** A status as a label (never colour alone). */ +export function StatusPill({ status }: { status: string }) { + const [label, tone] = STATUS[status] || [status, "grey"]; + return {label}; +} + +export const pct = (n: number | null | undefined) => (n == null ? "–" : `${Math.round(n)}%`); + +// works in the browser's time; the API takes ISO. +export const toInput = (d: Date) => new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 16); +export const fromInput = (v: string) => (v ? new Date(v).toISOString() : ""); + +/** + * A single-series line chart of a percentage (0–100) over time, with spikes over `spike`% + * marked, a crosshair tooltip and a table view. One axis; the title names the series. + */ +export function PercentChart({ title, points, spike = 85 }: { title: string; points: { at: string; value: number; peak: number }[]; spike?: number }) { + const W = 640, H = 160, L = 34, R = 8, T = 10, B = 22; + const [hover, setHover] = useState(null); + const svgRef = useRef(null); + const times = useMemo(() => points.map(p => new Date(p.at).getTime()), [points]); + if (points.length < 2) return

{title}

Not enough data yet.

; + const t0 = times[0], t1 = times[times.length - 1] || t0 + 1; + const x = (t: number) => L + ((t - t0) / Math.max(1, t1 - t0)) * (W - L - R); + const y = (v: number) => T + (1 - Math.min(100, Math.max(0, v)) / 100) * (H - T - B); + const path = points.map((p, i) => `${i ? "L" : "M"}${x(times[i]).toFixed(1)},${y(p.value).toFixed(1)}`).join(""); + const spikes = points.map((p, i) => ({ p, i })).filter(({ p }) => p.peak > spike); + const onMove = (e: React.MouseEvent) => { + const r = svgRef.current?.getBoundingClientRect(); + if (!r) return; + const t = t0 + ((((e.clientX - r.left) / r.width) * W - L) / (W - L - R)) * (t1 - t0); + let best = 0; + for (let i = 1; i < times.length; i++) if (Math.abs(times[i] - t) < Math.abs(times[best] - t)) best = i; + setHover(best); + }; + const h = hover != null ? points[hover] : null; + return ( +
+
+

{title}

+ {spikes.length ? `${spikes.length} spike${spikes.length === 1 ? "" : "s"} over ${spike}%` : `No spikes over ${spike}%`} +
+
+ setHover(null)}> + {[0, 50, 100].map(v => ( + + + {v}% + + ))} + + {fmtDate(points[0].at)} + {fmtDate(points[points.length - 1].at)} + + {spikes.map(({ p, i }) => {`Spike ${Math.round(p.peak)}% at ${fmtDate(p.at)}`})} + {h && hover != null && ( + + + + + )} + + {h && hover != null && ( +
+
{fmtDate(h.at)}
+
{Math.round(h.value)}% (peak {Math.round(h.peak)}%)
+
+ )} +
+
+ Show as a table +
+ + + {points.slice(-200).reverse().map(p => )} +
TimeAveragePeak
{fmtDate(p.at)}{Math.round(p.value)}%{Math.round(p.peak)}%
+
+
+
+ ); +} + +const SUBNAV = [ + { href: "/servers", label: "Servers" }, + { href: "/servers/installs", label: "Installs" }, + { href: "/servers/updates", label: "Updates" }, + { href: "/jobs", label: "Jobs" }, + { href: "/servers/settings", label: "Ports & defaults" }, +]; + +/** The links between the servers pages. */ +export function ServersNav({ active }: { active: string }) { + return ( + + ); +}