/** * 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 => ({ 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); }); });