/** * What a thing would take with it: the impact lookup, the graph for the map, silencing dependents along with the target, and an alert * pointing at the alert that explains it. * * 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-impact-")); 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, integrations, auditLog } = await import("../src/db/schema.js"); const { runMigrations } = await import("../src/db/migrate.js"); const { buildEdges, dependentsOf, needsOfNode } = await import("../src/services/dependencies.js"); const { dependenciesRouter } = await import("../src/routes/dependencies.js"); const { maintenanceRouter } = await import("../src/routes/maintenance.js"); const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js"); const { trackIntegrationHealth } = await import("../src/services/integrationHealthMonitor.js"); const { listActiveWindows } = await import("../src/services/maintenance.js"); await runMigrations(); const everything = () => true; const edge = (fromType: "server" | "integration", fromId: number, toType: "server" | "integration", toId: number) => ({ fromType, fromId, toType, toId }); describe("walking the graph", () => { const edges = buildEdges(new Map(), [edge("integration", 1, "server", 1), edge("integration", 2, "integration", 1), edge("server", 2, "integration", 1), edge("server", 3, "server", 2)], everything); test("what needs a thing, nearest first, each once, through others too", () => { assert.deepEqual(dependentsOf(edges, "server:1"), [ { key: "integration:1", distance: 1 }, { key: "integration:2", distance: 2 }, { key: "server:2", distance: 2 }, { key: "server:3", distance: 3 }, ]); assert.deepEqual(dependentsOf(edges, "server:3"), [], "nothing needs it"); }); test("what a thing needs, nearest first", () => { assert.deepEqual(needsOfNode(edges, "server:3"), ["server:2", "integration:1", "server:1"]); assert.deepEqual(needsOfNode(edges, "server:1"), []); }); }); describe("through the routes", () => { let app: Server; let base = ""; let who = "operator"; let box = 0; let app1 = 0; let gitea = 0; let semaphore = 0; before(async () => { await db.insert(users).values([ { oidcSub: "operator", name: "Olga", role: "operator" }, { oidcSub: "viewer", name: "Vic", role: "viewer" }, ]); const made = await db .insert(servers) .values([ { name: "box", apiTokenHash: "b", apiTokenPrefix: "b", lastSeenAt: new Date(Date.now() - 3 * 3600_000).toISOString() }, { name: "app", apiTokenHash: "a", apiTokenPrefix: "a", lastSeenAt: new Date().toISOString() }, ]) .returning({ id: servers.id }); box = made[0].id; app1 = made[1].id; const ints = await db .insert(integrations) .values([ { type: "gitea", name: "Gitea", baseUrl: "https://git.lab", config: "{}" }, { type: "semaphore", name: "Semaphore", baseUrl: "https://sem.lab", config: "{}" }, ]) .returning({ id: integrations.id }); gitea = ints[0].id; semaphore = ints[1].id; const a = express(); a.use(express.json()); a.use((req, _res, next) => { (req as unknown as { session: unknown }).session = { user: { sub: who } }; next(); }); a.use("/api/dependencies", dependenciesRouter); a.use("/api/maintenance", maintenanceRouter); app = await new Promise((resolve) => { const s = a.listen(0, "127.0.0.1", () => resolve(s)); }); base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`; const post = (body: unknown) => fetch(`${base}/dependencies`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); assert.equal((await post(edge("integration", gitea, "server", box))).status, 201); assert.equal((await post(edge("integration", semaphore, "integration", gitea))).status, 201); assert.equal((await post(edge("server", app1, "integration", gitea))).status, 201); }); after(() => { app.close(); try { rmSync(dir, { recursive: true, force: true }); } catch { // Windows keeps the database file locked until the process exits. } }); const get = (path: string) => fetch(`${base}${path}`); const startMaintenance = (body: unknown) => fetch(`${base}/maintenance`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); test("the impact of the server: everything that needs it, with how far away it is; what Semaphore needs, nearest first", async () => { const impact = await (await get(`/dependencies/impact?type=server&id=${box}`)).json(); assert.equal(impact.target.name, "box"); assert.deepEqual(impact.dependents.map((d: { name: string; distance: number }) => [d.name, d.distance]).sort(), [["Gitea", 1], ["Semaphore", 2], ["app", 2]]); assert.deepEqual(impact.needs, []); const sem = await (await get(`/dependencies/impact?type=integration&id=${semaphore}`)).json(); assert.deepEqual(sem.needs.map((n: { name: string }) => n.name), ["Gitea", "box"]); assert.equal((await get(`/dependencies/impact?type=server&id=99999`)).status, 404); assert.equal((await get(`/dependencies/impact?type=dns&id=1`)).status, 400); assert.equal((await get(`/dependencies/impact?type=server`)).status, 400); }); test("the graph for the map: only what takes part, the foundations first, with how each is doing", async () => { const graph = await (await get("/dependencies/graph")).json(); const byName = Object.fromEntries(graph.nodes.map((n: { name: string; status: string; href: string }) => [n.name, n])); assert.deepEqual(Object.keys(byName).sort(), ["Gitea", "Semaphore", "app", "box"]); assert.equal(byName.box.status, "bad", "silent for 3 hours"); assert.equal(byName.app.status, "ok"); assert.equal(byName.Gitea.status, "unknown", "nothing has called it yet"); assert.equal(byName.box.href, `/servers/${box}`); assert.deepEqual( graph.edges.map((e: { from: string; to: string; kind: string }) => `${e.from}>${e.to}:${e.kind}`).sort(), [`integration:${gitea}>integration:${semaphore}:written`, `integration:${gitea}>server:${app1}:written`, `server:${box}>integration:${gitea}:written`].sort(), ); }); test("an alert points at the alert that explains it", async () => { await trackIntegrationHealth("gitea", false); invalidateAlertsCache(); const report = await getAlerts(true); const offline = report.alerts.find((a) => a.category === "offline" && a.message.startsWith("box"))!; const failing = report.alerts.find((a) => a.id === "integration:failing:gitea")!; assert.deepEqual(failing.causedBy, { name: "box", alertId: offline.id }); assert.ok(report.alerts.some((a) => a.id === failing.causedBy!.alertId), "and that alert exists"); }); test("silencing a server for maintenance leaves what depends on it alone unless asked", async () => { const res = await startMaintenance({ targetType: "server", targetId: box, minutes: 30, reason: "reboot" }); assert.equal(res.status, 201); assert.deepEqual((await res.json()).alsoSilenced, []); assert.equal((await listActiveWindows()).length, 1); }); test("asked to, it silences everything that depends on it too, for the same time, and says why", async () => { const res = await startMaintenance({ targetType: "server", targetId: box, minutes: 30, reason: "reboot", withDependents: true }); assert.equal(res.status, 201); const body = await res.json(); assert.deepEqual(body.alsoSilenced.map((s: { name: string }) => s.name).sort(), ["Gitea", "Semaphore", "app"]); const windows = await listActiveWindows(); assert.equal(windows.length, 4); const gitea1 = windows.find((w) => w.targetType === "integration" && w.targetId === gitea)!; assert.equal(gitea1.reason, "Depends on box — reboot"); assert.equal(Math.round((Date.parse(gitea1.endsAt) - Date.parse(body.window.endsAt)) / 1000), 0, "the same end"); const audits = (await db.select().from(auditLog)).filter((e) => e.category === "maintenance" && /depends on box/.test(e.detail ?? "")); assert.equal(audits.length, 3); }); test("a viewer can look at the impact but not start maintenance", async () => { who = "viewer"; assert.equal((await get(`/dependencies/impact?type=server&id=${box}`)).status, 200); assert.equal((await startMaintenance({ targetType: "server", targetId: box, minutes: 30, withDependents: true })).status, 403); who = "operator"; }); });