Files
Homelab-manager/web/src/components/ServerTrends.tsx
T
bobbanandClaude Sonnet 5.5 31044b2b64 What is normal for the time: baselines per hour of the week
Each server's CPU load and memory use get a baseline for every hour of the week
(median and robust spread over up to ten weeks, four needed). A clearly high last
hour that never dropped back toward normal is a warning; everything else stays
quiet. Server History -> Trends draws a usual line and band. Setting under
Notifications, on by default.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 21:57:57 +02:00

133 lines
6.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useMemo, useState } from "react";
import { api, type BaselineView, type ServerMetricSeries } from "../api/client";
import { hourOfWeek } from "../utils/hourOfWeek";
import TimeChart from "./TimeChart";
import RangeSelect from "./RangeSelect";
import { BlockSkeleton } from "./Skeleton";
import { CHART_RANGES, useChartRange } from "../utils/chartRanges";
function levelColor(series: ServerMetricSeries): string {
const v = series.latest ?? 0;
if (series.kind === "disk") return v >= 90 ? "#f03e3e" : v >= 80 ? "#f59f00" : "#4299e1";
return "#4299e1";
}
/** One line of words about where a series is heading: a disk's rate and when it fills, or a load/memory range. */
function describeTrend(series: ServerMetricSeries): string {
if (series.kind === "disk" && series.trend) {
const { perDay, daysToFull } = series.trend;
if (daysToFull !== null) return `rising ${perDay.toFixed(1)} points a day — full in about ${daysToFull} day${daysToFull === 1 ? "" : "s"}`;
if (perDay <= -0.05) return `falling ${Math.abs(perDay).toFixed(1)} points a day`;
return "steady";
}
if (series.kind === "disk") return "not enough history for a trend yet";
const values = series.points.map((p) => p.v);
if (values.length === 0) return "";
// With hourly or daily figures the line is an average: the real lowest and highest are in the band.
const lo = Math.min(...series.points.map((p) => p.lo ?? p.v));
const hi = Math.max(...series.points.map((p) => p.hi ?? p.v));
return `${Math.round(lo)}–${Math.round(hi)}% over this time`;
}
/** How an agent-reported server's load, memory and disks have moved over a day to a year, with a forecast for a filling disk. */
export default function ServerTrends({ serverId }: { serverId: number }) {
const [days, setDays] = useChartRange(7);
const [series, setSeries] = useState<ServerMetricSeries[] | null>(null);
const [failed, setFailed] = useState(false);
const [baseline, setBaseline] = useState<BaselineView | null>(null);
// Fixed per load, so the right-hand end of a chart is when it was read and does not creep as the page re-renders.
const [to, setTo] = useState(() => Date.now());
useEffect(() => {
let alive = true;
setFailed(false);
api.servers
.metrics(serverId, days)
.then((res) => {
if (!alive) return;
setSeries(res.series);
setTo(Date.now());
})
.catch(() => alive && setFailed(true));
return () => {
alive = false;
};
}, [serverId, days]);
// What is usual for each hour of the week, loaded once; it only matters while the points are single samples or hours (the weekday means nothing for a day's average).
useEffect(() => {
let alive = true;
api.servers
.baseline(serverId)
.then((res) => alive && setBaseline(res))
.catch(() => alive && setBaseline(null));
return () => {
alive = false;
};
}, [serverId]);
const from = to - days * 86_400_000;
const rangeLabel = CHART_RANGES.find((r) => r.days === days)?.label ?? `${days} days`;
const charts = useMemo(
() =>
(series ?? []).map((s) => {
const lines = [{ name: s.label, color: levelColor(s), points: s.points as { t: string; v: number; lo?: number; hi?: number }[] }];
const slots = s.kind === "disk" || !baseline ? null : baseline.slots[s.kind];
if (slots && days <= 30) {
// The usual for the hour each point falls in, as a line with a band around it: the median and two spreads either side.
const usual = s.points.flatMap((p) => {
const h = hourOfWeek(Date.parse(p.t), baseline!.timezone);
const slot = slots[h.dow * 24 + h.hour];
if (!slot) return [];
const room = 2 * Math.max(slot.spread, s.kind === "cpu" ? 4 : 2);
return [{ t: p.t, v: slot.median, lo: Math.max(0, slot.median - room), hi: Math.min(100, slot.median + room) }];
});
if (usual.length > 0) lines.push({ name: "Usual for the time", color: "#868e96", points: usual });
}
const here = s.kind === "disk" || !baseline ? null : baseline.slots[s.kind][baseline.now.dow * 24 + baseline.now.hour];
return { s, words: describeTrend(s), series: lines, usualNow: here };
}),
[series, baseline, days],
);
return (
<div className="card mb-3">
<div className="card-header d-flex flex-wrap gap-2">
<h3 className="card-title me-auto">Trends</h3>
<RangeSelect value={days} onChange={setDays} />
</div>
<div className="card-body">
{failed ? (
<div className="text-secondary">Couldn't load the history.</div>
) : series === null ? (
<BlockSkeleton lines={4} />
) : series.length === 0 ? (
<div className="text-secondary">
No history in this stretch yet. A sample is kept about every ten minutes once the agent has reported, and its hours and days after that, so lines appear here after a short while.
</div>
) : (
<div className="trend-grid">
{charts.map(({ s, words, series: lines, usualNow }) => (
<div key={s.metric} className="trend-block mb-3">
<div className="d-flex flex-wrap align-items-baseline gap-2 mb-1">
<strong>{s.label}</strong>
<span>{s.latest !== null ? `${Math.round(s.latest)}%` : "—"}</span>
<span className="text-secondary small">{words}</span>
{usualNow && (
<span className="text-secondary small" title={`The median of this hour of the week over ${usualNow.weeks} weeks`}>
· usually about {Math.round(usualNow.median)}% now
</span>
)}
</div>
<TimeChart series={lines} from={from} to={to} compact label={`${s.label} over the last ${rangeLabel}, ${s.latest !== null ? `${Math.round(s.latest)}% now` : "no reading"}`} />
</div>
))}
{charts.some((c) => c.series.length > 1) && <div className="text-secondary small">The grey band is what is usual for that hour of the week, from this server&rsquo;s own history (the median, two spreads either side).</div>}
{days > 35 && <div className="text-secondary small">Over {days > 120 ? "more than four months" : "more than five weeks"} each point is {days > 120 ? "a day" : "an hour"}&rsquo;s average, and the shaded band is its lowest and highest.</div>}
</div>
)}
</div>
</div>
);
}