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

Games: a proxy plugin update can wait until nobody has been on for 30 minutes #18039

opened this

Merged 16h 6m ago, live in production

sold/when-quiet → main 0 commits 5 threads · 5 unresolved

  • Merged. sold/when-quiet was merged into main as 9a5eb31.

Review

Sign in to review this change.
12 files changed +468 −3
docs/features/games.md +2
@@ -82,6 +82,8 @@ Uploading a world file is still to come: a link is how a world comes in today.
8282
8383 Creating it is one commit to the network's compose file: the service from the Paper anchor with its own RCON key, a volume, the proxy's `[servers]` and `[forced-hosts]` lines, sleep's label and waker lists, and its lockfile beside it. Remove on the server's row, `d` on the terminal Games screen, or `remove_server` takes the service and its proxy lines back out by commit, its plan shown first, and keeps its world's volume (`src/games/presets.ts`). The proxy, the waker, and a server the proxy's list of servers new players land on first (its `try` line) or another forced host still names are refused.
8484
85 **When nobody is on.** A change that restarts a server can wait until nobody has been on the box for 30 minutes (`src/games/when_quiet.ts`): on the proxy's Forge plugins row, **Save when nobody has been on for 30 minutes** holds the pin instead of restarting the proxy now. The forge applies it itself at the first full check-in after 30 minutes with nobody on and nobody joining or leaving; a newer ask replaces an older one, and one that cannot be applied is dropped with its reason in the log.
86
8587 ## From in the game
8688
8789 A player can ask the forge from a server's chat (#17284). Link the name first: **Link your Minecraft name** under Minecraft on the account page (`/settings`), or `L` on the terminal's Games screen (`src/tui/screens/games.ts`), gives a one-time code (6 characters, 10 minutes, kept only as its hash) shown only to the person signed in. The block is there for everyone signed in once the forge has a game box, and neither door gives a code before that: a link gives no role. In chat on any server of the box, type `!forge link 4F7QXZ`; where the proxy has the plugin, type `/forge link 4F7QXZ`, then `/forge yes` and the six digits it shows. The link binds the account to the name and to the player's UUID as the server itself lists it (`list uuids`, the same answer People keeps as who is online), never to anything typed in chat; a Bedrock name (`.Name`) links the same way. A name the server does not list yet is told to stay on and try again, and the code stays good. Five wrong codes for a name lock it out for an hour. The account page lists the linked names with Unlink, and `/games/<box>` lists who is linked there to an operator of the box (anyone else sees their own links) and, to its owner, the last commands as they were typed (`/forge` or `!forge`, kept in `game_chat.door`; a question asked through the proxy before that column existed reads as `!forge`) and what came of each. The forge's words to a player in game are not in the service's console.
src/core/migration-pins/20261204041500-game-when-quiet.pin added +1
@@ -0,0 +1,1 @@
1 06f20627617d121528ac724d2538168c4979a5465bb3a968bfd82299eb4fbb8f
src/core/migration-pins/20261204100000-game-quiet-reports.pin added +1
@@ -0,0 +1,1 @@
1 32ea5adee5c11df63e4977d6eb70a8cf019959f4cf73d8704fe517a375722c63
src/core/migrations/20261204041500-game-when-quiet.ts added +12
@@ -0,0 +1,12 @@
1 // A change to a game box held until nobody has been on it for a while (#18025): one row a box and
2 // kind, replaced by a newer ask of the same kind, removed once it is applied. Additive: one table.
3 export default `
4 CREATE TABLE IF NOT EXISTS game_when_quiet (
5 box_id TEXT NOT NULL,
6 kind TEXT NOT NULL,
7 ref TEXT NOT NULL,
8 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
9 asked_at TEXT NOT NULL,
10 PRIMARY KEY (box_id, kind)
11 ) WITHOUT ROWID;
12 `;
src/core/migrations/20261204100000-game-quiet-reports.ts added +6
@@ -0,0 +1,6 @@
1 // What a quiet box needs (#18025): when a server last reported who is on it (a list that is not
2 // reporting is not an empty one), and why a held change's last try did not go. Additive: two columns.
3 export default `
4 ALTER TABLE game_service ADD COLUMN online_at TEXT;
5 ALTER TABLE game_when_quiet ADD COLUMN error TEXT NOT NULL DEFAULT '';
6 `;
src/games/metrics.ts +1 −1
@@ -251,7 +251,7 @@ export function recordMetrics(db: Database, box: Pick<GameBox, "id">, body: Metr
251251 if (r.names !== undefined)
252252 db.query("UPDATE game_service SET players = ?3 WHERE box_id = ?1 AND name = ?2").run(box.id, service, r.names.join(","));
253253 for (const [service, r] of rows)
254 if (r.online !== undefined) db.query("UPDATE game_service SET online_json = ?3 WHERE box_id = ?1 AND name = ?2").run(box.id, service, JSON.stringify(r.online));
254 if (r.online !== undefined) db.query("UPDATE game_service SET online_json = ?3, online_at = ?4 WHERE box_id = ?1 AND name = ?2").run(box.id, service, JSON.stringify(r.online), at);
255255 const event = db.query("INSERT INTO game_player_event (box_id, service, player, kind, at, text) VALUES (?1, ?2, ?3, ?4, ?5, ?6)");
256256 for (const e of events) event.run(box.id, e.service, e.player, e.kind, at, e.text);
257257 // Past the window: once a minute is plenty, and each delete walks the minute index.
src/games/when_quiet.ts added +110
@@ -0,0 +1,110 @@
1 /**
2 * Changes that restart a game box's servers, held until nobody has been on the box for
3 * `QUIET_MINUTES` (#18025): the forge applies them itself at a check-in, with no person and no
4 * agent turn. Today one kind: a pinned proxy plugin, whose commit restarts the proxy.
5 */
6
7 import type { App } from "../app.ts";
8 import { getUserById } from "../core/users.ts";
9 import { readCompose } from "./compose.ts";
10 import { peopleOf } from "./people.ts";
11 import { commitJar, pinOf } from "./proxy_jars.ts";
12 import { proxyOf } from "./sleep.ts";
13 import { mayDo, roleOn, servicesOf, type GameBox } from "./store.ts";
14
15 export const QUIET_MINUTES = 30;
16 const QUIET_MS = QUIET_MINUTES * 60_000;
17
18 export interface Held {
19 readonly kind: "pin";
20 readonly ref: string;
21 readonly userId: string;
22 readonly askedAt: string;
23 /** Why the last try did not go, when it did not; "" before one. */
24 readonly error: string;
25 }
26
27 /** Hold a change until the box is quiet; a newer ask of the same kind replaces the older. */
28 export function holdUntilQuiet(app: App, box: Pick<GameBox, "id">, held: Omit<Held, "askedAt" | "error">, now = Date.now()): void {
29 app.db
30 .query("INSERT INTO game_when_quiet (box_id, kind, ref, user_id, asked_at) VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT (box_id, kind) DO UPDATE SET ref = excluded.ref, user_id = excluded.user_id, asked_at = excluded.asked_at, error = ''")
31 .run(box.id, held.kind, held.ref, held.userId, new Date(now).toISOString());
32 }
33
34 /** A person takes back what they held; true when something was held. */
35 export function cancelHeld(app: App, box: Pick<GameBox, "id">, kind: Held["kind"], ref: string): boolean {
36 return app.db.query("DELETE FROM game_when_quiet WHERE box_id = ?1 AND kind = ?2 AND ref = ?3").run(box.id, kind, ref).changes > 0;
37 }
38
39 export const heldOf = (app: App, box: Pick<GameBox, "id">): Held[] =>
40 app.db
41 .query<{ kind: "pin"; ref: string; user_id: string; asked_at: string; error: string }, [string]>("SELECT kind, ref, user_id, asked_at, error FROM game_when_quiet WHERE box_id = ?1 ORDER BY asked_at")
42 .all(box.id)
43 .map((r) => ({ kind: r.kind, ref: r.ref, userId: r.user_id, askedAt: r.asked_at, error: r.error }));
44
45 /** How old a server's player list may be and still count: a few check-ins. Older, or none, is not known to be empty. */
46 export const FRESH_MS = 3 * 60_000;
47
48 /**
49 * Whether nobody is on any server of the box now, and nobody joined or left in the last
outdated

High: only checks that the user still exists. Re-check that they are still an owner of the box before committing as them (the gate gameJarSubmit uses). Otherwise a demoted person's old ask still writes to the compose repo.

50 * `QUIET_MINUTES`. Quiet is something the box has said: at least one server reported its player
51 * list a moment ago, and none that has reported is stale. A box whose list is not reporting is not
52 * quiet, whatever the table holds.
53 */
54 export function isQuiet(app: App, box: Pick<GameBox, "id">, now = Date.now()): boolean {
55 const lists = app.db.query<{ online_json: string; online_at: string | null }, [string]>("SELECT online_json, online_at FROM game_service WHERE box_id = ?1 AND online_at IS NOT NULL").all(box.id);
56 const fresh = (at: string | null): boolean => at !== null && now - Date.parse(at) <= FRESH_MS;
57 if (lists.length === 0 || lists.some((l) => !fresh(l.online_at))) return false;
58 if (servicesOf(app.db, box.id).some((s) => peopleOf(app.db, box.id, s.name).online.length > 0)) return false;
59 // The event's time is the forge's own receive time, not the box's clock; one that does not read is not quiet.
60 const last = app.db.query<{ at: string | null }, [string]>("SELECT MAX(at) AS at FROM game_player_event WHERE box_id = ?1").get(box.id)?.at;
61 if (last === null || last === undefined) return true;
62 const ago = now - Date.parse(last);
63 return Number.isFinite(ago) && ago >= QUIET_MS;
64 }
65
66 /** One application of a held change: its commit, or why not. */
67 type Apply = (app: App, box: GameBox, held: Held) => Promise<{ ok: true } | { ok: false; error: string; permanent?: true }>;
68
69 const applyPin: Apply = async (app, box, held) => {
70 const pin = pinOf(held.ref);
71 const user = getUserById(app.db, held.userId);
72 if (pin === undefined || user === undefined) return { ok: false, error: "the pin or the person who asked is gone", permanent: true };
73 const compose = await readCompose(app, box);
74 if (compose === undefined) return { ok: false, error: "the compose file could not be read" };
75 // Committed as them, so only while they are still an owner of the proxy, as when they pressed it.
76 if (!mayDo(roleOn(app.db, user, box.id, proxyOf(compose.text) ?? ""), "owner")) return { ok: false, error: "the person who asked is no longer an owner of the box", permanent: true };
77 const done = await commitJar(app, user, box, pin, compose.sha);
78 return done.ok ? { ok: true } : done;
79 };
80
81 const running = new WeakMap<App, Set<string>>();
82
83 /**
84 * Apply what a quiet box holds, once: a check-in calls it and does not wait. A change that cannot be
85 * applied for good (the pin, or the owner, is gone) is dropped; any other failure is kept with its
86 * reason for the next quiet check-in, and shown on the row until it is cancelled.
87 */
88 export async function applyWhenQuiet(app: App, box: GameBox, now = Date.now(), apply: Apply = applyPin): Promise<number> {
89 const held = heldOf(app, box);
90 if (held.length === 0 || !isQuiet(app, box, now)) return 0;
91 const busy = running.get(app) ?? new Set<string>();
92 running.set(app, busy);
93 if (busy.has(box.id)) return 0;
94 busy.add(box.id);
95 let done = 0;
96 try {
97 for (const h of held) {
98 const result = await apply(app, box, h);
99 const row = [box.id, h.kind, h.askedAt] as const;
100 // Gone on success or for a reason that will not change; any other is kept, with why, for the next quiet check-in.
101 if (result.ok || result.permanent === true) app.db.query("DELETE FROM game_when_quiet WHERE box_id = ?1 AND kind = ?2 AND asked_at = ?3").run(...row);
102 else app.db.query("UPDATE game_when_quiet SET error = ?4 WHERE box_id = ?1 AND kind = ?2 AND asked_at = ?3").run(...row, result.error.slice(0, 300));
103 if (result.ok) done++;
104 else app.log.warn("a change held until the box was quiet could not be applied", { box: box.name, kind: h.kind, why: result.error, kept: result.permanent !== true });
105 }
106 } finally {
107 busy.delete(box.id);
108 }
109 return done;
110 }
src/http/games_routes.ts +3
@@ -3,6 +3,7 @@
33 * bearer), the signed jar download, and the `/games` pages (`web/pages/games.ts`).
44 */
55
6 import { applyWhenQuiet } from "../games/when_quiet.ts";
67 import { composeServices, readCompose } from "../games/compose.ts";
78 import { AGENT_SH, AGENT_SHA } from "../games/boot.ts";
89 import { heal } from "../games/heal.ts";
@@ -47,6 +48,8 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
4748 if (sent === "too_large") return apiError("too_large", 413, "a sync is at most 200 log lines a service");
4849 const body = sent as SyncBody;
4950 const commands = recordSync(ctx.app.db, box, body);
51 // A change held until nobody is on is applied here, at a full check-in, without waiting for it.
52 if (body.light !== true) void applyWhenQuiet(ctx.app, box).catch((e) => ctx.app.log.warn("applying a held change failed", { box: box.name, error: String(e) }));

This hook has no test: a full sync must apply a quiet held change and a light sync must not. Add one.

5053 // A light sync (results in, commands out) is answered at once: the agent polls it every second or
5154 // two so a console command is run and answered in seconds, not at the pace of a full sync.
5255 if (body.light === true) {
src/web/pages/games.ts +25 −2
@@ -7,6 +7,7 @@
77 * the box's compose repository, so a merge redeploys and the crew can propose them too.
88 */
99
10 import { cancelHeld, heldOf, holdUntilQuiet, QUIET_MINUTES } from "../../games/when_quiet.ts";
1011 import { addPluginUrl, commitServiceEnv, composeServices, readCompose, serviceEnv } from "../../games/compose.ts";
1112 import { commitPlan, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf, type Mods, type Plan } from "../../games/mods.ts";
1213 import { search, searchPacks, type Hit, type Result } from "../../games/modrinth.ts";
@@ -1348,6 +1349,12 @@ const changed = (title: string, lines: readonly string[]): Html[] =>
13481349 /** The plugins the forge pins for the proxy: what each would change, and the owner's button that commits it. */
13491350 async function pinnedBlock(ctx: Ctx, box: GameBox, base: string, owner: boolean): Promise<Html> {
13501351 const plans = await Promise.all(PINS.map(async (pin) => ({ pin, plan: await planJar(ctx.app, box, pin) })));
1352 const held = heldOf(ctx.app, box).filter((h) => h.kind === "pin");
1353 const cancelForm = (sha: string): Html => html`<form method="post" action="${base}/jar" class="row-fields">
1354 <input type="hidden" name="pin" value="${sha}" />
1355 <input type="hidden" name="when" value="cancel" />
1356 ${btn("Cancel the held save", { variant: "ghost" })}
1357 </form>`;
13511358 return html`<section class="settings-block">
13521359 <h2>Forge plugins</h2>
13531360 ${rowList(
@@ -1357,12 +1364,14 @@ async function pinnedBlock(ctx: Ctx, box: GameBox, base: string, owner: boolean)
13571364 meta: html`${pin.does}`,
13581365 facts: plan.ok
13591366 ? [
1367 ...held.filter((h) => h.ref === pin.sha256).map((h) => ({ label: "Held", value: `Saved and restarted once nobody has been on for ${String(QUIET_MINUTES)} minutes${h.error === "" ? "" : `. The last try did not go: ${h.error}`}` })),

Principle 1: the held sentence is built here and again at line 1371 with identical text. Make one heldFact(h) helper so the wording cannot drift.

13601368 { label: "Restart", value: plan.value.restart },
13611369 { label: "The old jar", value: plan.value.swap },
13621370 { label: "The image", value: plan.value.still },
13631371 { label: "Waiting", value: plan.value.wait },
13641372 ].filter((f) => f.value !== "")
1365 : [{ label: "Not now", value: plan.error }],
1373 : [{ label: "Not now", value: plan.error }, ...held.filter((h) => h.ref === pin.sha256).map((h) => ({ label: "Held", value: `Saved and restarted once nobody has been on for ${String(QUIET_MINUTES)} minutes${h.error === "" ? "" : `. The last try did not go: ${h.error}`}` }))],
1374 ...(!plan.ok && owner && held.some((h) => h.ref === pin.sha256) ? { after: cancelForm(pin.sha256) } : {}),
13661375 ...(plan.ok
13671376 ? {
13681377 children: [...changed(`${box.path} gains`, plan.value.lines), ...changed(`${box.path} loses`, plan.value.gone)],
@@ -1372,7 +1381,11 @@ async function pinnedBlock(ctx: Ctx, box: GameBox, base: string, owner: boolean)
13721381 <input type="hidden" name="pin" value="${pin.sha256}" />
13731382 <input type="hidden" name="sha" value="${plan.value.sha}" />
13741383 ${btn("Save and restart the proxy", { variant: "secondary" })}
1375 </form>`,
1384 </form>${held.some((h) => h.ref === pin.sha256) ? cancelForm(pin.sha256) : html`<form method="post" action="${base}/jar" class="row-fields">
1385 <input type="hidden" name="pin" value="${pin.sha256}" />
1386 <input type="hidden" name="when" value="quiet" />
1387 ${btn(`Save when nobody has been on for ${String(QUIET_MINUTES)} minutes`, { variant: "ghost" })}
1388 </form>`}`,
13761389 }
13771390 : {}),
13781391 }
@@ -1404,7 +1417,17 @@ export async function gameJarSubmit(ctx: Ctx): Promise<Response> {
14041417 if (owner instanceof Response) return owner;
14051418 const pin = pinOf(field(form, "pin"));
14061419 if (pin === undefined || !onProxy) return notFoundPage(ctx);
1420 if (field(form, "when") === "quiet") {
1421 holdUntilQuiet(ctx.app, got.box, { kind: "pin", ref: pin.sha256, userId: ctx.auth.user!.id });
1422 return flashTo(ctx, plugins, { message: `Held: the proxy restarts with ${pin.title} once nobody has been on for ${String(QUIET_MINUTES)} minutes. Pressing Save and restart does it now.` });
1423 }
1424 if (field(form, "when") === "cancel") {
1425 cancelHeld(ctx.app, got.box, "pin", pin.sha256);
1426 return flashTo(ctx, plugins, { message: `Cancelled: ${pin.title} is not held any more.` });
1427 }
14071428 const put = await commitJar(ctx.app, ctx.auth.user!, got.box, pin, field(form, "sha"));
1429 // Saved now, so a held save of the same pin must not restart the proxy a second time.
1430 if (put.ok) cancelHeld(ctx.app, got.box, "pin", pin.sha256);
14081431 return flashTo(
14091432 ctx,
14101433 plugins,
test/game-metrics.test.ts +1
@@ -99,6 +99,7 @@ describe("the rollup", () => {
9999 db.exec((await import("../src/core/migrations/20261203080000-lent-proof.ts")).default);
100100 db.exec((await import("../src/core/migrations/20261116005600-check-runner.ts")).default);
101101 db.exec((await import("../src/core/migrations/20261202000000-game-people.ts")).default.replace(/^.*game_box.*$/m, ""));
102 db.exec("ALTER TABLE game_service ADD COLUMN online_at TEXT");
102103 db.query("INSERT INTO game_service (box_id, name) VALUES ('b', 'hub')").run();
103104 });
104105
test/game-when-quiet-door.test.ts added +205
@@ -0,0 +1,205 @@
1 /**
2 * Held changes at the doors (#18025): the New plugin row's `when=quiet` holds without committing and
3 * only an owner may; a held pin shows on its row and can be cancelled; a full check-in applies a
4 * quiet held change and a light one does not; and a person demoted since they asked is not committed
5 * as.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtempSync } from "node:fs";
9 import { rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { createSession } from "../src/core/sessions.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { readCompose } from "../src/games/compose.ts";
17 import { PINS } from "../src/games/proxy_jars.ts";
18 import { boxNamed, createGameBox, grant, storeJar, type GameBox } from "../src/games/store.ts";
19 import { applyWhenQuiet, heldOf, holdUntilQuiet } from "../src/games/when_quiet.ts";
20 import type { LogFields } from "../src/kernel/log.ts";
21 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23
24 quietLogs();
25
26 const COMPOSE = `name: game
27
28 x-paper: &paper
29 image: itzg/minecraft-server:latest
30 restart: unless-stopped
31
32 configs:
33 velocity_toml:
34 content: |
35 bind = "0.0.0.0:25565"
36 [servers]
37 hub = "hub:25565"
38 try = ["hub"]
39
40 volumes:
41 hub: {}
42
43 services:
44 velocity:
45 image: itzg/mc-proxy:latest
46 container_name: velocity
47 environment:
48 TYPE: VELOCITY
49 MEMORY: 768M
50 configs:
51 - source: velocity_toml
52 target: /config/velocity.toml
53
54 hub:
55 <<: *paper
56 container_name: hub
57 environment:
58 TYPE: PAPER
59 VERSION: "1.21.6"
60 MEMORY: 1G
61 `;
62
63 let dir = "";
64 let app: App;
65 let http: ForgeHttp;
66 let ada: User;
67 let bob: User;
68 let carol: User;
69 let box: GameBox;
70 let token = "";
71 const cookieOf = (u: User): string => `forge_session=${createSession(app.db, u.id).token}`;
72 /** The hub says, now, that nobody is on it. */
73 const reported = (): void => void app.db.run("UPDATE game_service SET online_json = '[]', online_at = ?2 WHERE box_id = ?1", [box.id, new Date().toISOString()]);
74 const tip = async (): Promise<string> => (await readCompose(app, box))!.sha;
75
76 beforeAll(async () => {
77 dir = mkdtempSync(join(tmpdir(), "forge-when-quiet-door-"));
78 app = createApp({ dataDir: dir, port: 0 });
79 http = forgeHttp(app);
80 const warn = app.log.warn.bind(app.log);
81 app.log.warn = ((message: string, fields?: LogFields) => {
82 if (message.startsWith("a change held until the box was quiet")) {
83 why = String(fields?.["why"]);
84 dropped();
85 }
86 return warn(message, fields);
87 }) as typeof app.log.warn;
88 const make = async (username: string, isAdmin: boolean): Promise<User> => {
89 const u = await createUser(app.db, { username, email: `${username}@f.test`, password: "a-good-passphrase", origin: "seed", isAdmin, trusted: true });
90 if (!u.ok) throw new Error(u.error);
91 return u.value;
92 };
93 ada = await make("ada", true);
94 bob = await make("bob", false);
95 carol = await make("carol", false);
96 const repo = await createRepo(app, ada, { name: "mc-network", visibility: "private" });
97 if (!repo.ok) throw new Error(String(repo.error));
98 const seeded = await commitToBranch(app, ada, repo.value, { message: "seed", files: [{ path: "docker-compose.yml", content: COMPOSE }] });
99 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
100 const made = createGameBox(app.db, { name: "mc", repo: "ada/mc-network" });
101 token = made.token;
102 box = boxNamed(app.db, "mc")!;
103 // The box's agent holds the pinned jars, and the forge keeps one of each, as the proxy page needs.
104 await sync({ jars: true });
105 box = boxNamed(app.db, "mc")!;
106 for (const [i, pin] of PINS.slice(0, 2).entries()) {
107 const stands = `PK\u0003\u0004 stands for pin ${String(i)}`;
108 expect((await storeJar(app, box.id, new Blob([stands]), `p${String(i)}.jar`)).ok).toBe(true);
109 app.db.query("UPDATE game_jar SET sha256 = ?1 WHERE sha256 = ?2").run(pin.sha256, new Bun.CryptoHasher("sha256").update(stands).digest("hex"));
110 }
111 app.db.run("INSERT INTO game_service (box_id, name, state, health, started_at, cpu_pct, mem_mib, seen_at) VALUES (?1, 'hub', 'running', 'healthy', '', 0, 0, '')", [box.id]);
112 grant(app.db, box.id, bob.id, "operator");
113 grant(app.db, box.id, carol.id, "owner");
114 }, 30_000);
115 afterAll(async () => {
116 app.close();
117 await rm(dir, { recursive: true, force: true });
118 });
119
120 const post = (u: User, body: Record<string, string>) =>
121 http.handle(new Request("http://forge.test/games/mc/velocity/jar", { method: "POST", headers: { cookie: cookieOf(u), origin: "http://forge.test" }, body: new URLSearchParams(body) }));
122 const page = async (u: User) => (await http.handle(new Request("http://forge.test/games/mc/velocity", { headers: { cookie: cookieOf(u) } }))).text();
123 const sync = (body: Record<string, unknown>) =>
124 http.handle(new Request("http://forge.test/api/v1/games/agent/sync", { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ agent: 1, ...body }) }));
125 /** Told when the forge drops a held change it could not apply: the one sign a check-in's own work is done. */
126 let dropped: () => void = () => {};
127 let why = "";
128 const droppedOnce = (): Promise<void> => new Promise((resolve) => (dropped = resolve));
129
130 test("when=quiet holds without committing, for an owner only; the held pin shows on its row and can be cancelled", async () => {
131 const before = await tip();
132 const pin = PINS[0]!.sha256;
133 expect((await post(bob, { pin, when: "quiet" })).status).toBe(404);
134 expect(heldOf(app, box)).toEqual([]);
135 expect((await post(ada, { pin, when: "quiet" })).status).toBeLessThan(400);
136 expect(heldOf(app, box).map((h) => h.ref)).toEqual([pin]);
137 expect(await tip()).toBe(before);
138 const shown = await page(ada);
139 expect(shown).toContain("Held");
140 expect(shown).toContain("Cancel the held save");
141 expect((await post(bob, { pin, when: "cancel" })).status).toBe(404);
142 expect(heldOf(app, box)).toHaveLength(1);
143 await post(ada, { pin, when: "cancel" });
144 expect(heldOf(app, box)).toEqual([]);
145 expect(await page(ada)).not.toContain("Cancel the held save");
146 });
147
148 test("a change that did not go shows its reason on the row; Save and restart now clears a held save of the same pin", async () => {
149 const pin = PINS[0]!.sha256;
150 holdUntilQuiet(app, box, { kind: "pin", ref: pin, userId: ada.id });
151 reported();
152 expect(await applyWhenQuiet(app, box, Date.now(), async () => ({ ok: false, error: "the tip moved" }))).toBe(0);
153 expect(await page(ada)).toContain("the tip moved");
154 expect(heldOf(app, box)).toHaveLength(1);
155 const planned = await tip();
156 const sent = await post(ada, { pin, sha: planned });
157 expect(sent.headers.get("set-cookie") ?? "").not.toContain("danger");
158 expect(sent.status).toBeLessThan(400);
159 expect(await tip()).not.toBe(planned);
160 expect(heldOf(app, box)).toEqual([]);
161 });
162
163 test("a person who is no longer an owner of the box is not committed as; one who still is passes that check", async () => {
164 const before = await tip();
165 holdUntilQuiet(app, box, { kind: "pin", ref: PINS[1]!.sha256, userId: carol.id });
166 grant(app.db, box.id, carol.id, "none");
167 reported();
168 expect(await applyWhenQuiet(app, box)).toBe(0);
169 expect(why).toContain("no longer an owner");
170 expect(heldOf(app, box)).toEqual([]);
171 expect(await tip()).toBe(before);
172 // One who still is an owner passes that check; what stops them here is the repository, a failure that may pass, so it is kept with its reason.
173 grant(app.db, box.id, carol.id, "owner");
174 holdUntilQuiet(app, box, { kind: "pin", ref: PINS[0]!.sha256, userId: carol.id });
175 reported();
176 expect(await applyWhenQuiet(app, box)).toBe(0);
177 const kept = heldOf(app, box).map((h) => h.error);
178 expect(kept).toHaveLength(1);
179 expect(kept[0]).not.toBe("");
180 expect(kept[0]).not.toContain("no longer an owner");
181 expect(await tip()).toBe(before);
182 app.db.run("DELETE FROM game_when_quiet WHERE box_id = ?1", [box.id]);
183 });
184
185 test("a full check-in applies a held change on a quiet box, a light one does not", async () => {
186 holdUntilQuiet(app, box, { kind: "pin", ref: "0".repeat(64), userId: ada.id });
187 reported();
188 const heard = droppedOnce();
189 expect((await sync({ light: true })).status).toBe(200);
190 // The light check-in's response is out; had it applied the change, the row would be on its way out.
191 expect(heldOf(app, box)).toHaveLength(1);
192 expect((await sync({ host: { memMiB: 7_900 } })).status).toBe(200);
193 await heard;
194 expect(heldOf(app, box)).toEqual([]);
195 });
196
197 test("a box whose player list is not reporting is not quiet: nothing held is applied", async () => {
198 holdUntilQuiet(app, box, { kind: "pin", ref: PINS[0]!.sha256, userId: ada.id });
199 app.db.run("UPDATE game_service SET online_json = '[]', online_at = NULL WHERE box_id = ?1", [box.id]);
200 const before = await tip();
201 expect(await applyWhenQuiet(app, box)).toBe(0);
202 expect(heldOf(app, box)).toHaveLength(1);
203 expect(await tip()).toBe(before);
204 app.db.run("DELETE FROM game_when_quiet WHERE box_id = ?1", [box.id]);
205 });
test/game-when-quiet.test.ts added +101
@@ -0,0 +1,101 @@
1 /**
2 * A change held until nobody has been on the box (src/games/when_quiet.ts): it waits while
3 * someone is on or someone came or went in the last 30 minutes, is applied at the first quiet
4 * check-in, and only once.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtempSync } from "node:fs";
8 import { rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { boxNamed, createGameBox, type GameBox } from "../src/games/store.ts";
14 import { recordMetrics } from "../src/games/metrics.ts";
15 import { applyWhenQuiet, FRESH_MS, heldOf, holdUntilQuiet, isQuiet, QUIET_MINUTES } from "../src/games/when_quiet.ts";
16
17 let dir = "";
18 let app: App;
19 let alice: User;
20 let box: GameBox;
21 const NOW = Date.parse("2026-12-04T05:00:00Z");
22 const MIN = 60_000;
23
24 beforeAll(async () => {
25 dir = mkdtempSync(join(tmpdir(), "forge-when-quiet-"));
26 app = createApp({ dataDir: dir, port: 0 });
27 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
28 if (!made.ok) throw new Error(made.error);
29 alice = made.value;
30 createGameBox(app.db, { name: "mc", repo: "alice/game" });
31 box = boxNamed(app.db, "mc")!;
32 app.db.run("INSERT INTO game_service (box_id, name, state, health, started_at, cpu_pct, mem_mib, seen_at) VALUES (?1, 'survival', 'running', 'healthy', '', 0, 0, '')", [box.id]);
33 });
34 afterAll(async () => {
35 await app.close?.();
36 await rm(dir, { recursive: true, force: true });
37 });
38
39 /** The server's player list as it reported it at `at`. */
40 const on = (names: string[], at: number = NOW) => app.db.run("UPDATE game_service SET online_json = ?2, online_at = ?3 WHERE box_id = ?1", [box.id, JSON.stringify(names.map((name) => ({ name }))), new Date(at).toISOString()]);
41 const event = (minutesAgo: number) => app.db.run("INSERT INTO game_player_event (box_id, service, player, kind, at) VALUES (?1, 'survival', 'otavert', 'leave', ?2)", [box.id, new Date(NOW - minutesAgo * MIN).toISOString()]);
42
43 test("a held change waits while someone is on, and for 30 minutes after the last came or went; then it is applied once", async () => {
44 expect(QUIET_MINUTES).toBe(30);
45 holdUntilQuiet(app, box, { kind: "pin", ref: "abc", userId: alice.id }, NOW);
46 const applied: string[] = [];
47 const apply = async (_a: App, _b: GameBox, h: { ref: string }) => (applied.push(h.ref), { ok: true as const });
48
49 on(["otavert"]);
50 expect(isQuiet(app, box, NOW)).toBe(false);
51 expect(await applyWhenQuiet(app, box, NOW, apply)).toBe(0);
52
53 on([]);
54 event(10);
55 expect(isQuiet(app, box, NOW)).toBe(false);
56 expect(await applyWhenQuiet(app, box, NOW, apply)).toBe(0);
57
58 on([], NOW + 21 * MIN);
59 expect(isQuiet(app, box, NOW + 21 * MIN)).toBe(true);
60 expect(await applyWhenQuiet(app, box, NOW + 21 * MIN, apply)).toBe(1);
61 expect(applied).toEqual(["abc"]);
62 expect(heldOf(app, box)).toEqual([]);
63 on([], NOW + 40 * MIN);
64 expect(await applyWhenQuiet(app, box, NOW + 40 * MIN, apply)).toBe(0);
65 });
66
67 test("a list that is not reporting is not an empty one: none, a stale one, or an event that does not read means not quiet", () => {
68 app.db.run("DELETE FROM game_player_event");
69 app.db.run("UPDATE game_service SET online_json = '[]', online_at = NULL WHERE box_id = ?1", [box.id]);
70 expect(isQuiet(app, box, NOW)).toBe(false);
71 on([], NOW);
72 expect(isQuiet(app, box, NOW)).toBe(true);
73 expect(isQuiet(app, box, NOW + FRESH_MS + 1_000)).toBe(false);
74 app.db.run("INSERT INTO game_player_event (box_id, service, player, kind, at) VALUES (?1, 'survival', 'x', 'leave', 'not a time')", [box.id]);
75 expect(isQuiet(app, box, NOW)).toBe(false);
76 app.db.run("DELETE FROM game_player_event");
77 });
78
79 test("a service's player list, once the box reports one, is stamped; a report without one leaves the stamp", () => {
80 app.db.run("UPDATE game_service SET online_at = NULL WHERE box_id = ?1", [box.id]);
81 recordMetrics(app.db, box, { metrics: { survival: { list: "There are 0 of a max of 20 players online:" } } }, new Date(NOW));
82 const at = () => app.db.query<{ at: string | null }, [string]>("SELECT online_at AS at FROM game_service WHERE box_id = ?1").get(box.id)!.at;
83 expect(at()).toBe(new Date(NOW).toISOString());
84 recordMetrics(app.db, box, { metrics: { survival: { tps: "" } } }, new Date(NOW + MIN));
85 expect(at()).toBe(new Date(NOW).toISOString());
86 });
87
88 test("a newer ask replaces the older; a failure that may pass is kept with its reason, one that cannot is dropped", async () => {
89 holdUntilQuiet(app, box, { kind: "pin", ref: "old", userId: alice.id }, NOW);
90 holdUntilQuiet(app, box, { kind: "pin", ref: "new", userId: alice.id }, NOW + MIN);
91 expect(heldOf(app, box).map((h) => h.ref)).toEqual(["new"]);
92 const later = NOW + 120 * MIN;
93 on([], later);
94 expect(await applyWhenQuiet(app, box, later, async () => ({ ok: false, error: "the tip moved" }))).toBe(0);
95 expect(heldOf(app, box).map((h) => [h.ref, h.error])).toEqual([["new", "the tip moved"]]);
96 expect(await applyWhenQuiet(app, box, later, async () => ({ ok: true }))).toBe(1);
97 expect(heldOf(app, box)).toEqual([]);
98 holdUntilQuiet(app, box, { kind: "pin", ref: "gone", userId: alice.id }, NOW);
99 expect(await applyWhenQuiet(app, box, later, async () => ({ ok: false, error: "no pin", permanent: true }))).toBe(0);
100 expect(heldOf(app, box)).toEqual([]);
101 });

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

Keyboard shortcuts

Docs