Public: anyone can read this; the crew can change it.
A game command whose answer never comes says so #17661
Merged 20h 46m ago, live in production
sold/game-answer → main 0 commits
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 | ||
| 121 | 121 | |
| 122 | 122 | `/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. |
| 123 | 123 | |
| 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. | |
| 125 | 125 | |
| 126 | 126 | ## On a phone (#17656) |
| 127 | 127 |
src/games/notify.ts +15 −1
| @@ -4,11 +4,12 @@ | ||
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | 6 | import type { App } from "../app.ts"; |
| 7 | import { during } from "../perf/jobs.ts"; | |
| 7 | 8 | |
| 8 | 9 | const watchers = new WeakMap<App, Map<string, Set<() => void>>>(); |
| 9 | 10 | |
| 10 | 11 | /** 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 { | |
| 12 | 13 | const byBox = watchers.get(app) ?? new Map<string, Set<() => void>>(); |
| 13 | 14 | watchers.set(app, byBox); |
| 14 | 15 | const set = byBox.get(boxId) ?? new Set<() => void>(); |
| @@ -20,6 +21,19 @@ export function onSync(app: App, boxId: string, told: () => void): () => void { | ||
| 20 | 21 | }; |
| 21 | 22 | } |
| 22 | 23 | |
| 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 | ||
| 23 | 37 | /** A box synced: tell its watchers. */ |
| 24 | 38 | export function synced(app: App, boxId: string): void { |
| 25 | 39 | for (const told of [...(watchers.get(app)?.get(boxId) ?? [])]) { |
src/games/store.ts +52 −15
| @@ -317,25 +317,62 @@ export interface CommandState { | ||
| 317 | 317 | readonly ok: boolean | null; |
| 318 | 318 | readonly output: string; |
| 319 | 319 | } |
| 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 { | |
| 321 | 328 | const r = db |
| 322 | 329 | .query< |
| 323 | 330 | { id: string; kind: string; service: string; text: string; handed_at: string; done_at: string; ok: number | null; output: string }, |
| 324 | 331 | [string] |
| 325 | 332 | >("SELECT id, kind, service, text, handed_at, done_at, ok, output FROM game_command WHERE id = ?1") |
| 326 | 333 | .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 | }; | |
| 339 | 376 | } |
| 340 | 377 | |
| 341 | 378 | /** 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 | ||
| 347 | 384 | .all(boxId, service, limit) |
| 348 | 385 | .map((r) => r.text); |
| 349 | 386 | |
| 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[] => | |
| 351 | 388 | db |
| 352 | 389 | .query<{ id: string }, [string, string, number]>( |
| 353 | 390 | // 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 | ||
| 356 | 393 | "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", |
| 357 | 394 | ) |
| 358 | 395 | .all(boxId, service, limit) |
| 359 | .map((r) => commandOf(db, r.id)!); | |
| 396 | .map((r) => commandOf(db, r.id, now)!); | |
| 360 | 397 | |
| 361 | 398 | // ---- secrets: the env files the box gets ----------------------------------------------------- |
| 362 | 399 |
src/tui/screens/games.ts +5 −4
| @@ -16,7 +16,7 @@ import { emptyText } from "../../core/empty_words.ts"; | ||
| 16 | 16 | import { consoleText, crashOf } from "../../games/console.ts"; |
| 17 | 17 | import { commitPolicy, policyOf, STILL_BILLED } from "../../games/sleep.ts"; |
| 18 | 18 | import { SHELL_SERVICE, queueShell } from "../../games/shell.ts"; |
| 19 | import { onSync } from "../../games/notify.ts"; | |
| 19 | import { watchBox } from "../../games/notify.ts"; | |
| 20 | 20 | import { joinAddress, nowWords, powerNow } from "../../games/gist.ts"; |
| 21 | 21 | import { findingLine, findingsOf as kickFindingsOf } from "../../games/findings.ts"; |
| 22 | 22 | import { eventsOf, eventWords, isBedrock, peopleOf, peopleWords, queuePeople } from "../../games/people.ts"; |
| @@ -30,6 +30,7 @@ import { getUserByName } from "../../core/users.ts"; | ||
| 30 | 30 | import { commitServiceEnv, readCompose, serviceEnv } from "../../games/compose.ts"; |
| 31 | 31 | import { commitSettings, planSettings, settingsOf, type SettingsPlan, type SettingValue } from "../../games/settings.ts"; |
| 32 | 32 | import { |
| 33 | commandSays, | |
| 33 | 34 | SERVICE_NAME, |
| 34 | 35 | boxNamed, |
| 35 | 36 | bootTroubled, |
| @@ -274,7 +275,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 274 | 275 | const lines = (): string[] => { |
| 275 | 276 | if (part === "console") { |
| 276 | 277 | // 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]}`); | |
| 278 | 279 | // The game's colour codes read as plain text here; a crash leads, in one line. |
| 279 | 280 | const crash = crashOf(logsOf(f.app.db, box.id, service, 2_000).lines); |
| 280 | 281 | 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 | ||
| 341 | 342 | ], |
| 342 | 343 | async load(signal) { |
| 343 | 344 | // 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()); | |
| 345 | 346 | signal.addEventListener("abort", off, { once: true }); |
| 346 | 347 | }, |
| 347 | 348 | render(area, s) { |
| @@ -629,7 +630,7 @@ export function gameShellScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 629 | 630 | keys: [binding([":"], "run a command")], |
| 630 | 631 | async load(signal) { |
| 631 | 632 | // 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()); | |
| 633 | 634 | signal.addEventListener("abort", off, { once: true }); |
| 634 | 635 | }, |
| 635 | 636 | render(area, s) { |
src/web/pages/games.ts +13 −20
| @@ -18,10 +18,11 @@ import { spareRow } from "../../games/spare_row.ts"; | ||
| 18 | 18 | import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts"; |
| 19 | 19 | import { commitSettings, planSettings, previewSettings, settingsOf, SETTINGS, type SettingValue, type SettingsPlan } from "../../games/settings.ts"; |
| 20 | 20 | import { |
| 21 | answersOf, | |
| 22 | commandSays, | |
| 21 | 23 | bootWords, |
| 22 | 24 | boxNamed, |
| 23 | 25 | COMMAND_KINDS, |
| 24 | commandOf, | |
| 25 | 26 | grant, |
| 26 | 27 | grantsOf, |
| 27 | 28 | jarHref, |
| @@ -57,7 +58,7 @@ import { html, raw, type Html } from "../html.ts"; | ||
| 57 | 58 | import { consoleHtml, consoleText, crashOf, shareOnMclogs } from "../../games/console.ts"; |
| 58 | 59 | import { flashTo, page } from "../layout.ts"; |
| 59 | 60 | 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"; | |
| 61 | 62 | import { accountLinks, chatLog, newLinkCode, playersOn, unlink } from "../../games/chat.ts"; |
| 62 | 63 | import { commitServer, planRemoveServer, planServer, wishOn } from "../../games/presets.ts"; |
| 63 | 64 | import { canSleep, commitPolicy, EMPTY_SECONDS, isGameServer, policyOf, STILL_BILLED } from "../../games/sleep.ts"; |
| @@ -356,14 +357,12 @@ export function gameShellStream(ctx: Ctx): Response { | ||
| 356 | 357 | const got = boxOf(ctx, "owner"); |
| 357 | 358 | if (got instanceof Response) return got; |
| 358 | 359 | 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); | |
| 360 | 361 | return eventStream(ctx.app, ctx.request, (emit, _close, ready) => |
| 361 | onSync(ctx.app, box.id, () => { | |
| 362 | watchBox(ctx.app, box.id, () => { | |
| 362 | 363 | 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) })) }); | |
| 367 | 366 | }), |
| 368 | 367 | ); |
| 369 | 368 | } |
| @@ -492,7 +491,7 @@ export const gamesConsoleJs = /* js */ ` | ||
| 492 | 491 | if (now && d.now) now.textContent = d.now; |
| 493 | 492 | (d.results || []).forEach(function (r) { |
| 494 | 493 | 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; | |
| 496 | 495 | }); |
| 497 | 496 | }); |
| 498 | 497 | // 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 | ||
| 615 | 614 | row({ |
| 616 | 615 | title: c.kind === "world" ? worldWords(c.text) : html`<span class="mono">${c.kind} ${c.text}</span>`, |
| 617 | 616 | 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 | |
| 619 | 618 | >`, |
| 620 | 619 | }), |
| 621 | 620 | ), |
| @@ -945,24 +944,18 @@ export function gameServiceStream(ctx: Ctx): Response { | ||
| 945 | 944 | const { box } = got; |
| 946 | 945 | let shown = ""; |
| 947 | 946 | 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); | |
| 953 | 948 | return eventStream(ctx.app, ctx.request, (emit, _close, ready) => |
| 954 | onSync(ctx.app, box.id, () => { | |
| 949 | watchBox(ctx.app, box.id, () => { | |
| 955 | 950 | if (!ready()) return; |
| 956 | 951 | const got = logsOf(ctx.app.db, box.id, service, 500, after); |
| 957 | 952 | 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(); | |
| 961 | 954 | const now = nowWords(servicesOf(ctx.app.db, box.id).find((x) => x.name === service), powerNow(ctx.app.db, box.id, service)); |
| 962 | 955 | const shownBefore = shown; |
| 963 | 956 | shown = now; |
| 964 | 957 | 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) })) }); | |
| 966 | 959 | }), |
| 967 | 960 | ); |
| 968 | 961 | } |
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"; | ||
| 40 | 40 | import { checkUpstream as checkParent } from "../src/spawn/upstream.ts"; |
| 41 | 41 | import { census, censusWords, processRows } from "../src/kernel/census.ts"; |
| 42 | 42 | import { runDelivery } from "../src/core/webhooks.ts"; |
| 43 | import { pruneSessions } from "../src/core/sessions.ts"; | |
| 43 | import { createSession, pruneSessions } from "../src/core/sessions.ts"; | |
| 44 | 44 | import { pruneTokens } from "../src/core/tokens.ts"; |
| 45 | 45 | import { runSync } from "../src/origins/sync.ts"; |
| 46 | 46 | import { checkDue } from "../src/actions/upstream_follow.ts"; |
| @@ -69,6 +69,9 @@ import { pullDue } from "../src/apps/pull_schedule.ts"; | ||
| 69 | 69 | import { startMaintain } from "../src/maintain/runner.ts"; |
| 70 | 70 | import { retentionJobs } from "../src/system/retention.ts"; |
| 71 | 71 | 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"; | |
| 72 | 75 | import { readNumbers } from "../src/web/pages/boards-index-stream.ts"; |
| 73 | 76 | |
| 74 | 77 | /** |
| @@ -83,7 +86,10 @@ quietLogs(); | ||
| 83 | 86 | |
| 84 | 87 | let app: App; |
| 85 | 88 | 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 () => { | |
| 87 | 93 | ({ app, dir } = bigForge(BUSY)); |
| 88 | 94 | // A crew with work: a queue past the pump's 50-run window, and runs a dead forge left running. |
| 89 | 95 | const at = new Date(Date.now() - 3_600_000).toISOString(); |
| @@ -93,8 +99,31 @@ beforeAll(() => { | ||
| 93 | 99 | for (let n = 1; n <= 80; n++) run.run(`q${n}`, `i${n}`, "queued", at, null); |
| 94 | 100 | for (let n = 81; n <= 90; n++) run.run(`s${n}`, `i${n}`, "running", at, at); |
| 95 | 101 | 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 | })(); | |
| 96 | 123 | }, 60_000); |
| 97 | afterAll(() => { | |
| 124 | let closeGamePage = async (): Promise<void> => {}; | |
| 125 | afterAll(async () => { | |
| 126 | await closeGamePage(); | |
| 98 | 127 | reads.stop(); |
| 99 | 128 | app.db.close(); |
| 100 | 129 | rmSync(dir, { recursive: true, force: true }); |
| @@ -248,6 +277,9 @@ function jobs(): Record<string, () => unknown> { | ||
| 248 | 277 | "standing-sweep": () => sweepCallers(app.db, () => {}), |
| 249 | 278 | "nightly-scan": () => nightlyDue(app.db, new Date(Date.now() - 24 * 3_600_000).toISOString(), 25), |
| 250 | 279 | "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), | |
| 251 | 283 | maintain: () => maintainer.tick(new Date(Date.now() + 1e9)), |
| 252 | 284 | // The retention slices, each as its timer calls it: bounded rows, paced by their own cost |
| 253 | 285 | // (`system/retention.ts`). |
| @@ -412,6 +444,7 @@ test("every timed job's tick holds the loop under the ceiling on a busy fixture, | ||
| 412 | 444 | measured.sort((a, b) => b.ms - a.ms); |
| 413 | 445 | console.log(`job slices (ms), worst first:\n${measured.map((j) => ` ${j.name}: ${j.ms.toFixed(1)}`).join("\n")}`); |
| 414 | 446 | expect(measured.filter((j) => j.ms >= CEILING_MS)).toEqual([]); |
| 447 | expect(gameSaid).toContain("line 5000"); | |
| 415 | 448 | }, 60_000); |
| 416 | 449 | |
| 417 | 450 | test("the memory sampler reads the heap's size without walking the heap", async () => { |
new above
offline