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

opened this

Merged 15h 48m ago, live in production

sold/forge-instant-path → main 0 commits

  • Merged. sold/forge-instant-path was merged into main as e529fa8.

Review

Sign in to review this change.
4 files changed +81 −7
src/games/agent.sh +32 −5
@@ -1384,7 +1384,7 @@ desk() {
13841384 # Whether the proxy runs, as the last full sync's services say: nothing is asked of one that does not.
13851385 desk_here() { jq -e 'any(.[]; .name == "velocity" and .state == "running")' "$DIR/.sync.services" >/dev/null 2>&1; }
13861386 # 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
13881388 # a second, and ends when those end: with this agent, with the proxy, or after an hour; also when none came
13891389 # for 60 s, where the proxy has a shell whose `read` can say so (bash, busybox; dash says 2). Started again
13901390 # then, at most every 10 s. The full sync looks for itself, so nothing depends on it.
@@ -1398,7 +1398,7 @@ desk_watch() {
13981398 [ "$SECONDS" -ge "${DESK_NEXT:-0}" ] || return 0
13991399 DESK_NEXT=$((SECONDS + 10))
14001400 # 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 |
14021402 "${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
14031403 was=""; t="-t 60"; read $t _ </dev/null; [ $? != 2 ] || t=""
14041404 while read -r $t _; do
@@ -2037,7 +2037,8 @@ light_sync() {
20372037 job_tick
20382038 shell_tick
20392039 POLLED="$SECONDS"
2040 if [ -f "$DIR/.desk.due" ] && desk_here; then desk_take; else echo '[]' >"$DIR/.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 "$DIR/.desk.due" ] && desk_here; then desk_take; else rm -f "$DIR/.desk.due"; echo '[]' >"$DIR/.sync.ask"; fi
20412042 json_or '[]' <"$DIR/.results" >"$DIR/.sync.results"
20422043 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)" \
20432044 '{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
@@ -2051,18 +2052,44 @@ light_sync() {
20512052 [ "$(jq 'length' "$DIR/.results" 2>/dev/null || echo 0)" = 0 ] && return 0
20522053 done
20532054 }
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 "$DIR/.desk.due" ] && [ "$LIGHT_OK" = 1 ] && desk_here; then
2066 EARLY=1
2067 sleep 0.1
2068 return 0
2069 fi
2070 [[ "$LIGHT_SLEEP" =~ ^[1-9][0-9]{0,2}$ ]] || { sleep "$LIGHT_SLEEP"; return 0; }
2071 for ((i = 0; i < LIGHT_SLEEP * 10; i++)); do
2072 sleep 0.1
2073 if [ -e "$DIR/.desk.due" ] && [ "$LIGHT_OK" = 1 ] && desk_here; then
2074 EARLY=1
2075 return 0
2076 fi
2077 done
2078 }
20542079 # The wait between full syncs, spent polling lightly.
20552080 wait_polling() {
20562081 local waited=0
20572082 while [ "$waited" -lt "$EVERY" ]; do
2058 sleep "$LIGHT_SLEEP"
2059 waited=$((waited + LIGHT_EVERY))
2083 nap
2084 [ "$EARLY" = 1 ] || waited=$((waited + LIGHT_EVERY))
20602085 # A failed poll (the forge is down or restarting) ends no wait early: the rest of EVERY is
20612086 # waited out, so a full sync never follows at once and boxes do not all come back together.
20622087 if ! light_sync; then
2088 LIGHT_OK=0
20632089 [ "$waited" -lt "$EVERY" ] && sleep $((EVERY - waited))
20642090 return 0
20652091 fi
2092 LIGHT_OK=1
20662093 done
20672094 }
20682095
src/http/games_routes.ts +10 −2
@@ -29,6 +29,14 @@ import { InvalidJson } from "./json_body.ts";
2929 import { apiError, boundedMachineBody, json } from "./respond.ts";
3030 import type { Router } from "./router.ts";
3131
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
3240 /** POST /api/v1/games/agent/sync: one pull of a game box's agent (the contract in docs/features/games.md). */
3341 export async function gameAgentSync(ctx: Ctx): Promise<Response> {
3442 const auth = ctx.request.headers.get("authorization") ?? "";
@@ -58,7 +66,7 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
5866 // The proxy's `/forge`, as in a full sync: kept once by its id, and answered here where it can be.
5967 if (Array.isArray(body.ask)) {
6068 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));
6270 }
6371 const told = body.told === true ? toldTo(ctx.app.db, box, Date.now(), body.got) : [];
6472 if (told.length > 0) reply["told"] = told;
@@ -85,7 +93,7 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
8593 gameChat(ctx.app, box, body.chat, compose?.text, ctx.url.origin, Date.now(), body.chatId);
8694 // The same through the proxy's `/forge` (`games/door.ts`).
8795 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));
8997 synced(ctx.app, box.id);
9098 const reply: Record<string, unknown> = {
9199 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
174174 expect(b.inbox()).toHaveLength(64);
175175 }, 60_000);
176176
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
177196 deskTest("an answer that comes with the quick poll is put in the inbox too", async () => {
178197 const told = [{ id: "r1", uuid: uuid(1), text: "hi", confirm: false }];
179198 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
301301 expect((await readCompose(app, box))!.text).not.toContain("theirs");
302302 }, 30_000);
303303
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
304324 test("what does not have the plugin's shape is dropped; a server that is not the network's is told", async () => {
305325 expect(await send("x")).toEqual([]);
306326 expect(await send([null, 1, {}, request("help", { id: "../a" }), request("help", { uuid: "u" }), request("help", { name: "a b" })])).toEqual([]);

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

Keyboard shortcuts

Docs