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

/forge answers in about a second: a request rides the next quick poll, not the next full sync #18016

opened this

Merged 13h 46m ago, live in production

sold/forge-fast → main 0 commits

  • Merged. sold/forge-fast was merged into main as b9491db.

Review

Sign in to review this change.
6 files changed +208 −19
docs/features/game-box.md +1 −1
@@ -33,7 +33,7 @@ experiment.
3333 - **`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`.
3434 - **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: …".
3535 - **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 - **`/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.
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 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: `id`, `uuid`, `text`, `confirm`, and `lines` when it is a list) 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. One shell stays in the proxy and says when the outbox changed (it looks twice a second, and ends with the agent, the proxy or after an hour, or when the agent was silent for 60 s; as it starts, it puts the origin of `FORGE_URL` in `plugins/forge/origin`, one line, https only, none when it has a path): the next quick poll then carries `ask` and is answered with `asked`, under the same rules. With an older forge, or no such shell, the full sync carries them. Quick polls go on between the parts of a full sync, so a long one holds a request back for one part, not for all. 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.
3737 - **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.
3838 - **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.
3939
src/contract/openapi/routes/postApiV1GamesAgentSync.ts +1 −1
@@ -4,7 +4,7 @@ export const route: Route = {
44 method: "post",
55 path: "/api/v1/games/agent/sync",
66 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? (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",
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; a quick poll (`light: true`) sends results and `ask?` and is answered `{ commands, asked?, told? }`; agentSha is the sha256 of the agent this forge runs, which a box whose own differs fetches from GET /api/v1/games/agent/script",
88 auth: false,
99 role: "anonymous",
1010 refuses: [401],
src/games/agent.sh +71 −14
@@ -1287,15 +1287,49 @@ export WORLDS HELPER
12871287 # (which runs no player's mods), as the proxy's own user: the host never opens a file there. ----
12881288
12891289 # `sh` in the proxy, in one of the plugin's two folders, when neither it nor its parents is a link.
1290 DESK=("${COMPOSE[@]}" exec -T -u bungeecord velocity sh -c)
1291 # shellcheck disable=SC2016 # the script runs in the container's own shell
1292 DESK_CD='for d in plugins plugins/forge "plugins/forge/$0"; do [ -d "$d" ] && [ ! -L "$d" ] || exit 0; done
1293 cd "plugins/forge/$0" || exit 0
1294 '
12901295 desk() {
12911296 local box="$1" script="$2"
12921297 shift 2
1293 capped 5 "${COMPOSE[@]}" exec -T -u bungeecord velocity sh -c 'for d in plugins plugins/forge "plugins/forge/$0"; do [ -d "$d" ] && [ ! -L "$d" ] || exit 0; done
1294 cd "plugins/forge/$0" || exit 0
1295 '"$script" "$box" "$@" 2>/dev/null
1298 capped 5 "${DESK[@]}" "$DESK_CD$script" "$box" "$@" 2>/dev/null
12961299 }
12971300 # Whether the proxy runs, as the last full sync's services say: nothing is asked of one that does not.
12981301 desk_here() { jq -e 'any(.[]; .name == "velocity" and .state == "running")' "$DIR/.sync.services" >/dev/null 2>&1; }
1302 # One long-lived `sh` in the proxy says when the outbox holds other files than at its last look, so the
1303 # next quick poll carries them; only that a line came is used. It looks once for each line it is sent, twice
1304 # a second, and ends when those end: with this agent, with the proxy, or after an hour; also when none came
1305 # for 60 s, where the proxy has a shell whose `read` can say so (bash, busybox; dash says 2). Started again
1306 # then, at most every 10 s. The full sync looks for itself, so nothing depends on it.
1307 # First it puts the forge's origin (https only; none when FORGE_URL has a path or a user) in plugins/forge/origin: the plugin
1308 # makes its links with it. A new proxy ends this shell, so it gets the file too.
1309 ORIGIN=""
1310 [[ "$FORGE_URL" =~ ^https://[A-Za-z0-9.-]+(:[0-9]{1,5})?/?$ ]] && ORIGIN="${FORGE_URL%/}"
1311 desk_watch() {
1312 [ "$ONCE" != 1 ] && desk_here || return 0
1313 [ -z "${DESK_PID:-}" ] || ! kill -0 "$DESK_PID" 2>/dev/null || return 0
1314 [ "$SECONDS" -ge "${DESK_NEXT:-0}" ] || return 0
1315 DESK_NEXT=$((SECONDS + 10))
1316 # shellcheck disable=SC2016
1317 for ((i = 0; i < 7200; i++)); do kill -0 "$$" 2>/dev/null && echo && sleep 0.5 || break; done 2>/dev/null |
1318 "${DESK[@]}" "$DESK_CD"'exec "$(command -v bash || echo sh)" -c "$1" sh "$2"' outbox 'rm -f ../origin.tmp; if [ -z "$1" ]; then rm -f ../origin; else (umask 022; printf "%s\n" "$1" >../origin.tmp && mv -f ../origin.tmp ../origin); fi
1319 was=""; t="-t 60"; read $t _ </dev/null; [ $? != 2 ] || t=""
1320 while read -r $t _; do
1321 set -- *.json; [ -e "$1" ] || set --
1322 [ "$*" = "$was" ] || { was="$*"; [ $# = 0 ] || echo new; }
1323 done' "$ORIGIN" 2>/dev/null | while read -r _; do : >"$DIR/.desk.due"; done &
1324 DESK_PID=$!
1325 }
1326 # What a sync carries. The mark goes first: a file that comes during the look marks again.
1327 desk_take() {
1328 rm -f "$DIR/.desk.due"
1329 desk_asks | json_or '[]' >"$DIR/.sync.ask"
1330 }
1331 # The sync that carried them got no answer: the next quick poll carries them again.
1332 desk_again() { [ "$(cat "$DIR/.sync.ask" 2>/dev/null)" = '[]' ] || : >"$DIR/.desk.due"; }
12991333 # The requests among the oldest 20 files. One the forge could never name (over 2 KiB, no JSON object,
13001334 # or an id that is not the file's own lowercase name) would hold its place for ever: it is dropped.
13011335 # A line without its closing tab was cut short (the 5 s, a read that failed): left for the next sync.
@@ -1342,19 +1376,19 @@ desk_heard() {
13421376 # not written again. The container says the number of each one it wrote; one it did not write comes
13431377 # again. One over 16 KiB never goes in, so it counts as had.
13441378 desk_told() {
1345 local state wrote
1379 local state wrote put='def put: {id, uuid, text, confirm} + (if (.lines | type) == "array" then {lines} else {} end) | tojson; '
13461380 desk_here && jq -e '(.told // []) | length > 0' >/dev/null 2>&1 <<<"$1" || return 0
13471381 state="$(desk_state)"
13481382 # shellcheck disable=SC2016
1349 wrote="$(jq -r --argjson s "$state" '.told[0:20][] | objects | . as $t | select(any($s.had[]; .n == $t.n and .id == $t.id) | not)
1350 | ({id, uuid, text, confirm} | tojson) as $line | select(($line | utf8bytelength) <= 16384) | "\(if (.n | type) == "number" then .n else "-" end)\t\($line)"' <<<"$1" 2>/dev/null |
1383 wrote="$(jq -r --argjson s "$state" "$put"'.told[0:20][] | objects | . as $t | select(any($s.had[]; .n == $t.n and .id == $t.id) | not)
1384 | put as $line | select(($line | utf8bytelength) <= 16384) | "\(if (.n | type) == "number" then .n else "-" end)\t\($line)"' <<<"$1" 2>/dev/null |
13511385 desk inbox 'umask 022; n=0; tab="$(printf "\t")"; while IFS="$tab" read -r num line; do
13521386 [ "$(ls | wc -l)" -lt 64 ] || exit 0
13531387 n=$((n + 1)); printf "%s\n" "$line" > "$1-$n.tmp" && mv "$1-$n.tmp" "$1-$n.json" && printf "%s\n" "$num"
13541388 done' "$(date +%s)-$RANDOM")" || echo "forge-game-agent: an answer to /forge could not be put in the proxy" >&2
1355 jq -c --argjson s "$state" --arg wrote "$wrote" --argjson now "$(date +%s)" '($wrote | split("\n")) as $w
1389 jq -c --argjson s "$state" --arg wrote "$wrote" --argjson now "$(date +%s)" "$put"'($wrote | split("\n")) as $w
13561390 | [.told[0:20][] | objects | select((.n | type) == "number") | . as $t | any($s.had[]; .n == $t.n and .id == $t.id) as $before
1357 | select($before or ($w | index([$t.n | tostring])) != null or ({id, uuid, text, confirm} | tojson | utf8bytelength) > 16384) | {n, id, before: $before}] as $have
1391 | select($before or ($w | index([$t.n | tostring])) != null or (put | utf8bytelength) > 16384) | {n, id, before: $before}] as $have
13581392 | {had: ([$s.had[] | select(.at > $now - 7200)] + [$have[] | select(.before | not) | {n, id, at: $now}]), got: ($s.got + [$have[].n] | unique)}' <<<"$1" >"$TOLD.next" 2>/dev/null &&
13591393 mv "$TOLD.next" "$TOLD"
13601394 return 0
@@ -1365,16 +1399,23 @@ sync() {
13651399 next="$(now)"
13661400 # Each part through a file, checked as JSON on the way: a sync can pass the 128 KB one argument
13671401 # may hold (200 log lines from each of several servers), and then curl would never run.
1402 # These can take 20 s together: the quick poll goes on between them.
13681403 services | json_or '[]' >"$DIR/.sync.services"
1369 desk_asks | json_or '[]' >"$DIR/.sync.ask"
1404 between
13701405 logs "$since" | json_or '{}' >"$DIR/.sync.logs"
1371 json_or '[]' <"$DIR/.results" >"$DIR/.sync.results"
1406 between
13721407 host | json_or '{}' >"$DIR/.sync.host"
13731408 bounded_diag | jq -c --argjson hold "$(held)" --argjson waits "$([ -f "$DIR/.jars.waits" ] && echo true || echo false)" '. + {hold: $hold} + (if $waits then {jarsWait: true} else {} end)' 2>/dev/null | json_or '{}' >"$DIR/.sync.diag"
1409 between
13741410 people | json_or '{}' >"$DIR/.sync.people"
1411 between
13751412 metrics | json_or '{}' >"$DIR/.sync.metrics"
1413 between
13761414 jq -c 'if type == "object" then . else {} end' "$WORLDS/snapshots.json" 2>/dev/null | json_or '{}' >"$DIR/.sync.snapshots"
13771415 chat | json_or '{}' >"$DIR/.sync.chat"
1416 # Last, after every quick poll: what one of those delivered is not sent again.
1417 desk_take
1418 json_or '[]' <"$DIR/.results" >"$DIR/.sync.results"
13781419 # Every string as plain text: real servers print colour escapes and control bytes (itzg's logs,
13791420 # rcon-cli's colours), and the forge takes none of them. Colours go first as Minecraft's own
13801421 # printable section codes (\u00a7: the sixteen colours, l bold, n underline, r every reset), which
@@ -1420,9 +1461,12 @@ sync() {
14201461 # The forge may have kept this body before the answer was lost: the next says so, and it
14211462 # skips the log lines it already holds, so a console never shows a line twice.
14221463 : >"$DIR/.sync.retry"
1464 desk_again
1465 POLLS=0
14231466 return 1
14241467 fi
14251468 token_answered "$answer"
1469 POLLS=1
14261470 desk_heard "$DIR/.sync.body"
14271471 desk_told "$answer"
14281472 desk_asked "$answer"
@@ -1862,7 +1906,8 @@ metadata_close
18621906
18631907 # The quick poll (#17610): between full syncs, only the command results go in and the queued
18641908 # commands come out, so a console command is run in about a second, not at the pace of a full
1865 # sync (which asks every container a few questions and can take 20 s). A command that ran has its
1909 # sync (which asks every container a few questions and can take 20 s). It also carries the requests to
1910 # /forge, as soon as the proxy says there are some. A command that ran has its
18661911 # result sent at once, not at the next poll. The forge handles a `light` body without touching
18671912 # anything else it knows.
18681913 LIGHT_EVERY="${FORGE_GAME_LIGHT_EVERY:-1}"
@@ -1870,18 +1915,30 @@ LIGHT_EVERY="${FORGE_GAME_LIGHT_EVERY:-1}"
18701915 [[ "$LIGHT_EVERY" =~ ^[1-9][0-9]{0,2}$ ]] || LIGHT_EVERY=1
18711916 # How long such a second really is: shorter in tests, which wait for many syncs.
18721917 LIGHT_SLEEP="${FORGE_GAME_LIGHT_SLEEP:-$LIGHT_EVERY}"
1918 # In a full sync, between its parts: at most one a second, once a full sync was answered and while
1919 # each is, and only where quick polls go between full syncs too (EVERY is a second or more).
1920 POLLS=0
1921 between() {
1922 [ "$ONCE" != 1 ] && [ "$EVERY" -ge 1 ] 2>/dev/null && [ "$POLLS" = 1 ] && [ "$SECONDS" != "${POLLED:-}" ] || return 0
1923 light_sync || POLLS=0
1924 return 0
1925 }
18731926 light_sync() {
18741927 local answer round
1928 desk_watch
18751929 for round in 1 2; do
18761930 job_tick
18771931 shell_tick
1932 POLLED="$SECONDS"
1933 if [ -f "$DIR/.desk.due" ] && desk_here; then desk_take; else echo '[]' >"$DIR/.sync.ask"; fi
18781934 json_or '[]' <"$DIR/.results" >"$DIR/.sync.results"
1879 jq -cn --arg sha "$(cat "$DIR/.compose-sha" 2>/dev/null)" --slurpfile results "$DIR/.sync.results" --argjson told "$(desk_here && echo true || echo false)" --argjson got "$(desk_got)" \
1880 '{agent: 1, light: true, composeSha: $sha, results: $results[0], got: $got} + (if $told then {told: true} else {} end)' >"$DIR/.sync.light" || return 1
1881 answer="$(curl -fsS -m 5 -H "@$AUTH" -H 'content-type: application/json' --data-binary "@$DIR/.sync.light" "${FORGE_URL%/}/api/v1/games/agent/sync")" || return 1
1935 jq -cn --slurpfile ask "$DIR/.sync.ask" --arg sha "$(cat "$DIR/.compose-sha" 2>/dev/null)" --slurpfile results "$DIR/.sync.results" --argjson told "$(desk_here && echo true || echo false)" --argjson got "$(desk_got)" \
1936 '{agent: 1, light: true, composeSha: $sha, results: $results[0], got: $got} + (if $told then {told: true} else {} end) + (if $ask[0] == [] then {} else {ask: $ask[0]} end)' >"$DIR/.sync.light" || return 1
1937 answer="$(curl -fsS -m 5 -H "@$AUTH" -H 'content-type: application/json' --data-binary "@$DIR/.sync.light" "${FORGE_URL%/}/api/v1/games/agent/sync")" || { desk_again; return 1; }
18821938 echo '[]' >"$DIR/.results"
18831939 desk_heard "$DIR/.sync.light"
18841940 desk_told "$answer"
1941 desk_asked "$answer"
18851942 apply "$answer"
18861943 # Something ran: its result goes in now. Nothing ran: the next poll is a second away.
18871944 [ "$(jq 'length' "$DIR/.results" 2>/dev/null || echo 0)" = 0 ] && return 0
src/http/games_routes.ts +8 −1
@@ -54,8 +54,15 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
5454 synced(ctx.app, box.id);
5555 // Only to an agent that says it reads them here; what it got is heard either way.
5656 if (body.told !== true) toldGot(ctx.app.db, box, body.got);
57 const reply: Record<string, unknown> = { commands };
58 // The proxy's `/forge`, as in a full sync: kept once by its id, and answered here where it can be.
59 if (Array.isArray(body.ask)) {
60 reply["asked"] = gameAsk(ctx.app, box, body.ask, (await readCompose(ctx.app, box))?.text, ctx.url.origin);
61 void runChat(ctx.app, box.id);
62 }
5763 const told = body.told === true ? toldTo(ctx.app.db, box, Date.now(), body.got) : [];
58 return json(told.length > 0 ? { commands, told } : { commands });
64 if (told.length > 0) reply["told"] = told;
65 return json(reply);
5966 }
6067 // Every shell command the box answered, its output with it, into the audit.
6168 auditShellResults(ctx.app, box, (body.results ?? []).map((r) => r.id));
test/game-desk.test.ts +120 −2
@@ -30,11 +30,13 @@ function made(answer: (n: number, ask: { id: string }[] | undefined) => Response
3030 fake,
3131 `#!/usr/bin/env bash
3232 case "$*" in *" ps -a --format json") echo '{"Name":"c1","Service":"${service}","State":"running"}'; exit ;; esac
33 case " $* " in *" logs "*) while [ -f "${root}/slow" ]; do : >"${root}/in-logs"; sleep 0.1; done ;; esac
3334 while [ $# -gt 0 ] && [ "$1" != exec ]; do shift; done
3435 [ $# = 0 ] || echo x >>"${root}/execs"
3536 [ "\${1:-}" = exec ] && [ "$2 $3 $4 $5" = "-T -u bungeecord velocity" ] || exit 0
3637 shift 5
3738 cd "${proxy}" || exit 1
39 case "$*" in *'while read -r $t'*) echo $$ >>"${root}/watchers" ;; esac
3840 if [ -f "${root}/cut" ]; then "$@" | head -c 150; else exec "$@"; fi
3941 `,
4042 );
@@ -52,7 +54,7 @@ if [ -f "${root}/cut" ]; then "$@" | head -c 150; else exec "$@"; fi
5254 forge.stop(true);
5355 await rm(root, { recursive: true, force: true });
5456 });
55 const run = async (until?: () => boolean): Promise<void> => {
57 const run = async (until?: () => boolean | Promise<boolean>, env: Record<string, string> = {}, signal: NodeJS.Signals = "SIGTERM"): Promise<void> => {
5658 const p = Bun.spawn(["bash", AGENT], {
5759 env: {
5860 PATH: process.env["PATH"] ?? "",
@@ -63,6 +65,8 @@ if [ -f "${root}/cut" ]; then "$@" | head -c 150; else exec "$@"; fi
6365 FORGE_GAME_DIAG_S: "0",
6466 FORGE_GAME_VOLUME_CHECK: "0",
6567 FORGE_GAME_ONCE: until === undefined ? "1" : "0",
68 FORGE_GAME_LIGHT_SLEEP: "0.1",
69 ...env,
6670 },
6771 stdout: "ignore",
6872 stderr: Bun.file(join(root, "log")),
@@ -71,7 +75,7 @@ if [ -f "${root}/cut" ]; then "$@" | head -c 150; else exec "$@"; fi
7175 if (until === undefined) await p.exited;
7276 else await pollUntil(until, "the agent to get there", 30_000);
7377 } finally {
74 p.kill();
78 p.kill(signal);
7579 await p.exited;
7680 }
7781 };
@@ -178,6 +182,106 @@ deskTest("an answer that comes with the quick poll is put in the inbox too", asy
178182 expect(JSON.parse(readFileSync(join(b.desk, "inbox", b.inbox()[0]!), "utf8"))).toEqual(told[0]);
179183 }, 60_000);
180184
185 const light = (b: ReturnType<typeof made>) => b.bodies.filter((x) => x["light"] === true);
186 /** Makes request `n`, once, when the agent has sent more than `after` bodies. */
187 const later = (b: ReturnType<typeof made>, n: number, after = 0) => {
188 let made = false;
189 return (): void => {
190 if (made || b.bodies.length <= after) return;
191 made = true;
192 b.asks(n, 0);
193 };
194 };
195 const carried = (xs: Record<string, any>[]): string[][] => xs.flatMap((x) => (x["ask"] === undefined ? [] : [x["ask"].map((a: { id: string }) => a.id)]));
196
197 deskTest("a request made between full syncs goes with the quick poll, again when that got no answer, and is deleted once named", async () => {
198 // Only the first full sync is answered in time to matter: the next is ten minutes away.
199 let failed = 0;
200 const b = made((_n, ask) => (ask !== undefined && failed++ === 0 ? new Response("", { status: 502 }) : ask === undefined ? ok() : took(ask)));
201 // Two runs: a failed quick poll waits out the rest of the time between full syncs.
202 const first = later(b, 1);
203 await b.run(() => {
204 first();
205 return failed === 1;
206 }, { FORGE_GAME_EVERY: "600" });
207 expect(carried(light(b))).toEqual([[uuid(1)]]);
208 expect(b.outbox()).toEqual([`${uuid(1)}.json`]);
209 const before = b.bodies.length;
210 const second = later(b, 2, before);
211 await b.run(() => {
212 second();
213 return b.outbox().length === 0 && b.bodies.length > before + 3;
214 }, { FORGE_GAME_EVERY: "600" });
215 const all = carried(b.bodies.slice(before)).flat();
216 expect(all.sort()).toEqual([uuid(1), uuid(2)]);
217 expect(carried(light(b)).flat()).toContain(uuid(2));
218 }, 90_000);
219
220 deskTest("the shell in the proxy ends with the agent, stopped or killed", async () => {
221 const alive = (pid: number): boolean => {
222 try {
223 return process.kill(pid, 0);
224 } catch {
225 return false;
226 }
227 };
228 for (const signal of ["SIGTERM", "SIGKILL"] as const) {
229 const b = made(() => ok());
230 let pid = 0;
231 await b.run(() => {
232 pid = existsSync(join(b.root, "watchers")) ? Number(readFileSync(join(b.root, "watchers"), "utf8")) : 0;
233 return pid > 0 && alive(pid);
234 }, {}, signal);
235 await pollUntil(() => !alive(pid), `the shell to end after ${signal}`, 30_000);
236 }
237 }, 120_000);
238
239 deskTest("the plugin's folder gets the forge's origin alone, and none that is not https", async () => {
240 const b = made(() => ok());
241 const file = join(b.desk, "origin");
242 // Nothing answers there: the file does not wait for the forge.
243 const https = (url: string, want: string) => b.run(() => existsSync(file) && readFileSync(file, "utf8") === want, { FORGE_URL: url, FORGE_GAME_EVERY: "2" });
244 await https("https://127.0.0.1:1/", "https://127.0.0.1:1\n");
245 await https("https://localhost", "https://localhost\n");
246 // An http forge, one with a name and password in its address, one under a path: the old file goes.
247 await b.run(() => !existsSync(file));
248 await https("https://localhost", "https://localhost\n");
249 await b.run(() => !existsSync(file), { FORGE_URL: "https://user:pass@localhost/" });
250 await https("https://localhost", "https://localhost\n");
251 await b.run(() => !existsSync(file), { FORGE_URL: "https://localhost/a/path" });
252 expect(readdirSync(b.desk).sort()).toEqual(["inbox", "outbox"]);
253 }, 120_000);
254
255 deskTest("an older forge that names none in a quick poll is not asked at each one", async () => {
256 const b = made(() => ok());
257 const one = later(b, 1);
258 await b.run(() => {
259 one();
260 return carried(light(b)).length > 0 && light(b).length >= 6;
261 }, { FORGE_GAME_EVERY: "600" });
262 expect(carried(light(b))).toEqual([[uuid(1)]]);
263 expect(b.outbox()).toEqual([`${uuid(1)}.json`]);
264 }, 90_000);
265
266 deskTest("a request made in a long full sync goes with a quick poll between its parts, not again with the sync", async () => {
267 const b = made((_n, ask) => took(ask));
268 let since = 0;
269 await b.run(() => {
270 const full = b.bodies.length - light(b).length;
271 if (full === 1 && since === 0 && light(b).length > 0) writeFileSync(join(b.root, "slow"), "");
272 if (since === 0 && existsSync(join(b.root, "in-logs"))) {
273 b.asks(1, 0);
274 since = Date.now();
275 }
276 // Past the second of the last quick poll, and long enough for the proxy's shell to say so.
277 if (since > 0 && existsSync(join(b.root, "slow")) && existsSync(join(b.root, "game/.desk.due")) && Date.now() - since > 1_200) void rm(join(b.root, "slow"), { force: true });
278 return full >= 2;
279 }, { FORGE_GAME_EVERY: "20" });
280 expect(carried(light(b))).toEqual([[uuid(1)]]);
281 expect(carried(b.bodies.filter((x) => x["light"] !== true))).toEqual([]);
282 expect(b.outbox()).toEqual([]);
283 }, 90_000);
284
181285 const answer = (n: number, text: string, ask = n) => ({ n, id: uuid(ask), uuid: uuid(1), text, confirm: false });
182286 const texts = (b: ReturnType<typeof made>): string[] => b.inbox().map((f) => (JSON.parse(readFileSync(join(b.desk, "inbox", f), "utf8")) as { text: string }).text).sort();
183287
@@ -203,6 +307,20 @@ deskTest("an answer in the inbox is said back until a sync that said it is answe
203307 expect(texts(b)).toEqual(["first", "new", "second"]);
204308 }, 60_000);
205309
310 deskTest("an answer's `lines` go in as they are, and count in its 16 KiB", async () => {
311 const lines = [{ t: "#12 fix \\n é", c: "good", open: "/a/b/pulls/12" }, { t: "Next", put: "/forge more" }];
312 const b = made(() => ok({ told: [{ ...answer(7, "rich"), lines }, { ...answer(8, "big"), lines: [{ t: "y".repeat(17_000) }] }, { ...answer(9, "plain"), lines: "x", other: 1 }] }));
313 await b.run();
314 const in_ = b.inbox().map((f) => JSON.parse(readFileSync(join(b.desk, "inbox", f), "utf8")) as object);
315 const { n: _a, ...rich } = { ...answer(7, "rich"), lines };
316 const { n: _b, ...plain } = answer(9, "plain");
317 expect(in_).toHaveLength(2);
318 expect(in_).toContainEqual(rich);
319 expect(in_).toContainEqual(plain);
320 await b.run();
321 expect(b.bodies[1]!["got"]).toEqual([7, 8, 9]);
322 }, 60_000);
323
206324 deskTest("an answer that found no room is not said back, and goes in when it comes again", async () => {
207325 const b = made(() => ok({ told: [answer(7, "waits")] }));
208326 for (let i = 0; i < 64; i++) writeFileSync(join(b.desk, "inbox", `w${i}.json`), "{}");
test/game-door.test.ts +7
@@ -407,6 +407,13 @@ test("the sync carries a request in and its answer out, once", async () => {
407407 expect((await sync({ light: true, told: true })).told).toEqual([next.id]);
408408 expect((await sync({ light: true, told: true })).told).toBeUndefined();
409409
410 // A quick poll carries a request too: taken once, answered there.
411 const quick = request("help");
412 expect(await sync({ light: true, told: true, got: [], ask: [quick] })).toEqual({ told: [quick.id], asked: [quick.id] });
413 const row = app.db.query<{ id: number }, [string]>("SELECT id FROM game_told WHERE ask_id = ?1").get(quick.id)!.id;
414 expect(await sync({ light: true, told: true, got: [row], ask: [quick] })).toEqual({ told: undefined, asked: [quick.id] });
415 expect((await sync({ light: true, told: true, got: [] })).asked).toBeUndefined();
416
410417 // Told again until `got`, in either sync.
411418 const kept = request("help");
412419 expect((await sync({ ask: [kept], got: [] })).told).toEqual([kept.id]);

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

Keyboard shortcuts

Docs