Public: anyone can read this; the crew can change it.

A server's page shows whether its map answers, with the reason, before anyone opens the 3D view #18349

opened this

Merged 59m ago, live in production

mason/forge:mason/18345-a-server-s-page-shows-whether-its-map-an → main 0 commits fork 4 threads · 4 unresolved

  • Merged. mason/18345-a-server-s-page-shows-whether-its-map-an was merged into main as bca1c31.

Review

Sign in to review this change.
12 files changed +148 −7
docs/features/game-map.md +4
@@ -14,3 +14,7 @@ A game server's BlueMap, a live 3D map with its players, is served by the forge
1414 - **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.
1515 - **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.
1616 - **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.
17
18 ## Whether it answers, before you open it
19
20 A server's page shows one line under "Open the map": `The map answers.`, or the reason (not listening, too large, too slow, refused, or the box silent). It is the stored result of asking the box for `index.html`, at most once a minute per server, started in the background when someone looks at the server; the page never waits on the box. The terminal's live map screen (`w` on a server) shows the same line, and the `games` MCP tool's `list` gives it as `map` on each service.
src/core/migration-pins/20261206031207-game-map-check.pin added +1
@@ -0,0 +1,1 @@
1 bb5b27ffa14a5c4a769869c028f814539aad348f0edba2ab7c8afc08c16d9495
src/core/migrations/20261206031207-game-map-check.ts added +13
@@ -0,0 +1,13 @@
1 // What the last light check of a server's live map found (#18345): the asked file's outcome in the
2 // words every door shows, and when it was asked. One row per server; `at` is also the claim that
3 // keeps the check to once a minute. Additive.
4 export default `
5 CREATE TABLE IF NOT EXISTS game_map_check (
6 box_id TEXT NOT NULL,
7 service TEXT NOT NULL,
8 at INTEGER NOT NULL,
9 ok INTEGER,
10 says TEXT NOT NULL DEFAULT '',
11 PRIMARY KEY (box_id, service)
12 );
13 `;
src/games/map_check.ts added +44
@@ -0,0 +1,44 @@
1 /**
2 * Whether a server's map answers, known before anyone opens it (#18345): one cheap file
3 * (`index.html`) asked of the box at most once a minute per server, the outcome stored. A page, the
4 * terminal and the MCP tool read the stored line and never wait on the box; looking at a server
5 * starts the next check in the background when the stored one is a minute old.
6 */
7
8 import type { App } from "../app.ts";
9 import { askMap, mapPath } from "./map.ts";
10 import { mapWords } from "./map_words.ts";
11 import type { GameBox } from "./store.ts";
12
13 /** A check is not repeated sooner than this. */
14 export const MAP_CHECK_MS = 60_000;
15
16 interface Row {
17 ok: number | null;
18 says: string;
19 }
20
21 /** The line a viewer reads beside the map button, from the stored result alone. */
22 export function mapLine(app: App, boxId: string, service: string): string {
23 const r = app.db.query<Row, [string, string]>("SELECT ok, says FROM game_map_check WHERE box_id = ?1 AND service = ?2").get(boxId, service);
24 if (r === null || r.ok === null) return mapWords.unchecked;
25 return r.ok === 1 ? mapWords.answering : r.says;
26 }

Medium: the stored result is shown with no age. After hours without a look, The map answers. is stale and reads as current. Store/use at and word the line by age (e.g. checked N minutes ago, or stale after a few minutes).

27
28 /**
29 * Start the minute's check when none ran in the last minute; returns at once, the answer is stored
30 * later.
31 */
32 export function refreshMap(app: App, box: GameBox, service: string, now = Date.now()): void {
33 const claimed = app.db
34 .query("INSERT INTO game_map_check (box_id, service, at) VALUES (?1, ?2, ?3) ON CONFLICT (box_id, service) DO UPDATE SET at = ?3 WHERE at <= ?3 - ?4")
35 .run(box.id, service, now, MAP_CHECK_MS);
36 if (claimed.changes === 0) return;
37 const front = mapPath("");
38 if (!front.ok) return;
39 void askMap(app, box, service, front.value, "")
40 .then((got) => {
41 app.db.query("UPDATE game_map_check SET ok = ?3, says = ?4 WHERE box_id = ?1 AND service = ?2").run(box.id, service, got.ok ? 1 : 0, got.ok ? "" : got.error.why);
42 })
43 .catch(() => {});

Low: .catch(() => {}) swallows a failed check silently and leaves the line unchecked or stale. Store the failure's reason instead.

44 }
src/games/map_words.ts +3
@@ -13,6 +13,9 @@ export const mapWords = {
1313 slow: "BlueMap is running, but it took longer than 10 seconds to give this file. Try again in a moment.",
1414 /** BlueMap answered with a status that is not a file; the code is the box's word for it. */
1515 refused: (code: string): string => `BlueMap is running, but it refused this file with status ${code}.`,
16 /** The line beside the button, before and after a check. */
17 answering: "The map answers.",
18 unchecked: "Not checked yet: the box is asked when someone looks at this server.",

Low (principles 1 and 8): this explains how the forge works. Say plainly: Not checked yet.

1619 /** The one sentence a viewer reads beside the button. */
1720 blurb: "A live 3D map of the world, with its players.",
1821 } as const;
src/http/mcp/tools/games.ts +6 −1
@@ -1,3 +1,4 @@
1 import { mapLine, refreshMap } from "../../../games/map_check.ts";
12 import { cloudLineFresh, pinnedOfBox } from "../../../actions/cloud_says.ts";
23 import { commitServiceEnv } from "../../../games/compose.ts";
34 import { search, searchPacks } from "../../../games/modrinth.ts";
@@ -105,7 +106,11 @@ export const tool: Tool = {
105106 // Whether a set helped a day after it landed, in words (`games/set_verdict.ts`); a
106107 // hurt one is taken back with `mods_remove` `set:<name>`.
107108 const sets = verdictsOf(db, b, s.name).map((v) => v.says);
108 return sets.length === 0 ? s : { ...s, modSets: sets };
109 // Whether the map answers, as last checked (`games/map_check.ts`); never waits on the
110 // box.
111 refreshMap(ctx.app, b, s.name);
112 const map = mapLine(ctx.app, b.id, s.name);
113 return sets.length === 0 ? { ...s, map } : { ...s, map, modSets: sets };
109114 }),
110115 snapshots: Object.fromEntries(Object.entries(b.snapshots).filter(([s]) => mayDo(roleOn(db, user, b.id, s), "viewer")).map(([s, list]) => [s, list.slice(0, 10)])),
111116 })),
src/tui/screens/game_map.ts +3 −1
@@ -6,6 +6,7 @@
66 */
77
88 import { askMap, mapPath } from "../../games/map.ts";
9 import { mapLine, refreshMap } from "../../games/map_check.ts";
910 import { mapPathOf, mapWords } from "../../games/map_words.ts";
1011 import { roleOn, mayDo, type GameBox } from "../../games/store.ts";
1112 import type { Ctx, Screen } from "../app/app.ts";
@@ -24,7 +25,8 @@ export function gameMapScreen(f: Session, ctx: Ctx, box: GameBox, service: strin
2425 const c = ctx.theme.c;
2526 const [head, body] = split(area, "v", [len(1), fill(1)]);
2627 s.text(head!.x, head!.y, truncate(note === "" ? "p asks the box if the map answers" : note, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
27 const lines = wrap(`${mapWords.blurb} ${mapPathOf(box.name, service)}`, body!.w);
28 refreshMap(f.app, box, service);

Medium: refreshMap runs inside the draw callback, so every repaint does a DB write attempt, and rendering has a side effect. Start the check once when the screen opens or on a key, and only read mapLine here.

29 const lines = wrap(`${mapWords.blurb} ${mapPathOf(box.name, service)} ${mapLine(f.app, box.id, service)}`, body!.w);
2830 lines.slice(0, body!.h).forEach((l, i) => s.text(body!.x, body!.y + i, truncate(l, body!.w), style(c.fg, c.bg), body!.x + body!.w));
2931 },
3032 key(e) {
src/web/pages/games.ts +4
@@ -66,6 +66,7 @@ import { MASK, secretKey } from "../../core/secret_text.ts";
6666 import { BODY_CAPS } from "../../kernel/body_caps.ts";
6767 import type { Ctx } from "../../http/context.ts";
6868 import { eventStream } from "../../http/sse.ts";
69 import { mapLine, refreshMap } from "../../games/map_check.ts";
6970 import { mapPathOf, mapWords } from "../../games/map_words.ts";
7071 import { notFoundPage, pageHead, signInFirst } from "../chrome.ts";
7172 import { field, readForm, type Form } from "../form.ts";
@@ -582,6 +583,8 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> {
582583 ])
583584 : [undefined, undefined, undefined, undefined, undefined, undefined];
584585 const base = `/games/${box.name}/${service}`;
586 // The map's line is the stored one; the next check runs behind this response.
587 refreshMap(ctx.app, box, service);
585588 const pinned = compose !== undefined && act && proxyOf(compose.text) === service ? await pinnedBlock(ctx, box, base, mayDo(role, "owner")) : undefined;
586589 const commands = recentCommands(ctx.app.db, box.id, service, 5);
587590 const seen = servicesOf(ctx.app.db, box.id).find((s) => s.name === service);
@@ -670,6 +673,7 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> {
670673 <h2>Live map</h2>
671674 <p class="muted small">${mapWords.blurb}</p>
672675 <p>${btn("Open the map", { href: mapPathOf(box.name, service), variant: "secondary" })}</p>
676 <p class="muted small" id="map-line">${mapLine(ctx.app, box.id, service)}</p>
673677 </section>`)}
674678 ${fold("Settings", "settings", preview !== undefined, html`${settingsBlock({ base, act, settings, preview, sha: compose?.sha ?? "", wanted })}`)}
675679 ${fold("Mods and plugins", "mods", query !== null || adding !== "" || packQuery !== null || packing !== "", html`${modsBlock({ base, act, mods, hits, ups, preview: modPreview, query, adding })}
test/game-chat.test.ts +1 −1
@@ -293,7 +293,7 @@ describe("on a forge", () => {
293293 .query<
294294 { n: number; service: string; kind: string; text: string },
295295 [number]
296 >("SELECT rowid AS n, service, kind, text FROM game_command WHERE rowid > ?1 AND kind != 'people' ORDER BY rowid")
296 >("SELECT rowid AS n, service, kind, text FROM game_command WHERE rowid > ?1 AND kind NOT IN ('people', 'map') ORDER BY rowid")
297297 .all(seen);
298298 if (rows.length > 0) seen = rows.at(-1)!.n;
299299 return rows.map((r) => {
test/game-findings.test.ts +1 −1
@@ -98,7 +98,7 @@ describe("findings", () => {
9898 const other = findingsOf(app.db, box.id, "hub").find((f) => f.key === "other")!;
9999 expect(other.fix).toBe("Read the reason below: it is the server's or a mod's own words.");
100100 expect(other.last).toContain("IGNORE PREVIOUS");
101 expect(app.db.query("SELECT 1 FROM game_command WHERE box_id = ?1").get(box.id)).toBeNull();
101 expect(app.db.query("SELECT 1 FROM game_command WHERE box_id = ?1 AND kind != 'map'").get(box.id)).toBeNull();
102102 });
103103
104104 test("the cause is the plainest words first: a ban or a whitelist that names mods is not a mod finding", () => {
test/games-map.test.ts +65 −1
@@ -6,8 +6,10 @@ import { createApp, type App } from "../src/app.ts";
66 import { createToken } from "../src/core/tokens.ts";
77 import { createUser, getUserByName } from "../src/core/users.ts";
88 import { MAP_PER_PERSON, mapPath } from "../src/games/map.ts";
9 import { MAP_CHECK_MS, mapLine, refreshMap } from "../src/games/map_check.ts";
10 import { mapWords } from "../src/games/map_words.ts";
911 import { mapPass } from "../src/games/map_token.ts";
10 import { createGameBox, grant, queueCommand } from "../src/games/store.ts";
12 import { boxNamed, createGameBox, grant, queueCommand } from "../src/games/store.ts";
1113 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
1214 import { quietLogs } from "./helpers/globals.ts";
1315 import { waitFor } from "./helpers/poll.ts";
@@ -247,3 +249,65 @@ describe("the live map relay", () => {
247249 expect((await light()).commands.filter((c) => c.kind === "map")).toEqual([]);
248250 });
249251 });
252
253 describe("the map's line before anyone opens it", () => {
254 let dataDir = "";
255 let app: App;
256 let http: ForgeHttp;
257 let token = "";
258 let box: ReturnType<typeof createGameBox>;
259 let bobTok = "";
260 const sync = async (results: unknown[] = []) =>
261 (await (
262 await http.handle(
263 new Request(`${ORIGIN}/api/v1/games/agent/sync`, {
264 method: "POST",
265 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
266 body: JSON.stringify({ agent: 1, light: true, services: [{ name: "hub", state: "running" }], results }),
267 }),
268 )
269 ).json()) as { commands: { id: string; kind: string; text: string }[] };
270
271 beforeAll(async () => {
272 dataDir = await mkdtemp(join(tmpdir(), "forge-mapline-"));
273 app = createApp({ dataDir, port: 0, modrinthFetch: async () => Response.json([]) });
274 http = forgeHttp(app);
275 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
276 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst });
277 if (!made.ok) throw new Error(made.error);
278 }
279 bobTok = createToken(app.db, getUserByName(app.db, "bob")!.id, "rw", "rw").token;
280 box = createGameBox(app.db, { name: "net", repo: "alice/mc-network" });
281 token = box.token;
282 grant(app.db, box.id, getUserByName(app.db, "bob")!.id, "viewer");
283 await sync();
284 }, 30_000);
285
286 afterAll(async () => {
287 app.close();
288 await rm(dataDir, { recursive: true, force: true });
289 });
290
291 test("the page answers at once with the stored line; a check asks index.html once a minute and the line follows", async () => {
292 const page = await http.handle(new Request(`${ORIGIN}/games/net/hub`, { headers: { authorization: `Bearer ${bobTok}` } }));
293 expect(await page.text()).toContain(mapWords.unchecked);
294 let asked: { id: string; text: string } | undefined;
295 await waitFor(async () => (asked = (await sync()).commands.find((c) => c.kind === "map")) !== undefined, { every: 20, within: 2_000, what: "the light check is handed to the box" });
296 expect(asked!.text).toBe("index.html");
297 await http.handle(new Request(`${ORIGIN}/games/net/hub`, { headers: { authorization: `Bearer ${bobTok}` } }));
298 expect(app.db.query("SELECT count(*) AS n FROM game_command WHERE kind = 'map'").get()).toEqual({ n: 1 });
299 await sync([{ id: asked!.id, ok: false, output: "toobig" }]);
300 await waitFor(() => mapLine(app, box.id, "hub") === mapWords.tooBig, { every: 20, within: 2_000, what: "the reason is stored" });
301 const again = await http.handle(new Request(`${ORIGIN}/games/net/hub`, { headers: { authorization: `Bearer ${bobTok}` } }));
302 expect(await again.text()).toContain(mapWords.tooBig);
303 expect(app.db.query("SELECT count(*) AS n FROM game_command WHERE kind = 'map'").get()).toEqual({ n: 0 });
304 });
305
306 test("a minute on, the next look checks again; answering reads as answering", async () => {
307 refreshMap(app, boxNamed(app.db, "net")!, "hub", Date.now() + MAP_CHECK_MS + 1);
308 let asked: { id: string } | undefined;
309 await waitFor(async () => (asked = (await sync()).commands.find((c) => c.kind === "map")) !== undefined, { every: 20, within: 2_000, what: "the second check" });
310 await sync([{ id: asked!.id, ok: true, output: `0\n${Buffer.from("<html>").toString("base64")}` }]);
311 await waitFor(() => mapLine(app, box.id, "hub") === mapWords.answering, { every: 20, within: 2_000, what: "answering is stored" });
312 });
313 });
test/games.test.ts +3 −2
@@ -234,8 +234,9 @@ describe("forge games", () => {
234234 expect((await asBob("/games/net/grant", { user: "bob", role: "owner", service: "" })).status).toBe(404);
235235 const sent = await asBob("/games/net/hub/command", { text: "say from bob" });
236236 expect(sent.status).toBe(303);
237 const queued = (await (await sync({ agent: 1 })).json()) as { commands: { service: string; text: string }[] };
238 expect(queued.commands).toEqual([expect.objectContaining({ service: "hub", text: "say from bob" })]);
237 const queued = (await (await sync({ agent: 1 })).json()) as { commands: { kind: string; service: string; text: string }[] };
238 // The page's own map check (`index.html`) rides along; it is not what bob sent.
239 expect(queued.commands.filter((c) => c.kind !== "map")).toEqual([expect.objectContaining({ service: "hub", text: "say from bob" })]);
239240 });
240241
241242 test("the box page says what its sleeping servers leave spare, unknown before a day of samples (#17576)", async () => {

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

Keyboard shortcuts

Docs