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

Games survival step 2b: read FabricExporter Prometheus metrics at check-in so TPS and tick time show on the games page #18116

opened this

Merged 9h 37m ago, live in production

scout/forge:scout/18088-games-survival-step-2b-read-fabricexport → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/18088-games-survival-step-2b-read-fabricexport was merged into main as 0d92810.

Review

Sign in to review this change.
6 files changed +108 −11
docs/features/games.md +2 −2
@@ -163,9 +163,9 @@ A plugin or jar runs code on the game server; give operator only to people you t
163163
164164 ## Numbers
165165
166 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, deaths, chat, errors and warnings in the log lines (`src/games/metrics.ts`), each read only right after the head the server itself writes at a line's start (`[12:00:01 INFO]: `), so chat that reads "[x] Alice joined the game" stays chat. A row a minute a service is kept 30 days (`game_metric`), and each join and leave (`game_player_event`).
166 Each sync, the agent asks every running server with `rcon-cli` for `list`, `tps` and `mspt` (Paper; a Fabric server, which has neither, is read at FabricExporter's Prometheus page inside its container, the tick and TPS lines only, `parsePrometheus`) 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, deaths, chat, errors and warnings in the log lines (`src/games/metrics.ts`), each read only right after the head the server itself writes at a line's start (`[12:00:01 INFO]: `), so chat that reads "[x] Alice joined the game" stays chat. **A Fabric server shows no TPS or tick time unless FabricExporter (a Prometheus exporter mod) is installed on it**; it is not installed by the forge. The agent reads `http://127.0.0.1:25585/metrics` inside the server's container (port 25585 is what the agent assumes, so the exporter must listen there, on that address) with `curl`, which the image must have. Only these names are read, unlabelled: `mc_`/`minecraft_` then optional `server_` then `tps`, or `tick_time`/`tick_duration`/`mspt` ending `_ms`, `_milliseconds` or (tick only) `_seconds`. A mod that spells them otherwise shows no numbers and no error; those spellings were not checked against a captured page. A row a minute a service is kept 30 days (`game_metric`), and each join and leave (`game_player_event`).
167167
168 `/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`).
168 `/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, TPS and tick time. 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`).
169169
170170 ## Who may do what
171171
src/games/agent.sh +9 −2
@@ -522,7 +522,7 @@ running() { capped 5 "${COMPOSE[@]}" ps --status running --format '{{.Service}}'
522522 # them (games/metrics.ts). A service without rcon-cli (the Velocity proxy) is asked once, then not.
523523 NORCON=" "
524524 metrics() {
525 local out='{}' name list tps mspt
525 local out='{}' name list tps mspt prom
526526 # Every list is read from fd 3: `docker compose exec` takes all of stdin, the rest of the list with it.
527527 while IFS= read -r name <&3; do
528528 [[ "$name" =~ $SAFE ]] || continue
@@ -536,7 +536,14 @@ metrics() {
536536 fi
537537 tps="$(capped 5 "${COMPOSE[@]}" exec -T "$name" rcon-cli -- tps 2>/dev/null || true)"
538538 mspt="$(capped 5 "${COMPOSE[@]}" exec -T "$name" rcon-cli -- mspt 2>/dev/null || true)"
539 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")"
539 # A Fabric server has neither command: FabricExporter's Prometheus page (127.0.0.1:25585, inside the
540 # container only), cut to the tick and TPS lines, is read when `tps` said nothing. The grep is looser
541 # than `parsePrometheus` (src/games/metrics.ts), which alone decides what counts; extra lines are dropped there.
542 prom=""
543 if [[ "$tps" != *TPS* ]]; then
outdated

The grep is looser than parsePrometheus. Say in the comment that the parser decides. Also the exporter's port and the need to install it are not documented anywhere a person will read.

544 prom="$(capped 5 "${COMPOSE[@]}" exec -T "$name" curl -fs -m 3 http://127.0.0.1:25585/metrics 2>/dev/null | grep -E '^(mc|minecraft)_[a-z_]*(tps|tick|mspt)[a-z_]* [0-9]' | head -c 4000 || true)"
545 fi
546 out="$(jq -c --arg n "$name" --arg l "${list:0:4000}" --arg t "${tps:0:1000}" --arg m "${mspt:0:2000}" --arg p "$prom" '. + {($n): {list: $l, tps: $t, mspt: $m, prom: $p}}' <<<"$out")"
540547 done 3< <(running)
541548 echo "$out"
542549 }
src/games/metrics.ts +41 −5
@@ -1,8 +1,9 @@
11 /**
22 * Game metrics (forge games): what each service of a game box does, so a person, the crew and Talk
33 * 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.
4 * `tps` and `mspt` (Paper), or a Fabric server's exporter page (`prom`), beside the CPU, memory and
5 * log lines it already sends; everything is parsed here, so the agent stays a shell script and the
6 * parsers are tested in one place.
67 *
78 * Kept per box and service, a row a minute (`game_metric`, sums and counts, so a minute is rolled
89 * up as syncs arrive), 30 days; and each join and leave (`game_player_event`). Read back as a
@@ -78,6 +79,37 @@ export function parseMspt(raw: string): number | undefined {
7879 return m === null ? undefined : Number(m[1]);
7980 }
8081
82 /**
83 * FabricExporter's Prometheus text (a Fabric server has no `tps` command): ticks a second and tick
84 * time in milliseconds, whichever the exporter names. A tick time in seconds is turned to ms, and
85 * a server that reports only tick time gets the TPS that time allows (at most 20). Labelled
86 * samples (per dimension) are skipped: the first plain sample of each name wins.
87 *
outdated

These exporter metric names are not backed by a sample or a documented source. A wrong name gives silent empty numbers. Add a real fixture, or cite where the names come from, and document in docs/features/games.md that FabricExporter must be installed.

88 * Source of the names: NOT verified against a captured FabricExporter page (no sample was reachable
89 * from where this was written). They are the conventional Prometheus spellings, so a mod that names
90 * them otherwise yields no numbers and no error; `test/game-metrics.test.ts` pins the spellings
91 * accepted. The agent's grep is looser than this: this parser decides what counts.
92 */
93 const PROM_TPS = /^(?:mc|minecraft)_(?:server_)?tps$/;
94 const PROM_TICK_MS = /^(?:mc|minecraft)_(?:server_)?(?:tick_(?:time|duration)|mspt)_(?:ms|milliseconds)$/;
95 const PROM_TICK_S = /^(?:mc|minecraft)_(?:server_)?tick_(?:time|duration)_seconds$/;
96 export function parsePrometheus(raw: string): { tps?: number; mspt?: number } {
97 const out: { tps?: number; mspt?: number } = {};
98 for (const line of raw.slice(0, 64_000).split("\n")) {
99 const m = /^([a-zA-Z_:][a-zA-Z0-9_:]*)\s+([-+0-9.eE]+|NaN|[+-]?Inf)\s*$/.exec(line.trim());
100 if (m === null) continue;
101 const v = Number(m[2]);
102 if (!Number.isFinite(v) || v < 0) continue;
103 const name = m[1]!;
104 if (PROM_TPS.test(name)) out.tps ??= Math.min(20, v);
105 else if (PROM_TICK_MS.test(name)) out.mspt ??= v;
106 else if (PROM_TICK_S.test(name)) out.mspt ??= v * 1000;
107 }
108 if (out.mspt !== undefined) out.mspt = Math.round(out.mspt * 100) / 100;
109 if (out.tps === undefined && out.mspt !== undefined && out.mspt > 0) out.tps = Math.round(Math.min(20, 1000 / out.mspt) * 10) / 10;
110 return out;
111 }
112
81113 /** What a service's log says happened to or by a player, kept as an event (`game_player_event`). */
82114 export type PlayerEventKind = "join" | "leave" | "chat" | "death" | "kick" | "command" | "refused" | "wake" | "stuck" | "start";
83115
@@ -155,7 +187,10 @@ export function parseLogLine(line: string): LogFact {
155187 export interface MetricsBody {
156188 readonly services?: readonly { name?: unknown; cpuPct?: unknown; memMiB?: unknown }[];
157189 readonly logs?: Record<string, unknown>;
158 /** Per service, the raw RCON answers: `list`, `tps`, `mspt` (any may be missing). */
190 /**
191 * Per service, the raw RCON answers: `list`, `tps`, `mspt` (any may be missing), and `prom`,
192 * FabricExporter's Prometheus text.
193 */
159194 readonly metrics?: Record<string, unknown>;
160195 }
161196
@@ -186,8 +221,9 @@ export function recordMetrics(db: Database, box: Pick<GameBox, "id">, body: Metr
186221 r.names = list.names;
187222 r.online = list.players;
188223 }
189 r.tps = parseTps(text(m["tps"]));
190 r.mspt = parseMspt(text(m["mspt"]));
224 const prom = parsePrometheus(text(m["prom"], 16_000));
225 r.tps = parseTps(text(m["tps"])) ?? prom.tps;
226 r.mspt = parseMspt(text(m["mspt"])) ?? prom.mspt;
191227 }
192228 const tpsRead = [...rows.values()].flatMap((r) => (r.tps === undefined ? [] : [r.tps]));
193229 const msptRead = [...rows.values()].flatMap((r) => (r.mspt === undefined ? [] : [r.mspt]));
src/tui/screens/games.ts +2 −2
@@ -72,10 +72,10 @@ import type { PaletteEntry } from "./entries.ts";
7272 import { gameConfigScreen } from "./game_config.ts";
7373 import { gameModsScreen } from "./game_mods.ts";
7474
75 /** "4 online · 19.8 TPS · " from the last hour's numbers, or nothing before any. */
75 /** "4 online · 19.8 TPS · 3.1 ms tick" from the last hour's numbers, or nothing before any. */
7676 function playersTps(f: Session, box: { id: string }, service: string): string[] {
7777 const last = metricsSeries(f.app.db, box, service, "1h").at(-1);

New behaviour (tick time in the terminal) with no test that would fail without it. Add a screen test that expects ms tick, and one where mspt is null so the segment is absent.

78 return last === undefined ? [] : [`${last.players} online`, ...(last.tps === null ? [] : [`${last.tps} TPS`])];
78 return last === undefined ? [] : [`${last.players} online`, ...(last.tps === null ? [] : [`${last.tps} TPS`]), ...(last.mspt === null ? [] : [`${last.mspt} ms tick`])];
7979 }
8080
8181 export function gamesScreen(f: Session, ctx: Ctx): Screen {
test/game-metrics.test.ts +32
@@ -16,6 +16,7 @@ import {
1616 parseList,
1717 parseLogLine,
1818 parseMspt,
19 parsePrometheus,
1920 parseTps,
2021 playerEvents,
2122 recordMetrics,
@@ -53,6 +54,13 @@ describe("parsing what Paper and Velocity say", () => {
5354 expect(parseList('Unknown command. Type "/help" for help.')).toBeUndefined();
5455 });
5556
57 test("tps and tick time from FabricExporter's Prometheus text", () => {
58 const raw = ["# HELP mc_tps ticks", "# TYPE mc_tps gauge", "mc_tps 19.87", 'mc_tick_time_ms{dim="x"} 99', "mc_tick_time_ms 12.345", ""].join("\n");
59 expect(parsePrometheus(raw)).toEqual({ tps: 19.87, mspt: 12.35 });
60 expect(parsePrometheus("minecraft_tick_duration_seconds 0.1")).toEqual({ tps: 10, mspt: 100 });
61 expect(parsePrometheus("mc_tps NaN\nnothing 3")).toEqual({});
62 });
63
5664 test("tps and mspt from Paper, colours and the capped star removed", () => {
5765 expect(parseTps("§6TPS from last 1m, 5m, 15m: §a*20.0, §a19.97, §a19.99")).toBe(20);
5866 expect(parseTps("TPS from last 1m, 5m, 15m: 17.42, 18.1, 19.0")).toBe(17.42);
@@ -102,6 +110,30 @@ describe("the rollup", () => {
102110 db.query("INSERT INTO game_service (box_id, name) VALUES ('b', 'hub')").run();
103111 });
104112
113 test("a Fabric server's tick numbers are recorded when Paper's commands said nothing", () => {
114 db.query("INSERT INTO game_service (box_id, name) VALUES ('fab', 'hub')").run();
115 recordMetrics(db, { id: "fab" }, { metrics: { hub: { list: "", tps: "Unknown command", mspt: "", prom: "mc_tps 18.5\nmc_tick_time_ms 7.5" } } }, new Date("2026-12-03T01:00:00Z"));
116 const last = metricsSeries(db, { id: "fab" }, "hub", "1h", new Date("2026-12-03T01:00:30Z")).at(-1);
117 expect(last?.tps).toBe(18.5);
118 expect(last?.mspt).toBe(7.5);
119 db.query("DELETE FROM game_metric WHERE box_id = 'fab'").run();
120 });
121
122 test("the prom field is cut at 16 KB and a non-string is nothing: a number past the cut is never read", () => {
123 db.query("INSERT INTO game_service (box_id, name) VALUES ('big', 'hub')").run();
124 const at = new Date("2026-12-03T02:00:00Z");
125 const read = (prom: unknown) => {
126 db.query("DELETE FROM game_metric WHERE box_id = 'big'").run();
127 recordMetrics(db, { id: "big" }, { metrics: { hub: { list: "", tps: "", mspt: "", prom } } }, at);
128 return metricsSeries(db, { id: "big" }, "hub", "1h", new Date("2026-12-03T02:00:30Z")).at(-1)?.tps ?? null;
129 };
130 expect(read("# pad\n".repeat(3_400) + "mc_tps 12\n")).toBeNull(); // 20 KB: the sample sits past 16 000
131 expect(read("mc_tps 12\n" + "# pad\n".repeat(3_400))).toBe(12);
132 expect(read(12345)).toBeNull();
133 expect(read({ mc_tps: 12 })).toBeNull();
134 db.query("DELETE FROM game_metric WHERE box_id = 'big'").run();
135 });
136
105137 test("syncs within a minute roll into one row; the next minute is its own", () => {
106138 const t0 = new Date("2026-12-01T01:00:05Z");
107139 const body = (players: number, tps: string, cpu: number) => ({
test/tui-games.test.ts +22
@@ -17,6 +17,7 @@ import { readCompose, serviceEnv } from "../src/games/compose.ts";
1717 import { WAKE_GRACE_MS } from "../src/games/heal.ts";
1818 import { lentRunnerOf } from "../src/games/lend.ts";
1919 import { boxNamed, createGameBox, grant, grantsOf, recentCommands, recordSync } from "../src/games/store.ts";
20 import { recordMetrics } from "../src/games/metrics.ts";
2021 import { queueWorld } from "../src/games/worlds.ts";
2122 import { createForgeApp } from "../src/tui/forge.ts";
2223 import { sha256 } from "../src/kernel/hash.ts";
@@ -370,3 +371,24 @@ test("the terminal's box screen shows the switch Run checks while servers sleep
370371 operator.tui.stop?.();
371372 }
372373 });
374
375 test("the Games list says tick time after TPS when a Fabric exporter gave it, and no tick segment when it did not", async () => {
376 const box = boxNamed(app.db, "net")!;
377 const line = async () => {
378 const { tui, session } = drive(alice, 200);
379 tui.ctx.push(gamesScreen(session, tui.ctx));
380 await settleApp(tui);
381 const text = tui.screen.toText();
382 tui.stop?.();
383 return text.split("\n").find((l) => l.includes("net/hub")) ?? "";
384 };
385 app.db.query("DELETE FROM game_metric WHERE box_id = ?").run(box.id);
386 recordMetrics(app.db, box, { metrics: { hub: { list: "", tps: "Unknown command", mspt: "", prom: "mc_tps 18.5\nmc_tick_time_ms 7.5" } } }, new Date());
387 expect(await line()).toContain("18.5 TPS · 7.5 ms tick");
388 app.db.query("DELETE FROM game_metric WHERE box_id = ?").run(box.id);
389 recordMetrics(app.db, box, { metrics: { hub: { list: "", tps: "TPS from last 1m, 5m, 15m: *19.0, 19.0, 19.0", mspt: "" } } }, new Date());
390 const bare = await line();
391 expect(bare).toContain("19 TPS");
392 expect(bare).not.toContain("ms tick");
393 app.db.query("DELETE FROM game_metric WHERE box_id = ?").run(box.id);
394 });

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

Keyboard shortcuts

Docs