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

+13
View File
@@ -0,0 +1,13 @@
CREATE TABLE `fragnet_power_log` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`integration_id` integer NOT NULL,
`server_id` text NOT NULL,
`server_name` text NOT NULL,
`at` text NOT NULL,
`kind` text NOT NULL,
`detail` text,
`by` text,
FOREIGN KEY (`integration_id`) REFERENCES `integrations`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE INDEX `fragnet_power_log_idx` ON `fragnet_power_log` (`integration_id`,`server_id`,`at`);
File diff suppressed because it is too large. Load diff
+7
View File
@@ -638,6 +638,13 @@
"when": 1794333852784,
"tag": "0090_watery_mathemanic",
"breakpoints": true
},
{
"idx": 91,
"version": "6",
"when": 1794334785852,
"tag": "0091_adorable_wasp",
"breakpoints": true
}
]
}
+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. */
+9 -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, auditLog } = await import("../src/db/schema.js");
const { users, integrations, fragnetState, fragnetPowerLog, auditLog } = 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");
@@ -669,6 +669,14 @@ describe("the health pass, the page, the power signals and /metrics", () => {
const [entry] = (await db.select().from(auditLog)).filter((e) => e.action === "restart_game_server");
assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "fragnet_server", "abcd1234"]);
assert.match(entry.detail ?? "", /survival/);
// and who asked, for the history
const sent = (await db.select().from(fragnetPowerLog).where(eq(fragnetPowerLog.integrationId, fgId))).filter((r) => r.kind === "signal");
assert.deepEqual(sent.map((r) => [r.serverId, r.detail, r.by]), [["abcd1234", "restart", "Olle"]]);
const page = (await (await fetch(base, as("viewer"))).json()) as { accounts: { id: number; state: { servers: { id: string; power: { stats: { on: boolean; trackedSince: string } | null; timeline: { segments: unknown[] } | null; recent: { kind: string; by: string | null }[] } | null }[] } }[] };
const power = page.accounts.find((a) => a.id === fgId)!.state.servers.find((x) => x.id === "abcd1234")!.power!;
assert.equal(power.stats?.on, true);
assert.ok((power.timeline?.segments.length ?? 0) >= 1);
assert.deepEqual(power.recent.map((e) => [e.kind, e.by]), [["signal", "Olle"]]);
});
test("only a server the last read found, and only a real signal, are accepted — nothing typed in the address reaches the panel", async () => {
+212
View File
@@ -0,0 +1,212 @@
/**
* A game server's power history: what is written down when a read shows it turned on or off (and who asked, when it was done from here), how much of the last 30 days it was on,
* the seven-day timeline, and the latest events — all of it to the nearest five minutes, which is how often the account is read.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const dir = mkdtempSync(join(tmpdir(), "hm-power-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
const { db } = await import("../src/db/client.js");
const { integrations, fragnetPowerLog } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const p = await import("../src/services/fragnetPower.js");
const fn = await import("../src/services/fragnetSync.js");
const { eq } = await import("drizzle-orm");
const g = await import("../../web/src/utils/gamePower.js");
await runMigrations();
const MIN = 60_000;
const HOUR = 60 * MIN;
const DAY = 24 * HOUR;
const NOW = Date.parse("2026-11-10T12:00:00Z");
const iso = (ms: number) => new Date(ms).toISOString();
type Ev = import("../src/services/fragnetPower.js").PowerEvent;
const ev = (agoMs: number, kind: Ev["kind"], extra: Partial<Ev> = {}): Ev => ({ at: iso(NOW - agoMs), kind, detail: null, by: null, ...extra });
describe("how much it was on", () => {
test("nothing known says nothing; a server that is only known to be on has been on all the time it could be seen", () => {
assert.equal(p.powerStats([], NOW), null);
const s = p.powerStats([ev(10 * DAY, "start_on")], NOW)!;
assert.deepEqual([s.onPercent, s.starts, s.stops, s.on, s.lastOnAt, s.lastOffAt], [100, 0, 0, true, null, null], "a starting point is not a start");
assert.equal(s.trackedSince, iso(NOW - 10 * DAY));
});
test("the share of the time it could be seen that it was on, from the stretches between the changes", () => {
// off for 2 days, on for 4, off for 4: on 4 of 10 days
const s = p.powerStats([ev(10 * DAY, "start_off"), ev(8 * DAY, "on"), ev(4 * DAY, "off")], NOW)!;
assert.deepEqual([s.onPercent, s.starts, s.stops, s.on], [40, 1, 1, false]);
assert.deepEqual([s.lastOnAt, s.lastOffAt], [iso(NOW - 8 * DAY), iso(NOW - 4 * DAY)]);
});
test("only the last 30 days count, and what was known before them sets how it began", () => {
// known for 40 days: on, turned off 5 days ago: on for 25 of the last 30
const s = p.powerStats([ev(40 * DAY, "start_on"), ev(5 * DAY, "off")], NOW)!;
assert.equal(s.onPercent, 83.3);
assert.equal(s.spanMs, 30 * DAY);
// a start 35 days ago is not one of the last 30 days'
const old = p.powerStats([ev(40 * DAY, "start_off"), ev(35 * DAY, "on"), ev(20 * DAY, "off"), ev(10 * DAY, "on")], NOW)!;
assert.deepEqual([old.starts, old.stops], [1, 1]);
});
test("under an hour of history gives no percentage, and signals are not changes", () => {
assert.equal(p.powerStats([ev(30 * MIN, "start_on")], NOW)!.onPercent, null);
const s = p.powerStats([ev(2 * DAY, "start_on"), ev(DAY, "signal", { detail: "stop", by: "Ada" })], NOW)!;
assert.deepEqual([s.onPercent, s.stops, s.on], [100, 0, true]);
});
test("the events may come in any order", () => {
const a = p.powerStats([ev(10 * DAY, "start_off"), ev(8 * DAY, "on"), ev(4 * DAY, "off")], NOW);
const b = p.powerStats([ev(4 * DAY, "off"), ev(10 * DAY, "start_off"), ev(8 * DAY, "on")], NOW);
assert.deepEqual(b, a);
});
});
describe("the timeline", () => {
test("none without history; otherwise stretches from where it is known to now, in order and without gaps", () => {
assert.equal(p.powerTimeline([], NOW), null);
const t = p.powerTimeline([ev(3 * DAY, "start_on"), ev(2 * DAY, "off"), ev(DAY, "on")], NOW)!;
assert.deepEqual(t.segments.map((s) => s.on), [true, false, true]);
assert.equal(t.from, iso(NOW - 3 * DAY), "it starts where the server was first seen, not seven days ago");
for (let i = 1; i < t.segments.length; i++) assert.equal(t.segments[i].from, t.segments[i - 1].to);
assert.equal(t.segments.at(-1)!.to, iso(NOW));
});
test("a long history is cut at seven days, the stretch crossing the edge shortened", () => {
const t = p.powerTimeline([ev(20 * DAY, "start_on"), ev(3 * DAY, "off")], NOW)!;
assert.equal(t.from, iso(NOW - 7 * DAY));
assert.deepEqual(t.segments.map((s) => [s.on, s.from]), [[true, iso(NOW - 7 * DAY)], [false, iso(NOW - 3 * DAY)]]);
});
});
describe("the latest events", () => {
test("newest first, changes and signals, never the starting point; cut at the limit", () => {
const list = [ev(5 * DAY, "start_on"), ev(4 * DAY, "off"), ev(3 * DAY, "signal", { detail: "start", by: "Ada" }), ev(2 * DAY, "on", { detail: "start", by: "Ada" })];
assert.deepEqual(p.recentEvents(list).map((e) => e.kind), ["on", "signal", "off"]);
assert.equal(p.recentEvents(list, 2).length, 2);
});
test("a signal makes a server go on if it starts it and off if it stops it", () => {
assert.deepEqual(["start", "restart", "stop", "kill", "other"].map(p.signalGoesOn), [true, true, false, false, false]);
});
});
describe("how the page says it", () => {
test("how long, in the biggest sensible unit", () => {
assert.deepEqual([30 * DAY, 6 * DAY, 3 * HOUR, 90 * MIN, 20 * MIN, 10_000].map(g.spanText), ["30 days", "6 days", "3 hours", "90 minutes", "20 minutes", "1 minute"]);
assert.equal(g.spanText(2 * DAY), "2 days");
});
test("the headline is of the last 30 days when that is known, and of what has been watched when not; none for under an hour", () => {
assert.equal(g.onHeadline({ onPercent: 94.3, spanMs: 30 * DAY }), "On 94.3% of the last 30 days");
assert.equal(g.onHeadline({ onPercent: 100, spanMs: 30 * DAY }), "On 100% of the last 30 days");
assert.equal(g.onHeadline({ onPercent: 40, spanMs: 6 * DAY }), "On 40% of the 6 days it has been watched");
assert.equal(g.onHeadline({ onPercent: null, spanMs: 20 * MIN }), null);
});
test("an event: turned on or off, with who and what when it was done from here; a signal says who sent it", () => {
assert.equal(g.eventText({ kind: "on", detail: null, by: null }), "Turned on");
assert.equal(g.eventText({ kind: "off", detail: null, by: null }), "Turned off");
assert.equal(g.eventText({ kind: "off", detail: "stop", by: "Ada" }), "Turned off — stop by Ada");
assert.equal(g.eventText({ kind: "signal", detail: "restart", by: "Olle" }), "Olle sent restart");
assert.equal(g.eventText({ kind: "signal", detail: null, by: null }), "Someone sent a power signal");
});
test("a stretch sits in the bar by where it is in the time covered, and the unknown part before it is empty", () => {
const t = { from: iso(NOW - 4 * DAY), to: iso(NOW) };
assert.deepEqual(g.barPosition(t, { from: iso(NOW - 4 * DAY), to: iso(NOW - 2 * DAY) }), [0, 50]);
assert.deepEqual(g.barPosition(t, { from: iso(NOW - 2 * DAY), to: iso(NOW) }), [50, 50]);
assert.deepEqual(g.barPosition({ from: iso(NOW), to: iso(NOW) }, { from: iso(NOW), to: iso(NOW) }), [0, 0]);
});
});
describe("what is written down", () => {
let id = 0;
const rows = async (serverId?: string) => (await db.select().from(fragnetPowerLog).where(eq(fragnetPowerLog.integrationId, id))).filter((r) => serverId === undefined || r.serverId === serverId).sort((a, b) => a.at.localeCompare(b.at) || a.id - b.id);
before(async () => {
id = (await db.insert(integrations).values({ type: "fragnet", name: "Power log", baseUrl: "https://panel.fragnet.net", config: JSON.stringify({}) }).returning({ id: integrations.id }))[0].id;
});
after(() => {
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
test("the first read of a server is a starting point, not a change; one whose state is unknown has none yet", async () => {
await p.recordRead(id, [{ id: "aaaa1111", name: "survival", on: true }, { id: "bbbb2222", name: "rust", on: false }, { id: "cccc3333", name: "new", on: null }], [], new Date(NOW - 5 * DAY));
assert.deepEqual((await rows()).map((r) => [r.serverId, r.kind]), [["aaaa1111", "start_on"], ["bbbb2222", "start_off"]]);
await p.recordRead(id, [{ id: "aaaa1111", name: "survival", on: true }, { id: "cccc3333", name: "new", on: true }], [], new Date(NOW - 4 * DAY));
assert.deepEqual((await rows()).map((r) => [r.serverId, r.kind]), [["aaaa1111", "start_on"], ["bbbb2222", "start_off"], ["cccc3333", "start_on"]], "only the one that had none gets a starting point");
});
test("a change is written down with the name and the time of the read", async () => {
await p.recordRead(id, [{ id: "aaaa1111", name: "survival", on: false }], [{ id: "aaaa1111", name: "survival", on: false }], new Date(NOW - 3 * DAY));
const last = (await rows("aaaa1111")).at(-1)!;
assert.deepEqual([last.kind, last.serverName, last.at, last.by, last.detail], ["off", "survival", iso(NOW - 3 * DAY), null, null]);
});
test("a change after a signal from here is put down to it: who, and which signal", async () => {
await p.recordSignal(id, { id: "aaaa1111", name: "survival" }, "start", "Ada", new Date(NOW - 2 * DAY - 6 * MIN));
await p.recordRead(id, [{ id: "aaaa1111", name: "survival", on: true }], [{ id: "aaaa1111", name: "survival", on: true }], new Date(NOW - 2 * DAY));
const last = (await rows("aaaa1111")).at(-1)!;
assert.deepEqual([last.kind, last.by, last.detail], ["on", "Ada", "start"]);
});
test("not when the signal was too long before, or would have done the opposite", async () => {
await p.recordSignal(id, { id: "aaaa1111", name: "survival" }, "stop", "Olle", new Date(NOW - DAY - 30 * MIN));
await p.recordRead(id, [{ id: "aaaa1111", name: "survival", on: false }], [{ id: "aaaa1111", name: "survival", on: false }], new Date(NOW - DAY));
let last = (await rows("aaaa1111")).at(-1)!;
assert.deepEqual([last.kind, last.by], ["off", null], "half an hour is too long ago");
await p.recordSignal(id, { id: "aaaa1111", name: "survival" }, "start", "Olle", new Date(NOW - 12 * HOUR - 2 * MIN));
await p.recordRead(id, [{ id: "aaaa1111", name: "survival", on: false }], [{ id: "aaaa1111", name: "survival", on: false }], new Date(NOW - 12 * HOUR));
last = (await rows("aaaa1111")).at(-1)!;
assert.deepEqual([last.kind, last.by], ["off", null], "a start does not explain a stop");
});
test("the account's history says how each server did, with the signals among the latest events", async () => {
const power = await p.powerOfAccount(id, NOW);
const s = power["aaaa1111"];
assert.ok(s.stats && s.timeline);
assert.equal(s.stats!.trackedSince, iso(NOW - 5 * DAY));
assert.deepEqual(s.recent.map((e) => [e.kind, e.by]).slice(0, 3), [["off", null], ["signal", "Olle"], ["off", null]]);
assert.ok(s.recent.some((e) => e.kind === "on" && e.by === "Ada"));
assert.equal(power["bbbb2222"].stats!.on, false);
});
test("a read stored through the sync writes it down, and the first read of an account has no changes to say", async () => {
const srv = (state: string) => ({ id: "dddd4444", name: "valheim", game: "Valheim", state, installing: false, transferring: false, suspended: false }) as never;
const t0 = new Date(NOW - 6 * HOUR);
assert.deepEqual(await fn.storeRead(id, { servers: [srv("running")] }, t0), []);
assert.equal((await rows("dddd4444")).at(-1)!.kind, "start_on");
const changes = await fn.storeRead(id, { servers: [srv("offline")] }, new Date(NOW - 5 * HOUR));
assert.deepEqual(changes.map((c) => c.on), [false]);
assert.deepEqual((await rows("dddd4444")).map((r) => r.kind), ["start_on", "off"]);
});
test("a server being installed has no starting point until it is done, and writing it down never throws", async () => {
const installing = { id: "eeee5555", name: "fresh", game: null, state: "offline", installing: true, transferring: false, suspended: false } as never;
await fn.storeRead(id, { servers: [installing] }, new Date(NOW - 4 * HOUR));
assert.equal((await rows("eeee5555")).length, 0);
await p.recordRead(999_999, [{ id: "ffff6666", name: "x", on: true }], [], new Date(NOW));
await p.recordSignal(999_999, { id: "ffff6666", name: "x" }, "start", null, new Date(NOW));
});
test("entries older than 180 days are let go, and the history goes with the integration", async () => {
await db.insert(fragnetPowerLog).values({ integrationId: id, serverId: "gggg7777", serverName: "ancient", at: iso(NOW - 200 * DAY), kind: "on" });
await p.recordSignal(id, { id: "gggg7777", name: "ancient" }, "stop", "Ada", new Date(NOW));
assert.equal((await rows("gggg7777")).some((r) => r.kind === "on"), false, "the old one is gone");
await db.delete(integrations).where(eq(integrations.id, id));
assert.equal((await rows()).length, 0);
});
});