/** * Turns maintenance windows beginning and ending into events, whatever made the window — by hand, in bulk, from a recurring schedule or * mirrored from Uptime Kuma, and whether it ended on its own or was ended early. It simply watches which windows are running: one that * wasn't a moment ago is "started", one that was and isn't now is "ended". After a restart it starts from what is running then, so nothing * is announced twice or announced for a window that began before. */ import { listActiveWindows, describeTarget, type ActiveWindow } from "./maintenance.js"; import { emitEvent } from "./eventWebhooks.js"; const INTERVAL_MS = 30_000; let known: Map | null = null; let timer: ReturnType | null = null; async function describe(w: ActiveWindow) { const target = await describeTarget(w.targetType, w.targetId); return { id: w.id, targetType: w.targetType, targetId: w.targetId, targetName: target?.name ?? null, reason: w.reason, startedAt: w.startedAt, endsAt: w.endsAt, source: w.source }; } /** One look. Returns what it announced, for the tests. */ export async function checkMaintenanceEvents(now: Date = new Date()): Promise<{ started: number[]; ended: number[] }> { const active = new Map((await listActiveWindows(now)).map((w) => [w.id, w])); const started: number[] = []; const ended: number[] = []; if (known !== null) { for (const [id, w] of active) { if (!known.has(id)) { started.push(id); emitEvent("maintenance.started", { window: await describe(w) }); } } for (const [id, w] of known) { if (!active.has(id)) { ended.push(id); // The window as it was last seen (one ended early has had its end brought forward since), and when it was noticed to be over. emitEvent("maintenance.ended", { window: { ...(await describe(w)), endedAt: now.toISOString() } }); } } } known = active; return { started, ended }; } /** For tests: forget what was running, so the next look is a first look. */ export function resetMaintenanceEventsForTests(): void { known = null; } export function initMaintenanceEvents(): void { if (timer) return; void checkMaintenanceEvents().catch((err) => console.error("[maintenanceEvents]", err)); timer = setInterval(() => void checkMaintenanceEvents().catch((err) => console.error("[maintenanceEvents]", err)), INTERVAL_MS); }