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

A game command whose answer never comes says so #17661

opened this

Merged 20h 46m ago, live in production

sold/game-answer → main 0 commits

  • Merged. sold/game-answer was merged into main as 486ac5c.

Review

Sign in to review this change.
7 files changed +213 −44
docs/features/games.md +1 −1
@@ -121,7 +121,7 @@ A game's own refusal is a failure: `op` with a name that does not exist ("That p
121121
122122 `/forge` typed as a command is heard like `!forge` ("Alice issued server command: /forge …" on Paper and Fabric); the server's own "Unknown command" shows to the player beside the forge's answer.
123123
124 **Quick commands.** Between full syncs the agent polls lightly every second (`FORGE_GAME_LIGHT_EVERY`): a body `{"agent":1,"light":true,"results":[…]}` that keeps only results and answers only `commands`, touching nothing else the forge knows. A command is handed out within a second of being queued, run, and its result sent at once, so a console command answers in under 3 s (measured in `test/game-findings.test.ts` against the real agent). A full sync that got no answer is sent again with `"retry":true`, and the forge skips the log lines it already holds, so the console does not show a line twice. The agent never asks `forge-waker` (sleep's proxy, with no shell) anything.
124 **Quick commands.** Between full syncs the agent polls lightly every second (`FORGE_GAME_LIGHT_EVERY`): a body `{"agent":1,"light":true,"results":[…]}` that keeps only results and answers only `commands`, touching nothing else the forge knows. A command is handed out within a second of being queued, run, and its result sent at once, so a console command answers in under 3 s (measured in `test/game-findings.test.ts` against the real agent). A full sync that got no answer is sent again with `"retry":true`, and the forge skips the log lines it already holds, so the console does not show a line twice. The agent never asks `forge-waker` (sleep's proxy, with no shell) anything. A command handed out and not answered (2 minutes for a console, player or shell command, 2 hours for a job) says "No answer came back; it may have run." An open page or terminal screen looks every 15 s, so it says so for a box that stopped syncing too; a page without JavaScript says it on the next look. It is never sent again; an answer that comes late replaces the words.
125125
126126 ## On a phone (#17656)
127127
src/games/notify.ts +15 −1
@@ -4,11 +4,12 @@
44 */
55
66 import type { App } from "../app.ts";
7 import { during } from "../perf/jobs.ts";
78
89 const watchers = new WeakMap<App, Map<string, Set<() => void>>>();
910
1011 /** Call `told` after each sync of `boxId`; the returned function stops it. */
11 export function onSync(app: App, boxId: string, told: () => void): () => void {
12 function onSync(app: App, boxId: string, told: () => void): () => void {
1213 const byBox = watchers.get(app) ?? new Map<string, Set<() => void>>();
1314 watchers.set(app, byBox);
1415 const set = byBox.get(boxId) ?? new Set<() => void>();
@@ -20,6 +21,19 @@ export function onSync(app: App, boxId: string, told: () => void): () => void {
2021 };
2122 }
2223
24 /** How often a watcher looks with no sync: a command's time to be answered runs out on a silent box too. */
25 export const LOOK_MS = 15_000;
26
27 /** Call `look` after each sync of `boxId` and every `LOOK_MS`; the returned function stops both. */
28 export function watchBox(app: App, boxId: string, look: () => void): () => void {
29 const off = onSync(app, boxId, look);
30 const timer = setInterval(() => during("game-look", look), LOOK_MS);
31 return () => {
32 clearInterval(timer);
33 off();
34 };
35 }
36
2337 /** A box synced: tell its watchers. */
2438 export function synced(app: App, boxId: string): void {
2539 for (const told of [...(watchers.get(app)?.get(boxId) ?? [])]) {
src/games/store.ts +52 −15
@@ -317,25 +317,62 @@ export interface CommandState {
317317 readonly ok: boolean | null;
318318 readonly output: string;
319319 }
320 export function commandOf(db: Database, id: string): CommandState | undefined {
320 /** What a command handed to the box and never answered says: it is not sent again, since running one twice is worse. */
321 export const NO_ANSWER = "No answer came back; it may have run.";
322 /** How long an answer is waited for: a quick command or a shell one ends in 30 s, a job (a pull, a world) can take an hour. */
323 const ANSWER_MS = 2 * 60_000;
324 const JOB_ANSWER_MS = 2 * 3_600_000;
325
326 /** A command as every door shows it. One whose answer never came is done with `ok` null; a late answer still replaces that. */
327 export function commandOf(db: Database, id: string, now = Date.now()): CommandState | undefined {
321328 const r = db
322329 .query<
323330 { id: string; kind: string; service: string; text: string; handed_at: string; done_at: string; ok: number | null; output: string },
324331 [string]
325332 >("SELECT id, kind, service, text, handed_at, done_at, ok, output FROM game_command WHERE id = ?1")
326333 .get(id);
327 return r === null
328 ? undefined
329 : {
330 id: r.id,
331 kind: r.kind,
332 service: r.service,
333 text: r.text,
334 handed: r.handed_at !== "",
335 done: r.done_at !== "",
336 ok: r.ok === null ? null : r.ok === 1,
337 output: r.output,
338 };
334 if (r === null) return undefined;
335 const limit = ["rcon", "people", "tell", "shell"].includes(r.kind) ? ANSWER_MS : JOB_ANSWER_MS;
336 const unanswered = r.done_at === "" && r.handed_at !== "" && now - Date.parse(r.handed_at) > limit;
337 return {
338 id: r.id,
339 kind: r.kind,
340 service: r.service,
341 text: r.text,
342 handed: r.handed_at !== "",
343 done: r.done_at !== "" || unanswered,
344 ok: r.ok === null ? null : r.ok === 1,
345 output: unanswered ? NO_ANSWER : r.output,
346 };
347 }
348
349 /** What became of a command, in words: "ok: …", "failed: …", that no answer came, or that it waits. */
350 export const commandSays = (c: Pick<CommandState, "done" | "ok" | "handed" | "output">): string =>
351 !c.done ? (c.handed ? "sent to the box" : "queued") : c.ok === null ? c.output : `${c.ok ? "ok" : "failed"}: ${c.output}`;
352
353 /**
354 * For a stream of a service's answers: each call gives the commands settled since the last one, among
355 * those unsettled when the stream began or queued since. One told "no answer came" is told again if
356 * its answer comes late.
357 */
358 export function answersOf(db: Database, boxId: string, service: string): (now?: number) => CommandState[] {
359 const pending = new Map<string, "waiting" | "unanswered">();
360 const look = (now: number): void => {
361 for (const c of recentCommands(db, boxId, service, 10, now)) if ((!c.done || c.ok === null) && !pending.has(c.id)) pending.set(c.id, c.done ? "unanswered" : "waiting");
362 };
363 look(Date.now());
364 return (now = Date.now()) => {
365 look(now);
366 const settled: CommandState[] = [];
367 for (const [id, was] of [...pending]) {
368 const c = commandOf(db, id, now);
369 if (c === undefined || c.ok !== null) pending.delete(id);
370 else if (!c.done || was === "unanswered") continue;
371 else pending.set(id, "unanswered");
372 if (c !== undefined) settled.push(c);
373 }
374 return settled;
375 };
339376 }
340377
341378 /** A service's RCON commands as typed, newest first, each once: the console's history. */
@@ -347,7 +384,7 @@ export const commandHistory = (db: Database, boxId: string, service: string, lim
347384 .all(boxId, service, limit)
348385 .map((r) => r.text);
349386
350 export const recentCommands = (db: Database, boxId: string, service: string, limit = 10): CommandState[] =>
387 export const recentCommands = (db: Database, boxId: string, service: string, limit = 10, now = Date.now()): CommandState[] =>
351388 db
352389 .query<{ id: string }, [string, string, number]>(
353390 // A pack check (`hashes`) is the forge's own, not a person's; it is said on the box, not
@@ -356,7 +393,7 @@ export const recentCommands = (db: Database, boxId: string, service: string, lim
356393 "SELECT id FROM game_command WHERE box_id = ?1 AND service = ?2 AND kind NOT IN ('hashes', 'tell') ORDER BY created_at DESC LIMIT ?3",
357394 )
358395 .all(boxId, service, limit)
359 .map((r) => commandOf(db, r.id)!);
396 .map((r) => commandOf(db, r.id, now)!);
360397
361398 // ---- secrets: the env files the box gets -----------------------------------------------------
362399
src/tui/screens/games.ts +5 −4
@@ -16,7 +16,7 @@ import { emptyText } from "../../core/empty_words.ts";
1616 import { consoleText, crashOf } from "../../games/console.ts";
1717 import { commitPolicy, policyOf, STILL_BILLED } from "../../games/sleep.ts";
1818 import { SHELL_SERVICE, queueShell } from "../../games/shell.ts";
19 import { onSync } from "../../games/notify.ts";
19 import { watchBox } from "../../games/notify.ts";
2020 import { joinAddress, nowWords, powerNow } from "../../games/gist.ts";
2121 import { findingLine, findingsOf as kickFindingsOf } from "../../games/findings.ts";
2222 import { eventsOf, eventWords, isBedrock, peopleOf, peopleWords, queuePeople } from "../../games/people.ts";
@@ -30,6 +30,7 @@ import { getUserByName } from "../../core/users.ts";
3030 import { commitServiceEnv, readCompose, serviceEnv } from "../../games/compose.ts";
3131 import { commitSettings, planSettings, settingsOf, type SettingsPlan, type SettingValue } from "../../games/settings.ts";
3232 import {
33 commandSays,
3334 SERVICE_NAME,
3435 boxNamed,
3536 bootTroubled,
@@ -274,7 +275,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
274275 const lines = (): string[] => {
275276 if (part === "console") {
276277 // A world command's link shows as host and path only: its query string may be a signed secret.
277 const done = recentCommands(f.app.db, box.id, service, 5).map((c) => `> ${c.kind === "world" ? worldWords(c.text) : c.text} ${c.done ? (c.ok ? "ok" : "failed") : "waiting for the box"}${c.output === "" ? "" : `: ${c.output.split("\n")[0]}`}`);
278 const done = recentCommands(f.app.db, box.id, service, 5).map((c) => `> ${c.kind === "world" ? worldWords(c.text) : c.text} ${commandSays(c).split("\n")[0]}`);
278279 // The game's colour codes read as plain text here; a crash leads, in one line.
279280 const crash = crashOf(logsOf(f.app.db, box.id, service, 2_000).lines);
280281 return [...(crash === undefined ? [] : [crash.summary]), ...consoleText(logsOf(f.app.db, box.id, service, 200).lines), ...done];
@@ -341,7 +342,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
341342 ],
342343 async load(signal) {
343344 // Each sync may bring an event or a finding: redraw then.
344 const off = onSync(f.app, box.id, () => ctx.invalidate());
345 const off = watchBox(f.app, box.id, () => ctx.invalidate());
345346 signal.addEventListener("abort", off, { once: true });
346347 },
347348 render(area, s) {
@@ -629,7 +630,7 @@ export function gameShellScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
629630 keys: [binding([":"], "run a command")],
630631 async load(signal) {
631632 // Each sync may bring an answer: redraw then, and stop listening when the screen goes.
632 const off = onSync(f.app, box.id, () => ctx.invalidate());
633 const off = watchBox(f.app, box.id, () => ctx.invalidate());
633634 signal.addEventListener("abort", off, { once: true });
634635 },
635636 render(area, s) {
src/web/pages/games.ts +13 −20
@@ -18,10 +18,11 @@ import { spareRow } from "../../games/spare_row.ts";
1818 import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts";
1919 import { commitSettings, planSettings, previewSettings, settingsOf, SETTINGS, type SettingValue, type SettingsPlan } from "../../games/settings.ts";
2020 import {
21 answersOf,
22 commandSays,
2123 bootWords,
2224 boxNamed,
2325 COMMAND_KINDS,
24 commandOf,
2526 grant,
2627 grantsOf,
2728 jarHref,
@@ -57,7 +58,7 @@ import { html, raw, type Html } from "../html.ts";
5758 import { consoleHtml, consoleText, crashOf, shareOnMclogs } from "../../games/console.ts";
5859 import { flashTo, page } from "../layout.ts";
5960 import { avatar, badge, btn, disclosure, field as input, row, rowList, time } from "../ui.ts";
60 import { onSync } from "../../games/notify.ts";
61 import { watchBox } from "../../games/notify.ts";
6162 import { accountLinks, chatLog, newLinkCode, playersOn, unlink } from "../../games/chat.ts";
6263 import { commitServer, planRemoveServer, planServer, wishOn } from "../../games/presets.ts";
6364 import { canSleep, commitPolicy, EMPTY_SECONDS, isGameServer, policyOf, STILL_BILLED } from "../../games/sleep.ts";
@@ -356,14 +357,12 @@ export function gameShellStream(ctx: Ctx): Response {
356357 const got = boxOf(ctx, "owner");
357358 if (got instanceof Response) return got;
358359 const { box } = got;
359 const pending = new Set(recentCommands(ctx.app.db, box.id, SHELL_SERVICE, 10).filter((c) => !c.done).map((c) => c.id));
360 const answers = answersOf(ctx.app.db, box.id, SHELL_SERVICE);
360361 return eventStream(ctx.app, ctx.request, (emit, _close, ready) =>
361 onSync(ctx.app, box.id, () => {
362 watchBox(ctx.app, box.id, () => {
362363 if (!ready()) return;
363 for (const c of recentCommands(ctx.app.db, box.id, SHELL_SERVICE, 10)) if (!c.done) pending.add(c.id);
364 const results = [...pending].map((id) => commandOf(ctx.app.db, id)).filter((c) => c !== undefined && c.done);
365 for (const r of results) pending.delete(r!.id);
366 if (results.length > 0) emit("lines", { lines: [], results: results.map((r) => ({ id: r!.id, ok: r!.ok, output: `$ ${r!.text}\n${r!.output}` })) });
364 const results = answers();
365 if (results.length > 0) emit("lines", { lines: [], results: results.map((r) => ({ id: r.id, ok: r.ok, output: `$ ${r.text}\n${r.output}`, says: commandSays(r) })) });
367366 }),
368367 );
369368 }
@@ -492,7 +491,7 @@ export const gamesConsoleJs = /* js */ `
492491 if (now && d.now) now.textContent = d.now;
493492 (d.results || []).forEach(function (r) {
494493 var el = document.getElementById('cmd-' + r.id);
495 if (el) el.textContent = (r.ok ? 'ok: ' : 'failed: ') + r.output;
494 if (el) el.textContent = r.says;
496495 });
497496 });
498497 // The command box walks its history with up and down, as a terminal does.
@@ -615,7 +614,7 @@ ${rawView ? tail.lines.join("\n") : raw(consoleHtml(tail.lines).join("\n"))}${ta
615614 row({
616615 title: c.kind === "world" ? worldWords(c.text) : html`<span class="mono">${c.kind} ${c.text}</span>`,
617616 meta: html`<span id="cmd-${c.id}"
618 >${c.done ? `${c.ok ? "ok" : "failed"}: ${c.output}` : c.handed ? "sent to the box" : "queued"}</span
617 >${commandSays(c)}</span
619618 >`,
620619 }),
621620 ),
@@ -945,24 +944,18 @@ export function gameServiceStream(ctx: Ctx): Response {
945944 const { box } = got;
946945 let shown = "";
947946 let after = Number(ctx.url.searchParams.get("after") ?? "0") || 0;
948 const pending = new Set(
949 recentCommands(ctx.app.db, box.id, service, 10)
950 .filter((c) => !c.done)
951 .map((c) => c.id),
952 );
947 const answers = answersOf(ctx.app.db, box.id, service);
953948 return eventStream(ctx.app, ctx.request, (emit, _close, ready) =>
954 onSync(ctx.app, box.id, () => {
949 watchBox(ctx.app, box.id, () => {
955950 if (!ready()) return;
956951 const got = logsOf(ctx.app.db, box.id, service, 500, after);
957952 after = got.last;
958 for (const c of recentCommands(ctx.app.db, box.id, service, 10)) if (!c.done) pending.add(c.id);
959 const results = [...pending].map((id) => commandOf(ctx.app.db, id)).filter((c) => c !== undefined && c.done);
960 for (const r of results) pending.delete(r!.id);
953 const results = answers();
961954 const now = nowWords(servicesOf(ctx.app.db, box.id).find((x) => x.name === service), powerNow(ctx.app.db, box.id, service));
962955 const shownBefore = shown;
963956 shown = now;
964957 if (got.lines.length > 0 || results.length > 0 || now !== shownBefore)
965 emit("lines", { now, html: consoleHtml(got.lines), lines: got.lines, results: results.map((r) => ({ id: r!.id, ok: r!.ok, output: r!.output })) });
958 emit("lines", { now, html: consoleHtml(got.lines), lines: got.lines, results: results.map((r) => ({ id: r.id, ok: r.ok, output: r.output, says: commandSays(r) })) });
966959 }),
967960 );
968961 }
test/game-answer.test.ts added +91
@@ -0,0 +1,91 @@
1 /**
2 * A command the box was given and never answered says so on every door; it is not sent again, since
3 * running one twice is worse, and an answer that comes late replaces the words.
4 */
5 import { expect, jest, test } from "bun:test";
6 import { mkdtempSync } from "node:fs";
7 import { rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp } from "../src/app.ts";
11 import { createSession } from "../src/core/sessions.ts";
12 import { createUser } from "../src/core/users.ts";
13 import { LOOK_MS } from "../src/games/notify.ts";
14 import { answersOf, boxNamed, commandOf, commandSays, createGameBox, NO_ANSWER, queueCommand, recordSync, type CommandKind } from "../src/games/store.ts";
15 import { forgeHttp } from "../src/http/server.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 test("a command whose answer never comes says so, is not sent again, and a late answer replaces it", async () => {
21 const dir = mkdtempSync(join(tmpdir(), "forge-game-answer-"));
22 const app = createApp({ dataDir: dir, port: 0 });
23 try {
24 createGameBox(app.db, { name: "mc" });
25 const box = boxNamed(app.db, "mc")!;
26 const answers = answersOf(app.db, box.id, "hub");
27 const queue = (kind: CommandKind, text: string): string => queueCommand(app.db, box.id, "hub", kind, text, "");
28 const says = (id: string): string => commandSays(commandOf(app.db, id)!);
29 const handed = (id: string, secondsAgo: number): void => {
30 app.db.query("UPDATE game_command SET handed_at = ?2 WHERE id = ?1").run(id, new Date(Date.now() - secondsAgo * 1_000).toISOString());
31 };
32 const id = queue("rcon", "say once");
33 expect(says(id)).toBe("queued");
34 expect(recordSync(app.db, box, { light: true }).map((c) => c.id)).toEqual([id]);
35 expect(says(id)).toBe("sent to the box");
36 expect(answers()).toEqual([]);
37 handed(id, 121);
38 expect(commandOf(app.db, id)).toMatchObject({ done: true, ok: null });
39 expect(says(id)).toBe(NO_ANSWER);
40 expect(answers().map(commandSays)).toEqual([NO_ANSWER]);
41 expect(answers()).toEqual([]);
42 expect(recordSync(app.db, box, { light: true })).toEqual([]);
43 recordSync(app.db, box, { light: true, results: [{ id, ok: true, output: "said" }] });
44 expect(answers().map(commandSays)).toEqual(["ok: said"]);
45 // A restart may take long: it is still waited for.
46 const restart = queue("restart", "");
47 handed(restart, 600);
48 expect(says(restart)).toBe("sent to the box");
49 } finally {
50 app.close();
51 await rm(dir, { recursive: true, force: true });
52 }
53 });
54
55 for (const [door, path, service, kind] of [
56 ["a service's page", "/games/mc/hub/stream", "hub", "rcon"],
57 ["the owner's console", "/games/mc/@shell/stream", "", "shell"],
58 ] as const)
59 test(`with no sync at all, ${door} is told that no answer came, and the look ends with the stream`, async () => {
60 const dir = mkdtempSync(join(tmpdir(), "forge-game-silent-"));
61 const app = createApp({ dataDir: dir, port: 0 });
62 jest.useFakeTimers();
63 try {
64 const ada = await createUser(app.db, { origin: "seed", trusted: true, username: "ada", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
65 if (!ada.ok) throw new Error(ada.error);
66 const http = forgeHttp(app);
67 createGameBox(app.db, { name: "mc" });
68 const box = boxNamed(app.db, "mc")!;
69 recordSync(app.db, box, { services: [{ name: "hub", state: "running" }] });
70 const id = queueCommand(app.db, box.id, service, kind, "say once", ada.value.id);
71 recordSync(app.db, box, { light: true });
72 const before = jest.getTimerCount();
73 const res = await http.handle(new Request(`http://forge.test${path}`, { headers: { cookie: `forge_session=${createSession(app.db, ada.value.id).token}` } }));
74 expect(res.status).toBe(200);
75 const reader = res.body!.getReader();
76 // The box goes silent, and the command's time runs out.
77 app.db.query("UPDATE game_command SET handed_at = ?2 WHERE id = ?1").run(id, new Date(Date.now() - 121_000).toISOString());
78 jest.advanceTimersByTime(LOOK_MS);
79 let text = "";
80 while (!text.includes("event: lines")) text += new TextDecoder().decode((await reader.read()).value);
81 expect(text).toContain(`"id":"${id}"`);
82 expect(text).toContain(NO_ANSWER);
83 expect(jest.getTimerCount()).toBeGreaterThan(before);
84 await reader.cancel();
85 expect(jest.getTimerCount()).toBe(before);
86 } finally {
87 jest.useRealTimers();
88 app.close();
89 await rm(dir, { recursive: true, force: true });
90 }
91 });
test/job-slices.test.ts +36 −3
@@ -40,7 +40,7 @@ import { sweepReach } from "../src/spawn/reach.ts";
4040 import { checkUpstream as checkParent } from "../src/spawn/upstream.ts";
4141 import { census, censusWords, processRows } from "../src/kernel/census.ts";
4242 import { runDelivery } from "../src/core/webhooks.ts";
43 import { pruneSessions } from "../src/core/sessions.ts";
43 import { createSession, pruneSessions } from "../src/core/sessions.ts";
4444 import { pruneTokens } from "../src/core/tokens.ts";
4545 import { runSync } from "../src/origins/sync.ts";
4646 import { checkDue } from "../src/actions/upstream_follow.ts";
@@ -69,6 +69,9 @@ import { pullDue } from "../src/apps/pull_schedule.ts";
6969 import { startMaintain } from "../src/maintain/runner.ts";
7070 import { retentionJobs } from "../src/system/retention.ts";
7171 import { returnSnoozed } from "../src/actions/gate_snooze.ts";
72 import { synced } from "../src/games/notify.ts";
73 import { boxNamed, createGameBox, recordSync } from "../src/games/store.ts";
74 import { forgeHttp } from "../src/http/server.ts";
7275 import { readNumbers } from "../src/web/pages/boards-index-stream.ts";
7376
7477 /**
@@ -83,7 +86,10 @@ quietLogs();
8386
8487 let app: App;
8588 let dir = "";
86 beforeAll(() => {
89 /** The fixture's game box, with one open page of its busy server: what "game-look" times. */
90 let gameBox = "";
91 let gameSaid = "";
92 beforeAll(async () => {
8793 ({ app, dir } = bigForge(BUSY));
8894 // A crew with work: a queue past the pump's 50-run window, and runs a dead forge left running.
8995 const at = new Date(Date.now() - 3_600_000).toISOString();
@@ -93,8 +99,31 @@ beforeAll(() => {
9399 for (let n = 1; n <= 80; n++) run.run(`q${n}`, `i${n}`, "queued", at, null);
94100 for (let n = 81; n <= 90; n++) run.run(`s${n}`, `i${n}`, "running", at, at);
95101 reads = createReadWriter(app.db, readLedger, app.log, Date.now, 1e9);
102 createGameBox(app.db, { name: "mc" });
103 const box = boxNamed(app.db, "mc")!;
104 gameBox = box.id;
105 recordSync(app.db, box, { services: [{ name: "hub", state: "running" }] });
106 const command = app.db.prepare(
107 "INSERT INTO game_command (id, box_id, service, kind, text, created_at, handed_at, done_at, ok) VALUES (?1, ?2, 'hub', ?3, 'list', ?4, ?4, ?5, ?6)",
108 );
109 const line = app.db.prepare("INSERT INTO game_log (box_id, service, line, at) VALUES (?1, 'hub', ?2, ?3)");
110 app.db.transaction(() => {
111 // The last ten were handed out and not answered yet: each is looked up at every look.
112 for (let n = 1; n <= 5_000; n++) command.run(`g${n}`, gameBox, n % 5 === 0 ? "restart" : "rcon", n > 4_990 ? new Date().toISOString() : at, n > 4_990 ? "" : at, n > 4_990 ? null : 1);
113 for (let n = 1; n <= 5_000; n++) line.run(gameBox, `[12:00:00 INFO]: line ${n}`, at);
114 })();
115 const page = await forgeHttp(app).handle(
116 new Request("http://forge.test/games/mc/hub/stream", { headers: { cookie: `forge_session=${createSession(app.db, "own").token}` } }),
117 );
118 const reader = page.body!.getReader();
119 closeGamePage = () => reader.cancel();
120 void (async () => {
121 for (let got = await reader.read(); !got.done; got = await reader.read()) gameSaid += new TextDecoder().decode(got.value);
122 })();
96123 }, 60_000);
97 afterAll(() => {
124 let closeGamePage = async (): Promise<void> => {};
125 afterAll(async () => {
126 await closeGamePage();
98127 reads.stop();
99128 app.db.close();
100129 rmSync(dir, { recursive: true, force: true });
@@ -248,6 +277,9 @@ function jobs(): Record<string, () => unknown> {
248277 "standing-sweep": () => sweepCallers(app.db, () => {}),
249278 "nightly-scan": () => nightlyDue(app.db, new Date(Date.now() - 24 * 3_600_000).toISOString(), 25),
250279 "pull-schedule": () => pullDue(app),
280 // One open game page's look (games/notify.ts), through its real stream: a sync tells the same
281 // watcher the timer does. Its log lines are sent once, so the timed look finds none new.
282 "game-look": () => synced(app, gameBox),
251283 maintain: () => maintainer.tick(new Date(Date.now() + 1e9)),
252284 // The retention slices, each as its timer calls it: bounded rows, paced by their own cost
253285 // (`system/retention.ts`).
@@ -412,6 +444,7 @@ test("every timed job's tick holds the loop under the ceiling on a busy fixture,
412444 measured.sort((a, b) => b.ms - a.ms);
413445 console.log(`job slices (ms), worst first:\n${measured.map((j) => ` ${j.name}: ${j.ms.toFixed(1)}`).join("\n")}`);
414446 expect(measured.filter((j) => j.ms >= CEILING_MS)).toEqual([]);
447 expect(gameSaid).toContain("line 5000");
415448 }, 60_000);
416449
417450 test("the memory sampler reads the heap's size without walking the heap", async () => {

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

Keyboard shortcuts

Docs