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

Games G3: people: who is online with heads, joins, deaths and chat, whitelist, ops and bans, move between servers (#17284) #17295

opened this

Merged 34h 55m ago, live in production

sold/game-people → main 0 commits 2 threads · 2 unresolved

  • Merged. sold/game-people was merged into main as b50a2de.

Review

Sign in to review this change.
29 files changed +2106 −52
docs/design/areas/games.md added +3
@@ -0,0 +1,3 @@
1 # Games
2
3 - `.net`, `.net-node`, `.net-servers`, `.net-server`, `.net-heads`, `.net-head` — the network picture on /games/<box> (`src/web/pages/games_topology.ts`, `TOPOLOGY_CSS`): the proxy as one `.net-node` card on top, a line (the grid's top border) and the game servers under it as cards in a grid that folds to one column on a phone. A server's state is its card's left edge: green awake, the attention colour waking, dashed muted asleep, red stopped, and always the word too, so no state is colour alone. Each card is a link to the server's page. A player is a `.net-head`: their head and name; for an operator a `<details>` whose buttons move them to each server that is up. No script, design tokens only, and the only hover is behind `(hover: hover)`.
docs/features/games.md +14
@@ -37,6 +37,14 @@ Warm again takes all of it away; the same labels always give the same file. Only
3737
3838 A box owner, and only an owner, sees what the provider says about the box machine (the same facts as on /infra, see docs/features/infra.md): as "Its machine" on `/games/<box>`, a line a box on the terminal Games screen, and as `cloud` on each box of the `games` tool `list`. The machine is the one the box own row names (its `pinnedId`), never one found by name.
3939
40 ## People
41
outdated

Missing blank line before this heading; also the terminal people tab is described twice in this section.

42 A service page has a People block (#17284), with no plugin on the game servers: who is on now, with their heads; the whitelist (and whether it is on), the ops and the bans; and the latest joins, leaves, deaths and chat (kept 30 days and at most 5,000 a server; the page is for those with a grant, viewer or above). An operator has a toggle on each player: Op or Deop, Whitelist or Unlist, Kick, Ban or Pardon, each the server's own command through its RCON, and each undone by its opposite. A Bedrock player (through Floodgate) shows with the "." before their name and a Bedrock badge.
43
44 `/games/<box>` draws **the network**: the proxy on top and each game server under it, awake, waking (running while its health check starts), asleep (stopped by its sleep) or stopped, with its TPS and the heads of who is on it, every player by server as the proxy says (Velocircon, an RCON console on Velocity that only the compose network reaches; the agent sends its password through stdin, never a command line), with **Move**: an operator opens a player's head and picks a server that is up. A move goes only to a server of the same box that the person also operates, on the page, in the terminal and in the `games` tool alike. A server's card opens its page (`src/web/pages/games_topology.ts`). In the terminal, the Games screen (`src/tui/screens/games.ts`) lists the same servers with their state, players and TPS.
45
46 The agent reads `list uuids` each sync, and each server's whitelist.json, ops.json and banned-players.json and the proxy's `glist all` every 60 s or right after a change. Heads come from the player's UUID through the forge (`/games/head/<uuid>`), fetched once from mc-heads.net and kept on the forge's disk a week, so a page never calls out. Only a player the forge has seen on a server the person sees (on it now, or in its whitelist, ops or bans) has a head fetched; any other UUID gets the default head. A failed fetch is not tried again for 15 minutes, and at most four fetches are out at once. The terminal's service screen has a people tab (`p` takes "op Alice", "move Alice survival"), and the `games` tool has `people` with `op` list or a change.
47
4048 ## Secrets
4149
4250 The Velocity forwarding secret (`forwarding.env`) and an RCON password a service (`rcon-<service>.env`) are generated once, sealed like every forge secret and sent only in the sync's `env`, never committed. A box token is shown once and stored hashed. An uploaded jar is kept by the forge at `/games/jar/<id>/<name>`; the compose a box gets carries it signed for 6 hours, and only for the box that uploaded it. A jar must be a `.jar` (a zip), at most 64 MiB, and a box keeps at most 20 jars and 256 MiB.
@@ -45,6 +53,12 @@ The environment editor refuses a key that looks like a secret (`PASSWORD`, `SECR
4553
4654 A plugin or jar runs code on the game server; give operator only to people you trust.
4755
56 ## Numbers
57
58 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`).
59
60 `/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`).
61
4862 ## Who may do what
4963
5064 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.
forge.json +1
@@ -13,6 +13,7 @@
1313 "api.cloudflare.com",
1414 "api.digitalocean.com",
1515 "api.hetzner.cloud",
16 "mc-heads.net",
1617 "api.us.ovhcloud.com",
1718 "www.ecb.europa.eu",
1819 "api.fly.io",
src/core/migration-pins/20261201050000-game-metrics.pin added +1
@@ -0,0 +1,1 @@
1 e1b79d3e8929312118093c3fc3f1b4f8d8e5ce5b6b0d7fd0ccff4a3b02b2c71b
src/core/migration-pins/20261202000000-game-people.pin added +1
@@ -0,0 +1,1 @@
1 37ee337444ec6f1f421b835ac6c13f3180294648744c44ca1481f8950294de4b
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/core/migrations/20261202000000-game-people.ts added +10
@@ -0,0 +1,10 @@
1 // People on a game network (#17284 G3): who is online on each server with their UUIDs (from
2 // `list uuids`), each server's whitelist, ops and bans (as its agent last read them), who is on
3 // which server across the network (the proxy's glist), and the text of a chat line or a death in
4 // the event log. Additive: four columns.
5 export default `
6 ALTER TABLE game_service ADD COLUMN online_json TEXT NOT NULL DEFAULT '[]';
7 ALTER TABLE game_service ADD COLUMN people_json TEXT NOT NULL DEFAULT '{}';
8 ALTER TABLE game_box ADD COLUMN network_json TEXT NOT NULL DEFAULT '{}';
9 ALTER TABLE game_player_event ADD COLUMN text TEXT NOT NULL DEFAULT '';
10 `;
src/crew/conversation_ask.ts +16
@@ -329,6 +329,22 @@ export const ASKED_AS: Readonly<Record<string, Form>> = {
329329 if (a["action"] === "plugin") return `Add the plugin ${val(a, "modrinth") || val(a, "value")} to ${on}, a commit that redeploys it`;
330330 if (a["action"] === "config_set") return `Set the setting ${val(a, "key")} on ${on}${clause(" to ", val(a, "value"))}, a commit that restarts it`;
331331 if (a["action"] === "sleep") return a["value"] === "warm" ? `Keep ${on} warm, a commit that redeploys it` : `Let ${on} sleep when empty and wake on join, a commit that redeploys it`;
332 if (a["action"] === "people") {
333 const p = val(a, "player") || "a player";
334 const words: Record<string, string> = {
335 op: `Make ${p} an operator on ${on}`,
336 deop: `Take operator from ${p} on ${on}`,
337 "whitelist-add": `Whitelist ${p} on ${on}`,
338 "whitelist-remove": `Take ${p} off the whitelist on ${on}`,
339 "whitelist-on": `Turn the whitelist on for ${on}`,
340 "whitelist-off": `Turn the whitelist off for ${on}`,
341 ban: `Ban ${p} from ${on}`,
342 pardon: `Unban ${p} on ${on}`,
343 kick: `Kick ${p} from ${on}`,
344 move: `Move ${p} to ${val(a, "to") || "another server"}`,
345 };
346 return words[val(a, "op")] ?? `Change ${p} on ${on}`;
347 }
332348 return `Change ${on}`;
333349 },
334350 crew_accounts: (a) => `Let the crew's runs for ${val(a, "repo") || val(a, "owner") || "your repositories"} spend the account ${val(a, "allow")}`,
src/games/agent.sh +96 −1
@@ -344,6 +344,66 @@ logs() {
344344 | group_by(.s) | map({key: .[0].s, value: (map(.l) | .[-200:])}) | from_entries' 2>/dev/null || echo '{}'
345345 }
346346
347 # Each running service's RCON answers to `list`, `tps` and `mspt` (Paper), raw: the forge parses
348 # them (games/metrics.ts). A service without rcon-cli (the Velocity proxy) is asked once, then not.
349 NORCON=" "
350 metrics() {
351 local out='{}' name list tps mspt
352 while IFS= read -r name; do
353 [[ "$name" =~ $SAFE ]] || continue
354 case "$NORCON" in *" $name "*) continue ;; esac
355 # `list uuids`: each name with its UUID, so the forge can show who it is (games/people.ts).
356 if ! list="$(capped 5 "${COMPOSE[@]}" exec -T "$name" rcon-cli -- list uuids 2>/dev/null)"; then
357 NORCON="$NORCON$name "
358 continue
359 fi
360 tps="$(capped 5 "${COMPOSE[@]}" exec -T "$name" rcon-cli -- tps 2>/dev/null || true)"
361 mspt="$(capped 5 "${COMPOSE[@]}" exec -T "$name" rcon-cli -- mspt 2>/dev/null || true)"
362 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")"
363 done < <(capped 5 "${COMPOSE[@]}" ps --status running --format '{{.Service}}' 2>/dev/null)
364 echo "$out"
365 }
366
367 # ---- people (games/people.ts): every 60 s, or right after a people command, each game server's
368 # whitelist, ops and bans (its own JSON files, read where the server keeps them) and the proxy's
369 # glist all (who is on which server), through Velocircon's RCON on the compose network. ----
370 PEOPLE_EVERY="${FORGE_GAME_PEOPLE_EVERY:-60}"
371 people_due() {
372 [ -f "$DIR/.people.due" ] && return 0
373 [ ! -f "$DIR/.people.json" ] && return 0
374 [ $(( $(date +%s) - $(stat -c %Y "$DIR/.people.json" 2>/dev/null || echo 0) )) -ge "$PEOPLE_EVERY" ]
375 }
376 # A backend's rcon-cli asks the proxy: the password goes in through stdin into the environment, never argv.
377 proxy_rcon() {
378 local via="$1" pw
379 shift
380 pw="$(sed -n 's/^RCON_VELOCITY=//p' "$DIR/.env" 2>/dev/null | head -n 1)"
381 [ -n "$pw" ] || return 1
382 printf '%s\n' "$pw" | capped 10 "${COMPOSE[@]}" exec -T "$via" sh -c 'read -r p; RCON_PASSWORD="$p" exec rcon-cli --host velocity --port 25575 "$@"' sh "$@"
383 }
384 people() {
385 local out='{}' name raw part via="" glist
386 if ! people_due; then cat "$DIR/.people.json" 2>/dev/null || echo '{}'; return; fi
387 rm -f "$DIR/.people.due"
388 while IFS= read -r name; do
389 [[ "$name" =~ $SAFE ]] || continue
390 case "$NORCON" in *" $name "*) continue ;; esac
391 raw="$(capped 5 "${COMPOSE[@]}" exec -T "$name" sh -c 'for f in whitelist.json ops.json banned-players.json; do echo "=== $f"; cat "$f" 2>/dev/null; echo; done; echo "=== props"; grep -E "^(white-list|enforce-whitelist)=" server.properties 2>/dev/null' 2>/dev/null)" || continue
392 [ -n "$via" ] || via="$name"
393 part="$(jq -cn --arg raw "${raw:0:200000}" '
394 def file($n): ($raw | split("=== " + $n + "\n")[1] // "" | split("\n=== ")[0] | (try fromjson catch []) | if type == "array" then . else [] end);
395 {whitelist: [file("whitelist.json")[] | {name: (.name // ""), uuid: (.uuid // "")}][0:500],
396 ops: [file("ops.json")[] | {name: (.name // ""), uuid: (.uuid // ""), level: (.level // 0)}][0:200],
397 bans: [file("banned-players.json")[] | {name: (.name // ""), uuid: (.uuid // ""), reason: ((.reason // "") | .[0:200]), created: (.created // "")}][0:500],
398 whitelistOn: ($raw | test("(?m)^white-list=true"))}' 2>/dev/null)" || continue
399 out="$(jq -c --arg n "$name" --argjson p "$part" '. + {($n): $p}' <<<"$out")"
400 done < <(capped 5 "${COMPOSE[@]}" ps --status running --format '{{.Service}}' 2>/dev/null)
401 glist=""
402 [ -n "$via" ] && glist="$(proxy_rcon "$via" glist all 2>/dev/null || true)"
403 jq -c --arg g "${glist:0:20000}" '{servers: ., network: $g}' <<<"$out" >"$DIR/.people.json.next" && mv "$DIR/.people.json.next" "$DIR/.people.json"
404 cat "$DIR/.people.json"
405 }
406
347407 host() {
348408 local total avail load disk
349409 total="$(awk '/^MemTotal:/ {print int($2/1024)}' /proc/meminfo 2>/dev/null || echo 0)"
@@ -383,6 +443,37 @@ run() {
383443 queue_job "$id" "recreate $service" "" up -d --force-recreate "$service"
384444 return
385445 ;;
446 # A player's place on a server (games/people.ts): the server's own commands through its RCON,
447 # or the proxy's `send` to move them. The next sync reads the lists again.
448 people)
449 local op player server
450 op="$(jq -r '.op // ""' <<<"$text" 2>/dev/null)"
451 player="$(jq -r '.player // ""' <<<"$text" 2>/dev/null)"
452 server="$(jq -r '.server // ""' <<<"$text" 2>/dev/null)"
453 if [[ "$op" != whitelist-on && "$op" != whitelist-off ]] && ! [[ "$player" =~ ^[A-Za-z0-9_.]{1,17}$ ]]; then
454 out="refused: that is not a player's name"
455 ok=false
456 else
457 case "$op" in
458 whitelist-add) out="$(bounded30 "${COMPOSE[@]}" exec -T "$service" rcon-cli -- whitelist add "$player" 2>&1)" || ok=false ;;
459 whitelist-remove) out="$(bounded30 "${COMPOSE[@]}" exec -T "$service" rcon-cli -- whitelist remove "$player" 2>&1)" || ok=false ;;
460 whitelist-on) out="$(bounded30 "${COMPOSE[@]}" exec -T "$service" rcon-cli -- whitelist on 2>&1)" || ok=false ;;
461 whitelist-off) out="$(bounded30 "${COMPOSE[@]}" exec -T "$service" rcon-cli -- whitelist off 2>&1)" || ok=false ;;
462 op | deop | ban | pardon | kick) out="$(bounded30 "${COMPOSE[@]}" exec -T "$service" rcon-cli -- "$op" "$player" 2>&1)" || ok=false ;;
463 move)
464 if [[ "$server" =~ $SAFE ]]; then out="$(proxy_rcon "$service" send "$player" "$server" 2>&1)" || ok=false; else
465 out="refused: name a server to move them to"
466 ok=false
467 fi
468 ;;
469 *)
470 out="refused: $op is not something this agent does for a player"
471 ok=false
472 ;;
473 esac
474 touch "$DIR/.people.due"
475 fi
476 ;;
386477 *)
387478 out="refused: $kind is not a command this agent runs"
388479 ok=false
@@ -606,6 +697,8 @@ sync() {
606697 json_or '[]' <"$DIR/.results" >"$DIR/.sync.results"
607698 host | json_or '{}' >"$DIR/.sync.host"
608699 bounded_diag | json_or '{}' >"$DIR/.sync.diag"
700 people | json_or '{}' >"$DIR/.sync.people"
701 metrics | json_or '{}' >"$DIR/.sync.metrics"
609702 # Every string as plain text: real servers print colour escapes and control bytes (itzg's logs,
610703 # rcon-cli's colours), and the forge takes none of them.
611704 jq -cn \
@@ -615,8 +708,10 @@ sync() {
615708 --slurpfile results "$DIR/.sync.results" \
616709 --slurpfile host "$DIR/.sync.host" \
617710 --slurpfile diag "$DIR/.sync.diag" \
711 --slurpfile people "$DIR/.sync.people" \
712 --slurpfile metrics "$DIR/.sync.metrics" \
618713 'def plain: gsub("\u001b\\[[0-9;?]*[ -/]*[@-~]"; "") | gsub("\u001b[@-_]?"; "") | gsub("[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]"; "");
619 {agent: 1, composeSha: $sha, services: $services[0], logs: $logs[0], results: $results[0], host: $host[0], diag: $diag[0]}
714 {agent: 1, composeSha: $sha, services: $services[0], logs: $logs[0], results: $results[0], host: $host[0], diag: $diag[0], people: $people[0], metrics: $metrics[0]}
620715 | walk(if type == "string" then plain else . end)' >"$DIR/.sync.body" || return 1
621716 answer="$(curl -fsS -m 20 -H "@$AUTH" -H 'content-type: application/json' --data-binary "@$DIR/.sync.body" "${FORGE_URL%/}/api/v1/games/agent/sync")" || return 1
622717 # Delivered: the results and the log lines are the forge's now.
src/games/heads.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * Players' heads (#17284 G3): a Java player's head from their UUID, fetched once from mc-heads.net
3 * by the forge and kept on its disk for a week, so a page never calls out and a busy page costs
4 * nothing. A Bedrock player (Floodgate) or a UUID the service does not know gets the default head.
5 *
6 * Bounded: the route serves only a UUID the forge has seen on a server it shows the person
7 * (`knowsPlayer` in people.ts), a failed fetch is remembered for `MISS_MS` before it is tried again,
8 * and at most `FETCHES_MAX` fetches are out at once (past that, the default head, not kept).
9 */
10
11 import { mkdir, stat } from "node:fs/promises";
12 import { join } from "node:path";
13 import type { App } from "../app.ts";
14
15 /** A kept head this young is served as is. */
16 export const HEAD_KEPT_MS = 7 * 86_400_000;
17 const UUID = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/;
18 const FETCH_MS = 5_000;
19 /** A head mc-heads.net did not give is not asked for again this long. */
20 export const MISS_MS = 15 * 60_000;
21 /** Fetches out at once; the misses remembered at most. */
22 export const FETCHES_MAX = 4;
23 const MISSES_MAX = 1_000;
24
25 /** Each app's remembered misses and fetches out: the app's, not the process's (#12569). */
26 interface Heads {
27 readonly misses: Map<string, number>;
28 readonly fetching: Map<string, Promise<boolean>>;
29 }
30 const headsByApp = new WeakMap<object, Heads>();
31 function headsOf(app: object): Heads {
outdated

Unbounded fetch-and-store per arbitrary UUID, no negative cache: see finding 2 in the review body.

32 let heads = headsByApp.get(app);
33 if (heads === undefined) headsByApp.set(app, (heads = { misses: new Map(), fetching: new Map() }));
34 return heads;
35 }
36
37 /** The default head: a plain grey face, inline. */
38 export const DEFAULT_HEAD = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" width="32" height="32"><rect width="8" height="8" fill="#8a8a8a"/><rect x="2" y="3" width="1" height="1" fill="#3a3a3a"/><rect x="5" y="3" width="1" height="1" fill="#3a3a3a"/><rect x="3" y="5" width="2" height="1" fill="#5a5a5a"/></svg>`;
39
40 const defaultHead = (keep = true): Response =>
41 new Response(DEFAULT_HEAD, { headers: { "content-type": "image/svg+xml", "cache-control": keep ? "public, max-age=86400" : "no-store" } });
42
43 /** The default head, for a player whose head is not to be fetched (a Bedrock player, an unknown one). */
44 export const defaultHeadResponse = (): Response => defaultHead();
45
46 /** The head for `uuid`, from the disk when it is younger than `HEAD_KEPT_MS`, else fetched and kept. */
47 export async function headResponse(app: App, uuid: string, fetcher: typeof fetch = fetch, now = Date.now()): Promise<Response> {
48 const id = uuid.toLowerCase();
49 if (!UUID.test(id)) return defaultHead();
50 const dir = join(app.config.dataDir, "game-heads");
51 const file = join(dir, `${id.replace(/-/g, "")}.png`);
52 const kept = await stat(file).catch(() => undefined);
53 const serve = (): Response => new Response(Bun.file(file), { headers: { "content-type": "image/png", "cache-control": "public, max-age=86400" } });
54 if (kept !== undefined && now - kept.mtimeMs < HEAD_KEPT_MS) return serve();
55 // An old head beats none; nothing at all is the default.
56 const fallback = (keep: boolean): Response => (kept !== undefined ? serve() : defaultHead(keep));
57 const { misses, fetching } = headsOf(app);
58 if ((misses.get(id) ?? 0) > now) return fallback(true);
59 let pending = fetching.get(id);
60 if (pending === undefined) {
61 if (fetching.size >= FETCHES_MAX) return fallback(false);
62 pending = (async (): Promise<boolean> => {
63 try {
64 const res = await fetcher(`https://mc-heads.net/avatar/${id.replace(/-/g, "")}/32`, { signal: AbortSignal.timeout(FETCH_MS) });
65 const bytes = new Uint8Array(await res.arrayBuffer());
66 // A PNG, and small: anything else is not a head.
67 if (!res.ok || bytes.length > 65_536 || bytes[0] !== 0x89 || bytes[1] !== 0x50) throw new Error("not a head");
68 await mkdir(dir, { recursive: true });
69 await Bun.write(file, bytes);
70 misses.delete(id);
71 return true;
72 } catch {
73 if (misses.size >= MISSES_MAX) misses.delete(misses.keys().next().value!);
74 misses.set(id, now + MISS_MS);
75 return false;
76 } finally {
77 fetching.delete(id);
78 }
79 })();
80 fetching.set(id, pending);
81 }
82 return (await pending) ? serve() : fallback(true);
83 }
src/games/metrics.ts added +418
@@ -0,0 +1,418 @@
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 /** The most joins, leaves, deaths and chat lines a server keeps (besides the 30 days). */
17 export const EVENTS_KEPT = 5_000;
18 /** How long a minute is kept. */
19 export const KEEP_DAYS = 30;
20 /** The most points a series answers with, whatever the window. */
21 export const MAX_POINTS = 120;
22 const NAMES_MAX = 100;
23
24 // ---- parsing ----------------------------------------------------------------------------------
25
26 /** Minecraft's colour codes (`§a`) and terminal colour sequences, gone. */
27 export const plain = (s: string): string => s.replace(/\u001b\[[0-9;]*[A-Za-z]/g, "").replace(/§[0-9a-fk-orx]/gi, "");
28
29 /**
30 * `list`'s answer: how many are online, the most allowed, and their names. Vanilla and Paper say
31 * "There are 2 of a max of 20 players online: Alice, Bob"; newer Paper says "There are 2 out of
32 * maximum 20 players online." with the names on the lines after, grouped ("default: Alice, Bob").
33 */
34 /** A player's name: Java's 1–16 characters, or Floodgate's Bedrock name with its "." before it. */
35 export const PLAYER = /^[.]?[A-Za-z0-9_]{1,16}$/;
36 const NAME = "[.]?[A-Za-z0-9_]{1,16}";
37
38 export function parseList(raw: string): { online: number; max: number; names: string[]; players: { name: string; uuid: string }[] } | undefined {
39 const text = plain(raw);
40 const m = /There are (\d+)(?: of a max of| out of maximum| out of a maximum of)? ?(\d+)? players? online[.:]?/i.exec(text);
41 if (m === null) return undefined;
42 const online = Number(m[1]);
43 const max = m[2] === undefined ? 0 : Number(m[2]);
44 const rest = text.slice(m.index + m[0].length);
45 // `list uuids` gives "Alice (069a79f4-44e9-4726-a5be-fca90e38aaf5)": the UUID is kept with the name.
46 const players = rest
47 .split("\n")
48 .map((l) => (l.includes(":") ? l.slice(l.indexOf(":") + 1) : l))
49 .flatMap((l) => l.split(","))
50 .map((n) =>
51 n
52 .trim()
53 .replace(/^\[[^\]]*\]\s*/, "")
54 .replace(/^[~*]/, ""),
55 )
56 .map((n) => /^(\S+?)(?:\s+\(([0-9a-fA-F-]{32,36})\))?$/.exec(n))
57 .filter((m): m is RegExpExecArray => m !== null && PLAYER.test(m[1]!))
58 .map((m) => ({ name: m[1]!, uuid: (m[2] ?? "").toLowerCase() }))
59 .slice(0, NAMES_MAX);
60 return { online, max, names: players.map((p) => p.name), players };
61 }
62
63 /** Paper's `tps`: the last minute's ticks a second ("TPS from last 1m, 5m, 15m: *20.0, 19.8, 19.9"). */
64 export function parseTps(raw: string): number | undefined {
65 const text = plain(raw);
66 const m = /TPS from last[^:]*:\s*\*?([0-9]+(?:\.[0-9]+)?)/i.exec(text);
67 return m === null ? undefined : Number(m[1]);
68 }
69
70 /** Paper's `mspt`: the average tick time of the last 5 s, in milliseconds (the first avg/min/max triple). */
71 export function parseMspt(raw: string): number | undefined {
72 const text = plain(raw);
73 const at = text.indexOf(":", text.search(/tick times/i));
74 if (at < 0) return undefined;
75 const m = /([0-9]+(?:\.[0-9]+)?)\s*\/\s*[0-9.]+\s*\/\s*[0-9.]+/.exec(text.slice(at + 1));
76 return m === null ? undefined : Number(m[1]);
77 }
78
79 export type LogFact =
80 | { kind: "join" | "leave"; player: string }
81 | { kind: "chat" | "death"; player: string; text: string }
82 | { kind: "error" | "warn" }
83 | undefined;
84
85 /**
86 * The head a server itself writes on each log line, at its start, and nothing else: Paper's and
87 * Velocity's "[12:00:01 INFO]: ", vanilla's "[12:00:01] [Server thread/INFO]: ", a plugin's
88 * "[12:00:01 INFO] [velocircon]: ". Every fact is matched right after it, so a player's chat that
89 * reads "[x] Alice joined the game" is chat, never a join (#17295 review).
90 */
91 const HEAD = "^\\[([^\\]]*)\\](?: \\[([^\\]]*)\\])?: ";
92
93 /** How a death reads after the player's name, from Minecraft's death messages ("was slain by", "drowned"). */
94 const DEATH = new RegExp(
95 `${HEAD}(${NAME}) (was (?!kicked|banned|whitelisted|opped)\\S.*|drowned.*|died.*|blew up.*|burned to death.*|went up in flames.*|tried to swim in lava.*|hit the ground too hard.*|fell .*|starved to death.*|suffocated .*|withered away.*|froze to death.*|experienced kinetic energy.*|walked into .*|discovered the floor was lava.*|didn't want to live .*|left the confines of this world.*|went off with a bang.*)$`,
96 );
97 const CHAT = new RegExp(`${HEAD}(?:\\[Not Secure\\] )?<(${NAME})> (.*)$`);
98 const RENAMED = `(?: \\(formerly known as ${NAME}\\))?`;
99 const JOIN = new RegExp(`${HEAD}(?:(${NAME})${RENAMED} joined the game|\\[connected player\\] (${NAME}) \\([^)]*\\) has connected)$`);
100 const LEAVE = new RegExp(`${HEAD}(?:(${NAME}) left the game|\\[connected player\\] (${NAME}) \\([^)]*\\) has disconnected)$`);
101 const LEVEL_ERROR = /(?:^|[\s/])(?:ERROR|SEVERE|FATAL)$/;
102 const LEVEL_WARN = /(?:^|[\s/])(?:WARN|WARNING)$/;
103
104 /**
105 * What one log line says that is counted: a player joining or leaving (Paper's "Alice joined the
106 * game", Velocity's "[connected player] Alice (/1.2.3.4:5) has connected"), chat, a death, or an
107 * error or a warning (the level in the line's own head: "[12:00:00 ERROR]: ", "[Server thread/WARN]: ").
108 */
109 export function parseLogLine(line: string): LogFact {
110 const text = plain(line).trimEnd();
111 const head = new RegExp(HEAD).exec(text);
112 if (head === null) return undefined;
113 // Chat first: "<Alice> I fell" is Alice talking, not falling.
114 let m = CHAT.exec(text);
115 if (m !== null) return { kind: "chat", player: m[3]!, text: m[4]!.slice(0, 300) };
116 m = JOIN.exec(text);
117 if (m !== null) return { kind: "join", player: (m[3] ?? m[4])! };
118 m = LEAVE.exec(text);
119 if (m !== null) return { kind: "leave", player: (m[3] ?? m[4])! };
120 m = DEATH.exec(text);
121 if (m !== null) return { kind: "death", player: m[3]!, text: `${m[3]!} ${m[4]!}`.slice(0, 300) };
122 const levels = [head[1] ?? "", head[2] ?? ""];
123 if (levels.some((l) => LEVEL_ERROR.test(l))) return { kind: "error" };
124 if (levels.some((l) => LEVEL_WARN.test(l))) return { kind: "warn" };
125 return undefined;
126 }
127
128 // ---- recording --------------------------------------------------------------------------------
129
130 export interface MetricsBody {
131 readonly services?: readonly { name?: unknown; cpuPct?: unknown; memMiB?: unknown }[];
132 readonly logs?: Record<string, unknown>;
133 /** Per service, the raw RCON answers: `list`, `tps`, `mspt` (any may be missing). */
134 readonly metrics?: Record<string, unknown>;
135 }
136
137 const num = (v: unknown): number | undefined => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
138 const text = (v: unknown, max = 8_000): string => (typeof v === "string" ? v.slice(0, max) : "");
139
140 /** One sync's numbers, rolled into each service's current minute; joins and leaves kept as events. */
141 export function recordMetrics(db: Database, box: Pick<GameBox, "id">, body: MetricsBody, now = new Date()): void {
142 const minute = Math.floor(now.getTime() / 60_000);
143 const at = now.toISOString();
144 type Row = { players?: number | undefined; names?: string[] | undefined; online?: { name: string; uuid: string }[] | undefined; tps?: number | undefined; mspt?: number | undefined; cpu?: number | undefined; mem?: number | undefined; errors: number; warns: number; joins: number; leaves: number };
145 const rows = new Map<string, Row>();
146 const rowOf = (s: string): Row => rows.get(s) ?? (rows.set(s, { errors: 0, warns: 0, joins: 0, leaves: 0 }), rows.get(s)!);
147 for (const s of (body.services ?? []).slice(0, 64)) {
148 const name = typeof s.name === "string" ? s.name : "";
149 if (!SERVICE_NAME.test(name)) continue;
150 const r = rowOf(name);
151 r.cpu = num(s.cpuPct);
152 r.mem = num(s.memMiB);
153 }
154 for (const [service, raw] of Object.entries(body.metrics ?? {}).slice(0, 64)) {
155 if (!SERVICE_NAME.test(service) || raw === null || typeof raw !== "object") continue;
156 const m = raw as Record<string, unknown>;
157 const r = rowOf(service);
158 const list = parseList(text(m["list"]));
159 if (list !== undefined) {
160 r.players = list.online;
161 r.names = list.names;
162 r.online = list.players;
163 }
164 r.tps = parseTps(text(m["tps"]));
165 r.mspt = parseMspt(text(m["mspt"]));
166 }
167 const events: { service: string; player: string; kind: "join" | "leave" | "chat" | "death"; text: string }[] = [];
168 for (const [service, lines] of Object.entries(body.logs ?? {}).slice(0, 64)) {
169 if (!SERVICE_NAME.test(service) || !Array.isArray(lines)) continue;
170 const r = rowOf(service);
171 for (const line of lines.slice(-200)) {
172 if (typeof line !== "string") continue;
173 const fact = parseLogLine(line);
174 if (fact === undefined) continue;
175 if (fact.kind === "join" || fact.kind === "leave") {
176 if (fact.kind === "join") r.joins++;
177 else r.leaves++;
178 events.push({ service, player: fact.player, kind: fact.kind, text: "" });
179 } else if (fact.kind === "chat" || fact.kind === "death") {
180 events.push({ service, player: fact.player, kind: fact.kind, text: fact.text });
181 } else if (fact.kind === "error") r.errors++;
182 else r.warns++;
183 }
184 }
185 db.transaction(() => {
186 const upsert = db.query(
187 `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)
188 VALUES (?1, ?2, ?3, 1, ?4, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)
189 ON CONFLICT (box_id, service, minute) DO UPDATE SET
190 n = n + 1,
191 players_max = MAX(players_max, excluded.players_max),
192 players_last = CASE WHEN excluded.players_n > 0 THEN excluded.players_last ELSE players_last END,
193 players_n = players_n + excluded.players_n,
194 tps_sum = tps_sum + excluded.tps_sum, tps_n = tps_n + excluded.tps_n,
195 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,
196 mspt_sum = mspt_sum + excluded.mspt_sum, mspt_n = mspt_n + excluded.mspt_n,
197 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,
198 cpu_sum = cpu_sum + excluded.cpu_sum, mem_sum = mem_sum + excluded.mem_sum,
199 errors = errors + excluded.errors, warns = warns + excluded.warns, joins = joins + excluded.joins, leaves = leaves + excluded.leaves`,
200 );
201 for (const [service, r] of rows)
202 upsert.run(
203 box.id,
204 service,
205 minute,
206 r.players ?? 0,
207 r.players === undefined ? 0 : 1,
208 r.tps ?? 0,
209 r.tps ?? null,
210 r.tps === undefined ? 0 : 1,
211 r.mspt ?? 0,
212 r.mspt ?? null,
213 r.mspt === undefined ? 0 : 1,
214 r.cpu ?? 0,
215 r.mem ?? 0,
216 r.errors,
217 r.warns,
218 r.joins,
219 r.leaves,
220 );
221 for (const [service, r] of rows)
222 if (r.names !== undefined)
223 db.query("UPDATE game_service SET players = ?3 WHERE box_id = ?1 AND name = ?2").run(box.id, service, r.names.join(","));
224 for (const [service, r] of rows)
225 if (r.online !== undefined) db.query("UPDATE game_service SET online_json = ?3 WHERE box_id = ?1 AND name = ?2").run(box.id, service, JSON.stringify(r.online));
226 const event = db.query("INSERT INTO game_player_event (box_id, service, player, kind, at, text) VALUES (?1, ?2, ?3, ?4, ?5, ?6)");
227 for (const e of events) event.run(box.id, e.service, e.player, e.kind, at, e.text);
228 // Past the window: once a minute is plenty, and each delete walks the minute index.
229 if (minute % 10 === 0) {
230 db.query("DELETE FROM game_metric WHERE minute < ?1").run(minute - KEEP_DAYS * 1440);
231 db.query("DELETE FROM game_player_event WHERE at < ?1").run(new Date(now.getTime() - KEEP_DAYS * 86_400_000).toISOString());
232 // And at most EVENTS_KEPT a server, however busy its chat: the newest stay.
233 for (const service of rows.keys())
234 db.query("DELETE FROM game_player_event WHERE box_id = ?1 AND service = ?2 AND id <= (SELECT id FROM game_player_event WHERE box_id = ?1 AND service = ?2 ORDER BY id DESC LIMIT 1 OFFSET ?3)").run(box.id, service, EVENTS_KEPT);
235 }
236 })();
237 }
238
239 // ---- reading ----------------------------------------------------------------------------------
240
241 interface MinuteRow {
242 service: string;
243 minute: number;
244 n: number;
245 players_max: number;
246 players_last: number;
247 players_n: number;
248 tps_sum: number;
249 tps_min: number | null;
250 tps_n: number;
251 mspt_sum: number;
252 mspt_max: number | null;
253 mspt_n: number;
254 cpu_sum: number;
255 mem_sum: number;
256 errors: number;
257 warns: number;
258 joins: number;
259 leaves: number;
260 }
261
262 const minutes = (db: Database, boxId: string, since: number, service?: string): MinuteRow[] =>
263 service === undefined
264 ? db
265 .query<MinuteRow, [string, number]>("SELECT * FROM game_metric WHERE box_id = ?1 AND minute >= ?2 ORDER BY service, minute")
266 .all(boxId, since)
267 : db
268 .query<
269 MinuteRow,
270 [string, string, number]
271 >("SELECT * FROM game_metric WHERE box_id = ?1 AND service = ?2 AND minute >= ?3 ORDER BY minute")
272 .all(boxId, service, since);
273
274 const round = (n: number, places = 1): number => Math.round(n * 10 ** places) / 10 ** places;
275
276 /** min, avg, max and p95 of what is known; undefined with nothing. */
277 export function stats(values: readonly number[]): { min: number; avg: number; max: number; p95: number } | undefined {
278 if (values.length === 0) return undefined;
279 const sorted = [...values].sort((a, b) => a - b);
280 const p95 = sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * 0.95) - 1)]!;
281 return {
282 min: round(sorted[0]!),
283 avg: round(values.reduce((s, v) => s + v, 0) / values.length),
284 max: round(sorted.at(-1)!),
285 p95: round(p95),
286 };
287 }
288
289 /** A window of minutes rolled into one: averages per minute, peaks, counts. */
290 function windowOf(rows: readonly MinuteRow[]) {
291 const tps = rows.filter((r) => r.tps_n > 0).map((r) => r.tps_sum / r.tps_n);
292 const mspt = rows.filter((r) => r.mspt_n > 0).map((r) => r.mspt_sum / r.mspt_n);
293 const cpu = rows.filter((r) => r.n > 0).map((r) => r.cpu_sum / r.n);
294 const mem = rows.filter((r) => r.n > 0).map((r) => r.mem_sum / r.n);
295 const out: Record<string, unknown> = {};
296 const add = (k: string, v: unknown) => {
297 if (v !== undefined) out[k] = v;
298 };
299 add("tps", stats(tps));
300 add("mspt", stats(mspt));
301 add("cpu", stats(cpu));
302 add("memMiB", stats(mem));
303 out["peakPlayers"] = rows.reduce((m, r) => Math.max(m, r.players_max), 0);
304 out["errors"] = rows.reduce((s, r) => s + r.errors, 0);
305 out["joins"] = rows.reduce((s, r) => s + r.joins, 0);
306 return out;
307 }
308
309 /**
310 * Each service of a box: now (its last minute), the last hour and the last day. Compact by design:
311 * a handful of numbers a service, so a network of a dozen servers stays well under 4 KB.
312 */
313 export function metricsSummary(db: Database, box: Pick<GameBox, "id">, now = new Date()): Record<string, unknown> {
314 const minute = Math.floor(now.getTime() / 60_000);
315 const all = minutes(db, box.id, minute - 1440);
316 const services = [...new Set(all.map((r) => r.service))].sort();
317 const out: Record<string, unknown> = {};
318 for (const s of services) {
319 const rows = all.filter((r) => r.service === s);
320 const last = rows.at(-1)!;
321 const current = db
322 .query<{ players: string }, [string, string]>("SELECT players FROM game_service WHERE box_id = ?1 AND name = ?2")
323 .get(box.id, s);
324 out[s] = {
325 now: {
326 at: new Date(last.minute * 60_000).toISOString(),
327 players: last.players_last,
328 ...(last.tps_n > 0 ? { tps: round(last.tps_sum / last.tps_n) } : {}),
329 ...(last.mspt_n > 0 ? { mspt: round(last.mspt_sum / last.mspt_n) } : {}),
330 cpu: round(last.cpu_sum / Math.max(1, last.n)),
331 memMiB: Math.round(last.mem_sum / Math.max(1, last.n)),
332 online: (current?.players ?? "").split(",").filter(Boolean).slice(0, 10),
333 },
334 "1h": windowOf(rows.filter((r) => r.minute > minute - 60)),
335 "24h": windowOf(rows),
336 };
337 }
338 return out;
339 }
340
341 export const WINDOWS = { "1h": 60, "6h": 360, "24h": 1440, "7d": 10_080, "30d": 43_200 } as const;
342 export type Window = keyof typeof WINDOWS;
343
344 export interface Point {
345 readonly at: string;
346 readonly players: number;
347 readonly tps: number | null;
348 readonly mspt: number | null;
349 readonly cpu: number | null;
350 readonly memMiB: number | null;
351 readonly errors: number;
352 }
353
354 /** One service's series over a window, in at most `MAX_POINTS` buckets (empty buckets are left out). */
355 export function metricsSeries(db: Database, box: Pick<GameBox, "id">, service: string, window: Window, now = new Date()): Point[] {
356 const span = WINDOWS[window];
357 const minute = Math.floor(now.getTime() / 60_000);
358 const step = Math.max(1, Math.ceil(span / MAX_POINTS));
359 const rows = minutes(db, box.id, minute - span + 1, service);
360 const buckets = new Map<number, MinuteRow[]>();
361 for (const r of rows) {
362 const b = Math.floor((r.minute - (minute - span + 1)) / step);
363 (buckets.get(b) ?? (buckets.set(b, []), buckets.get(b)!)).push(r);
364 }
365 return [...buckets.entries()]
366 .sort((a, b) => a[0] - b[0])
367 .slice(-MAX_POINTS)
368 .map(([b, rs]) => {
369 const sum = (f: (r: MinuteRow) => number) => rs.reduce((s, r) => s + f(r), 0);
370 const tpsN = sum((r) => r.tps_n);
371 const msptN = sum((r) => r.mspt_n);
372 const n = sum((r) => r.n);
373 return {
374 at: new Date((minute - span + 1 + b * step) * 60_000).toISOString(),
375 players: Math.max(...rs.map((r) => r.players_max)),
376 tps: tpsN === 0 ? null : round(sum((r) => r.tps_sum) / tpsN),
377 mspt: msptN === 0 ? null : round(sum((r) => r.mspt_sum) / msptN),
378 cpu: n === 0 ? null : round(sum((r) => r.cpu_sum) / n),
379 memMiB: n === 0 ? null : Math.round(sum((r) => r.mem_sum) / n),
380 errors: sum((r) => r.errors),
381 };
382 });
383 }
384
385 /** The latest joins and leaves of a service (or the box), newest first. */
386 export const playerEvents = (
387 db: Database,
388 boxId: string,
389 service?: string,
390 limit = 20,
391 ): { service: string; player: string; kind: string; at: string }[] =>
392 service === undefined
393 ? db
394 .query<
395 { service: string; player: string; kind: string; at: string },
396 [string, number]
397 >("SELECT service, player, kind, at FROM game_player_event WHERE box_id = ?1 ORDER BY id DESC LIMIT ?2")
398 .all(boxId, limit)
399 : db
400 .query<
401 { service: string; player: string; kind: string; at: string },
402 [string, string, number]
403 >("SELECT service, player, kind, at FROM game_player_event WHERE box_id = ?1 AND service = ?2 ORDER BY id DESC LIMIT ?3")
404 .all(boxId, service, limit);
405
406 /** The latest error lines a service logged (from the log tail), newest first. */
407 export function recentErrors(db: Database, boxId: string, service: string, limit = 10): { line: string; at: string }[] {
408 const rows = db
409 .query<
410 { line: string; at: string },
411 [string, string]
412 >("SELECT line, at FROM game_log WHERE box_id = ?1 AND service = ?2 ORDER BY id DESC LIMIT 2000")
413 .all(boxId, service);
414 return rows
415 .filter((r) => parseLogLine(r.line)?.kind === "error")
416 .slice(0, limit)
417 .map((r) => ({ line: plain(r.line).slice(0, 300), at: r.at }));
418 }
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/people.ts added +239
@@ -0,0 +1,239 @@
1 /**
2 * People on a game network (#17284 G3), with no plugin on the game servers: the box's agent reads
3 * what each server already keeps and says (`list uuids`, its whitelist.json, ops.json and
4 * banned-players.json, the joins, leaves, deaths and chat in its log), and asks the proxy (Velocircon,
5 * an RCON console on Velocity, reached only on the compose network) who is on which server. A
6 * person acts through the same commands a server admin types: whitelist, op, ban, kick, each with
7 * its opposite as its undo, and the proxy's `send` to move someone.
8 *
9 * A Bedrock player comes through Floodgate with a "." before their name; they are shown with a
10 * Bedrock badge and the default head (no Java skin).
11 */
12
13 import type { Database } from "bun:sqlite";
14 import { PLAYER } from "./metrics.ts";
15 import type { User } from "../core/users.ts";
16 import { mayDo, queueCommand, roleOn, SERVICE_NAME, servicesOf, type GameBox } from "./store.ts";
17
18 export interface Player {
19 readonly name: string;
20 readonly uuid: string;
21 }
22 export interface Ban extends Player {
23 readonly reason: string;
24 readonly created: string;
25 }
26 export interface People {
27 readonly whitelist: readonly Player[];
28 readonly ops: readonly (Player & { readonly level: number })[];
29 readonly bans: readonly Ban[];
30 readonly whitelistOn: boolean;
31 }
32 export interface PeopleEvent {
33 readonly player: string;
34 readonly kind: "join" | "leave" | "chat" | "death";
35 readonly text: string;
36 readonly at: string;
37 }
38
39 const NONE: People = { whitelist: [], ops: [], bans: [], whitelistOn: false };
40 const UUID = /^[0-9a-f-]{32,36}$/;
41
42 export const isBedrock = (name: string): boolean => name.startsWith(".");
43
44 const str = (v: unknown, max: number): string => (typeof v === "string" ? v.slice(0, max) : "");
45 const playerOf = (v: unknown): Player | undefined => {
46 if (v === null || typeof v !== "object") return undefined;
47 const o = v as Record<string, unknown>;
48 const name = str(o["name"], 17);
49 const uuid = str(o["uuid"], 36).toLowerCase();
50 return PLAYER.test(name) ? { name, uuid: UUID.test(uuid) ? uuid : "" } : undefined;
51 };
52 const listOf = <T>(v: unknown, max: number, each: (x: unknown) => T | undefined): T[] =>
53 (Array.isArray(v) ? v : [])
54 .map(each)
55 .filter((x): x is T => x !== undefined)
56 .slice(0, max);
57
58 /** One server's lists as the agent sent them, cleaned. */
59 export function keptPeople(sent: unknown): People {
60 if (sent === null || typeof sent !== "object") return NONE;
61 const o = sent as Record<string, unknown>;
62 return {
63 whitelist: listOf(o["whitelist"], 500, playerOf),
64 ops: listOf(o["ops"], 200, (x) => {
65 const p = playerOf(x);
66 const level = (x as Record<string, unknown>)["level"];
67 return p === undefined ? undefined : { ...p, level: typeof level === "number" && Number.isInteger(level) ? level : 0 };
68 }),
69 bans: listOf(o["bans"], 500, (x) => {
70 const p = playerOf(x);
71 const r = x as Record<string, unknown>;
72 return p === undefined ? undefined : { ...p, reason: str(r["reason"], 200), created: str(r["created"], 40) };
73 }),
74 whitelistOn: o["whitelistOn"] === true,
75 };
76 }
77
78 /** The proxy's `glist all`: "[hub] (2): Alice, Bob" a line, servers with nobody left out. */
79 export function parseGlist(raw: string): Record<string, string[]> {
80 const out: Record<string, string[]> = {};
81 for (const line of raw.split("\n")) {
82 const m = /^\s*\[([A-Za-z0-9._-]{1,64})\] \((\d+)\):\s*(.*)$/.exec(line);
83 if (m === null) continue;
84 out[m[1]!] = m[3]!
85 .split(",")
86 .map((n) => n.trim())
87 .filter((n) => PLAYER.test(n))
88 .slice(0, 500);
89 }
90 return out;
91 }
92
93 /** What a sync says of people: each server's lists, and the network from the proxy. */
94 export function recordPeople(db: Database, box: Pick<GameBox, "id">, sent: unknown): void {
95 if (sent === null || typeof sent !== "object") return;
96 const o = sent as { servers?: unknown; network?: unknown };
97 db.transaction(() => {
98 if (o.servers !== null && typeof o.servers === "object")
99 for (const [service, lists] of Object.entries(o.servers as Record<string, unknown>).slice(0, 64))
100 if (SERVICE_NAME.test(service))
101 db.query("UPDATE game_service SET people_json = ?3 WHERE box_id = ?1 AND name = ?2").run(
102 box.id,
103 service,
104 JSON.stringify(keptPeople(lists)),
105 );
106 if (typeof o.network === "string")
107 db.query("UPDATE game_box SET network_json = ?2 WHERE id = ?1").run(box.id, JSON.stringify(parseGlist(o.network.slice(0, 20_000))));
108 })();
109 }
110
111 const parsed = <T>(json: string | undefined, fallback: T): T => {
112 try {
113 return json === undefined ? fallback : (JSON.parse(json) as T);
114 } catch {
115 return fallback;
116 }
117 };
118
119 /** Who is on a server now (from `list uuids`), and its lists. */
120 export function peopleOf(db: Database, boxId: string, service: string): { online: Player[]; lists: People } {
121 const r = db
122 .query<
123 { online_json: string; people_json: string },
124 [string, string]
125 >("SELECT online_json, people_json FROM game_service WHERE box_id = ?1 AND name = ?2")
126 .get(boxId, service);
127 return { online: parsed<Player[]>(r?.online_json, []), lists: { ...NONE, ...parsed<Partial<People>>(r?.people_json, {}) } };
128 }
129
130 const WHOLE_UUID = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/;
131
132 /**
133 * Whether `uuid` (lowercase) is a player the forge has seen on a server of a box `user` sees: on
134 * it now, or in its whitelist, ops or bans. Only such a player's head is fetched.
135 */
136 export function knowsPlayer(db: Database, user: User | undefined, uuid: string): boolean {
137 if (user === undefined || !WHOLE_UUID.test(uuid)) return false;
138 return (
139 db
140 .query(
141 `SELECT 1 FROM game_service
142 WHERE (instr(online_json, ?1) > 0 OR instr(people_json, ?1) > 0)
143 AND (?2 = 1 OR box_id IN (SELECT box_id FROM game_grant WHERE user_id = ?3))
144 LIMIT 1`,
145 )
146 .get(JSON.stringify(uuid), user.isAdmin ? 1 : 0, user.id) !== null
147 );
148 }
149
150 /** Who is on which server across the box's network, as the proxy last said. */
151 export const networkOf = (db: Database, boxId: string): Record<string, string[]> =>
152 parsed<Record<string, string[]>>(
153 db.query<{ network_json: string }, [string]>("SELECT network_json FROM game_box WHERE id = ?1").get(boxId)?.network_json,
154 {},
155 );
156
157 /** A server's latest joins, leaves, deaths and chat, newest first: for those who may see the server. */
158 export const eventsOf = (db: Database, boxId: string, service: string, limit = 30): PeopleEvent[] =>
159 db
160 .query<
161 PeopleEvent,
162 [string, string, number]
163 >("SELECT player, kind, text, at FROM game_player_event WHERE box_id = ?1 AND service = ?2 ORDER BY id DESC LIMIT ?3")
164 .all(boxId, service, Math.min(200, limit));
165
166 export const PEOPLE_OPS = [
167 "whitelist-add",
168 "whitelist-remove",
169 "whitelist-on",
170 "whitelist-off",
171 "op",
172 "deop",
173 "ban",
174 "pardon",
175 "kick",
176 "move",
177 ] as const;
178 export type PeopleOp = (typeof PEOPLE_OPS)[number];
179
180 /** Each change's opposite: its Undo. A kick and a move have none. */
181 export const UNDO: Partial<Record<PeopleOp, PeopleOp>> = {
182 "whitelist-add": "whitelist-remove",
183 "whitelist-remove": "whitelist-add",
184 "whitelist-on": "whitelist-off",
185 "whitelist-off": "whitelist-on",
186 op: "deop",
187 deop: "op",
188 ban: "pardon",
189 pardon: "ban",
190 };
191
192 /**
193 * Queue a change to a player on `service` (for a move, the server they are on now; `to` where they
194 * go, a server of this box that `by` may operate too): the command's id, or why not. The caller has
195 * checked `by` operates `service`.
196 */
197 export function queuePeople(
198 db: Database,
199 box: GameBox,
200 service: string,
201 op: string,
202 player: string,
203 by: User | undefined,
204 to = "",
205 ): { ok: true; id: string } | { ok: false; error: string } {
206 if (!(PEOPLE_OPS as readonly string[]).includes(op)) return { ok: false, error: `Choose one of: ${PEOPLE_OPS.join(", ")}.` };
207 const whole = op === "whitelist-on" || op === "whitelist-off";
208 if (!whole && !PLAYER.test(player)) return { ok: false, error: "That is not a player's name." };
209 if (op === "move") {
210 if (to === "" || to === service) return { ok: false, error: "Name the server to move them to." };
211 const theirs = servicesOf(db, box.id).some((s) => s.name === to);
212 if (!theirs || !mayDo(roleOn(db, by, box.id, to), "operator"))
213 return { ok: false, error: `Move people only to a server of ${box.name} you operate; ${to} is not one.` };
214 }
215 return {
216 ok: true,
217 id: queueCommand(
218 db,
219 box.id,
220 service,
221 "people",
222 JSON.stringify({ op, ...(whole ? {} : { player }), ...(op === "move" ? { server: to } : {}) }),
223 by?.id ?? "",
224 ),
225 };
226 }
227
228 /** A people command in words: "op Alice", "move Alice to survival", "turn the whitelist on". */
229 export function peopleWords(text: string): string {
230 try {
231 const v = JSON.parse(text) as { op?: string; player?: string; server?: string };
232 if (v.op === "whitelist-on") return "turn the whitelist on";
233 if (v.op === "whitelist-off") return "turn the whitelist off";
234 if (v.op === "move") return `move ${v.player ?? "a player"} to ${v.server ?? "another server"}`;
235 return `${(v.op ?? "change").replace("-", " ")} ${v.player ?? "a player"}`;
236 } catch {
237 return "a change to a player";
238 }
239 }
src/games/store.ts +5 −1
@@ -24,7 +24,7 @@ export const LOG_KEEP = 2_000;
2424 const LINES_A_SYNC = 200;
2525 /** The most of a command's output kept: a shell's 16 KB (`shell.ts`); the rest say far less. */
2626 const OUTPUT_MAX = 16_384;
27 export const COMMAND_KINDS = ["rcon", "restart", "stop", "start", "recreate", "pull", "shell"] as const;
27 export const COMMAND_KINDS = ["rcon", "restart", "stop", "start", "recreate", "pull", "shell", "people"] as const;
2828 export type CommandKind = (typeof COMMAND_KINDS)[number];
2929 export type Role = "owner" | "operator" | "viewer";
3030 const RANK: Record<Role, number> = { viewer: 1, operator: 2, owner: 3 };
@@ -431,6 +431,10 @@ export interface SyncBody {
431431 memMiB?: unknown;
432432 }[];
433433 readonly logs?: Record<string, unknown>;
434 /** Per service, the raw RCON answers the agent read (`list`, `tps`, `mspt`): `games/metrics.ts` parses them. */
435 readonly metrics?: Record<string, unknown>;
436 /** Each server's whitelist, ops and bans, and the proxy's glist (`people.ts`). */
437 readonly people?: unknown;
434438 readonly results?: readonly { id?: unknown; ok?: unknown; output?: unknown }[];
435439 readonly host?: Record<string, unknown>;
436440 /** 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 +42 −38
@@ -443,25 +443,27 @@ 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-advisories.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/20261201190000-game-sleep.ts";
460 import m456 from "../core/migrations/20261201190000-working-edit.ts";
461 import m457 from "../core/migrations/20261201190200-dep-accept.ts";
462 import m458 from "../core/migrations/20261201190500-runner-machine.ts";
463 import m459 from "../core/migrations/20261201200000-cloud-projects.ts";
464 import m460 from "../core/migrations/20261202000000-mail-relay-scope.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-advisories.ts";
456 import m452 from "../core/migrations/20261201150000-dns-record.ts";
457 import m453 from "../core/migrations/20261201150000-pinned-firewall.ts";
458 import m454 from "../core/migrations/20261201170000-managed-database.ts";
459 import m455 from "../core/migrations/20261201180000-game-box-diag.ts";
460 import m456 from "../core/migrations/20261201190000-game-sleep.ts";
461 import m457 from "../core/migrations/20261201190000-working-edit.ts";
462 import m458 from "../core/migrations/20261201190200-dep-accept.ts";
463 import m459 from "../core/migrations/20261201190500-runner-machine.ts";
464 import m460 from "../core/migrations/20261201200000-cloud-projects.ts";
465 import m461 from "../core/migrations/20261202000000-game-people.ts";
466 import m462 from "../core/migrations/20261202000000-mail-relay-scope.ts";
465467
466468 /** Each migration file's name and its default export, in name order. */
467469 export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
@@ -907,23 +909,25 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
907909 ["20261130170100-chat-build-lane.ts", m439],
908910 ["20261130235220-run-check-plan.ts", m440],
909911 ["20261201000000-games.ts", m441],
910 ["20261201090000-app-vital-member.ts", m442],
911 ["20261201120000-first-change-forge.ts", m443],
912 ["20261201121000-repo-check-slots.ts", m444],
913 ["20261201130000-finding-touched.ts", m445],
914 ["20261201130000-game-box-boot.ts", m446],
915 ["20261201140000-app-registry-item.ts", m447],
916 ["20261201140000-infra-snapshot.ts", m448],
917 ["20261201140000-scan-finding-excerpt.ts", m449],
918 ["20261201150000-advisories.ts", m450],
919 ["20261201150000-dns-record.ts", m451],
920 ["20261201150000-pinned-firewall.ts", m452],
921 ["20261201170000-managed-database.ts", m453],
922 ["20261201180000-game-box-diag.ts", m454],
923 ["20261201190000-game-sleep.ts", m455],
924 ["20261201190000-working-edit.ts", m456],
925 ["20261201190200-dep-accept.ts", m457],
926 ["20261201190500-runner-machine.ts", m458],
927 ["20261201200000-cloud-projects.ts", m459],
928 ["20261202000000-mail-relay-scope.ts", m460],
912 ["20261201050000-game-metrics.ts", m442],
913 ["20261201090000-app-vital-member.ts", m443],
914 ["20261201120000-first-change-forge.ts", m444],
915 ["20261201121000-repo-check-slots.ts", m445],
916 ["20261201130000-finding-touched.ts", m446],
917 ["20261201130000-game-box-boot.ts", m447],
918 ["20261201140000-app-registry-item.ts", m448],
919 ["20261201140000-infra-snapshot.ts", m449],
920 ["20261201140000-scan-finding-excerpt.ts", m450],
921 ["20261201150000-advisories.ts", m451],
922 ["20261201150000-dns-record.ts", m452],
923 ["20261201150000-pinned-firewall.ts", m453],
924 ["20261201170000-managed-database.ts", m454],
925 ["20261201180000-game-box-diag.ts", m455],
926 ["20261201190000-game-sleep.ts", m456],
927 ["20261201190000-working-edit.ts", m457],
928 ["20261201190200-dep-accept.ts", m458],
929 ["20261201190500-runner-machine.ts", m459],
930 ["20261201200000-cloud-projects.ts", m460],
931 ["20261202000000-game-people.ts", m461],
932 ["20261202000000-mail-relay-scope.ts", m462],
929933 ];
src/http/games_routes.ts +7 −1
@@ -7,11 +7,13 @@ import { composeServices, readCompose } from "../games/compose.ts";
77 import { AGENT_SH, AGENT_SHA } from "../games/boot.ts";
88 import { synced } from "../games/notify.ts";
99 import { auditShellResults } from "../games/shell.ts";
10 import { recordMetrics } from "../games/metrics.ts";
11 import { recordPeople } from "../games/people.ts";
1012 import { sleeping } from "../games/sleep.ts";
1113 import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, type SyncBody } from "../games/store.ts";
1214 import { BODY_CAPS } from "../kernel/body_caps.ts";
1315 import {
14 gameBoxPage, gameCommandSubmit, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gamePluginSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage,
16 gameBoxPage, gameCommandSubmit, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gamePluginSubmit, gamePeopleSubmit, gameHead, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage,
1517 } from "../web/pages/games.ts";
1618 import type { Ctx, Handler } from "./context.ts";
1719 import { InvalidJson } from "./json_body.ts";
@@ -38,6 +40,8 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
3840 const commands = recordSync(ctx.app.db, box, body);
3941 // Every shell command the box answered, its output with it, into the audit.
4042 auditShellResults(ctx.app, box, (body.results ?? []).map((r) => r.id));
43 recordMetrics(ctx.app.db, box, body);
44 recordPeople(ctx.app.db, box, body.people);
4145 const compose = await readCompose(ctx.app, box);
4246 // A server its sleep stopped is asleep, not down: the compose file says which sleep.
4347 markAsleep(ctx.app.db, box.id, compose === undefined ? [] : sleeping(compose.text));
@@ -70,6 +74,7 @@ export function gamesApiRoutes(router: Router<Handler>): void {
7074 export function gamesRoutes(router: Router<Handler>): void {
7175 router.add("GET", "/games", gamesPage);
7276 router.add("GET", "/games/jar/:id/:name", gameJarDownload);
77 router.add("GET", "/games/head/:uuid", gameHead);
7378 router.add("GET", "/games/:box", gameBoxPage);
7479 router.add("POST", "/games/:box/grant", gameGrantSubmit);
7580 // Before the service routes: no compose service can be named "@shell".
@@ -82,6 +87,7 @@ export function gamesRoutes(router: Router<Handler>): void {
8287 router.add("POST", "/games/:box/:service/env", gameEnvSubmit);
8388 router.add("POST", "/games/:box/:service/plugin", gamePluginSubmit);
8489 router.add("POST", "/games/:box/:service/sleep", gameSleepSubmit);
90 router.add("POST", "/games/:box/:service/people", gamePeopleSubmit);
8591 router.add("POST", "/games/:box/:service/jar", gameJarSubmit);
8692 router.add("POST", "/games/:box/:service/settings", gameSettingsSubmit);
8793 }
src/http/lazy_lists.ts +2
@@ -607,6 +607,7 @@ export const OPERATIONS_ROUTES = [
607607 ["POST", "/infra/:name/:act"],
608608 ["GET", "/games"],
609609 ["GET", "/games/jar/:id/:name"],
610 ["GET", "/games/head/:uuid"],
610611 ["GET", "/games/:box"],
611612 ["POST", "/games/:box/grant"],
612613 ["POST", "/games/:box/@shell"],
@@ -618,6 +619,7 @@ export const OPERATIONS_ROUTES = [
618619 ["POST", "/games/:box/:service/env"],
619620 ["POST", "/games/:box/:service/plugin"],
620621 ["POST", "/games/:box/:service/sleep"],
622 ["POST", "/games/:box/:service/people"],
621623 ["POST", "/games/:box/:service/jar"],
622624 ["POST", "/games/:box/:service/settings"],
623625 ["GET", "/resilience"],
src/http/mcp/tools/games.ts +34 −5
@@ -2,21 +2,28 @@ import { cloudLineFresh, pinnedOfBox } from "../../../actions/cloud_says.ts";
22 import { addPlugin, pluginSays, commitServiceEnv } from "../../../games/compose.ts";
33 import { boxStatus, boxStatusShared } from "../../../games/diag.ts";
44 import { commitSettings, previewSettings, serviceSettings } from "../../../games/settings.ts";
5 import { compactMetrics, compactSeries } from "../../../games/metrics_answer.ts";
6 import { WINDOWS, type Window } from "../../../games/metrics.ts";
57 import { boxNamed, listBoxes, mayDo, queueCommand, roleOn, seesBox, SERVICE_NAME, servicesOf, type CommandKind } from "../../../games/store.ts";
68 import { good, bad, type Tool, str } from "../shared.ts";
79 import { commitPolicy } from "../../../games/sleep.ts";
10 import { eventsOf, networkOf, PEOPLE_OPS, peopleOf, peopleWords, queuePeople } from "../../../games/people.ts";
811
912 const POWER = ["start", "stop", "restart", "recreate", "pull"];
1013
1114 export const tool: Tool = {
1215 name: "games",
1316 listedTo: "admin",
14 doc: "`{ action, box?, service?, text?, kind?, key?, value?, modrinth?, preview?, dryRun? }`: game boxes. `list`; `sleep` sets a `service` to `value` warm or sleep (stops when empty, starts on join), a commit; `console` queues `text` as RCON; `power` `kind` (start, stop, restart); `env` commits `key`=`value` (empty removes); `plugin` adds a `modrinth` slug (`preview` true only says what it would add: the newest compatible version and its required dependencies; incompatible is refused with the reason, a lockfile with sha512 is committed); `config` lists a service's settings (server.properties, Paper's); `config_set` sets `key` to `value`, planned first (`dryRun: false` commits the plan on the commit it was planned on). Grants as on /games",
15 description: "Game boxes: list, console, power, env, plugins, settings, sleep.",
17 doc: "`{ action, box?, service?, text?, kind?, key?, value?, modrinth?, preview?, dryRun?, window? }`: game boxes. `list`; `metrics` per service (now, 1h, 24h), or one `service` over `window` (1h to 30d); `sleep` sets a `service` to `value` warm or sleep (stops when empty, starts on join), a commit; `console` queues `text` as RCON; `power` `kind` (start, stop, restart); `env` commits `key`=`value` (empty removes); `plugin` adds a `modrinth` slug (`preview` true only says what it would add: the newest compatible version and its required dependencies; incompatible is refused with the reason, a lockfile with sha512 is committed); `people` with `op` list (online, whitelist, ops, bans, who is where, the latest joins, deaths and chat) or op, deop, whitelist-add, whitelist-remove, whitelist-on, whitelist-off, ban, pardon, kick for `player`, or move `player` to `to`; `config` lists a service's settings (server.properties, Paper's); `config_set` sets `key` to `value`, planned first (`dryRun: false` commits the plan on the commit it was planned on). Grants as on /games",
18 description: "Game boxes: list, metrics, console, power, env, plugins, people, settings, sleep.",
1619 inputSchema: {
1720 type: "object",
1821 properties: {
19 action: { type: "string", enum: ["list", "console", "power", "env", "plugin", "config", "config_set", "sleep"] },
22 action: { type: "string", enum: ["list", "metrics", "console", "power", "env", "plugin", "people", "config", "config_set", "sleep"] },
23 op: { type: "string", enum: ["list", ...PEOPLE_OPS] },
24 player: { type: "string", maxLength: 17 },
25 to: { type: "string", maxLength: 64 },
26 window: { type: "string", enum: Object.keys(WINDOWS) },
2027 box: { type: "string", maxLength: 40 },
2128 service: { type: "string", maxLength: 64 },
2229 text: { type: "string", maxLength: 1000 },
@@ -30,7 +37,12 @@ export const tool: Tool = {
3037 required: ["action"],
3138 },
3239 writes: true,
33 heldNotWhen: (args) => args["action"] === "list" || args["action"] === "config" || (args["action"] === "config_set" && args["dryRun"] !== false),
40 heldNotWhen: (args) =>
41 args["action"] === "list" ||
42 args["action"] === "metrics" ||
43 (args["action"] === "people" && args["op"] === "list") ||
44 args["action"] === "config" ||
45 (args["action"] === "config_set" && args["dryRun"] !== false),
3446 async run(ctx, user, args) {
3547 const action = str(args["action"]);
3648 const db = ctx.app.db;
@@ -60,6 +72,14 @@ export const tool: Tool = {
6072 }
6173 const box = boxNamed(db, str(args["box"]));
6274 const service = str(args["service"]);
75 if (action === "metrics") {
76 if (box === undefined || !seesBox(db, user, box.id)) return bad("not_found", "no such box here");
77 if (service === "") return good(compactMetrics(db, box, (s) => mayDo(roleOn(db, user, box.id, s), "viewer")));
78 if (!SERVICE_NAME.test(service) || !mayDo(roleOn(db, user, box.id, service), "viewer")) return bad("not_found", "no such service here");
79 const window = (str(args["window"]) || "1h") as Window;
80 if (!(window in WINDOWS)) return bad("invalid", `window is one of ${Object.keys(WINDOWS).join(", ")}`);
81 return good(compactSeries(db, box, service, window));
82 }
6383 if (box === undefined || !seesBox(db, user, box.id) || !SERVICE_NAME.test(service)) return bad("not_found", "no such box or service here");
6484 if (action === "config") {
6585 if (!mayDo(roleOn(db, user, box.id, service), "viewer")) return bad("forbidden", `you may not see ${service} on ${box.name}`);
@@ -99,6 +119,15 @@ export const tool: Tool = {
99119 const done = await addPlugin(ctx.app, user, box, service, { modrinth: str(args["modrinth"]) }, { dry: args["preview"] === true });
100120 return done.ok ? good({ says: pluginSays(done, args["preview"] === true), sha: done.sha }) : bad("refused", done.error);
101121 }
122 if (action === "people") {
123 const op = str(args["op"]);
124 if (op === "list") {
125 const { online, lists } = peopleOf(db, box.id, service);
126 return good({ service, online, ...lists, network: networkOf(db, box.id), latest: eventsOf(db, box.id, service, 50) });
127 }
128 const queued = queuePeople(db, box, service, op, str(args["player"]), user, str(args["to"]));
129 return queued.ok ? good({ says: `Queued: ${peopleWords(JSON.stringify({ op, player: str(args["player"]), server: str(args["to"]) }))}; the box does it on its next sync.`, id: queued.id }) : bad("refused", queued.error);
130 }
102131 if (action === "config_set") {
103132 const plan = await previewSettings(ctx.app, box, service, { [str(args["key"])]: str(args["value"]) });
104133 if (!plan.ok) return bad("refused", plan.error);
@@ -113,6 +142,6 @@ export const tool: Tool = {
113142 const done = await commitPolicy(ctx.app, user, box, service, policy);
114143 return done.ok ? good({ says: `${service} ${policy === "sleep" ? "sleeps when empty" : "stays warm"} once the box redeploys (${done.sha.slice(0, 10)}).`, sha: done.sha }) : bad("refused", done.error);
115144 }
116 return bad("bad_action", "action is list, console, power, env, plugin, config, config_set or sleep");
145 return bad("bad_action", "action is list, metrics, console, power, env, plugin, people, config, config_set or sleep");
117146 },
118147 };
src/tui/screens/games.ts +30 −3
@@ -16,6 +16,7 @@ import { emptyText } from "../../core/empty_words.ts";
1616 import { commitPolicy, policyOf, stateWords } from "../../games/sleep.ts";
1717 import { SHELL_SERVICE, queueShell } from "../../games/shell.ts";
1818 import { onSync } from "../../games/notify.ts";
19 import { eventsOf, isBedrock, peopleOf, peopleWords, queuePeople } from "../../games/people.ts";
1920 import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts";
2021 import { cloudLine, pinnedOfBox } from "../../actions/cloud_says.ts";
2122 import { getUserByName } from "../../core/users.ts";
@@ -39,6 +40,7 @@ import {
3940 type GameBox,
4041 type Role,
4142 } from "../../games/store.ts";
43 import { metricsSeries } from "../../games/metrics.ts";
4244 import type { Ctx, Screen } from "../app/app.ts";
4345 import { binding } from "../app/keys.ts";
4446 import { style } from "../term/style.ts";
@@ -48,6 +50,12 @@ import { fill, len, split } from "../ui/layout.ts";
4850 import { ListState, drawList, promptScreen, type ListRow } from "./common.ts";
4951 import type { PaletteEntry } from "./entries.ts";
5052
53 /** "4 online · 19.8 TPS · " from the last hour's numbers, or nothing before any. */
54 function playersTps(f: Session, box: { id: string }, service: string): string {
55 const last = metricsSeries(f.app.db, box, service, "1h").at(-1);
56 return last === undefined ? "" : `${last.players} online · ${last.tps === null ? "" : `${last.tps} TPS · `}`;
57 }
58
5159 export function gamesScreen(f: Session, ctx: Ctx): Screen {
5260 const state = new ListState();
5361 let note = "";
@@ -100,7 +108,7 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
100108 const view: ListRow[] = all.map(({ box, service }) => ({
101109 title: `${box.name}/${service.name}`,
102110 ...(service.state === "exited" ? { tone: "danger" as const } : {}),
103 secondary: `${stateWords(service.state, service.asleep)} · ${Math.round(service.memMiB)} MiB · ${service.cpuPct.toFixed(1)}% CPU`,
111 secondary: `${stateWords(service.state, service.asleep)} · ${playersTps(f, box, service.name)}${Math.round(service.memMiB)} MiB · ${service.cpuPct.toFixed(1)}% CPU`,
104112 meta: box.seenAt.slice(11, 19),
105113 }));
106114 // The machines after the services: the cursor moves over the services only.
@@ -161,7 +169,7 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
161169 return screen;
162170 }
163171
164 const PARTS = ["console", "env", "plugins"] as const;
172 const PARTS = ["console", "env", "plugins", "people"] as const;
165173 type Part = (typeof PARTS)[number];
166174
167175 /**
@@ -189,6 +197,17 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
189197 const done = recentCommands(f.app.db, box.id, service, 5).map((c) => `> ${c.text} ${c.done ? (c.ok ? "ok" : "failed") : "waiting for the box"}${c.output === "" ? "" : `: ${c.output.split("\n")[0]}`}`);
190198 return [...logsOf(f.app.db, box.id, service, 200).lines, ...done];
191199 }
200 if (part === "people") {
201 const { online, lists } = peopleOf(f.app.db, box.id, service);
202 const tag = (n: string) => `${n}${isBedrock(n) ? " (Bedrock)" : ""}${lists.ops.some((o) => o.name === n) ? " · op" : ""}`;
203 return [
204 online.length === 0 ? `Nobody is on ${service} right now.` : `Online: ${online.map((p) => tag(p.name)).join(", ")}`,
205 `Whitelist ${lists.whitelistOn ? "on" : "off"} · ${lists.whitelist.length} listed · ${lists.ops.length} ops · ${lists.bans.length} banned`,
206 ...lists.bans.map((b) => `banned: ${b.name}${b.reason === "" ? "" : ` (${b.reason})`}`),
207 ...eventsOf(f.app.db, box.id, service, 20).map((e) => `${e.at.slice(11, 16)} ${e.kind === "chat" ? `<${e.player}> ${e.text}` : e.kind === "death" ? e.text : `${e.player} ${e.kind === "join" ? "joined" : "left"}`}`),
208 "p: op, deop, whitelist-add, whitelist-remove, ban, pardon, kick <player>, or move <player> <server>",
209 ];
210 }
192211 if (!loaded) return ["Reading the compose file…"];
193212 if (compose === undefined) return [`No ${box.path} on ${box.repo}@${box.branch}.`];
194213 if (part === "env") {
@@ -219,11 +238,12 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
219238 const screen: Screen = {
220239 title: `${box.name}/${service}`,
221240 keys: [
222 binding(["tab"], "console, env, plugins"),
241 binding(["tab"], "console, env, plugins, people"),
223242 binding([":"], "rcon"),
224243 binding(["e"], "set env"),
225244 binding(["a"], "add plugin"),
226245 binding(["c"], "settings"),
246 binding(["p"], "a player: op, ban, kick, move…"),
227247 ],
228248 render(area, s) {
229249 const c = ctx.theme.c;
@@ -261,6 +281,13 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
261281 return `Committed ${done.sha.slice(0, 10)}; the box redeploys on its next sync.`;
262282 });
263283 else if (e.key === "c") ctx.push(gameSettingsScreen(f, ctx, box, service));
284 else if (e.key === "p")
285 ask("Player", "op | deop | whitelist-add | whitelist-remove | ban | pardon | kick <player>, or move <player> <server>", async (raw) => {
286 const [op = "", player = "", to = ""] = raw.trim().split(/\s+/);
287 const queued = queuePeople(f.app.db, box, service, op, player, f.user, to);
288 part = "people";
289 return queued.ok ? `Asked: ${peopleWords(JSON.stringify({ op, player, server: to }))}; the box does it on its next sync.` : queued.error;
290 });
264291 else if (e.key === "a")
265292 ask("Plugin", "A Modrinth slug (start with ? to preview it), or an https URL to a jar", async (raw) => {
266293 const dry = raw.trim().startsWith("?");
src/web/pages/games.ts +118 −2
@@ -49,7 +49,25 @@ import { badge, btn, disclosure, field as input, row, rowList, time } from "../u
4949 import { onSync } from "../../games/notify.ts";
5050 import { canSleep, commitPolicy, EMPTY_SECONDS, policyOf, stateWords } from "../../games/sleep.ts";
5151 import { CLOUD_EVENT, cloudFacts, GAME_CLOUD_EVENT, pinnedOfBox } from "../../actions/cloud_says.ts";
52 import { topologyBlock, TOPOLOGY_CSS } from "./games_topology.ts";
53 import { defaultHeadResponse, headResponse } from "../../games/heads.ts";
54 import { eventsOf, isBedrock, knowsPlayer, peopleOf, peopleWords, queuePeople, UNDO, type PeopleOp } from "../../games/people.ts";
5255 import { emptyLine } from "../empty_words.ts";
56 import { metricsSeries, playerEvents, recentErrors, type Point } from "../../games/metrics.ts";
57 import { daySpark } from "../studio/kpi_row.ts";
58
59 /** A small line of a series (oldest first); nothing when no point is known. */
60 const sparkOf = (points: readonly Point[], pick: (p: Point) => number | null, label: string): Html | null =>
61 daySpark(points.map(pick), label);
62
63 /** The last known value of a series. */
64 const lastOf = (points: readonly Point[], pick: (p: Point) => number | null): number | null => {
65 for (let i = points.length - 1; i >= 0; i--) {
66 const v = pick(points[i]!);
67 if (v !== null) return v;
68 }
69 return null;
70 };
5371
5472 const dollars = (cents: number): string => `$${(cents / 100).toFixed(2)}`;
5573 const mib = (n: number | undefined): string =>
@@ -126,6 +144,7 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> {
126144 return timePhase(ctx.request, "render", () => page({
127145 ctx,
128146 title: `Games · ${box.name}`,
147 styleCss: TOPOLOGY_CSS,
129148 // The owner's console streams its answers over the box's own sync, as a service's does.
130149 ...(role === "owner" ? { scriptJs: gamesConsoleJs } : {}),
131150 body: html`${pageHead(box.name, {
@@ -140,16 +159,21 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> {
140159 visible.map((n) => {
141160 const s = seen.find((x) => x.name === n);
142161 const act = mayDo(roleOn(ctx.app.db, user, box.id, n), "operator");
162 const day = metricsSeries(ctx.app.db, box, n, "24h");
163 const tps = lastOf(day, (p) => p.tps);
164 const players = day.length === 0 ? null : day.at(-1)!.players;
143165 return row({
144166 href: `/games/${box.name}/${n}`,
145167 title: n,
146168 trail: badge(stateWords(s?.state ?? "", s?.asleep === true), { tone: s?.asleep === true ? "default" : (TONE[s?.state ?? ""] ?? "default") }),
147 meta: html`${mib(s?.memMiB)} ·
148 ${s === undefined ? "" : `${s.cpuPct.toFixed(1)}% CPU`}${s?.startedAt ? html` · up since ${time(s.startedAt)}` : ""}`,
169 meta: html`${players === null ? "" : `${players} online · `}${tps === null ? "" : `${tps.toFixed(1)} TPS · `}${mib(s?.memMiB)} ·
170 ${s === undefined ? "" : `${s.cpuPct.toFixed(1)}% CPU`}${s?.startedAt ? html` · up since ${time(s.startedAt)}` : ""}
171 ${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>`}`,
149172 ...(act ? { after: power(box, n) } : {}),
150173 });
151174 }),
152175 )}
176 ${topologyBlock(ctx, box, compose?.text, visible)}
153177 ${role === "owner" ? boxBlock(box) : sharedBoxBlock(box)} ${role === "owner" ? shellBlock(ctx, box) : null}
154178 ${role === "owner" ? grantsBlock(ctx, box) : null}`,
155179 }));
@@ -296,6 +320,8 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> {
296320 title: `${service} · ${box.name}`,
297321 scriptJs: gamesConsoleJs,
298322 body: html`${pageHead(service, { sub: `on ${box.name}`, actions: act ? power(box, service) : undefined })}
323 ${numbersBlock(ctx, box, service)}
324 ${peopleBlock(ctx, box, service, act)}
299325 <section class="settings-block">
300326 <h2>Console</h2>
301327 <pre
@@ -377,6 +403,24 @@ ${tail.lines.join("\n")}${tail.lines.length > 0 ? "\n" : ""}</pre
377403 }));
378404 }
379405
406 /** A service's numbers: 24 hours of players, TPS, tick time and memory, then the latest joins and errors. */
407 function numbersBlock(ctx: Ctx, box: GameBox, service: string): Html {
408 const day = metricsSeries(ctx.app.db, box, service, "24h");
409 const joins = playerEvents(ctx.app.db, box.id, service, 8);
410 const errors = recentErrors(ctx.app.db, box.id, service, 5);
411 if (day.length === 0 && joins.length === 0 && errors.length === 0) return html``;
412 const line = (label: string, pick: (p: Point) => number | null, unit: string): Html => {
413 const now = lastOf(day, pick);
414 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>` });
415 };
416 return html`<section class="settings-block">
417 <h2>Numbers, last 24 hours</h2>
418 ${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, "")])}
419 ${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)}` })))}`}
420 ${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) })))}`}
421 </section>`;
422 }
423
380424 // GET /games/:box/:service/stream: new log lines and command results after each sync.
381425 export function gameServiceStream(ctx: Ctx): Response {
382426 const service = ctx.params.service ?? "";
@@ -587,6 +631,78 @@ export async function gameSleepSubmit(ctx: Ctx): Promise<Response> {
587631 }
588632
589633 // POST /games/:box/:service/plugin: a Modrinth slug.
634 /** A player's head and name, with a Bedrock badge for a Floodgate player. */
635 const who = (name: string, uuid: string): Html =>
636 html`<img src="/games/head/${uuid === "" || isBedrock(name) ? "none" : uuid}" alt="" width="20" height="20" loading="lazy" /> ${name}${isBedrock(name) ? html` ${badge("Bedrock", { tone: "default" })}` : null}`;
637
638 /** One button that sends a people change for `player` on the service's form. */
639 const peopleButton = (base: string, op: PeopleOp, player: string, label: string): Html =>
640 html`<form method="post" action="${base}/people" class="row-fields"><input type="hidden" name="op" value="${op}" /><input type="hidden" name="player" value="${player}" />${btn(label, { variant: "secondary", size: "sm" })}</form>`;
641
642 /**
643 * Who plays here: online now with their heads, whitelist, ops and bans, each with its toggle for an
644 * operator, and the latest joins, leaves, deaths and chat. The page is a viewer's or above, so chat
645 * is seen by nobody without a grant.
646 */
647 function peopleBlock(ctx: Ctx, box: GameBox, service: string, act: boolean): Html {
648 const { online, lists } = peopleOf(ctx.app.db, box.id, service);
649 const events = eventsOf(ctx.app.db, box.id, service, 30);
650 const base = `/games/${box.name}/${service}`;
651 const isOp = (n: string) => lists.ops.some((o) => o.name === n);
652 const listed = (n: string) => lists.whitelist.some((w) => w.name === n);
653 const toggles = (n: string): Html | null =>
654 act
655 ? html`<span class="row-fields">${peopleButton(base, isOp(n) ? "deop" : "op", n, isOp(n) ? "Deop" : "Op")}${lists.whitelistOn ? peopleButton(base, listed(n) ? "whitelist-remove" : "whitelist-add", n, listed(n) ? "Unlist" : "Whitelist") : null}${peopleButton(base, "kick", n, "Kick")}${peopleButton(base, "ban", n, "Ban")}</span>`
656 : null;
657 const words: Record<string, string> = { join: "joined", leave: "left", death: "", chat: "" };
658 return html`<section class="settings-block">
659 <h2>People</h2>
660 ${online.length === 0
661 ? html`<p class="muted small">Nobody is on ${service} right now.</p>`
662 : rowList(online.map((p) => row({ title: who(p.name, p.uuid), meta: html`${isOp(p.name) ? "op" : ""}`, ...(act ? { after: toggles(p.name) ?? html`` } : {}) })))}
663 ${act
664 ? html`<form method="post" action="${base}/people" class="row-fields">
665 ${input({ name: "player", label: "Player", required: true, mono: true })}
666 <select class="input" name="op" aria-label="What to do">
667 <option value="whitelist-add">Whitelist</option><option value="op">Op</option><option value="ban">Ban</option><option value="pardon">Pardon</option>
668 </select>
669 ${btn("Do it", { variant: "secondary" })}
670 </form>
671 ${peopleButton(base, lists.whitelistOn ? "whitelist-off" : "whitelist-on", "", lists.whitelistOn ? "Turn the whitelist off" : "Turn the whitelist on")}`
672 : null}
673 <p class="muted small">Whitelist ${lists.whitelistOn ? "on" : "off"} · ${lists.whitelist.length} listed · ${lists.ops.length} ops · ${lists.bans.length} banned</p>
674 ${lists.bans.length === 0 ? null : html`<h3>Banned</h3>${rowList(lists.bans.map((b) => row({ title: who(b.name, b.uuid), meta: html`${b.reason}`, ...(act ? { after: peopleButton(base, "pardon", b.name, "Pardon") } : {}) })))}`}
675 ${lists.ops.length === 0 ? null : html`<h3>Ops</h3>${rowList(lists.ops.map((o) => row({ title: who(o.name, o.uuid), meta: html`level ${o.level}`, ...(act ? { after: peopleButton(base, "deop", o.name, "Deop") } : {}) })))}`}
676 ${lists.whitelistOn && lists.whitelist.length > 0 ? html`<h3>Whitelist</h3>${rowList(lists.whitelist.map((w) => row({ title: who(w.name, w.uuid), ...(act ? { after: peopleButton(base, "whitelist-remove", w.name, "Unlist") } : {}) })))}` : null}
677 ${events.length === 0
678 ? null
679 : html`<h3>Latest</h3>${rowList(events.map((e) => row({ title: e.kind === "chat" ? html`<span class="mono">&lt;${e.player}&gt;</span> ${e.text}` : e.kind === "death" ? e.text : `${e.player} ${words[e.kind]}`, meta: time(e.at) })))}`}
680 </section>`;
681 }
682
683 // POST /games/:box/:service/people: whitelist, op, ban, kick or move a player, through the box.
684 export async function gamePeopleSubmit(ctx: Ctx): Promise<Response> {
685 const got = await operatorForm(ctx);
686 if (got instanceof Response) return got;
687 const op = field(got.form, "op");
688 const player = field(got.form, "player").trim();
689 const queued = queuePeople(ctx.app.db, got.box, got.service, op, player, ctx.auth.user, field(got.form, "to"));
690 const undo = UNDO[op as PeopleOp];
691 return flashTo(
692 ctx,
693 `/games/${got.box.name}/${got.service}`,
694 queued.ok ? { message: `Asked: ${peopleWords(JSON.stringify({ op, player, server: field(got.form, "to") }))}, on the box's next sync.${undo === undefined ? "" : " Its opposite undoes it."}` } : { tone: "danger", message: queued.error },
695 );
696 }
697
698 // GET /games/head/:uuid: a player's head, kept on the forge's disk (`games/heads.ts`). Signed in
699 // only, and only for a player the forge has seen on a server this person sees; anyone else's is the default.
700 export function gameHead(ctx: Ctx): Promise<Response> | Response {
701 const uuid = (ctx.params.uuid ?? "").toLowerCase();
702 if (!knowsPlayer(ctx.app.db, ctx.auth.user, uuid)) return defaultHeadResponse();
703 return headResponse(ctx.app, uuid);
704 }
705
590706 export async function gamePluginSubmit(ctx: Ctx): Promise<Response> {
591707 const got = await operatorForm(ctx);
592708 if (got instanceof Response) return got;
src/web/pages/games_topology.ts added +127
@@ -0,0 +1,127 @@
1 /**
2 * The network as a picture (#17284 G5): the proxy on top, each game server under it, awake, waking,
3 * asleep or stopped, with the heads of who is on it and its TPS. A server opens its own page; a head
4 * opens to the servers it can be moved to, one button each (an operator's), so a move is picking a
5 * head and a target. Plain HTML and a little CSS from the design tokens: no script, and it folds to
6 * one column on a phone.
7 */
8
9 import type { Ctx } from "../../http/context.ts";
10 import { metricsSeries } from "../../games/metrics.ts";
11 import { isBedrock, networkOf, peopleOf } from "../../games/people.ts";
12 import { mayDo, roleOn, servicesOf, type GameBox, type GameService } from "../../games/store.ts";
13 import { html, type Html } from "../html.ts";
14 import { btn } from "../ui.ts";
15
16 export const TOPOLOGY_CSS = `/* ---- the network (#17284 G5): the proxy, a line down, the servers under it ---- */
17 .net { display: grid; gap: 16px; justify-items: center; }
18 .net-node {
19 display: grid; gap: 2px; min-width: 160px; padding: 10px 12px;
20 border: 1px solid var(--border); border-radius: var(--radius); background: var(--card);
21 color: inherit; text-decoration: none;
22 }
23 .net-node:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
24 @media (hover: hover) { .net-node:hover { border-color: var(--accent); } }
25 .net-node strong { font-size: 14px; }
26 .net-node small { color: var(--muted-fg); font-variant-numeric: tabular-nums; }
27 .net-servers {
28 margin: 0; padding: 16px 0 0; width: 100%;
29 display: grid; gap: 12px; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
30 border-top: 1px solid var(--border);
31 }
32 .net-server { display: grid; gap: 8px; align-content: start; }
33 .net-server[data-state="awake"] > .net-node { border-left: 3px solid var(--success); }
34 .net-server[data-state="waking"] > .net-node { border-left: 3px solid var(--attn); }
35 .net-server[data-state="asleep"] > .net-node { border-left: 3px dashed var(--muted-fg); }
36 .net-server[data-state="stopped"] > .net-node { border-left: 3px solid var(--danger); }
37 .net-heads { display: flex; flex-wrap: wrap; gap: 6px; }
38 .net-head > summary { list-style: none; display: inline-flex; align-items: center; gap: 4px; cursor: pointer; font-size: 13px; }
39 .net-head > summary::-webkit-details-marker { display: none; }
40 .net-head > summary img { border-radius: var(--radius-sm); }
41 .net-head form { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 4px; }
42 `;
43
44 export type NetState = "awake" | "waking" | "asleep" | "stopped";
45
46 /**
47 * A server's state in four words: running and healthy is awake; running while its health check
48 * still starts is waking (a sleeper coming up on a join); stopped by its sleep is asleep; any other
49 * stop is stopped.
50 */
51 export function netState(s: GameService | undefined): NetState {
52 if (s === undefined) return "stopped";
53 if (s.state === "running") return s.health === "starting" ? "waking" : "awake";
54 if (s.state === "restarting" || s.state === "created") return "waking";
55 return s.asleep ? "asleep" : "stopped";
56 }
57 const STATE_WORDS: Record<NetState, string> = { awake: "awake", waking: "waking up", asleep: "asleep, wakes on join", stopped: "stopped" };
58
59 /** The proxy players come in through: the compose service running itzg's mc-proxy. */
60 export function proxyOf(compose: string | undefined): string | undefined {
61 if (compose === undefined) return undefined;
62 try {
63 const doc = Bun.YAML.parse(compose) as { services?: Record<string, { image?: unknown }> } | null;
64 return Object.entries(doc?.services ?? {}).find(([, s]) => typeof s.image === "string" && /(^|\/)itzg\/mc-proxy(:|$)/.test(s.image))?.[0];
65 } catch {
66 return undefined;
67 }
68 }
69
70 /** The network block, or nothing when the box has no proxy in its compose file. */
71 export function topologyBlock(ctx: Ctx, box: GameBox, compose: string | undefined, visible: readonly string[]): Html {
72 const proxy = proxyOf(compose);
73 if (proxy === undefined) return html``;
74 const user = ctx.auth.user!;
75 const seen = servicesOf(ctx.app.db, box.id);
76 const servers = visible.filter((n) => n !== proxy);
77 const network = networkOf(ctx.app.db, box.id);
78 // Each player's UUID from the server they are on (its `list uuids`), for their head.
79 const uuidOf = new Map<string, string>();
80 const onServer = (n: string): string[] => {
81 const { online } = peopleOf(ctx.app.db, box.id, n);
82 for (const p of online) uuidOf.set(p.name, p.uuid);
83 return network[n] ?? online.map((p) => p.name);
84 };
85 const players = new Map(servers.map((n) => [n, onServer(n)] as const));
86 const total = [...players.values()].reduce((sum, list) => sum + list.length, 0);
87 const proxyState = netState(seen.find((s) => s.name === proxy));
88 const head = (server: string, name: string, act: boolean): Html => {
89 const uuid = uuidOf.get(name) ?? "";
90 const face = html`<img src="/games/head/${uuid === "" || isBedrock(name) ? "none" : uuid}" alt="" width="20" height="20" loading="lazy" />`;
91 // Only to a server this person operates too: the move's own rule (`queuePeople`).
92 const targets = servers.filter((t) => t !== server && netState(seen.find((s) => s.name === t)) !== "stopped" && mayDo(roleOn(ctx.app.db, user, box.id, t), "operator"));
93 if (!act || targets.length === 0) return html`<span class="net-head">${face} ${name}</span>`;
94 return html`<details class="net-head">
95 <summary>${face} ${name}</summary>
96 <form method="post" action="/games/${box.name}/${server}/people" aria-label="Move ${name}">
97 <input type="hidden" name="op" value="move" /><input type="hidden" name="player" value="${name}" />
98 ${targets.map((t) => btn(`To ${t}`, { variant: "secondary", size: "sm", name: "to", value: t }))}
99 </form>
100 </details>`;
101 };
102 return html`<section class="settings-block" data-topology>
103 <h2>The network</h2>
104 <div class="net">
105 <a class="net-node" href="/games/${box.name}/${proxy}" data-state="${proxyState}">
106 <strong>${proxy}</strong>
107 <small>the way in · ${STATE_WORDS[proxyState]} · ${total === 1 ? "1 player" : `${total} players`}</small>
108 </a>
109 <div class="net-servers">
110 ${servers.map((n) => {
111 const s = seen.find((x) => x.name === n);
112 const state = netState(s);
113 const tps = metricsSeries(ctx.app.db, box, n, "1h").findLast((p) => p.tps !== null)?.tps ?? null;
114 const list = players.get(n) ?? [];
115 const act = mayDo(roleOn(ctx.app.db, user, box.id, n), "operator");
116 return html`<div class="net-server" data-state="${state}">
117 <a class="net-node" href="/games/${box.name}/${n}">
118 <strong>${n}</strong>
119 <small>${STATE_WORDS[state]}${tps === null ? "" : ` · ${tps.toFixed(1)} TPS`} · ${list.length === 1 ? "1 player" : `${list.length} players`}</small>
120 </a>
121 ${list.length === 0 ? null : html`<div class="net-heads">${list.map((name) => head(n, name, act))}</div>`}
122 </div>`;
123 })}
124 </div>
125 </div>
126 </section>`;
127 }
test/budgets/unfixtured/games-head-uuid.json added +4
@@ -0,0 +1,4 @@
1 {
2 "pattern": "/games/head/:uuid",
3 "why": "no fixture holds the id this route needs"
4 }
test/conversation-ask.test.ts +2
@@ -524,6 +524,8 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [
524524 ["games", { action: "config_set", box: "net", service: "hub", key: "view-distance", value: "12", dryRun: false }, "Set the setting view-distance on hub on net to 12, a commit that restarts it."],
525525 ["games", { action: "sleep", box: "net", service: "hunting", value: "sleep" }, "Let hunting on net sleep when empty and wake on join, a commit that redeploys it."],
526526 ["games", { action: "sleep", box: "net", service: "hub", value: "warm" }, "Keep hub on net warm, a commit that redeploys it."],
527 ["games", { action: "people", box: "mc", service: "hub", op: "ban", player: "Griefer" }, "Ban Griefer from hub on mc."],
528 ["games", { action: "people", box: "mc", service: "hub", op: "move", player: ".Steve", to: "survival" }, "Move .Steve to survival."],
527529 ["crew_accounts", { repo: "marin/cakes", allow: "espo-corp" }, "Let the crew's runs for marin/cakes spend the account espo-corp."],
528530 ["subscriptions", { everywhere: "espo-corp" }, "Put the account espo-corp in the pool, so the crew uses it by default on every repository a forge admin owns."],
529531 ["subscriptions", { limit: "espo-corp" }, "Keep the account espo-corp to where it is allowed."],
test/game-metrics.test.ts added +242
@@ -0,0 +1,242 @@
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")).toMatchObject({
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: ")).toMatchObject({ 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")).toMatchObject({
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")).toMatchObject({
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")).toMatchObject({ 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 // Chat, not a join: the words are Alice's.
81 expect(parseLogLine("[12:00:04 INFO]: <Alice> I joined the game yesterday")).toEqual({ kind: "chat", player: "Alice", text: "I joined the game yesterday" });
82 expect(parseLogLine('[12:00:05 INFO]: Done (3.2s)! For help, type "help"')).toBeUndefined();
83 });
84
85 test("stats: min, avg, max, p95", () => {
86 expect(stats([])).toBeUndefined();
87 expect(stats([20, 20, 19, 10])).toEqual({ min: 10, avg: 17.3, max: 20, p95: 20 });
88 });
89 });
90
91 describe("the rollup", () => {
92 const db = new Database(":memory:");
93 beforeAll(async () => {
94 const m = await import("../src/core/migrations/20261201000000-games.ts");
95 const n = await import("../src/core/migrations/20261201050000-game-metrics.ts");
96 db.exec("CREATE TABLE user (id TEXT PRIMARY KEY, username TEXT)");
97 db.exec(m.default);
98 db.exec(n.default);
99 db.exec((await import("../src/core/migrations/20261202000000-game-people.ts")).default.replace(/^.*game_box.*$/m, ""));
100 db.query("INSERT INTO game_service (box_id, name) VALUES ('b', 'hub')").run();
101 });
102
103 test("syncs within a minute roll into one row; the next minute is its own", () => {
104 const t0 = new Date("2026-12-01T01:00:05Z");
105 const body = (players: number, tps: string, cpu: number) => ({
106 services: [{ name: "hub", cpuPct: cpu, memMiB: 1000 }],
107 metrics: {
108 hub: {
109 list: `There are ${players} of a max of 20 players online: Alice`,
110 tps: `TPS from last 1m, 5m, 15m: ${tps}, 20, 20`,
111 mspt: "",
112 },
113 },
114 logs: { hub: ["[01:00:01 INFO]: Alice joined the game", "[01:00:02 ERROR]: boom"] },
115 });
116 recordMetrics(db, { id: "b" }, body(1, "20.0", 10), t0);
117 recordMetrics(db, { id: "b" }, body(3, "18.0", 30), new Date(t0.getTime() + 20_000));
118 recordMetrics(db, { id: "b" }, body(2, "19.0", 20), new Date(t0.getTime() + 60_000));
119 const rows = db
120 .query<
121 { minute: number; n: number; players_max: number; players_last: number; tps_min: number; errors: number; joins: number },
122 []
123 >("SELECT minute, n, players_max, players_last, tps_min, errors, joins FROM game_metric ORDER BY minute")
124 .all();
125 expect(rows.map((r) => [r.n, r.players_max, r.players_last, r.tps_min, r.errors, r.joins])).toEqual([
126 [2, 3, 3, 18, 2, 2],
127 [1, 2, 2, 19, 1, 1],
128 ]);
129 const series = metricsSeries(db, { id: "b" }, "hub", "1h", new Date(t0.getTime() + 61_000));
130 expect(series.map((p) => [p.players, p.tps, p.cpu, p.errors])).toEqual([
131 [3, 19, 20, 2],
132 [2, 19, 20, 1],
133 ]);
134 const summary = metricsSummary(db, { id: "b" }, new Date(t0.getTime() + 61_000)) as Record<
135 string,
136 { now: { players: number; tps: number; online: string[] }; "1h": { peakPlayers: number; errors: number } }
137 >;
138 expect(summary["hub"]!.now).toMatchObject({ players: 2, tps: 19, online: ["Alice"] });
139 expect(summary["hub"]!["1h"]).toMatchObject({ peakPlayers: 3, errors: 3 });
140 expect(playerEvents(db, "b", "hub").length).toBe(3);
141 });
142
143 test("a summary of a big network and a month's series stay under the answer bound", () => {
144 const start = Date.parse("2026-11-01T00:00:00Z");
145 const services = Array.from({ length: 40 }, (_, i) => `server-number-${i}`);
146 for (const s of services) db.query("INSERT INTO game_service (box_id, name) VALUES ('big', ?1)").run(s);
147 db.transaction(() => {
148 for (let m = 0; m < 1440; m += 5)
149 for (const s of services)
150 db.query(
151 "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)",
152 ).run(s, Math.floor(start / 60_000) + m);
153 })();
154 const at = new Date(start + 1440 * 60_000);
155 const all = compactMetrics(db, { id: "big", name: "big" }, () => true, at);
156 expect(size(all)).toBeLessThanOrEqual(ANSWER_MAX);
157 const month = compactSeries(db, { id: "big", name: "big" }, "server-number-0", "30d", at);
158 expect(size(month)).toBeLessThanOrEqual(ANSWER_MAX);
159 const day = compactSeries(db, { id: "big", name: "big" }, "server-number-0", "24h", at) as { at: string[]; tps: number[] };
160 expect(day.at.length).toBeGreaterThan(10);
161 expect(day.tps.every((v) => v === 19.5)).toBe(true);
162 });
163 });
164
165 describe("the sync and the tool", () => {
166 let dataDir = "";
167 let app: App;
168 let http: ForgeHttp;
169 let alice: User;
170 let token = "";
171 let admin = "";
172 let rpc = 1;
173 /** The games tool over the real MCP door, as alice's admin token. */
174 const call = async (args: Record<string, unknown>): Promise<{ text: string; value: any }> => {
175 const res = await http.handle(
176 new Request("http://forge.test/mcp", {
177 method: "POST",
178 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${admin}` },
179 body: JSON.stringify({ jsonrpc: "2.0", id: rpc++, method: "tools/call", params: { name: "games", arguments: args } }),
180 }),
181 );
182 const body: any = await res.json();
183 const text: string = body.result.content[0].text;
184 return { text, value: JSON.parse(text) };
185 };
186 beforeAll(async () => {
187 dataDir = await mkdtemp(join(tmpdir(), "forge-game-metrics-"));
188 app = createApp({ dataDir, port: 0 });
189 http = forgeHttp(app);
190 const made = await createUser(app.db, {
191 origin: "seed",
192 trusted: true,
193 username: "alice",
194 email: "[email protected]",
195 password: "a-good-passphrase",
196 adminIfFirst: true,
197 });
198 if (!made.ok) throw new Error(made.error);
199 alice = getUserByName(app.db, "alice")!;
200 admin = createToken(app.db, alice.id, "metrics", "admin").token;
201 token = createGameBox(app.db, { name: "net" }).token;
202 }, 30_000);
203 afterAll(async () => {
204 app.close();
205 await rm(dataDir, { recursive: true, force: true });
206 });
207
208 test("a sync with metrics is stored; one without them is still answered (agent: 1 stays compatible)", async () => {
209 const send = (body: unknown) =>
210 http.handle(
211 new Request("http://forge.test/api/v1/games/agent/sync", {
212 method: "POST",
213 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
214 body: JSON.stringify(body),
215 }),
216 );
217 expect((await send({ agent: 1, services: [{ name: "hub", state: "running", cpuPct: 5, memMiB: 900 }] })).status).toBe(200);
218 expect(
219 (
220 await send({
221 agent: 1,
222 services: [{ name: "hub", state: "running", cpuPct: 5, memMiB: 900 }],
223 metrics: {
224 hub: {
225 list: "There are 4 of a max of 20 players online: A, B, C, D",
226 tps: "TPS from last 1m, 5m, 15m: 19.8, 20, 20",
227 mspt: "",
228 },
229 },
230 })
231 ).status,
232 ).toBe(200);
233 const box = boxNamed(app.db, "net")!;
234 const got = await call({ action: "metrics", box: "net" });
235 expect(got.value.services["hub"].now).toMatchObject({ players: 4, tps: 19.8 });
236 expect(new TextEncoder().encode(got.text).length).toBeLessThan(6_144);
237 const detail = await call({ action: "metrics", box: "net", service: "hub", window: "1h" });
238 expect(detail.value.players.at(-1)).toBe(4);
239 expect(tool.heldNotWhen?.({ action: "metrics" })).toBe(true);
240 expect(box.name).toBe("net");
241 });
242 });
test/game-people.test.ts added +405
@@ -0,0 +1,405 @@
1 /**
2 * People on a game network (#17284 G3), with no plugin on the game servers: the agent reads who is
3 * online (`list uuids`), each server's whitelist, ops and bans, and the proxy's glist (its password
4 * through stdin, never a command line); the forge keeps them with the joins, deaths and chat, shows
5 * them with heads (kept on its disk) and a Bedrock badge, and queues whitelist, op, ban, kick and
6 * move as the server's own commands, from the page, the terminal's keys and the games tool.
7 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
10 import { rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { createSession } from "../src/core/sessions.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { DEFAULT_HEAD, FETCHES_MAX, HEAD_KEPT_MS, headResponse, MISS_MS } from "../src/games/heads.ts";
18 import { parseList, parseLogLine } from "../src/games/metrics.ts";
19 import { eventsOf, keptPeople, knowsPlayer, networkOf, parseGlist, peopleOf, peopleWords, queuePeople } from "../src/games/people.ts";
20 import { boxNamed, commandOf, createGameBox, grant, recentCommands } from "../src/games/store.ts";
21 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23
24 quietLogs();
25
26 const AGENT = join(import.meta.dir, "../src/games/agent.sh");
27 const TOKEN = "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
28 const ALICE = "069a79f4-44e9-4726-a5be-fca90e38aaf5";
29 const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]);
30
31 describe("what the servers say", () => {
32 test("list uuids, the proxy's glist, and each server's lists, cleaned", () => {
33 expect(
34 parseList(`There are 2 of a max of 20 players online: Alice (${ALICE.toUpperCase()}), .Steve (00000000-0000-0000-0009-01f64f65c7c3)`)
35 ?.players,
36 ).toEqual([
37 { name: "Alice", uuid: ALICE },
38 { name: ".Steve", uuid: "00000000-0000-0000-0009-01f64f65c7c3" },
39 ]);
40 expect(parseGlist("[hub] (2): Alice, .Steve\n[survival] (1): Bob\n3 players are currently connected to the proxy.")).toEqual({
41 hub: ["Alice", ".Steve"],
42 survival: ["Bob"],
43 });
44 expect(
45 keptPeople({
46 whitelist: [
47 { name: "Alice", uuid: ALICE },
48 { name: "bad name!", uuid: "x" },
49 ],
50 ops: [{ name: "Alice", uuid: ALICE, level: 4 }],
51 bans: [{ name: "Griefer", uuid: "", reason: "x".repeat(500), created: "2026-12-01" }],
52 whitelistOn: true,
53 }),
54 ).toEqual({
55 whitelist: [{ name: "Alice", uuid: ALICE }],
56 ops: [{ name: "Alice", uuid: ALICE, level: 4 }],
57 bans: [{ name: "Griefer", uuid: "", reason: "x".repeat(200), created: "2026-12-01" }],
58 whitelistOn: true,
59 });
60 });
61
62 test("chat and deaths from the log, a Bedrock name too; a chat line is never a death", () => {
63 expect(parseLogLine("[12:00:02 INFO]: <Alice> I fell off")).toEqual({ kind: "chat", player: "Alice", text: "I fell off" });
64 expect(parseLogLine("[12:00:03 INFO]: [Not Secure] <.Steve> hi")).toEqual({ kind: "chat", player: ".Steve", text: "hi" });
65 expect(parseLogLine("[12:00:04 INFO]: Alice was slain by Zombie")).toEqual({
66 kind: "death",
67 player: "Alice",
68 text: "Alice was slain by Zombie",
69 });
70 expect(parseLogLine("[12:00:05 INFO]: .Steve fell from a high place")).toEqual({
71 kind: "death",
72 player: ".Steve",
73 text: ".Steve fell from a high place",
74 });
75 expect(parseLogLine("[12:00:06 INFO]: .Steve joined the game")).toEqual({ kind: "join", player: ".Steve" });
76 expect(parseLogLine("[12:00:07 INFO]: Alice was kicked")).toBeUndefined();
77 expect(parseLogLine("[12:00:08 INFO]: Alice has made the advancement [Getting Wood]")).toBeUndefined();
78 });
79
80 test("only the server's own line head starts a fact: chat that reads like a join, a death or an error is chat", () => {
81 expect(parseLogLine("[12:00:09 INFO]: <Mallory> [x] Alice joined the game")).toEqual({ kind: "chat", player: "Mallory", text: "[x] Alice joined the game" });
82 expect(parseLogLine("[12:00:09 INFO]: [Not Secure] <Mallory> [x] Alice was slain by Bob")).toEqual({
83 kind: "chat",
84 player: "Mallory",
85 text: "[x] Alice was slain by Bob",
86 });
87 expect(parseLogLine("[12:00:09 INFO]: <Mallory> [12:00:09 ERROR]: boom")).toMatchObject({ kind: "chat" });
88 // /say and a plugin's own tag are not the server's head either.
89 expect(parseLogLine("[12:00:09 INFO]: [Mallory] Alice left the game")).toBeUndefined();
90 expect(parseLogLine("[12:00:09 INFO]: [Server] Alice was slain by Bob")).toBeUndefined();
91 expect(parseLogLine("Alice joined the game")).toBeUndefined();
92 // Vanilla's head, and a renamed player, are real.
93 expect(parseLogLine("[12:00:10] [Server thread/INFO]: Alice joined the game")).toEqual({ kind: "join", player: "Alice" });
94 expect(parseLogLine("[12:00:10] [Server thread/ERROR]: boom")).toEqual({ kind: "error" });
95 expect(parseLogLine("[12:00:11 INFO]: Alice (formerly known as Al) joined the game")).toEqual({ kind: "join", player: "Alice" });
96 });
97 });
98
99 describe("on a forge", () => {
100 let dataDir = "";
101 let app: App;
102 let http: ForgeHttp;
103 let ada: User;
104 let token = "";
105 let cookie = "";
106 beforeAll(async () => {
107 dataDir = mkdtempSync(join(tmpdir(), "forge-game-people-"));
108 app = createApp({ dataDir, port: 0 });
109 http = forgeHttp(app);
110 const u = await createUser(app.db, {
111 username: "ada",
112 email: "[email protected]",
113 password: "a-good-passphrase",
114 origin: "seed",
115 isAdmin: true,
116 trusted: true,
117 });
118 if (!u.ok) throw new Error(u.error);
119 ada = u.value;
120 token = createGameBox(app.db, { name: "mc" }).token;
121 cookie = `forge_session=${createSession(app.db, ada.id).token}`;
122 }, 30_000);
123 afterAll(async () => {
124 app.close();
125 await rm(dataDir, { recursive: true, force: true });
126 });
127 const sync = (body: unknown) =>
128 http.handle(
129 new Request("http://forge.test/api/v1/games/agent/sync", {
130 method: "POST",
131 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
132 body: JSON.stringify(body),
133 }),
134 );
135 const post = (path: string, form: Record<string, string>) =>
136 http.handle(
137 new Request(`http://forge.test${path}`, {
138 method: "POST",
139 headers: { cookie, origin: "http://forge.test", "content-type": "application/x-www-form-urlencoded" },
140 body: new URLSearchParams(form),
141 }),
142 );
143
144 test("a sync's people land on the pages: heads, a Bedrock badge, chat and deaths, the lists, who is where with Move", async () => {
145 expect(
146 (
147 await sync({
148 agent: 1,
149 services: [
150 { name: "hub", state: "running" },
151 { name: "survival", state: "running" },
152 ],
153 metrics: {
154 hub: {
155 list: `There are 2 of a max of 20 players online: Alice (${ALICE}), .Steve (00000000-0000-0000-0009-01f64f65c7c3)`,
156 tps: "",
157 mspt: "",
158 },
159 },
160 logs: {
161 hub: [
162 "[12:00:01 INFO]: .Steve joined the game",
163 "[12:00:02 INFO]: <Alice> welcome back",
164 "[12:00:03 INFO]: Alice was slain by Zombie",
165 ],
166 },
167 people: {
168 servers: {
169 hub: {
170 whitelist: [{ name: "Alice", uuid: ALICE }],
171 ops: [{ name: "Alice", uuid: ALICE, level: 4 }],
172 bans: [{ name: "Griefer", uuid: "", reason: "griefing", created: "" }],
173 whitelistOn: true,
174 },
175 },
176 network: "[hub] (2): Alice, .Steve\n2 players are currently connected to the proxy.",
177 },
178 })
179 ).status,
180 ).toBe(200);
181 const box = boxNamed(app.db, "mc")!;
182 expect(peopleOf(app.db, box.id, "hub").online.map((p) => p.name)).toEqual(["Alice", ".Steve"]);
183 expect(networkOf(app.db, box.id)).toEqual({ hub: ["Alice", ".Steve"] });
184 expect(eventsOf(app.db, box.id, "hub").map((e) => e.kind)).toEqual(["death", "chat", "join"]);
185 const page = await (await http.handle(new Request("http://forge.test/games/mc/hub", { headers: { cookie } }))).text();
186 expect(page).toContain("<h2>People</h2>");
187 expect(page).toContain(`/games/head/${ALICE}`);
188 expect(page).toContain("Bedrock");
189 expect(page).toContain("welcome back");
190 expect(page).toContain("Alice was slain by Zombie");
191 expect(page).toContain("griefing");
192 expect(page).toMatch(/>\s*Deop\s*</);
193 // Who is where is the box page's network picture now, which needs the box's compose file: test/game-topology.test.ts.
194 });
195
196 test("the page's buttons and the games tool queue the server's own commands; a bad name or a move nowhere is refused", async () => {
197 expect((await post("/games/mc/hub/people", { op: "ban", player: "Griefer2" })).status).toBe(303);
198 const banned = recentCommands(app.db, boxNamed(app.db, "mc")!.id, "hub", 1)[0]!;
199 expect([banned.kind, JSON.parse(banned.text)]).toEqual(["people", { op: "ban", player: "Griefer2" }]);
200 const box = boxNamed(app.db, "mc")!;
201 expect(queuePeople(app.db, box, "hub", "op", "not a name", ada)).toEqual({ ok: false, error: "That is not a player's name." });
202 expect(queuePeople(app.db, box, "hub", "move", "Alice", ada, "hub")).toEqual({
203 ok: false,
204 error: "Name the server to move them to.",
205 });
206 expect(queuePeople(app.db, box, "hub", "whitelist-on", "", ada).ok).toBe(true);
207 expect(peopleWords(JSON.stringify({ op: "move", player: ".Steve", server: "survival" }))).toBe("move .Steve to survival");
208 const said = async (args: Record<string, unknown>) => {
209 const res = await http.handle(
210 new Request("http://forge.test/mcp", {
211 method: "POST",
212 headers: {
213 "content-type": "application/json",
214 accept: "application/json, text/event-stream",
215 authorization: `Bearer ${createToken(app.db, ada.id, "p", "admin").token}`,
216 },
217 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "games", arguments: args } }),
218 }),
219 );
220 const body = (await res.json()) as { result: { content: { text: string }[] } };
221 return body.result.content[0]!.text;
222 };
223 const call = async (args: Record<string, unknown>) => JSON.parse(await said(args)) as Record<string, any>;
224 const listed = await call({ action: "people", box: "mc", service: "hub", op: "list" });
225 expect(listed["online"].map((p: { name: string }) => p.name)).toEqual(["Alice", ".Steve"]);
226 expect(listed["bans"][0].name).toBe("Griefer");
227 expect(listed["latest"][0].kind).toBe("death");
228 const moved = await call({ action: "people", box: "mc", service: "hub", op: "move", player: ".Steve", to: "survival" });
229 expect(JSON.parse(commandOf(app.db, moved["id"])!.text)).toEqual({ op: "move", player: ".Steve", server: "survival" });
230 // A move only to a server of this box: a name the box has no service for is refused.
231 expect(await said({ action: "people", box: "mc", service: "hub", op: "move", player: ".Steve", to: "elsewhere" })).toContain("you operate; elsewhere is not one");
232 expect(queuePeople(app.db, box, "hub", "move", ".Steve", ada, "elsewhere")).toEqual({ ok: false, error: "Move people only to a server of mc you operate; elsewhere is not one." });
233 });
234
235 test("a move goes only to a server the person operates too, from the page, the tool and the terminal alike", async () => {
236 const made = await createUser(app.db, { username: "bo", email: "[email protected]", password: "a-good-passphrase", origin: "seed", isAdmin: false, trusted: true });
237 if (!made.ok) throw new Error(made.error);
238 const bo = made.value;
239 const box = boxNamed(app.db, "mc")!;
240 grant(app.db, box.id, bo.id, "operator", "hub");
241 const refused = queuePeople(app.db, box, "hub", "move", "Alice", bo, "survival");
242 expect(refused).toEqual({ ok: false, error: "Move people only to a server of mc you operate; survival is not one." });
243 expect(queuePeople(app.db, box, "hub", "move", "Alice", undefined, "survival").ok).toBe(false);
244 // The page refuses it the same way (one function behind the page, the tool and the terminal).
245 const before = recentCommands(app.db, box.id, "hub", 50).length;
246 const res = await http.handle(
247 new Request("http://forge.test/games/mc/hub/people", {
248 method: "POST",
249 headers: { cookie: `forge_session=${createSession(app.db, bo.id).token}`, origin: "http://forge.test", "content-type": "application/x-www-form-urlencoded" },
250 body: new URLSearchParams({ op: "move", player: "Alice", to: "survival" }),
251 }),
252 );
253 expect(res.status).toBe(303);
254 expect(recentCommands(app.db, box.id, "hub", 50).length).toBe(before);
255 grant(app.db, box.id, bo.id, "operator", "survival");
256 expect(queuePeople(app.db, box, "hub", "move", "Alice", bo, "survival").ok).toBe(true);
257 });
258
259 test("a head is served only for a player the forge has seen on a server the person sees", async () => {
260 const box = boxNamed(app.db, "mc")!;
261 expect(knowsPlayer(app.db, ada, ALICE)).toBe(true);
262 // Online now (.Steve's UUID from `list uuids`) counts as seen, as do the lists.
263 expect(knowsPlayer(app.db, ada, "00000000-0000-0000-0009-01f64f65c7c3")).toBe(true);
264 expect(knowsPlayer(app.db, ada, "11111111-2222-3333-4444-555555555555")).toBe(false);
265 expect(knowsPlayer(app.db, ada, "069a79f4")).toBe(false);
266 expect(knowsPlayer(app.db, undefined, ALICE)).toBe(false);
267 const made = await createUser(app.db, { username: "cy", email: "[email protected]", password: "a-good-passphrase", origin: "seed", isAdmin: false, trusted: true });
268 if (!made.ok) throw new Error(made.error);
269 expect(knowsPlayer(app.db, made.value, ALICE)).toBe(false);
270 grant(app.db, box.id, made.value.id, "viewer", "hub");
271 expect(knowsPlayer(app.db, made.value, ALICE)).toBe(true);
272 // An unknown UUID through the route: the default head, and nothing fetched.
273 const res = await http.handle(new Request("http://forge.test/games/head/11111111-2222-3333-4444-555555555555", { headers: { cookie } }));
274 expect(await res.text()).toBe(DEFAULT_HEAD);
275 });
276
277 test("a head is fetched once and kept a week; anything that is not a PNG, and a Bedrock player, get the default", async () => {
278 let fetched = 0;
279 const fetcher = (async () => (fetched++, new Response(PNG, { headers: { "content-type": "image/png" } }))) as unknown as typeof fetch;
280 const first = await headResponse(app, ALICE, fetcher);
281 expect(first.headers.get("content-type")).toBe("image/png");
282 await headResponse(app, ALICE, fetcher);
283 expect(fetched).toBe(1);
284 await headResponse(app, ALICE, fetcher, Date.now() + HEAD_KEPT_MS + 1_000);
285 expect(fetched).toBe(2);
286 const notPng = (async () => new Response("<html>", { headers: { "content-type": "text/html" } })) as unknown as typeof fetch;
287 expect(await (await headResponse(app, "00000000-0000-0000-0000-000000000001", notPng)).text()).toBe(DEFAULT_HEAD);
288 expect(await (await headResponse(app, "none", fetcher)).text()).toBe(DEFAULT_HEAD);
289 });
290
291 test("a failed head is not asked for again for a while, and only a few fetches are out at once", async () => {
292 let fetched = 0;
293 const fails = (async () => (fetched++, new Response("nope", { status: 404 }))) as unknown as typeof fetch;
294 const miss = "00000000-0000-0000-0000-00000000aaaa";
295 const now = Date.now();
296 expect(await (await headResponse(app, miss, fails, now)).text()).toBe(DEFAULT_HEAD);
297 expect(await (await headResponse(app, miss, fails, now + 1_000)).text()).toBe(DEFAULT_HEAD);
298 expect(fetched).toBe(1);
299 await headResponse(app, miss, fails, now + MISS_MS + 1_000);
300 expect(fetched).toBe(2);
301 // Hold FETCHES_MAX fetches open: the next head is the default, not kept, and not fetched.
302 const held: (() => void)[] = [];
303 let started = 0;
304 let allStarted!: () => void;
305 const outAll = new Promise<void>((done) => (allStarted = done));
306 const slow = (async () => {
307 if (++started === FETCHES_MAX) allStarted();
308 await new Promise<void>((done) => held.push(done));
309 return new Response(PNG);
310 }) as unknown as typeof fetch;
311 const uuid = (i: number) => `00000000-0000-0000-0000-0000000bb${String(i).padStart(3, "0")}`;
312 const out = Array.from({ length: FETCHES_MAX }, (_, i) => headResponse(app, uuid(i), slow));
313 await outAll;
314 // The same head asked again shares its fetch.
315 const again = headResponse(app, uuid(0), slow);
316 const busy = await headResponse(app, uuid(99), slow);
317 expect(busy.headers.get("cache-control")).toBe("no-store");
318 expect(started).toBe(FETCHES_MAX);
319 for (const done of held) done();
320 for (const r of await Promise.all([...out, again])) expect(r.headers.get("content-type")).toBe("image/png");
321 });
322 });
323
324 describe("the agent", () => {
325 const lacks = ["bash", "curl", "jq"].filter((t) => Bun.which(t) === null);
326 test.skipIf(lacks.length > 0)(
327 `reads each server's lists and the proxy's glist, its password never on a command line, and runs a people command${lacks.length > 0 ? ` (skipped: no ${lacks.join(", ")} here)` : ""}`,
328 async () => {
329 const root = mkdtempSync(join(tmpdir(), "forge-game-people-agent-"));
330 const box = join(root, "box");
331 mkdirSync(box);
332 const calls = join(root, "calls");
333 const fake = join(root, "docker");
334 writeFileSync(
335 fake,
336 `#!/usr/bin/env bash
337 echo "$*" >> "${calls}"
338 case "$*" in
339 *" ps -a --format json") echo '{"Service":"hub","Name":"hub","State":"running"}' ;;
340 *" ps --status running --format "*) echo hub ;;
341 *" exec -T hub rcon-cli -- list uuids") echo "There are 1 of a max of 20 players online: Alice (${ALICE})" ;;
342 *" exec -T hub rcon-cli -- op Alice") echo "Made Alice a server operator" ;;
343 *" exec -T hub sh -c for f in"*) printf '=== whitelist.json\\n[{"uuid":"${ALICE}","name":"Alice"}]\\n\\n=== ops.json\\n[]\\n\\n=== banned-players.json\\n[]\\n\\n=== props\\nwhite-list=true\\n' ;;
344 *" exec -T hub sh -c read -r p;"*) read -r p; [ "$p" = pw123 ] && printf '[hub] (1): Alice\\n1 player is currently connected to the proxy.\\n' ;;
345 esac
346 exit 0
347 `,
348 );
349 chmodSync(fake, 0o755);
350 const bodies: Record<string, any>[] = [];
351 const forge: ReturnType<typeof Bun.serve> = Bun.serve({
352 port: 0,
353 hostname: "127.0.0.1",
354 async fetch(req): Promise<Response> {
355 bodies.push((await req.json()) as Record<string, any>);
356 return Response.json(
357 bodies.length === 1
358 ? {
359 composeSha: "",
360 env: { ".env": "RCON_VELOCITY=pw123\n" },
361 commands: [{ id: "p1", kind: "people", service: "hub", text: JSON.stringify({ op: "op", player: "Alice" }) }],
362 }
363 : { composeSha: "", commands: [] },
364 );
365 },
366 });
367 try {
368 const run = async (): Promise<string> => {
369 const p = Bun.spawn(["bash", AGENT], {
370 env: {
371 PATH: process.env["PATH"] ?? "",
372 FORGE_URL: `http://127.0.0.1:${String(forge.port)}`,
373 FORGE_GAME_TOKEN: TOKEN,
374 FORGE_GAME_DIR: box,
375 FORGE_GAME_DOCKER: fake,
376 FORGE_GAME_ONCE: "1",
377 },
378 stdout: "pipe",
379 stderr: "pipe",
380 });
381 await p.exited;
382 return new Response(p.stderr).text();
383 };
384 const said = await run();
385 expect(bodies.length, `the agent sent nothing; it said: ${said}`).toBe(1);
386 expect(bodies[0]!["people"].servers.hub).toEqual({
387 whitelist: [{ name: "Alice", uuid: ALICE }],
388 ops: [],
389 bans: [],
390 whitelistOn: true,
391 });
392 expect(bodies[0]!["metrics"].hub.list).toContain(ALICE);
393 // The second sync: the command's result, and the proxy's glist now that .env has its password.
394 await run();
395 const second = bodies[1]!;
396 expect(second["results"]).toEqual([expect.objectContaining({ id: "p1", ok: true, output: "Made Alice a server operator" })]);
397 expect(second["people"].network).toContain("[hub] (1): Alice");
398 expect(readFileSync(calls, "utf8")).not.toContain("pw123");
399 } finally {
400 forge.stop(true);
401 await rm(root, { recursive: true, force: true });
402 }
403 },
404 );
405 });
test/game-topology.test.ts added +116
@@ -0,0 +1,116 @@
1 /**
2 * The network as a picture (#17284 G5): the proxy, the servers under it in four states, the heads of
3 * who is on each with their TPS, a server opening its page, and Move as a head's buttons to the
4 * servers it can go to, for an operator only.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtempSync } from "node:fs";
8 import { 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 { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { createGameBox, grant, boxNamed } from "../src/games/store.ts";
16 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
17 import { netState, proxyOf } from "../src/web/pages/games_topology.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21
22 const ALICE = "069a79f4-44e9-4726-a5be-fca90e38aaf5";
23 const COMPOSE = `services:
24 velocity:
25 image: itzg/mc-proxy:latest
26 hub:
27 image: itzg/minecraft-server:latest
28 survival:
29 image: itzg/minecraft-server:latest
30 hunting:
31 image: itzg/minecraft-server:latest
32 `;
33 const svc = (state: string, health = "") => ({ name: "x", state, health, startedAt: "", cpuPct: 0, memMiB: 0, seenAt: "", asleep: false });
34
35 describe("the pieces", () => {
36 test("four states, and an old box's stop reads as stopped", () => {
37 expect(netState(svc("running", "healthy"))).toBe("awake");
38 expect(netState(svc("running", "starting"))).toBe("waking");
39 expect(netState({ ...svc("exited"), asleep: true })).toBe("asleep");
40 expect(netState(svc("exited"))).toBe("stopped");
41 expect(netState(undefined)).toBe("stopped");
42 });
43
44 test("the proxy is the mc-proxy service; no proxy, no picture", () => {
45 expect(proxyOf(COMPOSE)).toBe("velocity");
46 expect(proxyOf("services:\n hub:\n image: itzg/minecraft-server\n")).toBeUndefined();
47 expect(proxyOf(undefined)).toBeUndefined();
48 });
49 });
50
51 describe("on /games/<box>", () => {
52 let dataDir = "";
53 let app: App;
54 let http: ForgeHttp;
55 let ada: User;
56 let bob: User;
57 let token = "";
58 beforeAll(async () => {
59 dataDir = mkdtempSync(join(tmpdir(), "forge-game-topology-"));
60 app = createApp({ dataDir, port: 0 });
61 http = forgeHttp(app);
62 const a = await createUser(app.db, { username: "ada", email: "[email protected]", password: "a-good-passphrase", origin: "seed", isAdmin: true, trusted: true });
63 const b = await createUser(app.db, { username: "bob", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true });
64 if (!a.ok || !b.ok) throw new Error("users");
65 [ada, bob] = [a.value, b.value];
66 const repo = await createRepo(app, ada, { name: "mc-network", visibility: "private" });
67 if (!repo.ok) throw new Error(String(repo.error));
68 const seeded = await commitToBranch(app, ada, repo.value, { message: "seed", files: [{ path: "docker-compose.yml", content: COMPOSE }] });
69 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
70 token = createGameBox(app.db, { name: "mc", repo: "ada/mc-network" }).token;
71 grant(app.db, boxNamed(app.db, "mc")!.id, bob.id, "viewer");
72 const sync = (body: unknown) =>
73 http.handle(new Request("http://forge.test/api/v1/games/agent/sync", { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify(body) }));
74 await sync({
75 agent: 1,
76 services: [
77 { name: "velocity", state: "running", health: "" },
78 { name: "hub", state: "running", health: "healthy" },
79 { name: "survival", state: "running", health: "starting" },
80 { name: "hunting", state: "exited", health: "" },
81 ],
82 metrics: { hub: { list: `There are 2 of a max of 20 players online: Alice (${ALICE}), .Steve (00000000-0000-0000-0009-01f64f65c7c3)`, tps: "TPS from last 1m, 5m, 15m: 19.8, 20, 20", mspt: "" } },
83 people: { servers: {}, network: "[hub] (2): Alice, .Steve\n2 players are currently connected to the proxy." },
84 });
85 }, 30_000);
86 afterAll(async () => {
87 app.close();
88 await rm(dataDir, { recursive: true, force: true });
89 });
90 const page = async (u: User) => (await http.handle(new Request("http://forge.test/games/mc", { headers: { cookie: `forge_session=${createSession(app.db, u.id).token}` } }))).text();
91
92 test("the proxy above the servers in their states, heads and TPS on hub, each a link to its page", async () => {
93 const text = await page(ada);
94 expect(text).toContain("data-topology");
95 expect(text).toContain('href="/games/mc/velocity"');
96 expect(text).toContain("the way in");
97 expect(text).toContain("2 players");
98 expect(text).toMatch(/data-state="awake">\s*<a class="net-node" href="\/games\/mc\/hub"/);
99 expect(text).toMatch(/data-state="waking">\s*<a class="net-node" href="\/games\/mc\/survival"/);
100 expect(text).toMatch(/data-state="stopped">\s*<a class="net-node" href="\/games\/mc\/hunting"/);
101 expect(text).toContain("19.8 TPS");
102 expect(text).toContain(`/games/head/${ALICE}`);
103 expect(text).toContain('/games/head/none');
104 });
105
106 test("an operator moves a player by picking their head and a server that is up; a viewer only sees the heads", async () => {
107 const text = await page(ada);
108 expect(text).toContain('<details class="net-head">');
109 expect(text).toMatch(/name="to"\s+value="survival"/);
110 // A stopped server is no place to move to.
111 expect(text).not.toMatch(/name="to"\s+value="hunting"/);
112 const viewer = await page(bob);
113 expect(viewer).toContain("data-topology");
114 expect(viewer).not.toContain('<details class="net-head">');
115 });
116 });
test/no-polling.test.ts +1
@@ -332,6 +332,7 @@ const NOT_WALKED: Record<string, string> = {
332332 "/games/:box/@shell/stream": "a game box's shell output for its owner, which the seed does not make (test/game-console.test.ts covers it)",
333333 "/games/:box/:service/stream": "a game box, which the seed does not make (test/games.test.ts covers it)",
334334 "/games/jar/:id/:name": "a kept plugin jar, a download behind a signed URL, not a page",
335 "/games/head/:uuid": "a player's head, a PNG kept from mc-heads.net, not a page",
335336 "/:owner/:name/waves/:version": "needs a wave of a milestone",
336337 "/boards/:slug": "needs a board",
337338 "/boards/:slug/stream": "needs a board; a stream, not a page",
test/open-routes-floor.test.ts +1 −1
@@ -41,7 +41,7 @@ const FILL: Readonly<Record<string, string>> = {
4141 ref: "main", branch: "main", oid: "0".repeat(40), sha: "0".repeat(40), commit: "0".repeat(40),
4242 // Not seeded: each still has to answer its not-found with the floor.
4343 team: "core", env: "prod", file: "README.md", label: "v1", chapter: "1", kind: "desktop", machine: "web",
44 range: `${"0".repeat(40)}...${"1".repeat(40)}`, op: "x", step: "1", group: "a", version: "1", slug: "board", receipt: "r", token: "t", code: "c", spec: "16", stage: "build", walk: "1", flag: "x", room: "lobby", box: "net", service: "hub", hash: "0".repeat(16),
44 range: `${"0".repeat(40)}...${"1".repeat(40)}`, op: "x", step: "1", group: "a", version: "1", slug: "board", receipt: "r", token: "t", code: "c", spec: "16", stage: "build", walk: "1", flag: "x", room: "lobby", box: "net", service: "hub", hash: "0".repeat(16), uuid: "069a79f4-44e9-4726-a5be-fca90e38aaf5",
4545 };
4646
4747 /** Open GET routes that cannot be filled in from a seeded public repository, each with why. */
test/security-floor-routes.test.ts +1
@@ -75,6 +75,7 @@ const UNSEEDED: Record<string, string> = {
7575 "/games/:box/:service": "a game box, which the seed does not make (test/games.test.ts covers it)",
7676 "/games/:box/@shell/stream": "a game box's shell output for its owner, which the seed does not make (test/game-console.test.ts covers it)",
7777 "/games/:box/:service/stream": "a game box, which the seed does not make (test/games.test.ts covers it)",
78 "/games/head/:uuid": "a player's head picture, by a Minecraft UUID only a game box's agent reports",
7879 "/games/jar/:id/:name": "a kept plugin jar of a game box, behind a signed URL the seed does not make",
7980 "/talk/dev/:token": "a dev cell reached by a one-time token the seed does not mint (test/dev-cell.test.ts covers it)",
8081 "/talk/dev/:token/*path": "a dev cell reached by a one-time token the seed does not mint (test/dev-cell.test.ts covers it)",

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

Keyboard shortcuts

Docs