Event webhooks: game_server.started and game_server.stopped

Sent for every Fragnet game server seen turned on or off, whatever the notification switch says, with the server, game, account and, when a power signal sent from here caused it, which signal and who sent it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-14 22:59:40 +01:00
1 parent 2986734196
commit 25183c0320
10 files changed
+127 -9

No files matched your search

+1 -1
View File
@@ -1943,7 +1943,7 @@ export const apiTokens = sqliteTable("api_tokens", {
// ─── Event webhooks: tell another system when something happens ─────────────
export const webhookEvents = ["alert.opened", "alert.resolved", "maintenance.started", "maintenance.ended"] as const;
export const webhookEvents = ["alert.opened", "alert.resolved", "maintenance.started", "maintenance.ended", "game_server.started", "game_server.stopped"] as const;
export type WebhookEvent = (typeof webhookEvents)[number];
// A URL that gets a signed JSON message for the events it subscribes to — for Home Assistant, n8n, a status board. Separate from the
+2
View File
@@ -6,6 +6,8 @@
* alert.opened / alert.resolved a problem began or ended — on the same terms as a notification (a problem under maintenance,
* or folded under another, isn't announced until it stands alone)
* maintenance.started / .ended a maintenance window began or finished, however it was made
* game_server.started / .stopped a Fragnet game server was seen turned on or off (services/fragnetSync.ts) — whatever the notification
* switch for it says, and whoever or whatever did it
*
* Delivery is best-effort and never holds anything up: one try, one more if that fails, then the result is noted on the webhook (shown in
* Settings) and forgotten.
+5 -1
View File
@@ -63,7 +63,9 @@ export async function recordRead(
current: { id: string; name: string; on: boolean | null }[],
changes: { id: string; name: string; on: boolean }[],
now: Date = new Date(),
): Promise<void> {
): Promise<Map<string, { signal: string | null; by: string | null }>> {
/** For each change: the signal sent from here it was put down to, and who sent it (both null when nothing was sent from here). */
const attributed = new Map<string, { signal: string | null; by: string | null }>();
try {
const at = now.toISOString();
const known = new Set((await db.select({ id: fragnetPowerLog.serverId }).from(fragnetPowerLog).where(and(eq(fragnetPowerLog.integrationId, integrationId), inArray(fragnetPowerLog.kind, ["on", "off", "start_on", "start_off"]))).groupBy(fragnetPowerLog.serverId)).map((r) => r.id));
@@ -78,6 +80,7 @@ export async function recordRead(
.orderBy(desc(fragnetPowerLog.at), desc(fragnetPowerLog.id))
).find((s) => signalGoesOn(s.detail ?? "") === c.on);
rows.push({ integrationId, serverId: c.id, serverName: c.name, at, kind: c.on ? "on" : "off", detail: signal?.detail ?? null, by: signal?.by ?? null });
attributed.set(c.id, { signal: signal?.detail ?? null, by: signal?.by ?? null });
}
// A server read for the first time is how it is: a starting point for what follows.
for (const s of current) if (s.on !== null && !known.has(s.id) && !changed.has(s.id)) rows.push({ integrationId, serverId: s.id, serverName: s.name, at, kind: s.on ? "start_on" : "start_off", detail: null, by: null });
@@ -88,6 +91,7 @@ export async function recordRead(
} catch (err) {
console.error("[fragnetPower] couldn't write the read down:", err instanceof Error ? err.message : err);
}
return attributed;
}
// ─── What it says ───────────────────────────────────────────────────────────
+14 -3
View File
@@ -17,6 +17,7 @@ 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 { emitEvent } from "./eventWebhooks.js";
import { recordRead } from "./fragnetPower.js";
import { getInternalFlag, setInternalFlag } from "./settingsStore.js";
@@ -111,8 +112,16 @@ export function powerChanges(previous: Pick<StoredServer, "id" | "state">[], cur
return out.sort((a, b) => a.name.localeCompare(b.name));
}
/**
* Pure: what an event webhook is told of one change. `signal` and `by` are set when the change followed a power signal sent from here (so a receiver that sent it can tell its own doing);
* both are null for one made in the panel or on the server itself. `at` is when the read saw it, to the nearest five minutes.
*/
export function gameServerEvent(integration: { id: number; name: string }, c: PowerChange & { signal: string | null; by: string | null }, now: Date) {
return { id: c.id, name: c.name, game: c.game, integrationId: integration.id, integrationName: integration.name, on: c.on, at: now.toISOString(), signal: c.signal, by: c.by };
}
/** 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[]> {
export async function storeRead(integrationId: number, r: FragnetRead, now: Date = new Date()): Promise<(PowerChange & { signal: string | null; by: string | null })[]> {
const [previous] = await db.select({ servers: fragnetState.servers }).from(fragnetState).where(eq(fragnetState.integrationId, integrationId)).limit(1);
const before = previous ? serversOf(previous) : [];
const values = { servers: JSON.stringify(carryTimes(r.servers, before, now)), updatedAt: now.toISOString() };
@@ -120,8 +129,8 @@ export async function storeRead(integrationId: number, r: FragnetRead, now: Date
// An account read for the first time has nothing to compare with: nothing is said.
const changes = previous ? powerChanges(before, r.servers) : [];
// Written down for the history (and a starting point for each server read for the first time).
await recordRead(integrationId, r.servers.map((s) => ({ id: s.id, name: s.name, on: s.installing || s.transferring ? null : powerOf(s.state) })), changes, now);
return changes;
const attributed = await recordRead(integrationId, r.servers.map((s) => ({ id: s.id, name: s.name, on: s.installing || s.transferring ? null : powerOf(s.state) })), changes, now);
return changes.map((c) => ({ ...c, signal: attributed.get(c.id)?.signal ?? null, by: attributed.get(c.id)?.by ?? null }));
}
/** Reads one account and stores it. Never throws: how it went is the answer, and what was stored is left alone when it failed. */
@@ -134,6 +143,8 @@ export async function syncFragnet(integrationId: number, now: Date = new Date(),
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.
// The event webhooks hear of every change, whatever the notification switch for game servers says: they are a separate way of being told.
for (const c of changes) emitEvent(c.on ? "game_server.started" : "game_server.stopped", { gameServer: gameServerEvent(loaded.integration, c, now) });
if (changes.length > 0) {
try {
await notifyGameServerPower(changes.map((c) => ({ integrationName: loaded.integration.name, serverName: c.name, game: c.game, on: c.on })));
+93 -1
View File
@@ -20,7 +20,7 @@ process.env.HEALTH_STARTUP_GRACE_MS = "0";
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, integrations, fragnetState, fragnetPowerLog, auditLog } = await import("../src/db/schema.js");
const { users, integrations, fragnetState, fragnetPowerLog, auditLog, eventWebhooks } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const adapter = await import("../src/integrations/fragnet/adapter.js");
const fn = await import("../src/services/fragnetSync.js");
@@ -564,6 +564,98 @@ describe("a game server turned on or off", () => {
assert.equal(status.ok, true, "the read counts as done whatever happened to the message");
});
});
describe("the event webhooks", () => {
let id = 0;
let hook: Server;
let hookId = 0;
const got: { event: string; data: { gameServer: Record<string, unknown> } }[] = [];
before(async () => {
hook = createHttpServer((req, res) => {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
got.push(JSON.parse(body));
res.writeHead(200).end("ok");
});
});
await new Promise<void>((resolve) => hook.listen(0, "127.0.0.1", resolve));
const url = `http://127.0.0.1:${(hook.address() as AddressInfo).port}/hook`;
hookId = (await db.insert(eventWebhooks).values({ label: "Home Assistant", url, events: JSON.stringify(["game_server.started", "game_server.stopped"]) }).returning({ id: eventWebhooks.id }))[0].id;
id = (await db.insert(integrations).values({ type: "fragnet", name: "Fragnet account", baseUrl: "https://panel.fragnet.net", config: JSON.stringify({}) }).returning({ id: integrations.id }))[0].id;
});
after(async () => {
hook.close();
await db.delete(eventWebhooks).where(eq(eventWebhooks.id, hookId));
await updateSettings({ notifications: { gameServerPower: true } });
await fn.forgetFragnet(id);
await db.delete(integrations).where(eq(integrations.id, id));
});
const sync = (...servers: Srv[]) => fn.syncFragnet(id, new Date(), async () => read(...servers));
const heard = async (n: number) => {
for (let t = 0; t < 3000 && got.length < n; t += 25) await new Promise((r) => setTimeout(r, 25));
await new Promise((r) => setTimeout(r, 100));
};
test("a server turned off is game_server.stopped and turned on is game_server.started, with the server, the game and the account", async () => {
await sync(server({ state: "running" }));
await new Promise((r) => setTimeout(r, 150));
assert.equal(got.length, 0, "the first read says nothing");
await sync(server({ state: "offline" }));
await heard(1);
assert.equal(got.length, 1);
assert.equal(got[0].event, "game_server.stopped");
assert.deepEqual({ ...got[0].data.gameServer, at: "x" }, { id: "abcd1234", name: "survival", game: "Minecraft: Paper", integrationId: id, integrationName: "Fragnet account", on: false, at: "x", signal: null, by: null });
await sync(server({ state: "starting" }));
await heard(2);
assert.equal(got[1].event, "game_server.started");
assert.equal(got[1].data.gameServer.on, true);
await sync(server({ state: "running" }));
await new Promise((r) => setTimeout(r, 150));
assert.equal(got.length, 2, "the start finishing is not another change");
});
test("each server that changed is its own event", async () => {
await sync(server({ id: "aaaa1111", name: "ark", state: "running" }), server({ id: "bbbb2222", name: "rust", state: "offline" }));
got.length = 0;
await sync(server({ id: "aaaa1111", name: "ark", state: "offline" }), server({ id: "bbbb2222", name: "rust", state: "running" }));
await heard(2);
assert.deepEqual(got.map((g) => [g.event, g.data.gameServer.name]).sort(), [["game_server.started", "rust"], ["game_server.stopped", "ark"]]);
});
test("they hear of it whatever the notification switch says, and a change made by a signal sent from here says who sent it", async () => {
await updateSettings({ notifications: { gameServerPower: false } });
const { recordSignal } = await import("../src/services/fragnetPower.js");
await sync(server({ id: "aaaa1111", name: "ark", state: "offline" }), server({ id: "bbbb2222", name: "rust", state: "running" }));
got.length = 0;
await recordSignal(id, { id: "aaaa1111", name: "ark" }, "start", "Ada");
await sync(server({ id: "aaaa1111", name: "ark", state: "starting" }), server({ id: "bbbb2222", name: "rust", state: "running" }));
await heard(1);
assert.equal(got.length, 1);
assert.equal(got[0].event, "game_server.started");
assert.equal(got[0].data.gameServer.signal, "start");
assert.equal(got[0].data.gameServer.by, "Ada");
});
test("an unchanged server or a failed read sends nothing, and a webhook that did not ask for them hears nothing", async () => {
got.length = 0;
await sync(server({ id: "aaaa1111", name: "ark", state: "starting" }), server({ id: "bbbb2222", name: "rust", state: "running" }));
await fn.syncFragnet(id, new Date(), async () => {
throw new Error("panel down");
});
await db.update(eventWebhooks).set({ events: JSON.stringify(["alert.opened"]) }).where(eq(eventWebhooks.id, hookId));
await sync(server({ id: "aaaa1111", name: "ark", state: "offline" }), server({ id: "bbbb2222", name: "rust", state: "running" }));
await new Promise((r) => setTimeout(r, 300));
assert.equal(got.length, 0);
});
test("they are two of the events a webhook can ask for", async () => {
const { webhookEvents } = await import("../src/db/schema.js");
assert.ok(webhookEvents.includes("game_server.started") && webhookEvents.includes("game_server.stopped"));
const { parseEvents } = await import("../src/services/eventWebhooks.js");
assert.deepEqual(parseEvents(JSON.stringify(["game_server.started", "nonsense"])), ["game_server.started"]);
});
});
});
describe("the health pass, the page, the power signals and /metrics", () => {