Files
Homelab-manager/server/test/maintenanceSchedules.test.ts
bobbanandClaude Sonnet 5.5 540ab704b7 Export CSV on every table, edit recurring maintenance, runs-on nothing, and run package checks outside the agent sandbox
- Export CSV for the small tables that had none (reads the table as shown)
- Servers page shows a skeleton while loading instead of "No servers registered yet"
- Recurring maintenance schedules can be edited (PUT /schedules/:id)
- A server can be set to run on nothing (servers.no_parent, migration 0028)
- Linux agent v3: package-manager question runs in ExecStartPre=-+ outside the sandbox,
  with --prepare-updates and --check-updates modes
- Docs: README, DATABASE, AGENT_UPDATE

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-17 22:25:18 +02:00

235 lines
14 KiB
TypeScript

/**
* Recurring maintenance: when a schedule happens (across summer and winter time), and the windows made from 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-sched-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, servers, maintenanceWindows, maintenanceSchedules, auditLog } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { maintenanceRouter } = await import("../src/routes/maintenance.js");
const { occurrencesBetween, zonedTime, materializeSchedules, isValidTimeZone } = await import("../src/services/maintenanceSchedules.js");
const { listActiveWindows } = await import("../src/services/maintenance.js");
const { eq, like } = await import("drizzle-orm");
await runMigrations();
const sched = (days: number[], startTime: string, durationMinutes: number, timezone: string) => ({ days: JSON.stringify(days), startTime, durationMinutes, timezone });
const iso = (d: Date) => d.toISOString();
describe("when a schedule happens", () => {
test("a wall-clock time follows summer and winter time", () => {
// Sundays in Stockholm: 18 October is still summer time (UTC+2), 1 November is winter time (UTC+1).
const s = sched([0], "02:00", 120, "Europe/Stockholm");
const occ = occurrencesBetween(s, new Date("2026-10-15T00:00:00Z"), new Date("2026-11-03T00:00:00Z"));
const byDate = Object.fromEntries(occ.map((o) => [o.date, [iso(o.start), iso(o.end)]]));
assert.deepEqual(byDate["2026-10-18"], ["2026-10-18T00:00:00.000Z", "2026-10-18T02:00:00.000Z"]);
assert.deepEqual(byDate["2026-11-01"], ["2026-11-01T01:00:00.000Z", "2026-11-01T03:00:00.000Z"]);
assert.deepEqual(Object.keys(byDate).sort(), ["2026-10-18", "2026-10-25", "2026-11-01"]);
});
test("it is the same wall-clock time in another zone, and a time that doesn't exist that night still happens", () => {
assert.equal(iso(zonedTime(2026, 7, 1, 2, 0, "America/New_York")), "2026-07-01T06:00:00.000Z");
assert.equal(iso(zonedTime(2026, 1, 1, 2, 0, "America/New_York")), "2026-01-01T07:00:00.000Z");
// 29 March 2026: clocks in Stockholm jump from 02:00 to 03:00, so 02:30 isn't a time that night.
const gap = zonedTime(2026, 3, 29, 2, 30, "Europe/Stockholm");
assert.ok(Math.abs(gap.getTime() - Date.parse("2026-03-29T01:00:00Z")) <= 3600_000);
assert.equal(zonedTime(2026, 10, 18, 0, 0, "UTC").toISOString(), "2026-10-18T00:00:00.000Z");
});
test("one that runs past midnight belongs to the day it starts, and one under way counts", () => {
const s = sched([6], "23:00", 180, "UTC"); // Saturday 23:00 for three hours
const [occ] = occurrencesBetween(s, new Date("2026-10-18T00:30:00Z"), new Date("2026-10-18T06:00:00Z"));
assert.equal(occ.date, "2026-10-17");
assert.equal(iso(occ.start), "2026-10-17T23:00:00.000Z");
assert.equal(iso(occ.end), "2026-10-18T02:00:00.000Z");
assert.equal(occurrencesBetween(s, new Date("2026-10-18T02:00:00Z"), new Date("2026-10-18T06:00:00Z")).length, 0, "already over");
});
test("every day, and only the days chosen", () => {
const week = occurrencesBetween(sched([0, 1, 2, 3, 4, 5, 6], "04:00", 60, "UTC"), new Date("2026-10-12T00:00:00Z"), new Date("2026-10-19T00:00:00Z"));
assert.equal(week.length, 7);
const weekdays = occurrencesBetween(sched([1, 3], "04:00", 60, "UTC"), new Date("2026-10-12T00:00:00Z"), new Date("2026-10-19T00:00:00Z"));
assert.deepEqual(weekdays.map((o) => o.date), ["2026-10-12", "2026-10-14"]);
});
test("time zone names are checked", () => {
assert.equal(isValidTimeZone("Europe/Stockholm"), true);
assert.equal(isValidTimeZone("Mars/Olympus"), false);
});
});
describe("the schedules and their windows", () => {
let app: Server;
let base = "";
let who = "operator";
let a = 0;
let b = 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: "elsa", apiTokenHash: "a", apiTokenPrefix: "a" },
{ name: "anna", apiTokenHash: "b", apiTokenPrefix: "b" },
])
.returning({ id: servers.id });
a = made[0].id;
b = made[1].id;
const app0 = express();
app0.use(express.json());
app0.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: who } };
next();
});
app0.use("/api/maintenance", maintenanceRouter);
app = await new Promise<Server>((resolve) => {
const s = app0.listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/maintenance`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
const call = (method: string, path: string, body?: unknown) =>
fetch(`${base}${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
const good = { name: "Patch night", reason: "OS updates", targets: [{ type: "server", id: 0 }], days: [0, 1, 2, 3, 4, 5, 6], startTime: "03:00", durationMinutes: 60, timezone: "UTC" };
const windowsOf = async (id: number) => db.select().from(maintenanceWindows).where(like(maintenanceWindows.source, `schedule:${id}:%`));
let scheduleId = 0;
test("making a schedule makes the coming week's windows, once each, for every server on it", async () => {
const res = await call("POST", "/schedules", { ...good, targets: [{ type: "server", id: a }, { type: "server", id: b }, { type: "server", id: a }] });
assert.equal(res.status, 201);
const body = await res.json();
scheduleId = body.id;
const windows = await windowsOf(scheduleId);
assert.ok(body.windowsMade === windows.length && (windows.length === 14 || windows.length === 16), `made ${windows.length}`);
assert.equal(new Set(windows.map((w) => `${w.targetId}|${w.source}`)).size, windows.length, "no duplicates");
assert.ok(windows.every((w) => w.reason === "Patch night: OS updates" && w.createdBy === "Recurring: Patch night"));
assert.ok(windows.every((w) => w.endsAt > w.startedAt));
// running again makes nothing more
assert.equal(await materializeSchedules(), 0);
assert.equal((await windowsOf(scheduleId)).length, windows.length);
});
test("a window cancelled by hand isn't made again, and the list says what is next", async () => {
const before = await windowsOf(scheduleId);
const one = before.find((w) => w.startedAt > new Date().toISOString())!;
await db.update(maintenanceWindows).set({ endsAt: one.startedAt }).where(eq(maintenanceWindows.id, one.id));
assert.equal(await materializeSchedules(), 0);
assert.equal((await windowsOf(scheduleId)).length, before.length);
const list = await (await call("GET", "/schedules")).json();
assert.equal(list.schedules.length, 1);
assert.equal(list.schedules[0].targets.length, 2);
assert.deepEqual(list.schedules[0].days, [0, 1, 2, 3, 4, 5, 6]);
assert.ok(Date.parse(list.schedules[0].nextStart) > 0);
});
test("a window made from a schedule silences while it runs", async () => {
const now = Date.now();
await db.insert(maintenanceWindows).values({ targetType: "server", targetId: a, reason: "x", startedAt: new Date(now - 60_000).toISOString(), endsAt: new Date(now + 600_000).toISOString(), source: `schedule:${scheduleId}:2000-01-01` });
assert.ok((await listActiveWindows()).some((w) => w.source === `schedule:${scheduleId}:2000-01-01`));
await db.delete(maintenanceWindows).where(eq(maintenanceWindows.source, `schedule:${scheduleId}:2000-01-01`));
});
test("switching it off takes back what hasn't begun, and on makes it again", async () => {
assert.equal((await call("PATCH", `/schedules/${scheduleId}`, { enabled: false })).status, 200);
assert.equal((await windowsOf(scheduleId)).filter((w) => w.startedAt > new Date().toISOString()).length, 0);
assert.equal(await materializeSchedules(), 0, "off means nothing is made");
assert.equal((await call("PATCH", `/schedules/${scheduleId}`, { enabled: true })).status, 200);
assert.ok((await windowsOf(scheduleId)).length >= 12);
});
test("editing a schedule remakes the windows that haven't begun from the new settings, and keeps what is under way", async () => {
const now = Date.now();
await db.insert(maintenanceWindows).values({ targetType: "server", targetId: a, reason: "x", startedAt: new Date(now - 60_000).toISOString(), endsAt: new Date(now + 600_000).toISOString(), source: `schedule:${scheduleId}:2000-01-02` });
const edited = { ...good, name: "Patch weekend", reason: "", targets: [{ type: "server", id: a }], days: [6], startTime: "01:30", durationMinutes: 90 };
const res = await call("PUT", `/schedules/${scheduleId}`, edited);
assert.equal(res.status, 200);
const future = (await windowsOf(scheduleId)).filter((w) => w.startedAt > new Date().toISOString());
assert.ok(future.length >= 1 && future.length <= 2, `${future.length} Saturdays in the coming week`);
assert.ok(future.every((w) => w.targetId === a && w.reason === "Patch weekend" && new Date(w.startedAt).getUTCDay() === 6 && w.startedAt.includes("T01:30") && Date.parse(w.endsAt) - Date.parse(w.startedAt) === 90 * 60_000));
assert.ok((await windowsOf(scheduleId)).some((w) => w.source.endsWith("2000-01-02")), "the one under way is left alone");
await db.delete(maintenanceWindows).where(eq(maintenanceWindows.source, `schedule:${scheduleId}:2000-01-02`));
const list = await (await call("GET", "/schedules")).json();
assert.equal(list.schedules[0].name, "Patch weekend");
assert.deepEqual(list.schedules[0].days, [6]);
assert.equal(list.schedules[0].reason, null);
assert.equal(list.schedules[0].targets.length, 1);
assert.equal(list.schedules[0].enabled, true);
// a bad edit changes nothing; a schedule that is off stays off and makes nothing
assert.equal((await call("PUT", `/schedules/${scheduleId}`, { ...edited, timezone: "Mars/Olympus" })).status, 400);
assert.equal((await call("PUT", `/schedules/${scheduleId}`, { ...edited, targets: [{ type: "server", id: 99999 }] })).status, 400);
assert.equal((await call("PUT", "/schedules/99999", edited)).status, 404);
assert.equal((await (await call("GET", "/schedules")).json()).schedules[0].name, "Patch weekend");
await call("PATCH", `/schedules/${scheduleId}`, { enabled: false });
assert.equal((await (await call("PUT", `/schedules/${scheduleId}`, { ...edited, days: [0, 1] })).json()).windowsMade, 0);
assert.equal((await windowsOf(scheduleId)).filter((w) => w.startedAt > new Date().toISOString()).length, 0);
assert.equal((await (await call("GET", "/schedules")).json()).schedules[0].enabled, false);
await call("PUT", `/schedules/${scheduleId}`, { ...good, targets: [{ type: "server", id: a }, { type: "server", id: b }] });
await call("PATCH", `/schedules/${scheduleId}`, { enabled: true });
});
test("only operators change schedules; a bad one is refused", async () => {
who = "viewer";
assert.equal((await call("POST", "/schedules", { ...good, targets: [{ type: "server", id: a }] })).status, 403);
assert.equal((await call("PATCH", `/schedules/${scheduleId}`, { enabled: false })).status, 403);
assert.equal((await call("PUT", `/schedules/${scheduleId}`, { ...good, targets: [{ type: "server", id: a }] })).status, 403);
assert.equal((await call("DELETE", `/schedules/${scheduleId}`)).status, 403);
assert.equal((await call("GET", "/schedules")).status, 200, "anyone signed in can see them");
who = "operator";
const target = [{ type: "server", id: a }];
for (const bad of [
{ ...good, targets: target, name: "" },
{ ...good, targets: [] },
{ ...good, targets: target, days: [] },
{ ...good, targets: target, days: [7] },
{ ...good, targets: target, startTime: "25:00" },
{ ...good, targets: target, startTime: "3am" },
{ ...good, targets: target, durationMinutes: 5 },
{ ...good, targets: target, timezone: "Mars/Olympus" },
{ ...good, targets: [{ type: "server", id: 99999 }] },
]) {
assert.equal((await call("POST", "/schedules", bad)).status, 400, JSON.stringify(bad).slice(0, 80));
}
});
test("removing a schedule takes back what hasn't begun and is in the audit log", async () => {
assert.equal((await call("DELETE", `/schedules/${scheduleId}`)).status, 204);
assert.equal((await db.select().from(maintenanceSchedules)).length, 0);
assert.equal((await windowsOf(scheduleId)).filter((w) => w.startedAt > new Date().toISOString()).length, 0);
assert.equal((await call("DELETE", `/schedules/${scheduleId}`)).status, 404);
const actions = (await db.select().from(auditLog)).filter((e) => e.category === "maintenance").map((e) => e.action);
for (const wanted of ["create_schedule", "update_schedule", "disable_schedule", "enable_schedule", "delete_schedule"]) assert.ok(actions.includes(wanted), wanted);
});
});