import { useEffect, useState } from "react"; import { Link } from "react-router-dom"; import { api, type CurrentUser, type EndpointCheck, type EndpointInput, type EndpointKind, type EndpointValueOp } from "../api/client"; import Pagination from "../components/Pagination"; import SortableTh from "../components/SortableTh"; import TableToolbar from "../components/TableToolbar"; import TimeAgo from "../components/TimeAgo"; import { ErrorNotice } from "../components/Notice"; import { BlockSkeleton } from "../components/Skeleton"; import { usePagination } from "../hooks/usePagination"; import { useSortable } from "../hooks/useSortable"; import { useTableSearch } from "../hooks/useTableSearch"; import { downloadCsv } from "../utils/csv"; import { confirmDialog } from "../utils/dialogs"; import { readableError } from "../utils/errors"; import { toast } from "../utils/toast"; import { EmptyRow } from "../components/EmptyState"; import EndpointSuggestions from "../components/EndpointSuggestions"; import EndpointHistory from "../components/EndpointHistory"; const KIND_LABELS: Record = { http: "Web address", tcp: "Port", tls: "Certificate" }; const KIND_HINTS: Record = { http: "Asks the address and wants a good answer (and, if you like, a word in the page, or a value in a JSON answer within its limits).", tcp: "Opens a connection to the port and sees whether anything answers.", tls: "Reads the certificate the service shows and warns before it runs out.", }; type State = "waiting" | "up" | "failing" | "down" | "off"; const STATE_BADGE: Record = { waiting: { label: "Not asked yet", badge: "bg-secondary-lt text-secondary" }, up: { label: "Up", badge: "bg-green-lt text-green" }, failing: { label: "Failing", badge: "bg-yellow-lt text-yellow" }, down: { label: "Down", badge: "bg-red-lt text-red" }, off: { label: "Switched off", badge: "bg-secondary-lt text-secondary" }, }; const RANK: Record = { down: 0, failing: 1, waiting: 2, up: 3, off: 4 }; function stateOf(c: EndpointCheck): State { if (!c.enabled) return "off"; if (c.lastOk === null) return "waiting"; if (c.lastOk) return "up"; return c.consecutiveFailures >= c.failuresBeforeAlert ? "down" : "failing"; } const OP_LABELS: Record = { "<": "is below", "<=": "is at most", ">": "is above", ">=": "is at least", "=": "is equal to", "!=": "is anything but", contains: "contains", exists: "is there" }; const LIMIT_WORDS: Record = { "<": "below", "<=": "at most", ">": "above", ">=": "at least", "=": "equal to", "!=": "anything but", contains: "containing", exists: "there" }; const NUMERIC = (op: EndpointValueOp) => op === "<" || op === "<=" || op === ">" || op === ">="; /** What a value check wants, in words: "power.now should be below 5000 W". */ function limitWords(c: EndpointCheck): string { if (!c.valuePath || !c.valueOp) return ""; if (c.valueOp === "exists") return `${c.valuePath} should be there`; if (c.valueOp === "contains") return `${c.valuePath} should contain “${c.valueExpected}”`; const numeric = NUMERIC(c.valueOp) || (c.valueExpected !== null && c.valueExpected.trim() !== "" && Number.isFinite(Number(c.valueExpected))); return `${c.valuePath} should be ${LIMIT_WORDS[c.valueOp]} ${numeric ? c.valueExpected : `“${c.valueExpected}”`}${numeric && c.valueUnit ? ` ${c.valueUnit}` : ""}`; } const daysLeft = (iso: string | null) => (iso ? Math.floor((Date.parse(iso) - Date.now()) / 86_400_000) : null); interface Row extends EndpointCheck { state: State; rank: number; certDays: number | null; uptime24h: number | null; } /** The last results as a row of small ticks: green for an answer, red for none. */ function Ticks({ recent }: { recent: { at: string; ok: boolean }[] }) { if (recent.length === 0) return —; return ( r.ok).length} answered`}> {recent.map((r) => ( ))} ); } interface Draft { id: number | null; name: string; kind: EndpointKind; target: string; port: string; expectStatus: string; keyword: string; valuePath: string; valueOp: EndpointValueOp; valueExpected: string; valueUnit: string; headerName: string; headerValue: string; /** A header is already saved with this check, so its value may be left blank to keep it. */ hadHeader: boolean; insecure: boolean; intervalMinutes: string; timeoutSeconds: string; failuresBeforeAlert: string; warnDays: string; serverId: string; enabled: boolean; } const EMPTY: Draft = { id: null, name: "", kind: "http", target: "", port: "", expectStatus: "", keyword: "", valuePath: "", valueOp: "<", valueExpected: "", valueUnit: "", headerName: "", headerValue: "", hadHeader: false, insecure: false, intervalMinutes: "5", timeoutSeconds: "10", failuresBeforeAlert: "2", warnDays: "14", serverId: "", enabled: true }; const toDraft = (c: EndpointCheck): Draft => ({ id: c.id, name: c.name, kind: c.kind, target: c.target, port: c.port === null ? "" : String(c.port), expectStatus: c.expectStatus ?? "", keyword: c.keyword ?? "", valuePath: c.valuePath ?? "", valueOp: c.valueOp ?? "<", valueExpected: c.valueExpected ?? "", valueUnit: c.valueUnit ?? "", headerName: c.headerName ?? "", headerValue: "", hadHeader: c.hasHeader, insecure: c.insecure, intervalMinutes: String(c.intervalMinutes), timeoutSeconds: String(c.timeoutSeconds), failuresBeforeAlert: String(c.failuresBeforeAlert), warnDays: String(c.warnDays), serverId: c.serverId === null ? "" : String(c.serverId), enabled: c.enabled, }); const toInput = (d: Draft): EndpointInput => ({ name: d.name.trim(), kind: d.kind, target: d.target.trim(), port: d.kind === "http" || d.port.trim() === "" ? null : Number(d.port), expectStatus: d.kind === "http" && d.expectStatus.trim() ? d.expectStatus.trim() : null, keyword: d.kind === "http" && d.keyword ? d.keyword : null, valuePath: d.kind === "http" && d.valuePath.trim() ? d.valuePath.trim() : null, valueOp: d.kind === "http" && d.valuePath.trim() ? d.valueOp : null, valueExpected: d.kind === "http" && d.valuePath.trim() && d.valueOp !== "exists" ? d.valueExpected : null, valueUnit: d.kind === "http" && d.valuePath.trim() && d.valueUnit.trim() ? d.valueUnit.trim() : null, headerName: d.kind === "http" && d.headerName.trim() ? d.headerName.trim() : null, headerValue: d.kind === "http" && d.headerName.trim() && d.headerValue ? d.headerValue : undefined, insecure: d.insecure, intervalMinutes: Number(d.intervalMinutes), timeoutSeconds: Number(d.timeoutSeconds), failuresBeforeAlert: Number(d.failuresBeforeAlert), warnDays: Number(d.warnDays), serverId: d.serverId === "" ? null : Number(d.serverId), enabled: d.enabled, }); /** * "Is it up?" for the simple cases: a web address, a TCP port, a certificate. The app asks every few minutes, remembers how it went, and * raises an alert (and a notification) when a check keeps failing or a certificate is about to run out. Everyone can look; an administrator * sets them up, since each one makes this server connect somewhere. */ export default function Endpoints({ user }: { user: CurrentUser }) { const isAdmin = user.role === "admin"; const canCheck = user.role === "admin" || user.role === "operator"; const [checks, setChecks] = useState(null); const [servers, setServers] = useState<{ id: number; name: string }[]>([]); const [error, setError] = useState(null); const [draft, setDraft] = useState(null); const [busy, setBusy] = useState(false); const [asking, setAsking] = useState(null); const [historyFor, setHistoryFor] = useState<{ id: number; name: string } | null>(null); function load() { api.endpoints .list() .then((res) => { setChecks(res.checks); setServers(res.servers); }) .catch((err) => setError(readableError(err))); } useEffect(() => { load(); // The results come in on their own every few minutes: look again now and then. const t = setInterval(load, 60_000); return () => clearInterval(t); }, []); const rows: Row[] = (checks ?? []).map((c) => ({ ...c, state: stateOf(c), rank: RANK[stateOf(c)], certDays: daysLeft(c.certExpiresAt), uptime24h: c.stats?.uptime24h ?? null })); const tableSearch = useTableSearch(rows); const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "rank", "asc", { url: true }); const page = usePagination(sorted); const down = rows.filter((r) => r.state === "down" || r.state === "failing").length; const certs = rows.filter((r) => r.certDays !== null && r.certDays <= r.warnDays).length; async function save(e: React.FormEvent) { e.preventDefault(); if (!draft) return; setBusy(true); setError(null); try { if (draft.id === null) await api.endpoints.create(toInput(draft)); else await api.endpoints.update(draft.id, toInput(draft)); toast.success(draft.id === null ? `Added ${draft.name}.` : "Saved."); setDraft(null); load(); } catch (err) { setError(readableError(err)); } finally { setBusy(false); } } async function remove(c: EndpointCheck) { if (!(await confirmDialog({ title: "Remove a check", message: `Remove "${c.name}" and its history?`, confirmLabel: "Remove", danger: true }))) return; try { await api.endpoints.remove(c.id); load(); } catch (err) { setError(readableError(err)); } } async function askNow(c: EndpointCheck) { setAsking(c.id); try { const { result } = await api.endpoints.check(c.id); if (result.ok) toast.success(`${c.name}: ${result.message}`); else toast.error(`${c.name}: ${result.message}`); load(); } catch (err) { setError(readableError(err)); } finally { setAsking(null); } } function exportCsv() { downloadCsv( "endpoint-checks.csv", ["Name", "Kind", "Target", "Port", "Status", "Last answer", "Value read", "Answer time (ms)", "Uptime 24 h (%)", "Uptime 7 d (%)", "Certificate expires", "Last checked", "Server"], (sorted ?? []).map((r) => [r.name, KIND_LABELS[r.kind], r.target, r.port ?? "", STATE_BADGE[r.state].label, r.lastMessage ?? "", r.lastValue ?? "", r.lastResponseMs ?? "", r.stats?.uptime24h ?? "", r.stats?.uptime7d ?? "", r.certExpiresAt?.slice(0, 10) ?? "", r.lastCheckedAt ?? "", r.server?.name ?? ""]), ); } const set = (key: K, value: Draft[K]) => setDraft((d) => (d ? { ...d, [key]: value } : d)); const cards = [ { label: "Checks", value: checks ? String(rows.length) : "…", color: "" }, { label: "Not answering", value: checks ? String(down) : "…", color: down > 0 ? "text-red" : "text-green" }, { label: "Certificates to renew", value: checks ? String(certs) : "…", color: certs > 0 ? "text-yellow" : "" }, ]; return ( <>

Endpoints

{isAdmin && !draft && ( )}

The app asks a web address, a port or a certificate whether it is fine, every few minutes, and says so on the Alerts page and in notifications when it keeps failing or a certificate is about to run out.

{cards.map((c) => (
{c.value}
{c.label}
))}
{isAdmin && !draft && } {draft && (

{draft.id === null ? "Add a check" : `Edit ${draft.name || "the check"}`}

set("name", e.target.value)} />
{KIND_HINTS[draft.kind]}
Maintenance on that server silences this check’s alerts, and its tags can route them.
set("target", e.target.value)} />
{draft.kind !== "http" && (
set("port", e.target.value)} />
)} {draft.kind === "http" && ( <>
set("expectStatus", e.target.value)} />
set("keyword", e.target.value)} />
)} {draft.kind === "http" && (
Judge a value in the answer (optional)
For an answer in JSON: say where the value is and what it should be. For example power.now is below 5000, state is equal to playing, or, for a Prometheus query, data.result[0].value[1] is above 0. Use [0] for the first place in a list.
set("valuePath", e.target.value)} />
{draft.valueOp !== "exists" && (
set("valueExpected", e.target.value)} />
)}
set("valueUnit", e.target.value)} />
set("headerName", e.target.value)} />
set("headerValue", e.target.value)} />
For an API that wants a token. It is stored encrypted, never shown again, and only sent to this address — not to another host a redirect leads to.
)}
set("intervalMinutes", e.target.value)} /> min
set("timeoutSeconds", e.target.value)} /> s
set("failuresBeforeAlert", e.target.value)} /> failures in a row
set("warnDays", e.target.value)} /> days before
Only addresses this server may reach are accepted: not itself (loopback) and not the cloud metadata address. Your own network is fine.
)}
label="Check" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Status" sortKeyName="rank" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Answer" sortKeyName="lastResponseMs" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Uptime" sortKeyName="uptime24h" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Certificate" sortKeyName="certDays" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Checked" sortKeyName="lastCheckedAt" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> {(canCheck || isAdmin) && } {checks === null && !error && ( )} {page.pageItems?.map((c) => ( {(canCheck || isAdmin) && ( )} ))} {checks !== null && sorted?.length === 0 && ( tableSearch.setQuery("") } : { title: "Nothing is being checked yet", hint: "Ask a web address, a port or a certificate every few minutes, and hear about it when it stops answering or a certificate is about to run out.", action: isAdmin ? { label: "Add a check", onClick: () => setDraft({ ...EMPTY }) } : undefined })} /> )}
Actions
{c.name} {KIND_LABELS[c.kind]}
{c.target} {c.port !== null ? `:${c.port}` : ""}
{c.valuePath &&
{limitWords(c)}
} {c.server && (
about {c.server.name}
)}
{STATE_BADGE[c.state].label} {c.lastOk === false && c.lastMessage &&
{c.lastMessage}
} {c.lastOk === false && c.state === "failing" && (
failed {c.consecutiveFailures} of {c.failuresBeforeAlert}
)}
{c.lastValue !== null && (
{c.lastValue} {c.valueUnit && Number.isFinite(Number(c.lastValue)) ? ` ${c.valueUnit}` : ""}
)} {c.lastResponseMs === null ? — : `${c.lastResponseMs} ms`} {c.stats?.avgMs24h != null &&
avg {c.stats.avgMs24h} ms
}
{c.stats?.uptime24h == null ? ( — ) : ( <> {c.stats.uptime24h}% 24 h
{c.stats.uptime7d}% 7 d
)}
{c.certDays === null ? ( — ) : c.certDays < 0 ? ( expired {-c.certDays} d ago ) : c.certDays <= c.warnDays ? ( {c.certDays} d left ) : ( {c.certDays} d left )} {c.lastCheckedAt ? : "—"}
{canCheck && ( )} {isAdmin && ( <> )}
{historyFor && setHistoryFor(null)} />} ); }