Public: anyone can read this; the crew can change it.
A map file over 600 KB is served in parts instead of failing the whole 3D view #18350
Merged 27m ago, live in production
scout/forge:scout/18344-a-map-file-over-600-kb-is-served-in-part → main 0 commits fork 3 threads · 3 unresolved
6 files
changed +193
−22
docs/features/game-map.md +3 −3
| @@ -7,13 +7,13 @@ row: Game live map | ||
| 7 | 7 | A game server's BlueMap, a live 3D map with its players, is served by the forge behind login at |
| 8 | 8 | `/games/<box>/<server>/map` (#18087, step 2a of #18059). The box publishes no port for it. |
| 9 | 9 | |
| 10 | - **The choice, a relay and not static files:** BlueMap's web server listens on the box's own loopback (`127.0.0.1:8100`) and the box's agent, which only ever calls out, fetches each file the forge asks for (`src/games/map.ts`, `kind: map`, the path as text) at its next light check-in (a second or two) and answers it as `<gzip 0|1>` and base64, 600 KB of file at most. The forge serves it and deletes the row: no tile is kept in the database. Static files would need the agent to upload a world's tiles, a second unbounded copy of the world on the forge, and would have no live players layer. The cost is a check-in's wait on a first look; the browser keeps a file for a minute. | |
| 10 | - **The choice, a relay and not static files:** BlueMap's web server listens on the box's own loopback (`127.0.0.1:8100`) and the box's agent, which only ever calls out, fetches each file the forge asks for (`src/games/map.ts`, `kind: map`, the path as text) at its next light check-in (a second or two) and answers it as `<gzip 0|1>[ total]` and base64, 512000 bytes at a time: a bigger file is asked again in slices (`path#from-to`, `curl -r`) and joined, up to 8 MiB (`FORGE_GAME_MAP_MOST`; past it a 413 saying so). The forge serves it and deletes the row: no tile is kept in the database. Static files would need the agent to upload a world's tiles, a second unbounded copy of the world on the forge, and would have no live players layer. The cost is a check-in's wait on a first look; the browser keeps a file for a minute. | |
| 11 | 11 | - **Set BlueMap up:** install it from the server's Mods block, then in its config: webserver `ip: "127.0.0.1"`, `port: 8100` (the agent reads `FORGE_GAME_MAP_PORT` for another), and in `core.conf` `render-thread-count: 1`, so rendering takes one thread of a shared box. Publish nothing. |
| 12 | 12 | - **Use it, on the page:** the server's page has a "Live map" block, one sentence and an "Open the map" button. Reading needs a viewer's grant on the server, as its console does; a person without one, or signed out, gets the sign-in or a 404. The setup above is shown nowhere on the page: BlueMap not listening is a 502 that names what to set. |
| 13 | 13 | - **Use it, in the terminal:** `w` on a service's screen opens `src/tui/screens/game_map.ts`: the same sentence and the map's address, and `p` asks the box for the map's front page and says whether it answered. |
| 14 | - **What is refused:** a path with `..`, `//`, a leading dot, a query, or an extension the map does not use (`html js css json png jpg webp svg ico woff2 txt prbm gz bin wasm`); at most 64 files waiting on one box and 24 on one person; no answer in 12 s is a 504 saying the box is asleep or its agent has not checked in; the agent says which way a fetch failed and the forge words each: `refused` (not listening, a 502 that names what to set), `toobig` (over 600 KB, 502), `slow` (over 10 s, 504), `status NNN` (BlueMap refused it, 502; 404 is a 404). An older agent's bare `status 000` still gets the not-listening sentence. | |
| 14 | - **What is refused:** a path with `..`, `//`, a leading dot, a query, or an extension the map does not use (`html js css json png jpg webp svg ico woff2 txt prbm gz bin wasm`); at most 64 files waiting on one box and 24 on one person; no answer in 12 s is a 504 saying the box is asleep or its agent has not checked in; the agent says which way a fetch failed and the forge words each: `refused` (not listening, a 502 that names what to set), `toobig` (a server that ignores ranges and sends over 600 KB, 502), `slow` (over 10 s, 504), `unsized` (a part without the whole file's size, 502), `status NNN` (BlueMap refused it, 502; 404 is a 404). An older agent's bare `status 000` still gets the not-listening sentence. | |
| 15 | 15 | - **What the map's scripts may do, nothing of the viewer's:** the files are the box owner's, scripts included, so they never run with the forge's session. `/map` is the one door that reads the cookie; it buys a pass (`src/games/map_token.ts`: person, server and the hour it ends, signed with the forge's key) and redirects to `/games/<box>/<server>/m/<pass>/`. Every file under it answers from the pass alone, with `sandbox allow-scripts` in its policy: the document has no origin, sends no cookie, and a call to the forge's API from it is a stranger's. Its files are read by CORS without credentials. The pass lasts an hour, a grant taken back ends it at the next file, and the policy lets the scripts talk only to the map's own path. |
| 16 | - **How it holds up:** a first look asks a few dozen files; the agent hands back up to eight a tick (about 1.2 MB at most in one sync, under the 2 MiB cap) and the box's own commands are handed before any map file, so a pan never waits in front of a stop. It has been run against faked answers only, not a live BlueMap; the 64 and 24 are judgments to tune with one. | |
| 16 | - **How it holds up:** a file of 8 MiB is 17 slices asked one after another, each waiting up to 12 s, so one request can hold a connection and up to 8 MiB in memory for minutes, and one person can have 24 of them; a slice that comes back longer than asked, or a part that does not say the whole file's size, is refused rather than served. A first look asks a few dozen files; the agent hands back up to eight a tick (about 1.2 MB at most in one sync, under the 2 MiB cap) and the box's own commands are handed before any map file, so a pan never waits in front of a stop. It has been run against faked answers only, not a live BlueMap; the 64 and 24 are judgments to tune with one. | |
| 17 | 17 | |
| 18 | 18 | ## Whether it answers, before you open it |
| 19 | 19 |
src/games/agent.sh +34 −9
| @@ -1145,22 +1145,37 @@ shell_tick() { | ||
| 1145 | 1145 | } |
| 1146 | 1146 | |
| 1147 | 1147 | # ---- the live map (#18087): the forge asks for one file of BlueMap's web root (`kind: map`, the |
| 1148 | # path as text); it is fetched from the box's own loopback (no published port), 600 KB at most, | |
| 1149 | # and answered as `<gzip 0|1>\n<base64>` at the next tick. A path is checked again here. ---- | |
| 1148 | # path as text); it is fetched from the box's own loopback (no published port), a 512000-byte slice | |
| 1149 | # at a time (`path#from-to`; the first answer says the total), and answered as `<gzip 0|1>[ total]\n<base64>` at the next tick. A path is checked again here. ---- | |
| 1150 | 1150 | |
| 1151 | 1151 | MAPS="/.map" |
| 1152 | 1152 | map_start() { |
| 1153 | local id="$1" path="$2" | |
| 1153 | local id="$1" path="$2" from=0 to=511999 | |
| 1154 | 1154 | [[ "" =~ ]] || return |
| 1155 | # `path#from-to` is a slice of a big file; a bare path is its first slice. | |
| 1156 | if [[ "" =~ ^([^#]*)#([0-9]{1,12})-([0-9]{1,12})$ ]]; then | |
| 1157 | path="" from="" to="" | |
| 1158 | if [ "" -lt "" ] || [ -ge 600000 ]; then | |
| 1159 | keep_result "" false "refused: not a slice" | |
| 1160 | return | |
| 1161 | fi | |
| 1162 | fi | |
| 1155 | 1163 | if ! [[ "" =~ ^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$ ]] || [[ "" == *..* ]] || [[ "" == *//* ]]; then |
| 1156 | 1164 | keep_result "" false "refused: not a map file" |
| 1157 | 1165 | return |
| 1158 | 1166 | fi |
| 1159 | 1167 | mkdir -p "" |
| 1160 | 1168 | ( |
| 1161 | code="$(curl -sS -m 10 --max-filesize 600000 -D "/.head" -o "/.body" -w '%{http_code}' "http://127.0.0.1:/" 2>/dev/null)" | |
| 1169 | url="http://127.0.0.1:/" | |
| 1170 | code="$(curl -sS -m 10 --max-filesize 600000 -r "-" -D "/.head" -o "/.body" -w '%{http_code}' "" 2>/dev/null)" | |
| 1171 | rc= | |
| 1172 | # An empty file has no first byte to ask for: many servers answer 416, and it is asked again whole. | |
| 1173 | if [ "" = 416 ] && [ "" = 0 ]; then | |
| 1174 | code="$(curl -sS -m 10 --max-filesize 600000 -D "/.head" -o "/.body" -w '%{http_code}' "" 2>/dev/null)" | |
| 1175 | rc= | |
| 1176 | fi | |
| 1162 | 1177 | # Why it failed, as a word the forge maps: curl 7 refused, 63 over the cap, 28 the timeout. |
| 1163 | case in | |
| 1178 | case in | |
| 1164 | 1179 | 0) ;; |
| 1165 | 1180 | 7) code=refused ;; |
| 1166 | 1181 | 63) code=toobig ;; |
| @@ -1172,7 +1187,7 @@ map_start() { | ||
| 1172 | 1187 | |
| 1173 | 1188 | # Each tick: every fetch that ended becomes a result; a few at a time so a sync stays small. |
| 1174 | 1189 | map_tick() { |
| 1175 | local f id rc gz ok n=0 sent=0 est | |
| 1190 | local f id rc gz ok total n=0 sent=0 est | |
| 1176 | 1191 | for f in ""/*.rc; do |
| 1177 | 1192 | [ -e "" ] || continue |
| 1178 | 1193 | [ "" -lt 8 ] || break |
| @@ -1186,13 +1201,23 @@ map_tick() { | ||
| 1186 | 1201 | rc="$(cat "")" |
| 1187 | 1202 | gz=0 |
| 1188 | 1203 | grep -qi '^content-encoding: *gzip' "/.head" 2>/dev/null && gz=1 |
| 1189 | if [ "" = 200 ]; then | |
| 1204 | if [ "" = 200 ] || [ "" = 206 ]; then | |
| 1190 | 1205 | ok=true |
| 1191 | { printf '%s\n' ""; base64 -w0 "/.body"; } >"/.out" | |
| 1206 | # A part says the whole file's size (Content-Range: bytes a-b/total); a whole file says nothing. | |
| 1207 | total="$(sed -nE 's/^[Cc]ontent-[Rr]ange: *bytes [0-9]+-[0-9]+\/([0-9]+).*/\1/p' "/.head" 2>/dev/null | tail -n1 | tr -d '\r')" | |
| 1208 | if [ "" = 206 ]; then | |
| 1209 | # A part that does not say how big the file is could be a cut-off one: never served as whole. | |
| 1210 | if [ -n "" ]; then gz=" "; else ok=false; fi | |
| 1211 | fi | |
| 1212 | if [ "" = true ]; then | |
| 1213 | { printf '%s\n' ""; base64 -w0 "/.body"; } >"/.out" | |
| 1214 | else | |
| 1215 | printf 'unsized' >"/.out" | |
| 1216 | fi | |
| 1192 | 1217 | else |
| 1193 | 1218 | ok=false |
| 1194 | 1219 | case "" in |
| 1195 | refused | toobig | slow) printf '%s' "" >"/.out" ;; | |
| 1220 | refused | toobig | slow | unsized) printf '%s' "" >"/.out" ;; | |
| 1196 | 1221 | *) printf 'status %s' "" >"/.out" ;; |
| 1197 | 1222 | esac |
| 1198 | 1223 | fi |
src/games/map.ts +56 −9
| @@ -3,8 +3,10 @@ | ||
| 3 | 3 | * (`127.0.0.1:8100`, no published port) and the box's agent relays it. The agent only ever calls |
| 4 | 4 | * out, so a page asks as a command (`kind: "map"`, the text is the path under BlueMap's web root), |
| 5 | 5 | * the agent fetches that file from loopback at its next light check-in (a second or two), and its |
| 6 | * answer is the file: `<gzip 0|1>\n<base64>`. The forge reads it, deletes the row (a tile is never | |
| 7 | * kept in the database) and serves it behind login with the security floor on every response. | |
| 6 | * answer is the file: `<gzip 0|1>[ <total bytes>]\n<base64>`; a file past one slice (MAP_SLICE) is | |
| 7 | * asked again as `path#from-to` and the slices are joined. The forge reads it, deletes the row (a | |
| 8 | * tile is never kept in the database) and serves it behind login with the security floor on every | |
| 9 | * response. | |
| 8 | 10 | * |
| 9 | 11 | * Why a relay and not static files: BlueMap's live layer (players, the day's sun) is a request |
| 10 | 12 | * the browser makes and static copies of a world's tiles would be a second, unbounded store of |
| @@ -51,6 +53,21 @@ export const MAP_WAIT_MS = 12_000; | ||
| 51 | 53 | */ |
| 52 | 54 | export const MAP_PENDING = 64; |
| 53 | 55 | export const MAP_PER_PERSON = 24; |
| 56 | /** | |
| 57 | * One slice of a file: under the 600 KB the agent fetches at once, and its base64 well inside the 2 | |
| 58 | * MiB a sync is read to. | |
| 59 | */ | |
| 60 | const MAP_SLICE = 512_000; | |
| 61 | /** | |
| 62 | * The most of one file the forge joins (a setting: `FORGE_GAME_MAP_MOST`, bytes). Why 8 MiB: the | |
| 63 | * biggest BlueMap files (textures.json, a dense hires tile) are a few MB, and the forge holds a | |
| 64 | * file's slices in memory until it is whole, up to 24 files in flight for one person; past it a | |
| 65 | * file is a 413 that says so, never a part of a file. | |
| 66 | */ | |
| 67 | function mapMost(): number { | |
| 68 | const n = Number(process.env.FORGE_GAME_MAP_MOST); | |
| 69 | return Number.isInteger(n) && n >= MAP_SLICE ? n : 8 * 1024 * 1024; | |
| 70 | } | |
| 54 | 71 | |
| 55 | 72 | /** A file asked for: its path under BlueMap's web root and the type the forge says it is. */ |
| 56 | 73 | export interface MapAsk { |
| @@ -72,16 +89,45 @@ export interface MapFile { | ||
| 72 | 89 | readonly bytes: Uint8Array; |
| 73 | 90 | } |
| 74 | 91 | |
| 75 | /** Ask the box for one file of its map, and wait for the answer; the row is gone either way. */ | |
| 76 | export async function askMap(app: App, box: GameBox, service: string, ask: MapAsk, by: string): Promise<Result<MapFile, { status: number; why: string }>> { | |
| 77 | const { type } = ask; | |
| 92 | type Fail = { status: number; why: string }; | |
| 93 | interface Slice { | |
| 94 | readonly gzip: boolean; | |
| 95 | /** The whole file's size, when the box says the answer is a part of it. */ | |
| 96 | readonly total: number | undefined; | |
| 97 | readonly bytes: Uint8Array; | |
| 98 | } | |
| 99 | ||
| 100 | /** | |
| 101 | * Ask the box for one file of its map, a slice at a time, and join them: each row is gone when | |
| 102 | * read. | |
| 103 | */ | |
| 104 | export async function askMap(app: App, box: GameBox, service: string, ask: MapAsk, by: string): Promise<Result<MapFile, Fail>> { | |
| 105 | const first = await askSlice(app, box, service, ask.path, by); | |
| 106 | if (!first.ok) return first; | |
| 107 | const { gzip, total } = first.value; | |
| 108 | if (total === undefined || total <= first.value.bytes.length) return ok({ type: ask.type, gzip, bytes: first.value.bytes }); | |
| 109 | if (total > mapMost()) return err({ status: 413, why: mapWords.tooLarge(mapMost()) }); | |
| 110 | const parts = [first.value.bytes]; | |
| 111 | let have = first.value.bytes.length; | |
| 112 | while (have < total) { | |
| 113 | const next = await askSlice(app, box, service, `${ask.path}#${have}-${Math.min(have + MAP_SLICE, total) - 1}`, by); | |
| 114 | if (!next.ok) return next; | |
| 115 | if (next.value.bytes.length === 0 || next.value.bytes.length > MAP_SLICE || have + next.value.bytes.length > total || next.value.total !== total) return err({ status: 502, why: "the box's answer was not a file" }); | |
| 116 | parts.push(next.value.bytes); | |
| 117 | have += next.value.bytes.length; | |
| 118 | } | |
| 119 | return ok({ type: ask.type, gzip, bytes: Buffer.concat(parts) }); | |
| 120 | } | |
| 121 | ||
| 122 | /** One command, one row: queued, waited for, read and deleted. */ | |
| 123 | async function askSlice(app: App, box: GameBox, service: string, text: string, by: string): Promise<Result<Slice, Fail>> { | |
| 78 | 124 | const waiting = app.db |
| 79 | 125 | .query<{ n: number; mine: number }, [string, string]>( |
| 80 | 126 | "SELECT count(*) AS n, coalesce(sum(by = ?2), 0) AS mine FROM game_command WHERE box_id = ?1 AND kind = 'map' AND done_at = ''", |
| 81 | 127 | ) |
| 82 | 128 | .get(box.id, by)!; |
| 83 | 129 | if (waiting.n >= MAP_PENDING || waiting.mine >= MAP_PER_PERSON) return err({ status: 503, why: "the map has too many files waiting; try again in a moment" }); |
| 84 | const id = queueCommand(app.db, box.id, service, "map", ask.path, by); | |
| 130 | const id = queueCommand(app.db, box.id, service, "map", text, by); | |
| 85 | 131 | const done = await new Promise<boolean>((resolve) => { |
| 86 | 132 | let off = (): void => {}; |
| 87 | 133 | const finish = (v: boolean): void => { |
| @@ -101,6 +147,7 @@ export async function askMap(app: App, box: GameBox, service: string, ask: MapAs | ||
| 101 | 147 | if (c.ok !== true) { |
| 102 | 148 | if (c.output === "refused") return err({ status: 502, why: mapWords.unreachable }); |
| 103 | 149 | if (c.output === "toobig") return err({ status: 502, why: mapWords.tooBig }); |
| 150 | if (c.output === "unsized") return err({ status: 502, why: mapWords.unsized }); | |
| 104 | 151 | if (c.output === "slow") return err({ status: 504, why: mapWords.slow }); |
| 105 | 152 | const status = /^status (\d{3})/.exec(c.output)?.[1]; |
| 106 | 153 | if (status === "404") return err({ status: 404, why: "not on the map" }); |
| @@ -109,8 +156,8 @@ export async function askMap(app: App, box: GameBox, service: string, ask: MapAs | ||
| 109 | 156 | return err({ status: 502, why: mapWords.refused(status) }); |
| 110 | 157 | } |
| 111 | 158 | const nl = c.output.indexOf("\n"); |
| 112 | const flag = c.output.slice(0, nl); | |
| 159 | const flag = /^([01])(?: (\d{1,12}))?$/.exec(c.output.slice(0, nl)); | |
| 113 | 160 | const b64 = c.output.slice(nl + 1); |
| 114 | if (nl === -1 || (flag !== "0" && flag !== "1") || !/^[A-Za-z0-9+/]*={0,2}$/.test(b64)) return err({ status: 502, why: "the box's answer was not a file" }); | |
| 115 | return ok({ type, gzip: flag === "1", bytes: Buffer.from(b64, "base64") }); | |
| 161 | if (nl === -1 || flag === null || !/^[A-Za-z0-9+/]*={0,2}$/.test(b64)) return err({ status: 502, why: "the box's answer was not a file" }); | |
| 162 | return ok({ gzip: flag[1] === "1", total: flag[2] === undefined ? undefined : Number(flag[2]), bytes: Buffer.from(b64, "base64") }); | |
| 116 | 163 | } |
src/games/map_words.ts +4 −1
| @@ -9,7 +9,10 @@ export const mapWords = { | ||
| 9 | 9 | /** Also what an agent that sends a bare `status 000` gets: it cannot say which way it failed. */ |
| 10 | 10 | unreachable: |
| 11 | 11 | "The box answered, but BlueMap's web server is not listening on its loopback port 8100. Install BlueMap on this server and set its webserver `ip: \"127.0.0.1\"`, `port: 8100` (see docs/features/game-map.md).", |
| 12 | tooBig: "BlueMap is running, but this file is larger than the 600 KB the box relays, so it cannot be shown.", | |
| 12 | tooBig: "BlueMap is running, but this file is larger than the 600 KB the box sends at once and its web server does not give it in parts, so it cannot be shown.", | |
| 13 | /** A file past what the forge joins from slices (the ceiling is FORGE_GAME_MAP_MOST). */ | |
| 14 | tooLarge: (most: number): string => `This file is larger than the ${(most / 1048576).toFixed(0)} MB the forge joins from the box's slices, so it cannot be shown.`, | |
| 15 | unsized: "BlueMap is running, but its web server gave this file in a part without saying how big the whole is, so it cannot be told from a cut-off one and is not shown.", | |
| 13 | 16 | slow: "BlueMap is running, but it took longer than 10 seconds to give this file. Try again in a moment.", |
| 14 | 17 | /** BlueMap answered with a status that is not a file; the code is the box's word for it. */ |
| 15 | 18 | refused: (code: string): string => `BlueMap is running, but it refused this file with status ${code}.`, |
test/game-agent-exec.test.ts +43
| @@ -18,6 +18,21 @@ const lacks = ["bash", "curl", "jq"].filter((t) => Bun.which(t) === null); | ||
| 18 | 18 | let box = ""; |
| 19 | 19 | let forge: ReturnType<typeof Bun.serve>; |
| 20 | 20 | let commands: unknown[] = []; |
| 21 | /** A stand-in for BlueMap's web server: honours Range, except where a path says otherwise. */ | |
| 22 | const blue = Bun.serve({ | |
| 23 | port: 0, | |
| 24 | hostname: "127.0.0.1", | |
| 25 | fetch(req) { | |
| 26 | const path = new URL(req.url).pathname; | |
| 27 | const whole = new Uint8Array(path === "/empty.json" ? 0 : 700_000).fill(97); | |
| 28 | const range = /^bytes=(\d+)-(\d+)$/.exec(req.headers.get("range") ?? ""); | |
| 29 | if (path === "/empty.json" && range !== null) return new Response(null, { status: 416 }); | |
| 30 | if (range === null) return new Response(whole); | |
| 31 | const [from, to] = [Number(range[1]), Math.min(Number(range[2]), whole.length - 1)]; | |
| 32 | const total = path === "/unsized.json" ? "*" : String(whole.length); | |
| 33 | return new Response(whole.slice(from, to + 1), { status: 206, headers: { "content-range": `bytes ${String(from)}-${String(to)}/${total}` } }); | |
| 34 | }, | |
| 35 | }); | |
| 21 | 36 | let heard = (): unknown => undefined; |
| 22 | 37 | const bodies: { results?: { id: string }[]; people?: { servers?: Record<string, { ops: { name: string }[] }> }; metrics?: Record<string, unknown> }[] = []; |
| 23 | 38 | |
| @@ -56,6 +71,7 @@ esac | ||
| 56 | 71 | }); |
| 57 | 72 | }); |
| 58 | 73 | afterAll(async () => { |
| 74 | blue.stop(true); | |
| 59 | 75 | forge.stop(true); |
| 60 | 76 | await rm(box, { recursive: true, force: true }); |
| 61 | 77 | }); |
| @@ -74,6 +90,7 @@ async function syncs(times: number): Promise<void> { | ||
| 74 | 90 | FORGE_GAME_EVERY: "0", |
| 75 | 91 | FORGE_GAME_DIAG_S: "0", |
| 76 | 92 | FORGE_GAME_VOLUME_CHECK: "0", |
| 93 | FORGE_GAME_MAP_PORT: String(blue.port), | |
| 77 | 94 | }, |
| 78 | 95 | stdout: "ignore", |
| 79 | 96 | stderr: "ignore", |
| @@ -101,3 +118,29 @@ test.skipIf(lacks.length > 0)("every command of an answer runs, and an op typed | ||
| 101 | 118 | expect(bodies.at(-1)!.results?.map((r) => r.id)).toEqual(["c1", "c2"]); |
| 102 | 119 | expect(bodies.at(-1)!.people?.servers?.["hub"]?.ops.map((o) => o.name)).toEqual(["Alice"]); |
| 103 | 120 | }, 30_000); |
| 121 | ||
| 122 | type Result = { id: string; ok: boolean; output: string }; | |
| 123 | /** Ask the agent for these map paths and read what it answered, by id. */ | |
| 124 | async function mapAnswers(paths: string[]): Promise<Record<string, Result>> { | |
| 125 | commands = paths.map((text, i) => ({ id: `m${String(i)}`, kind: "map", service: "hub", text })); | |
| 126 | const got: Record<string, Result> = {}; | |
| 127 | for (let tries = 0; tries < 8 && Object.keys(got).length < paths.length; tries++) { | |
| 128 | await syncs(3); | |
| 129 | for (const b of bodies) for (const r of (b.results ?? []) as Result[]) if (r.id.startsWith("m")) got[r.id] = r; | |
| 130 | } | |
| 131 | return got; | |
| 132 | } | |
| 133 | ||
| 134 | test.skipIf(lacks.length > 0)("a map file is answered a slice at a time with its total, and what is not a whole file or a slice is never ok", async () => { | |
| 135 | const a = await mapAnswers(["big.json", "big.json#512000-699999", "big.json#9-3", "big.json#0-600000", "unsized.json", "empty.json"]); | |
| 136 | const [first, second, backwards, wide, unsized, empty] = ["m0", "m1", "m2", "m3", "m4", "m5"].map((k): Result => a[k] ?? { id: k, ok: false, output: "no answer" }) as [Result, Result, Result, Result, Result, Result]; | |
| 137 | expect(first.ok).toBe(true); | |
| 138 | expect(first.output.split("\n")[0]).toBe("0 700000"); | |
| 139 | expect(Buffer.from(first.output.split("\n")[1]!, "base64").length).toBe(512000); | |
| 140 | expect(second.output.split("\n")[0]).toBe("0 700000"); | |
| 141 | expect(Buffer.from(second.output.split("\n")[1]!, "base64").length).toBe(188000); | |
| 142 | expect(backwards).toMatchObject({ ok: false, output: "refused: not a slice" }); | |
| 143 | expect(wide).toMatchObject({ ok: false, output: "refused: not a slice" }); | |
| 144 | expect(unsized).toMatchObject({ ok: false, output: "unsized" }); | |
| 145 | expect(empty).toMatchObject({ ok: true, output: "0\n" }); | |
| 146 | }, 60_000); |
test/games-map.test.ts +53
| @@ -200,6 +200,9 @@ describe("the live map relay", () => { | ||
| 200 | 200 | const no = await answer("t/r5.prbm", "status 403"); |
| 201 | 201 | expect(no.status).toBe(502); |
| 202 | 202 | expect(no.text).toContain("status 403"); |
| 203 | const part = await answer("t/r6.prbm", "unsized"); | |
| 204 | expect(part.status).toBe(502); | |
| 205 | expect(part.text).toContain("without saying how big"); | |
| 203 | 206 | expect(no.text).not.toContain("not listening"); |
| 204 | 207 | }); |
| 205 | 208 | |
| @@ -221,6 +224,56 @@ describe("the live map relay", () => { | ||
| 221 | 224 | expect((await res.arrayBuffer()).byteLength).toBe(600_000); |
| 222 | 225 | }); |
| 223 | 226 | |
| 227 | /** The box's side of a big file: the first slice says the total, `path#a-b` is the part asked. */ | |
| 228 | const serveParts = async (file: Buffer, got: string[]): Promise<void> => { | |
| 229 | for (;;) { | |
| 230 | const c = await taken(); | |
| 231 | got.push(c.text); | |
| 232 | const m = /#(\d+)-(\d+)$/.exec(c.text); | |
| 233 | const from = m === null ? 0 : Number(m[1]); | |
| 234 | const to = m === null ? 511_999 : Number(m[2]); | |
| 235 | const part = file.subarray(from, Math.min(to + 1, file.length)); | |
| 236 | await light([{ id: c.id, ok: true, output: `0 ${file.length}\n${part.toString("base64")}` }]); | |
| 237 | if (to + 1 >= file.length) return; | |
| 238 | } | |
| 239 | }; | |
| 240 | ||
| 241 | test("a file of 1.5 MB arrives whole, in slices, one row each and none left", async () => { | |
| 242 | const at = await base(bobTok); | |
| 243 | const file = Buffer.from(Array.from({ length: 1_500_000 }, (_, i) => i % 251)); | |
| 244 | const asking = get(`${at}t/textures.json`); | |
| 245 | const got: string[] = []; | |
| 246 | await serveParts(file, got); | |
| 247 | const res = await asking; | |
| 248 | expect(res.status).toBe(200); | |
| 249 | expect(Buffer.from(await res.arrayBuffer()).equals(file)).toBe(true); | |
| 250 | expect(got).toEqual(["t/textures.json", "t/textures.json#512000-1023999", "t/textures.json#1024000-1499999"]); | |
| 251 | expect(app.db.query("SELECT count(*) AS n FROM game_command WHERE kind = 'map'").get()).toEqual({ n: 0 }); | |
| 252 | }); | |
| 253 | ||
| 254 | test("a file past the ceiling is a 413 that names the ceiling, and no slice past the first is asked", async () => { | |
| 255 | const at = await base(bobTok); | |
| 256 | const asking = get(`${at}t/huge.prbm`); | |
| 257 | const c = await taken(); | |
| 258 | await light([{ id: c.id, ok: true, output: `0 ${9 * 1024 * 1024}\n${Buffer.alloc(512_000).toString("base64")}` }]); | |
| 259 | const res = await asking; | |
| 260 | expect(res.status).toBe(413); | |
| 261 | expect(await res.text()).toContain("8 MB"); | |
| 262 | expect((await light()).commands.filter((x) => x.kind === "map")).toEqual([]); | |
| 263 | }); | |
| 264 | ||
| 265 | test("a slice longer than asked is not a file, and the oversize join is never served", async () => { | |
| 266 | const at = await base(bobTok); | |
| 267 | const asking = get(`${at}t/liar.prbm`); | |
| 268 | const first = await taken(); | |
| 269 | await light([{ id: first.id, ok: true, output: `0 600000\n${Buffer.alloc(512_000).toString("base64")}` }]); | |
| 270 | const next = await taken(); | |
| 271 | await light([{ id: next.id, ok: true, output: `0 600000\n${Buffer.alloc(512_000).toString("base64")}` }]); | |
| 272 | const res = await asking; | |
| 273 | expect(res.status).toBe(502); | |
| 274 | expect(await res.text()).toContain("not a file"); | |
| 275 | }); | |
| 276 | ||
| 224 | 277 | test("the owner's commands are handed before a viewer's map files, however late they were queued", async () => { |
| 225 | 278 | const box = app.db.query<{ id: string }, []>("SELECT id FROM game_box WHERE name = 'net'").get()!; |
| 226 | 279 | const bob = getUserByName(app.db, "bob")!; |
new above
offline
A 206 whose Content-Range has no numeric total (
bytes 0-511999/*, or the header missing) leavesgzas plain0, so askMap serves the first 512000 bytes as the whole file with a 200. Make a 206 without a total a failed result with words, never ok.