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

A game box says why it is up but not playing: installs wait out apt's lock, a missing tool is reported, the boot reports itself #17013

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

sold/game-boot → main 0 commits 4 threads · 4 unresolved

  • Merged. sold/game-boot was merged into main as 88c0c58.

Review

Sign in to review this change.
11 files changed +288 −15
docs/features/game-box.md +1
@@ -14,6 +14,7 @@ experiment.
1414 - **Plan one (agents):** `infra` with `{ action: "plan", want: { game: true, where: "digitalocean/main@digitalocean:nyc3:s-4vcpu-8gb", name?: "mc", repo?: "trevato/mc-network", host?: "mc.trevato.dev" } }`, then `apply` its id. The plan says "Start a 4 vCPU, 8 GB game box in New York running trevato/mc-network's compose file" and waits for the address and the DNS record, not for an https answer. The web and terminal doors are `/games` and the Games screen.
1515 - **The machine:** Ubuntu with Docker and its compose plugin (Ubuntu's packages, data on the box's volume), 4 GB of swap for the JVMs, and a firewall that lets in only 25565/tcp: no SSH, no web, no backend port. Password and root logins are off and updates are on, as on a forge.
1616 - **The agent:** `/opt/forge-game/agent.sh` (`src/games/agent.sh`) under systemd (`forge-game-agent`). Every 5 s it POSTs the services, their CPU and memory, new log lines, command results and the host to `/api/v1/games/agent/sync`, and does what the answer asks: writes `compose.yml` and the answer's `.env` beside it (only that name: `FORWARDING_SECRET` and an `RCON_<SERVICE>` for every service; any other name is ignored and logged, so nothing can land on the agent's own files), runs `docker compose -p game --project-directory /opt/forge-game up -d --remove-orphans` when they change, and runs queued commands (rcon through `docker compose exec -T <service> rcon-cli -- <text>`, by service name, or restart, stop, start, pull, recreate). Nothing dials in to the box; a failed sync is tried again in 5 s, forever.
17 - **When it is up but not playing:** the boot installs Docker, its compose plugin and jq in `runcmd`, each apt call waiting up to ten minutes for the lock a first boot's unattended upgrade holds, three tries (a `packages:` list failed on that lock and left box `mc` with no jq). Its last step, `agent.sh --boot-report`, posts cloud-init's status to the sync once. An agent missing jq or docker still posts `{"agent":1,"boot":"missing jq: <cloud-init status>"}`, built by hand with curl, every 30 s until they are there. The forge keeps that word until a full sync clears it, and `/games` and the terminal's Games say "Box is up but missing jq: …".
1718 - **The token:** made whenever the box's machine is made (a create or a replace, which ends the old one's), kept only as its sha256 (`game_box.token_hash`, starting `fgb_`), and written only into the machine's `/opt/forge-game/agent.env` (mode 600), which the unit reads; the agent hands it to curl in a header file, never on a command line. `rotateGameBoxToken` makes a new one.
1819 - **DNS:** an A record, not proxied, for the box's `host` in any Cloudflare zone a connected token can write; with none, the plan says to set it by hand.
1920
src/core/migration-pins/20261201130000-game-box-boot.pin added +1
@@ -0,0 +1,1 @@
1 d0ea26cb82752c80ad233eed00d5048d7d6e12ad9fe3f67a4b255bbccea7a1b7
src/core/migrations/20261201130000-game-box-boot.ts added +7
@@ -0,0 +1,7 @@
1 // A game box's word about its own boot (2026-12-01, box `mc` never synced): what the agent says when
2 // a tool it needs is missing ("missing jq: …"), or the boot's own report of cloud-init's status, so
3 // /games says why a box is up but not running its games. Empty once the agent syncs in full.
4 // Additive: one column.
5 export default `
6 ALTER TABLE game_box ADD COLUMN boot TEXT NOT NULL DEFAULT '';
7 `;
src/games/agent.sh +50
@@ -12,6 +12,15 @@ DIR="${FORGE_GAME_DIR:-/opt/forge-game}"
1212 DOCKER="${FORGE_GAME_DOCKER:-docker}"
1313 EVERY="${FORGE_GAME_EVERY:-5}"
1414 ONCE="${FORGE_GAME_ONCE:-0}"
15 # How long the agent waits between word that a tool is missing.
16 MISSING_EVERY="${FORGE_GAME_MISSING_EVERY:-30}"
17 # Run by the boot (`--boot-report`), it reads its own env file, as systemd does for the service.
18 if [ -z "${FORGE_URL:-}" ] && [ -r "$DIR/agent.env" ]; then
19 set -a
20 # shellcheck disable=SC1091
21 . "$DIR/agent.env"
22 set +a
23 fi
1524 : "${FORGE_URL:?FORGE_URL is the forge this box answers to}"
1625 : "${FORGE_GAME_TOKEN:?FORGE_GAME_TOKEN is this box token}"
1726
@@ -23,6 +32,47 @@ printf 'Authorization: Bearer %s\n' "$FORGE_GAME_TOKEN" >"$AUTH"
2332 unset FORGE_GAME_TOKEN
2433
2534 SAFE='^[A-Za-z0-9._-]{1,64}$'
35
36 # A string as JSON, by hand: before jq is there, the agent still says why it is not.
37 json_str() {
38 local s="${1:0:1500}"
39 s="${s//\\/\\\\}"
40 s="${s//\"/\\\"}"

Non-UTF-8 bytes from cloud-init output survive this and make the body invalid JSON, which the forge rejects, so the word is lost. Pipe through iconv -c -t UTF-8 (or tr -cd printable ASCII) before building the string.

41 s="$(printf '%s' "$s" | tr '\n\t\r' ' ' | LC_ALL=C tr -cd '\040-\176')"
42 printf '"%s"' "$s"
43 }
44
45 # What the boot said, condensed to a line: cloud-init's status and any error it kept.
46 boot_status() {
47 cloud-init status --long 2>/dev/null | grep -E '^(status|errors|recoverable_errors|detail):|^ - ' | head -12 | tr '\n' ' ' || true
48 }
49
50 # One word to the forge with a body built without jq; never fails the caller.
51 say_boot() {
52 curl -fsS -m 20 -H "@$AUTH" -H 'content-type: application/json' \
53 --data-binary "{\"agent\":1,\"boot\":$(json_str "$1")}" "${FORGE_URL%/}/api/v1/games/agent/sync" >/dev/null 2>&1 || true
54 }
55
56 # The boot's last step: say how it went, once, so a box whose agent cannot start still shows why.
57 if [ "${1:-}" = "--boot-report" ]; then
58 say_boot "boot report: $(boot_status)"
59 exit 0
60 fi
61
62 # The tools the agent needs. Without curl it cannot say a word; without jq or docker it says which
63 # is missing every 30 s (the forge shows "Box is up but missing jq: …") until they are there.
64 missing() {
65 local t out=""
66 for t in curl jq "$DOCKER"; do command -v "$t" >/dev/null 2>&1 || out="$out ${t##*/}"; done
67 printf '%s' "${out# }"
68 }
69 while [ -n "$(missing)" ]; do
70 gone="$(missing)"
71 echo "forge-game-agent: missing $gone; saying so and checking again in ${MISSING_EVERY}s" >&2
72 case " $gone " in *" curl "*) ;; *) say_boot "missing $gone: $(boot_status)" ;; esac
73 [ "$ONCE" = 1 ] && exit 0
74 sleep "$MISSING_EVERY"
75 done
2676 # The project directory is the box's own, so compose reads the `.env` the forge writes beside it.
2777 compose() { "$DOCKER" compose -p game --project-directory "$DIR" -f "$DIR/compose.yml" "$@"; }
2878 now() { date -u +%Y-%m-%dT%H:%M:%SZ; }
src/games/boot.ts +12 −11
@@ -42,6 +42,15 @@ RestartSec=5
4242 WantedBy=multi-user.target
4343 `;
4444
45 /**
46 * What the box installs, in `runcmd` and not `packages:`: a first boot's unattended upgrade holds
47 * apt's lock, and a `packages:` that fails leaves no Docker and no jq (box `mc`, 2026-12-01). Each
48 * apt call waits up to ten minutes for the lock, and the whole is tried three times. No
49 * `package_upgrade`: unattended-upgrades does that once the box is up.
50 */
51 export const INSTALL =
52 "for try in 1 2 3; do apt-get -o DPkg::Lock::Timeout=600 update && DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=600 install -y docker.io docker-compose-v2 jq curl ca-certificates ufw unattended-upgrades && break; sleep 30; done";
53
4554 /** The cloud-config for a game box whose volume is mounted at `dataDir`. */
4655 export function gameBootConfig(g: GameBoot, dataDir: string): string {
4756 const url = new URL(g.forgeUrl);
@@ -53,16 +62,6 @@ export function gameBootConfig(g: GameBoot, dataDir: string): string {
5362 return `#cloud-config
5463 ssh_pwauth: false
5564 disable_root: true
56 package_update: true
57 package_upgrade: true
58 packages:
59 - ufw
60 - curl
61 - jq
62 - ca-certificates
63 - unattended-upgrades
64 - docker.io
65 - docker-compose-v2
6665 write_files:
6766 - path: ${GAME_DIR}/agent.env
6867 permissions: "0600"
@@ -84,8 +83,10 @@ runcmd:
8483 - ufw --force enable
8584 - fallocate -l ${SWAP_GIB}G /swapfile && chmod 600 /swapfile && mkswap /swapfile && swapon /swapfile && echo '/swapfile none swap sw 0 0' >> /etc/fstab
8685 - mkdir -p ${dataDir}/docker
87 - systemctl restart docker
86 - ${JSON.stringify(INSTALL)}
87 - systemctl restart docker || true
8888 - systemctl daemon-reload
8989 - systemctl enable --now forge-game-agent.service
90 - bash ${GAME_DIR}/agent.sh --boot-report
9091 `;
9192 }
src/games/store.ts +21 −1
@@ -40,6 +40,8 @@ export interface GameBox {
4040 readonly composeSha: string;
4141 readonly seenAt: string;
4242 readonly createdAt: string;
43 /** What the box last said about its boot ("missing jq: …", a boot report); empty once it syncs in full. */
44 readonly boot: string;
4345 }
4446
4547 export interface GameService {
@@ -65,6 +67,7 @@ interface BoxRow {
6567 compose_sha: string;
6668 seen_at: string;
6769 created_at: string;
70 boot: string;
6871 }
6972 const toBox = (r: BoxRow): GameBox => {
7073 let host: Record<string, number> = {};
@@ -84,6 +87,7 @@ const toBox = (r: BoxRow): GameBox => {
8487 composeSha: r.compose_sha,
8588 seenAt: r.seen_at,
8689 createdAt: r.created_at,
90 boot: r.boot,
8791 };
8892 };
8993
@@ -156,6 +160,15 @@ export const servicesOf = (db: Database, boxId: string): GameService[] =>
156160 seenAt: r.seen_at,
157161 }));
158162
163 /** A box's word about its boot as every door says it: "Box is up but missing jq: …". */
164 export const bootWords = (box: Pick<GameBox, "boot">): string =>
outdated

Principle 8: 'Box is up but boot report: status: running detail: DataSourceDigitalOcean' is not words a person reads. Give a boot report its own plain sentence ('Box is up; setup says: running') and keep 'Box is up but missing jq: …' for missing tools.

165 box.boot.startsWith("boot report:")
166 ? `Box is up; setup says: ${/status:\s*(\S+)/.exec(box.boot)?.[1] ?? "nothing yet"}`
167 : `Box is up but ${box.boot}`;
168
169 /** Whether the box's word is trouble (a tool it lacks), the only word the terminal shows in the danger tone. */
170 export const bootTroubled = (box: Pick<GameBox, "boot">): boolean => box.boot.startsWith("missing");
171
159172 /** The newest `limit` log lines of a service, oldest first, with the id of the last. */
160173 export function logsOf(db: Database, boxId: string, service: string, limit = 200, after = 0): { lines: string[]; last: number } {
161174 const rows = db
@@ -396,6 +409,8 @@ export interface SyncBody {
396409 readonly logs?: Record<string, unknown>;
397410 readonly results?: readonly { id?: unknown; ok?: unknown; output?: unknown }[];
398411 readonly host?: Record<string, unknown>;
412 /** The box's word about its boot, sent without jq when a tool is missing or by the boot's report. */
413 readonly boot?: string;
399414 }
400415
401416 const str = (v: unknown, max = 200): string => (typeof v === "string" ? v.slice(0, max) : "");
@@ -413,7 +428,12 @@ export function recordSync(
413428 const host: Record<string, number> = {};
414429 for (const [k, v] of Object.entries(body.host ?? {}))
415430 if (typeof v === "number" && Number.isFinite(v) && Object.keys(host).length < 16) host[k.slice(0, 40)] = v;
416 db.query("UPDATE game_box SET seen_at = ?2, host_json = ?3, compose_sha = ?4 WHERE id = ?1").run(
431 // A word about the boot (no services, no host) keeps what was known; a full sync clears it.
432 if (typeof body.boot === "string") {
433 db.query("UPDATE game_box SET seen_at = ?2, boot = ?3 WHERE id = ?1").run(box.id, at, str(body.boot, 2_000));
434 return;
435 }
436 db.query("UPDATE game_box SET seen_at = ?2, host_json = ?3, compose_sha = ?4, boot = '' WHERE id = ?1").run(
417437 box.id,
418438 at,
419439 JSON.stringify(host),
src/generated/migrations.ts +2
@@ -445,6 +445,7 @@ import m440 from "../core/migrations/20261201000000-games.ts";
445445 import m441 from "../core/migrations/20261201090000-app-vital-member.ts";
446446 import m442 from "../core/migrations/20261201120000-first-change-forge.ts";
447447 import m443 from "../core/migrations/20261201121000-repo-check-slots.ts";
448 import m444 from "../core/migrations/20261201130000-game-box-boot.ts";
448449
449450 /** Each migration file's name and its default export, in name order. */
450451 export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
@@ -892,4 +893,5 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
892893 ["20261201090000-app-vital-member.ts", m441],
893894 ["20261201120000-first-change-forge.ts", m442],
894895 ["20261201121000-repo-check-slots.ts", m443],
896 ["20261201130000-game-box-boot.ts", m444],
895897 ];
src/tui/screens/games.ts +6 −1
@@ -13,6 +13,8 @@ import { getUserByName } from "../../core/users.ts";
1313 import { addPlugin, commitServiceEnv, pluginsOf, readCompose, serviceEnv } from "../../games/compose.ts";
1414 import {
1515 SERVICE_NAME,
16 bootTroubled,
17 bootWords,
1618 grant,
1719 grantsOf,
1820 listBoxes,
@@ -57,7 +59,10 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
5759 const c = ctx.theme.c;
5860 const [head, list] = split(area, "v", [len(1), fill(1)]);
5961 const all = rows();
60 s.text(head!.x, head!.y, truncate(note !== "" ? note : all.length === 0 ? emptyText("gameServices") : "Each service of each game box you may see.", head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
62 // A box that is up but not running its games says why, as /games does, before anything else.
63 const booting = listBoxes(f.app.db).find((b) => b.boot !== "" && seesBox(f.app.db, f.user, b.id));
outdated

Every boot word is shown in the danger tone, including a routine boot report from a healthy box. Use danger only for 'missing …'; otherwise muted.

64 const said = note !== "" ? note : booting !== undefined ? `${booting.name}: ${bootWords(booting)}` : all.length === 0 ? emptyText("gameServices") : "Each service of each game box you may see.";
65 s.text(head!.x, head!.y, truncate(said, head!.w), style(booting !== undefined && note === "" && bootTroubled(booting) ? c.danger : c.mutedFg, c.bg), head!.x + head!.w);
6166 const view: ListRow[] = all.map(({ box, service }) => ({
6267 title: `${box.name}/${service.name}`,
6368 ...(service.state === "exited" ? { tone: "danger" as const } : {}),
src/web/pages/games.ts +3
@@ -8,6 +8,7 @@
88
99 import { addPlugin, commitServiceEnv, composeServices, pluginsOf, readCompose, SECRET_KEY, serviceEnv } from "../../games/compose.ts";
1010 import {
outdated

Mangled import: import { bootWords, shares a line with the opening brace. Put bootWords on its own line, in order with the rest.

11 bootWords,
1112 boxNamed,
1213 COMMAND_KINDS,
1314 commandOf,
@@ -81,6 +82,8 @@ export function gamesPage(ctx: Ctx): Response {
8182 meta: html`${b.place || "no machine yet"} · ${dollars(b.monthlyCents)} a month · agent
8283 ${b.seenAt === "" ? "never seen" : html`seen ${time(b.seenAt)}`} · host ${mib(b.host["memUsedMiB"])} of
8384 ${mib(b.host["memMiB"])}`,
85 // The box's own word about its boot, until its agent syncs in full.
86 ...(b.boot === "" ? {} : { facts: [{ label: "Boot", value: bootWords(b) }] }),
8487 }),
8588 ),
8689 )}`,
test/game-boot.test.ts added +170
@@ -0,0 +1,170 @@
1 /**
2 * A game box says why it is up but not running its games (box `mc`, 2026-12-01, booted and never
3 * synced): the agent, missing jq or docker, still POSTs a hand-built `{"agent":1,"boot":"missing
4 * jq: …"}` with curl; the boot's last step reports cloud-init's status the same way; the sync keeps
5 * that word (a full sync clears it), and /games and the terminal's Games say "Box is up but …".
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { chmodSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs";
9 import { rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { boxNamed, bootWords, createGameBox, recordSync } from "../src/games/store.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { createForgeApp } from "../src/tui/forge.ts";
18 import { gamesScreen } from "../src/tui/screens/games.ts";
19 import { headlessTerminal } from "../src/tui/term/terminal.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21 import { settleApp } from "./helpers/tui.ts";
22
23 quietLogs();
24
25 const AGENT = join(import.meta.dir, "../src/games/agent.sh");
26 const TOKEN = "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
27
28 /** A PATH of only these tools (found where this machine keeps them), so the rest are missing. */
29 function pathOf(dir: string, tools: readonly string[], extra: Record<string, string> = {}): string {
30 const bin = join(dir, "bin");
31 mkdirSync(bin, { recursive: true });
32 for (const t of tools) {
33 const at = Bun.which(t);
34 if (at !== null) symlinkSync(at, join(bin, t));
35 }
36 for (const [name, body] of Object.entries(extra)) {
37 writeFileSync(join(bin, name), body);
38 chmodSync(join(bin, name), 0o755);
39 }
40 return bin;
41 }
42
43 /** A forge that keeps every body it is sent. */
44 function standIn(): { url: string; bodies: Record<string, unknown>[]; stop(): void } {
45 const bodies: Record<string, unknown>[] = [];
46 const server = Bun.serve({
47 port: 0,
48 hostname: "127.0.0.1",
49 async fetch(req) {
50 bodies.push((await req.json()) as Record<string, unknown>);
51 return Response.json({ composeSha: "", commands: [] });
52 },
53 });
54 return { url: `http://127.0.0.1:${String(server.port)}`, bodies, stop: () => server.stop(true) };
55 }
56
57 const BASIC = ["bash", "curl", "tr", "grep", "head", "mkdir", "date", "cat", "printf"];
58 const lacks = ["bash", "curl"].filter((t) => Bun.which(t) === null);
59
60 describe("the agent, missing a tool", () => {
61 test.skipIf(lacks.length > 0)("without jq it still says so, in JSON it builds by hand, with the boot's status", async () => {
62 const box = mkdtempSync(join(tmpdir(), "forge-game-boot-"));
63 const forge = standIn();
64 try {
65 // No jq; a docker; a cloud-init that says how the boot went, quotes and all.
66 const bin = pathOf(box, BASIC, {
67 docker: "#!/usr/bin/env bash\nexit 0\n",
68 "cloud-init": "#!/usr/bin/env bash\nprintf 'status: error\\nerrors:\\n - \"package jq: apt lock held\"\\n'\n",
69 });
70 const p = Bun.spawn(["bash", AGENT], {
71 env: {
72 PATH: bin,
73 FORGE_URL: forge.url,
74 FORGE_GAME_TOKEN: TOKEN,
75 FORGE_GAME_DIR: join(box, "game"),
76 FORGE_GAME_DOCKER: "docker",
77 FORGE_GAME_ONCE: "1",
78 },
79 stdout: "pipe",
80 stderr: "pipe",
81 });
82 expect(await p.exited).toBe(0);
83 const said = await new Response(p.stderr).text();
84 expect(forge.bodies, `the agent said: ${said}`).toHaveLength(1);
85 expect(forge.bodies[0]).toEqual({ agent: 1, boot: 'missing jq: status: error errors: - "package jq: apt lock held" ' });
86 expect(said).toContain("missing jq; saying so and checking again in 30s");
87 } finally {
88 forge.stop();
89 await rm(box, { recursive: true, force: true });
90 }
91 });
92
93 test.skipIf(lacks.length > 0)("--boot-report reads its env file and posts cloud-init's status once", async () => {
94 const box = mkdtempSync(join(tmpdir(), "forge-game-report-"));
95 const forge = standIn();
96 try {
97 const dir = join(box, "game");
98 mkdirSync(dir, { recursive: true });
99 writeFileSync(join(dir, "agent.env"), `FORGE_URL=${forge.url}\nFORGE_GAME_TOKEN=${TOKEN}\n`, { mode: 0o600 });
100 const bin = pathOf(box, BASIC, {
101 "cloud-init": "#!/usr/bin/env bash\nprintf 'status: running\\ndetail: DataSourceDigitalOcean\\n'\n",
102 });
103 const p = Bun.spawn(["bash", AGENT, "--boot-report"], { env: { PATH: bin, FORGE_GAME_DIR: dir }, stdout: "pipe", stderr: "pipe" });
104 expect(await p.exited).toBe(0);
105 expect(forge.bodies).toEqual([{ agent: 1, boot: "boot report: status: running detail: DataSourceDigitalOcean " }]);
106 } finally {
107 forge.stop();
108 await rm(box, { recursive: true, force: true });
109 }
110 });
111 });
112
113 describe("on the forge", () => {
114 let dir = "";
115 let app: App;
116 let servers: Servers;
117 let alice: User;
118
119 beforeAll(async () => {
120 dir = mkdtempSync(join(tmpdir(), "forge-game-boot-doors-"));
121 app = createApp({ dataDir: dir, port: 0 });
122 servers = await serve(app);
123 const made = await createUser(app.db, {
124 origin: "seed",
125 trusted: true,
126 username: "alice",
127 email: "[email protected]",
128 password: "a-good-passphrase",
129 adminIfFirst: true,
130 });
131 if (!made.ok) throw new Error(made.error);
132 alice = made.value;
133 createGameBox(app.db, { name: "mc" });
134 });
135 afterAll(async () => {
136 servers.stop();
137 app.close();
138 await rm(dir, { recursive: true, force: true });
139 });
140
141 test("a boot word is kept beside what was known, and a full sync clears it", () => {
142 const box = () => boxNamed(app.db, "mc")!;
143 recordSync(app.db, box(), { composeSha: "abc", host: { memMiB: 8000 } });
144 recordSync(app.db, box(), { boot: "missing jq: status: error" });
145 expect(box()).toMatchObject({ boot: "missing jq: status: error", composeSha: "abc", host: { memMiB: 8000 } });
146 expect(bootWords(box())).toBe("Box is up but missing jq: status: error");
147 expect(bootWords({ boot: "boot report: status: running detail: DataSourceDigitalOcean " })).toBe("Box is up; setup says: running");
148 recordSync(app.db, box(), { composeSha: "abc", host: { memMiB: 8000 } });
149 expect(box().boot).toBe("");
150 recordSync(app.db, box(), { boot: "missing jq docker: status: error" });
151 });
152
153 test("/games and the terminal's Games say the box is up but missing what it misses", async () => {
154 const page = await (
155 await fetch(`${servers.url}/games`, { headers: { cookie: `forge_session=${createSession(app.db, alice.id).token}` } })
156 ).text();
157 expect(page).toContain("Box is up but missing jq docker: status: error");
158 const terminal = headlessTerminal(140, 20);
159 const { app: tui, session } = createForgeApp(
160 app,
161 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice },
162 { terminal, exitHooks: false },
163 );
164 tui.start();
165 tui.ctx.push(gamesScreen(session, tui.ctx));
166 await settleApp(tui);
167 expect(tui.screen.toText()).toContain("mc: Box is up but missing jq docker: status: error");
168 tui.stop?.();
169 });
170 });
test/game-box.test.ts +15 −2
@@ -17,7 +17,7 @@ import { readPlaces } from "../src/cloud/places_read.ts";
1717 import { bootConfig } from "../src/cloud/droplet.ts";
1818 import { insertPinned } from "../src/core/pinned.ts";
1919 import { createUser, type User } from "../src/core/users.ts";
20 import { AGENT_SH, GAME_PORT, gameBootConfig } from "../src/games/boot.ts";
20 import { AGENT_SH, GAME_PORT, INSTALL, gameBootConfig } from "../src/games/boot.ts";
2121 import { boxByToken, boxNamed, createGameBox, rotateGameBoxToken } from "../src/games/store.ts";
2222 import { sha256 } from "../src/kernel/hash.ts";
2323
@@ -32,11 +32,24 @@ describe("the boot config", () => {
3232 expect(cfg).toContain(`path: /opt/forge-game/agent.sh\n permissions: "0755"\n content: ${JSON.stringify(AGENT_SH)}`);
3333 expect(cfg).toContain("path: /etc/systemd/system/forge-game-agent.service");
3434 expect(cfg).toContain("systemctl enable --now forge-game-agent.service");
35 for (const pkg of ["docker.io", "docker-compose-v2", "jq", "curl", "ufw"]) expect(cfg).toContain(` - ${pkg}\n`);
35 for (const pkg of ["docker.io", "docker-compose-v2", "jq", "curl", "ufw"]) expect(INSTALL).toContain(` ${pkg}`);
3636 expect(cfg).toContain('{\\"data-root\\":\\"/mnt/forge_box_data/docker\\"');
3737 expect(cfg).toContain("mkswap /swapfile");
3838 });
3939
40 test("installs in runcmd, waiting out apt's lock, three tries, before the agent starts; reports the boot last", () => {
41 // A first boot's unattended upgrade holds the lock: \`packages:\` failed and left no jq (box mc).
42 expect(cfg).not.toContain("package_upgrade");
43 expect(cfg).not.toContain("packages:");
44 expect(INSTALL).toStartWith("for try in 1 2 3; do apt-get -o DPkg::Lock::Timeout=600 update && ");
45 expect(INSTALL).toContain("apt-get -o DPkg::Lock::Timeout=600 install -y docker.io docker-compose-v2 jq");
46 const runcmd = cfg.slice(cfg.indexOf("runcmd:\n")).split("\n").filter((l) => l.startsWith(" - "));
47 const at = (needle: string) => runcmd.findIndex((l) => l.includes(needle));
48 expect(at("DPkg::Lock::Timeout=600")).toBeGreaterThan(-1);
49 expect(at("DPkg::Lock::Timeout=600")).toBeLessThan(at("systemctl enable --now forge-game-agent.service"));
50 expect(runcmd.at(-1)).toBe(" - bash /opt/forge-game/agent.sh --boot-report");
51 });
52
4053 test("opens only the game's port: no SSH, no backend, no web", () => {
4154 const allowed = cfg.split("\n").filter((l) => l.includes("ufw allow"));
4255 expect(allowed).toEqual([` - ufw allow ${GAME_PORT}/tcp`]);

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

Keyboard shortcuts

Docs