Patch plans (Updates -> Patch plans): updates on a schedule, one server at a time, each by an ordinary update run, stopping at the first failure by default, silencing what depends on a server while it is updated, with one message at the end. Monthly report (Operations -> Monthly report, and optionally a message on a day of the month): availability, incidents, updates, restore tests, backups and renewals for a calendar month, printable. Backed by daily endpoint figures and a record of renewals. New ports: the first report with ports is the baseline; a TCP port that begins listening later and is not noted on the server's Ports card is a warning, cleared by Mark as expected. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
408 lines
24 KiB
TypeScript
408 lines
24 KiB
TypeScript
/**
|
||
* Patch plans: who a plan covers, when it is due, that it goes one server at a time and waits for each, what it does when one fails, what it silences,
|
||
* the message at the end, and who may do what.
|
||
*
|
||
* Run with: npm test --workspace server
|
||
*/
|
||
import { test, describe, before, after } from "node:test";
|
||
import assert from "node:assert/strict";
|
||
import { createServer as createHttpServer, type Server } from "node:http";
|
||
import { mkdtempSync, rmSync } from "node:fs";
|
||
import { tmpdir } from "node:os";
|
||
import { join } from "node:path";
|
||
import type { AddressInfo } from "node:net";
|
||
|
||
const dir = mkdtempSync(join(tmpdir(), "hm-patchplans-"));
|
||
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, patchPlans, patchPlanRuns, updateRuns, maintenanceWindows } = await import("../src/db/schema.js");
|
||
const { runMigrations } = await import("../src/db/migrate.js");
|
||
const { planServers, dueOccurrence, summariseItems, startPlanRun, advancePlanRuns, startDuePlans, cancelPlanRun, parseItems, PlanError } = await import("../src/services/patchPlans.js");
|
||
const { advanceUpdateRuns, setSemaphoreForTests } = await import("../src/services/updateRuns.js");
|
||
const { listActiveWindows } = await import("../src/services/maintenance.js");
|
||
const { agendaFromData } = await import("../src/services/agenda.js");
|
||
const { patchPlansRouter } = await import("../src/routes/patchPlans.js");
|
||
const { updateSettings } = await import("../src/services/settingsStore.js");
|
||
const { eq } = await import("drizzle-orm");
|
||
|
||
await runMigrations();
|
||
|
||
// ── a Semaphore that answers as told ──
|
||
const fake = { runs: [] as { limit?: string }[], task: { id: 41, status: "waiting", created: null as string | null, start: null as string | null, end: null as string | null }, refuseFor: new Set<string>() };
|
||
setSemaphoreForTests(async (integrationId) =>
|
||
integrationId === 9
|
||
? {
|
||
ping: async () => ({ ok: true }),
|
||
listTemplatesWithStatus: async () => [],
|
||
checkTemplates: async () => ({ templates: [{ id: 7, projectId: 2, projectName: "Homelab", name: "Apply updates", playbook: "u.yml", lastTask: null }], failedProjectIds: [] }),
|
||
runTemplate: async (_p: number, _t: number, options?: { limit?: string }) => {
|
||
if (options?.limit && fake.refuseFor.has(options.limit)) throw new Error("Semaphore is having a moment");
|
||
fake.runs.push({ limit: options?.limit });
|
||
return { ...fake.task } as never;
|
||
},
|
||
getTask: async () => ({ ...fake.task }) as never,
|
||
}
|
||
: null,
|
||
);
|
||
|
||
const T0 = new Date("2026-10-18T02:05:00.000Z"); // a Sunday
|
||
const at = (m: number) => new Date(T0.getTime() + m * 60_000);
|
||
|
||
describe("who a plan covers, and when it is due", () => {
|
||
const all = [
|
||
{ id: 1, name: "web", tags: JSON.stringify(["lab"]) },
|
||
{ id: 2, name: "api", tags: JSON.stringify(["prod"]) },
|
||
{ id: 3, name: "ångström", tags: JSON.stringify(["lab", "prod"]) },
|
||
{ id: 4, name: "db", tags: null },
|
||
];
|
||
|
||
test("servers with any of the tags, and those named, by name; each only once", () => {
|
||
assert.deepEqual(planServers({ tags: JSON.stringify(["lab"]), serverIds: "[]" }, all).map((s) => s.name), ["ångström", "web"].sort((x, y) => x.localeCompare(y)));
|
||
assert.deepEqual(planServers({ tags: JSON.stringify(["lab"]), serverIds: JSON.stringify([4, 3]) }, all).map((s) => s.name), ["db", "ångström", "web"].sort((x, y) => x.localeCompare(y)), "in the order the app sorts names");
|
||
assert.deepEqual(planServers({ tags: "[]", serverIds: "[]" }, all), [], "a plan that names no one covers no one");
|
||
});
|
||
|
||
const plan = { enabled: true, days: JSON.stringify([0]), startTime: "02:00", timezone: "UTC", lastRunDate: null as string | null };
|
||
|
||
test("due from its time to half an hour after, once a day, only on its days", () => {
|
||
assert.equal(dueOccurrence(plan, new Date("2026-10-18T01:59:00Z")), null, "not yet");
|
||
assert.equal(dueOccurrence(plan, new Date("2026-10-18T02:00:00Z"))?.date, "2026-10-18");
|
||
assert.equal(dueOccurrence(plan, new Date("2026-10-18T02:29:00Z"))?.date, "2026-10-18", "the app may have been down for a while");
|
||
assert.equal(dueOccurrence(plan, new Date("2026-10-18T02:31:00Z")), null, "too late: that day is skipped");
|
||
assert.equal(dueOccurrence({ ...plan, lastRunDate: "2026-10-18" }, new Date("2026-10-18T02:10:00Z")), null, "already started today");
|
||
assert.equal(dueOccurrence(plan, new Date("2026-10-19T02:10:00Z")), null, "Monday is not a day it runs");
|
||
assert.equal(dueOccurrence({ ...plan, enabled: false }, new Date("2026-10-18T02:10:00Z")), null);
|
||
});
|
||
|
||
test("its time is on the clock of its time zone, winter and summer", () => {
|
||
const stockholm = { ...plan, timezone: "Europe/Stockholm" };
|
||
assert.equal(dueOccurrence(stockholm, new Date("2026-10-18T00:05:00Z"))?.date, "2026-10-18", "02:05 in Stockholm is 00:05 UTC while summer time lasts");
|
||
assert.equal(dueOccurrence(stockholm, new Date("2026-11-01T01:05:00Z"))?.date, "2026-11-01", "and 01:05 UTC after the clocks go back");
|
||
assert.equal(dueOccurrence(stockholm, new Date("2026-11-01T00:05:00Z")), null);
|
||
});
|
||
|
||
test("a finished run says how each went in one line", () => {
|
||
const item = (status: string) => ({ serverId: 1, name: "x", status, updateRunId: null, message: null, windowIds: [] }) as never;
|
||
assert.equal(summariseItems([item("done"), item("done"), item("failed"), item("skipped")]), "2 updated, 1 failed, 1 left alone of 4 servers.");
|
||
assert.equal(summariseItems([item("done")]), "1 updated of 1 server.");
|
||
});
|
||
|
||
test("a plan is in the agenda as maintenance, with how many servers it updates", () => {
|
||
const data = { secrets: [], domains: [], endpoints: [], tailscale: [], assets: [], windows: [], schedules: [], restoreTests: [], restoreLimitDays: 0, updates: [], notes: [], patchPlans: [{ id: 5, name: "Lab nights", days: JSON.stringify([0]), startTime: "02:00", timezone: "UTC", servers: 3 }] };
|
||
const items = agendaFromData(data, new Date("2026-10-19T12:00:00Z"), "UTC", 20).items.filter((i) => i.id.startsWith("plan:"));
|
||
assert.deepEqual(items.map((i) => [i.title, i.detail, i.at.slice(0, 16), i.kind]), [["Patch plan: Lab nights", "updates 3 servers, one at a time", "2026-10-25T02:00", "maintenance"], ["Patch plan: Lab nights", "updates 3 servers, one at a time", "2026-11-01T02:00", "maintenance"], ["Patch plan: Lab nights", "updates 3 servers, one at a time", "2026-11-08T02:00", "maintenance"]]);
|
||
});
|
||
});
|
||
|
||
describe("a run, from start to end", () => {
|
||
let hook: Server;
|
||
const messages: string[] = [];
|
||
const ids: Record<string, number> = {};
|
||
let planId = 0;
|
||
|
||
const plan = (extra: Partial<typeof patchPlans.$inferInsert> = {}) => ({
|
||
name: "Lab nights", days: JSON.stringify([0]), startTime: "02:00", timezone: "UTC", tags: JSON.stringify(["lab"]), serverIds: "[]", integrationId: 9, projectId: 2, templateId: 7, templateName: "Apply updates", limitFrom: "name", stopOnFailure: true, onlyWithUpdates: true, silenceDependents: true, windowMinutes: 90, ...extra,
|
||
});
|
||
const updates = (count: number, reportedAt = T0.toISOString()) => JSON.stringify({ manager: "apt", count, security: 0, rebootRequired: false, reportedAt });
|
||
const runOf = async (id: number) => (await db.select().from(patchPlanRuns).where(eq(patchPlanRuns.id, id)))[0];
|
||
const itemsOf = async (id: number) => parseItems((await runOf(id)).items);
|
||
|
||
/** The playbook for the server being updated finishes and the server reports again — as the update run follows. */
|
||
async function finishCurrent(server: string, minute: number) {
|
||
fake.task = { id: 41, status: "success", created: null, start: null, end: at(minute).toISOString() };
|
||
await advanceUpdateRuns(at(minute + 1));
|
||
await db.update(servers).set({ lastSeenAt: at(minute + 2).toISOString(), pendingUpdates: updates(0, at(minute + 2).toISOString()) }).where(eq(servers.id, ids[server]));
|
||
await advanceUpdateRuns(at(minute + 3));
|
||
fake.task = { id: 41, status: "waiting", created: null, start: null, end: null };
|
||
}
|
||
|
||
async function reset(extra: Partial<typeof patchPlans.$inferInsert> = {}) {
|
||
await db.delete(patchPlans);
|
||
await db.delete(updateRuns);
|
||
await db.delete(maintenanceWindows); // the tests share one clock, so a window left by the last would still be open
|
||
fake.runs = [];
|
||
fake.refuseFor.clear();
|
||
fake.task = { id: 41, status: "waiting", created: null, start: null, end: null };
|
||
for (const name of ["web", "api"]) await db.update(servers).set({ lastSeenAt: T0.toISOString(), pendingUpdates: updates(4) }).where(eq(servers.id, ids[name]));
|
||
await db.update(servers).set({ lastSeenAt: T0.toISOString(), pendingUpdates: updates(0) }).where(eq(servers.id, ids.idle));
|
||
messages.length = 0;
|
||
planId = (await db.insert(patchPlans).values(plan(extra)).returning({ id: patchPlans.id }))[0].id;
|
||
}
|
||
|
||
before(async () => {
|
||
for (const name of ["web", "api", "idle"]) {
|
||
ids[name] = (await db.insert(servers).values({ name, apiTokenHash: name, apiTokenPrefix: name, tags: JSON.stringify(["lab"]), lastSeenAt: T0.toISOString() }).returning({ id: servers.id }))[0].id;
|
||
}
|
||
ids.prod = (await db.insert(servers).values({ name: "prod", apiTokenHash: "p", apiTokenPrefix: "p", tags: JSON.stringify(["prod"]), lastSeenAt: T0.toISOString(), pendingUpdates: updates(9) }).returning({ id: servers.id }))[0].id;
|
||
// a guest that runs on web: what depends on web
|
||
ids.guest = (await db.insert(servers).values({ name: "guest", apiTokenHash: "g", apiTokenPrefix: "g", lastSeenAt: T0.toISOString(), parentServerId: ids.web }).returning({ id: servers.id }))[0].id;
|
||
hook = createHttpServer((req, res) => {
|
||
const chunks: Buffer[] = [];
|
||
req.on("data", (c) => chunks.push(c));
|
||
req.on("end", () => {
|
||
messages.push(String(JSON.parse(Buffer.concat(chunks).toString()).content));
|
||
res.end("{}");
|
||
});
|
||
});
|
||
await new Promise<void>((r) => hook.listen(0, "127.0.0.1", r));
|
||
await updateSettings({ webhook: { enabled: true, url: `http://127.0.0.1:${(hook.address() as AddressInfo).port}/` } });
|
||
});
|
||
|
||
after(() => {
|
||
hook.close();
|
||
setSemaphoreForTests(null);
|
||
try {
|
||
rmSync(dir, { recursive: true, force: true });
|
||
} catch {
|
||
// Windows keeps the database file locked until the process exits.
|
||
}
|
||
});
|
||
|
||
test("one server at a time, each waited for, those with nothing waiting left alone, and a message at the end", async () => {
|
||
await reset();
|
||
const run = await startPlanRun(planId, { trigger: "manual", actor: "Olle", now: T0 });
|
||
assert.deepEqual((await itemsOf(run.id)).map((i) => [i.name, i.status]), [["api", "pending"], ["idle", "pending"], ["web", "pending"]], "by name");
|
||
|
||
await advancePlanRuns(T0);
|
||
assert.deepEqual((await itemsOf(run.id)).map((i) => i.status), ["running", "pending", "pending"]);
|
||
assert.deepEqual(fake.runs.map((r) => r.limit), ["api"], "only the first has been started");
|
||
assert.equal((await listActiveWindows(T0)).some((w) => w.targetType === "server" && w.targetId === ids.api), true, "and it is under maintenance");
|
||
|
||
await advancePlanRuns(at(1));
|
||
assert.equal(fake.runs.length, 1, "while it is still running, nothing else starts");
|
||
|
||
await finishCurrent("api", 5);
|
||
await advancePlanRuns(at(9));
|
||
assert.deepEqual((await itemsOf(run.id)).map((i) => i.status), ["done", "skipped", "running"], "idle has nothing waiting, so it is passed over, and web is next");
|
||
assert.deepEqual(fake.runs.map((r) => r.limit), ["api", "web"]);
|
||
assert.equal((await itemsOf(run.id))[1].message, "No updates were waiting.");
|
||
assert.equal((await listActiveWindows(at(9))).some((w) => w.targetId === ids.api), false, "api's maintenance ended with its update");
|
||
|
||
await finishCurrent("web", 15);
|
||
await advancePlanRuns(at(19));
|
||
const done = await runOf(run.id);
|
||
assert.equal(done.status, "done");
|
||
assert.equal(done.message, "2 updated, 1 left alone of 3 servers.");
|
||
assert.equal(messages.length >= 3, true, "each update run says how it went, and so does the plan");
|
||
const last = messages[messages.length - 1];
|
||
assert.match(last, /2 updated, 1 left alone of 3 servers\./);
|
||
assert.match(last, /✓ api/);
|
||
assert.match(last, /– idle — No updates were waiting\./);
|
||
assert.match(last, /✓ web/);
|
||
});
|
||
|
||
test("what depends on a server is silenced while it is updated, and let go when it is done", async () => {
|
||
await reset({ tags: "[]", serverIds: JSON.stringify([ids.web]) });
|
||
const run = await startPlanRun(planId, { trigger: "manual", actor: "Olle", now: T0 });
|
||
await advancePlanRuns(T0);
|
||
const during = await listActiveWindows(T0);
|
||
assert.equal(during.some((w) => w.targetId === ids.guest), true, "the guest that runs on web");
|
||
assert.match(during.find((w) => w.targetId === ids.guest)!.reason ?? "", /Depends on web — patch plan "Lab nights"/);
|
||
assert.equal((await itemsOf(run.id))[0].windowIds.length, 1);
|
||
await finishCurrent("web", 5);
|
||
await advancePlanRuns(at(9));
|
||
assert.equal((await listActiveWindows(at(9))).some((w) => w.targetId === ids.guest), false);
|
||
assert.equal((await runOf(run.id)).status, "done");
|
||
});
|
||
|
||
test("it can be told not to silence what depends on a server", async () => {
|
||
await reset({ tags: "[]", serverIds: JSON.stringify([ids.web]), silenceDependents: false });
|
||
await startPlanRun(planId, { trigger: "manual", actor: "Olle", now: T0 });
|
||
await advancePlanRuns(T0);
|
||
assert.equal((await listActiveWindows(T0)).some((w) => w.targetId === ids.guest), false);
|
||
});
|
||
|
||
test("a failure stops the plan and leaves the rest alone, saying where it stopped", async () => {
|
||
await reset();
|
||
const run = await startPlanRun(planId, { trigger: "manual", actor: "Olle", now: T0 });
|
||
await advancePlanRuns(T0);
|
||
fake.task = { id: 41, status: "error", created: null, start: null, end: null };
|
||
await advanceUpdateRuns(at(2));
|
||
await advancePlanRuns(at(3));
|
||
const after = await runOf(run.id);
|
||
assert.equal(after.status, "failed");
|
||
assert.deepEqual((await itemsOf(run.id)).map((i) => [i.name, i.status]), [["api", "failed"], ["idle", "skipped"], ["web", "skipped"]]);
|
||
assert.equal((await itemsOf(run.id))[2].message, "Not started, because an earlier server failed.");
|
||
assert.match(after.message ?? "", /1 failed, 2 left alone of 3 servers\. Stopped after api\./);
|
||
assert.deepEqual(fake.runs.map((r) => r.limit), ["api"], "web was never touched");
|
||
assert.match(messages[messages.length - 1], /✕ api/);
|
||
assert.equal(messages.some((m) => m.includes("didn't finish cleanly")), true);
|
||
});
|
||
|
||
test("told to carry on, it does: the failed one is reported and the rest are updated", async () => {
|
||
await reset({ stopOnFailure: false });
|
||
const run = await startPlanRun(planId, { trigger: "manual", actor: "Olle", now: T0 });
|
||
await advancePlanRuns(T0);
|
||
fake.task = { id: 41, status: "error", created: null, start: null, end: null };
|
||
await advanceUpdateRuns(at(2));
|
||
fake.task = { id: 41, status: "waiting", created: null, start: null, end: null };
|
||
await advancePlanRuns(at(3));
|
||
assert.deepEqual((await itemsOf(run.id)).map((i) => i.status), ["failed", "skipped", "running"], "web is next");
|
||
await finishCurrent("web", 10);
|
||
await advancePlanRuns(at(14));
|
||
const done = await runOf(run.id);
|
||
assert.equal(done.status, "failed", "something failed, so the run says so");
|
||
assert.equal(done.message, "1 updated, 1 failed, 1 left alone of 3 servers.");
|
||
});
|
||
|
||
test("a server that can't be started counts as a failure; a server with nothing to update can be updated all the same if asked", async () => {
|
||
await reset({ onlyWithUpdates: false, tags: "[]", serverIds: JSON.stringify([ids.idle]) });
|
||
const run = await startPlanRun(planId, { trigger: "manual", actor: "Olle", now: T0 });
|
||
await advancePlanRuns(T0);
|
||
assert.deepEqual(fake.runs.map((r) => r.limit), ["idle"], "it had nothing waiting but the plan was told not to mind");
|
||
await updateRunsCancelAll();
|
||
await cancelPlanRun(run.id, "Olle", at(1));
|
||
|
||
await reset({ tags: "[]", serverIds: JSON.stringify([ids.web]) });
|
||
fake.refuseFor.add("web");
|
||
const refused = await startPlanRun(planId, { trigger: "manual", actor: "Olle", now: T0 });
|
||
await advancePlanRuns(T0);
|
||
const items = await itemsOf(refused.id);
|
||
assert.equal(items[0].status, "failed");
|
||
assert.match(items[0].message ?? "", /Semaphore wouldn't start it: Semaphore is having a moment/);
|
||
assert.equal((await runOf(refused.id)).status, "failed");
|
||
});
|
||
|
||
async function updateRunsCancelAll() {
|
||
await db.update(updateRuns).set({ status: "cancelled" });
|
||
}
|
||
|
||
test("a plan does not overlap itself, and one with no servers says so rather than doing nothing silently", async () => {
|
||
await reset();
|
||
await startPlanRun(planId, { trigger: "manual", actor: "Olle", now: T0 });
|
||
await assert.rejects(startPlanRun(planId, { trigger: "manual", actor: "Olle", now: T0 }), (e: unknown) => e instanceof PlanError && e.code === "already_running");
|
||
await db.update(patchPlanRuns).set({ status: "cancelled" });
|
||
|
||
await db.update(patchPlans).set({ tags: JSON.stringify(["nothing-has-this"]) }).where(eq(patchPlans.id, planId));
|
||
await assert.rejects(startPlanRun(planId, { trigger: "manual", actor: "Olle", now: T0 }), (e: unknown) => e instanceof PlanError && e.code === "no_servers");
|
||
});
|
||
|
||
test("stopping a run that is going leaves the rest alone, ends the maintenance it made and stops the update run being followed", async () => {
|
||
await reset();
|
||
const run = await startPlanRun(planId, { trigger: "manual", actor: "Olle", now: T0 });
|
||
await advancePlanRuns(T0);
|
||
const stopped = await cancelPlanRun(run.id, "Olga", at(2));
|
||
assert.equal(stopped!.status, "cancelled");
|
||
assert.deepEqual(parseItems(stopped!.items).map((i) => i.status), ["failed", "skipped", "skipped"]);
|
||
assert.equal((await listActiveWindows(at(2))).some((w) => w.targetId === ids.api), false);
|
||
assert.equal((await db.select().from(updateRuns))[0].status, "cancelled");
|
||
await assert.rejects(cancelPlanRun(run.id, "Olga", at(3)), (e: unknown) => e instanceof PlanError && e.code === "not_active");
|
||
assert.equal(await cancelPlanRun(99999, "Olga"), null);
|
||
});
|
||
|
||
test("the schedule starts a plan once on its day, and a restart of the app does not start it again", async () => {
|
||
await reset();
|
||
assert.equal(await startDuePlans(T0), 1);
|
||
const [row] = await db.select().from(patchPlans).where(eq(patchPlans.id, planId));
|
||
assert.equal(row.lastRunDate, "2026-10-18");
|
||
assert.equal((await db.select().from(patchPlanRuns))[0].trigger, "schedule");
|
||
await db.update(patchPlanRuns).set({ status: "done" });
|
||
assert.equal(await startDuePlans(at(10)), 0, "not twice in a day");
|
||
assert.equal(await startDuePlans(new Date("2026-10-25T02:03:00Z")), 1, "but the next Sunday it does");
|
||
});
|
||
|
||
test("a plan that is due but has no servers leaves a failed run to say so", async () => {
|
||
await reset({ tags: JSON.stringify(["nothing-has-this"]) });
|
||
await db.delete(patchPlanRuns);
|
||
assert.equal(await startDuePlans(T0), 0);
|
||
const [run] = await db.select().from(patchPlanRuns);
|
||
assert.deepEqual([run.status, run.trigger], ["failed", "schedule"]);
|
||
assert.match(run.message ?? "", /^Didn't start: No server has this plan's tags/);
|
||
});
|
||
});
|
||
|
||
describe("through the routes", () => {
|
||
let app: Server;
|
||
let base = "";
|
||
let who = "admin";
|
||
const body = (extra: object = {}) => ({ name: "Weekend patching", days: [6, 0], startTime: "03:30", timezone: "Europe/Stockholm", tags: ["Lab"], serverIds: [], integrationId: 9, projectId: 2, templateId: 7, templateName: "Apply updates", ...extra });
|
||
|
||
before(async () => {
|
||
await db.insert(users).values([
|
||
{ oidcSub: "admin", name: "Ada", role: "admin" },
|
||
{ oidcSub: "operator", name: "Olga", role: "operator" },
|
||
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
|
||
]);
|
||
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/patch-plans", patchPlansRouter);
|
||
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/patch-plans`;
|
||
await db.delete(patchPlans);
|
||
await db.delete(patchPlanRuns);
|
||
});
|
||
|
||
after(() => app.close());
|
||
|
||
const send = (method: string, path: string, b?: unknown) => fetch(`${base}${path}`, { method, headers: { "content-type": "application/json" }, body: b === undefined ? undefined : JSON.stringify(b) });
|
||
let id = 0;
|
||
|
||
test("an administrator makes a plan, with its tags written the way tags are; a wrong one is refused with a reason; nobody else can", async () => {
|
||
const res = await send("POST", "/", body());
|
||
assert.equal(res.status, 201);
|
||
const plan = (await res.json()).plan;
|
||
id = plan.id;
|
||
assert.deepEqual([plan.tags, plan.days, plan.limitFrom, plan.stopOnFailure, plan.onlyWithUpdates, plan.windowMinutes], [["lab"], [0, 6], "name", true, true, 90]);
|
||
assert.deepEqual(plan.servers.map((s: { name: string }) => s.name), ["api", "idle", "web"], "the three tagged lab");
|
||
assert.equal(plan.next.length, 3, "its next times, so nobody has to work out when");
|
||
for (const bad of [{ days: [] }, { startTime: "3:30" }, { timezone: "Mars/Olympus" }, { tags: [], serverIds: [] }, { tags: ["bad tag!"] }, { windowMinutes: 5 }, { name: " " }, { integrationId: 0 }]) {
|
||
const r = await send("POST", "/", body(bad));
|
||
assert.equal(r.status, 400, JSON.stringify(bad));
|
||
assert.ok((await r.json()).message.length > 0);
|
||
}
|
||
who = "operator";
|
||
assert.equal((await send("POST", "/", body())).status, 403);
|
||
assert.equal((await send("PUT", `/${id}`, body())).status, 403);
|
||
assert.equal((await send("DELETE", `/${id}`)).status, 403);
|
||
who = "viewer";
|
||
const list = await (await send("GET", "/")).json();
|
||
assert.equal(list.plans.length, 1, "everyone can see what is planned");
|
||
assert.ok(list.tags.includes("lab") && list.servers.length >= 4);
|
||
});
|
||
|
||
test("changing when it happens forgets which day it last started on; changing anything else does not", async () => {
|
||
who = "admin";
|
||
await db.update(patchPlans).set({ lastRunDate: "2026-10-18" }).where(eq(patchPlans.id, id));
|
||
await send("PUT", `/${id}`, body({ name: "Renamed" }));
|
||
assert.equal((await db.select().from(patchPlans).where(eq(patchPlans.id, id)))[0].lastRunDate, "2026-10-18");
|
||
await send("PUT", `/${id}`, body({ name: "Renamed", startTime: "04:00" }));
|
||
assert.equal((await db.select().from(patchPlans).where(eq(patchPlans.id, id)))[0].lastRunDate, null);
|
||
assert.equal((await send("PUT", "/99999", body())).status, 404);
|
||
});
|
||
|
||
test("an operator can run it now and stop it; a viewer cannot; and it cannot be removed while it is running", async () => {
|
||
who = "viewer";
|
||
assert.equal((await send("POST", `/${id}/run`)).status, 403);
|
||
who = "operator";
|
||
const res = await send("POST", `/${id}/run`);
|
||
assert.equal(res.status, 201);
|
||
const run = (await res.json()).run;
|
||
assert.equal(run.status, "running");
|
||
assert.equal(run.trigger, "manual");
|
||
assert.ok(run.items.every((i: { windowIds?: unknown }) => i.windowIds === undefined), "the windows it made are its own business");
|
||
assert.equal((await send("POST", `/${id}/run`)).status, 409, "not twice at once");
|
||
who = "admin";
|
||
assert.equal((await send("DELETE", `/${id}`)).status, 409);
|
||
who = "operator";
|
||
const stopped = await send("POST", `/runs/${run.id}/cancel`);
|
||
assert.equal(stopped.status, 200);
|
||
assert.equal((await stopped.json()).run.status, "cancelled");
|
||
assert.equal((await send("POST", `/runs/${run.id}/cancel`)).status, 409);
|
||
assert.equal((await send("POST", "/runs/99999/cancel")).status, 404);
|
||
who = "admin";
|
||
assert.equal((await send("DELETE", `/${id}`)).status, 204);
|
||
assert.equal((await db.select().from(patchPlanRuns)).length, 0, "its history goes with it");
|
||
});
|
||
});
|