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

A box's TPS and tick time show live on its games pane, from spark's health report or `/spark tps` at check-in #18143

opened this

Merged 9h 36m ago, live in production

torque/forge:torque/18141-a-box-s-tps-and-tick-time-show-live-on-i → main 0 commits fork 1 thread · 1 unresolved

  • Merged. torque/18141-a-box-s-tps-and-tick-time-show-live-on-i was merged into main as f7e559b.

Review

Sign in to review this change.
6 files changed +115 −13
docs/features/games.md +1 −1
@@ -165,7 +165,7 @@ A plugin or jar runs code on the game server; give operator only to people you t
165165
166166 ## Numbers
167167
168 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`).
168 Each sync, the agent asks every running server with `rcon-cli` for `list`, `tps` and `mspt` (Paper; when `tps` says nothing the agent asks `spark tps`, and `parseSpark` reads the 1 m TPS and the 10 s median tick time, or nothing when the lines do not line up, so the pane says "not reported" rather than a wrong number (#18141); 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`).
169169
170170 `/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`).
171171
src/games/agent.sh +9 −4
@@ -518,11 +518,11 @@ logs() {
518518 # shell and no rcon-cli: an exec into it only fills Docker's journal with errors.
519519 running() { capped 5 "${COMPOSE[@]}" ps --status running --format '{{.Service}}' 2>/dev/null | grep -vx 'forge-waker'; }
520520
521 # Each running service's RCON answers to `list`, `tps` and `mspt` (Paper), raw: the forge parses
521 # Each running service's RCON answers to `list`, `tps` and `mspt` (Paper) and, when `tps` said nothing, `spark tps`, raw: the forge parses
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 prom
525 local out='{}' name list tps mspt spark 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
@@ -539,11 +539,16 @@ metrics() {
539539 # A Fabric server has neither command: FabricExporter's Prometheus page (127.0.0.1:25585, inside the
540540 # container only), cut to the tick and TPS lines, is read when `tps` said nothing. The grep is looser
541541 # than `parsePrometheus` (src/games/metrics.ts), which alone decides what counts; extra lines are dropped there.
542 prom=""
542 # spark (a plugin or mod many servers run instead) answers `spark tps` with both; asked only when `tps` said nothing.

This spark comment is inside the Fabric comment block, which the next lines still describe. Move it directly above spark="" and keep the Fabric comment above prom="".

543 spark=""
543544 if [[ "$tps" != *TPS* ]]; then
545 spark="$(capped 5 "${COMPOSE[@]}" exec -T "$name" rcon-cli -- spark tps 2>/dev/null || true)"
546 fi
547 prom=""
548 if [[ "$tps" != *TPS* && "$spark" != *TPS* ]]; then
544549 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)"
545550 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")"
551 out="$(jq -c --arg n "$name" --arg l "${list:0:4000}" --arg t "${tps:0:1000}" --arg m "${mspt:0:2000}" --arg s "${spark:0:2000}" --arg p "$prom" '. + {($n): {list: $l, tps: $t, mspt: $m, spark: $s, prom: $p}}' <<<"$out")"
547552 done 3< <(running)
548553 echo "$out"
549554 }
src/games/metrics.ts +48 −7
@@ -1,9 +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), 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.
4 * `tps` and `mspt` (Paper), spark's `spark tps`, or a Fabric server's exporter page (`prom`),
5 * beside the CPU, memory and log lines it already sends; everything is parsed here, so the agent
6 * stays a shell script and the parsers are tested in one place.
77 *
88 * Kept per box and service, a row a minute (`game_metric`, sums and counts, so a minute is rolled
99 * up as syncs arrive), 30 days; and each join and leave (`game_player_event`). Read back as a
@@ -79,6 +79,46 @@ export function parseMspt(raw: string): number | undefined {
7979 return m === null ? undefined : Number(m[1]);
8080 }
8181
82 /**
83 * spark's `/spark tps` (or the TPS and tick lines of its health report), the plugin or mod many
84 * servers run in place of Paper's own commands: "TPS from last 5s, 10s, 1m, 5m, 15m:" and the
85 * values on the next line, then "Tick durations (min/med/95%ile/max ms) from last 10s, 1m:" and
86 * their groups (the 10 s one first, separated by ";"). The TPS is the 1 m figure, the tick time the
87 * median of the 10 s group. Each line may begin with spark's "[⚡]" tag. Anything that does not
88 * line up (a label with no value, a count that differs, a figure that is no sane number) gives
89 * nothing for that field, never a guess.
90 */
91 export function parseSpark(raw: string): { tps?: number; mspt?: number } {
92 const lines = plain(raw)
93 .slice(0, 4_000)
94 .split("\n")
95 .map((l) => l.replace(/^\s*\[[^\]]*\]\s*/, "").trim())
96 .filter((l) => l !== "");
97 const out: { tps?: number; mspt?: number } = {};
98 const figures = (s: string, sep: RegExp): number[] | undefined => {
99 const parts = s.split(sep).map((p) => p.trim().replace(/^\*/, ""));
100 const nums = parts.map((p) => (/^[0-9]+(?:\.[0-9]+)?$/.test(p) ? Number(p) : Number.NaN));
101 return nums.length > 0 && nums.every((n) => Number.isFinite(n) && n <= 1_000) ? nums : undefined;
102 };
103 const tpsAt = lines.findIndex((l) => /^TPS from last\b[^:]*:/i.test(l));
104 if (tpsAt >= 0) {
105 const head = lines[tpsAt]!;
106 const labels = head.slice(head.indexOf("last") + 4, head.indexOf(":")).split(",").map((s) => s.trim());
107 // The values are on the header's own line or the next.
108 const values = figures(head.slice(head.indexOf(":") + 1).trim() === "" ? (lines[tpsAt + 1] ?? "") : head.slice(head.indexOf(":") + 1), /,/);
109 const at = labels.indexOf("1m");
110 if (values !== undefined && at >= 0 && values.length === labels.length && values[at]! <= 100) out.tps = values[at]!;
111 }
112 const tickAt = lines.findIndex((l) => /^Tick durations \(min\/med\/95%ile\/max ms\)/i.test(l));
113 if (tickAt >= 0) {
114 const after = lines[tickAt]!.slice(lines[tickAt]!.indexOf(")") + 1);
115 const body = /:\s*(\S.*)$/.exec(after)?.[1] ?? lines[tickAt + 1] ?? "";
116 const first = figures(body.split(";")[0]!, /\//);
117 if (first !== undefined && first.length === 4) out.mspt = first[1]!;
118 }
119 return out;
120 }
121
82122 /**
83123 * FabricExporter's Prometheus text (a Fabric server has no `tps` command): ticks a second and tick
84124 * time in milliseconds, whichever the exporter names. A tick time in seconds is turned to ms, and
@@ -188,8 +228,8 @@ export interface MetricsBody {
188228 readonly services?: readonly { name?: unknown; cpuPct?: unknown; memMiB?: unknown }[];
189229 readonly logs?: Record<string, unknown>;
190230 /**
191 * Per service, the raw RCON answers: `list`, `tps`, `mspt` (any may be missing), and `prom`,
192 * FabricExporter's Prometheus text.
231 * Per service, the raw RCON answers: `list`, `tps`, `mspt` and `spark` (spark's `spark tps`; any
232 * may be missing), and `prom`, FabricExporter's Prometheus text.
193233 */
194234 readonly metrics?: Record<string, unknown>;
195235 }
@@ -222,8 +262,9 @@ export function recordMetrics(db: Database, box: Pick<GameBox, "id">, body: Metr
222262 r.online = list.players;
223263 }
224264 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;
265 const spark = parseSpark(text(m["spark"], 2_000));
266 r.tps = parseTps(text(m["tps"])) ?? spark.tps ?? prom.tps;
267 r.mspt = parseMspt(text(m["mspt"])) ?? spark.mspt ?? prom.mspt;
227268 }
228269 const tpsRead = [...rows.values()].flatMap((r) => (r.tps === undefined ? [] : [r.tps]));
229270 const msptRead = [...rows.values()].flatMap((r) => (r.mspt === undefined ? [] : [r.mspt]));
src/games/store.ts +4 −1
@@ -603,7 +603,10 @@ export interface SyncBody {
603603 cpuLimit?: unknown;
604604 }[];
605605 readonly logs?: Record<string, unknown>;
606 /** Per service, the raw RCON answers the agent read (`list`, `tps`, `mspt`): `games/metrics.ts` parses them. */
606 /**
607 * Per service, the raw RCON answers the agent read (`list`, `tps`, `mspt`, `spark`):
608 * `games/metrics.ts` parses them.
609 */
607610 readonly metrics?: Record<string, unknown>;
608611 /** Each server's whitelist, ops and bans, and the proxy's glist (`people.ts`). */
609612 readonly people?: unknown;
test/game-metrics.test.ts +31
@@ -17,6 +17,7 @@ import {
1717 parseLogLine,
1818 parseMspt,
1919 parsePrometheus,
20 parseSpark,
2021 parseTps,
2122 playerEvents,
2223 recordMetrics,
@@ -110,6 +111,36 @@ describe("the rollup", () => {
110111 db.query("INSERT INTO game_service (box_id, name) VALUES ('b', 'hub')").run();
111112 });
112113
114 const SPARK = [
115 "§8[§e⚡§8] §7TPS from last 5s, 10s, 1m, 5m, 15m:",
116 "§8[§e⚡§8] §a*20.0§7, §a19.9§7, §a19.4§7, §a19.8§7, §a20.0",
117 "§8[§e⚡§8] §7Tick durations (min/med/95%ile/max ms) from last 10s, 1m:",
118 "§8[§e⚡§8] §a0.8§7/§a4.1§7/§a9.3§7/§c31.0§7; §a0.7§7/§a3.9§7/§a8.8§7/§c40.2",
119 "§8[§e⚡§8] §7CPU usage from last 10s, 1m, 15m:",
120 "§8[§e⚡§8] §a12%§7, §a10%§7, §a9%",
121 ].join("\n");
122
123 test("tps and tick time from recorded /spark tps output, and nothing from a garbled one", () => {
124 expect(parseSpark(SPARK)).toEqual({ tps: 19.4, mspt: 4.1 });
125 expect(parseSpark("TPS from last 5s, 10s, 1m, 5m, 15m:\n 20.0, 20.0, abc, 20.0, 20.0")).toEqual({});
126 expect(parseSpark("TPS from last 5s, 10s, 1m, 5m, 15m:\n 20.0, 20.0")).toEqual({});
127 expect(parseSpark("Tick durations (min/med/95%ile/max ms) from last 10s, 1m:\n 1/2/x/4; 1/2/3/4")).toEqual({});
128 expect(parseSpark("Unknown command. Type \"/help\" for help.")).toEqual({});
129 expect(parseSpark("")).toEqual({});
130 });
131
132 test("a sync's spark answer is recorded, and a garbled one records no number", () => {
133 db.query("INSERT INTO game_service (box_id, name) VALUES ('sp', 'hub')").run();
134 recordMetrics(db, { id: "sp" }, { metrics: { hub: { list: "", tps: "Unknown command", mspt: "", spark: SPARK } } }, new Date("2026-12-03T03:00:00Z"));
135 const last = metricsSeries(db, { id: "sp" }, "hub", "1h", new Date("2026-12-03T03:00:30Z")).at(-1);
136 expect([last?.tps, last?.mspt]).toEqual([19.4, 4.1]);
137 db.query("INSERT INTO game_service (box_id, name) VALUES ('sg', 'hub')").run();
138 recordMetrics(db, { id: "sg" }, { metrics: { hub: { list: "", spark: "TPS from last 5s, 10s, 1m, 5m, 15m:\n 2?.0, x, y" } } }, new Date("2026-12-03T03:00:00Z"));
139 const bad = metricsSeries(db, { id: "sg" }, "hub", "1h", new Date("2026-12-03T03:00:30Z")).at(-1);
140 expect([bad?.tps, bad?.mspt]).toEqual([null, null]);
141 db.query("DELETE FROM game_metric WHERE box_id IN ('sp', 'sg')").run();
142 });
143
113144 test("a Fabric server's tick numbers are recorded when Paper's commands said nothing", () => {
114145 db.query("INSERT INTO game_service (box_id, name) VALUES ('fab', 'hub')").run();
115146 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"));
test/tui-games.test.ts +22
@@ -394,6 +394,28 @@ test("the Games list says tick time after TPS when a Fabric exporter gave it, an
394394 app.db.query("DELETE FROM game_metric WHERE box_id = ?").run(box.id);
395395 });
396396
397 test("the Games list shows TPS and tick time from recorded /spark tps output, and a garbled answer shows neither (#18141)", async () => {
398 const box = boxNamed(app.db, "net")!;
399 const line = async () => {
400 const { tui, session } = drive(alice, 200);
401 tui.ctx.push(gamesScreen(session, tui.ctx));
402 await settleApp(tui);
403 const text = tui.screen.toText();
404 tui.stop?.();
405 return text.split("\n").find((l) => l.includes("net/hub")) ?? "";
406 };
407 const spark = "[⚡] TPS from last 5s, 10s, 1m, 5m, 15m:\n[⚡] *20.0, 19.9, 18.6, 19.8, 20.0\n[⚡] Tick durations (min/med/95%ile/max ms) from last 10s, 1m:\n[⚡] 0.8/ 4.1/ 9.3/ 31.0; 0.7/ 3.9/ 8.8/ 40.2";
408 app.db.query("DELETE FROM game_metric WHERE box_id = ?").run(box.id);
409 recordMetrics(app.db, box, { metrics: { hub: { list: "", tps: "Unknown command", mspt: "", spark } } }, new Date());
410 expect(await line()).toContain("18.6 TPS · 4.1 ms tick");
411 app.db.query("DELETE FROM game_metric WHERE box_id = ?").run(box.id);
412 recordMetrics(app.db, box, { metrics: { hub: { list: "", tps: "", mspt: "", spark: "[⚡] TPS from last 5s, 10s, 1m, 5m, 15m:\n[⚡] 2?.0, ??" } } }, new Date());
413 const bad = await line();
414 expect(bad).not.toContain("TPS");
415 expect(bad).not.toContain("ms tick");
416 app.db.query("DELETE FROM game_metric WHERE box_id = ?").run(box.id);
417 });
418
397419 test("the terminal's box screen says which version of the forge's plugin the proxy loaded, as the page does (#18110)", async () => {
398420 const box = boxNamed(app.db, "net")!;
399421 const pinned = PINS[0]!;

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

Keyboard shortcuts

Docs