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
Merged 13h 46m ago, live in production
sold/forge-fast → main 0 commits
6 files
changed +208
−19
docs/features/game-box.md +1 −1
| @@ -33,7 +33,7 @@ experiment. | ||
| 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 | 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 | - **`/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. | |
| 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. |
| 39 | 39 |
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? (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", | |
| 8 | 8 | auth: false, |
| 9 | 9 | role: "anonymous", |
| 10 | 10 | refuses: [401], |
src/games/agent.sh +71 −14
| @@ -1287,15 +1287,49 @@ export WORLDS HELPER | ||
| 1287 | 1287 | # (which runs no player's mods), as the proxy's own user: the host never opens a file there. ---- |
| 1288 | 1288 | |
| 1289 | 1289 | # `sh` in the proxy, in one of the plugin's two folders, when neither it nor its parents is a link. |
| 1290 | DESK=("" 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 | ' | |
| 1290 | 1295 | desk() { |
| 1291 | 1296 | local box="$1" script="$2" |
| 1292 | 1297 | shift 2 |
| 1293 | capped 5 "" 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 "" "" "" "$@" 2>/dev/null | |
| 1296 | 1299 | } |
| 1297 | 1300 | # Whether the proxy runs, as the last full sync's services say: nothing is asked of one that does not. |
| 1298 | 1301 | desk_here() { jq -e 'any(.[]; .name == "velocity" and .state == "running")' "/.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 | [[ "" =~ ^https://[A-Za-z0-9.-]+(:[0-9]{1,5})?/?$ ]] && ORIGIN="" | |
| 1311 | desk_watch() { | |
| 1312 | [ "" != 1 ] && desk_here || return 0 | |
| 1313 | [ -z "" ] || ! kill -0 "" 2>/dev/null || return 0 | |
| 1314 | [ "" -ge "" ] || return 0 | |
| 1315 | DESK_NEXT= | |
| 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 | "" ""'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 _ </dev/null; [ != 2 ] || t="" | |
| 1320 | while read -r _; do | |
| 1321 | set -- *.json; [ -e "$1" ] || set -- | |
| 1322 | [ "$*" = "" ] || { 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 "/.desk.due" | |
| 1329 | desk_asks | json_or '[]' >"/.sync.ask" | |
| 1330 | } | |
| 1331 | # The sync that carried them got no answer: the next quick poll carries them again. | |
| 1332 | desk_again() { [ "$(cat "/.sync.ask" 2>/dev/null)" = '[]' ] || : >"/.desk.due"; } | |
| 1299 | 1333 | # The requests among the oldest 20 files. One the forge could never name (over 2 KiB, no JSON object, |
| 1300 | 1334 | # or an id that is not the file's own lowercase name) would hold its place for ever: it is dropped. |
| 1301 | 1335 | # 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() { | ||
| 1342 | 1376 | # not written again. The container says the number of each one it wrote; one it did not write comes |
| 1343 | 1377 | # again. One over 16 KiB never goes in, so it counts as had. |
| 1344 | 1378 | 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; ' | |
| 1346 | 1380 | desk_here && jq -e '(.told // []) | length > 0' >/dev/null 2>&1 <<<"$1" || return 0 |
| 1347 | 1381 | state="$(desk_state)" |
| 1348 | 1382 | # shellcheck disable=SC2016 |
| 1349 | wrote="$(jq -r --argjson s "" '.told[0:20][] | objects | . as | select(any(.had[]; .n == .n and .id == .id) | not) | |
| 1350 | | ({id, uuid, text, confirm} | tojson) as | select(( | utf8bytelength) <= 16384) | "\(if (.n | type) == "number" then .n else "-" end)\t\()"' <<<"$1" 2>/dev/null | | |
| 1383 | wrote="$(jq -r --argjson s "" ""'.told[0:20][] | objects | . as | select(any(.had[]; .n == .n and .id == .id) | not) | |
| 1384 | | put as | select(( | utf8bytelength) <= 16384) | "\(if (.n | type) == "number" then .n else "-" end)\t\()"' <<<"$1" 2>/dev/null | | |
| 1351 | 1385 | desk inbox 'umask 022; n=0; tab="$(printf "\t")"; while IFS="$tab" read -r num line; do |
| 1352 | 1386 | [ "$(ls | wc -l)" -lt 64 ] || exit 0 |
| 1353 | 1387 | n=; printf "%s\n" "" > "$1-.tmp" && mv "$1-.tmp" "$1-.json" && printf "%s\n" "" |
| 1354 | 1388 | 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 "" --arg wrote "" --argjson now "$(date +%s)" '($wrote | split("\n")) as $w | |
| 1389 | jq -c --argjson s "" --arg wrote "" --argjson now "$(date +%s)" ""'($wrote | split("\n")) as $w | |
| 1356 | 1390 | | [.told[0:20][] | objects | select((.n | type) == "number") | . as | any(.had[]; .n == .n and .id == .id) as |
| 1357 | | select( or ( | index([.n | tostring])) != null or ({id, uuid, text, confirm} | tojson | utf8bytelength) > 16384) | {n, id, before: }] as | |
| 1391 | | select( or ( | index([.n | tostring])) != null or (put | utf8bytelength) > 16384) | {n, id, before: }] as | |
| 1358 | 1392 | | {had: ([.had[] | select(.at > - 7200)] + [[] | select(.before | not) | {n, id, at: }]), got: (.got + [[].n] | unique)}' <<<"$1" >"$TOLD.next" 2>/dev/null && |
| 1359 | 1393 | mv ".next" "" |
| 1360 | 1394 | return 0 |
| @@ -1365,16 +1399,23 @@ sync() { | ||
| 1365 | 1399 | next="$(now)" |
| 1366 | 1400 | # Each part through a file, checked as JSON on the way: a sync can pass the 128 KB one argument |
| 1367 | 1401 | # 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. | |
| 1368 | 1403 | services | json_or '[]' >"/.sync.services" |
| 1369 | desk_asks | json_or '[]' >"/.sync.ask" | |
| 1404 | between | |
| 1370 | 1405 | logs "" | json_or '{}' >"/.sync.logs" |
| 1371 | json_or '[]' <"/.results" >"/.sync.results" | |
| 1406 | between | |
| 1372 | 1407 | host | json_or '{}' >"/.sync.host" |
| 1373 | 1408 | bounded_diag | jq -c --argjson hold "$(held)" --argjson waits "$([ -f "/.jars.waits" ] && echo true || echo false)" '. + {hold: $hold} + (if $waits then {jarsWait: true} else {} end)' 2>/dev/null | json_or '{}' >"/.sync.diag" |
| 1409 | between | |
| 1374 | 1410 | people | json_or '{}' >"/.sync.people" |
| 1411 | between | |
| 1375 | 1412 | metrics | json_or '{}' >"/.sync.metrics" |
| 1413 | between | |
| 1376 | 1414 | jq -c 'if type == "object" then . else {} end' "/snapshots.json" 2>/dev/null | json_or '{}' >"/.sync.snapshots" |
| 1377 | 1415 | chat | json_or '{}' >"/.sync.chat" |
| 1416 | # Last, after every quick poll: what one of those delivered is not sent again. | |
| 1417 | desk_take | |
| 1418 | json_or '[]' <"/.results" >"/.sync.results" | |
| 1378 | 1419 | # Every string as plain text: real servers print colour escapes and control bytes (itzg's logs, |
| 1379 | 1420 | # rcon-cli's colours), and the forge takes none of them. Colours go first as Minecraft's own |
| 1380 | 1421 | # printable section codes (\u00a7: the sixteen colours, l bold, n underline, r every reset), which |
| @@ -1420,9 +1461,12 @@ sync() { | ||
| 1420 | 1461 | # The forge may have kept this body before the answer was lost: the next says so, and it |
| 1421 | 1462 | # skips the log lines it already holds, so a console never shows a line twice. |
| 1422 | 1463 | : >"/.sync.retry" |
| 1464 | desk_again | |
| 1465 | POLLS=0 | |
| 1423 | 1466 | return 1 |
| 1424 | 1467 | fi |
| 1425 | 1468 | token_answered "" |
| 1469 | POLLS=1 | |
| 1426 | 1470 | desk_heard "/.sync.body" |
| 1427 | 1471 | desk_told "" |
| 1428 | 1472 | desk_asked "" |
| @@ -1862,7 +1906,8 @@ metadata_close | ||
| 1862 | 1906 | |
| 1863 | 1907 | # The quick poll (#17610): between full syncs, only the command results go in and the queued |
| 1864 | 1908 | # 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 | |
| 1866 | 1911 | # result sent at once, not at the next poll. The forge handles a `light` body without touching |
| 1867 | 1912 | # anything else it knows. |
| 1868 | 1913 | LIGHT_EVERY="" |
| @@ -1870,18 +1915,30 @@ LIGHT_EVERY="${FORGE_GAME_LIGHT_EVERY:-1}" | ||
| 1870 | 1915 | [[ "" =~ ^[1-9][0-9]{0,2}$ ]] || LIGHT_EVERY=1 |
| 1871 | 1916 | # How long such a second really is: shorter in tests, which wait for many syncs. |
| 1872 | 1917 | LIGHT_SLEEP="" |
| 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 | [ "" != 1 ] && [ "" -ge 1 ] 2>/dev/null && [ "" = 1 ] && [ "" != "" ] || return 0 | |
| 1923 | light_sync || POLLS=0 | |
| 1924 | return 0 | |
| 1925 | } | |
| 1873 | 1926 | light_sync() { |
| 1874 | 1927 | local answer round |
| 1928 | desk_watch | |
| 1875 | 1929 | for round in 1 2; do |
| 1876 | 1930 | job_tick |
| 1877 | 1931 | shell_tick |
| 1932 | POLLED="" | |
| 1933 | if [ -f "/.desk.due" ] && desk_here; then desk_take; else echo '[]' >"/.sync.ask"; fi | |
| 1878 | 1934 | json_or '[]' <"/.results" >"/.sync.results" |
| 1879 | jq -cn --arg sha "$(cat "/.compose-sha" 2>/dev/null)" --slurpfile results "/.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)' >"/.sync.light" || return 1 | |
| 1881 | answer="$(curl -fsS -m 5 -H "@" -H 'content-type: application/json' --data-binary "@/.sync.light" "/api/v1/games/agent/sync")" || return 1 | |
| 1935 | jq -cn --slurpfile ask "/.sync.ask" --arg sha "$(cat "/.compose-sha" 2>/dev/null)" --slurpfile results "/.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)' >"/.sync.light" || return 1 | |
| 1937 | answer="$(curl -fsS -m 5 -H "@" -H 'content-type: application/json' --data-binary "@/.sync.light" "/api/v1/games/agent/sync")" || { desk_again; return 1; } | |
| 1882 | 1938 | echo '[]' >"/.results" |
| 1883 | 1939 | desk_heard "/.sync.light" |
| 1884 | 1940 | desk_told "" |
| 1941 | desk_asked "" | |
| 1885 | 1942 | apply "" |
| 1886 | 1943 | # Something ran: its result goes in now. Nothing ran: the next poll is a second away. |
| 1887 | 1944 | [ "$(jq 'length' "/.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> { | ||
| 54 | 54 | synced(ctx.app, box.id); |
| 55 | 55 | // Only to an agent that says it reads them here; what it got is heard either way. |
| 56 | 56 | 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 | } | |
| 57 | 63 | 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); | |
| 59 | 66 | } |
| 60 | 67 | // Every shell command the box answered, its output with it, into the audit. |
| 61 | 68 | 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 | ||
| 30 | 30 | fake, |
| 31 | 31 | `#!/usr/bin/env bash |
| 32 | 32 | 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 | |
| 33 | 34 | while [ $# -gt 0 ] && [ "$1" != exec ]; do shift; done |
| 34 | 35 | [ $# = 0 ] || echo x >>"${root}/execs" |
| 35 | 36 | [ "\${1:-}" = exec ] && [ "$2 $3 $4 $5" = "-T -u bungeecord velocity" ] || exit 0 |
| 36 | 37 | shift 5 |
| 37 | 38 | cd "${proxy}" || exit 1 |
| 39 | case "$*" in *'while read -r $t'*) echo $$ >>"${root}/watchers" ;; esac | |
| 38 | 40 | if [ -f "${root}/cut" ]; then "$@" | head -c 150; else exec "$@"; fi |
| 39 | 41 | `, |
| 40 | 42 | ); |
| @@ -52,7 +54,7 @@ if [ -f "${root}/cut" ]; then "$@" | head -c 150; else exec "$@"; fi | ||
| 52 | 54 | forge.stop(true); |
| 53 | 55 | await rm(root, { recursive: true, force: true }); |
| 54 | 56 | }); |
| 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> => { | |
| 56 | 58 | const p = Bun.spawn(["bash", AGENT], { |
| 57 | 59 | env: { |
| 58 | 60 | PATH: process.env["PATH"] ?? "", |
| @@ -63,6 +65,8 @@ if [ -f "${root}/cut" ]; then "$@" | head -c 150; else exec "$@"; fi | ||
| 63 | 65 | FORGE_GAME_DIAG_S: "0", |
| 64 | 66 | FORGE_GAME_VOLUME_CHECK: "0", |
| 65 | 67 | FORGE_GAME_ONCE: until === undefined ? "1" : "0", |
| 68 | FORGE_GAME_LIGHT_SLEEP: "0.1", | |
| 69 | ...env, | |
| 66 | 70 | }, |
| 67 | 71 | stdout: "ignore", |
| 68 | 72 | stderr: Bun.file(join(root, "log")), |
| @@ -71,7 +75,7 @@ if [ -f "${root}/cut" ]; then "$@" | head -c 150; else exec "$@"; fi | ||
| 71 | 75 | if (until === undefined) await p.exited; |
| 72 | 76 | else await pollUntil(until, "the agent to get there", 30_000); |
| 73 | 77 | } finally { |
| 74 | p.kill(); | |
| 78 | p.kill(signal); | |
| 75 | 79 | await p.exited; |
| 76 | 80 | } |
| 77 | 81 | }; |
| @@ -178,6 +182,106 @@ deskTest("an answer that comes with the quick poll is put in the inbox too", asy | ||
| 178 | 182 | expect(JSON.parse(readFileSync(join(b.desk, "inbox", b.inbox()[0]!), "utf8"))).toEqual(told[0]); |
| 179 | 183 | }, 60_000); |
| 180 | 184 | |
| 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 | ||
| 181 | 285 | const answer = (n: number, text: string, ask = n) => ({ n, id: uuid(ask), uuid: uuid(1), text, confirm: false }); |
| 182 | 286 | 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(); |
| 183 | 287 | |
| @@ -203,6 +307,20 @@ deskTest("an answer in the inbox is said back until a sync that said it is answe | ||
| 203 | 307 | expect(texts(b)).toEqual(["first", "new", "second"]); |
| 204 | 308 | }, 60_000); |
| 205 | 309 | |
| 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 | ||
| 206 | 324 | deskTest("an answer that found no room is not said back, and goes in when it comes again", async () => { |
| 207 | 325 | const b = made(() => ok({ told: [answer(7, "waits")] })); |
| 208 | 326 | 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 () => { | ||
| 407 | 407 | expect((await sync({ light: true, told: true })).told).toEqual([next.id]); |
| 408 | 408 | expect((await sync({ light: true, told: true })).told).toBeUndefined(); |
| 409 | 409 | |
| 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 | ||
| 410 | 417 | // Told again until `got`, in either sync. |
| 411 | 418 | const kept = request("help"); |
| 412 | 419 | expect((await sync({ ask: [kept], got: [] })).told).toEqual([kept.id]); |
new above
offline