Add a power history to each game server

Each change a read of a Fragnet account sees, and each power signal sent from
here with who sent it, is written down (180 days). A server's details show the
share of the last 30 days it was on, starts and stops, a seven-day bar and the
latest changes, with who asked for them.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-10 19:30:27 +01:00
1 parent 9126200295
commit a2b43bcd5d
14 files changed
+9773 -4

No files matched your search

+19
View File
@@ -1662,6 +1662,25 @@ export const jellyfinReadings = sqliteTable(
// ─── Duplicati ──────────────────────────────────────────────────────────────
// A game server's power history (services/fragnetPower.ts): each change a read of a Fragnet account saw (on or off), the starting point of a server when it was first read, and each power signal somebody sent
// from here — with who, so a change can say who did it. Kept 180 days.
export const fragnetPowerLog = sqliteTable(
"fragnet_power_log",
{
id: integer("id").primaryKey({ autoIncrement: true }),
integrationId: integer("integration_id")
.notNull()
.references(() => integrations.id, { onDelete: "cascade" }),
serverId: text("server_id").notNull(), // the panel's short id for the server
serverName: text("server_name").notNull(),
at: text("at").notNull(), // ISO
kind: text("kind").notNull(), // on | off | start_on | start_off | signal
detail: text("detail"), // the signal (start, stop, restart, kill)
by: text("by"), // who sent the signal
},
(t) => [index("fragnet_power_log_idx").on(t.integrationId, t.serverId, t.at)],
);
// What was sent: one row for each notification, with how it went through each channel, so "why did I not get it?" has an answer. Kept 30 days and at most 1000 rows (services/notificationLog.ts).
export const notificationLog = sqliteTable(
"notification_log",
+5 -1
View File
@@ -8,6 +8,7 @@ import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { recordAudit } from "../services/audit.js";
import { invalidateAlertsCache } from "../services/alerts.js";
import { fragnetProblems, fragnetSyncStatuses, isFragnetFresh, newestBackup, optionsOf, serversOf, syncFragnet } from "../services/fragnetSync.js";
import { powerOfAccount, recordSignal } from "../services/fragnetPower.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const fragnetRouter = Router();
@@ -34,6 +35,7 @@ fragnetRouter.get("/", asyncHandler(async (_req, res) => {
} catch {
// a config that cannot be read costs only the settings it holds
}
const power = await powerOfAccount(r.id, now);
accounts.push({
id: r.id,
name: r.name,
@@ -42,7 +44,7 @@ fragnetRouter.get("/", asyncHandler(async (_req, res) => {
status,
fresh,
options,
state: state ? { servers: stored.map((s) => ({ ...s, newestBackup: newestBackup(s) })), updatedAt: state.updatedAt } : null,
state: state ? { servers: stored.map((s) => ({ ...s, newestBackup: newestBackup(s), power: power[s.id] ?? null })), updatedAt: state.updatedAt } : null,
problems: state && fresh ? fragnetProblems(r.id, r.name, stored, now, options) : [],
});
}
@@ -136,6 +138,8 @@ fragnetRouter.post("/:id/servers/:server/power", requireRole("operator"), asyncH
} catch (err) {
return res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
}
// So the change that follows can say who asked for it.
await recordSignal(id, server, signal, req.currentUser?.name ?? req.currentUser?.email ?? null);
await recordAudit({
actor: req.currentUser!,
category: "integration",
+188
View File
@@ -0,0 +1,188 @@
/**
* A game server's power history: each time a read of a Fragnet account shows a server turned on or off (services/fragnetSync.ts) it is written down, and so is each power signal somebody sent from
* here, so a change can say who did it. From that: how much of the last 30 days a server was on, how many times it was started, a timeline of the last seven days, and the latest events.
*
* It is what this app *saw*: the accounts are read every five minutes, so every time is to the nearest five minutes, and nothing is known of the time before a server was first read (the first
* read of a server writes a starting point, which is not itself a start or a stop). Kept 180 days.
*/
import { and, desc, eq, gte, inArray, lt, notInArray } from "drizzle-orm";
import { db } from "../db/client.js";
import { fragnetPowerLog } from "../db/schema.js";
export const KEEP_DAYS = 180;
export const KEEP_ROWS = 3000;
/** A change is put down to a signal sent from here when the signal was sent no longer than this before the read that showed it. */
export const ATTRIBUTE_WITHIN_MS = 20 * 60_000;
const DAY = 86_400_000;
/** on, off: a change that was seen. start_on, start_off: how the server was when it was first read (a starting point, not a change). signal: somebody sent a power signal from here. */
export type PowerEventKind = "on" | "off" | "start_on" | "start_off" | "signal";
export interface PowerEvent {
at: string;
kind: PowerEventKind;
/** For a signal: which one (start, stop, restart, kill). For a change put down to a signal: the signal. */
detail: string | null;
/** Who sent the signal. */
by: string | null;
}
export type LogRow = typeof fragnetPowerLog.$inferSelect;
const isOn = (k: PowerEventKind) => k === "on" || k === "start_on";
const isState = (k: PowerEventKind) => k !== "signal";
/** Pure: whether a signal makes a server go on (start, restart) or off (stop, kill). */
export const signalGoesOn = (signal: string): boolean => signal === "start" || signal === "restart";
let sinceTrim = 0;
async function trim(integrationId: number, now: Date): Promise<void> {
await db.delete(fragnetPowerLog).where(and(eq(fragnetPowerLog.integrationId, integrationId), lt(fragnetPowerLog.at, new Date(now.getTime() - KEEP_DAYS * DAY).toISOString())));
if (++sinceTrim < 50) return;
sinceTrim = 0;
const keep = await db.select({ id: fragnetPowerLog.id }).from(fragnetPowerLog).where(eq(fragnetPowerLog.integrationId, integrationId)).orderBy(desc(fragnetPowerLog.at), desc(fragnetPowerLog.id)).limit(KEEP_ROWS);
if (keep.length === KEEP_ROWS) await db.delete(fragnetPowerLog).where(and(eq(fragnetPowerLog.integrationId, integrationId), notInArray(fragnetPowerLog.id, keep.map((k) => k.id))));
}
/** Writes down that somebody sent a power signal from here. Never throws: the history is not worth failing a power button for. */
export async function recordSignal(integrationId: number, server: { id: string; name: string }, signal: string, by: string | null, now: Date = new Date()): Promise<void> {
try {
await db.insert(fragnetPowerLog).values({ integrationId, serverId: server.id, serverName: server.name, at: now.toISOString(), kind: "signal", detail: signal, by });
await trim(integrationId, now);
} catch (err) {
console.error("[fragnetPower] couldn't write the signal down:", err instanceof Error ? err.message : err);
}
}
/**
* Writes down one read: each change since the last (put down to the signal sent shortly before it, if there was one), and a starting point for every server that has none yet. Never throws.
* `current` is every server as this read found it, `changes` the ones that were turned on or off.
*/
export async function recordRead(
integrationId: number,
current: { id: string; name: string; on: boolean | null }[],
changes: { id: string; name: string; on: boolean }[],
now: Date = new Date(),
): Promise<void> {
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));
const changed = new Set(changes.map((c) => c.id));
const rows: (typeof fragnetPowerLog.$inferInsert)[] = [];
for (const c of changes) {
const signal = (
await db
.select()
.from(fragnetPowerLog)
.where(and(eq(fragnetPowerLog.integrationId, integrationId), eq(fragnetPowerLog.serverId, c.id), eq(fragnetPowerLog.kind, "signal"), gte(fragnetPowerLog.at, new Date(now.getTime() - ATTRIBUTE_WITHIN_MS).toISOString())))
.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 });
}
// 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 });
if (rows.length > 0) {
await db.insert(fragnetPowerLog).values(rows);
await trim(integrationId, now);
}
} catch (err) {
console.error("[fragnetPower] couldn't write the read down:", err instanceof Error ? err.message : err);
}
}
// ─── What it says ───────────────────────────────────────────────────────────
export interface PowerStats {
/** When this app first saw the server (the start of what is known of it). */
trackedSince: string;
/** The share of the time it could see (at most the window) that the server was on; null while that is under an hour. */
onPercent: number | null;
/** How long the span the percentage is of is, in ms. */
spanMs: number;
starts: number;
stops: number;
lastOnAt: string | null;
lastOffAt: string | null;
/** How the last event left it. */
on: boolean;
}
export interface TimelineSegment {
from: string;
to: string;
on: boolean;
}
/** Pure: the state events of one server, oldest first, as a series of [from, to, on] stretches between `from` and `to` (the part before the first event is not known and is left out). */
function stretches(events: PowerEvent[], fromMs: number, toMs: number): { from: number; to: number; on: boolean }[] {
const states = events.filter((e) => isState(e.kind));
if (states.length === 0 || toMs <= fromMs) return [];
const out: { from: number; to: number; on: boolean }[] = [];
for (let i = 0; i < states.length; i++) {
const start = Date.parse(states[i].at);
const end = i + 1 < states.length ? Date.parse(states[i + 1].at) : toMs;
const a = Math.max(start, fromMs);
const b = Math.min(end, toMs);
if (b > a) out.push({ from: a, to: b, on: isOn(states[i].kind) });
}
return out;
}
/** Pure: how a server did over the last `windowDays` days, from its events (any order). Null when nothing is known of it. */
export function powerStats(events: PowerEvent[], nowMs: number, windowDays = 30): PowerStats | null {
const states = events.filter((e) => isState(e.kind)).sort((a, b) => a.at.localeCompare(b.at));
if (states.length === 0) return null;
const trackedMs = Date.parse(states[0].at);
const fromMs = Math.max(nowMs - windowDays * DAY, trackedMs);
const parts = stretches(states, fromMs, nowMs);
const spanMs = nowMs - fromMs;
const onMs = parts.filter((p) => p.on).reduce((n, p) => n + (p.to - p.from), 0);
const inWindow = states.filter((e) => Date.parse(e.at) >= fromMs && Date.parse(e.at) <= nowMs);
const last = (kind: "on" | "off") => [...states].reverse().find((e) => e.kind === kind)?.at ?? null;
return {
trackedSince: states[0].at,
onPercent: spanMs >= 3_600_000 ? Math.round((onMs / spanMs) * 1000) / 10 : null,
spanMs,
starts: inWindow.filter((e) => e.kind === "on").length,
stops: inWindow.filter((e) => e.kind === "off").length,
lastOnAt: last("on"),
lastOffAt: last("off"),
on: isOn(states[states.length - 1].kind),
};
}
/** Pure: the last `days` days as stretches of on and off, for a bar; `from` is where the bar starts (later than `days` ago when less than that is known). */
export function powerTimeline(events: PowerEvent[], nowMs: number, days = 7): { from: string; to: string; segments: TimelineSegment[] } | null {
const states = events.filter((e) => isState(e.kind)).sort((a, b) => a.at.localeCompare(b.at));
if (states.length === 0) return null;
const fromMs = Math.max(nowMs - days * DAY, Date.parse(states[0].at));
return { from: new Date(fromMs).toISOString(), to: new Date(nowMs).toISOString(), segments: stretches(states, fromMs, nowMs).map((p) => ({ from: new Date(p.from).toISOString(), to: new Date(p.to).toISOString(), on: p.on })) };
}
/** Pure: the latest events to show, newest first: changes and signals, not the starting point. */
export function recentEvents(events: PowerEvent[], limit = 15): PowerEvent[] {
return events
.filter((e) => e.kind === "on" || e.kind === "off" || e.kind === "signal")
.sort((a, b) => b.at.localeCompare(a.at))
.slice(0, limit);
}
export interface ServerPower {
stats: PowerStats | null;
timeline: ReturnType<typeof powerTimeline>;
recent: PowerEvent[];
}
/** The history of every server of one account, by the panel's id for the server: what the page shows. */
export async function powerOfAccount(integrationId: number, nowMs: number = Date.now()): Promise<Record<string, ServerPower>> {
const rows = await db.select().from(fragnetPowerLog).where(eq(fragnetPowerLog.integrationId, integrationId)).orderBy(fragnetPowerLog.at, fragnetPowerLog.id);
const by = new Map<string, PowerEvent[]>();
for (const r of rows) {
const list = by.get(r.serverId) ?? [];
list.push({ at: r.at, kind: r.kind as PowerEventKind, detail: r.detail, by: r.by });
by.set(r.serverId, list);
}
const out: Record<string, ServerPower> = {};
for (const [id, events] of by) out[id] = { stats: powerStats(events, nowMs), timeline: powerTimeline(events, nowMs), recent: recentEvents(events) };
return out;
}
+5 -1
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 { recordRead } from "./fragnetPower.js";
import { getInternalFlag, setInternalFlag } from "./settingsStore.js";
export const SYNC_INTERVAL_MS = 5 * 60_000;
@@ -117,7 +118,10 @@ export async function storeRead(integrationId: number, r: FragnetRead, now: Date
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) : [];
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;
}
/** Reads one account and stores it. Never throws: how it went is the answer, and what was stored is left alone when it failed. */