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>
206 lines
9.6 KiB
TypeScript
206 lines
9.6 KiB
TypeScript
/**
|
||
* 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)
|
||
});
|
||
});
|