Internet as a dependency: a node that can be needed, never judged down

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-30 23:14:24 +01:00
1 parent fca2dc0338
commit 7e625e7f42
11 files changed
+173 -22

No files matched your search

+5 -2
View File
@@ -6,7 +6,7 @@ import { dependencies, networkDevices, servers } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js";
import { invalidateAlertsCache } from "../services/alerts.js";
import { dependentsOf, impactOf, loadGraph, nodeKey, nodeTypes, wouldLoop } from "../services/dependencies.js";
import { dependentsOf, impactOf, INTERNET_ID, loadGraph, nodeKey, nodeTypes, wouldLoop } from "../services/dependencies.js";
import { getSettings } from "../services/settingsStore.js";
import { loadDependencySuggestions, loadDismissedDependencies, saveDismissedDependencies } from "../services/dependencySuggestions.js";
import { getSourceStatus } from "../services/integrationHealthMonitor.js";
@@ -121,6 +121,8 @@ dependenciesRouter.get("/graph", asyncHandler(async (_req, res) => {
if (type === "server") {
const s = serverById.get(id);
if (s) status = serverStatus(s, healthChecks.serverOfflineMinutes, now);
} else if (type === "internet") {
status = "unknown"; // not watched: nothing here judges the internet down
} else if (type === "device") {
const d = deviceById.get(id);
if (d) status = d.state === "online" ? "ok" : d.state === "offline" ? "bad" : d.state === "updating" ? "warn" : "unknown";
@@ -131,7 +133,7 @@ dependenciesRouter.get("/graph", asyncHandler(async (_req, res) => {
status = st === "failing" ? "bad" : st === "ok" ? "ok" : "unknown";
}
}
return { key, type: type as "server" | "integration" | "device", id, name: graph.names.get(key) ?? key, status, href: type === "server" ? `/servers/${id}` : type === "device" ? "/network/devices" : "/integrations" };
return { key, type: type as "server" | "integration" | "device" | "internet", id, name: graph.names.get(key) ?? key, status, href: type === "server" ? `/servers/${id}` : type === "device" ? "/network/devices" : type === "internet" ? "/map?view=dependencies" : "/integrations" };
})
.sort((a, b) => a.name.localeCompare(b.name));
res.json({ nodes, edges });
@@ -141,6 +143,7 @@ dependenciesRouter.post("/", requireRole("operator"), asyncHandler(async (req, r
const parsed = edgeSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Say what needs what: a server or an integration each.", details: parsed.error.flatten() });
const d = parsed.data;
if (d.fromType === "internet") return res.status(400).json({ error: "internet_needs_nothing", message: "The internet can't be made to need something; pick it as what a server, service or device needs." });
const graph = await loadGraph();
const from = nodeKey(d.fromType, d.fromId);
const to = nodeKey(d.toType, d.toId);
+15 -3
View File
@@ -8,6 +8,9 @@
* that can be down and be needed. (DNS providers raise no alerts of their own, so there is
* nothing to fold.) An integration is judged per kind of service, as its health is: it is folded only if every enabled instance of that
* kind is explained. A UPS is down while it runs on battery (services/upsSync.ts).
*
* "The internet" is a node too, so that what needs it (a cloud service, a VPS monitor, the router) can be drawn and found with "what depends on …?".
* Nothing here judges it down — it is the one node that is never down — so it explains no alert; it is a thing to point at, not a thing that is watched.
*/
import { eq } from "drizzle-orm";
import { db } from "../db/client.js";
@@ -20,9 +23,13 @@ import { upsOnBatteryIds } from "./upsSync.js";
/** Where the health monitor keeps the problems it is announcing; read here so a service's alert can tell a server it needs is down. */
export const HEALTH_STATE_FLAG = "healthActiveConditions";
export const nodeTypes = ["server", "integration", "device"] as const;
export const nodeTypes = ["server", "integration", "device", "internet"] as const;
export type NodeType = (typeof nodeTypes)[number];
/** There is one internet; its node is `internet:1`. */
export const INTERNET_ID = 1;
export const INTERNET_NAME = "Internet";
export const nodeKey = (type: NodeType, id: number) => `${type}:${id}`;
export interface DependencyEdge {
@@ -142,6 +149,7 @@ export async function loadGraph(): Promise<Graph> {
for (const s of serverRows) names.set(nodeKey("server", s.id), s.name);
for (const i of intRows) names.set(nodeKey("integration", i.id), i.name);
for (const d of deviceRows) names.set(nodeKey("device", d.id), d.name);
names.set(nodeKey("internet", INTERNET_ID), INTERNET_NAME);
const rows = depRows.map((r) => ({ id: r.id, fromType: r.fromType as NodeType, fromId: r.fromId, toType: r.toType as NodeType, toId: r.toId, createdAt: r.createdAt }));
const instances = new Map<string, number[]>();
for (const i of intRows) if (i.enabled) instances.set(i.type, [...(instances.get(i.type) ?? []), i.id]);
@@ -197,8 +205,11 @@ export interface ImpactItem {
silenced: boolean;
}
/** What needs something is never the internet (it is only ever needed), so what is affected is one of the three that can be put in maintenance. */
export type DependentItem = ImpactItem & { type: Exclude<NodeType, "internet"> };
/** What would be affected if `type`/`id` went down (everything that needs it) and what it needs itself. Null if it doesn't exist. */
export async function impactOf(type: NodeType, id: number, now: Date = new Date()): Promise<{ target: { key: string; type: NodeType; id: number; name: string }; dependents: ImpactItem[]; needs: ImpactItem[] } | null> {
export async function impactOf(type: NodeType, id: number, now: Date = new Date()): Promise<{ target: { key: string; type: NodeType; id: number; name: string }; dependents: DependentItem[]; needs: ImpactItem[] } | null> {
const graph = await loadGraph();
const key = nodeKey(type, id);
const name = graph.names.get(key);
@@ -211,7 +222,7 @@ export async function impactOf(type: NodeType, id: number, now: Date = new Date(
};
return {
target: { key, type, id, name },
dependents: dependentsOf(graph.edges, key).map((d) => item(d.key, d.distance)),
dependents: dependentsOf(graph.edges, key).map((d) => item(d.key, d.distance) as DependentItem),
needs: needsOfNode(graph.edges, key).map((k, i) => item(k, i + 1)),
};
}
@@ -294,6 +305,7 @@ export async function integrationCausedBy(type: string, failingTypes: string[]):
}
export async function nodeExists(type: NodeType, id: number): Promise<boolean> {
if (type === "internet") return id === INTERNET_ID;
if (type === "device") return (await db.select({ id: networkDevices.id }).from(networkDevices).where(eq(networkDevices.id, id)).limit(1)).length > 0;
if (type === "server") return (await db.select({ id: servers.id }).from(servers).where(eq(servers.id, id)).limit(1)).length > 0;
return (await db.select({ id: integrations.id }).from(integrations).where(eq(integrations.id, id)).limit(1)).length > 0;
+125
View File
@@ -0,0 +1,125 @@
/**
* "The internet" as something a server, a service or a network device can need: it is a node of the dependency graph that is always there, can only be needed, and is never
* judged down — so it can be drawn and asked "what depends on it?", and it folds no alert.
*
* 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-deps-net-"));
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, networkDevices } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { dependenciesRouter } = await import("../src/routes/dependencies.js");
const { nodeExists, INTERNET_ID } = await import("../src/services/dependencies.js");
await runMigrations();
describe("the internet as a dependency", () => {
let app: Server;
let base = "";
let who = "operator";
let box = 0;
let hetzner = 0;
let gateway = 0;
before(async () => {
await db.insert(users).values([
{ oidcSub: "operator", name: "Olga", role: "operator" },
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
]);
box = (await db.insert(servers).values({ name: "vps", apiTokenHash: "v", apiTokenPrefix: "v", lastSeenAt: new Date().toISOString() }).returning({ id: servers.id }))[0].id;
const ints = await db.insert(integrations).values([{ type: "hetzner", name: "Hetzner", baseUrl: "https://api.hetzner.cloud", config: "{}" }, { type: "unifi", name: "UniFi", baseUrl: "https://unifi.lab", config: "{}" }]).returning({ id: integrations.id });
hetzner = ints[0].id;
gateway = (await db.insert(networkDevices).values({ integrationId: ints[1].id, externalId: "aa:bb:cc:dd:ee:ff", name: "Gateway", kind: "gateway", state: "online", firstSeenAt: new Date().toISOString(), updatedAt: new Date().toISOString() }).returning({ id: networkDevices.id }))[0].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);
app = await new Promise<Server>((resolve) => {
const s = a.listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/dependencies`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
const send = (method: string, path: string, body?: unknown) => fetch(`${base}${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
const need = (fromType: string, fromId: number) => ({ fromType, fromId, toType: "internet", toId: INTERNET_ID });
test("the internet is always there to be picked, whatever else exists", async () => {
const list = await (await send("GET", "/")).json();
assert.ok(list.nodes.some((n: { key: string; name: string; type: string }) => n.key === "internet:1" && n.name === "Internet" && n.type === "internet"));
assert.equal(await nodeExists("internet", 1), true);
assert.equal(await nodeExists("internet", 2), false);
});
test("a server, a service and a network device can each need it", async () => {
assert.equal((await send("POST", "/", need("server", box))).status, 201);
assert.equal((await send("POST", "/", need("integration", hetzner))).status, 201);
assert.equal((await send("POST", "/", need("device", gateway))).status, 201);
const list = await (await send("GET", "/")).json();
assert.deepEqual(list.dependencies.map((d: { from: { name: string }; to: { name: string } }) => `${d.from.name} > ${d.to.name}`).sort(), ["Gateway > Internet", "Hetzner > Internet", "vps > Internet"]);
});
test("it can't be made to need anything, there is only the one, and it isn't added twice", async () => {
const reverse = await send("POST", "/", { fromType: "internet", fromId: 1, toType: "server", toId: box });
assert.equal(reverse.status, 400);
assert.match((await reverse.json()).message, /can't be made to need/);
assert.equal((await send("POST", "/", { fromType: "server", fromId: box, toType: "internet", toId: 2 })).status, 400, "there is no second internet");
assert.equal((await send("POST", "/", need("server", box))).status, 409, "twice");
who = "viewer";
assert.equal((await send("POST", "/", need("integration", hetzner))).status, 403);
who = "operator";
});
test("asking what depends on it lists all three; it relies on nothing", async () => {
const impact = await (await send("GET", "/impact?type=internet&id=1")).json();
assert.equal(impact.target.name, "Internet");
assert.deepEqual(impact.dependents.map((d: { name: string }) => d.name).sort(), ["Gateway", "Hetzner", "vps"]);
assert.deepEqual(impact.needs, []);
const server = await (await send("GET", `/impact?type=server&id=${box}`)).json();
assert.deepEqual(server.needs.map((n: { name: string; type: string }) => [n.name, n.type]), [["Internet", "internet"]]);
});
test("on the map it is a box that is not watched; it is never down", async () => {
const graph = await (await send("GET", "/graph")).json();
const node = graph.nodes.find((n: { key: string }) => n.key === "internet:1");
assert.equal(node.name, "Internet");
assert.equal(node.status, "unknown");
assert.equal(node.type, "internet");
assert.equal(graph.edges.filter((e: { from: string }) => e.from === "internet:1").length, 3, "from what is needed to what needs it");
});
test("removing one works, and the internet stays", async () => {
const list = await (await send("GET", "/")).json();
const one = list.dependencies.find((d: { from: { name: string } }) => d.from.name === "Hetzner");
assert.equal((await send("DELETE", `/${one.id}`)).status, 204);
const after = await (await send("GET", "/impact?type=internet&id=1")).json();
assert.deepEqual(after.dependents.map((d: { name: string }) => d.name).sort(), ["Gateway", "vps"]);
assert.equal(after.target.name, "Internet");
});
});