Public: anyone can read this; the crew can change it.
Games: /forge reads are answered in the same sync, and the agent sends a request within a fifth of a second #18149
Merged 15h 48m ago, live in production
sold/forge-instant-path → main 0 commits
4 files
changed +81
−7
src/games/agent.sh +32 −5
| @@ -1384,7 +1384,7 @@ desk() { | ||
| 1384 | 1384 | # Whether the proxy runs, as the last full sync's services say: nothing is asked of one that does not. |
| 1385 | 1385 | desk_here() { jq -e 'any(.[]; .name == "velocity" and .state == "running")' "/.sync.services" >/dev/null 2>&1; } |
| 1386 | 1386 | # One long-lived `sh` in the proxy says when the outbox holds other files than at its last look, so the |
| 1387 | # next quick poll carries them; only that a line came is used. It looks once for each line it is sent, twice | |
| 1387 | # next quick poll carries them; only that a line came is used. It looks once for each line it is sent, five times | |
| 1388 | 1388 | # a second, and ends when those end: with this agent, with the proxy, or after an hour; also when none came |
| 1389 | 1389 | # for 60 s, where the proxy has a shell whose `read` can say so (bash, busybox; dash says 2). Started again |
| 1390 | 1390 | # then, at most every 10 s. The full sync looks for itself, so nothing depends on it. |
| @@ -1398,7 +1398,7 @@ desk_watch() { | ||
| 1398 | 1398 | [ "" -ge "" ] || return 0 |
| 1399 | 1399 | DESK_NEXT= |
| 1400 | 1400 | # shellcheck disable=SC2016 |
| 1401 | for ((i = 0; i < 7200; i++)); do kill -0 "$$" 2>/dev/null && echo && sleep 0.5 || break; done 2>/dev/null | | |
| 1401 | for ((i = 0; i < 18000; i++)); do kill -0 "$$" 2>/dev/null && echo && sleep 0.2 || break; done 2>/dev/null | | |
| 1402 | 1402 | "" ""'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 |
| 1403 | 1403 | was=""; t="-t 60"; read _ </dev/null; [ != 2 ] || t="" |
| 1404 | 1404 | while read -r _; do |
| @@ -2037,7 +2037,8 @@ light_sync() { | ||
| 2037 | 2037 | job_tick |
| 2038 | 2038 | shell_tick |
| 2039 | 2039 | POLLED="" |
| 2040 | if [ -f "/.desk.due" ] && desk_here; then desk_take; else echo '[]' >"/.sync.ask"; fi | |
| 2040 | # A mark with no proxy to carry it is stale: it goes, so it cannot cut a wait short. | |
| 2041 | if [ -f "/.desk.due" ] && desk_here; then desk_take; else rm -f "/.desk.due"; echo '[]' >"/.sync.ask"; fi | |
| 2041 | 2042 | json_or '[]' <"/.results" >"/.sync.results" |
| 2042 | 2043 | 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)" \ |
| 2043 | 2044 | '{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 |
| @@ -2051,18 +2052,44 @@ light_sync() { | ||
| 2051 | 2052 | [ "$(jq 'length' "/.results" 2>/dev/null || echo 0)" = 0 ] && return 0 |
| 2052 | 2053 | done |
| 2053 | 2054 | } |
| 2055 | # The wait between quick polls: LIGHT_SLEEP, ended early by the mark that a /forge request came (`desk_watch`), so a | |
| 2056 | # player's words go out within a fifth of a second of being typed, not at the next whole second. Never ended early | |
| 2057 | # when the proxy is not running or the last poll failed (the forge is restarting): a mark then waits like any poll, | |
| 2058 | # and a poll is never closer than a tenth of a second to the one before. | |
| 2059 | LIGHT_OK=1 | |
| 2060 | # EARLY is 1 when the last nap ended for a request: that poll does not count as a second of the wait. | |
| 2061 | EARLY=0 | |
| 2062 | nap() { | |
| 2063 | local i | |
| 2064 | EARLY=0 | |
| 2065 | if [ -e "/.desk.due" ] && [ "" = 1 ] && desk_here; then | |
| 2066 | EARLY=1 | |
| 2067 | sleep 0.1 | |
| 2068 | return 0 | |
| 2069 | fi | |
| 2070 | [[ "" =~ ^[1-9][0-9]{0,2}$ ]] || { sleep ""; return 0; } | |
| 2071 | for ((i = 0; i < LIGHT_SLEEP * 10; i++)); do | |
| 2072 | sleep 0.1 | |
| 2073 | if [ -e "/.desk.due" ] && [ "" = 1 ] && desk_here; then | |
| 2074 | EARLY=1 | |
| 2075 | return 0 | |
| 2076 | fi | |
| 2077 | done | |
| 2078 | } | |
| 2054 | 2079 | # The wait between full syncs, spent polling lightly. |
| 2055 | 2080 | wait_polling() { |
| 2056 | 2081 | local waited=0 |
| 2057 | 2082 | while [ "" -lt "" ]; do |
| 2058 | sleep "" | |
| 2059 | waited= | |
| 2083 | nap | |
| 2084 | [ "" = 1 ] || waited= | |
| 2060 | 2085 | # A failed poll (the forge is down or restarting) ends no wait early: the rest of EVERY is |
| 2061 | 2086 | # waited out, so a full sync never follows at once and boxes do not all come back together. |
| 2062 | 2087 | if ! light_sync; then |
| 2088 | LIGHT_OK=0 | |
| 2063 | 2089 | [ "" -lt "" ] && sleep |
| 2064 | 2090 | return 0 |
| 2065 | 2091 | fi |
| 2092 | LIGHT_OK=1 | |
| 2066 | 2093 | done |
| 2067 | 2094 | } |
| 2068 | 2095 |
src/http/games_routes.ts +10 −2
| @@ -29,6 +29,14 @@ import { InvalidJson } from "./json_body.ts"; | ||
| 29 | 29 | import { apiError, boundedMachineBody, json } from "./respond.ts"; |
| 30 | 30 | import type { Router } from "./router.ts"; |
| 31 | 31 | |
| 32 | /** | |
| 33 | * How long a sync waits for the answers to the requests it just took: a read or a question is done in | |
| 34 | * a few milliseconds, so it rides the same reply instead of the next poll. A plan or the crew is never | |
| 35 | * waited for; its answer comes at a later poll. | |
| 36 | */ | |
| 37 | const QUICK_MS = 250; | |
| 38 | const quickly = (work: Promise<void>): Promise<unknown> => Promise.race([work.catch(() => undefined), Bun.sleep(QUICK_MS)]); | |
| 39 | ||
| 32 | 40 | /** POST /api/v1/games/agent/sync: one pull of a game box's agent (the contract in docs/features/games.md). */ |
| 33 | 41 | export async function gameAgentSync(ctx: Ctx): Promise<Response> { |
| 34 | 42 | const auth = ctx.request.headers.get("authorization") ?? ""; |
| @@ -58,7 +66,7 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> { | ||
| 58 | 66 | // The proxy's `/forge`, as in a full sync: kept once by its id, and answered here where it can be. |
| 59 | 67 | if (Array.isArray(body.ask)) { |
| 60 | 68 | reply["asked"] = gameAsk(ctx.app, box, body.ask, (await readCompose(ctx.app, box))?.text, ctx.url.origin); |
| 61 | void runChat(ctx.app, box.id); | |
| 69 | await quickly(runChat(ctx.app, box.id)); | |
| 62 | 70 | } |
| 63 | 71 | const told = body.told === true ? toldTo(ctx.app.db, box, Date.now(), body.got) : []; |
| 64 | 72 | if (told.length > 0) reply["told"] = told; |
| @@ -85,7 +93,7 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> { | ||
| 85 | 93 | gameChat(ctx.app, box, body.chat, compose?.text, ctx.url.origin, Date.now(), body.chatId); |
| 86 | 94 | // The same through the proxy's `/forge` (`games/door.ts`). |
| 87 | 95 | const asked = gameAsk(ctx.app, box, body.ask, compose?.text, ctx.url.origin); |
| 88 | void runChat(ctx.app, box.id); | |
| 96 | await quickly(runChat(ctx.app, box.id)); | |
| 89 | 97 | synced(ctx.app, box.id); |
| 90 | 98 | const reply: Record<string, unknown> = { |
| 91 | 99 | composeSha: compose?.sha ?? "", |
test/game-desk.test.ts +19
| @@ -174,6 +174,25 @@ deskTest("answers are put whole in the inbox, readable, under the agent's own na | ||
| 174 | 174 | expect(b.inbox()).toHaveLength(64); |
| 175 | 175 | }, 60_000); |
| 176 | 176 | |
| 177 | deskTest("a poll that failed is waited out even with a request waiting: the agent does not spin on a restarting forge", async () => { | |
| 178 | const b = made((_n, ask) => (b.bodies.at(-1)!["light"] === true ? new Response("", { status: 502 }) : took(ask))); | |
| 179 | b.asks(1, 10); | |
| 180 | await b.run(() => b.bodies.filter((x) => x["light"] === true).length >= 1); | |
| 181 | const from = Date.now(); | |
| 182 | await b.run(() => Date.now() - from > 3_000, { FORGE_GAME_LIGHT_SLEEP: "1" }); | |
| 183 | expect(b.bodies.filter((x) => x["light"] === true).length).toBeLessThan(12); | |
| 184 | }, 60_000); | |
| 185 | ||
| 186 | deskTest("a mark left behind with the proxy stopped does not end the wait: quick polls stay a second apart", async () => { | |
| 187 | const b = made(() => ok(), "hub"); | |
| 188 | mkdirSync(join(b.root, "game"), { recursive: true }); | |
| 189 | writeFileSync(join(b.root, "game", ".desk.due"), ""); | |
| 190 | const from = Date.now(); | |
| 191 | await b.run(() => Date.now() - from > 3_500, { FORGE_GAME_LIGHT_SLEEP: "1" }); | |
| 192 | expect(b.bodies.filter((x) => x["light"] === true).length).toBeLessThan(8); | |
| 193 | expect(existsSync(join(b.root, "game", ".desk.due"))).toBe(false); | |
| 194 | }, 60_000); | |
| 195 | ||
| 177 | 196 | deskTest("an answer that comes with the quick poll is put in the inbox too", async () => { |
| 178 | 197 | const told = [{ id: "r1", uuid: uuid(1), text: "hi", confirm: false }]; |
| 179 | 198 | const b = made((n) => (n === 2 ? Response.json({ commands: [], told }) : ok())); |
test/game-door.test.ts +20
| @@ -301,6 +301,26 @@ test("a plan through the proxy takes the place of chat's, and chat's yes does no | ||
| 301 | 301 | expect((await readCompose(app, box))!.text).not.toContain("theirs"); |
| 302 | 302 | }, 30_000); |
| 303 | 303 | |
| 304 | test("a read taken in a sync is answered in the same reply, not at the next poll", async () => { | |
| 305 | app.db | |
| 306 | .query("INSERT OR REPLACE INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, 'ada', ?2, ?3, ?4)") | |
| 307 | .run(box.id, ada.id, ADA, new Date().toISOString()); | |
| 308 | anHourOn(); | |
| 309 | const read = request("servers"); | |
| 310 | const res = await forgeHttp(app).handle( | |
| 311 | new Request("http://forge.test/api/v1/games/agent/sync", { | |
| 312 | method: "POST", | |
| 313 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 314 | body: JSON.stringify({ agent: 1, light: true, told: true, got: [], ask: [read] }), | |
| 315 | }), | |
| 316 | ); | |
| 317 | const { told } = (await res.json()) as { told?: { id: string; text: string }[] }; | |
| 318 | expect(told?.map((t) => t.id)).toEqual([read.id]); | |
| 319 | expect(told![0]!.text).toBe("hub: running, 1 player"); | |
| 320 | // Handed again until the box says it has it: nothing of it is left for the next test. | |
| 321 | app.db.query("DELETE FROM game_told").run(); | |
| 322 | }); | |
| 323 | ||
| 304 | 324 | test("what does not have the plugin's shape is dropped; a server that is not the network's is told", async () => { |
| 305 | 325 | expect(await send("x")).toEqual([]); |
| 306 | 326 | expect(await send([null, 1, {}, request("help", { id: "../a" }), request("help", { uuid: "u" }), request("help", { name: "a b" })])).toEqual([]); |
new above
offline