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:
1 parent
9126200295
commit
a2b43bcd5d
14 files changed
+9773
-4
No files matched your search
+2
-1
@@ -475,7 +475,8 @@ osTicket's API cannot close a ticket, so this is the one place in the app that *
|
|||||||
- **What it does:** every **five minutes** each game server of the account (also those shared with it) is read — the game (the panel's *egg*, for example *Minecraft: Paper*), every IP address and port, SFTP, the plan's memory, disk and CPU limits and its room for backups and databases, whether it is running, what it uses, its backups, schedules and databases. **Infrastructure → Game servers** shows them; a row opens to show every address (click to copy), the backups, the schedules and a link to the server in the game panel.
|
- **What it does:** every **five minutes** each game server of the account (also those shared with it) is read — the game (the panel's *egg*, for example *Minecraft: Paper*), every IP address and port, SFTP, the plan's memory, disk and CPU limits and its room for backups and databases, whether it is running, what it uses, its backups, schedules and databases. **Infrastructure → Game servers** shows them; a row opens to show every address (click to copy), the backups, the schedules and a link to the server in the game panel.
|
||||||
- **Power:** operators can **start, stop, restart and kill** a server from the page (a confirmation first; kill says it loses unsaved progress). It sends exactly that signal to the panel and writes it to the audit log (`start_game_server` …). The page reads again a few seconds later. Beside backups, it is the only thing this integration ever sends but reads, and only a server the last read found can be signalled.
|
- **Power:** operators can **start, stop, restart and kill** a server from the page (a confirmation first; kill says it loses unsaved progress). It sends exactly that signal to the panel and writes it to the audit log (`start_game_server` …). The page reads again a few seconds later. Beside backups, it is the only thing this integration ever sends but reads, and only a server the last read found can be signalled.
|
||||||
- **Back up now:** operators can ask for a backup of a server whose plan has room for backups (*Back up* on its row, or *Back up now* beside its backups; a confirmation first, which says how many the plan allows and how many are made). It is `POST /api/client/servers/{id}/backups` with a name that says it was asked for here (`Homelab Manager — 2026-11-04 14:30 UTC`) and nothing else — no file is left out, nothing is locked. The panel makes it in the background; the page reads the account again after a few seconds and then every twenty seconds until the backup has finished. It is written to the audit log (`backup_game_server`, with the backup's id). **Refused here before the panel is asked:** a plan with no room for backups, a server that is suspended or being installed, one for which a backup is already being made (one that has been "being made" for more than two hours is taken to be lost and does not count), and the same server asked again within 30 seconds (HTTP 429). **Refused by the panel, and said in its words:** a server at the number of backups its plan allows (delete one in the panel first — the app never deletes a backup), the panel's own limit of a couple of backups in ten minutes (429), an account that may not make backups on a shared server (403 — it needs the *Backups → Create* permission) and a server that is busy (409). A refusal costs no wait before the next try.
|
- **Back up now:** operators can ask for a backup of a server whose plan has room for backups (*Back up* on its row, or *Back up now* beside its backups; a confirmation first, which says how many the plan allows and how many are made). It is `POST /api/client/servers/{id}/backups` with a name that says it was asked for here (`Homelab Manager — 2026-11-04 14:30 UTC`) and nothing else — no file is left out, nothing is locked. The panel makes it in the background; the page reads the account again after a few seconds and then every twenty seconds until the backup has finished. It is written to the audit log (`backup_game_server`, with the backup's id). **Refused here before the panel is asked:** a plan with no room for backups, a server that is suspended or being installed, one for which a backup is already being made (one that has been "being made" for more than two hours is taken to be lost and does not count), and the same server asked again within 30 seconds (HTTP 429). **Refused by the panel, and said in its words:** a server at the number of backups its plan allows (delete one in the panel first — the app never deletes a backup), the panel's own limit of a couple of backups in ten minutes (429), an account that may not make backups on a shared server (403 — it needs the *Backups → Create* permission) and a server that is busy (409). A refusal costs no wait before the next try.
|
||||||
- **Alerts** (source *Fragnet*; held back by maintenance on the integration): a server whose plan allows backups and whose **newest successful backup is older** than the limit (or has none, once the app has known it for that long; a backup that failed does not count, and the message says when the newest attempt failed); **disk** over the limit (critical from 98%); **memory** over the limit while it runs. A server that is **stopped** is not an alert. (When one is turned on or off, a notification says so: [NOTIFICATIONS.md](NOTIFICATIONS.md).) See [MONITORING.md](docs/MONITORING.md#game-servers-fragnet).
|
- **Alerts** (source *Fragnet*; held back by maintenance on the integration): a server whose plan allows backups and whose **newest successful backup is older** than the limit (or has none, once the app has known it for that long; a backup that failed does not count, and the message says when the newest attempt failed); **disk** over the limit (critical from 98%); **memory** over the limit while it runs. A server that is **stopped** is not an alert. (When one is turned on or off, a notification says so: [NOTIFICATIONS.md](NOTIFICATIONS.md).)
|
||||||
|
- **Power history.** Every change a read sees (turned on, turned off) is written down, and so is each Start, Stop, Restart or Kill sent from here with who sent it, so a row's details have a **Power history**: the share of the last 30 days (or of what has been watched, when less) that the server was on, how many times it started and stopped, a bar for the last seven days (green on, grey off), and the latest changes — *"Turned on — start by Ada"* when the change followed a signal sent from here in the 20 minutes before. It is what this app saw: the account is read every five minutes, so every time is to the nearest five, and nothing is known of the time before a server was first read. Kept 180 days; it goes with the integration. See [MONITORING.md](docs/MONITORING.md#game-servers-fragnet).
|
||||||
- If the panel cannot be read for 20 minutes its alerts are neither raised nor cleared, the Alerts page says it could not check, and the integration is raised as failing like any other. A part that cannot be read for one server (a sub-user without the *database* permission, say) is shown as *could not be listed*, never as none.
|
- If the panel cannot be read for 20 minutes its alerts are neither raised nor cleared, the Alerts page says it could not check, and the integration is raised as failing like any other. A part that cannot be read for one server (a sub-user without the *database* permission, say) is shown as *could not be listed*, never as none.
|
||||||
- `/metrics` has `homelab_fragnet_server_running`, `homelab_fragnet_disk_used_bytes`, `homelab_fragnet_disk_limit_bytes`, `homelab_fragnet_memory_used_bytes`, `homelab_fragnet_memory_limit_bytes` and `homelab_fragnet_newest_backup_timestamp_seconds`.
|
- `/metrics` has `homelab_fragnet_server_running`, `homelab_fragnet_disk_used_bytes`, `homelab_fragnet_disk_limit_bytes`, `homelab_fragnet_memory_used_bytes`, `homelab_fragnet_memory_limit_bytes` and `homelab_fragnet_newest_backup_timestamp_seconds`.
|
||||||
- **Not verified against a live account** — the endpoints (`/api/client?include=egg,allocations`, `/servers/{id}/resources`, `…/backups`, `…/schedules`, `…/databases`, `POST …/power`) and their fields are as Pterodactyl's own source and Fragnet's documentation have them, and the reader is tried against a pretend panel. Fragnet's fork may differ: the game is left out (shown as the Docker image) if the panel does not send the egg, and a panel that refuses the extra `include` is asked again plainly. Disk and memory limits are in MB as the panel counts them and shown in binary units. What the servers cost is not in the API: add it under Records → Costs.
|
- **Not verified against a live account** — the endpoints (`/api/client?include=egg,allocations`, `/servers/{id}/resources`, `…/backups`, `…/schedules`, `…/databases`, `POST …/power`) and their fields are as Pterodactyl's own source and Fragnet's documentation have them, and the reader is tried against a pretend panel. Fragnet's fork may differ: the game is left out (shown as the Docker image) if the panel does not send the egg, and a panel that refuses the extra `include` is asked again plainly. Disk and memory limits are in MB as the panel counts them and shown in binary units. What the servers cost is not in the API: add it under Records → Costs.
|
||||||
|
|||||||
@@ -349,6 +349,8 @@ An integration of type *Fragnet game servers* ([INTEGRATIONS.md](../INTEGRATIONS
|
|||||||
|
|
||||||
Each of the three can be **switched off on its own** in the integration's settings (Administration → Integrations → edit: *Do not alert about disk space / memory / backups*) — for example to hear about disk and backups but not memory. The page keeps showing the figures; a bar for something switched off is blue instead of green, yellow or red, and the backups tile says *not judged*. There is no CPU alert: the CPU is shown on the server's row only.
|
Each of the three can be **switched off on its own** in the integration's settings (Administration → Integrations → edit: *Do not alert about disk space / memory / backups*) — for example to hear about disk and backups but not memory. The page keeps showing the figures; a bar for something switched off is blue instead of green, yellow or red, and the backups tile says *not judged*. There is no CPU alert: the CPU is shown on the server's row only.
|
||||||
|
|
||||||
|
Each game server's row opens to a **power history** (how much of the last 30 days it was on, a seven-day bar and the latest changes, with who pressed the button when it was done from here — see [INTEGRATIONS.md](../INTEGRATIONS.md#fragnet-game-servers)).
|
||||||
|
|
||||||
When a server is **turned on or off** it is not an alert but a **notification** — see [NOTIFICATIONS.md](../NOTIFICATIONS.md): one message, through the configured channels, when a read shows it changed since the last one (switch it off under Settings → Notifications → What to send).
|
When a server is **turned on or off** it is not an alert but a **notification** — see [NOTIFICATIONS.md](../NOTIFICATIONS.md): one message, through the configured channels, when a read shows it changed since the last one (switch it off under Settings → Notifications → What to send).
|
||||||
|
|
||||||
A server that is **stopped** is not an alert (game servers are often stopped on purpose), and one that is suspended or being installed is not judged. "Since when" a server has been in its state is **when the app first saw it** in a read. Maintenance on the integration holds the alerts; a reading older than 20 minutes is not believed (they are neither raised nor cleared, and the Alerts page says it could not check). `/metrics` has the running state, disk and memory against their limits and when the newest backup finished.
|
A server that is **stopped** is not an alert (game servers are often stopped on purpose), and one that is suspended or being installed is not judged. "Since when" a server has been in its state is **when the app first saw it** in a read. Maintenance on the integration holds the alerts; a reading older than 20 minutes is not believed (they are neither raised nor cleared, and the Alerts page says it could not check). `/metrics` has the running state, disk and memory against their limits and when the newest backup finished.
|
||||||
|
|||||||
@@ -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
@@ -638,6 +638,13 @@
|
|||||||
"when": 1794333852784,
|
"when": 1794333852784,
|
||||||
"tag": "0090_watery_mathemanic",
|
"tag": "0090_watery_mathemanic",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 91,
|
||||||
|
"version": "6",
|
||||||
|
"when": 1794334785852,
|
||||||
|
"tag": "0091_adorable_wasp",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -1662,6 +1662,25 @@ export const jellyfinReadings = sqliteTable(
|
|||||||
|
|
||||||
// ─── Duplicati ──────────────────────────────────────────────────────────────
|
// ─── 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).
|
// 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(
|
export const notificationLog = sqliteTable(
|
||||||
"notification_log",
|
"notification_log",
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
|
|||||||
import { recordAudit } from "../services/audit.js";
|
import { recordAudit } from "../services/audit.js";
|
||||||
import { invalidateAlertsCache } from "../services/alerts.js";
|
import { invalidateAlertsCache } from "../services/alerts.js";
|
||||||
import { fragnetProblems, fragnetSyncStatuses, isFragnetFresh, newestBackup, optionsOf, serversOf, syncFragnet } from "../services/fragnetSync.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";
|
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||||
|
|
||||||
export const fragnetRouter = Router();
|
export const fragnetRouter = Router();
|
||||||
@@ -34,6 +35,7 @@ fragnetRouter.get("/", asyncHandler(async (_req, res) => {
|
|||||||
} catch {
|
} catch {
|
||||||
// a config that cannot be read costs only the settings it holds
|
// a config that cannot be read costs only the settings it holds
|
||||||
}
|
}
|
||||||
|
const power = await powerOfAccount(r.id, now);
|
||||||
accounts.push({
|
accounts.push({
|
||||||
id: r.id,
|
id: r.id,
|
||||||
name: r.name,
|
name: r.name,
|
||||||
@@ -42,7 +44,7 @@ fragnetRouter.get("/", asyncHandler(async (_req, res) => {
|
|||||||
status,
|
status,
|
||||||
fresh,
|
fresh,
|
||||||
options,
|
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) : [],
|
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) {
|
} catch (err) {
|
||||||
return res.status(502).json({ error: err instanceof Error ? err.message : String(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({
|
await recordAudit({
|
||||||
actor: req.currentUser!,
|
actor: req.currentUser!,
|
||||||
category: "integration",
|
category: "integration",
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -17,6 +17,7 @@ import { fragnetState, integrations } from "../db/schema.js";
|
|||||||
import { createFragnetAdapter, type FragnetRead, type FragnetServer } from "../integrations/fragnet/adapter.js";
|
import { createFragnetAdapter, type FragnetRead, type FragnetServer } from "../integrations/fragnet/adapter.js";
|
||||||
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
|
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
|
||||||
import { notifyGameServerPower } from "./notify.js";
|
import { notifyGameServerPower } from "./notify.js";
|
||||||
|
import { recordRead } from "./fragnetPower.js";
|
||||||
import { getInternalFlag, setInternalFlag } from "./settingsStore.js";
|
import { getInternalFlag, setInternalFlag } from "./settingsStore.js";
|
||||||
|
|
||||||
export const SYNC_INTERVAL_MS = 5 * 60_000;
|
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() };
|
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 });
|
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.
|
// 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. */
|
/** Reads one account and stores it. Never throws: how it went is the answer, and what was stored is left alone when it failed. */
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ process.env.HEALTH_STARTUP_GRACE_MS = "0";
|
|||||||
|
|
||||||
const express = (await import("express")).default;
|
const express = (await import("express")).default;
|
||||||
const { db } = await import("../src/db/client.js");
|
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 { runMigrations } = await import("../src/db/migrate.js");
|
||||||
const adapter = await import("../src/integrations/fragnet/adapter.js");
|
const adapter = await import("../src/integrations/fragnet/adapter.js");
|
||||||
const fn = await import("../src/services/fragnetSync.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");
|
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.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "fragnet_server", "abcd1234"]);
|
||||||
assert.match(entry.detail ?? "", /survival/);
|
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 () => {
|
test("only a server the last read found, and only a real signal, are accepted — nothing typed in the address reaches the panel", async () => {
|
||||||
|
|||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1524,6 +1524,12 @@ export interface FragnetServerInfo {
|
|||||||
firstSeenAt: string;
|
firstSeenAt: string;
|
||||||
/** The newest backup that worked, and whether a newer one failed; null when the backups could not be listed. */
|
/** The newest backup that worked, and whether a newer one failed; null when the backups could not be listed. */
|
||||||
newestBackup: { at: string | null; failedSince: boolean } | null;
|
newestBackup: { at: string | null; failedSince: boolean } | null;
|
||||||
|
/** How the server has been on and off, as this app saw it; null before it has been read. */
|
||||||
|
power: {
|
||||||
|
stats: { trackedSince: string; onPercent: number | null; spanMs: number; starts: number; stops: number; lastOnAt: string | null; lastOffAt: string | null; on: boolean } | null;
|
||||||
|
timeline: { from: string; to: string; segments: { from: string; to: string; on: boolean }[] } | null;
|
||||||
|
recent: { at: string; kind: "on" | "off" | "signal"; detail: string | null; by: string | null }[];
|
||||||
|
} | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One Fragnet game panel account (an integration of type fragnet), as its page shows it. */
|
/** One Fragnet game panel account (an integration of type fragnet), as its page shows it. */
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import { formatBytes } from "./settings/StorageSettings";
|
|||||||
import { confirmDialog } from "../utils/dialogs";
|
import { confirmDialog } from "../utils/dialogs";
|
||||||
import { readableError } from "../utils/errors";
|
import { readableError } from "../utils/errors";
|
||||||
import { toast } from "../utils/toast";
|
import { toast } from "../utils/toast";
|
||||||
|
import { barPosition, eventText, onHeadline } from "../utils/gamePower";
|
||||||
|
import { formatDateTime } from "../utils/date";
|
||||||
|
|
||||||
type Server = FragnetServerInfo;
|
type Server = FragnetServerInfo;
|
||||||
|
|
||||||
@@ -81,6 +83,70 @@ const SIGNAL_TEXT: Record<FragnetSignal, { verb: string; done: string; confirm:
|
|||||||
kill: { verb: "Kill", done: "kill", confirm: "Kill {name}? It is stopped at once, without saving — unsaved progress is lost. Use it only when Stop does not work.", danger: true },
|
kill: { verb: "Kill", done: "kill", confirm: "Kill {name}? It is stopped at once, without saving — unsaved progress is lost. Use it only when Stop does not work.", danger: true },
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** How the server has been on and off over the last days, as this app saw it: the share of the time it was on, a bar for the last week, and the latest changes and who asked for them. */
|
||||||
|
function PowerHistory({ power }: { power: Server["power"] }) {
|
||||||
|
const stats = power?.stats ?? null;
|
||||||
|
const timeline = power?.timeline ?? null;
|
||||||
|
const headline = stats ? onHeadline(stats) : null;
|
||||||
|
return (
|
||||||
|
<div className="col-12">
|
||||||
|
<h5>Power history</h5>
|
||||||
|
{!stats && <div className="text-secondary small">Nothing yet — this app keeps it from the first time it reads a server, so it fills in as the days go by.</div>}
|
||||||
|
{stats && (
|
||||||
|
<div className="row g-3">
|
||||||
|
<div className="col-lg-8">
|
||||||
|
{headline ? <div className="fw-bold">{headline}</div> : <div className="text-secondary small">Too little is known to say how much of the time it is on (it was first read less than an hour ago).</div>}
|
||||||
|
<div className="small text-secondary mb-2">
|
||||||
|
Started {stats.starts} time{stats.starts === 1 ? "" : "s"}, stopped {stats.stops} in that time
|
||||||
|
{stats.lastOnAt && (
|
||||||
|
<>
|
||||||
|
{" "}
|
||||||
|
· last turned on <TimeAgo value={stats.lastOnAt} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{stats.lastOffAt && (
|
||||||
|
<>
|
||||||
|
{" "}
|
||||||
|
· last turned off <TimeAgo value={stats.lastOffAt} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{timeline && timeline.segments.length > 0 && (
|
||||||
|
<>
|
||||||
|
<div className="position-relative rounded overflow-hidden bg-secondary-lt" style={{ height: 16 }} role="img" aria-label="The last seven days: green where the server was on, grey where it was off">
|
||||||
|
{timeline.segments.map((seg, i) => {
|
||||||
|
const [left, width] = barPosition(timeline, seg);
|
||||||
|
return <div key={i} className={seg.on ? "bg-green" : "bg-secondary"} style={{ position: "absolute", top: 0, bottom: 0, left: `${left}%`, width: `${width}%`, opacity: seg.on ? 1 : 0.35 }} title={`${seg.on ? "On" : "Off"} from ${formatDateTime(new Date(seg.from))} to ${formatDateTime(new Date(seg.to))}`} />;
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
<div className="d-flex justify-content-between small text-secondary mt-1">
|
||||||
|
<span>{formatDateTime(new Date(timeline.from))}</span>
|
||||||
|
<span>now</span>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<div className="small text-secondary mt-1">Seen by reading the account every five minutes, so each time is to the nearest five. Known since {formatDateTime(new Date(stats.trackedSince))}.</div>
|
||||||
|
</div>
|
||||||
|
<div className="col-lg-4">
|
||||||
|
<div className="small text-secondary mb-1">Latest</div>
|
||||||
|
{power && power.recent.length === 0 && <div className="small text-secondary">Nothing has changed since it was first read.</div>}
|
||||||
|
<ul className="list-unstyled small mb-0">
|
||||||
|
{power?.recent.slice(0, 8).map((e, i) => (
|
||||||
|
<li key={i}>
|
||||||
|
<span className={e.kind === "on" ? "text-green" : e.kind === "off" ? "text-secondary" : "text-blue"} aria-hidden="true">
|
||||||
|
{e.kind === "on" ? "●" : e.kind === "off" ? "○" : "▸"}
|
||||||
|
</span>{" "}
|
||||||
|
{eventText(e)} <span className="text-secondary">· <TimeAgo value={e.at} /></span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/** Whether a backup of this server is being made now (one the panel has begun and not finished, from the last two hours). */
|
/** Whether a backup of this server is being made now (one the panel has begun and not finished, from the last two hours). */
|
||||||
function backupInProgress(s: Server): boolean {
|
function backupInProgress(s: Server): boolean {
|
||||||
return (s.backups ?? []).some((b) => b.completedAt === null && Date.now() - Date.parse(b.createdAt ?? "") < 2 * 60 * 60_000);
|
return (s.backups ?? []).some((b) => b.completedAt === null && Date.now() - Date.parse(b.createdAt ?? "") < 2 * 60 * 60_000);
|
||||||
@@ -186,6 +252,7 @@ function Details({ s, panelUrl, canAct, onSignal, onBackup, busy }: { s: Server;
|
|||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
<PowerHistory power={s.power} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
/** How a game server's power history is told on the page: a headline, the words for an event, and where each stretch of the timeline sits in its bar. */
|
||||||
|
|
||||||
|
const HOUR = 3_600_000;
|
||||||
|
const DAY = 24 * HOUR;
|
||||||
|
|
||||||
|
export interface PowerStatsInfo {
|
||||||
|
trackedSince: string;
|
||||||
|
onPercent: number | null;
|
||||||
|
spanMs: number;
|
||||||
|
starts: number;
|
||||||
|
stops: number;
|
||||||
|
lastOnAt: string | null;
|
||||||
|
lastOffAt: string | null;
|
||||||
|
on: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PowerEventInfo {
|
||||||
|
at: string;
|
||||||
|
kind: "on" | "off" | "signal";
|
||||||
|
detail: string | null;
|
||||||
|
by: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const plural = (n: number, one: string) => `${n} ${one}${n === 1 ? "" : "s"}`;
|
||||||
|
|
||||||
|
/** "6 days", "5 hours", "40 minutes". */
|
||||||
|
export function spanText(ms: number): string {
|
||||||
|
if (ms >= 2 * DAY) return plural(Math.round(ms / DAY), "day");
|
||||||
|
if (ms >= 2 * HOUR) return plural(Math.round(ms / HOUR), "hour");
|
||||||
|
return plural(Math.max(1, Math.round(ms / 60_000)), "minute");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "On 94.3% of the last 30 days", or of "the 6 days it has been watched" when that is all that is known; null while under an hour is known. */
|
||||||
|
export function onHeadline(s: Pick<PowerStatsInfo, "onPercent" | "spanMs">): string | null {
|
||||||
|
if (s.onPercent === null) return null;
|
||||||
|
const pct = Number.isInteger(s.onPercent) ? String(s.onPercent) : s.onPercent.toFixed(1);
|
||||||
|
return s.spanMs >= 29.5 * DAY ? `On ${pct}% of the last 30 days` : `On ${pct}% of the ${spanText(s.spanMs)} it has been watched`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The words for one event: what happened, and who asked for it when it was done from here. */
|
||||||
|
export function eventText(e: Pick<PowerEventInfo, "kind" | "detail" | "by">): string {
|
||||||
|
if (e.kind === "signal") return `${e.by ?? "Someone"} sent ${e.detail ?? "a power signal"}`;
|
||||||
|
const what = e.kind === "on" ? "Turned on" : "Turned off";
|
||||||
|
return e.by ? `${what} — ${e.detail ?? "asked"} by ${e.by}` : what;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a stretch sits in a bar covering the timeline, in percent: [left, width]. The part before anything was known is empty. */
|
||||||
|
export function barPosition(timeline: { from: string; to: string }, seg: { from: string; to: string }): [number, number] {
|
||||||
|
const start = Date.parse(timeline.from);
|
||||||
|
const total = Date.parse(timeline.to) - start;
|
||||||
|
if (!(total > 0)) return [0, 0];
|
||||||
|
const left = ((Date.parse(seg.from) - start) / total) * 100;
|
||||||
|
const width = ((Date.parse(seg.to) - Date.parse(seg.from)) / total) * 100;
|
||||||
|
return [Math.max(0, Math.round(left * 100) / 100), Math.max(0, Math.round(width * 100) / 100)];
|
||||||
|
}
|
||||||
Reference in new issue
Block a user