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

Games: a console command is answered at once, and a log line is kept once #17626

opened this

Closed 20h 30m ago

sold/game-lane → main 3 commits

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
16 files changed +705 −58
docs/features/games.md +6
@@ -13,10 +13,16 @@ A **game box** is a VM on your own cloud running Docker and `forge-game-agent`,
1313 - **MCP:** `games` (admin-listed): `list`, `console`, `power`, `env`, `config`, `config_set`, and `mods`, `mods_search`, `mods_install`, `mods_update`, `mods_remove` (each change planned first; `dryRun: false` commits), with the same grants.
1414 - **Agent:** `POST /api/v1/games/agent/sync` with the box token as bearer (`src/http/games_routes.ts`, `src/games/store.ts`): status, a log tail (2,000 lines a service), command results in; the compose (only when its sha differs), env files and queued commands (each handed out once) out.
1515
16 - **Commands at once:** beside its sync the agent holds one poll open, `POST /api/v1/games/agent/commands`, which the forge answers the moment a console or player command is queued (`src/games/wake.ts`); the result comes back with the next poll. Anything else queued (a restart, a world, a shell command) makes the poll ask for a full sync at once. A box holds at most one request (a newer poll ends the one before it), looked at again every 20 s; a closing forge lets it go with nothing handed out. An agent without the poll still gets every command with its sync. A command handed out and not answered (2 minutes for a console, player or shell command, 2 hours for a job) says "No answer came back; it may have run." It is never sent again; an answer that comes late replaces the words.
17
1618 ## What a sync carries
1719
1820 The agent sends every string plain: terminal colour escapes and control bytes (which itzg images and `rcon-cli` print) are taken out, and every part is checked as JSON and passed through a file, never a command line, so a large sync still goes. The forge cleans the same from what an older agent sends (`boundedMachineBody`), and refuses only a body that is not JSON, with where it broke; its log holds the first 200 bytes.
1921
22 Log lines go as a batch under an id (`logsId`) until a sync is answered, and the forge skips a batch it has, so a sync whose answer was lost stores nothing twice; the next batch starts after the last line read, by Docker's own time. A failed sync or poll is tried again after 1 or 2 s, and after a minute of failures every 10 to 14 s; a sync is given 5 s to be answered, then 10, then 20. The first poll the forge answers again asks for a sync at once.
23
24 A player command (`op`, `deop`, `whitelist`, `ban`, `pardon`, `kick`) the server refused ("That player does not exist") is kept as failed, with up to three names seen on that server (never another's) that are closest to the one typed; the name itself is never changed (`src/games/outcome.ts`).
25
2026 ## Sleep and wake
2127
2228 Each game server is warm or sleeps when empty. A sleeping server container stops after 10 minutes with nobody on it, which frees all its memory (not the bill: the machine it runs on is billed in full, asleep or not), and starts again when a player joins through the proxy: the player waits on the join screen while it boots (measured 13.9 to 15.2 s for Paper 1.21.6 once its world exists, 30 s on its first boot). The Minecraft client gives up on a silent join after about 30 s, so a boot that takes longer means one rejoin.
src/contract/openapi/routes/index.ts +1
@@ -383,6 +383,7 @@ export { route as postApiV1ForgeTemplates } from "./postApiV1ForgeTemplates.ts";
383383 export { route as postApiV1Forges } from "./postApiV1Forges.ts";
384384 export { route as postApiV1ForgesNameClaimLink } from "./postApiV1ForgesNameClaimLink.ts";
385385 export { route as postApiV1ForgesNameSandbox } from "./postApiV1ForgesNameSandbox.ts";
386 export { route as postApiV1GamesAgentCommands } from "./postApiV1GamesAgentCommands.ts";
386387 export { route as postApiV1GamesAgentSync } from "./postApiV1GamesAgentSync.ts";
387388 export { route as postApiV1Heartbeat } from "./postApiV1Heartbeat.ts";
388389 export { route as postApiV1MaintenanceDutiesName } from "./postApiV1MaintenanceDutiesName.ts";
src/contract/openapi/routes/postApiV1GamesAgentCommands.ts added +11
@@ -0,0 +1,11 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: "/api/v1/games/agent/commands",
6 summary: "A game box agent's poll for commands: results in, the next commands out as soon as they are queued",
7 detail: "The bearer is the game box's token. Send `{ results, wait }`: the results of the console and player commands it ran, and how many seconds to hold the request (25 at most). The answer is `{ commands, sync? }`, each command handed out once; `sync: true` asks for a full sync now. A newer poll of the same box ends the one before it",
8 auth: false,
9 role: "anonymous",
10 refuses: [401],
11 };
src/core/migration-pins/20261202195500-game-log-batch.pin added +1
@@ -0,0 +1,1 @@
1 9bb830bc028a21481ea8f4087a3d7791c637a33572a8856692eb4ce60a2e186c
src/core/migrations/20261202195500-game-log-batch.ts added +8
@@ -0,0 +1,8 @@
1 // The last batch of log lines a game box's sync stored (#17610): the agent sends a batch under its id
2 // until a sync is answered, and one the forge has is skipped. Additive: one table, one row a box.
3 export default `
4 CREATE TABLE IF NOT EXISTS game_log_batch (
5 box_id TEXT PRIMARY KEY,
6 id TEXT NOT NULL
7 );
8 `;
src/games/agent.sh +106 −17
@@ -4,7 +4,8 @@
44 # $FORGE_URL/api/v1/games/agent/sync with the box's bearer token, and does what the answer asks:
55 # writes compose.yml and the secret env files beside it and brings the project up when the compose
66 # sha (or an env file) changes, and runs the queued commands. Nothing dials in to the box. A failed
7 # sync waits 5 s and tries again, forever. The token is read from the environment (systemd's
7 # sync is tried again after 1 or 2 s (10 to 14 after many), forever. Console and player commands do
8 # not wait for a sync: `lane` polls for them. The token is read from the environment (systemd's
89 # EnvironmentFile, mode 600) and handed to curl in a header file, never on a command line.
910 set -u
1011
@@ -326,6 +327,10 @@ json_or() {
326327
327328 since="$(now)"
328329 [ -f "$DIR/.results" ] || echo '[]' >"$DIR/.results"
330 # Where a command's result waits to be sent: the sync's here, the poll's own in `lane`.
331 RESULTS="$DIR/.results"
332 [ -f "$DIR/.logs.last" ] || echo '{}' >"$DIR/.logs.last"
333 [ -f "$DIR/.logs.out" ] || : >"$DIR/.logs.out"
329334
330335 # The services as compose sees them, with each one's CPU and memory from docker stats.
331336 services() {
@@ -348,11 +353,25 @@ services() {
348353 })'
349354 }
350355
351 # New log lines since the last sync, at most 200 a service: "hub | text" split at the first bar.
356 # New log lines, at most 200 a service: "hub | <time> text" split at the first bar. Each batch goes
357 # under an id, whole, until a sync is answered, and the forge skips one it has. What follows starts
358 # after the last line read of each service (.logs.last, Docker's own nanosecond times), so a line is
359 # sent once however the seconds of two reads overlap.
352360 logs() {
353 capped 5 "${COMPOSE[@]}" logs --no-color --since "$1" 2>/dev/null | jq -cRn '
354 [inputs | capture("^(?<s>[^ |]+)[ ]*\\| ?(?<l>.*)$")?]
355 | group_by(.s) | map({key: .[0].s, value: (map(.l) | .[-200:])}) | from_entries' 2>/dev/null || echo '{}'
361 [ -s "$DIR/.logs.out" ] && return
362 local next
363 next="$(now)"
364 json_or '{}' <"$DIR/.logs.last" >"$DIR/.logs.from" 2>/dev/null || echo '{}' >"$DIR/.logs.from"
365 capped 5 "${COMPOSE[@]}" logs --no-color --since "$since" --timestamps 2>/dev/null | jq -cRn --slurpfile from "$DIR/.logs.from" --arg id "$(date +%s)-$RANDOM$RANDOM" '
366 $from[0] as $from
367 | [inputs | capture("^(?<s>[^ |]+)[ ]*\\| ?((?<t>[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:.]+Z)( |$))?(?<l>.*)$")? | select(.t == null or .t > ($from[.s] // ""))]
368 | group_by(.s)
369 | {id: $id, lines: (map({key: .[0].s, value: (map(.l[0:2000]) | .[-200:])}) | from_entries),
370 last: ($from + (map({key: .[0].s, value: (map(.t // "") | max)} | select(.value != "")) | from_entries))}' >"$DIR/.logs.next" 2>/dev/null || return 0
371 since="$next"
372 jq -e '.lines != {}' "$DIR/.logs.next" >/dev/null 2>&1 || return 0
373 # The batch is on disk before its lines count as read.
374 jq -c '.last' "$DIR/.logs.next" >"$DIR/.logs.last.next" && mv "$DIR/.logs.next" "$DIR/.logs.out" && mv "$DIR/.logs.last.next" "$DIR/.logs.last"
356375 }
357376
358377 # The running services a command can be run in. The waker (forge-waker, the socket proxy) has no
@@ -553,8 +572,7 @@ run() {
553572 ;;
554573 esac
555574 fi
556 jq -c --arg id "$id" --argjson ok "$ok" --arg out "${out:0:$max}" '. + [{id: $id, ok: $ok, output: $out}]' "$DIR/.results" >"$DIR/.results.next" &&
557 mv "$DIR/.results.next" "$DIR/.results"
575 keep_result "$id" "$ok" "$out" "$max"
558576 }
559577
560578 # ---- the job queue: compose up, pull and the power verbs run here, one at a time, in the
@@ -586,8 +604,8 @@ queue_job() {
586604 # Keep a command's result for the next sync.
587605 keep_result() {
588606 local most="${4:-4096}"
589 jq -c --arg id "$1" --argjson ok "$2" --arg out "${3:0:$most}" '. + [{id: $id, ok: $ok, output: $out}]' "$DIR/.results" >"$DIR/.results.next" &&
590 mv "$DIR/.results.next" "$DIR/.results"
607 jq -c --arg id "$1" --argjson ok "$2" --arg out "${3:0:$most}" '. + [{id: $id, ok: $ok, output: $out}]' "$RESULTS" >"$RESULTS.next" &&
608 mv "$RESULTS.next" "$RESULTS"
591609 }
592610
593611 # Each tick: reap a job that ended (its result, the sha an up made current), then start the next.
@@ -897,12 +915,12 @@ export -f world_job world_steps world_cid world_sh world_level world_index world
897915 export WORLDS HELPER
898916
899917 sync() {
900 local next answer
901 next="$(now)"
918 local answer code
902919 # Each part through a file, checked as JSON on the way: a sync can pass the 128 KB one argument
903920 # may hold (200 log lines from each of several servers), and then curl would never run.
904921 services | json_or '[]' >"$DIR/.sync.services"
905 logs "$since" | json_or '{}' >"$DIR/.sync.logs"
922 logs
923 json_or '{}' <"$DIR/.logs.out" >"$DIR/.sync.logs"
906924 json_or '[]' <"$DIR/.results" >"$DIR/.sync.results"
907925 host | json_or '{}' >"$DIR/.sync.host"
908926 bounded_diag | json_or '{}' >"$DIR/.sync.diag"
@@ -936,17 +954,28 @@ sync() {
936954 else [.[0]] + (.[1:] | codes) end;
937955 (if . == "" then ["0"] else split(";") end) | [codes[] | $t[.] // empty | "\u00a7" + .] | join("");
938956 def plain: gsub("\u001b\\[(?<p>[0-9;]*)m"; (.p // "" | sect)) | gsub("^(\u00a7r)+|(\u00a7r)+$"; "") | gsub("(\u00a7r)+"; "\u00a7r") | gsub("\u001b\\[[0-9;?]*[ -/]*[@-~]"; "") | gsub("\u001b[@-_]?"; "") | gsub("[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]"; "");
939 {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], snapshots: $snapshots[0], chat: $chat[0].lines, chatId: $chat[0].id, lend: $lend}
957 {agent: 1, composeSha: $sha, services: $services[0], logs: ($logs[0].lines // {}), logsId: $logs[0].id, results: $results[0], host: $host[0], diag: $diag[0], people: $people[0], metrics: $metrics[0], snapshots: $snapshots[0], chat: $chat[0].lines, chatId: $chat[0].id, lend: $lend}
940958 | walk(if type == "string" then plain else . end)' >"$DIR/.sync.body" || return 1
941 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
959 # The answer is never a file: it can carry a world's signed link. Its status is its last line.
960 answer="$(curl -sS -m "$(sync_limit)" -H "@$AUTH" -H 'content-type: application/json' --data-binary "@$DIR/.sync.body" -w '\n%{http_code}' "${FORGE_URL%/}/api/v1/games/agent/sync")" || return 1
961 code="${answer##*$'\n'}"
962 answer="${answer%$'\n'*}"
963 if [[ "$code" != 2?? ]]; then
964 echo "forge-game-agent: the forge answered the sync $code" >&2
965 # Refused as it is (not JSON, too large): the same lines would be refused for ever.
966 case "$code" in 400 | 413) : >"$DIR/.logs.out" ;; esac
967 return 1
968 fi
942969 # Delivered: the results and the log lines are the forge's now.
943970 echo '[]' >"$DIR/.results"
944971 : >"$DIR/.chat.out"
945 since="$next"
972 : >"$DIR/.logs.out"
946973 # A newer agent first: nothing of this answer is applied by a script the forge has replaced.
947974 self_update "$(jq -r '.agentSha // ""' <<<"$answer")"
948975 apply "$answer"
949976 lend_apply "$answer"
977 # Answered: what came of applying it is not a failed sync, which would be tried again at once.
978 return 0
950979 }
951980
952981 # ---- "Run checks while servers sleep" (#17578): the box's side. With the owner's switch on, the
@@ -1320,18 +1349,78 @@ lend_give() {
13201349 rm -f "$LEND_JOBAUTH"
13211350 }
13221351
1352 # ---- the poll for commands, beside the sync (a full sync gathers for seconds): one request the forge
1353 # holds until a console or player command is queued; its result goes back with the next poll, at once.
1354 # Nothing here can cut the box off: it never updates the agent, every command it does not take still
1355 # comes with the sync, and it ends with the agent. ----
1356
1357 NUDGE="$DIR/.nudge"
1358 # Wait `secs`, or until the poll asks for a sync now. No process is started while it waits.
1359 nap() {
1360 if [ -p "$NUDGE" ]; then read -r -t "$1" -u 8 _ || true; else sleep "$1"; fi
1361 }
1362 nudge() { [ -p "$NUDGE" ] && printf '\n' >&8; }
1363 # Seconds before the next try after the `n`th failure in a row: 1 or 2, so a forge that was only
1364 # starting is found again at once; after 30 failures 10 to 14, for a forge that is gone. The random
1365 # part keeps boxes cut off together from coming back together.
1366 backoff() {
1367 if [ "$1" -le 30 ]; then echo $((1 + RANDOM % 2)); else echo $((10 + RANDOM % 5)); fi
1368 }
1369 # How long a sync may take to be answered: short while the forge has been answering (it takes well
1370 # under a second), longer after each failure, so one that is only slow is still reached.
1371 sync_limit() {
1372 case "$failed" in 0) echo "${FORGE_GAME_SYNC_S:-5}" ;; 1) echo 10 ;; *) echo 20 ;; esac
1373 }
1374
1375 lane() {
1376 local main="$1" answer failed=0 began cmd
1377 RESULTS="$DIR/.lane.results"
1378 jq -e 'type == "array"' "$RESULTS" >/dev/null 2>&1 || echo '[]' >"$RESULTS"
1379 while kill -0 "$main" 2>/dev/null; do
1380 began=$SECONDS
1381 if ! jq -c --argjson wait "${FORGE_GAME_WAIT:-20}" '{results: ., wait: $wait}' "$RESULTS" >"$DIR/.lane.body" ||
1382 ! answer="$(curl -fsS -m 35 --connect-timeout 10 -H "@$AUTH" -H 'content-type: application/json' --data-binary "@$DIR/.lane.body" "${FORGE_URL%/}/api/v1/games/agent/commands" 2>/dev/null)"; then
1383 failed=$((failed + 1))
1384 sleep "$(backoff "$failed")"
1385 continue
1386 fi
1387 # The forge is back: a sync that is waiting its turn goes now.
1388 [ "$failed" -gt 0 ] && nudge
1389 failed=0
1390 echo '[]' >"$RESULTS"
1391 while IFS= read -r cmd <&3; do
1392 [ -n "$cmd" ] && run "$cmd"
1393 done 3< <(jq -c '.commands // [] | .[]' <<<"$answer" 2>/dev/null)
1394 if [ -f "$DIR/.people.due" ] || [[ "$answer" == *'"sync":true'* ]]; then nudge; fi
1395 # An empty answer at once (a forge closing, a newer poll) is not asked again in a tight loop.
1396 if [ "$(jq -r '.commands // [] | length' <<<"$answer" 2>/dev/null)" = 0 ] && [ $((SECONDS - began)) -lt 1 ]; then sleep 1; fi
1397 done
1398 }
1399
13231400 # Once at each start: a volume attached but not mounted at the data directory is mounted, or the
13241401 # data the root disk holds is moved onto it.
13251402 if [ "${FORGE_GAME_VOLUME_CHECK:-1}" = 1 ] && [ -n "$(volume_device)" ] && [ -n "$(data_dir)" ] && ! volume_here "$(volume_device)" "$(data_dir)"; then
13261403 FORGE_GAME_VOLUME_WAIT=1 volume_mount || true
13271404 fi
13281405
1406 if [ "$ONCE" != 1 ]; then
1407 rm -f "$NUDGE"
1408 mkfifo "$NUDGE" 2>/dev/null && exec 8<>"$NUDGE"
1409 lane $$ &
1410 fi
1411
1412 failed=0
13291413 while :; do
13301414 job_tick
13311415 shell_tick
1332 sync || echo "forge-game-agent: sync failed; again in ${EVERY}s" >&2
1416 wait="$EVERY"
1417 if sync; then failed=0; else
1418 failed=$((failed + 1))
1419 wait="$(backoff "$failed")"
1420 echo "forge-game-agent: sync failed; again in ${wait}s" >&2
1421 fi
13331422 job_tick
13341423 lend_tick
13351424 [ "$ONCE" = 1 ] && exit 0
1336 sleep "$EVERY"
1425 nap "$wait"
13371426 done
src/games/store.ts +87 −21
@@ -16,6 +16,7 @@ import { rm } from "node:fs/promises";
1616 import type { App } from "../app.ts";
1717 import { resolveSecrets, setSecret } from "../core/secret_store.ts";
1818 import type { User } from "../core/users.ts";
19 import { wakeBox } from "./wake.ts";
1920 import { sha256 } from "../kernel/hash.ts";
2021 import { id as newId } from "../kernel/id.ts";
2122
@@ -277,6 +278,7 @@ export function queueCommand(db: Database, boxId: string, service: string, kind:
277278 by,
278279 new Date().toISOString(),
279280 );
281 wakeBox(db, boxId, isQuick(kind) ? "command" : "sync");
280282 return id;
281283 }
282284
@@ -290,25 +292,62 @@ export interface CommandState {
290292 readonly ok: boolean | null;
291293 readonly output: string;
292294 }
293 export function commandOf(db: Database, id: string): CommandState | undefined {
295 /** What a command handed to the box and never answered says: it is not sent again, since running one twice is worse. */
296 export const NO_ANSWER = "No answer came back; it may have run.";
297 /** How long an answer is waited for: a quick command or a shell one ends in 30 s, a job (a pull, a world) can take an hour. */
298 const ANSWER_MS = 2 * 60_000;
299 const JOB_ANSWER_MS = 2 * 3_600_000;
300
301 /** A command as every door shows it. One whose answer never came is done with `ok` null; a late answer still replaces that. */
302 export function commandOf(db: Database, id: string, now = Date.now()): CommandState | undefined {
294303 const r = db
295304 .query<
296305 { id: string; kind: string; service: string; text: string; handed_at: string; done_at: string; ok: number | null; output: string },
297306 [string]
298307 >("SELECT id, kind, service, text, handed_at, done_at, ok, output FROM game_command WHERE id = ?1")
299308 .get(id);
300 return r === null
301 ? undefined
302 : {
303 id: r.id,
304 kind: r.kind,
305 service: r.service,
306 text: r.text,
307 handed: r.handed_at !== "",
308 done: r.done_at !== "",
309 ok: r.ok === null ? null : r.ok === 1,
310 output: r.output,
311 };
309 if (r === null) return undefined;
310 const limit = r.kind === "shell" || (QUICK as readonly string[]).includes(r.kind) ? ANSWER_MS : JOB_ANSWER_MS;
311 const unanswered = r.done_at === "" && r.handed_at !== "" && now - Date.parse(r.handed_at) > limit;
312 return {
313 id: r.id,
314 kind: r.kind,
315 service: r.service,
316 text: r.text,
317 handed: r.handed_at !== "",
318 done: r.done_at !== "" || unanswered,
319 ok: r.ok === null ? null : r.ok === 1,
320 output: unanswered ? NO_ANSWER : r.output,
321 };
322 }
323
324 /** What became of a command, in words: "ok: …", "failed: …", that no answer came, or that it waits. */
325 export const commandSays = (c: Pick<CommandState, "done" | "ok" | "handed" | "output">): string =>
326 !c.done ? (c.handed ? "sent to the box" : "queued") : c.ok === null ? c.output : `${c.ok ? "ok" : "failed"}: ${c.output}`;
327
328 /**
329 * For a stream of a service's answers: each call gives the commands settled since the last one, among
330 * those unsettled when the stream began or queued since. One told "no answer came" is told again if
331 * its answer comes late.
332 */
333 export function answersOf(db: Database, boxId: string, service: string): () => CommandState[] {
334 const pending = new Map<string, "waiting" | "unanswered">();
335 const look = (): void => {
336 for (const c of recentCommands(db, boxId, service, 10)) if ((!c.done || c.ok === null) && !pending.has(c.id)) pending.set(c.id, c.done ? "unanswered" : "waiting");
337 };
338 look();
339 return () => {
340 look();
341 const settled: CommandState[] = [];
342 for (const [id, was] of [...pending]) {
343 const c = commandOf(db, id);
344 if (c === undefined || c.ok !== null) pending.delete(id);
345 else if (!c.done || was === "unanswered") continue;
346 else pending.set(id, "unanswered");
347 if (c !== undefined) settled.push(c);
348 }
349 return settled;
350 };
312351 }
313352
314353 /** A service's RCON commands as typed, newest first, each once: the console's history. */
@@ -461,6 +500,8 @@ export interface SyncBody {
461500 memMiB?: unknown;
462501 }[];
463502 readonly logs?: Record<string, unknown>;
503 /** The batch those lines are: sent again, under the same id, until a sync is answered. */
504 readonly logsId?: unknown;
464505 /** Per service, the raw RCON answers the agent read (`list`, `tps`, `mspt`): `games/metrics.ts` parses them. */
465506 readonly metrics?: Record<string, unknown>;
466507 /** Each server's whitelist, ops and bans, and the proxy's glist (`people.ts`). */
@@ -485,16 +526,27 @@ const str = (v: unknown, max = 200): string => (typeof v === "string" ? v.slice(
485526 const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : 0);
486527
487528 /** The command results a box sent, each kept once. */
488 function recordResults(db: Database, boxId: string, results: SyncBody["results"], at: string): void {
529 function recordResults(db: Database, boxId: string, results: SyncBody["results"], at: string, kinds: readonly string[] = COMMAND_KINDS): void {
489530 for (const r of (results ?? []).slice(0, 64)) {
490531 const id = str(r.id, 64);
491532 const asked = db.query<{ kind: string; service: string; text: string }, [string, string]>("SELECT kind, service, text FROM game_command WHERE id = ?1 AND box_id = ?2 AND done_at = ''").get(id, boxId);
492 if (asked === null) continue;
533 if (asked === null || !kinds.includes(asked.kind)) continue;
493534 const { ok, output } = outcomeOf(db, boxId, asked, { ok: r.ok === true, output: str(r.output, OUTPUT_MAX) });
494535 db.query("UPDATE game_command SET done_at = ?2, ok = ?3, output = ?4 WHERE id = ?1").run(id, at, ok ? 1 : 0, output);
495536 }
496537 }
497538
539 /**
540 * The body without its log lines when this box's last batch was the same one: the sync that carried it
541 * was stored and its answer lost. Called with no wait before `recordSync`, which notes the batch as it
542 * stores the lines, so two syncs of one batch cannot both be the first.
543 */
544 export function freshLogs(db: Database, boxId: string, body: SyncBody): SyncBody {
545 const id = str(body.logsId, 64);
546 if (id === "") return body;
547 return db.query("SELECT 1 FROM game_log_batch WHERE box_id = ?1 AND id = ?2").get(boxId, id) === null ? body : { ...body, logs: {} };
548 }
549
498550 /** One sync: store what the box says, hand out what is queued (once), say what to run. */
499551 export function recordSync(
500552 db: Database,
@@ -537,15 +589,24 @@ export function recordSync(
537589 "DELETE FROM game_log WHERE box_id = ?1 AND service = ?2 AND id <= (SELECT id FROM game_log WHERE box_id = ?1 AND service = ?2 ORDER BY id DESC LIMIT 1 OFFSET ?3)",
538590 ).run(box.id, service, LOG_KEEP);
539591 }
592 if (str(body.logsId, 64) !== "") db.query("INSERT OR REPLACE INTO game_log_batch (box_id, id) VALUES (?1, ?2)").run(box.id, str(body.logsId, 64));
540593 recordResults(db, box.id, body.results, at);
541594 })();
542 // Handed out once: a command leaves the queue the moment it is in a reply.
595 return handOut(db, box.id, at);
596 }
597
598 type Handed = { id: string; kind: string; service: string; text: string };
599 /** The commands the agent answers at once, beside its sync; every other kind is the sync's. */
600 const QUICK: readonly CommandKind[] = ["rcon", "people", "tell"];
601 const isQuick = (kind: CommandKind): boolean => QUICK.includes(kind);
602
603 /** The commands queued for a box, handed out once: each leaves the queue the moment it is in a reply. */
604 function handOut(db: Database, boxId: string, at: string, kinds: readonly CommandKind[] = COMMAND_KINDS): Handed[] {
543605 const due = db
544 .query<
545 { id: string; kind: string; service: string; text: string },
546 [string]
547 >("SELECT id, kind, service, text FROM game_command WHERE box_id = ?1 AND handed_at = '' ORDER BY created_at LIMIT 32")
548 .all(box.id);
606 .query<Handed, [string, string]>(
607 "SELECT id, kind, service, text FROM game_command WHERE box_id = ?1 AND handed_at = '' AND kind IN (SELECT value FROM json_each(?2)) ORDER BY created_at LIMIT 32",
608 )
609 .all(boxId, JSON.stringify(kinds));
549610 for (const c of due) db.query("UPDATE game_command SET handed_at = ?2 WHERE id = ?1").run(c.id, at);
550611 // A world import's link is a secret (a signed URL): it goes to the box once, in this reply, and
551612 // what stays is its host and path (`worlds.ts`).
@@ -553,3 +614,8 @@ export function recordSync(
553614 // The box runs a `tell` as the rcon command it is.
554615 return due.map((c) => (c.kind === "tell" ? { ...c, kind: "rcon" } : c));
555616 }
617
618 /** What the agent's poll brought and takes: the quick commands' results in, the quick commands queued out. */
619 export const keepQuickResults = (db: Database, boxId: string, results: SyncBody["results"], now = new Date()): void =>
620 db.transaction(() => recordResults(db, boxId, results, now.toISOString(), QUICK))();
621 export const quickCommands = (db: Database, boxId: string, now = new Date()): Handed[] => handOut(db, boxId, now.toISOString(), QUICK);
src/games/wake.ts added +37
@@ -0,0 +1,37 @@
1 /**
2 * The game boxes' waiting agents: each agent holds one request open (`POST
3 * /api/v1/games/agent/commands`), and a queued command wakes it at once, so a command's answer does
4 * not wait for two full syncs. A box has one waiter: a newer poll ends the one before it, so a box
5 * costs at most one held request. Gone with the process, and nothing is lost with it: the queue is rows.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { during } from "../perf/jobs.ts";
10
11 /** Why a wait ended: a command the poll can carry, one that is the full sync's, or neither. */
12 export type Woken = "command" | "sync" | "over";
13
14 const waiting = new WeakMap<Database, Map<string, (why: Woken) => void>>();
15
16 /** Wait until a command is queued for `boxId`, `ms` pass, a newer poll comes or `signal` aborts. */
17 export function nextCommand(db: Database, boxId: string, ms: number, signal: AbortSignal): Promise<Woken> {
18 if (ms <= 0 || signal.aborted) return Promise.resolve("over");
19 const boxes = waiting.get(db) ?? new Map<string, (why: Woken) => void>();
20 waiting.set(db, boxes);
21 boxes.get(boxId)?.("over");
22 return new Promise((resolve) => {
23 const done = (why: Woken): void => {
24 clearTimeout(timer);
25 if (boxes.get(boxId) === done) boxes.delete(boxId);
26 signal.removeEventListener("abort", over);
27 resolve(why);
28 };
29 const over = (): void => done("over");
30 const timer = setTimeout(() => during("game-wait", over), ms);
31 boxes.set(boxId, done);
32 signal.addEventListener("abort", over, { once: true });
33 });
34 }
35
36 /** A command was queued for `boxId`: its waiting agent hears it now. */
37 export const wakeBox = (db: Database, boxId: string, why: Woken): void => waiting.get(db)?.get(boxId)?.(why);
src/http/games_routes.ts +40 −2
@@ -13,7 +13,9 @@ import { gameChat, runChat } from "../games/chat.ts";
1313 import { packChecks } from "../games/pack_check.ts";
1414 import { lendAnswer } from "../games/lend.ts";
1515 import { sleeping } from "../games/sleep.ts";
16 import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, type SyncBody } from "../games/store.ts";
16 import { boxByToken, envFiles, freshLogs, keepQuickResults, markAsleep, quickCommands, recordSync, signJarUrls, type SyncBody } from "../games/store.ts";
17 import { nextCommand } from "../games/wake.ts";
18 import { inFlight } from "../perf/live.ts";
1719 import { BODY_CAPS } from "../kernel/body_caps.ts";
1820 import {
1921 gameBoxPage, gameCommandSubmit, gameCrashShare, gameEnvSubmit, gameGrantSubmit, gameLendSubmit, gameServersSubmit, gameJarDownload, gameJarSubmit, gameModInstall, gameModPack, gameModRemove, gameModUpdate, gamePeopleSubmit, gameHead, gameWorldSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage,
@@ -39,7 +41,7 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
3941 throw e;
4042 }
4143 if (sent === "too_large") return apiError("too_large", 413, "a sync is at most 200 log lines a service");
42 const body = sent as SyncBody;
44 const body = freshLogs(ctx.app.db, box.id, sent as SyncBody);
4345 const commands = recordSync(ctx.app.db, box, body);
4446 // Every shell command the box answered, its output with it, into the audit.
4547 auditShellResults(ctx.app, box, (body.results ?? []).map((r) => r.id));
@@ -69,6 +71,41 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
6971 return json(reply);
7072 }
7173
74 /** How long a poll is held, at most: under the tunnel's and the agent's own limits. */
75 const WAIT_MAX_S = 25;
76
77 /**
78 * POST /api/v1/games/agent/commands: the agent's poll beside its sync. The results of the commands it
79 * ran come in and are kept at once; it is held until one is queued (`games/wake.ts`), `wait` seconds
80 * pass or this forge closes. `sync: true` asks for a full sync now: what was queued is the sync's.
81 */
82 export async function gameAgentCommands(ctx: Ctx): Promise<Response> {
83 const auth = ctx.request.headers.get("authorization") ?? "";
84 const token = auth.startsWith("Bearer ") ? auth.slice(7).trim() : "";
85 const refused = (): Response => apiError("unauthorized", 401, "send the game box's token as the bearer");
86 const box = boxByToken(ctx.app.db, token);
87 if (box === undefined) return refused();
88 const body = await boundedMachineBody(ctx.request, BODY_CAPS.gameSync.bytes, (why) => ctx.app.log.warn(`game box ${box.name}: a poll that is not JSON`, { why }));
89 if (body === "too_large") return apiError("too_large", 413, "at most 64 results");
90 const { results, wait } = body as { results?: SyncBody["results"]; wait?: unknown };
91 if (Array.isArray(results) && results.length > 0) {
92 keepQuickResults(ctx.app.db, box.id, results);
93 synced(ctx.app, box.id);
94 }
95 const until = Date.now() + Math.min(Math.max(Number(wait) || 0, 0), WAIT_MAX_S) * 1_000;
96 const stop = AbortSignal.any([ctx.request.signal, ctx.app.closing.signal]);
97 for (;;) {
98 // Its token may have been changed, or its machine retired, while it waited.
99 if (boxByToken(ctx.app.db, token)?.id !== box.id) return refused();
100 // Nobody is there to take a command on an ended request: it stays queued.
101 const commands = stop.aborted ? [] : quickCommands(ctx.app.db, box.id);
102 if (commands.length > 0 || stop.aborted) return json({ commands });
103 const woken = await inFlight.rest(ctx.request, () => nextCommand(ctx.app.db, box.id, until - Date.now(), stop));
104 if (woken === "sync") return json({ commands: [], sync: true });
105 if (woken === "over") return json({ commands: [] });
106 }
107 }
108
72109 // GET /api/v1/games/agent/script: the agent this forge runs, for a box that holds an older one.
73110 // The box's bearer token, as the sync; the box checks the sha the sync answered before running it.
74111 export function gameAgentScript(ctx: Ctx): Response {
@@ -80,6 +117,7 @@ export function gameAgentScript(ctx: Ctx): Response {
80117
81118 export function gamesApiRoutes(router: Router<Handler>): void {
82119 router.add("POST", "/api/v1/games/agent/sync", gameAgentSync);
120 router.add("POST", "/api/v1/games/agent/commands", gameAgentCommands);
83121 router.add("GET", "/api/v1/games/agent/script", gameAgentScript);
84122 }
85123
src/http/lazy_lists.ts +1
@@ -1279,6 +1279,7 @@ export const API_ROUTES = [
12791279 ["GET", "/api/v1/runner/jobs/:id/git/info/refs"],
12801280 ["POST", "/api/v1/runner/jobs/:id/git/git-upload-pack"],
12811281 ["POST", "/api/v1/games/agent/sync"],
1282 ["POST", "/api/v1/games/agent/commands"],
12821283 ["GET", "/api/v1/games/agent/script"],
12831284 ["GET", "/api/v1/admin/maintenance"],
12841285 ["POST", "/api/v1/admin/maintenance/prepare"],
src/tui/screens/games.ts +2 −1
@@ -27,6 +27,7 @@ import { getUserByName } from "../../core/users.ts";
2727 import { commitServiceEnv, readCompose, serviceEnv } from "../../games/compose.ts";
2828 import { commitSettings, planSettings, settingsOf, type SettingsPlan, type SettingValue } from "../../games/settings.ts";
2929 import {
30 commandSays,
3031 SERVICE_NAME,
3132 boxNamed,
3233 bootTroubled,
@@ -265,7 +266,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
265266 const lines = (): string[] => {
266267 if (part === "console") {
267268 // A world command's link shows as host and path only: its query string may be a signed secret.
268 const done = recentCommands(f.app.db, box.id, service, 5).map((c) => `> ${c.kind === "world" ? worldWords(c.text) : c.text} ${c.done ? (c.ok ? "ok" : "failed") : "waiting for the box"}${c.output === "" ? "" : `: ${c.output.split("\n")[0]}`}`);
269 const done = recentCommands(f.app.db, box.id, service, 5).map((c) => `> ${c.kind === "world" ? worldWords(c.text) : c.text} ${commandSays(c).split("\n")[0]}`);
269270 // The game's colour codes read as plain text here; a crash leads, in one line.
270271 const crash = crashOf(logsOf(f.app.db, box.id, service, 2_000).lines);
271272 return [...(crash === undefined ? [] : [crash.summary]), ...consoleText(logsOf(f.app.db, box.id, service, 200).lines), ...done];
src/web/pages/games.ts +10 −17
@@ -18,10 +18,11 @@ import { spareRow } from "../../games/spare_row.ts";
1818 import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts";
1919 import { commitSettings, planSettings, previewSettings, settingsOf, SETTINGS, type SettingValue, type SettingsPlan } from "../../games/settings.ts";
2020 import {
21 answersOf,
22 commandSays,
2123 bootWords,
2224 boxNamed,
2325 COMMAND_KINDS,
24 commandOf,
2526 grant,
2627 grantsOf,
2728 jarHref,
@@ -333,14 +334,12 @@ export function gameShellStream(ctx: Ctx): Response {
333334 const got = boxOf(ctx, "owner");
334335 if (got instanceof Response) return got;
335336 const { box } = got;
336 const pending = new Set(recentCommands(ctx.app.db, box.id, SHELL_SERVICE, 10).filter((c) => !c.done).map((c) => c.id));
337 const answers = answersOf(ctx.app.db, box.id, SHELL_SERVICE);
337338 return eventStream(ctx.app, ctx.request, (emit, _close, ready) =>
338339 onSync(ctx.app, box.id, () => {
339340 if (!ready()) return;
340 for (const c of recentCommands(ctx.app.db, box.id, SHELL_SERVICE, 10)) if (!c.done) pending.add(c.id);
341 const results = [...pending].map((id) => commandOf(ctx.app.db, id)).filter((c) => c !== undefined && c.done);
342 for (const r of results) pending.delete(r!.id);
343 if (results.length > 0) emit("lines", { lines: [], results: results.map((r) => ({ id: r!.id, ok: r!.ok, output: `$ ${r!.text}\n${r!.output}` })) });
341 const results = answers();
342 if (results.length > 0) emit("lines", { lines: [], results: results.map((r) => ({ id: r.id, ok: r.ok, output: `$ ${r.text}\n${r.output}`, says: commandSays(r) })) });
344343 }),
345344 );
346345 }
@@ -467,7 +466,7 @@ export const gamesConsoleJs = /* js */ `
467466 if (stick) log.scrollTop = log.scrollHeight;
468467 (d.results || []).forEach(function (r) {
469468 var el = document.getElementById('cmd-' + r.id);
470 if (el) el.textContent = (r.ok ? 'ok: ' : 'failed: ') + r.output;
469 if (el) el.textContent = r.says;
471470 });
472471 });
473472 // The command box walks its history with up and down, as a terminal does.
@@ -585,7 +584,7 @@ ${rawView ? tail.lines.join("\n") : raw(consoleHtml(tail.lines).join("\n"))}${ta
585584 row({
586585 title: c.kind === "world" ? worldWords(c.text) : html`<span class="mono">${c.kind} ${c.text}</span>`,
587586 meta: html`<span id="cmd-${c.id}"
588 >${c.done ? `${c.ok ? "ok" : "failed"}: ${c.output}` : c.handed ? "sent to the box" : "queued"}</span
587 >${commandSays(c)}</span
589588 >`,
590589 }),
591590 ),
@@ -888,21 +887,15 @@ export function gameServiceStream(ctx: Ctx): Response {
888887 if (got instanceof Response) return got;
889888 const { box } = got;
890889 let after = Number(ctx.url.searchParams.get("after") ?? "0") || 0;
891 const pending = new Set(
892 recentCommands(ctx.app.db, box.id, service, 10)
893 .filter((c) => !c.done)
894 .map((c) => c.id),
895 );
890 const answers = answersOf(ctx.app.db, box.id, service);
896891 return eventStream(ctx.app, ctx.request, (emit, _close, ready) =>
897892 onSync(ctx.app, box.id, () => {
898893 if (!ready()) return;
899894 const got = logsOf(ctx.app.db, box.id, service, 500, after);
900895 after = got.last;
901 for (const c of recentCommands(ctx.app.db, box.id, service, 10)) if (!c.done) pending.add(c.id);
902 const results = [...pending].map((id) => commandOf(ctx.app.db, id)).filter((c) => c !== undefined && c.done);
903 for (const r of results) pending.delete(r!.id);
896 const results = answers();
904897 if (got.lines.length > 0 || results.length > 0)
905 emit("lines", { html: consoleHtml(got.lines), lines: got.lines, results: results.map((r) => ({ id: r!.id, ok: r!.ok, output: r!.output })) });
898 emit("lines", { html: consoleHtml(got.lines), lines: got.lines, results: results.map((r) => ({ id: r.id, ok: r.ok, output: r.output, says: commandSays(r) })) });
906899 }),
907900 );
908901 }
test/game-agent-exec.test.ts +2
@@ -49,6 +49,8 @@ esac
4949 port: 0,
5050 hostname: "127.0.0.1",
5151 async fetch(req) {
52 // The agent's poll for commands (test/game-fast.test.ts): this forge has none.
53 if (!req.url.endsWith("/sync")) return new Response("", { status: 404 });
5254 bodies.push((await req.json()) as (typeof bodies)[number]);
5355 heard();
5456 return Response.json({ composeSha: "", commands: commands.splice(0) });
test/game-diag.test.ts +2
@@ -90,6 +90,8 @@ function scratch(docker: string, answer: Record<string, unknown> = { composeSha:
9090 port: 0,
9191 hostname: "127.0.0.1",
9292 async fetch(req) {
93 // The agent's poll for commands: this forge has none.
94 if (!req.url.endsWith("/sync")) return new Response("", { status: 404 });
9395 bodies.push((await req.json()) as Record<string, any>);
9496 return Response.json(answer);
9597 },
test/game-fast.test.ts added +276
@@ -0,0 +1,276 @@
1 /**
2 * A console or player command is answered in seconds, not two full syncs later (2026-12-02: about 20 s
3 * for an `op`). The agent holds one poll open beside its sync, the forge answers it the moment a command
4 * is queued, and the result goes back with the next poll. What the poll does not carry (a restart, a
5 * world) asks for a sync at once and stays queued for it. A closing forge lets a held poll go.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { chmodSync, mkdtempSync, 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 { onSync } from "../src/games/notify.ts";
14 import { peopleOf } from "../src/games/people.ts";
15 import { answersOf, boxNamed, commandOf, commandSays, createGameBox, NO_ANSWER, queueCommand, type CommandKind, type GameBox } from "../src/games/store.ts";
16 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20
21 const AGENT = join(import.meta.dir, "../src/games/agent.sh");
22 const lacks = ["bash", "curl", "jq", "mkfifo"].filter((t) => Bun.which(t) === null);
23 let dir = "";
24 let app: App;
25 let http: ForgeHttp;
26 let box: GameBox;
27 let token = "";
28 beforeAll(() => {
29 dir = mkdtempSync(join(tmpdir(), "forge-game-fast-"));
30 app = createApp({ dataDir: dir, port: 0 });
31 http = forgeHttp(app);
32 token = createGameBox(app.db, { name: "mc" }).token;
33 box = boxNamed(app.db, "mc")!;
34 });
35 afterAll(async () => {
36 app.close();
37 await rm(dir, { recursive: true, force: true });
38 });
39 const poll = async (body: unknown, bearer = token) => {
40 const res = await http.handle(
41 new Request("http://forge.test/api/v1/games/agent/commands", {
42 method: "POST",
43 headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json" },
44 body: JSON.stringify(body),
45 }),
46 );
47 return { status: res.status, body: (await res.json()) as { commands?: { id: string; kind: string }[]; sync?: boolean } };
48 };
49 const queue = (kind: CommandKind, text: string): string => queueCommand(app.db, box.id, "hub", kind, text, "");
50 /** A poll held by the forge: until the box is waiting, what is queued would be handed at once. */
51 async function held(): Promise<{ answer: ReturnType<typeof poll> }> {
52 const answer = poll({ results: [], wait: 25 });
53 for (let i = 0; i < 20; i++) await Promise.resolve();
54 await new Promise((r) => setImmediate(r));
55 return { answer };
56 }
57
58 test("a held poll is answered by the command queued, its result kept with the next one", async () => {
59 const { answer } = await held();
60 const id = queue("rcon", "say hi");
61 expect((await answer).body.commands).toMatchObject([{ id, kind: "rcon" }]);
62 await poll({ results: [{ id, ok: true, output: "hi" }], wait: 0 });
63 expect(commandOf(app.db, id)).toMatchObject({ done: true, ok: true, output: "hi" });
64 });
65
66 test("a restart asks for a sync and stays queued for it; the poll takes no result of its kind", async () => {
67 const { answer } = await held();
68 const id = queue("restart", "");
69 expect((await answer).body).toEqual({ commands: [], sync: true });
70 expect(commandOf(app.db, id)!.handed).toBe(false);
71 await poll({ results: [{ id, ok: true, output: "no" }], wait: 0 });
72 expect(commandOf(app.db, id)!.done).toBe(false);
73 });
74
75 test("a newer poll of the box ends the one before it, and a token that is not a box's is refused", async () => {
76 const { answer } = await held();
77 const second = await held();
78 expect((await answer).body).toEqual({ commands: [] });
79 const id = queue("tell", "tellraw Alice {}");
80 expect((await second.answer).body.commands).toMatchObject([{ id, kind: "rcon" }]);
81 expect((await poll({ wait: 25 }, "fgb_wrong")).status).toBe(401);
82 });
83
84 test("a command whose answer never comes says so on every door, is not sent again, and a late answer replaces it", async () => {
85 const answers = answersOf(app.db, box.id, "hub");
86 const id = queue("rcon", "say once");
87 expect(commandSays(commandOf(app.db, id)!)).toBe("queued");
88 expect((await poll({ wait: 0 })).body.commands).toMatchObject([{ id }]);
89 expect(commandSays(commandOf(app.db, id)!)).toBe("sent to the box");
90 expect(answers()).toEqual([]);
91 // Two minutes on, nothing has come back.
92 app.db.query("UPDATE game_command SET handed_at = ?2 WHERE id = ?1").run(id, new Date(Date.now() - 121_000).toISOString());
93 expect(commandOf(app.db, id)).toMatchObject({ done: true, ok: null });
94 expect(commandSays(commandOf(app.db, id)!)).toBe(NO_ANSWER);
95 expect(answers().map(commandSays)).toEqual([NO_ANSWER]);
96 expect(answers()).toEqual([]);
97 expect((await poll({ wait: 0 })).body.commands).toEqual([]);
98 await poll({ results: [{ id, ok: true, output: "said" }], wait: 0 });
99 expect(answers().map(commandSays)).toEqual(["ok: said"]);
100 // A restart may take long: it is still waited for.
101 const restart = queue("restart", "");
102 app.db.query("UPDATE game_command SET handed_at = ?2 WHERE id = ?1").run(restart, new Date(Date.now() - 600_000).toISOString());
103 expect(commandSays(commandOf(app.db, restart)!)).toBe("sent to the box");
104 });
105
106 test("a held poll whose connection is cut takes nothing: the command stays queued for the next poll", async () => {
107 const taken: Promise<Response>[] = [];
108 const asked = Promise.withResolvers<void>();
109 const forge = Bun.serve({
110 port: 0,
111 hostname: "127.0.0.1",
112 fetch(req) {
113 const answer = http.handle(req);
114 taken.push(answer);
115 asked.resolve();
116 return answer;
117 },
118 });
119 const cut = new AbortController();
120 const asking = fetch(`http://127.0.0.1:${String(forge.port)}/api/v1/games/agent/commands`, {
121 method: "POST",
122 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
123 body: JSON.stringify({ wait: 25 }),
124 signal: cut.signal,
125 });
126 try {
127 await asked.promise;
128 cut.abort();
129 await expect(asking).rejects.toThrow();
130 // The forge noticed and let the request go, long before its 25 s.
131 await taken[0];
132 const id = queue("rcon", "say after");
133 expect(commandOf(app.db, id)!.handed).toBe(false);
134 expect((await poll({ wait: 0 })).body.commands).toMatchObject([{ id }]);
135 } finally {
136 forge.stop(true);
137 }
138 });
139
140 test("an agent from before the poll gets its commands with the sync, as ever", async () => {
141 const id = queue("rcon", "say old");
142 const sync = async (body: unknown) =>
143 (await (
144 await 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) }))
145 ).json()) as { commands: { id: string }[] };
146 expect((await sync({ logs: { hub: ["x"] } })).commands.map((c) => c.id)).toContain(id);
147 await sync({ results: [{ id, ok: true, output: "old" }] });
148 expect(commandSays(commandOf(app.db, id)!)).toBe("ok: old");
149 });
150
151 test.skipIf(lacks.length > 0)("the agent answers a command while its sync rests, and an op brings the lists at once", async () => {
152 const root = mkdtempSync(join(tmpdir(), "forge-game-fast-box-"));
153 writeFileSync(
154 join(root, "docker"),
155 `#!/usr/bin/env bash
156 case "$*" in
157 *" ps -a --format json") echo '{"Service":"hub","Name":"hub","State":"running"}' ;;
158 *" ps --status running "*) echo hub ;;
159 *" rcon-cli -- say hi") echo said ;;
160 *" rcon-cli -- op Alice") echo 'Made Alice a server operator'; : >"${root}/op" ;;
161 *" hub sh -c for f in whitelist.json"*) echo '=== whitelist.json'; echo '[]'; echo '=== ops.json'; [ -f "${root}/op" ] && echo '[{"name":"Alice","uuid":"","level":4}]'; echo '=== props' ;;
162 esac
163 `,
164 );
165 chmodSync(join(root, "docker"), 0o755);
166 let syncs = 0;
167 const forge = Bun.serve({
168 port: 0,
169 hostname: "127.0.0.1",
170 idleTimeout: 60,
171 async fetch(req) {
172 const full = req.url.endsWith("/sync");
173 const answer = await http.handle(req);
174 if (!full) return answer;
175 syncs += 1;
176 return Response.json({ ...((await answer.json()) as object), agentSha: "" });
177 },
178 });
179 const until = (done: () => boolean): Promise<void> =>
180 new Promise((resolve) => {
181 const look = (): void => {
182 if (!done()) return;
183 stop();
184 resolve();
185 };
186 const stop = onSync(app, box.id, look);
187 look();
188 });
189 // A minute between syncs: only the poll can answer within this test's time.
190 const agent = Bun.spawn(["bash", AGENT], {
191 env: {
192 PATH: process.env["PATH"] ?? "",
193 FORGE_URL: `http://127.0.0.1:${String(forge.port)}`,
194 FORGE_GAME_TOKEN: token,
195 FORGE_GAME_DIR: root,
196 FORGE_GAME_DOCKER: join(root, "docker"),
197 FORGE_GAME_EVERY: "60",
198 FORGE_GAME_DIAG_S: "0",
199 FORGE_GAME_VOLUME_CHECK: "0",
200 },
201 stdout: "ignore",
202 stderr: "ignore",
203 });
204 try {
205 await until(() => syncs > 0 || boxNamed(app.db, "mc")!.seenAt !== "");
206 const said = queue("rcon", "say hi");
207 await until(() => commandOf(app.db, said)!.done);
208 expect(commandOf(app.db, said)).toMatchObject({ ok: true, output: "said" });
209 queue("people", JSON.stringify({ op: "op", player: "Alice" }));
210 await until(() => peopleOf(app.db, box.id, "hub").lists.ops.length > 0);
211 expect(peopleOf(app.db, box.id, "hub").lists.ops.map((o) => o.name)).toEqual(["Alice"]);
212 } finally {
213 agent.kill();
214 await agent.exited;
215 forge.stop(true);
216 await rm(root, { recursive: true, force: true });
217 }
218 }, 45_000);
219
220 test.skipIf(lacks.length > 0)("a forge still starting is tried again after 1 or 2 s, and one that hangs is let go and asked longer", async () => {
221 const root = mkdtempSync(join(tmpdir(), "forge-game-back-"));
222 let syncs = 0;
223 let back = (): void => {};
224 const returned = new Promise<void>((resolve) => (back = resolve));
225 // As a release does it: the first sync hangs, the next two meet a 502, then the forge is there.
226 const forge = Bun.serve({
227 port: 0,
228 hostname: "127.0.0.1",
229 async fetch(req) {
230 if (!req.url.endsWith("/sync")) return new Response("", { status: 502 });
231 syncs += 1;
232 if (syncs === 1) return new Promise<Response>(() => {});
233 if (syncs <= 3) return new Response("", { status: 502 });
234 if (syncs === 5) back();
235 return Response.json({ composeSha: "", commands: [] });
236 },
237 });
238 const agent = Bun.spawn(["bash", AGENT], {
239 env: {
240 PATH: process.env["PATH"] ?? "",
241 FORGE_URL: `http://127.0.0.1:${String(forge.port)}`,
242 FORGE_GAME_TOKEN: token,
243 FORGE_GAME_DIR: root,
244 FORGE_GAME_DOCKER: "true",
245 FORGE_GAME_EVERY: "0",
246 FORGE_GAME_SYNC_S: "1",
247 FORGE_GAME_DIAG_S: "0",
248 FORGE_GAME_VOLUME_CHECK: "0",
249 },
250 stdout: "ignore",
251 stderr: "pipe",
252 });
253 try {
254 await returned;
255 agent.kill();
256 const said = (await new Response(agent.stderr).text()).split("\n").filter((l) => l !== "");
257 expect(said[0]).toMatch(/^curl: \(28\) Operation timed out after 1\d{3} /);
258 const waits = said.filter((l) => l.includes("sync failed"));
259 expect(waits.length).toBe(3);
260 for (const line of waits) expect(line).toMatch(/again in [12]s$/);
261 } finally {
262 agent.kill();
263 await agent.exited;
264 forge.stop(true);
265 await rm(root, { recursive: true, force: true });
266 }
267 }, 45_000);
268
269 test("a closing forge lets a held poll go, with nothing handed out", async () => {
270 const { answer } = await held();
271 app.closing.abort();
272 expect((await answer).body).toEqual({ commands: [] });
273 const id = queue("rcon", "say late");
274 expect((await poll({ wait: 25 })).body).toEqual({ commands: [] });
275 expect(commandOf(app.db, id)!.handed).toBe(false);
276 });
test/game-log-once.test.ts added +115
@@ -0,0 +1,115 @@
1 /**
2 * Each log line of a game box is kept once (2026-12-02: after a sync that timed out, lines appeared
3 * twice on the console). The forge stored that sync and its answer was lost, so the agent sent the
4 * lines again; and two reads whose seconds overlap gave the same line twice. The agent sends a batch
5 * under its id until it is answered, starts after the last line read, and the forge skips a batch it has.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { chmodSync, mkdtempSync, 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 { boxNamed, createGameBox, logsOf } from "../src/games/store.ts";
14 import { eventsOf } from "../src/games/people.ts";
15 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 const AGENT = join(import.meta.dir, "../src/games/agent.sh");
21 const lacks = ["bash", "curl", "jq"].filter((t) => Bun.which(t) === null);
22 let dir = "";
23 let app: App;
24 let http: ForgeHttp;
25 let token = "";
26 beforeAll(() => {
27 dir = mkdtempSync(join(tmpdir(), "forge-game-once-"));
28 app = createApp({ dataDir: dir, port: 0 });
29 http = forgeHttp(app);
30 token = createGameBox(app.db, { name: "mc" }).token;
31 });
32 afterAll(async () => {
33 app.close();
34 await rm(dir, { recursive: true, force: true });
35 });
36 const sync = (body: string) =>
37 http.handle(new Request("http://forge.test/api/v1/games/agent/sync", { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body }));
38 const kept = () => logsOf(app.db, boxNamed(app.db, "mc")!.id, "hub").lines;
39
40 test("a batch sent again under its id is stored once, its joins too; one without an id is stored as before", async () => {
41 const batch = JSON.stringify({ services: [{ name: "lobby", state: "running" }], logsId: "a1", logs: { lobby: ["[12:00:01 INFO]: Alice joined the game"] } });
42 const id = boxNamed(app.db, "mc")!.id;
43 await sync(batch);
44 await sync(batch);
45 expect(logsOf(app.db, id, "lobby").lines).toEqual(["[12:00:01 INFO]: Alice joined the game"]);
46 expect(eventsOf(app.db, id, "lobby").length).toBe(1);
47 const old = JSON.stringify({ logs: { lobby: ["x"] } });
48 await sync(old);
49 await sync(old);
50 expect(logsOf(app.db, id, "lobby").lines.slice(1)).toEqual(["x", "x"]);
51 });
52
53 test.skipIf(lacks.length > 0)("a sync whose answer is lost, and reads that overlap, leave each line once and in order", async () => {
54 const box = mkdtempSync(join(tmpdir(), "forge-game-once-box-"));
55 const said: string[] = [];
56 const say = (second: string, text: string): void => {
57 said.push(`hub | 2026-12-02T19:00:${second}Z ${text}`);
58 writeFileSync(join(box, "log"), `${said.join("\n")}\n`);
59 };
60 // Every read gives the whole log, as reads within one second do.
61 writeFileSync(join(box, "docker"), `#!/usr/bin/env bash\ncase "$*" in *" logs --no-color --since "*) cat "${box}/log" ;; esac\n`);
62 chmodSync(join(box, "docker"), 0o755);
63 let lose = true;
64 let refuse = false;
65 const forge = Bun.serve({
66 port: 0,
67 hostname: "127.0.0.1",
68 async fetch(req) {
69 const body = await req.text();
70 if (refuse) return new Response("too large", { status: 413 });
71 const answer = await sync(body);
72 if (lose) return new Response("the tunnel is down", { status: 502 });
73 return Response.json({ ...((await answer.json()) as object), agentSha: "" });
74 },
75 });
76 const run = async (): Promise<void> => {
77 const p = Bun.spawn(["bash", AGENT], {
78 env: {
79 PATH: process.env["PATH"] ?? "",
80 FORGE_URL: `http://127.0.0.1:${String(forge.port)}`,
81 FORGE_GAME_TOKEN: token,
82 FORGE_GAME_DIR: box,
83 FORGE_GAME_DOCKER: join(box, "docker"),
84 FORGE_GAME_ONCE: "1",
85 FORGE_GAME_DIAG_S: "0",
86 FORGE_GAME_VOLUME_CHECK: "0",
87 },
88 stdout: "ignore",
89 stderr: "ignore",
90 });
91 await p.exited;
92 };
93 try {
94 say("01.100000000", "one");
95 say("01.200000000", "two");
96 await run();
97 say("01.200000001", "three");
98 lose = false;
99 await run();
100 await run();
101 await run();
102 expect(kept()).toEqual(["one", "two", "three"]);
103 // A batch the forge refuses as it is does not hold the box's syncs for ever.
104 say("02.000000000", "refused");
105 refuse = true;
106 await run();
107 refuse = false;
108 say("03.000000000", "four");
109 await run();
110 expect(kept()).toEqual(["one", "two", "three", "four"]);
111 } finally {
112 forge.stop(true);
113 await rm(box, { recursive: true, force: true });
114 }
115 }, 60_000);

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

Keyboard shortcuts

Docs