Public: anyone can read this; the crew can change it.
Games: the forge keeps a SQLite snapshot of what /forge answers alone, and the agent puts it on the proxy #18150
Merged 15h 28m ago, live in production
sold/forge-desk-snapshot → main 0 commits
9 files
changed +376
−12
docs/features/games.md +6
| @@ -104,6 +104,12 @@ The sync only checks and keeps a command (`game_chat_job`); a plan, a commit or | ||
| 104 | 104 | |
| 105 | 105 | **Through the proxy (`/forge`, #17610).** The forge's side of a command on the proxy itself (`src/games/door.ts`); a box has it once its proxy has the plugin. A request comes in the sync's `ask` (`{ id, uuid, name, server, words, confirms? }`, at most 20) and its answers go back in `told` (`{ n, id, uuid, text, confirm }`, at most 20, dropped after an hour); a quick poll (`light`) that says `told: true` gets them too. An agent that sends `got`, the numbers `n` it has (an empty list too), is handed each answer until it has it, and skips a number it had; one that never sends it, each once. A question's three minutes count from its first handing out: after the first of them it is handed out again only as words to ask again. It runs the same rules as `!forge`: the link, the role and the limits; the UUID is the proxy's own. Each request is kept once by its `id` for a day, so one sent again does nothing. Whenever the sync carries `ask`, the answer's `asked` lists the ids the forge took, now or before; the agent deletes those and sends the rest again. Not taken: past the first 20, or no compose file could be read. One that names no player cannot be answered: it is taken, and the forge's log counts it. |
| 106 | 106 | |
| 107 | **How long a `/forge` answer takes (#18028).** Typing, then the answer on screen, went: the plugin writes a file (milliseconds); the agent's watcher notices it (up to half a second, now a fifth); the agent's next quick poll carries it (up to a second, now the moment the proxy says a request came, never sooner than a tenth of a second after the last poll, and only while the proxy runs and the last poll got an answer); the forge answers (a few milliseconds for a read or a question) but, before, only at the poll after that (up to a second more); the agent puts the answer in the proxy's inbox (a `docker exec`, about 0.2 s); the plugin looks (once a second, now five times a second). A sync that carries a request (quick or full) now waits up to 250 ms for the answers to it, so a read or a question that is done by then rides the same reply; a sync with no request is never held, and a plan or the crew's answer is never waited for. A crew answer shows "thinking…" at once, in the action bar. | |
| 108 | ||
| 109 | **The snapshot (#18028).** An agent that says `desk: { v }` in a quick poll (`v` is the version it has, "" for none) is sent `desk: { v, db }` when the forge has a different one: `db` is a SQLite file in base64 (`src/games/desk_snapshot.ts`), made at most every 15 seconds and only while a linked player is on a server. The version is a hash of the content with the minute, so an unchanged file is sent again once a minute, not every poll; the agent records the version it was offered whether or not it could put the file in place, so one it cannot is not sent over and over. The agent puts the file whole at `plugins/forge/snapshot.db` in the proxy's container (readable by its owner and group only), and the plugin answers from it with no round trip: for each linked player on a server, the words `help`, `status`, `servers`, `who is on`, `what is the address`, `why could i not join`, and for each server they see `what does <server> need` and `is <server> asleep`, with the very answer the forge would give that account (`answer(uuid, words, text, ttl)`). Each answer is good for two minutes after the file was put in place, counted by the box's own clock, so the forge's and the box's clocks never have to agree; after that the word goes to the forge. An answer is therefore as old as the file: up to 15 seconds when it was made, a second to arrive, and never used past two minutes after it arrived. A role taken away, or an account made inactive, keeps its answers for as long: about two minutes and a quarter at the most. The file is at most 1.5 MB of base64 (`SNAPSHOT_MAX_B64`, also the agent's limit): when the players on a network would make it larger, the last ones ask the forge as before. The reader is `Snapshot.java` in the plugin, the repository trevato/forge-velocity, whose key for a word is the one in `snapshotKey`. Other wording goes to the forge. What an account may see is decided when the file is made; a command answered from the file is not in the forge's command log. | |
| 110 | ||
| 111 | A player is known by the UUID the proxy authenticated. That holds where the proxy runs in online mode (the default) and Bedrock players come in through Floodgate; in an offline-mode network anyone can join under a linked name and get that UUID, for `/forge` and `!forge` alike, and the plugin adds no check of its own. | |
| 112 | ||
| 107 | 113 | A server can show text whose click runs a command as the player, so a request that links a name, builds or drops a plan, or asks the crew changes nothing: it is answered with `confirm: true`, and the proxy shows the player a one-time code. Only a later request whose `confirms` names it acts, from the same UUID on the same box, once, within three minutes of the answer going to the box (the code itself lives two). A plan is built only at the door it was asked at: a `!forge yes` in chat never builds a plan made through the proxy, nor the other way round. Questions, help and the making of a plan need no code. |
| 108 | 114 | |
| 109 | 115 | How the forge hears chat: the agent reads each server's `logs/latest.log` and sends only new lines that carry `!forge`. Only the server's own chat line counts: Paper's `[Async Chat Thread - #N/INFO]: <Name> …` and Fabric's `[Server thread/INFO] (Minecraft) <Name> …` (or vanilla's `[Server thread/INFO]: <Name> …`). `/say` (`[Name] …`), `/me` (`* Name …`), tellraw (not logged) and a plugin's broadcast (logged on the server thread or under the plugin's name) do not match. |
src/games/agent.sh +24 −2
| @@ -1544,6 +1544,27 @@ desk_asks() { | ||
| 1544 | 1544 | jq -c '[.[].ask | objects |
| 1545 | 1545 | | with_entries(select((.key == "at" and (.value | type) == "number") or ((.key | IN("id", "uuid", "name", "server", "words", "confirms")) and (.value | type) == "string")))]' <<<"$rows" 2>/dev/null |
| 1546 | 1546 | } |
| 1547 | # The forge's snapshot of what /forge may answer without a model (#18028): a SQLite file the plugin opens, | |
| 1548 | # made whole in the proxy's plugin folder, and the version of the one this box has, sent in each quick poll so | |
| 1549 | # the forge sends a new one only when its content changes (and once a minute). A version is recorded whether or | |
| 1550 | # not it was put in place, so one that cannot be is not sent again every poll; the next differs. Nothing of it | |
| 1551 | # is run; the plugin only reads it, and only its owner and group may. | |
| 1552 | desk_snapshot() { | |
| 1553 | local v db | |
| 1554 | desk_here || return 0 | |
| 1555 | v="$(jq -r '(.desk.v // "") | select(test("\\A[0-9a-z]{1,20}\\z"))' <<<"" 2>/dev/null)" || return 0 | |
| 1556 | [ -n "" ] || return 0 | |
| 1557 | # At most 1500000 bytes of base64 (the forge's SNAPSHOT_MAX_B64): one byte more is read to see that it is over, and then nothing is installed. | |
| 1558 | db="$(jq -r '.desk.db // empty' <<<"" | head -c 1500001)" | |
| 1559 | if [ "" -le 1500000 ]; then | |
| 1560 | # shellcheck disable=SC2016 # the script runs in the container's own shell | |
| 1561 | printf '%s' "" | desk outbox 'umask 027; base64 -d >../snapshot.tmp && [ -s ../snapshot.tmp ] && mv -f ../snapshot.tmp ../snapshot.db' | |
| 1562 | else | |
| 1563 | echo "forge-game-agent: the proxy's snapshot is over its limit; not installed" >&2 | |
| 1564 | fi | |
| 1565 | printf '%s' "" >"/.desk.v" | |
| 1566 | return 0 | |
| 1567 | } | |
| 1547 | 1568 | # Of the requests this sync carried, those the answer's `asked` names are deleted. An older forge |
| 1548 | 1569 | # names none: they stay, and the plugin itself stops at 64 waiting. |
| 1549 | 1570 | desk_asked() { |
| @@ -2148,12 +2169,13 @@ light_sync() { | ||
| 2148 | 2169 | # A mark with no proxy to carry it is stale: it goes, so it cannot cut a wait short. |
| 2149 | 2170 | if [ -f "/.desk.due" ] && desk_here; then desk_take; else rm -f "/.desk.due"; echo '[]' >"/.sync.ask"; fi |
| 2150 | 2171 | json_or '[]' <"/.results" >"/.sync.results" |
| 2151 | 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)" \ | |
| 2152 | '{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 | |
| 2172 | 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)" --arg deskv "$(cat "/.desk.v" 2>/dev/null)" \ | |
| 2173 | '{agent: 1, light: true, composeSha: $sha, results: $results[0], got: $got} + (if $told then {told: true, desk: {v: $deskv}} else {} end) + (if $ask[0] == [] then {} else {ask: $ask[0]} end)' >"/.sync.light" || return 1 | |
| 2153 | 2174 | answer="$(curl -fsS -m 5 -H "@" -H 'content-type: application/json' --data-binary "@/.sync.light" "/api/v1/games/agent/sync")" || { desk_again; return 1; } |
| 2154 | 2175 | echo '[]' >"/.results" |
| 2155 | 2176 | desk_heard "/.sync.light" |
| 2156 | 2177 | desk_told "" |
| 2178 | desk_snapshot "" | |
| 2157 | 2179 | desk_asked "" |
| 2158 | 2180 | apply "" |
| 2159 | 2181 | # Something ran: its result goes in now. Nothing ran: the next poll is a second away. |
src/games/chat.ts +9 −6
| @@ -38,7 +38,7 @@ import { readLines, readOf } from "./forge_read.ts"; | ||
| 38 | 38 | import { commitServer, planServer, wishOn } from "./presets.ts"; |
| 39 | 39 | import { peopleOf } from "./people.ts"; |
| 40 | 40 | import { proxyOf } from "./sleep.ts"; |
| 41 | import { LINES_OUT, listBoxes, mayDo, roleOn, SERVICE_NAME, type GameBox } from "./store.ts"; | |
| 41 | import { LINES_OUT, listBoxes, mayDo, roleOn, SERVICE_NAME, type GameBox, type Role } from "./store.ts"; | |
| 42 | 42 | |
| 43 | 43 | export const CODE_MS = 10 * 60_000; |
| 44 | 44 | /** Said where `newLinkCode` gives none. */ |
| @@ -228,6 +228,13 @@ const OPERATOR_HELP = [ | ||
| 228 | 228 | "!forge no: drops a plan. !forge link <code>: links this name (a code from your forge settings).", |
| 229 | 229 | ]; |
| 230 | 230 | |
| 231 | /** What `help` says to someone with `role`; through the proxy it names the two reads too. */ | |
| 232 | export const helpLines = (role: Role | undefined, proxy: boolean): string[] => [ | |
| 233 | ...(proxy ? [`!forge status: the forge and its crew.${mayDo(role, "viewer") ? " !forge servers: the servers you may see." : ""}`] : []), | |
| 234 | ...(mayDo(role, "viewer") ? ["Ask: who is on? why could I not join? what does survival need? is survival asleep? what is the address?"] : []), | |
| 235 | ...(mayDo(role, "operator") ? OPERATOR_HELP : []), | |
| 236 | ]; | |
| 237 | ||
| 231 | 238 | /** Words that ask for a new server: a level, a plugin we know, or the word itself. */ |
| 232 | 239 | const asksForServer = (words: string): boolean => /\b(void|flat|superflat|skyblock|world|server|fawe|worldedit|bedwars)\b/i.test(words); |
| 233 | 240 | |
| @@ -475,11 +482,7 @@ function one( | ||
| 475 | 482 | db, |
| 476 | 483 | box, |
| 477 | 484 | at, |
| 478 | [ | |
| 479 | ...(door === undefined ? [] : [`!forge status: the forge and its crew.${mayDo(role, "viewer") ? " !forge servers: the servers you may see." : ""}`]), | |
| 480 | ...(mayDo(role, "viewer") ? ["Ask: who is on? why could I not join? what does survival need? is survival asleep? what is the address?"] : []), | |
| 481 | ...(mayDo(role, "operator") ? OPERATOR_HELP : []), | |
| 482 | ], | |
| 485 | helpLines(role, door !== undefined), | |
| 483 | 486 | user.id, |
| 484 | 487 | ); |
| 485 | 488 | } |
src/games/desk_snapshot.ts added +153
| @@ -0,0 +1,153 @@ | ||
| 1 | /** | |
| 2 | * What the proxy's plugin may answer without asking the forge (#18028): for each linked player who | |
| 3 | * is on a server now, the words the forge answers without a model (help, status, servers, who is on, | |
| 4 | * the address, why a join failed, what a server needs, whether it sleeps) and the very answer it | |
| 5 | * would give, as the account's own rights make it. A small SQLite file the box's agent puts in the | |
| 6 | * proxy's plugin folder whole; each answer is good for two minutes after the file was put there (by the | |
| 7 | * box's own clock), so a box the forge cannot reach goes on asking the forge and shows nothing much out | |
| 8 | * of date. An answer is as old as the file: up to 15 seconds when made, a second to arrive, and then | |
| 9 | * never used past two minutes. | |
| 10 | * | |
| 11 | * The plugin only looks a word up. What a player may see is decided here, once, when the file is | |
| 12 | * made; a word the file lacks goes to the forge as it always did. | |
| 13 | */ | |
| 14 | ||
| 15 | import { Database } from "bun:sqlite"; | |
| 16 | import type { App } from "../app.ts"; | |
| 17 | import { getUserById, isActive } from "../core/users.ts"; | |
| 18 | import { answerTo, questionOf, serversSeen } from "./ask.ts"; | |
| 19 | import { composeServices, readCompose } from "./compose.ts"; | |
| 20 | import { helpLines } from "./chat.ts"; | |
| 21 | import { readLines } from "./forge_read.ts"; | |
| 22 | import { peopleOf } from "./people.ts"; | |
| 23 | import { proxyOf } from "./sleep.ts"; | |
| 24 | import { mayDo, roleOn, type GameBox } from "./store.ts"; | |
| 25 | ||
| 26 | /** How long an answer in the file is good for once it is in place, and how often the file is made again. */ | |
| 27 | export const SNAPSHOT_TTL_MS = 120_000; | |
| 28 | /** The most base64 the agent takes (`desk_snapshot` in agent.sh refuses more): the forge never makes a file over it. */ | |
| 29 | export const SNAPSHOT_MAX_B64 = 1_500_000; | |
| 30 | const REMAKE_MS = 15_000; | |
| 31 | /** The version changes with the content, and at least this often, so the file is put in place again before its answers run out. */ | |
| 32 | const RESEND_MS = 60_000; | |
| 33 | const MOST_PLAYERS = 100; | |
| 34 | const MAKE_LIMIT_MS = 20_000; | |
| 35 | const bare = (uuid: string): string => uuid.toLowerCase().replaceAll("-", ""); | |
| 36 | /** | |
| 37 | * The plugin's own key for words: lower case, one space, no ending mark. It is `Snapshot.key` in the | |
| 38 | * plugin (trevato/forge-velocity, `Snapshot.java`), and the two must agree: a word is looked up by it. | |
| 39 | */ | |
| 40 | export const snapshotKey = (words: string): string => words.trim().toLowerCase().replace(/\s+/g, " ").replace(/[?!. ]+$/, ""); | |
| 41 | ||
| 42 | export interface Made { | |
| 43 | /** Changes with every making: an agent that has this one is sent nothing. */ | |
| 44 | readonly v: string; | |
| 45 | readonly b64: string; | |
| 46 | } | |
| 47 | ||
| 48 | interface Kept { | |
| 49 | made: Made | undefined; | |
| 50 | at: number; | |
| 51 | making: boolean; | |
| 52 | } | |
| 53 | const kept = new WeakMap<App, Map<string, Kept>>(); | |
| 54 | ||
| 55 | /** The latest file for `box`; made again in the background when it is old. Undefined until the first is made, or when nobody linked is on. */ | |
| 56 | export function snapshotFor(app: App, box: GameBox, origin: string, now = Date.now()): Made | undefined { | |
| 57 | let boxes = kept.get(app); | |
| 58 | if (boxes === undefined) kept.set(app, (boxes = new Map())); | |
| 59 | let k = boxes.get(box.id); | |
| 60 | if (k === undefined) boxes.set(box.id, (k = { made: undefined, at: 0, making: false })); | |
| 61 | if (!k.making && now - k.at >= REMAKE_MS) { | |
| 62 | const mine = k; | |
| 63 | mine.making = true; | |
| 64 | mine.at = now; | |
| 65 | // A making that hangs (a slow read) lets go after its limit, so a new one can start. | |
| 66 | void Promise.race([make(app, box, origin, now), Bun.sleep(MAKE_LIMIT_MS).then(() => undefined)]) | |
| 67 | .then((m) => (mine.made = m)) | |
| 68 | .catch((e: unknown) => app.log.warn("the snapshot for /forge could not be made", { box: box.name, error: String(e) })) | |
| 69 | .finally(() => (mine.making = false)); | |
| 70 | } | |
| 71 | return k.made; | |
| 72 | } | |
| 73 | ||
| 74 | /** The rows one player gets: [words, answer]. */ | |
| 75 | async function rowsFor(app: App, box: GameBox, compose: string, origin: string, userId: string, service: string, player: string, now: number): Promise<[string, string][]> { | |
| 76 | const user = getUserById(app.db, userId); | |
| 77 | if (user === undefined || !isActive(user)) return []; | |
| 78 | const text = (lines: readonly string[]): string => lines.join("\n").replaceAll("!forge", "/forge").slice(0, 2_000); | |
| 79 | const role = roleOn(app.db, user, box.id, service); | |
| 80 | const rows: [string, string][] = [["help", text(helpLines(role, true))]]; | |
| 81 | const [status, servers] = await Promise.all([readLines(app, user, box, compose, origin, "status"), readLines(app, user, box, compose, origin, "servers")]); | |
| 82 | rows.push(["status", text(status)], ["servers", text(servers)]); | |
| 83 | if (!mayDo(role, "viewer")) return rows; | |
| 84 | const seen = serversSeen(app, user, box, compose); | |
| 85 | const words = ["who is on", "what is the address", "why could i not join", ...seen.flatMap((s) => [`what does ${s} need`, `is ${s} asleep`])]; | |
| 86 | for (const w of words) { | |
| 87 | const q = questionOf(w, service, seen); | |
| 88 | if (q !== undefined) rows.push([snapshotKey(w), text(await answerTo(app, user, box, compose, player, q, new Date(now)))]); | |
| 89 | } | |
| 90 | return rows; | |
| 91 | } | |
| 92 | ||
| 93 | /** The SQLite file for the players linked and on a server of `box` now. */ | |
| 94 | async function make(app: App, box: GameBox, origin: string, now: number): Promise<Made | undefined> { | |
| 95 | const compose = (await readCompose(app, box))?.text; | |
| 96 | if (compose === undefined) return undefined; | |
| 97 | const proxy = proxyOf(compose); | |
| 98 | const links = new Map( | |
| 99 | app.db | |
| 100 | .query<{ uuid: string; user_id: string; player: string }, [string]>("SELECT uuid, user_id, player FROM game_link WHERE box_id = ?1 AND uuid != ''") | |
| 101 | .all(box.id) | |
| 102 | .map((l) => [bare(l.uuid), l] as const), | |
| 103 | ); | |
| 104 | const on: { uuid: string; userId: string; service: string; player: string }[] = []; | |
| 105 | for (const service of composeServices(compose).filter((s) => s !== proxy)) | |
| 106 | for (const p of peopleOf(app.db, box.id, service).online) { | |
| 107 | const link = links.get(bare(p.uuid)); | |
| 108 | if (link !== undefined && !on.some((o) => o.uuid === link.uuid)) on.push({ uuid: link.uuid, userId: link.user_id, service, player: link.player }); | |
| 109 | } | |
| 110 | if (on.length === 0) return undefined; | |
| 111 | const players: PlayerRows[] = []; | |
| 112 | for (const o of on.slice(0, MOST_PLAYERS)) players.push({ uuid: o.uuid, rows: await rowsFor(app, box, compose, origin, o.userId, o.service, o.player, now) }); | |
| 113 | const made = pack(players, now); | |
| 114 | if (made !== undefined && made.players < players.length) | |
| 115 | app.log.warn("the snapshot for /forge holds only some players: the rest ask the forge", { box: box.name, kept: made.players, on: players.length }); | |
| 116 | return made; | |
| 117 | } | |
| 118 | ||
| 119 | export interface PlayerRows { | |
| 120 | readonly uuid: string; | |
| 121 | readonly rows: readonly (readonly [string, string])[]; | |
| 122 | } | |
| 123 | ||
| 124 | /** | |
| 125 | * The SQLite file for `players`, as base64, never over `maxB64`: players are dropped from the end | |
| 126 | * (they ask the forge as before the file) until it fits. Undefined when none fits. | |
| 127 | */ | |
| 128 | export function pack(players: readonly PlayerRows[], now: number, maxB64 = SNAPSHOT_MAX_B64): (Made & { players: number }) | undefined { | |
| 129 | for (let keep = players.slice(0, MOST_PLAYERS); keep.length > 0; keep = keep.slice(0, Math.floor(keep.length / 2))) { | |
| 130 | const made = build(keep, now); | |
| 131 | if (made.b64.length <= maxB64) return { ...made, players: keep.length }; | |
| 132 | } | |
| 133 | return undefined; | |
| 134 | } | |
| 135 | ||
| 136 | function build(players: readonly PlayerRows[], now: number): Made { | |
| 137 | const db = new Database(":memory:"); | |
| 138 | try { | |
| 139 | db.run("CREATE TABLE answer (uuid TEXT NOT NULL, words TEXT NOT NULL, text TEXT NOT NULL, ttl INTEGER NOT NULL, PRIMARY KEY (uuid, words)) WITHOUT ROWID"); | |
| 140 | const put = db.prepare("INSERT OR REPLACE INTO answer (uuid, words, text, ttl) VALUES (?1, ?2, ?3, ?4)"); | |
| 141 | const hash = new Bun.CryptoHasher("sha256"); | |
| 142 | for (const p of players) | |
| 143 | for (const [words, answer] of p.rows) { | |
| 144 | put.run(p.uuid, words, answer, SNAPSHOT_TTL_MS); | |
| 145 | hash.update(`${p.uuid}\0${words}\0${answer}\0`); | |
| 146 | } | |
| 147 | // The content, and the minute: a file unchanged is put in place again once a minute, never every poll. | |
| 148 | const v = `${hash.digest("hex").slice(0, 12)}${Math.floor(now / RESEND_MS).toString(36)}`; | |
| 149 | return { v, b64: Buffer.from(db.serialize()).toString("base64") }; | |
| 150 | } finally { | |
| 151 | db.close(); | |
| 152 | } | |
| 153 | } |
src/games/store.ts +2
| @@ -628,6 +628,8 @@ export interface SyncBody { | ||
| 628 | 628 | readonly boot?: string; |
| 629 | 629 | /** The agent holds the answer's `jars`, checked, before it recreates the proxy. */ |
| 630 | 630 | readonly jars?: unknown; |
| 631 | /** The agent keeps the proxy's snapshot of what /forge answers alone, and says which it has: `{ v }` (`games/desk_snapshot.ts`). */ | |
| 632 | readonly desk?: unknown; | |
| 631 | 633 | /** The sha256 of the token the box made for itself, until the forge has taken it. */ |
| 632 | 634 | readonly tokenSha?: unknown; |
| 633 | 635 | /** What the box sees of itself, about 8 KB (`diag.ts`): kept, replacing the last. */ |
src/http/games_routes.ts +17 −4
| @@ -12,13 +12,14 @@ import { auditShellResults } from "../games/shell.ts"; | ||
| 12 | 12 | import { recordMetrics } from "../games/metrics.ts"; |
| 13 | 13 | import { recordPeople } from "../games/people.ts"; |
| 14 | 14 | import { gameAsk, gameChat, runChat } from "../games/chat.ts"; |
| 15 | import { snapshotFor } from "../games/desk_snapshot.ts"; | |
| 15 | 16 | import { toldGot, toldTo } from "../games/door.ts"; |
| 16 | 17 | import { packChecks } from "../games/pack_check.ts"; |
| 17 | 18 | import { lendAnswer } from "../games/lend.ts"; |
| 18 | 19 | import { recordProxyEvents, tellRefused } from "../games/player_events.ts"; |
| 19 | 20 | import { proxyOf, sleeping } from "../games/sleep.ts"; |
| 20 | 21 | import { jarsOf } from "../games/proxy_jars.ts"; |
| 21 | import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, swapGameBoxToken, type SyncBody } from "../games/store.ts"; | |
| 22 | import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, swapGameBoxToken, type GameBox, type SyncBody } from "../games/store.ts"; | |
| 22 | 23 | import { BODY_CAPS } from "../kernel/body_caps.ts"; |
| 23 | 24 | import { |
| 24 | 25 | gameBoxPage, gameCommandSubmit, gameCrashShare, gameEnvSubmit, gameGrantSubmit, gameLendSubmit, gameServersSubmit, gameJarDownload, gameJarSubmit, gameModInstall, gameModPack, gameModRemove, gameModUpdate, gamePeopleSubmit, gameHead, gameWorldSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gameTakeBackSubmit, gamesPage, |
| @@ -39,7 +40,15 @@ import type { Router } from "./router.ts"; | ||
| 39 | 40 | * waited for; its answer comes at a later poll. |
| 40 | 41 | */ |
| 41 | 42 | const QUICK_MS = 250; |
| 42 | const quickly = (work: Promise<void>): Promise<unknown> => Promise.race([work.catch(() => undefined), Bun.sleep(QUICK_MS)]); | |
| 43 | const quickly = (ctx: Ctx, work: Promise<void>): Promise<unknown> => | |
| 44 | Promise.race([work.catch((e: unknown) => ctx.app.log.warn("the answers to a sync's requests failed", { error: String(e) })), Bun.sleep(QUICK_MS)]); | |
| 45 | ||
| 46 | /** The proxy's snapshot, to an agent that keeps one and has not got the latest (`games/desk_snapshot.ts`). */ | |
| 47 | function deskAnswer(ctx: Ctx, box: GameBox, has: unknown, reply: Record<string, unknown>): void { | |
| 48 | if (typeof has !== "object" || has === null) return; | |
| 49 | const made = snapshotFor(ctx.app, box, ctx.url.origin); | |
| 50 | if (made !== undefined && made.v !== (has as { v?: unknown }).v) reply["desk"] = { v: made.v, db: made.b64 }; | |
| 51 | } | |
| 43 | 52 | |
| 44 | 53 | /** POST /api/v1/games/agent/sync: one pull of a game box's agent (the contract in docs/features/games.md). */ |
| 45 | 54 | export async function gameAgentSync(ctx: Ctx): Promise<Response> { |
| @@ -72,10 +81,11 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> { | ||
| 72 | 81 | // The proxy's `/forge`, as in a full sync: kept once by its id, and answered here where it can be. |
| 73 | 82 | if (Array.isArray(body.ask)) { |
| 74 | 83 | reply["asked"] = gameAsk(ctx.app, box, body.ask, (await readCompose(ctx.app, box))?.text, ctx.url.origin); |
| 75 | await quickly(runChat(ctx.app, box.id)); | |
| 84 | await quickly(ctx, runChat(ctx.app, box.id)); | |
| 76 | 85 | } |
| 77 | 86 | const told = body.told === true ? toldTo(ctx.app.db, box, Date.now(), body.got) : []; |
| 78 | 87 | if (told.length > 0) reply["told"] = told; |
| 88 | deskAnswer(ctx, box, body.desk, reply); | |
| 79 | 89 | return json(reply); |
| 80 | 90 | } |
| 81 | 91 | // Every shell command the box answered, its output with it, into the audit. |
| @@ -99,7 +109,9 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> { | ||
| 99 | 109 | gameChat(ctx.app, box, body.chat, compose?.text, ctx.url.origin, Date.now(), body.chatId); |
| 100 | 110 | // The same through the proxy's `/forge` (`games/door.ts`). |
| 101 | 111 | const asked = gameAsk(ctx.app, box, body.ask, compose?.text, ctx.url.origin); |
| 102 | await quickly(runChat(ctx.app, box.id)); | |
| 112 | // Waited for only when a request came: a sync with none is never held for a job. | |
| 113 | if (Array.isArray(body.ask) && body.ask.length > 0) await quickly(ctx, runChat(ctx.app, box.id)); | |
| 114 | else void runChat(ctx.app, box.id); | |
| 103 | 115 | synced(ctx.app, box.id); |
| 104 | 116 | const reply: Record<string, unknown> = { |
| 105 | 117 | composeSha: compose?.sha ?? "", |
| @@ -121,6 +133,7 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> { | ||
| 121 | 133 | if (Array.isArray(body.ask)) reply["asked"] = asked; |
| 122 | 134 | const told = toldTo(ctx.app.db, box, Date.now(), body.got); |
| 123 | 135 | if (told.length > 0) reply["told"] = told; |
| 136 | deskAnswer(ctx, box, body.desk, reply); | |
| 124 | 137 | // The agent this forge runs: a box whose own differs fetches it (`gameAgentScript`) and restarts |
| 125 | 138 | // before it applies the answer, so never beside commands, which are handed out once. The next |
| 126 | 139 | // answer without one says it. |
test/game-desk-snapshot.test.ts added +49
| @@ -0,0 +1,49 @@ | ||
| 1 | /** | |
| 2 | * The file the forge makes for the proxy's plugin (#18028): never over what the agent takes, one | |
| 3 | * version for one content, and the plugin's own key for words. | |
| 4 | */ | |
| 5 | import { Database } from "bun:sqlite"; | |
| 6 | import { expect, test } from "bun:test"; | |
| 7 | import { pack, snapshotKey, SNAPSHOT_MAX_B64, type PlayerRows } from "../src/games/desk_snapshot.ts"; | |
| 8 | ||
| 9 | const uuid = (n: number): string => `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`; | |
| 10 | const player = (n: number, rows: number, size: number): PlayerRows => ({ | |
| 11 | uuid: uuid(n), | |
| 12 | rows: Array.from({ length: rows }, (_, i) => [`word ${String(i)}`, `${String(n)}:${String(i)} `.padEnd(size, "x")] as const), | |
| 13 | }); | |
| 14 | ||
| 15 | test("a file is never over what the agent takes: players are dropped from the end until it fits", () => { | |
| 16 | // 100 players of 60 rows of 2 KB is 12 MB of text. | |
| 17 | const players = Array.from({ length: 100 }, (_, n) => player(n, 60, 2_000)); | |
| 18 | const made = pack(players, 1_700_000_000_000); | |
| 19 | expect(made).toBeDefined(); | |
| 20 | expect(made!.b64.length).toBeLessThanOrEqual(SNAPSHOT_MAX_B64); | |
| 21 | expect(made!.players).toBeGreaterThan(0); | |
| 22 | expect(made!.players).toBeLessThan(100); | |
| 23 | // The ones kept are the first, whole. | |
| 24 | const db = Database.deserialize(new Uint8Array(Buffer.from(made!.b64, "base64"))); | |
| 25 | expect(db.query("SELECT COUNT(DISTINCT uuid) AS n FROM answer").get()).toEqual({ n: made!.players }); | |
| 26 | expect(db.query("SELECT COUNT(*) AS n FROM answer WHERE uuid = ?1").get(uuid(0))).toEqual({ n: 60 }); | |
| 27 | expect(db.query("SELECT 1 FROM answer WHERE uuid = ?1").get(uuid(99))).toBeNull(); | |
| 28 | db.close(); | |
| 29 | // A limit nothing fits under makes no file. | |
| 30 | expect(pack(players, 1_700_000_000_000, 100)).toBeUndefined(); | |
| 31 | }); | |
| 32 | ||
| 33 | test("a version is the content and the minute: the same answers the same minute are one version", () => { | |
| 34 | const now = 1_700_000_000_000; | |
| 35 | const a = pack([player(1, 5, 50)], now)!; | |
| 36 | expect(pack([player(1, 5, 50)], now + 10_000)!.v).toBe(a.v); | |
| 37 | expect(pack([player(1, 5, 51)], now)!.v).not.toBe(a.v); | |
| 38 | expect(pack([player(1, 5, 50)], now + 61_000)!.v).not.toBe(a.v); | |
| 39 | expect(a.v).toMatch(/^[0-9a-f]{12}[0-9a-z]{1,8}$/); | |
| 40 | }); | |
| 41 | ||
| 42 | test("the key the plugin looks words up by: lower case, one space, no ending mark", () => { | |
| 43 | expect(snapshotKey("Who is ON?")).toBe("who is on"); | |
| 44 | expect(snapshotKey(" what is the\taddress ?! ")).toBe("what is the address"); | |
| 45 | expect(snapshotKey("Is Hub ASLEEP.")).toBe("is hub asleep"); | |
| 46 | expect(snapshotKey("status")).toBe("status"); | |
| 47 | // Only the end loses its marks. | |
| 48 | expect(snapshotKey("why? not")).toBe("why? not"); | |
| 49 | }); |
test/game-desk.test.ts +47
| @@ -174,6 +174,53 @@ 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("the forge's snapshot is put whole beside the folders, and the quick poll says which one the box has", async () => { | |
| 178 | const db = Buffer.from("SQLite format 3\0 the snapshot").toString("base64"); | |
| 179 | const b = made((n) => (n === 2 ? Response.json({ commands: [], desk: { v: "k1abc", db } }) : ok())); | |
| 180 | await b.run(() => b.bodies.filter((x) => x["light"] === true).length >= 3); | |
| 181 | const lights = b.bodies.filter((x) => x["light"] === true); | |
| 182 | expect(lights[0]!["desk"]).toEqual({ v: "" }); | |
| 183 | expect(lights.at(-1)!["desk"]).toEqual({ v: "k1abc" }); | |
| 184 | expect(readFileSync(join(b.desk, "snapshot.db"), "utf8")).toBe("SQLite format 3\0 the snapshot"); | |
| 185 | expect(existsSync(join(b.desk, "snapshot.tmp"))).toBe(false); | |
| 186 | }, 60_000); | |
| 187 | ||
| 188 | deskTest("a snapshot that is not base64 replaces nothing but is said to be had, so it is not sent again every poll; one with no safe version is not", async () => { | |
| 189 | const b = made((n) => (n === 2 ? Response.json({ commands: [], desk: { v: "../x", db: Buffer.from("x").toString("base64") } }) : n === 3 ? Response.json({ commands: [], desk: { v: "k2", db: "!!!" } }) : ok())); | |
| 190 | writeFileSync(join(b.desk, "snapshot.db"), "old"); | |
| 191 | await b.run(() => b.bodies.filter((x) => x["light"] === true).length >= 4); | |
| 192 | expect(readFileSync(join(b.desk, "snapshot.db"), "utf8")).toBe("old"); | |
| 193 | expect(b.bodies.filter((x) => x["light"] === true).at(-1)!["desk"]).toEqual({ v: "k2" }); | |
| 194 | }, 60_000); | |
| 195 | ||
| 196 | deskTest("a snapshot over the limit is not installed, not cut: the version is still said to be had", async () => { | |
| 197 | const b = made((n) => (n === 2 ? Response.json({ commands: [], desk: { v: "k3", db: "A".repeat(1_500_004) } }) : ok())); | |
| 198 | writeFileSync(join(b.desk, "snapshot.db"), "old"); | |
| 199 | await b.run(() => b.bodies.filter((x) => x["light"] === true).length >= 3); | |
| 200 | expect(readFileSync(join(b.desk, "snapshot.db"), "utf8")).toBe("old"); | |
| 201 | expect(b.bodies.filter((x) => x["light"] === true).at(-1)!["desk"]).toEqual({ v: "k3" }); | |
| 202 | expect(b.log()).toContain("over its limit"); | |
| 203 | }, 60_000); | |
| 204 | ||
| 205 | deskTest("a quick poll ends its wait the moment a request comes, not at the next whole second", async () => { | |
| 206 | const b = made((_n, ask) => took(ask)); | |
| 207 | let wrote = 0; | |
| 208 | let saw = 0; | |
| 209 | await b.run( | |
| 210 | () => { | |
| 211 | if (wrote === 0 && b.bodies.filter((x) => x["light"] === true).length >= 2) { | |
| 212 | b.asks(1, 1); | |
| 213 | wrote = Date.now(); | |
| 214 | } | |
| 215 | if (wrote > 0 && saw === 0 && b.bodies.some((x) => x["ask"] !== undefined)) saw = Date.now(); | |
| 216 | return saw > 0; | |
| 217 | }, | |
| 218 | { FORGE_GAME_LIGHT_SLEEP: "3" }, | |
| 219 | ); | |
| 220 | // Waiting out its three seconds would take at least that; the mark ends the wait. | |
| 221 | expect(saw - wrote).toBeLessThan(2_000); | |
| 222 | }, 60_000); | |
| 223 | ||
| 177 | 224 | deskTest("a poll that failed is waited out even with a request waiting: the agent does not spin on a restarting forge", async () => { |
| 178 | 225 | const b = made((_n, ask) => (b.bodies.at(-1)!["light"] === true ? new Response("", { status: 502 }) : took(ask))); |
| 179 | 226 | b.asks(1, 10); |
test/game-door.test.ts +69
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | * request; what changes something or starts crew work acts only on the same player's confirmation |
| 4 | 4 | * of that request, once, in time; and the two doors never answer each other's plans. |
| 5 | 5 | */ |
| 6 | import { Database } from "bun:sqlite"; | |
| 6 | 7 | import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test"; |
| 7 | 8 | import { mkdtemp, rm } from "node:fs/promises"; |
| 8 | 9 | import { tmpdir } from "node:os"; |
| @@ -321,6 +322,74 @@ test("a read taken in a sync is answered in the same reply, not at the next poll | ||
| 321 | 322 | app.db.query("DELETE FROM game_told").run(); |
| 322 | 323 | }); |
| 323 | 324 | |
| 325 | test("the sync hands an agent that keeps one the proxy's snapshot: each linked player's own answers, once per version", async () => { | |
| 326 | app.db | |
| 327 | .query("INSERT OR REPLACE INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, 'ada', ?2, ?3, ?4)") | |
| 328 | .run(box.id, ada.id, ADA, new Date().toISOString()); | |
| 329 | const sync = async (desk: unknown) => { | |
| 330 | const res = await forgeHttp(app).handle( | |
| 331 | new Request("http://forge.test/api/v1/games/agent/sync", { | |
| 332 | method: "POST", | |
| 333 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 334 | body: JSON.stringify({ agent: 1, light: true, told: true, got: [], ...(desk === undefined ? {} : { desk }) }), | |
| 335 | }), | |
| 336 | ); | |
| 337 | return ((await res.json()) as { desk?: { v: string; db: string } }).desk; | |
| 338 | }; | |
| 339 | // An agent that never says it keeps one is sent nothing. | |
| 340 | expect(await sync(undefined)).toBeUndefined(); | |
| 341 | let sent: { v: string; db: string } | undefined; | |
| 342 | await pollUntil(async () => (sent = await sync({ v: "" })) !== undefined, "the snapshot to be made", 10_000); | |
| 343 | const kept = Database.deserialize(new Uint8Array(Buffer.from(sent!.db, "base64"))); | |
| 344 | const row = (words: string) => kept.query<{ text: string; ttl: number }, [string, string]>("SELECT text, ttl FROM answer WHERE uuid = ?1 AND words = ?2").get(ADA, words); | |
| 345 | expect(row("status")!.text).toStartWith("The forge is up"); | |
| 346 | expect(row("servers")!.text).toBe("hub: running, 1 player"); | |
| 347 | expect(row("what is the address")!.text).toContain("play.example.test"); | |
| 348 | expect(row("who is on")!.text).toBe("On hub: ada."); | |
| 349 | expect(row("is hub asleep")!.text).toStartWith("hub is awake"); | |
| 350 | expect(row("help")!.text).toContain("/forge status"); | |
| 351 | expect(row("help")!.text).not.toContain("!forge"); | |
| 352 | expect(row("status")!.ttl).toBe(120_000); | |
| 353 | // Only players linked and on a server have rows. | |
| 354 | expect(kept.query("SELECT DISTINCT uuid FROM answer").all()).toEqual([{ uuid: ADA }]); | |
| 355 | kept.close(); | |
| 356 | // The one the agent has is not sent again, and a later making with the same content has the same version. | |
| 357 | expect(await sync({ v: sent!.v })).toBeUndefined(); | |
| 358 | expect(sent!.v).toMatch(/^[0-9a-f]{12}[0-9a-z]{1,8}$/); | |
| 359 | app.db.query("DELETE FROM game_told").run(); | |
| 360 | }); | |
| 361 | ||
| 362 | test("a full sync answers a read in the same reply, and is never held for a plan that is slow", async () => { | |
| 363 | app.db | |
| 364 | .query("INSERT OR REPLACE INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, 'ada', ?2, ?3, ?4)") | |
| 365 | .run(box.id, ada.id, ADA, new Date().toISOString()); | |
| 366 | anHourOn(); | |
| 367 | let release = () => {}; | |
| 368 | slow = new Promise((r) => (release = r)); | |
| 369 | app.db | |
| 370 | .query("INSERT INTO game_chat_job (box_id, service, player, user_id, kind, words, origin, audit_id, created_at) VALUES (?1, 'hub', 'ada', ?2, 'plan', 'a void world with luckperms', '', 0, ?3)") | |
| 371 | .run(box.id, ada.id, new Date().toISOString()); | |
| 372 | const read = request("servers"); | |
| 373 | try { | |
| 374 | const res = await forgeHttp(app).handle( | |
| 375 | new Request("http://forge.test/api/v1/games/agent/sync", { | |
| 376 | method: "POST", | |
| 377 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 378 | body: JSON.stringify({ agent: 1, ask: [read] }), | |
| 379 | }), | |
| 380 | ); | |
| 381 | const { told } = (await res.json()) as { told?: { id: string; text: string }[] }; | |
| 382 | expect(told?.map((t) => t.id)).toEqual([read.id]); | |
| 383 | expect(told![0]!.text).toBe("hub: running, 1 player"); | |
| 384 | // The reply came with the plan still waiting: it was not what the sync waited for. | |
| 385 | expect(app.db.query("SELECT kind FROM game_chat_job").all()).toEqual([{ kind: "plan" }]); | |
| 386 | } finally { | |
| 387 | release(); | |
| 388 | await pollUntil(() => app.db.query("SELECT 1 FROM game_chat_job").get() === null, "the plan to end", 10_000); | |
| 389 | app.db.query("DELETE FROM game_told").run(); | |
| 390 | } | |
| 391 | }); | |
| 392 | ||
| 324 | 393 | test("what does not have the plugin's shape is dropped; a server that is not the network's is told", async () => { |
| 325 | 394 | expect(await send("x")).toEqual([]); |
| 326 | 395 | expect(await send([null, 1, {}, request("help", { id: "../a" }), request("help", { uuid: "u" }), request("help", { name: "a b" })])).toEqual([]); |
new above
offline