Public: anyone can read this; the crew can change it.

Game servers are measured: players, TPS, tick time, memory and errors, per minute for 30 days #17214

opened this

Closed 43h 34m ago

sold/game-metrics → main 1 commit

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +825 −34
docs/features/games.md +6
@@ -21,6 +21,12 @@ The environment editor refuses a key that looks like a secret (`PASSWORD`, `SECR
2121
2222 A plugin or jar runs code on the game server; give operator only to people you trust.
2323
24 ## Numbers
25
26 Each sync, the agent asks every running server with `rcon-cli` for `list`, `tps` and `mspt` (Paper) and sends the answers raw in `metrics` (additive: `agent: 1` without it still works); the forge parses them, with the CPU and memory the agent already sends and the joins, leaves, errors and warnings in the log lines (`src/games/metrics.ts`). A row a minute a service is kept 30 days (`game_metric`), and each join and leave (`game_player_event`).
27
28 `/games/<box>` shows each server's players, TPS and memory with 24-hour sparklines; a service's page adds tick time, errors, the latest joins and the latest error lines; the terminal's Games screen shows players and TPS. The `games` tool's `metrics` answers each service's now, last hour and last day (min, avg, max, p95, peak players, errors) under 4 KB, or one `service` over a `window` (1h to 30d) as columns, also under 4 KB (`src/games/metrics_answer.ts`).
29
2430 ## Who may do what
2531
2632 Grants per box, optionally for one service: **owner** (everything and grants), **operator** (console, power, env, plugins), **viewer** (read). Forge admins own every box; owners grant on the box page.
src/core/migration-pins/20261201050000-game-metrics.pin added +1
@@ -0,0 +1,1 @@
1 e1b79d3e8929312118093c3fc3f1b4f8d8e5ce5b6b0d7fd0ccff4a3b02b2c71b
src/core/migrations/20261201050000-game-metrics.ts added +38
@@ -0,0 +1,38 @@
1 // Game metrics (forge games): each service's minute, rolled up as the box syncs (players, TPS,
2 // MSPT, CPU, memory, errors, joins), kept 30 days; the joins and leaves themselves; and who is
3 // online now. Additive: older rows keep the empty values.
4 export default `
5 CREATE TABLE IF NOT EXISTS game_metric (
6 box_id TEXT NOT NULL,
7 service TEXT NOT NULL,
8 minute INTEGER NOT NULL,
9 n INTEGER NOT NULL DEFAULT 0,
10 players_max INTEGER NOT NULL DEFAULT 0,
11 players_last INTEGER NOT NULL DEFAULT 0,
12 players_n INTEGER NOT NULL DEFAULT 0,
13 tps_sum REAL NOT NULL DEFAULT 0,
14 tps_min REAL,
15 tps_n INTEGER NOT NULL DEFAULT 0,
16 mspt_sum REAL NOT NULL DEFAULT 0,
17 mspt_max REAL,
18 mspt_n INTEGER NOT NULL DEFAULT 0,
19 cpu_sum REAL NOT NULL DEFAULT 0,
20 mem_sum REAL NOT NULL DEFAULT 0,
21 errors INTEGER NOT NULL DEFAULT 0,
22 warns INTEGER NOT NULL DEFAULT 0,
23 joins INTEGER NOT NULL DEFAULT 0,
24 leaves INTEGER NOT NULL DEFAULT 0,
25 PRIMARY KEY (box_id, service, minute)
26 );
27 CREATE INDEX IF NOT EXISTS game_metric_minute ON game_metric (minute);
28 CREATE TABLE IF NOT EXISTS game_player_event (
29 id INTEGER PRIMARY KEY,
30 box_id TEXT NOT NULL,
31 service TEXT NOT NULL,
32 player TEXT NOT NULL,
33 kind TEXT NOT NULL,
34 at TEXT NOT NULL
35 );
36 CREATE INDEX IF NOT EXISTS game_player_event_box ON game_player_event (box_id, service, id);
37 ALTER TABLE game_service ADD COLUMN players TEXT NOT NULL DEFAULT '';
38 `;
src/games/agent.sh +21 −1
@@ -138,6 +138,25 @@ logs() {
138138 | group_by(.s) | map({key: .[0].s, value: (map(.l) | .[-200:])}) | from_entries' 2>/dev/null || echo '{}'
139139 }
140140
141 # Each running service's RCON answers to `list`, `tps` and `mspt` (Paper), raw: the forge parses
142 # them (games/metrics.ts). A service without rcon-cli (the Velocity proxy) is asked once, then not.
143 NORCON=" "
144 metrics() {
145 local out='{}' name list tps mspt
146 while IFS= read -r name; do
147 [[ "$name" =~ $SAFE ]] || continue
148 case "$NORCON" in *" $name "*) continue ;; esac
149 if ! list="$(capped 5 compose exec -T "$name" rcon-cli -- list 2>/dev/null)"; then
150 NORCON="$NORCON$name "
151 continue
152 fi
153 tps="$(capped 5 compose exec -T "$name" rcon-cli -- tps 2>/dev/null || true)"
154 mspt="$(capped 5 compose exec -T "$name" rcon-cli -- mspt 2>/dev/null || true)"
155 out="$(jq -c --arg n "$name" --arg l "${list:0:4000}" --arg t "${tps:0:1000}" --arg m "${mspt:0:2000}" '. + {($n): {list: $l, tps: $t, mspt: $m}}' <<<"$out")"
156 done < <(compose ps --status running --format '{{.Service}}' 2>/dev/null)
157 echo "$out"
158 }
159
141160 host() {
142161 local total avail load disk
143162 total="$(awk '/^MemTotal:/ {print int($2/1024)}' /proc/meminfo 2>/dev/null || echo 0)"
@@ -355,7 +374,8 @@ sync() {
355374 --slurpfile results "$DIR/.results" \
356375 --argjson host "$(host)" \
357376 --argjson diag "$(bounded_diag)" \
358 '{agent: 1, composeSha: $sha, services: $services, logs: $logs, results: $results[0], host: $host, diag: $diag}')" || return 1
377 --argjson metrics "$(metrics)" \
378 '{agent: 1, composeSha: $sha, services: $services, logs: $logs, results: $results[0], host: $host, diag: $diag, metrics: $metrics}')" || return 1
359379 answer="$(curl -fsS -m 20 -H "@$AUTH" -H 'content-type: application/json' --data-binary "$body" "${FORGE_URL%/}/api/v1/games/agent/sync")" || return 1
360380 # Delivered: the results and the log lines are the forge's now.
361381 echo '[]' >"$DIR/.results"
src/games/metrics.ts added +375
@@ -0,0 +1,375 @@
1 /**
2 * Game metrics (forge games): what each service of a game box does, so a person, the crew and Talk
3 * can improve the network by numbers. The agent sends, each sync, the raw RCON answers to `list`,
4 * `tps` and `mspt` (Paper), beside the CPU, memory and log lines it already sends; everything is
5 * parsed here, so the agent stays a shell script and the parsers are tested in one place.
6 *
7 * Kept per box and service, a row a minute (`game_metric`, sums and counts, so a minute is rolled
8 * up as syncs arrive), 30 days; and each join and leave (`game_player_event`). Read back as a
9 * compact summary (now, 1 h, 24 h) that stays well under 4 KB, or one service's series over a
10 * window, bounded to `MAX_POINTS`.
11 */
12
13 import type { Database } from "bun:sqlite";
14 import { SERVICE_NAME, type GameBox } from "./store.ts";
15
16 /** How long a minute is kept. */
17 export const KEEP_DAYS = 30;
18 /** The most points a series answers with, whatever the window. */
19 export const MAX_POINTS = 120;
20 const NAMES_MAX = 100;
21
22 // ---- parsing ----------------------------------------------------------------------------------
23
24 /** Minecraft's colour codes (`§a`) and terminal colour sequences, gone. */
25 export const plain = (s: string): string => s.replace(/\u001b\[[0-9;]*[A-Za-z]/g, "").replace(/§[0-9a-fk-orx]/gi, "");
26
27 /**
28 * `list`'s answer: how many are online, the most allowed, and their names. Vanilla and Paper say
29 * "There are 2 of a max of 20 players online: Alice, Bob"; newer Paper says "There are 2 out of
30 * maximum 20 players online." with the names on the lines after, grouped ("default: Alice, Bob").
31 */
32 export function parseList(raw: string): { online: number; max: number; names: string[] } | undefined {
33 const text = plain(raw);
34 const m = /There are (\d+)(?: of a max of| out of maximum| out of a maximum of)? ?(\d+)? players? online[.:]?/i.exec(text);
35 if (m === null) return undefined;
36 const online = Number(m[1]);
37 const max = m[2] === undefined ? 0 : Number(m[2]);
38 const rest = text.slice(m.index + m[0].length);
39 const names = rest
40 .split("\n")
41 .map((l) => (l.includes(":") ? l.slice(l.indexOf(":") + 1) : l))
42 .flatMap((l) => l.split(","))
43 .map((n) =>
44 n
45 .trim()
46 .replace(/^\[[^\]]*\]\s*/, "")
47 .replace(/^[~*]/, ""),
48 )
49 .filter((n) => /^[A-Za-z0-9_]{1,16}$/.test(n))
50 .slice(0, NAMES_MAX);
51 return { online, max, names };
52 }
53
54 /** Paper's `tps`: the last minute's ticks a second ("TPS from last 1m, 5m, 15m: *20.0, 19.8, 19.9"). */
55 export function parseTps(raw: string): number | undefined {
56 const text = plain(raw);
57 const m = /TPS from last[^:]*:\s*\*?([0-9]+(?:\.[0-9]+)?)/i.exec(text);
58 return m === null ? undefined : Number(m[1]);
59 }
60
61 /** Paper's `mspt`: the average tick time of the last 5 s, in milliseconds (the first avg/min/max triple). */
62 export function parseMspt(raw: string): number | undefined {
63 const text = plain(raw);
64 const at = text.indexOf(":", text.search(/tick times/i));
65 if (at < 0) return undefined;
66 const m = /([0-9]+(?:\.[0-9]+)?)\s*\/\s*[0-9.]+\s*\/\s*[0-9.]+/.exec(text.slice(at + 1));
67 return m === null ? undefined : Number(m[1]);
68 }
69
70 export type LogFact = { kind: "join" | "leave"; player: string } | { kind: "error" | "warn" } | undefined;
71
72 /**
73 * What one log line says that is counted: a player joining or leaving (Paper's "Alice joined the
74 * game", Velocity's "[connected player] Alice (/1.2.3.4:5) has connected"), or an error or a warning
75 * (the level in the line's head: "[12:00:00 ERROR]:", "[Server thread/WARN]:", " ERROR ").
76 */
77 export function parseLogLine(line: string): LogFact {
78 const text = plain(line);
79 let m =
80 /\]:?\s*(?:\[[^\]]*\]\s*)?([A-Za-z0-9_]{1,16}) joined the game\b/.exec(text) ??
81 /\[connected player\] ([A-Za-z0-9_]{1,16}) \([^)]*\) has connected/.exec(text);
82 if (m !== null) return { kind: "join", player: m[1]! };
83 m =
84 /\]:?\s*(?:\[[^\]]*\]\s*)?([A-Za-z0-9_]{1,16}) left the game\b/.exec(text) ??
85 /\[connected player\] ([A-Za-z0-9_]{1,16}) \([^)]*\) has disconnected/.exec(text);
86 if (m !== null) return { kind: "leave", player: m[1]! };
87 const head = text.slice(0, 80);
88 if (/[\s/[](ERROR|SEVERE|FATAL)\]?[:\s]/.test(head)) return { kind: "error" };
89 if (/[\s/[](WARN|WARNING)\]?[:\s]/.test(head)) return { kind: "warn" };
90 return undefined;
91 }
92
93 // ---- recording --------------------------------------------------------------------------------
94
95 export interface MetricsBody {
96 readonly services?: readonly { name?: unknown; cpuPct?: unknown; memMiB?: unknown }[];
97 readonly logs?: Record<string, unknown>;
98 /** Per service, the raw RCON answers: `list`, `tps`, `mspt` (any may be missing). */
99 readonly metrics?: Record<string, unknown>;
100 }
101
102 const num = (v: unknown): number | undefined => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
103 const text = (v: unknown, max = 8_000): string => (typeof v === "string" ? v.slice(0, max) : "");
104
105 /** One sync's numbers, rolled into each service's current minute; joins and leaves kept as events. */
106 export function recordMetrics(db: Database, box: Pick<GameBox, "id">, body: MetricsBody, now = new Date()): void {
107 const minute = Math.floor(now.getTime() / 60_000);
108 const at = now.toISOString();
109 type Row = { players?: number | undefined; names?: string[] | undefined; tps?: number | undefined; mspt?: number | undefined; cpu?: number | undefined; mem?: number | undefined; errors: number; warns: number; joins: number; leaves: number };
110 const rows = new Map<string, Row>();
111 const rowOf = (s: string): Row => rows.get(s) ?? (rows.set(s, { errors: 0, warns: 0, joins: 0, leaves: 0 }), rows.get(s)!);
112 for (const s of (body.services ?? []).slice(0, 64)) {
113 const name = typeof s.name === "string" ? s.name : "";
114 if (!SERVICE_NAME.test(name)) continue;
115 const r = rowOf(name);
116 r.cpu = num(s.cpuPct);
117 r.mem = num(s.memMiB);
118 }
119 for (const [service, raw] of Object.entries(body.metrics ?? {}).slice(0, 64)) {
120 if (!SERVICE_NAME.test(service) || raw === null || typeof raw !== "object") continue;
121 const m = raw as Record<string, unknown>;
122 const r = rowOf(service);
123 const list = parseList(text(m["list"]));
124 if (list !== undefined) {
125 r.players = list.online;
126 r.names = list.names;
127 }
128 r.tps = parseTps(text(m["tps"]));
129 r.mspt = parseMspt(text(m["mspt"]));
130 }
131 const events: { service: string; player: string; kind: "join" | "leave" }[] = [];
132 for (const [service, lines] of Object.entries(body.logs ?? {}).slice(0, 64)) {
133 if (!SERVICE_NAME.test(service) || !Array.isArray(lines)) continue;
134 const r = rowOf(service);
135 for (const line of lines.slice(-200)) {
136 if (typeof line !== "string") continue;
137 const fact = parseLogLine(line);
138 if (fact === undefined) continue;
139 if (fact.kind === "join" || fact.kind === "leave") {
140 if (fact.kind === "join") r.joins++;
141 else r.leaves++;
142 events.push({ service, player: fact.player, kind: fact.kind });
143 } else if (fact.kind === "error") r.errors++;
144 else r.warns++;
145 }
146 }
147 db.transaction(() => {
148 const upsert = db.query(
149 `INSERT INTO game_metric (box_id, service, minute, n, players_max, players_last, players_n, tps_sum, tps_min, tps_n, mspt_sum, mspt_max, mspt_n, cpu_sum, mem_sum, errors, warns, joins, leaves)
150 VALUES (?1, ?2, ?3, 1, ?4, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)
151 ON CONFLICT (box_id, service, minute) DO UPDATE SET
152 n = n + 1,
153 players_max = MAX(players_max, excluded.players_max),
154 players_last = CASE WHEN excluded.players_n > 0 THEN excluded.players_last ELSE players_last END,
155 players_n = players_n + excluded.players_n,
156 tps_sum = tps_sum + excluded.tps_sum, tps_n = tps_n + excluded.tps_n,
157 tps_min = CASE WHEN excluded.tps_min IS NULL THEN tps_min WHEN tps_min IS NULL THEN excluded.tps_min ELSE MIN(tps_min, excluded.tps_min) END,
158 mspt_sum = mspt_sum + excluded.mspt_sum, mspt_n = mspt_n + excluded.mspt_n,
159 mspt_max = CASE WHEN excluded.mspt_max IS NULL THEN mspt_max WHEN mspt_max IS NULL THEN excluded.mspt_max ELSE MAX(mspt_max, excluded.mspt_max) END,
160 cpu_sum = cpu_sum + excluded.cpu_sum, mem_sum = mem_sum + excluded.mem_sum,
161 errors = errors + excluded.errors, warns = warns + excluded.warns, joins = joins + excluded.joins, leaves = leaves + excluded.leaves`,
162 );
163 for (const [service, r] of rows)
164 upsert.run(
165 box.id,
166 service,
167 minute,
168 r.players ?? 0,
169 r.players === undefined ? 0 : 1,
170 r.tps ?? 0,
171 r.tps ?? null,
172 r.tps === undefined ? 0 : 1,
173 r.mspt ?? 0,
174 r.mspt ?? null,
175 r.mspt === undefined ? 0 : 1,
176 r.cpu ?? 0,
177 r.mem ?? 0,
178 r.errors,
179 r.warns,
180 r.joins,
181 r.leaves,
182 );
183 for (const [service, r] of rows)
184 if (r.names !== undefined)
185 db.query("UPDATE game_service SET players = ?3 WHERE box_id = ?1 AND name = ?2").run(box.id, service, r.names.join(","));
186 const event = db.query("INSERT INTO game_player_event (box_id, service, player, kind, at) VALUES (?1, ?2, ?3, ?4, ?5)");
187 for (const e of events) event.run(box.id, e.service, e.player, e.kind, at);
188 // Past the window: once a minute is plenty, and each delete walks the minute index.
189 if (minute % 10 === 0) {
190 db.query("DELETE FROM game_metric WHERE minute < ?1").run(minute - KEEP_DAYS * 1440);
191 db.query("DELETE FROM game_player_event WHERE at < ?1").run(new Date(now.getTime() - KEEP_DAYS * 86_400_000).toISOString());
192 }
193 })();
194 }
195
196 // ---- reading ----------------------------------------------------------------------------------
197
198 interface MinuteRow {
199 service: string;
200 minute: number;
201 n: number;
202 players_max: number;
203 players_last: number;
204 players_n: number;
205 tps_sum: number;
206 tps_min: number | null;
207 tps_n: number;
208 mspt_sum: number;
209 mspt_max: number | null;
210 mspt_n: number;
211 cpu_sum: number;
212 mem_sum: number;
213 errors: number;
214 warns: number;
215 joins: number;
216 leaves: number;
217 }
218
219 const minutes = (db: Database, boxId: string, since: number, service?: string): MinuteRow[] =>
220 service === undefined
221 ? db
222 .query<MinuteRow, [string, number]>("SELECT * FROM game_metric WHERE box_id = ?1 AND minute >= ?2 ORDER BY service, minute")
223 .all(boxId, since)
224 : db
225 .query<
226 MinuteRow,
227 [string, string, number]
228 >("SELECT * FROM game_metric WHERE box_id = ?1 AND service = ?2 AND minute >= ?3 ORDER BY minute")
229 .all(boxId, service, since);
230
231 const round = (n: number, places = 1): number => Math.round(n * 10 ** places) / 10 ** places;
232
233 /** min, avg, max and p95 of what is known; undefined with nothing. */
234 export function stats(values: readonly number[]): { min: number; avg: number; max: number; p95: number } | undefined {
235 if (values.length === 0) return undefined;
236 const sorted = [...values].sort((a, b) => a - b);
237 const p95 = sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * 0.95) - 1)]!;
238 return {
239 min: round(sorted[0]!),
240 avg: round(values.reduce((s, v) => s + v, 0) / values.length),
241 max: round(sorted.at(-1)!),
242 p95: round(p95),
243 };
244 }
245
246 /** A window of minutes rolled into one: averages per minute, peaks, counts. */
247 function windowOf(rows: readonly MinuteRow[]) {
248 const tps = rows.filter((r) => r.tps_n > 0).map((r) => r.tps_sum / r.tps_n);
249 const mspt = rows.filter((r) => r.mspt_n > 0).map((r) => r.mspt_sum / r.mspt_n);
250 const cpu = rows.filter((r) => r.n > 0).map((r) => r.cpu_sum / r.n);
251 const mem = rows.filter((r) => r.n > 0).map((r) => r.mem_sum / r.n);
252 const out: Record<string, unknown> = {};
253 const add = (k: string, v: unknown) => {
254 if (v !== undefined) out[k] = v;
255 };
256 add("tps", stats(tps));
257 add("mspt", stats(mspt));
258 add("cpu", stats(cpu));
259 add("memMiB", stats(mem));
260 out["peakPlayers"] = rows.reduce((m, r) => Math.max(m, r.players_max), 0);
261 out["errors"] = rows.reduce((s, r) => s + r.errors, 0);
262 out["joins"] = rows.reduce((s, r) => s + r.joins, 0);
263 return out;
264 }
265
266 /**
267 * Each service of a box: now (its last minute), the last hour and the last day. Compact by design:
268 * a handful of numbers a service, so a network of a dozen servers stays well under 4 KB.
269 */
270 export function metricsSummary(db: Database, box: Pick<GameBox, "id">, now = new Date()): Record<string, unknown> {
271 const minute = Math.floor(now.getTime() / 60_000);
272 const all = minutes(db, box.id, minute - 1440);
273 const services = [...new Set(all.map((r) => r.service))].sort();
274 const out: Record<string, unknown> = {};
275 for (const s of services) {
276 const rows = all.filter((r) => r.service === s);
277 const last = rows.at(-1)!;
278 const current = db
279 .query<{ players: string }, [string, string]>("SELECT players FROM game_service WHERE box_id = ?1 AND name = ?2")
280 .get(box.id, s);
281 out[s] = {
282 now: {
283 at: new Date(last.minute * 60_000).toISOString(),
284 players: last.players_last,
285 ...(last.tps_n > 0 ? { tps: round(last.tps_sum / last.tps_n) } : {}),
286 ...(last.mspt_n > 0 ? { mspt: round(last.mspt_sum / last.mspt_n) } : {}),
287 cpu: round(last.cpu_sum / Math.max(1, last.n)),
288 memMiB: Math.round(last.mem_sum / Math.max(1, last.n)),
289 online: (current?.players ?? "").split(",").filter(Boolean).slice(0, 10),
290 },
291 "1h": windowOf(rows.filter((r) => r.minute > minute - 60)),
292 "24h": windowOf(rows),
293 };
294 }
295 return out;
296 }
297
298 export const WINDOWS = { "1h": 60, "6h": 360, "24h": 1440, "7d": 10_080, "30d": 43_200 } as const;
299 export type Window = keyof typeof WINDOWS;
300
301 export interface Point {
302 readonly at: string;
303 readonly players: number;
304 readonly tps: number | null;
305 readonly mspt: number | null;
306 readonly cpu: number | null;
307 readonly memMiB: number | null;
308 readonly errors: number;
309 }
310
311 /** One service's series over a window, in at most `MAX_POINTS` buckets (empty buckets are left out). */
312 export function metricsSeries(db: Database, box: Pick<GameBox, "id">, service: string, window: Window, now = new Date()): Point[] {
313 const span = WINDOWS[window];
314 const minute = Math.floor(now.getTime() / 60_000);
315 const step = Math.max(1, Math.ceil(span / MAX_POINTS));
316 const rows = minutes(db, box.id, minute - span + 1, service);
317 const buckets = new Map<number, MinuteRow[]>();
318 for (const r of rows) {
319 const b = Math.floor((r.minute - (minute - span + 1)) / step);
320 (buckets.get(b) ?? (buckets.set(b, []), buckets.get(b)!)).push(r);
321 }
322 return [...buckets.entries()]
323 .sort((a, b) => a[0] - b[0])
324 .slice(-MAX_POINTS)
325 .map(([b, rs]) => {
326 const sum = (f: (r: MinuteRow) => number) => rs.reduce((s, r) => s + f(r), 0);
327 const tpsN = sum((r) => r.tps_n);
328 const msptN = sum((r) => r.mspt_n);
329 const n = sum((r) => r.n);
330 return {
331 at: new Date((minute - span + 1 + b * step) * 60_000).toISOString(),
332 players: Math.max(...rs.map((r) => r.players_max)),
333 tps: tpsN === 0 ? null : round(sum((r) => r.tps_sum) / tpsN),
334 mspt: msptN === 0 ? null : round(sum((r) => r.mspt_sum) / msptN),
335 cpu: n === 0 ? null : round(sum((r) => r.cpu_sum) / n),
336 memMiB: n === 0 ? null : Math.round(sum((r) => r.mem_sum) / n),
337 errors: sum((r) => r.errors),
338 };
339 });
340 }
341
342 /** The latest joins and leaves of a service (or the box), newest first. */
343 export const playerEvents = (
344 db: Database,
345 boxId: string,
346 service?: string,
347 limit = 20,
348 ): { service: string; player: string; kind: string; at: string }[] =>
349 service === undefined
350 ? db
351 .query<
352 { service: string; player: string; kind: string; at: string },
353 [string, number]
354 >("SELECT service, player, kind, at FROM game_player_event WHERE box_id = ?1 ORDER BY id DESC LIMIT ?2")
355 .all(boxId, limit)
356 : db
357 .query<
358 { service: string; player: string; kind: string; at: string },
359 [string, string, number]
360 >("SELECT service, player, kind, at FROM game_player_event WHERE box_id = ?1 AND service = ?2 ORDER BY id DESC LIMIT ?3")
361 .all(boxId, service, limit);
362
363 /** The latest error lines a service logged (from the log tail), newest first. */
364 export function recentErrors(db: Database, boxId: string, service: string, limit = 10): { line: string; at: string }[] {
365 const rows = db
366 .query<
367 { line: string; at: string },
368 [string, string]
369 >("SELECT line, at FROM game_log WHERE box_id = ?1 AND service = ?2 ORDER BY id DESC LIMIT 2000")
370 .all(boxId, service);
371 return rows
372 .filter((r) => parseLogLine(r.line)?.kind === "error")
373 .slice(0, limit)
374 .map((r) => ({ line: plain(r.line).slice(0, 300), at: r.at }));
375 }
src/games/metrics_answer.ts added +49
@@ -0,0 +1,49 @@
1 /**
2 * Game metrics as an agent reads them (the `games` tool, Talk): compact by default, and never more
3 * than `ANSWER_MAX` bytes, whatever the network's size. A summary keeps each service's now, 1 h and
4 * 24 h; a series is columns (one array a measure) on a fixed step, not a list of objects.
5 */
6
7 import type { Database } from "bun:sqlite";
8 import { metricsSeries, metricsSummary, type Window } from "./metrics.ts";
9 import type { GameBox } from "./store.ts";
10
11 /** The most bytes a metrics answer carries. */
12 export const ANSWER_MAX = 4_096;
13
14 const size = (v: unknown): number => new TextEncoder().encode(JSON.stringify(v)).length;
15
16 /** Each service the asker may see: now, 1 h, 24 h; the 24 h windows go first, then services, until it fits. */
17 export function compactMetrics(db: Database, box: Pick<GameBox, "id" | "name">, sees: (service: string) => boolean, now = new Date()): Record<string, unknown> {
18 const all = metricsSummary(db, box, now);
19 const services: Record<string, unknown> = {};
20 for (const [s, v] of Object.entries(all)) if (sees(s)) services[s] = v;
21 const out: Record<string, unknown> = { box: box.name, services };
22 if (size(out) <= ANSWER_MAX) return out;
23 for (const v of Object.values(services)) delete (v as Record<string, unknown>)["24h"];
24 out["trimmed"] = "24h left out to fit; ask one service for its detail";
25 while (size(out) > ANSWER_MAX && Object.keys(services).length > 1) delete services[Object.keys(services).at(-1)!];
26 return out;
27 }
28
29 /** One service over a window, as columns on a fixed step, halved until it fits. */
30 export function compactSeries(db: Database, box: Pick<GameBox, "id" | "name">, service: string, window: Window, now = new Date()): Record<string, unknown> {
31 let points = metricsSeries(db, box, service, window, now);
32 const shape = () => ({
33 box: box.name,
34 service,
35 window,
36 at: points.map((p) => p.at.slice(0, 16)),
37 players: points.map((p) => p.players),
38 tps: points.map((p) => p.tps),
39 mspt: points.map((p) => p.mspt),
40 memMiB: points.map((p) => p.memMiB),
41 errors: points.map((p) => p.errors),
42 });
43 let out = shape();
44 while (size(out) > ANSWER_MAX && points.length > 1) {
45 points = points.filter((_, i) => i % 2 === 1);
46 out = shape();
47 }
48 return out;
49 }
src/games/store.ts +2
@@ -412,6 +412,8 @@ export interface SyncBody {
412412 memMiB?: unknown;
413413 }[];
414414 readonly logs?: Record<string, unknown>;
415 /** Per service, the raw RCON answers the agent read (`list`, `tps`, `mspt`): `games/metrics.ts` parses them. */
416 readonly metrics?: Record<string, unknown>;
415417 readonly results?: readonly { id?: unknown; ok?: unknown; output?: unknown }[];
416418 readonly host?: Record<string, unknown>;
417419 /** The box's word about its boot, sent without jq when a tool is missing or by the boot's report. */
src/generated/migrations.ts +28 −26
@@ -443,19 +443,20 @@ import m438 from "../core/migrations/20261130170000-fence-read-from.ts";
443443 import m439 from "../core/migrations/20261130170100-chat-build-lane.ts";
444444 import m440 from "../core/migrations/20261130235220-run-check-plan.ts";
445445 import m441 from "../core/migrations/20261201000000-games.ts";
446 import m442 from "../core/migrations/20261201090000-app-vital-member.ts";
447 import m443 from "../core/migrations/20261201120000-first-change-forge.ts";
448 import m444 from "../core/migrations/20261201121000-repo-check-slots.ts";
449 import m445 from "../core/migrations/20261201130000-finding-touched.ts";
450 import m446 from "../core/migrations/20261201130000-game-box-boot.ts";
451 import m447 from "../core/migrations/20261201140000-app-registry-item.ts";
452 import m448 from "../core/migrations/20261201140000-infra-snapshot.ts";
453 import m449 from "../core/migrations/20261201140000-scan-finding-excerpt.ts";
454 import m450 from "../core/migrations/20261201150000-dns-record.ts";
455 import m451 from "../core/migrations/20261201150000-pinned-firewall.ts";
456 import m452 from "../core/migrations/20261201170000-managed-database.ts";
457 import m453 from "../core/migrations/20261201180000-game-box-diag.ts";
458 import m454 from "../core/migrations/20261201190500-runner-machine.ts";
446 import m442 from "../core/migrations/20261201050000-game-metrics.ts";
447 import m443 from "../core/migrations/20261201090000-app-vital-member.ts";
448 import m444 from "../core/migrations/20261201120000-first-change-forge.ts";
449 import m445 from "../core/migrations/20261201121000-repo-check-slots.ts";
450 import m446 from "../core/migrations/20261201130000-finding-touched.ts";
451 import m447 from "../core/migrations/20261201130000-game-box-boot.ts";
452 import m448 from "../core/migrations/20261201140000-app-registry-item.ts";
453 import m449 from "../core/migrations/20261201140000-infra-snapshot.ts";
454 import m450 from "../core/migrations/20261201140000-scan-finding-excerpt.ts";
455 import m451 from "../core/migrations/20261201150000-dns-record.ts";
456 import m452 from "../core/migrations/20261201150000-pinned-firewall.ts";
457 import m453 from "../core/migrations/20261201170000-managed-database.ts";
458 import m454 from "../core/migrations/20261201180000-game-box-diag.ts";
459 import m455 from "../core/migrations/20261201190500-runner-machine.ts";
459460
460461 /** Each migration file's name and its default export, in name order. */
461462 export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
@@ -901,17 +902,18 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
901902 ["20261130170100-chat-build-lane.ts", m439],
902903 ["20261130235220-run-check-plan.ts", m440],
903904 ["20261201000000-games.ts", m441],
904 ["20261201090000-app-vital-member.ts", m442],
905 ["20261201120000-first-change-forge.ts", m443],
906 ["20261201121000-repo-check-slots.ts", m444],
907 ["20261201130000-finding-touched.ts", m445],
908 ["20261201130000-game-box-boot.ts", m446],
909 ["20261201140000-app-registry-item.ts", m447],
910 ["20261201140000-infra-snapshot.ts", m448],
911 ["20261201140000-scan-finding-excerpt.ts", m449],
912 ["20261201150000-dns-record.ts", m450],
913 ["20261201150000-pinned-firewall.ts", m451],
914 ["20261201170000-managed-database.ts", m452],
915 ["20261201180000-game-box-diag.ts", m453],
916 ["20261201190500-runner-machine.ts", m454],
905 ["20261201050000-game-metrics.ts", m442],
906 ["20261201090000-app-vital-member.ts", m443],
907 ["20261201120000-first-change-forge.ts", m444],
908 ["20261201121000-repo-check-slots.ts", m445],
909 ["20261201130000-finding-touched.ts", m446],
910 ["20261201130000-game-box-boot.ts", m447],
911 ["20261201140000-app-registry-item.ts", m448],
912 ["20261201140000-infra-snapshot.ts", m449],
913 ["20261201140000-scan-finding-excerpt.ts", m450],
914 ["20261201150000-dns-record.ts", m451],
915 ["20261201150000-pinned-firewall.ts", m452],
916 ["20261201170000-managed-database.ts", m453],
917 ["20261201180000-game-box-diag.ts", m454],
918 ["20261201190500-runner-machine.ts", m455],
917919 ];
src/http/games_routes.ts +2
@@ -5,6 +5,7 @@
55
66 import { composeServices, readCompose } from "../games/compose.ts";
77 import { synced } from "../games/notify.ts";
8 import { recordMetrics } from "../games/metrics.ts";
89 import { boxByToken, envFiles, recordSync, signJarUrls, type SyncBody } from "../games/store.ts";
910 import { BODY_CAPS } from "../kernel/body_caps.ts";
1011 import {
@@ -23,6 +24,7 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
2324 if (sent === "too_large") return apiError("too_large", 413, "a sync is at most 200 log lines a service");
2425 const body = sent as SyncBody;
2526 const commands = recordSync(ctx.app.db, box, body);
27 recordMetrics(ctx.app.db, box, body);
2628 synced(ctx.app, box.id);
2729 const compose = await readCompose(ctx.app, box);
2830 const reply: Record<string, unknown> = {
src/http/mcp/tools/games.ts +15 −4
@@ -1,5 +1,7 @@
11 import { addPlugin, commitServiceEnv } from "../../../games/compose.ts";
22 import { boxStatus, boxStatusShared } from "../../../games/diag.ts";
3 import { compactMetrics, compactSeries } from "../../../games/metrics_answer.ts";
4 import { WINDOWS, type Window } from "../../../games/metrics.ts";
35 import { boxNamed, listBoxes, mayDo, queueCommand, roleOn, seesBox, SERVICE_NAME, servicesOf, type CommandKind } from "../../../games/store.ts";
46 import { good, bad, type Tool, str } from "../shared.ts";
57
@@ -8,12 +10,13 @@ const POWER = ["start", "stop", "restart", "recreate", "pull"];
810 export const tool: Tool = {
911 name: "games",
1012 listedTo: "admin",
11 doc: "`{ action, box?, service?, text?, kind?, key?, value?, modrinth? }`: game boxes. `list`; `console` queues `text` as RCON; `power` `kind` (start, stop, restart); `env` commits `key`=`value` (empty removes); `plugin` adds a `modrinth` slug. Grants as on /games",
13 doc: "`{ action, box?, service?, text?, kind?, key?, value?, modrinth?, window? }`: game boxes. `list`; `metrics` per service (now, 1h, 24h), or one `service` over `window` (1h to 30d); `console` queues `text` as RCON; `power` `kind` (start, stop, restart); `env` commits `key`=`value` (empty removes); `plugin` adds a `modrinth` slug. Grants as on /games",
1214 description: "Game boxes: list, console, power, env, plugins.",
1315 inputSchema: {
1416 type: "object",
1517 properties: {
16 action: { type: "string", enum: ["list", "console", "power", "env", "plugin"] },
18 action: { type: "string", enum: ["list", "metrics", "console", "power", "env", "plugin"] },
19 window: { type: "string", enum: Object.keys(WINDOWS) },
1720 box: { type: "string", maxLength: 40 },
1821 service: { type: "string", maxLength: 64 },
1922 text: { type: "string", maxLength: 1000 },
@@ -25,7 +28,7 @@ export const tool: Tool = {
2528 required: ["action"],
2629 },
2730 writes: true,
28 heldNotWhen: (args) => args["action"] === "list",
31 heldNotWhen: (args) => args["action"] === "list" || args["action"] === "metrics",
2932 async run(ctx, user, args) {
3033 const action = str(args["action"]);
3134 const db = ctx.app.db;
@@ -47,6 +50,14 @@ export const tool: Tool = {
4750 });
4851 const box = boxNamed(db, str(args["box"]));
4952 const service = str(args["service"]);
53 if (action === "metrics") {
54 if (box === undefined || !seesBox(db, user, box.id)) return bad("not_found", "no such box here");
55 if (service === "") return good(compactMetrics(db, box, (s) => mayDo(roleOn(db, user, box.id, s), "viewer")));
56 if (!SERVICE_NAME.test(service) || !mayDo(roleOn(db, user, box.id, service), "viewer")) return bad("not_found", "no such service here");
57 const window = (str(args["window"]) || "1h") as Window;
58 if (!(window in WINDOWS)) return bad("invalid", `window is one of ${Object.keys(WINDOWS).join(", ")}`);
59 return good(compactSeries(db, box, service, window));
60 }
5061 if (box === undefined || !seesBox(db, user, box.id) || !SERVICE_NAME.test(service)) return bad("not_found", "no such box or service here");
5162 if (!mayDo(roleOn(db, user, box.id, service), "operator")) return bad("forbidden", `you are not an operator of ${service} on ${box.name}`);
5263 if (action === "console") {
@@ -68,6 +79,6 @@ export const tool: Tool = {
6879 const done = await addPlugin(ctx.app, user, box, service, { modrinth: str(args["modrinth"]) });
6980 return done.ok ? good({ says: `Committed ${done.sha.slice(0, 10)}.`, sha: done.sha }) : bad("refused", done.error);
7081 }
71 return bad("bad_action", "action is list, console, power, env or plugin");
82 return bad("bad_action", "action is list, metrics, console, power, env or plugin");
7283 },
7384 };
src/tui/screens/games.ts +8 −1
@@ -30,6 +30,7 @@ import {
3030 type GameBox,
3131 type Role,
3232 } from "../../games/store.ts";
33 import { metricsSeries } from "../../games/metrics.ts";
3334 import type { Ctx, Screen } from "../app/app.ts";
3435 import { binding } from "../app/keys.ts";
3536 import { style } from "../term/style.ts";
@@ -39,6 +40,12 @@ import { fill, len, split } from "../ui/layout.ts";
3940 import { ListState, drawList, promptScreen, type ListRow } from "./common.ts";
4041 import type { PaletteEntry } from "./entries.ts";
4142
43 /** "4 online · 19.8 TPS · " from the last hour's numbers, or nothing before any. */
44 function playersTps(f: Session, box: { id: string }, service: string): string {
45 const last = metricsSeries(f.app.db, box, service, "1h").at(-1);
46 return last === undefined ? "" : `${last.players} online · ${last.tps === null ? "" : `${last.tps} TPS · `}`;
47 }
48
4249 export function gamesScreen(f: Session, ctx: Ctx): Screen {
4350 const state = new ListState();
4451 let note = "";
@@ -80,7 +87,7 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
8087 const view: ListRow[] = all.map(({ box, service }) => ({
8188 title: `${box.name}/${service.name}`,
8289 ...(service.state === "exited" ? { tone: "danger" as const } : {}),
83 secondary: `${service.state || "unknown"} · ${Math.round(service.memMiB)} MiB · ${service.cpuPct.toFixed(1)}% CPU`,
90 secondary: `${service.state || "unknown"} · ${playersTps(f, box, service.name)}${Math.round(service.memMiB)} MiB · ${service.cpuPct.toFixed(1)}% CPU`,
8491 meta: box.seenAt.slice(11, 19),
8592 }));
8693 drawList(s, list!, c, state, view);
src/web/pages/games.ts +40 −2
@@ -46,6 +46,21 @@ import { flashTo, page } from "../layout.ts";
4646 import { badge, btn, disclosure, field as input, row, rowList, time } from "../ui.ts";
4747 import { onSync } from "../../games/notify.ts";
4848 import { emptyLine } from "../empty_words.ts";
49 import { metricsSeries, playerEvents, recentErrors, type Point } from "../../games/metrics.ts";
50 import { daySpark } from "../studio/kpi_row.ts";
51
52 /** A small line of a series (oldest first); nothing when no point is known. */
53 const sparkOf = (points: readonly Point[], pick: (p: Point) => number | null, label: string): Html | null =>
54 daySpark(points.map(pick), label);
55
56 /** The last known value of a series. */
57 const lastOf = (points: readonly Point[], pick: (p: Point) => number | null): number | null => {
58 for (let i = points.length - 1; i >= 0; i--) {
59 const v = pick(points[i]!);
60 if (v !== null) return v;
61 }
62 return null;
63 };
4964
5065 const dollars = (cents: number): string => `$${(cents / 100).toFixed(2)}`;
5166 const mib = (n: number | undefined): string =>
@@ -128,12 +143,16 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> {
128143 visible.map((n) => {
129144 const s = seen.find((x) => x.name === n);
130145 const act = mayDo(roleOn(ctx.app.db, user, box.id, n), "operator");
146 const day = metricsSeries(ctx.app.db, box, n, "24h");
147 const tps = lastOf(day, (p) => p.tps);
148 const players = day.length === 0 ? null : day.at(-1)!.players;
131149 return row({
132150 href: `/games/${box.name}/${n}`,
133151 title: n,
134152 trail: badge(s?.state || "unknown", { tone: TONE[s?.state ?? ""] ?? "default" }),
135 meta: html`${mib(s?.memMiB)} ·
136 ${s === undefined ? "" : `${s.cpuPct.toFixed(1)}% CPU`}${s?.startedAt ? html` · up since ${time(s.startedAt)}` : ""}`,
153 meta: html`${players === null ? "" : `${players} online · `}${tps === null ? "" : `${tps.toFixed(1)} TPS · `}${mib(s?.memMiB)} ·
154 ${s === undefined ? "" : `${s.cpuPct.toFixed(1)}% CPU`}${s?.startedAt ? html` · up since ${time(s.startedAt)}` : ""}
155 ${day.length === 0 ? "" : html`<span class="bar muted">${sparkOf(day, (p) => p.players, `${n}: players over 24 hours`)}${sparkOf(day, (p) => p.tps, `${n}: TPS over 24 hours`)}${sparkOf(day, (p) => p.memMiB, `${n}: memory over 24 hours`)}</span>`}`,
137156 ...(act ? { after: power(box, n) } : {}),
138157 });
139158 }),
@@ -240,6 +259,7 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> {
240259 title: `${service} · ${box.name}`,
241260 scriptJs: gamesConsoleJs,
242261 body: html`${pageHead(service, { sub: `on ${box.name}`, actions: act ? power(box, service) : undefined })}
262 ${numbersBlock(ctx, box, service)}
243263 <section class="settings-block">
244264 <h2>Console</h2>
245265 <pre
@@ -319,6 +339,24 @@ ${tail.lines.join("\n")}${tail.lines.length > 0 ? "\n" : ""}</pre
319339 }));
320340 }
321341
342 /** A service's numbers: 24 hours of players, TPS, tick time and memory, then the latest joins and errors. */
343 function numbersBlock(ctx: Ctx, box: GameBox, service: string): Html {
344 const day = metricsSeries(ctx.app.db, box, service, "24h");
345 const joins = playerEvents(ctx.app.db, box.id, service, 8);
346 const errors = recentErrors(ctx.app.db, box.id, service, 5);
347 if (day.length === 0 && joins.length === 0 && errors.length === 0) return html``;
348 const line = (label: string, pick: (p: Point) => number | null, unit: string): Html => {
349 const now = lastOf(day, pick);
350 return row({ title: label, meta: html`${now === null ? "not reported" : `${now}${unit} now`} <span class="bar muted">${sparkOf(day, pick, `${label} over 24 hours`)}</span>` });
351 };
352 return html`<section class="settings-block">
353 <h2>Numbers, last 24 hours</h2>
354 ${rowList([line("Players", (p) => p.players, ""), line("TPS", (p) => p.tps, ""), line("Tick time", (p) => p.mspt, " ms"), line("Memory", (p) => p.memMiB, " MiB"), line("Errors a bucket", (p) => p.errors, "")])}
355 ${joins.length === 0 ? null : html`<h3>Joins and leaves</h3>${rowList(joins.map((j) => row({ title: j.player, meta: html`${j.kind === "join" ? "joined" : "left"} ${time(j.at)}` })))}`}
356 ${errors.length === 0 ? null : html`<h3>Latest errors</h3>${rowList(errors.map((e) => row({ title: html`<span class="mono">${e.line}</span>`, meta: time(e.at) })))}`}
357 </section>`;
358 }
359
322360 // GET /games/:box/:service/stream: new log lines and command results after each sync.
323361 export function gameServiceStream(ctx: Ctx): Response {
324362 const service = ctx.params.service ?? "";
test/game-metrics.test.ts added +240
@@ -0,0 +1,240 @@
1 /**
2 * Game metrics (forge games): the parsers on real Paper and Velocity answers, the minute rollup and
3 * its windows, the sync carrying `metrics` additively, and the size bounds of what an agent reads
4 * (a summary under 4 KB however many servers, a series under 4 KB however long the window).
5 */
6 import { Database } from "bun:sqlite";
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { createUser, getUserByName, type User } from "../src/core/users.ts";
13 import {
14 metricsSeries,
15 metricsSummary,
16 parseList,
17 parseLogLine,
18 parseMspt,
19 parseTps,
20 playerEvents,
21 recordMetrics,
22 stats,
23 } from "../src/games/metrics.ts";
24 import { ANSWER_MAX, compactMetrics, compactSeries } from "../src/games/metrics_answer.ts";
25 import { boxNamed, createGameBox } from "../src/games/store.ts";
26 import { createToken } from "../src/core/tokens.ts";
27 import { tool } from "../src/http/mcp/tools/games.ts";
28 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
29 import { quietLogs } from "./helpers/globals.ts";
30
31 quietLogs();
32
33 const size = (v: unknown): number => new TextEncoder().encode(JSON.stringify(v)).length;
34
35 describe("parsing what Paper and Velocity say", () => {
36 test("list, in the old and the new Paper words, colour codes and all", () => {
37 expect(parseList("There are 3 of a max of 20 players online: Alice, Bob, Carol_9")).toEqual({
38 online: 3,
39 max: 20,
40 names: ["Alice", "Bob", "Carol_9"],
41 });
42 expect(parseList("There are 0 of a max of 20 players online: ")).toEqual({ online: 0, max: 20, names: [] });
43 expect(parseList("§6There are §c2§6 out of maximum §c20§6 players online.\n§6default§r: §fAlice§r, §f[AFK] Bob")).toEqual({
44 online: 2,
45 max: 20,
46 names: ["Alice", "Bob"],
47 });
48 expect(parseList("\u001b[0;33mThere are 1 out of maximum 50 players online.\nadmin: ~Steve\u001b[0m")).toEqual({
49 online: 1,
50 max: 50,
51 names: ["Steve"],
52 });
53 expect(parseList('Unknown command. Type "/help" for help.')).toBeUndefined();
54 });
55
56 test("tps and mspt from Paper, colours and the capped star removed", () => {
57 expect(parseTps("§6TPS from last 1m, 5m, 15m: §a*20.0, §a19.97, §a19.99")).toBe(20);
58 expect(parseTps("TPS from last 1m, 5m, 15m: 17.42, 18.1, 19.0")).toBe(17.42);
59 expect(parseTps("Unknown or incomplete command")).toBeUndefined();
60 const mspt =
61 "§6Server tick times §e(§7avg§e/§7min§e/§7max§e)§6 from last 5s§7,§6 10s§7,§6 1m§e:\n§6◴ §a3.4§7/§a1.2§7/§a10.1§7, §a3.5§7/§a1.0§7/§a12.0§7, §a3.6§7/§a0.9§7/§a40.2";
62 expect(parseMspt(mspt)).toBe(3.4);
63 expect(parseMspt("Unknown command")).toBeUndefined();
64 });
65
66 test("joins, leaves, errors and warnings from the log lines", () => {
67 expect(parseLogLine("[12:00:01 INFO]: Alice joined the game")).toEqual({ kind: "join", player: "Alice" });
68 expect(parseLogLine("[12:05:01 INFO]: Alice left the game")).toEqual({ kind: "leave", player: "Alice" });
69 expect(parseLogLine("[12:00:00 INFO]: [connected player] Bob (/203.0.113.4:51234) has connected")).toEqual({
70 kind: "join",
71 player: "Bob",
72 });
73 expect(parseLogLine("[12:09:00 INFO]: [connected player] Bob (/203.0.113.4:51234) has disconnected")).toEqual({
74 kind: "leave",
75 player: "Bob",
76 });
77 expect(parseLogLine("[12:00:02 ERROR]: Could not pass event PlayerJoinEvent to Essentials")).toEqual({ kind: "error" });
78 expect(parseLogLine("[12:00:03 WARN]: Can't keep up! Is the server overloaded?")).toEqual({ kind: "warn" });
79 expect(parseLogLine("[Server thread/WARN]: Something odd")).toEqual({ kind: "warn" });
80 expect(parseLogLine("[12:00:04 INFO]: <Alice> I joined the game yesterday")).toBeUndefined();
81 expect(parseLogLine('[12:00:05 INFO]: Done (3.2s)! For help, type "help"')).toBeUndefined();
82 });
83
84 test("stats: min, avg, max, p95", () => {
85 expect(stats([])).toBeUndefined();
86 expect(stats([20, 20, 19, 10])).toEqual({ min: 10, avg: 17.3, max: 20, p95: 20 });
87 });
88 });
89
90 describe("the rollup", () => {
91 const db = new Database(":memory:");
92 beforeAll(async () => {
93 const m = await import("../src/core/migrations/20261201000000-games.ts");
94 const n = await import("../src/core/migrations/20261201050000-game-metrics.ts");
95 db.exec("CREATE TABLE user (id TEXT PRIMARY KEY, username TEXT)");
96 db.exec(m.default);
97 db.exec(n.default);
98 db.query("INSERT INTO game_service (box_id, name) VALUES ('b', 'hub')").run();
99 });
100
101 test("syncs within a minute roll into one row; the next minute is its own", () => {
102 const t0 = new Date("2026-12-01T01:00:05Z");
103 const body = (players: number, tps: string, cpu: number) => ({
104 services: [{ name: "hub", cpuPct: cpu, memMiB: 1000 }],
105 metrics: {
106 hub: {
107 list: `There are ${players} of a max of 20 players online: Alice`,
108 tps: `TPS from last 1m, 5m, 15m: ${tps}, 20, 20`,
109 mspt: "",
110 },
111 },
112 logs: { hub: ["[01:00:01 INFO]: Alice joined the game", "[01:00:02 ERROR]: boom"] },
113 });
114 recordMetrics(db, { id: "b" }, body(1, "20.0", 10), t0);
115 recordMetrics(db, { id: "b" }, body(3, "18.0", 30), new Date(t0.getTime() + 20_000));
116 recordMetrics(db, { id: "b" }, body(2, "19.0", 20), new Date(t0.getTime() + 60_000));
117 const rows = db
118 .query<
119 { minute: number; n: number; players_max: number; players_last: number; tps_min: number; errors: number; joins: number },
120 []
121 >("SELECT minute, n, players_max, players_last, tps_min, errors, joins FROM game_metric ORDER BY minute")
122 .all();
123 expect(rows.map((r) => [r.n, r.players_max, r.players_last, r.tps_min, r.errors, r.joins])).toEqual([
124 [2, 3, 3, 18, 2, 2],
125 [1, 2, 2, 19, 1, 1],
126 ]);
127 const series = metricsSeries(db, { id: "b" }, "hub", "1h", new Date(t0.getTime() + 61_000));
128 expect(series.map((p) => [p.players, p.tps, p.cpu, p.errors])).toEqual([
129 [3, 19, 20, 2],
130 [2, 19, 20, 1],
131 ]);
132 const summary = metricsSummary(db, { id: "b" }, new Date(t0.getTime() + 61_000)) as Record<
133 string,
134 { now: { players: number; tps: number; online: string[] }; "1h": { peakPlayers: number; errors: number } }
135 >;
136 expect(summary["hub"]!.now).toMatchObject({ players: 2, tps: 19, online: ["Alice"] });
137 expect(summary["hub"]!["1h"]).toMatchObject({ peakPlayers: 3, errors: 3 });
138 expect(playerEvents(db, "b", "hub").length).toBe(3);
139 });
140
141 test("a summary of a big network and a month's series stay under the answer bound", () => {
142 const start = Date.parse("2026-11-01T00:00:00Z");
143 const services = Array.from({ length: 40 }, (_, i) => `server-number-${i}`);
144 for (const s of services) db.query("INSERT INTO game_service (box_id, name) VALUES ('big', ?1)").run(s);
145 db.transaction(() => {
146 for (let m = 0; m < 1440; m += 5)
147 for (const s of services)
148 db.query(
149 "INSERT INTO game_metric (box_id, service, minute, n, players_max, players_last, players_n, tps_sum, tps_min, tps_n, mspt_sum, mspt_max, mspt_n, cpu_sum, mem_sum, errors) VALUES ('big', ?1, ?2, 1, 12, 11, 1, 19.5, 19.5, 1, 12.3, 12.3, 1, 33.3, 2048, 1)",
150 ).run(s, Math.floor(start / 60_000) + m);
151 })();
152 const at = new Date(start + 1440 * 60_000);
153 const all = compactMetrics(db, { id: "big", name: "big" }, () => true, at);
154 expect(size(all)).toBeLessThanOrEqual(ANSWER_MAX);
155 const month = compactSeries(db, { id: "big", name: "big" }, "server-number-0", "30d", at);
156 expect(size(month)).toBeLessThanOrEqual(ANSWER_MAX);
157 const day = compactSeries(db, { id: "big", name: "big" }, "server-number-0", "24h", at) as { at: string[]; tps: number[] };
158 expect(day.at.length).toBeGreaterThan(10);
159 expect(day.tps.every((v) => v === 19.5)).toBe(true);
160 });
161 });
162
163 describe("the sync and the tool", () => {
164 let dataDir = "";
165 let app: App;
166 let http: ForgeHttp;
167 let alice: User;
168 let token = "";
169 let admin = "";
170 let rpc = 1;
171 /** The games tool over the real MCP door, as alice's admin token. */
172 const call = async (args: Record<string, unknown>): Promise<{ text: string; value: any }> => {
173 const res = await http.handle(
174 new Request("http://forge.test/mcp", {
175 method: "POST",
176 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${admin}` },
177 body: JSON.stringify({ jsonrpc: "2.0", id: rpc++, method: "tools/call", params: { name: "games", arguments: args } }),
178 }),
179 );
180 const body: any = await res.json();
181 const text: string = body.result.content[0].text;
182 return { text, value: JSON.parse(text) };
183 };
184 beforeAll(async () => {
185 dataDir = await mkdtemp(join(tmpdir(), "forge-game-metrics-"));
186 app = createApp({ dataDir, port: 0 });
187 http = forgeHttp(app);
188 const made = await createUser(app.db, {
189 origin: "seed",
190 trusted: true,
191 username: "alice",
192 email: "[email protected]",
193 password: "a-good-passphrase",
194 adminIfFirst: true,
195 });
196 if (!made.ok) throw new Error(made.error);
197 alice = getUserByName(app.db, "alice")!;
198 admin = createToken(app.db, alice.id, "metrics", "admin").token;
199 token = createGameBox(app.db, { name: "net" }).token;
200 }, 30_000);
201 afterAll(async () => {
202 app.close();
203 await rm(dataDir, { recursive: true, force: true });
204 });
205
206 test("a sync with metrics is stored; one without them is still answered (agent: 1 stays compatible)", async () => {
207 const send = (body: unknown) =>
208 http.handle(
209 new Request("http://forge.test/api/v1/games/agent/sync", {
210 method: "POST",
211 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
212 body: JSON.stringify(body),
213 }),
214 );
215 expect((await send({ agent: 1, services: [{ name: "hub", state: "running", cpuPct: 5, memMiB: 900 }] })).status).toBe(200);
216 expect(
217 (
218 await send({
219 agent: 1,
220 services: [{ name: "hub", state: "running", cpuPct: 5, memMiB: 900 }],
221 metrics: {
222 hub: {
223 list: "There are 4 of a max of 20 players online: A, B, C, D",
224 tps: "TPS from last 1m, 5m, 15m: 19.8, 20, 20",
225 mspt: "",
226 },
227 },
228 })
229 ).status,
230 ).toBe(200);
231 const box = boxNamed(app.db, "net")!;
232 const got = await call({ action: "metrics", box: "net" });
233 expect(got.value.services["hub"].now).toMatchObject({ players: 4, tps: 19.8 });
234 expect(new TextEncoder().encode(got.text).length).toBeLessThan(6_144);
235 const detail = await call({ action: "metrics", box: "net", service: "hub", window: "1h" });
236 expect(detail.value.players.at(-1)).toBe(4);
237 expect(tool.heldNotWhen?.({ action: "metrics" })).toBe(true);
238 expect(box.name).toBe("net");
239 });
240 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs