Public: anyone can read this; the crew can change it.
A game box's command is never lost to its agent's update #17791
Merged 8h 54m ago, live in production
sold/command-never-lost → main 0 commits
5 files
changed +57
−6
docs/features/game-box.md +1 −1
| @@ -32,7 +32,7 @@ experiment. | ||
| 32 | 32 | - **Play this disk's worlds:** mount the volume as above without `-o ro`, `mkdir /mnt/look/forge-aside`, move everything else there except `lost+found` into it, `umount /mnt/look`, and `systemctl restart forge-game-agent`. The agent copies this disk's data beside `forge-aside`, which it does not count as data. The volume needs room for both. |
| 33 | 33 | - **`no-volume`:** attach the volume; the agent sees it and looks again by itself. Docker has usually made its folders by then, so it ends as `other-worlds`: go on as above. **`signature`, `mount`:** look at the device on the machine, then `systemctl restart forge-game-agent`. |
| 34 | 34 | - **Reading it:** every step is a line of `/opt/forge-game/.volume.log` (the last 40 kept), each step of a move also posted to the forge as the box's word. Each sync's diag carries the volume's device and the log's last 12 lines (`disk.device`, `disk.log`). The owner reads them under "The volume (.volume.log)" in `/games/<box>`'s run log and on the terminal's box screen, and a last line starting `failed:` or `refused:` comes first in the Box section and the Games screen's top line as "The volume: …". |
| 35 | - **Updating itself:** every sync answers `agentSha`, the sha256 of the agent this forge ships. An agent whose own sha differs fetches `GET /api/v1/games/agent/script` with its token, checks that the fetched script's sha is the one answered and that `bash -n` parses it, puts it in place (`agent.sh.next`, then a rename) and exits, and systemd starts the new one. A script whose sha is not the one answered is deleted and never runs; an agent already current fetches nothing. An agent older than this step does not update itself; it takes the new one with its machine's next replace. | |
| 35 | - **Updating itself:** every full sync whose answer carries no command answers `agentSha`, the sha256 of the agent this forge ships (the agent exits before it applies that answer, and a command is handed out once). An agent whose own sha differs fetches `GET /api/v1/games/agent/script` with its token, checks that the fetched script's sha is the one answered and that `bash -n` parses it, puts it in place (`agent.sh.next`, then a rename) and exits, and systemd starts the new one. A script whose sha is not the one answered is deleted and never runs; an agent already current fetches nothing. An agent older than this step does not update itself; it takes the new one with its machine's next replace. | |
| 36 | 36 | - **`/forge` on the proxy:** the proxy's plugin leaves each request as `plugins/forge/outbox/<id>.json` (at most 2 KiB) and shows a player what it finds in `plugins/forge/inbox`. The agent reads and writes both inside the running `velocity` container, as `bungeecord`; with no running `velocity` service it does nothing there. A full sync's body carries the oldest 20 as `ask`, and only the files whose ids the answer's `asked` names are deleted: with no `asked` (an older forge) none is, and the plugin stops at 64 waiting. A file over 2 KiB, one that is no JSON object, or one whose `id` is not its file's name in lowercase is dropped, with one line in the agent's log that never holds its text. The answer's `told` (at most 20, 16 KiB each) goes to the inbox, each file put in place whole, none while 64 wait. A quick poll that says `"told": true` may be answered with `told` too; `ask` goes with full syncs only. Each answer has a number `n`: every body's `got` names those that are in the inbox, until a sync that named them is answered, and the forge hands an answer out again until then. The agent keeps the numbers for two hours (`/opt/forge-game/.told.json`), so a player does not see an answer twice. |
| 37 | 37 | - **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. |
| 38 | 38 | - **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. |
src/contract/openapi/routes/postApiV1GamesAgentSync.ts +1 −1
| @@ -4,7 +4,7 @@ export const route: Route = { | ||
| 4 | 4 | method: "post", |
| 5 | 5 | path: "/api/v1/games/agent/sync", |
| 6 | 6 | summary: "A game box agent's sync: status, logs and results in; compose, .env and commands out", |
| 7 | detail: "The bearer is the game box's token. Send `{ agent, composeSha, services, logs, results, host, ask? (the proxy's /forge requests) }`; the answer is `{ composeSha, compose? (only when the sha differs), env, commands, told? (answers to those requests), agentSha }`, each command handed out once; agentSha is the sha256 of the agent this forge runs, which a box whose own differs fetches from GET /api/v1/games/agent/script", | |
| 7 | detail: "The bearer is the game box's token. Send `{ agent, composeSha, services, logs, results, host, ask? (the proxy's /forge requests) }`; the answer is `{ composeSha, compose? (only when the sha differs), env, commands, told? (answers to those requests), agentSha? (only when there are no commands) }`, each command handed out once; agentSha is the sha256 of the agent this forge runs, which a box whose own differs fetches from GET /api/v1/games/agent/script", | |
| 8 | 8 | auth: false, |
| 9 | 9 | role: "anonymous", |
| 10 | 10 | refuses: [401], |
src/games/store.ts +2
| @@ -727,6 +727,8 @@ export function recordSync( | ||
| 727 | 727 | } |
| 728 | 728 | recordResults(db, box.id, body.results, at); |
| 729 | 729 | })(); |
| 730 | // The boot report reads no answer (`say_boot`): a command in it would be lost. | |
| 731 | if (body.light !== true && typeof body.boot === "string") return []; | |
| 730 | 732 | // Handed out once: a command leaves the queue the moment it is in a reply. |
| 731 | 733 | const due = db |
| 732 | 734 | .query< |
src/http/games_routes.ts +4 −2
| @@ -99,8 +99,10 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> { | ||
| 99 | 99 | if (Array.isArray(body.ask)) reply["asked"] = asked; |
| 100 | 100 | const told = toldTo(ctx.app.db, box, Date.now(), body.got); |
| 101 | 101 | if (told.length > 0) reply["told"] = told; |
| 102 | // The agent this forge runs: a box whose own differs fetches it (`gameAgentScript`) and restarts. | |
| 103 | reply["agentSha"] = AGENT_SHA; | |
| 102 | // The agent this forge runs: a box whose own differs fetches it (`gameAgentScript`) and restarts | |
| 103 | // before it applies the answer, so never beside commands, which are handed out once. The next | |
| 104 | // answer without one says it. | |
| 105 | if (commands.length === 0) reply["agentSha"] = AGENT_SHA; | |
| 104 | 106 | // The runner token of "Run checks while servers sleep", once; or the word to drop it. |
| 105 | 107 | const lend = lendAnswer(ctx.app.db, box, body.lend); |
| 106 | 108 | if (lend !== undefined) reply["lend"] = lend; |
test/game-agent-update.test.ts +49 −2
| @@ -7,14 +7,15 @@ | ||
| 7 | 7 | */ |
| 8 | 8 | import { $ } from "bun"; |
| 9 | 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 10 | import { copyFileSync, mkdirSync, mkdtempSync, readFileSync } from "node:fs"; | |
| 10 | import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; | |
| 11 | 11 | import { rm } from "node:fs/promises"; |
| 12 | 12 | import { tmpdir } from "node:os"; |
| 13 | 13 | import { join } from "node:path"; |
| 14 | 14 | import { createApp, type App } from "../src/app.ts"; |
| 15 | 15 | import { AGENT_SH, AGENT_SHA } from "../src/games/boot.ts"; |
| 16 | import { createGameBox } from "../src/games/store.ts"; | |
| 16 | import { commandOf, createGameBox, queueCommand } from "../src/games/store.ts"; | |
| 17 | 17 | import { serve, type Servers } from "../src/http/server.ts"; |
| 18 | import { pollUntil } from "./helpers/poll.ts"; | |
| 18 | 19 | |
| 19 | 20 | const AGENT = join(import.meta.dir, "../src/games/agent.sh"); |
| 20 | 21 | const TOKEN = "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG"; |
| @@ -139,4 +140,50 @@ describe("the forge", () => { | ||
| 139 | 140 | expect(script.headers.get("x-agent-sha")).toBe(AGENT_SHA); |
| 140 | 141 | expect((await fetch(`${servers.url}/api/v1/games/agent/script`, { headers: { authorization: "Bearer fgb_wrong" } })).status).toBe(401); |
| 141 | 142 | }); |
| 143 | ||
| 144 | const post = async (bearer: string, body: object) => | |
| 145 | (await ( | |
| 146 | await fetch(`${servers.url}/api/v1/games/agent/sync`, { method: "POST", headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json" }, body: JSON.stringify({ agent: 1, ...body }) }) | |
| 147 | ).json()) as { commands: { id: string }[]; agentSha?: string }; | |
| 148 | ||
| 149 | test("an answer carries commands or agentSha, never both; the boot report takes no command", async () => { | |
| 150 | const made = createGameBox(app.db, { name: "quiet" }); | |
| 151 | const id = queueCommand(app.db, made.id, "hub", "rcon", "list", ""); | |
| 152 | expect((await post(made.token, { boot: "cloud-init done" })).commands).toEqual([]); | |
| 153 | expect(commandOf(app.db, id)?.handed).toBe(false); | |
| 154 | const full = await post(made.token, {}); | |
| 155 | expect(full.commands.map((c) => c.id)).toEqual([id]); | |
| 156 | expect(full.agentSha).toBeUndefined(); | |
| 157 | expect(await post(made.token, {})).toMatchObject({ commands: [], agentSha: AGENT_SHA }); | |
| 158 | }); | |
| 159 | ||
| 160 | test.skipIf(lacks.length > 0)("a command queued before the agent replaces itself runs, and then it updates", async () => { | |
| 161 | const made = createGameBox(app.db, { name: "late" }); | |
| 162 | const root = mkdtempSync(join(tmpdir(), "forge-game-late-")); | |
| 163 | mkdirSync(join(root, "game")); | |
| 164 | const self = join(root, "agent.sh"); | |
| 165 | writeFileSync(self, `${AGENT_SH}\n# an older agent\n`); | |
| 166 | const id = queueCommand(app.db, made.id, "", "shell", "echo ran", ""); | |
| 167 | const start = () => | |
| 168 | Bun.spawn(["bash", self], { | |
| 169 | env: { PATH: process.env["PATH"] ?? "", HOME: root, FORGE_URL: servers.url, FORGE_GAME_TOKEN: made.token, FORGE_GAME_DIR: join(root, "game"), FORGE_GAME_DOCKER: "true", FORGE_GAME_DIAG_S: "0", FORGE_GAME_VOLUME_CHECK: "0" }, | |
| 170 | stdout: "ignore", | |
| 171 | stderr: "ignore", | |
| 172 | }); | |
| 173 | try { | |
| 174 | // The older one is handed it, and ends by itself at a later answer, its script replaced. | |
| 175 | expect(await start().exited).toBe(0); | |
| 176 | expect(readFileSync(self, "utf8")).toBe(AGENT_SH); | |
| 177 | const next = start(); | |
| 178 | try { | |
| 179 | await pollUntil(() => commandOf(app.db, id)?.done === true, "its answer is here", 15_000); | |
| 180 | } finally { | |
| 181 | next.kill(); | |
| 182 | await next.exited; | |
| 183 | } | |
| 184 | expect(commandOf(app.db, id)).toMatchObject({ ok: true, output: "ran" }); | |
| 185 | } finally { | |
| 186 | await rm(root, { recursive: true, force: true }); | |
| 187 | } | |
| 188 | }, 40_000); | |
| 142 | 189 | }); |
new above
offline