Notify when a game server is turned on or off

A read of a Fragnet account that shows a server on (running or starting) after
it was off, or off (stopped or stopping) after it was on, sends one message
through the configured channels and routing rules, a line for each server.
A server first seen, one whose state is unknown and one being installed or
moved say nothing. Switch: Settings -> Notifications -> What to send (on by
default).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-10 18:56:24 +01:00
1 parent 4d653f5a80
commit 5c6ccc0a4b
10 files changed
+193 -5

No files matched your search

+46 -4
View File
@@ -6,12 +6,17 @@
* not judged), or that has none and has been known for longer than that; a server can be left out by name (`ignoreBackups`). **Disk or memory nearly full** — over `fullPercent` (90 unless you
* say otherwise) of its limit; memory is judged only while it runs. A server that is stopped is not an alert: game servers are often stopped on purpose. A panel that cannot be reached shows
* as the integration being down, like any other. "Since when" a server has been in its state is what this app saw: the time of the first read that showed it.
*
* Not an alert but a message: when a read shows a game server **turned on or off** since the read before (however it happened: someone pressed Start, it crashed, the host stopped it), one notification
* goes through the configured channels (and routing rules), with a line for each server that changed in that read. A server met for the first time says nothing; neither does one whose state could
* not be read, or that is being installed or moved; "starting" counts as on and "stopping" as off, so a start is said when it begins and not again when it has finished.
*/
import { and, eq } from "drizzle-orm";
import { db } from "../db/client.js";
import { fragnetState, integrations } from "../db/schema.js";
import { createFragnetAdapter, type FragnetRead, type FragnetServer } from "../integrations/fragnet/adapter.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { notifyGameServerPower } from "./notify.js";
import { getInternalFlag, setInternalFlag } from "./settingsStore.js";
export const SYNC_INTERVAL_MS = 5 * 60_000;
@@ -79,11 +84,40 @@ export function carryTimes(servers: FragnetServer[], previous: StoredServer[], n
});
}
/** Writes down one read, replacing the last (and carrying what was seen between reads). */
export async function storeRead(integrationId: number, r: FragnetRead, now: Date = new Date()): Promise<void> {
/** Whether a panel state means on (running, starting) or off (offline, stopping); null when it says neither (unknown: the resources could not be read). */
export function powerOf(state: string): boolean | null {
return state === "running" || state === "starting" ? true : state === "offline" || state === "stopping" ? false : null;
}
export interface PowerChange {
id: string;
name: string;
game: string | null;
on: boolean;
}
/** Pure: the servers that were turned on or off between the last read and this one. A server not seen before, one whose state is unknown before or now, and one being installed or moved are left out. */
export function powerChanges(previous: Pick<StoredServer, "id" | "state">[], current: Pick<FragnetServer, "id" | "name" | "game" | "state" | "installing" | "transferring">[]): PowerChange[] {
const before = new Map(previous.map((p) => [p.id, powerOf(p.state)]));
const out: PowerChange[] = [];
for (const s of current) {
if (s.installing || s.transferring) continue;
const was = before.get(s.id);
const now = powerOf(s.state);
if (was === undefined || was === null || now === null || was === now) continue;
out.push({ id: s.id, name: s.name, game: s.game, on: now });
}
return out.sort((a, b) => a.name.localeCompare(b.name));
}
/** Writes down one read, replacing the last (and carrying what was seen between reads). Says which servers were turned on or off since the read before. */
export async function storeRead(integrationId: number, r: FragnetRead, now: Date = new Date()): Promise<PowerChange[]> {
const [previous] = await db.select({ servers: fragnetState.servers }).from(fragnetState).where(eq(fragnetState.integrationId, integrationId)).limit(1);
const values = { servers: JSON.stringify(carryTimes(r.servers, previous ? serversOf(previous) : [], now)), updatedAt: now.toISOString() };
const before = previous ? serversOf(previous) : [];
const values = { servers: JSON.stringify(carryTimes(r.servers, before, now)), updatedAt: now.toISOString() };
await db.insert(fragnetState).values({ integrationId, ...values }).onConflictDoUpdate({ target: fragnetState.integrationId, set: values });
// An account read for the first time has nothing to compare with: nothing is said.
return previous ? powerChanges(before, r.servers) : [];
}
/** Reads one account and stores it. Never throws: how it went is the answer, and what was stored is left alone when it failed. */
@@ -93,8 +127,16 @@ export async function syncFragnet(integrationId: number, now: Date = new Date(),
const loaded = await loadIntegrationConfig(integrationId);
if (!loaded || loaded.integration.type !== "fragnet") throw new Error("not a Fragnet integration");
const result = await (read ? read(loaded.config) : createFragnetAdapter(loaded.config as never).read());
await storeRead(integrationId, result, now);
const changes = await storeRead(integrationId, result, now);
status = { at: now.toISOString(), ok: true, error: null };
// Said after it is stored and recorded as read: a message that fails to send must not make the read look failed.
if (changes.length > 0) {
try {
await notifyGameServerPower(changes.map((c) => ({ integrationName: loaded.integration.name, serverName: c.name, game: c.game, on: c.on })));
} catch (err) {
console.error("[fragnet] couldn't send the power notification:", err);
}
}
} catch (err) {
const previous = (await readStatuses())[String(integrationId)];
status = { at: previous?.at ?? now.toISOString(), ok: false, error: err instanceof Error ? err.message : String(err) };
+10
View File
@@ -535,6 +535,16 @@ export async function notifyUpdateRunFinished(run: { serverName: string; templat
);
}
/** A game server was turned on or off: one message for what changed in one read, a line for each. Held for quiet hours like the rest (it is not critical). */
export async function notifyGameServerPower(changes: { integrationName: string; serverName: string; game: string | null; on: boolean }[]): Promise<void> {
if (changes.length === 0) return;
if (!(await eventEnabled("gameServerPower"))) return;
const ons = changes.filter((c) => c.on).length;
const title = ons === changes.length ? (changes.length === 1 ? `Homelab Manager — ${changes[0].serverName} turned on` : "Homelab Manager — Game servers turned on") : ons === 0 ? (changes.length === 1 ? `Homelab Manager — ${changes[0].serverName} turned off` : "Homelab Manager — Game servers turned off") : "Homelab Manager — Game servers turned on or off";
const lines = changes.map((c) => `${c.serverName}${c.game ? ` (${c.game})` : ""} [${c.integrationName}]: now ${c.on ? "on" : "off"}`);
await notify(title, lines.join("\n"), { category: "services", severity: "warning" });
}
/** How a patch plan's run ended: one message, with a line for each server. Held back or sent with the other update-run results. */
export async function notifyPatchPlanFinished(run: { planName: string; ok: boolean; message: string; lines: string[] }): Promise<void> {
if (!(await eventEnabled("updateRunResults"))) return;
+3
View File
@@ -82,6 +82,8 @@ export interface NotificationEvents {
automationAlerts: boolean;
/** How an update run started from the Updates page ended: what is still waiting, whether a restart is due, or why it failed. */
updateRunResults: boolean;
/** A game server (Fragnet) was turned on or off: said once, when the app sees it change between two reads. */
gameServerPower: boolean;
/** Daily reminder while a domain registration is close to expiring or has expired. */
domainExpiryCheck: boolean;
secretCheckTime: string; // "HH:MM" — shared by the secret-expiry, Tailscale key-expiry, Docker update, and Proxmox backup checks
@@ -348,6 +350,7 @@ const DEFAULTS: AppSettings = {
healthAlerts: true,
automationAlerts: true,
updateRunResults: true,
gameServerPower: true,
domainExpiryCheck: true,
secretCheckTime: "08:00",
timezone: "UTC",