Add small trend lines to the rows of the server, endpoint and integration lists
Server cards show load and memory over the last 24 hours, endpoint checks show their answer times with a tick where a check failed, and integrations that keep a figure history show their headline figure over the last week. Each list asks for all its lines in one request, drawn from the history already kept, and each line has a sentence for screen readers. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5750350565
commit
639408c0d0
15 files changed
+707
No files matched your search
@@ -913,6 +913,8 @@ exists; it can be hidden, and brought back from the search box.
|
||||
|
||||
**Proxmox snapshots.** Click a guest on Infrastructure → Proxmox and its drawer has a **Snapshots** section: what there is (oldest first, a branch indented, *with memory* marked), **Take a snapshot** for operators (a name or one from the time, a description, and for a running VM whether to keep its memory), and **Roll back…** and **Delete…** for administrators, each behind a confirmation that says what is lost. Proxmox does each as a task, followed for up to 20 seconds; each is in the audit log and the change log. The API token needs VM.Snapshot and VM.Snapshot.Rollback (the PVEVMAdmin role has them). The guest actions (start, shut down, restart, stop) were there already.
|
||||
|
||||
**Small trends in lists.** The rows of three lists carry a small line for which way things are going: each **server's card** (Infrastructure → Servers) has its load and memory over the last 24 hours (red or orange when it ends high), each **endpoint check** has how long it took to answer over the last day, with a red tick under each stretch in which a check failed, and each **integration** that keeps a history (Integrations, as cards or table, with a *Last week* column) has the figure it is known for over the last week — DNS queries for AdGuard, the queue for Sonarr, photos for Immich, the monthly cost for Hetzner. A gap in the data is a gap in the line, the newest reading is a dot, and each line is a picture with a sentence for a screen reader (*CPU load, last 24 hours: 12% now, between 3% and 40%*). They are drawn from the history the app already keeps (nothing new is stored), come from one request for the whole list, refresh every five minutes and are simply left out where there is no history. A line fitted to its own data makes a small change look steep — the sentence and the numbers beside it say how big it really is. The full charts are one click away on each page.
|
||||
|
||||
**On a phone.** Below desktop width the top bar (logo and menu button) stays at the top of the screen so the menu is always within reach, with a menu button of at least 44 px; an open menu scrolls by itself (it no longer pushes the page down), its rows are finger-sized and the favourite stars are always visible; text is a little larger on a small screen, toasts run across the width and drawers fill it. The page asks for the whole screen (`viewport-fit=cover`) and keeps clear of the notch, the rounded corners and the home bar, which matters when it is installed to the home screen (the status bar then sits over the app). Tables turn into stacked cards, form fields are 16 px so a phone does not zoom in on them, and what is pressed does not wait for a second tap. Checked at 375 px: no page scrolls sideways.
|
||||
|
||||
**Swedish interface.** Press *Svenska* under *Language* in the user menu and the whole screen is drawn again in Swedish at once; the choice is kept on your account and follows you to any browser (without a choice the browser's language decides, and that guess is not stored). Swedish covers the menu, the shared parts (search, tables, dialogs, "5 min ago"), the sign-in page, and the headings, buttons, table columns, filters and messages of the pages used every day — Dashboard, Alerts, Servers, Updates, Maintenance, My work, Coming up, To do, Integrations and Settings → Display. Text with no Swedish yet is shown in English, so nothing looks broken. Not yet translated: what the server writes (alert messages, notifications, digests, reports, e-mail), the long page introductions and the less-used pages. How to add more is in docs/LANGUAGES.md.
|
||||
|
||||
@@ -11,6 +11,7 @@ import { sealSecret } from "../services/sealed.js";
|
||||
import { VALUE_OPS, valueProblem } from "../services/valueCheck.js";
|
||||
import { loadDismissed, loadSuggestions, saveDismissed } from "../services/endpointSuggestions.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
import { endpointSparklines } from "../services/sparklines.js";
|
||||
|
||||
export const endpointsRouter = Router();
|
||||
|
||||
@@ -86,6 +87,11 @@ endpointsRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
});
|
||||
}));
|
||||
|
||||
// How long each check took to answer over the last day (and when one failed), as short series for the lines in the list.
|
||||
endpointsRouter.get("/sparklines", asyncHandler(async (_req, res) => {
|
||||
res.json({ hours: 24, checks: await endpointSparklines() });
|
||||
}));
|
||||
|
||||
// How one check has done over a day, a week, a month, three months or a year: availability and answer times, for the chart on its page.
|
||||
endpointsRouter.get("/:id/history", asyncHandler(async (req, res) => {
|
||||
const id = /^\d+$/.test(req.params.id) ? Number(req.params.id) : NaN;
|
||||
|
||||
@@ -31,6 +31,7 @@ import { dockerVulnSyncStatuses, findingsOf, imageAgeDays, imagesOf, isDockerVul
|
||||
import { invalidateAlertsCache } from "../services/alerts.js";
|
||||
import { forgetReading, readAfterChange, readIntegrationNow } from "../services/integrationSyncs.js";
|
||||
import { getIntegrationFigures, hasFigures } from "../services/integrationFigures.js";
|
||||
import { integrationSparklines } from "../services/sparklines.js";
|
||||
import { getSettings, updateSettings } from "../services/settingsStore.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
import { ID_PATTERNS, isValidId } from "../utils/pathSegment.js";
|
||||
@@ -45,6 +46,11 @@ integrationsRouter.get("/fields", (_req, res) => {
|
||||
res.json({ fields: INTEGRATION_FIELDS });
|
||||
});
|
||||
|
||||
// The figure each integration is known for, over the last week, as short series for the lines in the list (the full history is /:id/figures).
|
||||
integrationsRouter.get("/sparklines", asyncHandler(async (_req, res) => {
|
||||
res.json({ days: 7, integrations: await integrationSparklines() });
|
||||
}));
|
||||
|
||||
integrationsRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
const rows = await db
|
||||
.select({
|
||||
|
||||
@@ -27,6 +27,7 @@ import { invalidateAlertsCache } from "../services/alerts.js";
|
||||
import { getSettings, updateSettings } from "../services/settingsStore.js";
|
||||
import { osSummary } from "../services/osLifecycle.js";
|
||||
import { normaliseHostname } from "../utils/hostnames.js";
|
||||
import { serverSparklines } from "../services/sparklines.js";
|
||||
|
||||
export const serversRouter = Router();
|
||||
|
||||
@@ -253,6 +254,11 @@ serversRouter.patch("/:id", requireRole("admin"), asyncHandler(async (req, res)
|
||||
|
||||
// For the dashboard widget. Computed here, with the health monitor's own rules and the thresholds from Settings
|
||||
// (which viewers can't read), so the widget and the alerts always agree about what "offline" and "full" mean.
|
||||
// The last day's load and memory of every server that reports them, as short series for the lines in a list. Anyone signed in, like the list itself.
|
||||
serversRouter.get("/sparklines", asyncHandler(async (_req, res) => {
|
||||
res.json({ hours: 24, servers: await serverSparklines() });
|
||||
}));
|
||||
|
||||
serversRouter.get("/summary", asyncHandler(async (_req, res) => {
|
||||
const rows = await db
|
||||
.select({ id: servers.id, name: servers.name, osType: servers.osType, lastSeenAt: servers.lastSeenAt, disks: servers.disks, thresholds: servers.thresholds })
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* Short series for the small lines in the rows of a list — a server's load and memory over the last day, how long an endpoint took to answer (and when it did not), the figure an integration is
|
||||
* known for over the last week — so a list says not only how things are but which way they are going. Every one is worked out for all rows at once, in the database, so a list asks once.
|
||||
*
|
||||
* A series is a fixed number of equal slices from `from` to now, each the average of what was read in it, or null where nothing was (a gap is a gap, not a line through it). Nothing here is new data:
|
||||
* it is the history the app already keeps (services/serverMetrics.ts, services/endpointChecks.ts, services/integrationFigures.ts).
|
||||
*/
|
||||
import { sql } from "drizzle-orm";
|
||||
import { db } from "../db/client.js";
|
||||
|
||||
export const SLICES = 24;
|
||||
const HOUR_MS = 3600_000;
|
||||
|
||||
const round1 = (n: number) => Math.round(n * 10) / 10;
|
||||
|
||||
/** A column holding an ISO time, as the number of the slice it falls in (0 at `fromMs`): the work done in SQL so a list is one query. */
|
||||
const sliceOf = (column: string, fromMs: number, sliceMs: number) => sql.raw(`cast((strftime('%s', ${column}) * 1000 - ${Math.round(fromMs)}) / ${Math.round(sliceMs)} as integer)`);
|
||||
|
||||
/** Slices of (slice number → value) into a full list of `n` values, null where there is none. Pure. */
|
||||
export function fillSlices(found: Map<number, number>, n: number = SLICES): (number | null)[] {
|
||||
return Array.from({ length: n }, (_, i) => (found.has(i) ? round1(found.get(i)!) : null));
|
||||
}
|
||||
|
||||
export interface Spark {
|
||||
/** `SLICES` values, oldest first; null for a slice with nothing in it. */
|
||||
values: (number | null)[];
|
||||
/** The last value there is. */
|
||||
latest: number | null;
|
||||
low: number | null;
|
||||
high: number | null;
|
||||
}
|
||||
|
||||
/** A series with its last, lowest and highest value worked out; null when there is not one value in it. */
|
||||
export function sparkOf(values: (number | null)[]): Spark | null {
|
||||
const real = values.filter((v): v is number => v !== null);
|
||||
if (real.length === 0) return null;
|
||||
return { values, latest: real[real.length - 1], low: Math.min(...real), high: Math.max(...real) };
|
||||
}
|
||||
|
||||
// ─── Servers ──────────────────────────────────────────────────────────────
|
||||
|
||||
export type ServerSparklines = Record<number, { cpu?: Spark; mem?: Spark }>;
|
||||
|
||||
/** Load and memory of every server that reports them, over the last `hours` (an agent-reported figure, as a percentage). */
|
||||
export async function serverSparklines(now: Date = new Date(), hours = 24): Promise<ServerSparklines> {
|
||||
const to = now.getTime();
|
||||
const from = to - hours * HOUR_MS;
|
||||
const sliceMs = (hours * HOUR_MS) / SLICES;
|
||||
const rows = await db.all<{ server_id: number; metric: string; slice: number; v: number }>(sql`
|
||||
SELECT server_id, metric, ${sliceOf("recorded_at", from, sliceMs)} AS slice, avg(value) AS v
|
||||
FROM server_metrics
|
||||
WHERE recorded_at >= ${new Date(from).toISOString()} AND metric IN ('cpu', 'mem')
|
||||
GROUP BY server_id, metric, slice`);
|
||||
const grouped = new Map<string, Map<number, number>>();
|
||||
for (const r of rows) {
|
||||
if (r.slice < 0 || r.slice >= SLICES) continue;
|
||||
const key = `${r.server_id}:${r.metric}`;
|
||||
if (!grouped.has(key)) grouped.set(key, new Map());
|
||||
grouped.get(key)!.set(r.slice, r.v);
|
||||
}
|
||||
const out: ServerSparklines = {};
|
||||
for (const [key, found] of grouped) {
|
||||
const [id, metric] = key.split(":");
|
||||
const spark = sparkOf(fillSlices(found));
|
||||
if (!spark) continue;
|
||||
(out[Number(id)] ??= {})[metric as "cpu" | "mem"] = spark;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ─── Endpoints ────────────────────────────────────────────────────────────
|
||||
|
||||
export interface EndpointSpark extends Spark {
|
||||
/** For each slice: at least one check in it failed. */
|
||||
failed: boolean[];
|
||||
}
|
||||
export type EndpointSparklines = Record<number, EndpointSpark>;
|
||||
|
||||
/** How long each endpoint check took to answer over the last `hours` (milliseconds), and in which slices a check failed. */
|
||||
export async function endpointSparklines(now: Date = new Date(), hours = 24): Promise<EndpointSparklines> {
|
||||
const to = now.getTime();
|
||||
const from = to - hours * HOUR_MS;
|
||||
const sliceMs = (hours * HOUR_MS) / SLICES;
|
||||
const rows = await db.all<{ check_id: number; slice: number; ms: number | null; bad: number }>(sql`
|
||||
SELECT check_id, ${sliceOf("at", from, sliceMs)} AS slice, avg(CASE WHEN ok = 1 THEN ms END) AS ms, sum(CASE WHEN ok = 0 THEN 1 ELSE 0 END) AS bad
|
||||
FROM endpoint_results
|
||||
WHERE at >= ${new Date(from).toISOString()}
|
||||
GROUP BY check_id, slice`);
|
||||
const ms = new Map<number, Map<number, number>>();
|
||||
const bad = new Map<number, Set<number>>();
|
||||
for (const r of rows) {
|
||||
if (r.slice < 0 || r.slice >= SLICES) continue;
|
||||
if (!ms.has(r.check_id)) ms.set(r.check_id, new Map());
|
||||
if (r.ms !== null) ms.get(r.check_id)!.set(r.slice, r.ms);
|
||||
if (r.bad > 0) (bad.get(r.check_id) ?? bad.set(r.check_id, new Set()).get(r.check_id)!).add(r.slice);
|
||||
}
|
||||
const out: EndpointSparklines = {};
|
||||
for (const id of new Set([...ms.keys(), ...bad.keys()])) {
|
||||
const values = fillSlices(ms.get(id) ?? new Map());
|
||||
const failed = Array.from({ length: SLICES }, (_, i) => bad.get(id)?.has(i) ?? false);
|
||||
const spark = sparkOf(values) ?? { values, latest: null, low: null, high: null };
|
||||
out[id] = { ...spark, failed };
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ─── Integrations ─────────────────────────────────────────────────────────
|
||||
|
||||
/** Which figure stands for an integration in a list: the first of these it has, else the first it was given. */
|
||||
export const HEADLINE_ORDER = ["cost", "queries", "queue", "speedDown", "photos", "documents", "users", "devices", "failed24h", "targetsDown", "firing", "failedLogins24h", "movies", "active"];
|
||||
|
||||
export interface IntegrationSpark extends Spark {
|
||||
key: string;
|
||||
label: string;
|
||||
unit: string;
|
||||
}
|
||||
export type IntegrationSparklines = Record<number, IntegrationSpark>;
|
||||
|
||||
/** Pure: the figure that stands for an integration, from the ones it has (in the order they were first kept). */
|
||||
export function headlineOf<T extends { key: string }>(figures: T[]): T | null {
|
||||
for (const key of HEADLINE_ORDER) {
|
||||
const f = figures.find((x) => x.key === key);
|
||||
if (f) return f;
|
||||
}
|
||||
return figures[0] ?? null;
|
||||
}
|
||||
|
||||
/** The headline figure of every integration that keeps history, over the last `days`. */
|
||||
export async function integrationSparklines(now: Date = new Date(), days = 7): Promise<IntegrationSparklines> {
|
||||
const to = now.getTime();
|
||||
const from = to - days * 24 * HOUR_MS;
|
||||
const sliceMs = (days * 24 * HOUR_MS) / SLICES;
|
||||
const figures = await db.all<{ id: number; integration_id: number; key: string; label: string; unit: string }>(sql`SELECT id, integration_id, key, label, unit FROM integration_figures ORDER BY id`);
|
||||
const byIntegration = new Map<number, typeof figures>();
|
||||
for (const f of figures) (byIntegration.get(f.integration_id) ?? byIntegration.set(f.integration_id, []).get(f.integration_id)!).push(f);
|
||||
const chosen = new Map<number, (typeof figures)[number]>();
|
||||
for (const [integrationId, list] of byIntegration) {
|
||||
const pick = headlineOf(list);
|
||||
if (pick) chosen.set(pick.id, pick);
|
||||
void integrationId;
|
||||
}
|
||||
if (chosen.size === 0) return {};
|
||||
const rows = await db.all<{ figure_id: number; slice: number; v: number }>(sql`
|
||||
SELECT figure_id, ${sliceOf("at", from, sliceMs)} AS slice, avg(value) AS v
|
||||
FROM integration_figure_samples
|
||||
WHERE at >= ${new Date(from).toISOString()}
|
||||
GROUP BY figure_id, slice`);
|
||||
const found = new Map<number, Map<number, number>>();
|
||||
for (const r of rows) {
|
||||
if (!chosen.has(r.figure_id) || r.slice < 0 || r.slice >= SLICES) continue;
|
||||
if (!found.has(r.figure_id)) found.set(r.figure_id, new Map());
|
||||
found.get(r.figure_id)!.set(r.slice, r.v);
|
||||
}
|
||||
const out: IntegrationSparklines = {};
|
||||
for (const [figureId, f] of chosen) {
|
||||
const spark = sparkOf(fillSlices(found.get(figureId) ?? new Map()));
|
||||
if (spark) out[f.integration_id] = { ...spark, key: f.key, label: f.label, unit: f.unit };
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* The drawing of the small lines in the rows of a list: where the points go, that a gap is a gap, that a lone reading is a dot, the fixed scale of a percentage, and the sentence for a screen reader.
|
||||
*
|
||||
* Run with: npm test --workspace server
|
||||
*/
|
||||
import { test, describe } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { sparkGeometry, sparkTicks, sparkWords } from "../../web/src/utils/sparkline.js";
|
||||
|
||||
describe("the points", () => {
|
||||
test("oldest at the left, newest at the right, the highest reading at the top; the last reading is marked", () => {
|
||||
const g = sparkGeometry([0, 50, 100], 100, 20, { min: 0, max: 100, pad: 2 });
|
||||
assert.deepEqual(g.lines, ["M2 18 L50 10 L98 2"]);
|
||||
assert.deepEqual(g.last, { x: 98, y: 2 });
|
||||
assert.deepEqual([g.min, g.max], [0, 100]);
|
||||
assert.deepEqual(g.dots, []);
|
||||
});
|
||||
|
||||
test("a gap in the data is a gap in the line, and a reading alone between gaps is a dot", () => {
|
||||
const g = sparkGeometry([10, 20, null, 40, null, 60, 70], 120, 20, { min: 0, max: 100 });
|
||||
assert.equal(g.lines.length, 2, "two runs of two");
|
||||
assert.equal(g.dots.length, 1, "and the lone 40");
|
||||
assert.ok(g.lines[0].startsWith("M2 "));
|
||||
assert.deepEqual(g.last, { x: 118, y: 6.8 }, "the last reading, 70 on a scale of 0 to 100");
|
||||
assert.equal(sparkGeometry([null, null, null], 100, 20).last, null);
|
||||
assert.deepEqual(sparkGeometry([null, null], 100, 20).lines, []);
|
||||
});
|
||||
|
||||
test("the scale fits the data unless it is fixed; a flat line is drawn through the middle, not along an edge", () => {
|
||||
const fitted = sparkGeometry([100, 300], 100, 20);
|
||||
assert.deepEqual([fitted.min, fitted.max], [100, 300]);
|
||||
assert.equal(fitted.lines[0], "M2 18 L98 2");
|
||||
const flat = sparkGeometry([5, 5, 5], 100, 20);
|
||||
assert.deepEqual(flat.lines, ["M2 10 L50 10 L98 10"]);
|
||||
// a fixed scale is not moved by the data, and a reading outside it stays inside the picture
|
||||
const percent = sparkGeometry([5, 5], 100, 20, { min: 0, max: 100 });
|
||||
assert.equal(percent.lines[0], "M2 17.2 L98 17.2");
|
||||
assert.equal(sparkGeometry([250], 100, 20, { min: 0, max: 100 }).dots[0].y, 2);
|
||||
});
|
||||
|
||||
test("one reading is one dot in the middle", () => {
|
||||
const g = sparkGeometry([42], 100, 20);
|
||||
assert.deepEqual(g.lines, []);
|
||||
assert.deepEqual(g.dots, [{ x: 50, y: 10 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the ticks and the words", () => {
|
||||
test("a tick under each stretch that is marked, at the place of that stretch", () => {
|
||||
assert.deepEqual(sparkTicks([false, true, false, true], 100), [34, 98]);
|
||||
assert.deepEqual(sparkTicks([false, false], 100), []);
|
||||
});
|
||||
|
||||
test("the sentence says what it is, over what, where it stands now, the range, and the failures", () => {
|
||||
const pct = (v: number) => `${Math.round(v)}%`;
|
||||
assert.equal(sparkWords("CPU load", "last 24 hours", 12, 3, 40, pct), "CPU load, last 24 hours: 12% now, between 3% and 40%");
|
||||
assert.equal(sparkWords("Disk", "last week", 50, 50, 50, pct), "Disk, last week: 50% now");
|
||||
assert.equal(sparkWords("Wiki", "answer time, last 24 hours", 30, 20, 90, (v) => `${v} ms`, 2), "Wiki, answer time, last 24 hours: 30 ms now, between 20 ms and 90 ms, 2 stretches with a failure");
|
||||
assert.equal(sparkWords("Wiki", "x", 30, 30, 30, pct, 1), "Wiki, x: 30% now, 1 stretch with a failure");
|
||||
assert.equal(sparkWords("Up", "last week", null, null, null, pct), "Up, last week: nothing read");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,205 @@
|
||||
/**
|
||||
* The small lines in the rows of a list: servers' load and memory over a day, how long endpoints took to answer (and when they failed), the figure an integration is known for over a week —
|
||||
* how the slices are made, that a gap stays a gap, which figure stands for an integration, and the three routes.
|
||||
*
|
||||
* Run with: npm test --workspace server
|
||||
*/
|
||||
import { test, describe, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import type { Server } from "node:http";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "hm-spark-"));
|
||||
process.env.DATABASE_PATH = join(dir, "test.sqlite");
|
||||
process.env.SESSION_DIR = join(dir, "sessions");
|
||||
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
|
||||
process.env.HEALTH_STARTUP_GRACE_MS = "0";
|
||||
|
||||
const express = (await import("express")).default;
|
||||
const { db } = await import("../src/db/client.js");
|
||||
const { users, servers, serverMetrics, endpointChecks, endpointResults, integrations } = await import("../src/db/schema.js");
|
||||
const { runMigrations } = await import("../src/db/migrate.js");
|
||||
const S = await import("../src/services/sparklines.js");
|
||||
const { recordFigures } = await import("../src/services/integrationFigures.js");
|
||||
const { hashToken } = await import("../src/services/tokens.js");
|
||||
const { serversRouter } = await import("../src/routes/servers.js");
|
||||
const { endpointsRouter } = await import("../src/routes/endpoints.js");
|
||||
const { integrationsRouter } = await import("../src/routes/integrations.js");
|
||||
|
||||
await runMigrations();
|
||||
|
||||
const NOW = new Date("2026-11-10T12:00:00.000Z");
|
||||
const hoursAgo = (h: number) => new Date(NOW.getTime() - h * 3600_000);
|
||||
|
||||
describe("making a series", () => {
|
||||
test("a fixed number of slices, oldest first, null where nothing was read", () => {
|
||||
const filled = S.fillSlices(new Map([[0, 10.04], [3, 20], [23, 7]]));
|
||||
assert.equal(filled.length, S.SLICES);
|
||||
assert.deepEqual([filled[0], filled[1], filled[3], filled[23]], [10, null, 20, 7]);
|
||||
assert.equal(S.fillSlices(new Map(), 5).join(), ",,,,");
|
||||
});
|
||||
|
||||
test("a series knows its last, lowest and highest value, and no series is no spark", () => {
|
||||
assert.deepEqual(S.sparkOf([null, 5, null, 9, 2, null]), { values: [null, 5, null, 9, 2, null], latest: 2, low: 2, high: 9 });
|
||||
assert.equal(S.sparkOf([null, null]), null);
|
||||
});
|
||||
|
||||
test("the figure that stands for an integration is the first of the known ones it has, else its first", () => {
|
||||
assert.equal(S.headlineOf([{ key: "servers" }, { key: "cost" }])!.key, "cost");
|
||||
assert.equal(S.headlineOf([{ key: "blocked" }, { key: "queries" }])!.key, "queries");
|
||||
assert.equal(S.headlineOf([{ key: "odd" }, { key: "other" }])!.key, "odd");
|
||||
assert.equal(S.headlineOf([]), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("servers", () => {
|
||||
let a = 0;
|
||||
let b = 0;
|
||||
before(async () => {
|
||||
[{ id: a }] = await db.insert(servers).values({ name: "spark-a", apiTokenHash: hashToken("sa"), apiTokenPrefix: "sa" }).returning({ id: servers.id });
|
||||
[{ id: b }] = await db.insert(servers).values({ name: "spark-b", apiTokenHash: hashToken("sb"), apiTokenPrefix: "sb" }).returning({ id: servers.id });
|
||||
const rows = [];
|
||||
// a: load rises through the day, memory flat, nothing in the middle hours
|
||||
for (const h of [23.5, 22.5, 20.5, 2.5, 1.5, 0.5]) {
|
||||
rows.push({ serverId: a, metric: "cpu", value: 100 - h * 4, recordedAt: hoursAgo(h).toISOString() });
|
||||
rows.push({ serverId: a, metric: "mem", value: 50, recordedAt: hoursAgo(h).toISOString() });
|
||||
}
|
||||
// b: a disk figure only (not one of the lines), and a reading from two days ago (out of the stretch)
|
||||
rows.push({ serverId: b, metric: "disk:/", value: 80, recordedAt: hoursAgo(1).toISOString() });
|
||||
rows.push({ serverId: b, metric: "cpu", value: 99, recordedAt: hoursAgo(48).toISOString() });
|
||||
await db.insert(serverMetrics).values(rows);
|
||||
});
|
||||
|
||||
test("load and memory over the last day, a slice an hour; a gap is null; others are left out", async () => {
|
||||
const out = await S.serverSparklines(NOW);
|
||||
assert.deepEqual(Object.keys(out).map(Number), [a], "b has nothing in the last day that is drawn");
|
||||
const cpu = out[a].cpu!;
|
||||
assert.equal(cpu.values.length, S.SLICES);
|
||||
assert.equal(cpu.values[0], 6, "23.5 hours ago is the first slice: 100 − 94");
|
||||
assert.equal(cpu.values[3], 18, "20.5 hours ago is the fourth slice");
|
||||
assert.equal(cpu.values[8], null, "nothing sixteen hours in");
|
||||
assert.equal(cpu.latest, 98, "the newest reading, half an hour ago");
|
||||
assert.equal(cpu.values[23], 98);
|
||||
assert.deepEqual([cpu.low, cpu.high], [6, 98]);
|
||||
assert.ok(out[a].mem!.values.every((v) => v === null || v === 50));
|
||||
});
|
||||
|
||||
test("readings in the same slice are averaged", async () => {
|
||||
await db.insert(serverMetrics).values([
|
||||
{ serverId: a, metric: "cpu", value: 10, recordedAt: hoursAgo(10.9).toISOString() },
|
||||
{ serverId: a, metric: "cpu", value: 20, recordedAt: hoursAgo(10.2).toISOString() },
|
||||
]);
|
||||
const cpu = (await S.serverSparklines(NOW))[a].cpu!;
|
||||
assert.equal(cpu.values[13], 15);
|
||||
});
|
||||
});
|
||||
|
||||
describe("endpoints", () => {
|
||||
let up = 0;
|
||||
let flaky = 0;
|
||||
let quiet = 0;
|
||||
before(async () => {
|
||||
[{ id: up }] = await db.insert(endpointChecks).values({ name: "Up", kind: "tcp", target: "h", port: 1 }).returning({ id: endpointChecks.id });
|
||||
[{ id: flaky }] = await db.insert(endpointChecks).values({ name: "Flaky", kind: "tcp", target: "h", port: 2 }).returning({ id: endpointChecks.id });
|
||||
[{ id: quiet }] = await db.insert(endpointChecks).values({ name: "Quiet", kind: "tcp", target: "h", port: 3 }).returning({ id: endpointChecks.id });
|
||||
const at = (h: number) => hoursAgo(h).toISOString();
|
||||
await db.insert(endpointResults).values([
|
||||
{ checkId: up, at: at(5.5), ok: true, ms: 40 },
|
||||
{ checkId: up, at: at(5.2), ok: true, ms: 60 },
|
||||
{ checkId: up, at: at(0.5), ok: true, ms: 30 },
|
||||
{ checkId: flaky, at: at(8.5), ok: true, ms: 100 },
|
||||
{ checkId: flaky, at: at(7.5), ok: false, ms: null },
|
||||
{ checkId: flaky, at: at(7.4), ok: false, ms: null },
|
||||
{ checkId: quiet, at: at(100), ok: true, ms: 5 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("answer times by the hour for the last day; the ones that failed have no time but are marked", async () => {
|
||||
const out = await S.endpointSparklines(NOW);
|
||||
const u = out[up];
|
||||
assert.equal(u.values.length, S.SLICES);
|
||||
assert.equal(u.values[18], 50, "5.5 and 5.2 hours ago, averaged");
|
||||
assert.equal(u.latest, 30);
|
||||
assert.ok(u.failed.every((f) => !f));
|
||||
|
||||
const f = out[flaky];
|
||||
assert.equal(f.values[15], 100);
|
||||
assert.equal(f.values[16], null, "a failed check has no time");
|
||||
assert.equal(f.failed[16], true);
|
||||
assert.equal(f.failed[15], false);
|
||||
assert.equal(f.latest, 100, "the last time it did answer");
|
||||
});
|
||||
|
||||
test("a check with nothing in the last day is not in it", async () => {
|
||||
assert.equal((await S.endpointSparklines(NOW))[quiet], undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe("integrations", () => {
|
||||
let ag = 0;
|
||||
let nothing = 0;
|
||||
before(async () => {
|
||||
[{ id: ag }] = await db.insert(integrations).values({ type: "adguard", name: "AG", baseUrl: "http://x" }).returning({ id: integrations.id });
|
||||
[{ id: nothing }] = await db.insert(integrations).values({ type: "adguard", name: "No history", baseUrl: "http://y" }).returning({ id: integrations.id });
|
||||
for (let d = 6; d >= 0; d--) {
|
||||
await recordFigures(ag, [
|
||||
{ key: "blocked", label: "Blocked", unit: "count", value: 10 + d },
|
||||
{ key: "queries", label: "DNS queries", unit: "count", value: 100 * (7 - d) },
|
||||
], hoursAgo(d * 24 + 1));
|
||||
}
|
||||
});
|
||||
|
||||
test("the headline figure over the last week, a slice for each seven hours", async () => {
|
||||
const out = await S.integrationSparklines(NOW);
|
||||
assert.equal(out[nothing], undefined, "an integration with no history has no line");
|
||||
const s = out[ag];
|
||||
assert.deepEqual([s.key, s.label, s.unit], ["queries", "DNS queries", "count"]);
|
||||
assert.equal(s.values.length, S.SLICES);
|
||||
assert.equal(s.latest, 700);
|
||||
assert.equal(s.low, 100);
|
||||
assert.equal(s.values.filter((v) => v !== null).length, 7);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the routes", () => {
|
||||
let app: Server;
|
||||
let base = "";
|
||||
before(async () => {
|
||||
await db.insert(users).values({ oidcSub: "viewer", name: "Vera", role: "viewer" });
|
||||
const a = express();
|
||||
a.use(express.json());
|
||||
a.use((req, _res, next) => {
|
||||
(req as unknown as { session: unknown }).session = { user: { sub: "viewer" } };
|
||||
next();
|
||||
});
|
||||
a.use("/api/servers", serversRouter);
|
||||
a.use("/api/endpoints", endpointsRouter);
|
||||
a.use("/api/integrations", integrationsRouter);
|
||||
app = await new Promise<Server>((resolve) => {
|
||||
const x = a.listen(0, "127.0.0.1", () => resolve(x));
|
||||
});
|
||||
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`;
|
||||
});
|
||||
after(() => {
|
||||
app.close();
|
||||
try {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Windows keeps the database file locked until the process exits.
|
||||
}
|
||||
});
|
||||
|
||||
test("anyone signed in can ask for each; they answer in the shape the lists read, and are not mistaken for an id", async () => {
|
||||
for (const [path, key] of [["/servers/sparklines", "servers"], ["/endpoints/sparklines", "checks"], ["/integrations/sparklines", "integrations"]] as const) {
|
||||
const res = await fetch(`${base}${path}`);
|
||||
assert.equal(res.status, 200, path);
|
||||
const body = await res.json();
|
||||
assert.equal(typeof body[key], "object", path);
|
||||
assert.ok(!Array.isArray(body[key]));
|
||||
}
|
||||
// (their own data is old by now — the readings were made around a fixed day — so these are empty here; the figures are in the tests above)
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { } from "../i18n";
|
||||
export type UserRole = "admin" | "operator" | "viewer";
|
||||
|
||||
export interface CurrentUser {
|
||||
@@ -864,6 +865,23 @@ export interface IntegrationFigure {
|
||||
high: number | null;
|
||||
}
|
||||
|
||||
/** A short series for a row in a list: `values` is a fixed number of slices, oldest first, null where nothing was read. */
|
||||
export interface SparkSeries {
|
||||
values: (number | null)[];
|
||||
latest: number | null;
|
||||
low: number | null;
|
||||
high: number | null;
|
||||
}
|
||||
export interface EndpointSparkSeries extends SparkSeries {
|
||||
/** In which slices a check failed. */
|
||||
failed: boolean[];
|
||||
}
|
||||
export interface IntegrationSparkSeries extends SparkSeries {
|
||||
key: string;
|
||||
label: string;
|
||||
unit: string;
|
||||
}
|
||||
|
||||
export interface UpdateRun {
|
||||
id: number;
|
||||
serverId: number;
|
||||
@@ -3888,6 +3906,8 @@ export const api = {
|
||||
},
|
||||
endpoints: {
|
||||
list: () => request<{ checks: EndpointCheck[]; servers: { id: number; name: string }[] }>("/api/endpoints"),
|
||||
/** How long each check took to answer over the last day, and when one failed, for the lines in the list. */
|
||||
sparklines: () => request<{ hours: number; checks: Record<number, EndpointSparkSeries> }>("/api/endpoints/sparklines"),
|
||||
create: (data: EndpointInput) => request<{ check: EndpointCheck }>("/api/endpoints", { method: "POST", body: JSON.stringify(data) }),
|
||||
update: (id: number, data: EndpointInput) => request<{ check: EndpointCheck }>(`/api/endpoints/${id}`, { method: "PUT", body: JSON.stringify(data) }),
|
||||
remove: (id: number) => request<void>(`/api/endpoints/${id}`, { method: "DELETE" }),
|
||||
@@ -4292,6 +4312,8 @@ export const api = {
|
||||
},
|
||||
servers: {
|
||||
list: () => request<{ servers: ServerRecord[]; agentLatest: AgentLatest; agentAutoUpdate: boolean }>("/api/servers"),
|
||||
/** The last day's load and memory of each server that reports them, for the lines in the list. */
|
||||
sparklines: () => request<{ hours: number; servers: Record<number, { cpu?: SparkSeries; mem?: SparkSeries }> }>("/api/servers/sparklines"),
|
||||
setAgentAutoUpdate: (autoUpdate: boolean) => request<{ autoUpdate: boolean }>("/api/servers/agent-update", { method: "PUT", body: JSON.stringify({ autoUpdate }) }),
|
||||
create: (data: { name: string; hostname?: string; description?: string; osType?: "linux" | "windows" }) =>
|
||||
request<{ server: ServerRecord; token: string }>("/api/servers", {
|
||||
@@ -4408,6 +4430,8 @@ export const api = {
|
||||
integration: { id: number; type: IntegrationType; name: string; enabled: boolean };
|
||||
config: Record<string, string | boolean>;
|
||||
}>(`/api/integrations/${id}/config`),
|
||||
/** The figure each integration is known for, over the last week, for the lines in a list. */
|
||||
sparklines: () => request<{ days: number; integrations: Record<number, IntegrationSparkSeries> }>("/api/integrations/sparklines"),
|
||||
/** How the figures it reports have moved over the last `days` (a day to a year); `kept` is false for a kind that keeps none. */
|
||||
figures: (id: number, days: number) => request<{ kept: boolean; days: number; figures: IntegrationFigure[] }>(`/api/integrations/${id}/figures?days=${days}`),
|
||||
inspect: (id: number) => request<IntegrationInspection>(`/api/integrations/${id}/inspect`, { method: "POST" }),
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { sparkGeometry, sparkTicks, type SparkOptions } from "../utils/sparkline";
|
||||
|
||||
/**
|
||||
* A small line for a row in a list: which way something is going, not what it is exactly. A gap in the data is a gap in the line, the newest reading is a dot, and a check that failed in a stretch
|
||||
* has a red tick under it. It is a picture with a text for people who cannot see it (`label`); the exact figures are on the page of the thing itself.
|
||||
*/
|
||||
export default function Sparkline({
|
||||
values,
|
||||
failed,
|
||||
label,
|
||||
width = 84,
|
||||
height = 24,
|
||||
tone = "primary",
|
||||
...scale
|
||||
}: {
|
||||
values: (number | null)[];
|
||||
/** Slices in which something failed: a tick under the line. */
|
||||
failed?: boolean[];
|
||||
/** What the picture says, in words. */
|
||||
label: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
tone?: "primary" | "green" | "orange" | "red" | "secondary";
|
||||
} & SparkOptions) {
|
||||
const g = sparkGeometry(values, width, height, scale);
|
||||
const ticks = failed ? sparkTicks(failed, width) : [];
|
||||
return (
|
||||
<svg className={`sparkline sparkline-${tone}`} style={{ width, height }} width={width} height={height} viewBox={`0 0 ${width} ${height}`} role="img" aria-label={label}>
|
||||
<title>{label}</title>
|
||||
{g.lines.map((d, i) => (
|
||||
<path key={i} d={d} className="sparkline-line" fill="none" strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round" />
|
||||
))}
|
||||
{g.dots.map((p, i) => (
|
||||
<circle key={i} cx={p.x} cy={p.y} r="1.5" className="sparkline-dot" />
|
||||
))}
|
||||
{g.last && <circle cx={g.last.x} cy={g.last.y} r="2.2" className="sparkline-dot" />}
|
||||
{ticks.map((x, i) => (
|
||||
<line key={i} x1={x} x2={x} y1={height - 5} y2={height - 1} className="sparkline-fail" strokeWidth="1.5" />
|
||||
))}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** Loads the series for a list once, and again every few minutes (a series moves slowly); null until it is there, and for good if it cannot be had — a list without its lines is still a list. */
|
||||
export function useSparklines<T>(load: () => Promise<T>, everyMs = 5 * 60_000): T | null {
|
||||
const [data, setData] = useState<T | null>(null);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
const run = () =>
|
||||
load()
|
||||
.then((res) => alive && setData(res))
|
||||
.catch(() => undefined);
|
||||
void run();
|
||||
const timer = setInterval(run, everyMs);
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(timer);
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
return data;
|
||||
}
|
||||
@@ -26,6 +26,8 @@ export const sv: Record<string, string> = {
|
||||
"{n} more explained by something that is down": "{n} till förklaras av något som ligger nere",
|
||||
"{n} silenced by maintenance": "{n} tystade av underhåll",
|
||||
"{n} so far": "{n} hittills",
|
||||
"{n} stretch with a failure": "{n} period med ett fel",
|
||||
"{n} stretches with a failure": "{n} perioder med fel",
|
||||
"{n} thing needs attention": "{n} sak behöver uppmärksamhet",
|
||||
"{n} thing of yours wants a look: handed to you, about to run out, or still going": "{n} sak av dig behöver en titt: tilldelad dig, på väg att löpa ut eller pågår fortfarande",
|
||||
"{n} things need attention": "{n} saker behöver uppmärksamhet",
|
||||
@@ -34,9 +36,11 @@ export const sv: Record<string, string> = {
|
||||
"{n} waiting, {security} security": "{n} väntar, {security} säkerhet",
|
||||
"{n} y ago": "för {n} år sedan",
|
||||
"{name} ({time} left)": "{name} ({time} kvar)",
|
||||
"{name}, {period}: {parts}": "{name}, {period}: {parts}",
|
||||
"{names} — see Alerts for what that leaves unchecked": "{names} — se Larm för vad det lämnar okontrollerat",
|
||||
"{names} and {n} more (the last ends in {time})": "{names} och {n} till (det sista slutar om {time})",
|
||||
"{shown} of {total}": "{shown} av {total}",
|
||||
"{value} now": "{value} nu",
|
||||
"← Prev": "← Föregående",
|
||||
"1 hour": "1 timme",
|
||||
"1 year": "1 år",
|
||||
@@ -120,6 +124,7 @@ export const sv: Record<string, string> = {
|
||||
"Also takes down {n} thing: {list}": "Tar också ned {n} sak: {list}",
|
||||
"Also takes down {n} things: {list}": "Tar också ned {n} saker: {list}",
|
||||
"An API token, a certificate or a password — you're warned before it runs out.": "En API-nyckel, ett certifikat eller ett lösenord — du varnas innan det löper ut.",
|
||||
"answer time, last 24 hours": "svarstid, senaste 24 timmarna",
|
||||
"Any status": "Valfri status",
|
||||
"API tokens": "API-nycklar",
|
||||
"App versions": "Appversioner",
|
||||
@@ -137,6 +142,7 @@ export const sv: Record<string, string> = {
|
||||
"Backups": "Säkerhetskopior",
|
||||
"behind": "efter",
|
||||
"Belongs to": "Tillhör",
|
||||
"between {low} and {high}": "mellan {low} och {high}",
|
||||
"Between 5 and 500.": "Mellan 5 och 500.",
|
||||
"Blocking is switched off.": "Blockering är avstängd.",
|
||||
"Bound to localhost only — other machines can't connect, but the port is still taken": "Bunden bara till localhost — andra maskiner kan inte ansluta, men porten är ändå upptagen",
|
||||
@@ -303,10 +309,13 @@ export const sv: Record<string, string> = {
|
||||
"Kind of alert": "Sorts larm",
|
||||
"Kinds of things": "Sorters saker",
|
||||
"Language": "Språk",
|
||||
"last 24 hours": "senaste 24 timmarna",
|
||||
"Last 30 days": "Senaste 30 dagarna",
|
||||
"Last failed": "Senast misslyckad",
|
||||
"Last port": "Sista port",
|
||||
"Last seen": "Senast sedd",
|
||||
"last week": "senaste veckan",
|
||||
"Last week": "Senaste veckan",
|
||||
"Late or failed": "Sena eller misslyckade",
|
||||
"Leave a box empty to follow Settings → Notifications (shown inside the box). Only what you fill in is different for this server.": "Lämna en ruta tom för att följa Inställningar → Notiser (visas i rutan). Bara det du fyller i skiljer sig för den här servern.",
|
||||
"Leave a server alone when it has no updates waiting": "Lämna en server ifred när den inte har några väntande uppdateringar",
|
||||
@@ -335,6 +344,7 @@ export const sv: Record<string, string> = {
|
||||
"Matched to a server": "Kopplad till en server",
|
||||
"Matching settings": "Matchande inställningar",
|
||||
"Media managers": "Mediahanterare",
|
||||
"Memory": "Minne",
|
||||
"Monitoring": "Övervakning",
|
||||
"Most in an hour": "Flest på en timme",
|
||||
"most recent first": "senaste först",
|
||||
@@ -420,6 +430,7 @@ export const sv: Record<string, string> = {
|
||||
"Nothing needs attention right now.": "Inget behöver uppmärksamhet just nu.",
|
||||
"Nothing new": "Inget nytt",
|
||||
"Nothing on your plate": "Inget på din lista",
|
||||
"nothing read": "inget avläst",
|
||||
"Nothing recorded yet. Changes to this server, times it stopped reporting, and its maintenance windows will be listed here.": "Inget antecknat än. Ändringar av servern, tider då den slutade rapportera och dess underhållsfönster listas här.",
|
||||
"Nothing soon": "Inget inom kort",
|
||||
"Nothing to do": "Inget att göra",
|
||||
|
||||
@@ -19,6 +19,8 @@ import EndpointSuggestions from "../components/EndpointSuggestions";
|
||||
import EndpointHistory from "../components/EndpointHistory";
|
||||
import PageIntro from "../components/PageIntro";
|
||||
import { t } from "../i18n";
|
||||
import Sparkline, { useSparklines } from "../components/Sparkline";
|
||||
import { sparkWords } from "../utils/sparkline";
|
||||
|
||||
const KIND_LABELS: Record<EndpointKind, string> = { http: "Web address", tcp: "Port", tls: "Certificate" };
|
||||
const KIND_HINTS: Record<EndpointKind, string> = {
|
||||
@@ -160,6 +162,7 @@ export default function Endpoints({ user }: { user: CurrentUser }) {
|
||||
const isAdmin = user.role === "admin";
|
||||
const canCheck = user.role === "admin" || user.role === "operator";
|
||||
const [checks, setChecks] = useState<EndpointCheck[] | null>(null);
|
||||
const sparks = useSparklines(() => api.endpoints.sparklines());
|
||||
const [servers, setServers] = useState<{ id: number; name: string }[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [draft, setDraft] = useState<Draft | null>(null);
|
||||
@@ -540,6 +543,18 @@ export default function Endpoints({ user }: { user: CurrentUser }) {
|
||||
)}
|
||||
{c.lastResponseMs === null ? <span className="text-secondary">—</span> : `${c.lastResponseMs} ms`}
|
||||
{c.stats?.avgMs24h != null && <div className="text-secondary small">avg {c.stats.avgMs24h} ms</div>}
|
||||
{sparks?.checks[c.id] && (
|
||||
<div className="mt-1">
|
||||
<Sparkline
|
||||
values={sparks.checks[c.id].values}
|
||||
failed={sparks.checks[c.id].failed}
|
||||
width={96}
|
||||
height={26}
|
||||
tone={sparks.checks[c.id].failed.some(Boolean) ? "red" : "primary"}
|
||||
label={sparkWords(c.name, t("answer time, last 24 hours"), sparks.checks[c.id].latest, sparks.checks[c.id].low, sparks.checks[c.id].high, (v) => `${Math.round(v)} ms`, sparks.checks[c.id].failed.filter(Boolean).length)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="stack-label" data-label="Uptime">
|
||||
{c.stats?.uptime24h == null ? (
|
||||
|
||||
@@ -23,6 +23,9 @@ import SortableTh from "../components/SortableTh";
|
||||
import PageIntro from "../components/PageIntro";
|
||||
import { BrandTag } from "../components/BrandIcon";
|
||||
import { t } from "../i18n";
|
||||
import Sparkline, { useSparklines } from "../components/Sparkline";
|
||||
import { sparkWords } from "../utils/sparkline";
|
||||
import { formatFigure } from "../utils/figureUnits";
|
||||
|
||||
function HealthBadge({ i }: { i: IntegrationSummary }) {
|
||||
const status = integrationStatus(i);
|
||||
@@ -172,6 +175,21 @@ function IntegrationsList({ user, tabs }: { user: CurrentUser; tabs: ReactNode }
|
||||
const sortedIntegrations = tableSearch.filtered ? [...tableSearch.filtered].filter(matchesStatus).sort((a, b) => a.name.localeCompare(b.name)) : null;
|
||||
|
||||
const rows = sortedIntegrations ? sortedIntegrations.map(integrationRow) : null;
|
||||
// The figure each integration is known for, over the last week (only those that keep a history have one).
|
||||
const sparks = useSparklines(() => api.integrations.sparklines());
|
||||
const trendOf = (id: number) => {
|
||||
const s = sparks?.integrations[id];
|
||||
if (!s) return <span className="text-secondary">—</span>;
|
||||
return (
|
||||
<span className="d-inline-flex align-items-center gap-2">
|
||||
<Sparkline values={s.values} width={72} height={22} label={sparkWords(s.label, t("last week"), s.latest, s.low, s.high, (v) => formatFigure(s.unit, v))} />
|
||||
<span className="small">
|
||||
<span className="text-secondary">{s.label} </span>
|
||||
{s.latest === null ? "—" : formatFigure(s.unit, s.latest)}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
};
|
||||
const { sorted: sortedRows, sortKey, sortDir, requestSort } = useSortable<IntegrationRow>(rows, "name", "asc", { url: true });
|
||||
|
||||
// The cards in groups, as the sidebar groups their pages (a kind nobody has placed goes under "Other").
|
||||
@@ -334,6 +352,7 @@ function IntegrationsList({ user, tabs }: { user: CurrentUser; tabs: ReactNode }
|
||||
<SortableTh<IntegrationRow> label="Group" sortKeyName="group" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<IntegrationRow> label="Address" sortKeyName="host" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<IntegrationRow> label={t("Status")} sortKeyName="statusRank" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<th scope="col">{t("Last week")}</th>
|
||||
<th scope="col">{t("Last 30 days")}</th>
|
||||
<th scope="col">{t("Actions")}</th>
|
||||
</tr>
|
||||
@@ -352,6 +371,7 @@ function IntegrationsList({ user, tabs }: { user: CurrentUser; tabs: ReactNode }
|
||||
{testBadge(i)}
|
||||
{testResults[i.id] && !testResults[i.id].ok && testingId !== i.id && <div className="text-red small mt-1">{testResults[i.id].error}</div>}
|
||||
</td>
|
||||
<td>{trendOf(i.id)}</td>
|
||||
<td>{i.enabled ? <UptimeRibbon kind="integrations" id={i.id} name={i.name} /> : <span className="text-secondary">—</span>}</td>
|
||||
<td>
|
||||
<div className="btn-list">{actionsOf(i)}</div>
|
||||
@@ -389,6 +409,7 @@ function IntegrationsList({ user, tabs }: { user: CurrentUser; tabs: ReactNode }
|
||||
<HealthBadge i={i} />
|
||||
{testBadge(i)}
|
||||
</div>
|
||||
{i.enabled && sparks?.integrations[i.id] && <div className="mb-3">{trendOf(i.id)}</div>}
|
||||
{i.enabled && (
|
||||
<div className="mb-3">
|
||||
<UptimeRibbon kind="integrations" id={i.id} name={i.name} />
|
||||
|
||||
@@ -28,12 +28,15 @@ import { RunsOnBulkDrawer, SilenceBulkDrawer, TagBulkDrawer } from "../component
|
||||
import { doBulk, plural } from "../utils/bulk";
|
||||
import { BrandTag } from "../components/BrandIcon";
|
||||
import { t } from "../i18n";
|
||||
import Sparkline, { useSparklines } from "../components/Sparkline";
|
||||
import { sparkWords } from "../utils/sparkline";
|
||||
|
||||
|
||||
export default function Servers({ user }: { user: CurrentUser }) {
|
||||
const isAdmin = user.role === "admin";
|
||||
|
||||
const [servers, setServers] = useState<ServerRecord[]>([]);
|
||||
const sparks = useSparklines(() => api.servers.sparklines());
|
||||
// Until the first answer arrives there is nothing to say about "no servers", so show the page's shape instead of the empty message.
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [agentLatest, setAgentLatest] = useState<AgentLatest | null>(null);
|
||||
@@ -252,6 +255,22 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
||||
<div className="text-secondary small mt-2">
|
||||
{s.lastSeenAt ? <>{t("Last seen")} <TimeAgo value={s.lastSeenAt} /></> : t("Never reported")}
|
||||
</div>
|
||||
{(sparks?.servers[s.id]?.cpu || sparks?.servers[s.id]?.mem) && (
|
||||
<div className="mt-2 small text-secondary">
|
||||
{([["cpu", t("CPU load")], ["mem", t("Memory")]] as const).map(([metric, name]) => {
|
||||
const line = sparks?.servers[s.id]?.[metric];
|
||||
return line ? (
|
||||
<div key={metric} className="mb-1">
|
||||
<div className="d-flex justify-content-between">
|
||||
{name}
|
||||
<span className="text-body">{line.latest === null ? "—" : `${Math.round(line.latest)}%`}</span>
|
||||
</div>
|
||||
<Sparkline values={line.values} min={0} max={100} width={140} height={22} tone={line.latest !== null && line.latest >= 90 ? "red" : line.latest !== null && line.latest >= 75 ? "orange" : "primary"} label={sparkWords(name, t("last 24 hours"), line.latest, line.low, line.high, (v) => `${Math.round(v)}%`)} />
|
||||
</div>
|
||||
) : null;
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-2">
|
||||
<UptimeRibbon kind="servers" id={s.id} name={s.name} />
|
||||
</div>
|
||||
|
||||
@@ -301,6 +301,7 @@ html[data-env] .navbar-vertical {
|
||||
}
|
||||
|
||||
.sparkline {
|
||||
display: block;
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 4rem;
|
||||
@@ -2328,3 +2329,28 @@ select,
|
||||
[role="tab"] {
|
||||
touch-action: manipulation;
|
||||
}
|
||||
|
||||
/* ── The small lines in the rows of a list (components/Sparkline) ── */
|
||||
.sparkline {
|
||||
display: block;
|
||||
flex: 0 0 auto;
|
||||
vertical-align: middle;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.sparkline-line {
|
||||
stroke: var(--sparkline-color, var(--tblr-primary));
|
||||
}
|
||||
|
||||
.sparkline-dot {
|
||||
fill: var(--sparkline-color, var(--tblr-primary));
|
||||
}
|
||||
|
||||
.sparkline-fail {
|
||||
stroke: var(--tblr-red);
|
||||
}
|
||||
|
||||
.sparkline-green { --sparkline-color: var(--tblr-green); }
|
||||
.sparkline-orange { --sparkline-color: var(--tblr-orange); }
|
||||
.sparkline-red { --sparkline-color: var(--tblr-red); }
|
||||
.sparkline-secondary { --sparkline-color: var(--tblr-secondary); }
|
||||
@@ -0,0 +1,81 @@
|
||||
import { t, tn } from "../i18n";
|
||||
|
||||
/** The drawing of the small lines in the rows of a list. Pure, so it can be tested without a browser. */
|
||||
|
||||
export interface SparkOptions {
|
||||
/** The scale: both given makes it fixed (a percentage is 0–100 whatever the data), otherwise it fits the data. */
|
||||
min?: number;
|
||||
max?: number;
|
||||
/** Room kept round the drawing, in pixels, so the line and its last dot are not cut off. */
|
||||
pad?: number;
|
||||
}
|
||||
|
||||
export interface SparkGeometry {
|
||||
/** SVG path data, one for each run of readings with no gap in it. */
|
||||
lines: string[];
|
||||
/** A reading with a gap on both sides can't be a line; it is a dot. */
|
||||
dots: { x: number; y: number }[];
|
||||
/** The newest reading. */
|
||||
last: { x: number; y: number } | null;
|
||||
/** The scale used. */
|
||||
min: number;
|
||||
max: number;
|
||||
}
|
||||
|
||||
const r1 = (n: number) => Math.round(n * 10) / 10;
|
||||
|
||||
/**
|
||||
* Turns a series (null where nothing was read) into the lines of a w × h picture: oldest at the left, a gap in the data a gap in the drawing, the scale fixed or fitted. A flat series is drawn
|
||||
* through the middle rather than along an edge.
|
||||
*/
|
||||
export function sparkGeometry(values: (number | null)[], w: number, h: number, options: SparkOptions = {}): SparkGeometry {
|
||||
const pad = options.pad ?? 2;
|
||||
const real = values.filter((v): v is number => v !== null && Number.isFinite(v));
|
||||
let min = options.min ?? (real.length ? Math.min(...real) : 0);
|
||||
let max = options.max ?? (real.length ? Math.max(...real) : 1);
|
||||
if (max - min < 1e-9) {
|
||||
// flat: centre it
|
||||
min -= 1;
|
||||
max += 1;
|
||||
}
|
||||
const n = values.length;
|
||||
const x = (i: number) => r1(pad + (n <= 1 ? (w - 2 * pad) / 2 : (i / (n - 1)) * (w - 2 * pad)));
|
||||
const y = (v: number) => r1(pad + (1 - (Math.min(max, Math.max(min, v)) - min) / (max - min)) * (h - 2 * pad));
|
||||
|
||||
const lines: string[] = [];
|
||||
const dots: { x: number; y: number }[] = [];
|
||||
let run: { x: number; y: number }[] = [];
|
||||
const flush = () => {
|
||||
if (run.length === 1) dots.push(run[0]);
|
||||
else if (run.length > 1) lines.push(run.map((p, i) => `${i === 0 ? "M" : "L"}${p.x} ${p.y}`).join(" "));
|
||||
run = [];
|
||||
};
|
||||
let last: { x: number; y: number } | null = null;
|
||||
values.forEach((v, i) => {
|
||||
if (v === null || !Number.isFinite(v)) return flush();
|
||||
const p = { x: x(i), y: y(v) };
|
||||
run.push(p);
|
||||
last = p;
|
||||
// a null after this value ends the run
|
||||
if (i + 1 >= n || values[i + 1] === null || !Number.isFinite(values[i + 1] as number)) flush();
|
||||
});
|
||||
return { lines, dots, last, min, max };
|
||||
}
|
||||
|
||||
/** The positions (as x in a w-wide picture) of the slices marked, for the ticks under a line (a check that failed). */
|
||||
export function sparkTicks(marked: boolean[], w: number, pad = 2): number[] {
|
||||
const n = marked.length;
|
||||
return marked.flatMap((m, i) => (m ? [r1(pad + (n <= 1 ? (w - 2 * pad) / 2 : (i / (n - 1)) * (w - 2 * pad)))] : []));
|
||||
}
|
||||
|
||||
/** What the picture says, for someone who cannot see it: "CPU load, last 24 hours: 12% now, between 3% and 40%". */
|
||||
export function sparkWords(name: string, period: string, latest: number | null, low: number | null, high: number | null, write: (v: number) => string, failed = 0): string {
|
||||
const parts: string[] = [];
|
||||
if (latest === null) parts.push(t("nothing read"));
|
||||
else {
|
||||
parts.push(t("{value} now", { value: write(latest) }));
|
||||
if (low !== null && high !== null && low !== high) parts.push(t("between {low} and {high}", { low: write(low), high: write(high) }));
|
||||
}
|
||||
if (failed > 0) parts.push(tn(failed, "{n} stretch with a failure", "{n} stretches with a failure"));
|
||||
return t("{name}, {period}: {parts}", { name, period, parts: parts.join(", ") });
|
||||
}
|
||||
Reference in new issue
Block a user