Files
Homelab-manager/web/src/pages/ServiceLevels.tsx
T
bobbanandClaude Sonnet 5.5 4269213275 Put alert rules, service levels, notifications and alert tickets on one Alert settings page, in four tabs
Old addresses (/alert-rules, /service-levels, /settings/notifications) lead to the right tab.
Notifications and Alert tickets stay administrator-only.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 20:38:15 +01:00

293 lines
13 KiB
TypeScript

import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { api, type CurrentUser, type ServiceLevel, type ServiceLevelInput, type ServiceLevelSubject } from "../api/client";
import EmptyState from "../components/EmptyState";
import { ErrorNotice } from "../components/Notice";
import { BlockSkeleton } from "../components/Skeleton";
import { confirmDialog } from "../utils/dialogs";
import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
const SUBJECT_WORDS: Record<ServiceLevelSubject, string> = { endpoint: "Endpoint check", server: "Server", integration: "Integration" };
const SUBJECT_HINTS: Record<ServiceLevelSubject, string> = {
endpoint: "Measured from the check's answers, day by day: the share that failed.",
server: "Measured from when it stopped reporting and reported again, to the minute.",
integration: "Measured from when calls to that kind of service started failing and worked again.",
};
/** "43 min", "4 h", "2 d 3 h"; under a minute is said so. */
function span(minutes: number): string {
if (minutes < 1) return "under a minute";
const m = Math.round(minutes);
if (m < 60) return `${m} min`;
const h = Math.floor(m / 60);
if (h < 24) return m % 60 && h < 10 ? `${h} h ${m % 60} min` : `${h} h`;
const d = Math.floor(h / 24);
return h % 24 ? `${d} d ${h % 24} h` : `${d} d`;
}
const COLOR = { ok: "#2fb344", at_risk: "#f59f00", breached: "#e05252", no_data: "#9aa0a6" } as const;
const BADGE = {
ok: { label: "Within budget", cls: "bg-green-lt text-green" },
at_risk: { label: "Budget nearly used", cls: "bg-yellow-lt text-yellow" },
breached: { label: "Target missed", cls: "bg-red-lt text-red" },
no_data: { label: "Nothing to measure yet", cls: "bg-secondary-lt text-secondary" },
} as const;
interface Draft {
id: number | null;
name: string;
subjectType: ServiceLevelSubject;
subjectId: string;
target: string;
alert: boolean;
}
const EMPTY: Draft = { id: null, name: "", subjectType: "endpoint", subjectId: "", target: "99.9", alert: true };
function Card({ level: l, isAdmin, onEdit, onRemove }: { level: ServiceLevel; isAdmin: boolean; onEdit: () => void; onRemove: () => void }) {
const b = l.budget;
const used = b.usedPercent ?? 0;
return (
<div className="card mb-3">
<div className="card-header">
<div>
<h3 className="card-title mb-0">
{l.name} <span className={`badge ${BADGE[b.state].cls}`}>{BADGE[b.state].label}</span>
</h3>
<div className="text-secondary small">
{SUBJECT_WORDS[l.subjectType]}: {l.subjectName ?? <em>removed</em>} · target <strong>{l.target}%</strong> a month
</div>
</div>
{isAdmin && (
<div className="card-actions btn-list flex-nowrap">
<button className="btn btn-sm btn-outline-secondary" onClick={onEdit}>
Edit
</button>
<button className="btn btn-sm btn-outline-danger" onClick={onRemove}>
Remove
</button>
</div>
)}
</div>
<div className="card-body">
{b.state === "no_data" ? (
<div className="text-secondary">{l.subjectName === null ? "What this measured has been removed." : `Nothing has been recorded for ${l.period.label} yet. ${SUBJECT_HINTS[l.subjectType]}`}</div>
) : (
<>
<div className="row g-3 mb-2">
<div className="col-6 col-md-3">
<div className="text-secondary small">So far in {l.period.label}</div>
<div className="h2 mb-0" style={{ color: COLOR[b.state] }}>
{l.measure.percent}%
</div>
</div>
<div className="col-6 col-md-3">
<div className="text-secondary small">Down</div>
<div className="h2 mb-0">{l.measure.downMinutes > 0 ? span(l.measure.downMinutes) : "—"}</div>
</div>
<div className="col-6 col-md-3">
<div className="text-secondary small">Allowed this month</div>
<div className="h2 mb-0">{span(b.allowedMinutes)}</div>
</div>
<div className="col-6 col-md-3">
<div className="text-secondary small">{b.remainingMinutes >= 0 ? "Left in the budget" : "Over the budget by"}</div>
<div className="h2 mb-0" style={{ color: b.remainingMinutes < 0 ? COLOR.breached : undefined }}>
{b.remainingMinutes >= 0 ? span(b.remainingMinutes) : span(-b.remainingMinutes)}
</div>
</div>
</div>
<div className="progress progress-sm mb-1" role="progressbar" aria-label="Error budget used" aria-valuenow={Math.min(100, Math.round(used))} aria-valuemin={0} aria-valuemax={100}>
<div className="progress-bar" style={{ width: `${Math.min(100, used)}%`, background: COLOR[b.state] }} />
</div>
<div className="text-secondary small">
{used >= 100 ? "The whole error budget is used" : `${Math.round(used)}% of the error budget is used`}
{b.projectedPercent !== null && b.state !== "breached" ? ` · at this pace, about ${b.projectedPercent}% by the end of the month` : ""}
{l.alert ? "" : " · no alert for this one"}
</div>
</>
)}
{l.history.some((h) => h.percent !== null) && (
<div className="mt-3">
<div className="text-secondary small mb-1">The months before</div>
<div className="d-flex flex-wrap gap-2">
{l.history.map((h) => (
<span
key={h.id}
className={`badge ${h.met === null ? "bg-secondary-lt text-secondary" : h.met ? "bg-green-lt text-green" : "bg-red-lt text-red"}`}
title={h.percent === null ? `${h.label}: nothing recorded` : `${h.label}: ${h.percent}%, down ${span(h.downMinutes)} of ${span(h.allowedMinutes)} allowed`}
>
{h.label.split(" ")[0].slice(0, 3)} {h.percent === null ? "—" : `${h.percent}%`}
</span>
))}
</div>
</div>
)}
</div>
</div>
);
}
/** What each service is held to — "99.9% for Gitea" — and what is left of this month's error budget; the months before show whether it was kept. */
export default function ServiceLevels({ user }: { user: CurrentUser }) {
const isAdmin = user.role === "admin";
const [data, setData] = useState<Awaited<ReturnType<typeof api.serviceLevels.list>> | null>(null);
const [error, setError] = useState<string | null>(null);
const [draft, setDraft] = useState<Draft | null>(null);
const [busy, setBusy] = useState(false);
function load() {
api.serviceLevels
.list()
.then((res) => {
setData(res);
setError(null);
})
.catch((err) => setError(readableError(err)));
}
useEffect(() => {
load();
const t = setInterval(load, 120_000);
return () => clearInterval(t);
}, []);
const set = <K extends keyof Draft>(key: K, value: Draft[K]) => setDraft((d) => (d ? { ...d, [key]: value } : d));
const subjects = data && draft ? data.subjects[draft.subjectType] : [];
async function save(e: React.FormEvent) {
e.preventDefault();
if (!draft) return;
setBusy(true);
setError(null);
const input: ServiceLevelInput = { name: draft.name.trim(), subjectType: draft.subjectType, subjectId: Number(draft.subjectId), target: Number(draft.target), alert: draft.alert };
try {
if (draft.id === null) await api.serviceLevels.create(input);
else await api.serviceLevels.update(draft.id, input);
toast.success(draft.id === null ? `Set a target for ${input.name}.` : "Saved.");
setDraft(null);
load();
} catch (err) {
setError(readableError(err));
} finally {
setBusy(false);
}
}
async function remove(l: ServiceLevel) {
if (!(await confirmDialog({ title: "Remove a target", message: `Remove the target for "${l.name}"? What was measured is kept; only the target goes.`, confirmLabel: "Remove", danger: true }))) return;
try {
await api.serviceLevels.remove(l.id);
load();
} catch (err) {
setError(readableError(err));
}
}
return (
<>
<div className="d-flex align-items-center mb-1">
<h3 className="mb-0">Service levels</h3>
{isAdmin && !draft && (
<button className="btn btn-primary ms-auto" onClick={() => setDraft({ ...EMPTY })}>
Set a target
</button>
)}
</div>
<p className="text-secondary">
What a service is held to — for example <strong>99.9%</strong> for Gitea — and what is left of this month&rsquo;s <strong>error budget</strong>: the downtime the target allows. A month with 99.9% allows about 45 minutes. The months before show whether it
was kept. When most of the budget is used it is a warning, and when it is overspent a critical alert, until the month turns over. Planned maintenance is not taken out: down is down. The same figures are in the{" "}
<Link to="/reports">monthly, quarterly and annual reports</Link>.
</p>
<ErrorNotice error={error} />
{draft && data && (
<form className="card mb-3" onSubmit={save}>
<div className="card-header">
<h3 className="card-title">{draft.id === null ? "Set a target" : `Edit ${draft.name || "the target"}`}</h3>
</div>
<div className="card-body row g-3">
<div className="col-md-4">
<label className="form-label" htmlFor="sl-name">
Name
</label>
<input id="sl-name" className="form-control" required maxLength={100} placeholder="e.g. Gitea answers" value={draft.name} onChange={(e) => set("name", e.target.value)} />
</div>
<div className="col-md-3">
<label className="form-label" htmlFor="sl-type">
Measured on
</label>
<select
id="sl-type"
className="form-select"
value={draft.subjectType}
onChange={(e) => setDraft((d) => (d ? { ...d, subjectType: e.target.value as ServiceLevelSubject, subjectId: "" } : d))}
>
{(Object.keys(SUBJECT_WORDS) as ServiceLevelSubject[]).map((k) => (
<option key={k} value={k}>
{SUBJECT_WORDS[k]}
</option>
))}
</select>
</div>
<div className="col-md-5">
<label className="form-label" htmlFor="sl-subject">
Which one
</label>
<select id="sl-subject" className="form-select" required value={draft.subjectId} onChange={(e) => set("subjectId", e.target.value)}>
<option value="">— choose —</option>
{subjects.map((s) => (
<option key={s.id} value={s.id}>
{s.name}
</option>
))}
</select>
<div className="form-hint text-secondary small mt-1">{SUBJECT_HINTS[draft.subjectType]}</div>
</div>
<div className="col-md-4">
<label className="form-label" htmlFor="sl-target">
Target, per calendar month
</label>
<div className="input-group">
<input id="sl-target" type="number" className="form-control" required min={90} max={99.999} step="any" value={draft.target} onChange={(e) => set("target", e.target.value)} />
<span className="input-group-text">%</span>
</div>
<div className="form-hint text-secondary small mt-1">
99% allows about 7 h a month, 99.9% about 45 min, 99.99% about 4 min. Between 90 and 99.999.
</div>
</div>
<div className="col-md-8 d-flex align-items-end">
<label className="form-check mb-0">
<input type="checkbox" className="form-check-input" checked={draft.alert} onChange={(e) => set("alert", e.target.checked)} />
<span className="form-check-label">Warn when 80% of the month&rsquo;s error budget is used, and when it is overspent</span>
</label>
</div>
</div>
<div className="card-footer d-flex gap-2">
<button type="submit" className="btn btn-primary" disabled={busy || draft.name.trim() === "" || draft.subjectId === ""}>
{busy ? "Saving…" : "Save"}
</button>
<button type="button" className="btn" onClick={() => setDraft(null)}>
Cancel
</button>
</div>
</form>
)}
{!data && !error && <BlockSkeleton lines={4} />}
{data?.levels.length === 0 && !draft && (
<div className="card">
<div className="card-body">
<EmptyState
title="No targets are set"
hint="Say how available something should be — an endpoint check, a server, an integration — and see what is left of the month's error budget."
action={isAdmin ? { label: "Set a target", onClick: () => setDraft({ ...EMPTY }) } : undefined}
/>
</div>
</div>
)}
{data?.levels.map((l) => (
<Card key={l.id} level={l} isAdmin={isAdmin} onEdit={() => setDraft({ id: l.id, name: l.name, subjectType: l.subjectType, subjectId: String(l.subjectId), target: String(l.target), alert: l.alert })} onRemove={() => void remove(l)} />
))}
</>
);
}