Public: anyone can read this; the crew can change it.
A machine stays trustworthy under load: power cycle, live status, a memory check, a patient healer #18472
Merged 3h 19m ago, live in production
scout/forge:scout/18465-a-machine-stays-trustworthy-under-load-p → main 0 commits fork 3 threads · 3 unresolved
18 files
changed +666
−8
- docs/features/game-box.md
- src/cloud/droplet.ts
- src/cloud/hetzner.ts
- src/cloud/machine.ts
- src/cloud/ovh.ts
- src/core/event_audience.ts
- src/games/cycle.ts
- src/games/live.ts
- src/http/games_routes.ts
- src/http/lazy_lists.ts
- src/tui/screens/games.ts
- src/web/games_machine.ts
- src/web/pages/games.ts
- test/budgets/unfixtured/games-box-live.json
- test/game-machine.test.ts
- test/no-polling.test.ts
- test/pinned-ceiling.test.ts
- test/security-floor-routes.test.ts
docs/features/game-box.md +6
| @@ -55,3 +55,9 @@ Every hour the agent reads the TLS group its HTTPS to the forge negotiates (`ope | ||
| 55 | 55 | ## The game door from the Apple app (#18337) |
| 56 | 56 | |
| 57 | 57 | `/api/v1/games/<box>/door` (`src/http/api/game_door.ts`) is the door's third way beside `/games/<box>` and the terminal's box screen (`w`): the same code (`src/games/write_window.ts`, `src/actions/passkey_proof.ts`), the box's owner only (forge admins own every box); anyone else gets 404. `GET` (a read token) answers the door as `{ state, minutes, …, words }`. `POST` (a write token; a cookie's post must be same-origin) takes `{ "op": "lock" }`; `{ "op": "challenge" }` for a passkey challenge, `allow` (the keys that may answer) and `rpId`; and `{ "op": "open", challenge, id, clientDataJSON, authenticatorData, signature }`, which opens a window of the box's length only when one of the owner's passkeys signed the challenge just now, else 403 in words and the door as it was. Setting the window's length and lock-on-leave stay on the page and in the terminal. Neither door writes an audit row for these: the page's own lock and open write none. |
| 58 | ||
| 59 | ## The machine under load (#18465) | |
| 60 | ||
| 61 | - **Live state:** the top of `/games/<box>` is one line, `checked in 4 s ago · load 1.4 · memory 3.1 of 8.0 GiB used`, and one line a container: `starting · its log moved 12 s ago`, `ready`, `stopped`, `asleep`. A container is *starting* while its health check runs, and says whether its log still moves (the healer waits on that, `PATIENCE_MS`); a box silent for a minute says `· silent` at the end of that line. The page follows the box's own sync over `GET /games/<box>/@live` (server-sent, one event when the line changes) and writes the words over the server's. The terminal's box screen (`b`) opens with the same lines. `src/games/live.ts`. | |
| 62 | - **Power cycle:** the box's owner (of the whole box, never an agent) plans it on the page (`?cycle=1`) or in the terminal (`P` on the box screen): what it will do, what is lost (everything in memory; servers stop unsaved) and what is kept (disks, address). Confirming brings the plan's digest back (good for 10 minutes, tied to the machine); a wrong, old or changed plan is refused. It needs a cloud account the forge may write to, and a machine is not cycled again within 5 minutes. Each attempt, refused or done, is a cloud audit row (who, the plan) and a `game.cycle` event. Hetzner `reset`, DigitalOcean `power_cycle`, OVHcloud hard `reboot`. `src/games/cycle.ts`. | |
| 63 | - **Memory before a start or an add** and **the healer's patience** are `box_memory.ts` and `heal.ts` above: a start with no room is refused with the numbers, and a starting container whose log moves is left alone for up to 10 minutes. |
src/cloud/droplet.ts +3
| @@ -110,6 +110,9 @@ export const digitalocean: Driver = { | ||
| 110 | 110 | async stopMachine(call, remote) { |
| 111 | 111 | await call("POST", `/droplets/${remote}/actions`, { type: "power_off" }); |
| 112 | 112 | }, |
| 113 | async cycleMachine(call, remote) { | |
| 114 | await call("POST", `/droplets/${remote}/actions`, { type: "power_cycle" }); | |
| 115 | }, | |
| 113 | 116 | async deleteMachine(call, remote) { |
| 114 | 117 | await call("DELETE", `/droplets/${remote}`); |
| 115 | 118 | }, |
src/cloud/hetzner.ts +5
| @@ -97,6 +97,11 @@ export const hetzner: Driver = { | ||
| 97 | 97 | async stopMachine(call, remote) { |
| 98 | 98 | await call("POST", `/servers/${numericId(remote, "machine")}/actions/poweroff`); |
| 99 | 99 | }, |
| 100 | async cycleMachine(call, remote) { | |
| 101 | // Hetzner's `reset` is the hard power cycle; `reboot` asks the stuck system politely and may | |
| 102 | // not be heard. | |
| 103 | await call("POST", `/servers/${numericId(remote, "machine")}/actions/reset`); | |
| 104 | }, | |
| 100 | 105 | async deleteMachine(call, remote) { |
| 101 | 106 | await call("DELETE", `/servers/${numericId(remote, "machine")}`); |
| 102 | 107 | }, |
src/cloud/machine.ts +6
| @@ -234,6 +234,12 @@ export interface Driver { | ||
| 234 | 234 | * these clouds. Absent where the forge has no such call. |
| 235 | 235 | */ |
| 236 | 236 | stopMachine?(call: Call, remote: string): Promise<void>; |
| 237 | /** | |
| 238 | * Power the machine off and on again, hard, as pulling its plug does: the way back when its agent | |
| 239 | * stopped answering under load (#18465). Nothing is deleted. Absent where the forge has no such | |
| 240 | * call. | |
| 241 | */ | |
| 242 | cycleMachine?(call: Call, remote: string): Promise<void>; | |
| 237 | 243 | /** Delete the data volume: nothing of the forge's data is left once this answers. */ |
| 238 | 244 | deleteVolume(call: Call, volume: string): Promise<void>; |
| 239 | 245 | /** Whether the volume is attached to no machine: a cloud detaches it after a delete answers, and refuses a new machine with it until then. */ |
src/cloud/ovh.ts +3
| @@ -115,6 +115,9 @@ export const ovh: Driver = { | ||
| 115 | 115 | async stopMachine(call, remote) { |
| 116 | 116 | await call("POST", `/instance/${remote}/stop`); |
| 117 | 117 | }, |
| 118 | async cycleMachine(call, remote) { | |
| 119 | await call("POST", `/instance/${remote}/reboot`, { type: "hard" }); | |
| 120 | }, | |
| 118 | 121 | async deleteMachine(call, remote) { |
| 119 | 122 | await call("DELETE", `/instance/${remote}`); |
| 120 | 123 | }, |
src/core/event_audience.ts +4 −1
| @@ -453,7 +453,10 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 453 | 453 | kind === "dev.state" || |
| 454 | 454 | // A fresh reading of a game box's machine, raised for each of the box's owners who is not an |
| 455 | 455 | // admin (admins hear `infra.cloud`): one owner's alone (`actions/cloud_says.ts`). |
| 456 | kind === "game.cloud" | |
| 456 | kind === "game.cloud" || | |
| 457 | // A box owner power cycled the box's machine (`games/cycle.ts`, #18465): their own receipt; the | |
| 458 | // cloud audit row is the admins'. | |
| 459 | kind === "game.cycle" | |
| 457 | 460 | ) |
| 458 | 461 | return "actor"; |
| 459 | 462 | // A run's summary, an app's serving state and its pictures can carry the |
src/games/cycle.ts added +146
| @@ -0,0 +1,146 @@ | ||
| 1 | /** | |
| 2 | * Power cycle a game box's machine from its page (#18465): the way back when load or memory pinned | |
| 3 | * the machine and its agent stopped answering, which the forge could not mend before. Planned | |
| 4 | * first, in words the page and the terminal both show, then confirmed with the plan's digest; a | |
| 5 | * stale or altered plan is refused. Only a person holding the owner grant on the whole box may ask, | |
| 6 | * and only on an account that lets the forge write. Every attempt, refused or not, writes a cloud | |
| 7 | * audit row (who, what, the plan) and a `game.cycle` event. A machine cycled in the last | |
| 8 | * `AGAIN_MS` is not cycled again: a boot loop is for a person to read, not to repeat. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { App } from "../app.ts"; | |
| 12 | import { driverOf } from "../cloud/drivers.ts"; | |
| 13 | import { capped } from "../cloud/ceiling.ts"; | |
| 14 | import { caller, type Driver } from "../cloud/machine.ts"; | |
| 15 | import { cloudName } from "../cloud/tree.ts"; | |
| 16 | import { getCloudAccount, NO_ACCOUNT, READ_ONLY } from "../core/cloud_account.ts"; | |
| 17 | import { recordAudit } from "../core/cloud_audit.ts"; | |
| 18 | import type { Pinned } from "../core/pinned.ts"; | |
| 19 | import type { User } from "../core/users.ts"; | |
| 20 | import { agoWords } from "../kernel/ago.ts"; | |
| 21 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 22 | import { withCloud } from "../actions/pinned.ts"; | |
| 23 | import { pinnedOfBox } from "../actions/cloud_says.ts"; | |
| 24 | import { roleOn, type GameBox } from "./store.ts"; | |
| 25 | ||
| 26 | /** How long a plan may be confirmed after it was shown. */ | |
| 27 | export const PLAN_MS = 10 * 60_000; | |
| 28 | /** The least time between two cycles of one machine. */ | |
| 29 | export const AGAIN_MS = 5 * 60_000; | |
| 30 | const ID = /^[A-Za-z0-9-]{1,64}$/; | |
| 31 | const PURPOSE = "cycle:machine"; | |
| 32 | const FAILED = "cycle:failed"; | |
| 33 | ||
| 34 | export interface CyclePlan { | |
| 35 | /** What it will do, what it costs the running servers, what is kept: one line each. */ | |
| 36 | readonly lines: readonly string[]; | |
| 37 | /** Why it cannot be done; empty when it can. */ | |
| 38 | readonly refusal: string; | |
| 39 | /** A digest of what the plan said: the confirm brings it back. */ | |
| 40 | readonly digest: string; | |
| 41 | readonly machine: string; | |
| 42 | } | |
| 43 | ||
| 44 | const NOT_YOURS = "Only an owner of the whole box may power cycle its machine."; | |
| 45 | ||
| 46 | interface Target { | |
| 47 | readonly row: Pinned; | |
| 48 | readonly driver: Driver; | |
| 49 | } | |
| 50 | ||
| 51 | /** | |
| 52 | * The machine a person may cycle, or why not. A box with no machine row, or no driver, has none to | |
| 53 | * cycle. | |
| 54 | */ | |
| 55 | function targetOf(app: App, user: User | undefined, box: GameBox): Result<Target, string> { | |
| 56 | if (user === undefined || user.kind === "agent" || roleOn(app.db, user, box.id, "") !== "owner") return err(NOT_YOURS); | |
| 57 | const row = pinnedOfBox(app, box); | |
| 58 | if (row === undefined || row.remote === "") return err(`${box.name} has no machine at its cloud to power cycle.`); | |
| 59 | if (row.state === "retired") return err(`${row.name} is retired: its cloud holds no machine.`); | |
| 60 | let driver: Driver; | |
| 61 | try { | |
| 62 | driver = capped(app, row.name, driverOf(row.target)); | |
| 63 | } catch { | |
| 64 | return err(`The forge has no way to power cycle a machine on ${row.target}.`); | |
| 65 | } | |
| 66 | if (driver.cycleMachine === undefined) return err(`The forge cannot power cycle a machine on ${cloudName(row.target)} yet.`); | |
| 67 | if (!ID.test(row.remote)) return err("Its id is not one the forge will send to a cloud."); | |
| 68 | return ok({ row, driver }); | |
| 69 | } | |
| 70 | ||
| 71 | /** | |
| 72 | * When the machine was last cycled; none when the latest attempt's cloud call failed, so a retry is | |
| 73 | * not locked out. | |
| 74 | */ | |
| 75 | const lastCycle = (app: App, row: Pinned): string | undefined => { | |
| 76 | const last = app.db | |
| 77 | .query<{ at: string; purpose: string }, [string, string, string, string, string]>("SELECT at, purpose FROM cloud_audit WHERE provider = ?1 AND account = ?2 AND purpose IN (?3, ?4) AND target = ?5 AND allowed = 1 ORDER BY id DESC LIMIT 1") | |
| 78 | .get(row.target, row.account, PURPOSE, FAILED, `machine:${row.remote}`); | |
| 79 | return last === null || last.purpose === FAILED ? undefined : last.at; | |
| 80 | }; | |
| 81 | ||
| 82 | const usedSince = (app: App, row: Pinned, at: number): boolean => { | |
| 83 | const last = lastCycle(app, row); | |
| 84 | return last !== undefined && Date.parse(last) >= at; | |
| 85 | }; | |
| 86 | ||
| 87 | const digestOf = (app: App, at: number, box: string, remote: string, lines: readonly string[]): string => | |
| 88 | `${at}.${new Bun.CryptoHasher("sha256", `game-cycle\0${app.hookSecret}`).update(JSON.stringify([at, box, remote, lines])).digest("hex").slice(0, 32)}`; | |
| 89 | const stampOf = (digest: string): number => (/^\d{10,15}\./.test(digest) ? Number(digest.slice(0, digest.indexOf("."))) : 0); | |
| 90 | ||
| 91 | /** The plan as the cycle would run now; no cloud is called. */ | |
| 92 | export function planCycle(app: App, user: User | undefined, box: GameBox, now = Date.now()): Result<CyclePlan, string> { | |
| 93 | const t = targetOf(app, user, box); | |
| 94 | if (!t.ok) return t; | |
| 95 | const { row } = t.value; | |
| 96 | const lines = [ | |
| 97 | `Will: power ${row.name} off and on at ${cloudName(row.target)} / ${row.account}, hard, as pulling its plug does.`, | |
| 98 | "Lost: everything in memory on it. Every server on the box stops without saving and starts again when the machine is up; a world may lose its last minutes.", | |
| 99 | "Kept: its disks, its address and every file. Nothing is deleted.", | |
| 100 | ]; | |
| 101 | const acct = getCloudAccount(app.db, row.target, row.account); | |
| 102 | const last = lastCycle(app, row); | |
| 103 | const refusal = | |
| 104 | acct === undefined ? NO_ACCOUNT | |
| 105 | : !acct.writeAllowed ? READ_ONLY | |
| 106 | : last !== undefined && now - Date.parse(last) < AGAIN_MS ? `${row.name} was power cycled ${agoWords(last, now)}: give it ${Math.ceil(AGAIN_MS / 60_000)} minutes to come up before cycling it again.` | |
| 107 | : ""; | |
| 108 | return ok({ lines, refusal, digest: digestOf(app, now, box.name, row.remote, lines), machine: row.name }); | |
| 109 | } | |
| 110 | ||
| 111 | function record(app: App, user: User, row: Pinned, box: GameBox, plan: CyclePlan, allowed: boolean, why: string, purpose = PURPOSE): void { | |
| 112 | recordAudit(app.db, { provider: row.target, account: row.account, purpose, target: `machine:${row.remote}`.slice(0, 200), bytesOut: 0, allowed, actor: user.id, plan: `${why}${plan.lines.join(" ")}` }); | |
| 113 | app.bus.append({ kind: "game.cycle", actorId: user.id, payload: { box: box.name, machine: row.name, ok: allowed, ...(why === "" ? {} : { refused: why.trim() }) } }); | |
| 114 | } | |
| 115 | ||
| 116 | /** | |
| 117 | * Do it. Refused attempts are audited as refused; an attempt is audited before the cloud is | |
| 118 | * called, so a failed call still leaves its row. | |
| 119 | */ | |
| 120 | export async function performCycle(app: App, user: User | undefined, box: GameBox, digest: string, now = Date.now()): Promise<Result<string, string>> { | |
| 121 | const t = targetOf(app, user, box); | |
| 122 | if (!t.ok) return t; | |
| 123 | const { row, driver } = t.value; | |
| 124 | const planned = planCycle(app, user, box, now); | |
| 125 | if (!planned.ok) return planned; | |
| 126 | const plan = planned.value; | |
| 127 | const who = user!; | |
| 128 | const at = stampOf(digest); | |
| 129 | const stale = | |
| 130 | at === 0 || now - at > PLAN_MS || now < at ? "That plan is more than 10 minutes old, or not one the forge showed: review the plan again." | |
| 131 | : usedSince(app, row, at) ? "That plan was already used: review the plan again." | |
| 132 | : digest !== digestOf(app, at, box.name, row.remote, plan.lines) ? `What ${row.name} is changed since it was planned: review the plan again.` | |
| 133 | : ""; | |
| 134 | const why = plan.refusal !== "" ? plan.refusal : stale; | |
| 135 | if (why !== "") { | |
| 136 | record(app, who, row, box, plan, false, `Refused: ${why} `); | |
| 137 | return err(why); | |
| 138 | } | |
| 139 | record(app, who, row, box, plan, true, ""); | |
| 140 | const done = await withCloud(app, { id: who.id, by: who.id }, { target: row.target, account: row.account }, "cycle-machine", async (f, token) => driver.cycleMachine!(caller(driver, f, token), row.remote), false); | |
| 141 | if (!done.ok) { | |
| 142 | record(app, who, row, box, plan, true, `Failed: ${done.error} `, FAILED); | |
| 143 | return done; | |
| 144 | } | |
| 145 | return ok(`Power cycling ${row.name}: it is down for a minute, then its agent checks in again and the servers start.`); | |
| 146 | } |
src/games/live.ts added +93
| @@ -0,0 +1,93 @@ | ||
| 1 | /** | |
| 2 | * What a game box is doing now (#18465), in words the page, its live stream and the terminal share: | |
| 3 | * how long since its agent checked in, its load and memory as it last said them, and each | |
| 4 | * container's state with its progress (starting, ready). Plain data in, plain data out: the one | |
| 5 | * query is `boxLive`'s, for the log's last line of a container that is still starting. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import { servicesOf, type GameBox, type GameService } from "./store.ts"; | |
| 10 | import { PATIENCE_MS } from "./heal.ts"; | |
| 11 | ||
| 12 | /** | |
| 13 | * A box that has not checked in for this long is called silent: its numbers are not to be trusted. | |
| 14 | */ | |
| 15 | export const SILENT_MS = 60_000; | |
| 16 | ||
| 17 | export interface ContainerLive { | |
| 18 | readonly name: string; | |
| 19 | readonly state: string; | |
| 20 | /** `starting`, `ready`, `stopped`, `asleep`, `unhealthy`, or the container's own word. */ | |
| 21 | readonly progress: string; | |
| 22 | /** One line: "starting · its log moved 12 s ago". */ | |
| 23 | readonly says: string; | |
| 24 | } | |
| 25 | ||
| 26 | export interface BoxLive { | |
| 27 | /** "checked in 4 s ago", "never checked in". */ | |
| 28 | readonly checkIn: string; | |
| 29 | readonly silent: boolean; | |
| 30 | /** "load 1.4", "load unknown". */ | |
| 31 | readonly load: string; | |
| 32 | /** "memory 3.1 of 8.0 GiB used". */ | |
| 33 | readonly memory: string; | |
| 34 | readonly containers: readonly ContainerLive[]; | |
| 35 | } | |
| 36 | ||
| 37 | /** "4 s", "3 min", "2 h": the age of a reading. */ | |
| 38 | export function spanWords(ms: number): string { | |
| 39 | const s = Math.max(0, Math.floor(ms / 1000)); | |
| 40 | if (s < 90) return `${s} s`; | |
| 41 | if (s < 90 * 60) return `${Math.round(s / 60)} min`; | |
| 42 | return `${Math.round(s / 3600)} h`; | |
| 43 | } | |
| 44 | ||
| 45 | const gib = (mib: number): string => (mib / 1024).toFixed(1); | |
| 46 | ||
| 47 | /** | |
| 48 | * Where a container is: running with a health check still going is starting; running otherwise is | |
| 49 | * ready. | |
| 50 | */ | |
| 51 | export function progressOf(s: Pick<GameService, "state" | "health" | "asleep">): string { | |
| 52 | if (s.asleep) return "asleep"; | |
| 53 | if (s.state === "running") return s.health === "starting" ? "starting" : s.health === "unhealthy" ? "unhealthy" : "ready"; | |
| 54 | if (s.state === "restarting" || s.state === "created") return "starting"; | |
| 55 | return s.state === "" ? "not reported" : s.state === "exited" || s.state === "dead" ? "stopped" : s.state; | |
| 56 | } | |
| 57 | ||
| 58 | /** | |
| 59 | * One container: its progress, and for a starting one whether its log still moves (the healer waits | |
| 60 | * on that). | |
| 61 | */ | |
| 62 | export function containerLive(s: GameService, lastLog: string | null, now: number): ContainerLive { | |
| 63 | const progress = progressOf(s); | |
| 64 | let says = progress; | |
| 65 | if (progress === "starting" && lastLog !== null) { | |
| 66 | const age = now - Date.parse(lastLog); | |
| 67 | says = age < PATIENCE_MS ? `starting · its log moved ${spanWords(age)} ago` : `starting · its log has been still for ${spanWords(age)}`; | |
| 68 | } | |
| 69 | return { name: s.name, state: s.state, progress, says }; | |
| 70 | } | |
| 71 | ||
| 72 | export function liveOf(box: Pick<GameBox, "seenAt" | "host">, services: readonly GameService[], lastLog: (name: string) => string | null, now: number): BoxLive { | |
| 73 | const age = box.seenAt === "" ? Number.NaN : now - Date.parse(box.seenAt); | |
| 74 | const load = box.host["load1"]; | |
| 75 | const total = box.host["memMiB"]; | |
| 76 | const used = box.host["memUsedMiB"]; | |
| 77 | return { | |
| 78 | checkIn: Number.isFinite(age) ? `checked in ${spanWords(age)} ago` : "never checked in", | |
| 79 | silent: !Number.isFinite(age) || age >= SILENT_MS, | |
| 80 | load: typeof load === "number" ? `load ${load.toFixed(1)}` : "load unknown", | |
| 81 | memory: typeof total === "number" && typeof used === "number" && total > 0 ? `memory ${gib(used)} of ${gib(total)} GiB used` : "memory unknown", | |
| 82 | containers: services.map((s) => containerLive(s, progressOf(s) === "starting" ? lastLog(s.name) : null, now)), | |
| 83 | }; | |
| 84 | } | |
| 85 | ||
| 86 | /** `liveOf` for a stored box. */ | |
| 87 | export function boxLive(db: Database, box: GameBox, now = Date.now()): BoxLive { | |
| 88 | const q = db.query<{ at: string | null }, [string, string]>("SELECT MAX(at) AS at FROM game_log WHERE box_id = ?1 AND service = ?2"); | |
| 89 | return liveOf(box, servicesOf(db, box.id), (name) => q.get(box.id, name)?.at ?? null, now); | |
| 90 | } | |
| 91 | ||
| 92 | /** The head line: "checked in 4 s ago · load 1.4 · memory 3.1 of 8.0 GiB used". */ | |
| 93 | export const liveHead = (l: BoxLive): string => `${l.checkIn} · ${l.load} · ${l.memory}${l.silent ? " · silent" : ""}`; |
src/http/games_routes.ts +3
| @@ -33,6 +33,7 @@ import { gameSparkView } from "../web/pages/games_spark_view.ts"; | ||
| 33 | 33 | import { gameSparkLink, gameSparkOpen, gameSparkPost, gameSparkRead } from "../web/pages/games_spark.ts"; |
| 34 | 34 | import { gameConfigCommit, gameConfigPage, gameConfigPreview } from "../web/pages/games_config.ts"; |
| 35 | 35 | import { gameDoorOptions, gameDoorSubmit } from "../web/pages/games_door.ts"; |
| 36 | import { gameCycleSubmit, gameLiveStream } from "../web/games_machine.ts"; | |
| 36 | 37 | import { publicOrigin } from "../core/public_origin.ts"; |
| 37 | 38 | import type { Ctx, Handler } from "./context.ts"; |
| 38 | 39 | import { InvalidJson } from "./json_body.ts"; |
| @@ -190,6 +191,8 @@ export function gamesRoutes(router: Router<Handler>): void { | ||
| 190 | 191 | // Before the service routes: no compose service can be named "@shell". |
| 191 | 192 | router.add("POST", "/games/:box/@shell", gameShellSubmit); |
| 192 | 193 | router.add("GET", "/games/:box/@shell/stream", gameShellStream); |
| 194 | router.add("GET", "/games/:box/@live", gameLiveStream); | |
| 195 | router.add("POST", "/games/:box/@cycle", gameCycleSubmit); | |
| 193 | 196 | router.add("POST", "/games/:box/@spark", gameSparkLink); |
| 194 | 197 | router.add("GET", "/games/:box/@spark/:key", gameSparkOpen); |
| 195 | 198 | router.add("GET", "/games/:box/spark/:key", gameSparkView); |
src/http/lazy_lists.ts +2
| @@ -673,6 +673,8 @@ export const OPERATIONS_ROUTES = [ | ||
| 673 | 673 | ["POST", "/games/:box/door/options"], |
| 674 | 674 | ["POST", "/games/:box/@shell"], |
| 675 | 675 | ["GET", "/games/:box/@shell/stream"], |
| 676 | ["GET", "/games/:box/@live"], | |
| 677 | ["POST", "/games/:box/@cycle"], | |
| 676 | 678 | ["POST", "/games/:box/@spark"], |
| 677 | 679 | ["GET", "/games/:box/@spark/:key"], |
| 678 | 680 | ["GET", "/games/:box/spark/:key"], |
src/tui/screens/games.ts +41 −5
| @@ -37,6 +37,8 @@ import { lendWords, lentRunnerOf, setLend } from "../../games/lend.ts"; | ||
| 37 | 37 | import { lendCannot } from "../../games/lend_why.ts"; |
| 38 | 38 | import { spareRow } from "../../games/spare_row.ts"; |
| 39 | 39 | import { healWords } from "../../games/heal.ts"; |
| 40 | import { planCycle, performCycle } from "../../games/cycle.ts"; | |
| 41 | import { boxLive, liveHead } from "../../games/live.ts"; | |
| 40 | 42 | import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts"; |
| 41 | 43 | import { pluginLines } from "../../games/plugins_loaded.ts"; |
| 42 | 44 | import { heldLines, heldOn } from "../../games/hold.ts"; |
| @@ -638,8 +640,18 @@ export function gameSettingsScreen(f: Session, ctx: Ctx, box: GameBox, service: | ||
| 638 | 640 | */ |
| 639 | 641 | export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen { |
| 640 | 642 | let top = 0; |
| 643 | let note = ""; | |
| 641 | 644 | const lines = (w: number): string[] => { |
| 642 | 645 | const b = listBoxes(f.app.db).find((x) => x.id === box.id) ?? box; |
| 646 | // What it is doing now, as the page's live block says it (check-in age, load, memory, each | |
| 647 | // container's progress). | |
| 648 | const live = boxLive(f.app.db, b); | |
| 649 | const nowLines = [ | |
| 650 | ...(note === "" ? [] : wrap(note, w)), | |
| 651 | ...wrap(liveHead(live), w), | |
| 652 | ...live.containers.filter((c) => mayDo(roleOn(f.app.db, f.user, b.id, c.name), "viewer")).flatMap((c) => wrap(`${c.name}: ${c.says}`, w)), | |
| 653 | "", | |
| 654 | ]; | |
| 643 | 655 | const held = heldLines(heldOn(f.app.db, f.user, b)).flatMap((l) => [...wrap(l, w), ""]); |
| 644 | 656 | // The page's Spare rows, in the same words, first (kept a minute, so a redraw is free). |
| 645 | 657 | const lending = lentRunnerOf(f.app.db, b.id) !== undefined; |
| @@ -652,16 +664,16 @@ export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 652 | 664 | const spare = [spareRow(f.app.db, f.app.config.dataDir, b).map(([k, v]) => `${k}: ${v}.`).join(" "), ""]; |
| 653 | 665 | if (!mayDo(roleOn(f.app.db, f.user, b.id), "owner")) { |
| 654 | 666 | const shared = boxStatusShared(b.diag); |
| 655 | return [...held, ...spare, ...(shared.length === 0 ? ["The box has said nothing yet."] : shared)]; | |
| 667 | return [...nowLines, ...held, ...spare, ...(shared.length === 0 ? ["The box has said nothing yet."] : shared)]; | |
| 656 | 668 | } |
| 657 | 669 | const plain = [...boxStatus(b.diag), ...pluginLines(b.diag), ...healWords(f.app.db, b)]; |
| 658 | 670 | const tails = boxTails(b.diag); |
| 659 | if (plain.length + tails.length === 0) return [...held, ...door, ...lend, ...spare, "The box has sent no diagnosis yet: its agent sends one with every check-in."]; | |
| 660 | return [...held, ...door, ...lend, ...spare, ...plain, ...tails.flatMap(([k, v]) => ["", `== ${k}`, ...v.split("\n")])]; | |
| 671 | if (plain.length + tails.length === 0) return [...nowLines, ...held, ...door, ...lend, ...spare, "The box has sent no diagnosis yet: its agent sends one with every check-in."]; | |
| 672 | return [...nowLines, ...held, ...door, ...lend, ...spare, ...plain, ...tails.flatMap(([k, v]) => ["", `== ${k}`, ...v.split("\n")])]; | |
| 661 | 673 | }; |
| 662 | return { | |
| 674 | const screen: Screen = { | |
| 663 | 675 | title: `${box.name}: the box`, |
| 664 | keys: [binding(["j", "k"], "scroll"), binding(["l"], "run checks while servers sleep: switch"), binding(["w"], "lock the game door"), binding(["a"], "lock when the player leaves: switch"), binding(["p"], "spark profiles")], | |
| 676 | keys: [binding(["j", "k"], "scroll"), binding(["l"], "run checks while servers sleep: switch"), binding(["w"], "lock the game door"), binding(["a"], "lock when the player leaves: switch"), binding(["p"], "spark profiles"), binding(["P"], "power cycle the machine (the box's owner)")], | |
| 665 | 677 | render(area, s) { |
| 666 | 678 | const c = ctx.theme.c; |
| 667 | 679 | const all = lines(Math.max(10, area.w)); |
| @@ -677,6 +689,29 @@ export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 677 | 689 | else if (e.key === "p") { |
| 678 | 690 | ctx.push(gameSparkScreen(f, ctx, box)); |
| 679 | 691 | return true; |
| 692 | } else if (e.key === "P") { | |
| 693 | // Planned, then confirmed: the plan's words, and its digest back to the action. | |
| 694 | const planned = planCycle(f.app, f.user, box); | |
| 695 | if (!planned.ok) note = planned.error; | |
| 696 | else if (planned.value.refusal !== "") note = planned.value.refusal; | |
| 697 | else | |
| 698 | ctx.push( | |
| 699 | confirmScreen(ctx, screen, { | |
| 700 | title: `Power cycle ${planned.value.machine}`, | |
| 701 | body: planned.value.lines, | |
| 702 | actions: [{ label: "Power cycle now" }, { label: "Not now" }], | |
| 703 | yesNo: true, | |
| 704 | onChoose: (i) => { | |
| 705 | if (i !== 0) return; | |
| 706 | void ctx.track( | |
| 707 | performCycle(f.app, f.user, box, planned.value.digest).then((done) => { | |
| 708 | note = done.ok ? done.value : done.error; | |
| 709 | ctx.invalidate(); | |
| 710 | }), | |
| 711 | ); | |
| 712 | }, | |
| 713 | }), | |
| 714 | ); | |
| 680 | 715 | } else if (e.key === "l" && mayOnGame(f.app.db, principalOfUser(f.user), box.id, "", "owner") && f.user !== undefined) { |
| 681 | 716 | const b = listBoxes(f.app.db).find((x) => x.id === box.id) ?? box; |
| 682 | 717 | setLend(f.app.db, b, lentRunnerOf(f.app.db, b.id) === undefined, f.user.id); |
| @@ -689,6 +724,7 @@ export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 689 | 724 | return true; |
| 690 | 725 | }, |
| 691 | 726 | }; |
| 727 | return screen; | |
| 692 | 728 | } |
| 693 | 729 | |
| 694 | 730 | /** A box's grants, as /games/<box> lists them; an owner sets one with `a` ("user role [service]"). */ |
src/web/games_machine.ts added +107
| @@ -0,0 +1,107 @@ | ||
| 1 | /** | |
| 2 | * A game box's machine on its page (#18465): the live line (check-in age, load, memory) and each | |
| 3 | * container's progress, kept fresh over the box's own stream (`GET /games/:box/@live`, told after | |
| 4 | * each check-in), and the owner's power cycle: planned on the page (`?cycle=1`), confirmed by a | |
| 5 | * form, refused again at the action. The words are `games/live.ts`'s and `games/cycle.ts`'s, the | |
| 6 | * ones the terminal says too. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { Ctx } from "../http/context.ts"; | |
| 10 | import { eventStream } from "../http/sse.ts"; | |
| 11 | import { boxLive, liveHead, type BoxLive } from "../games/live.ts"; | |
| 12 | import { watchBox } from "../games/notify.ts"; | |
| 13 | import { performCycle, planCycle } from "../games/cycle.ts"; | |
| 14 | import { boxNamed, mayDo, roleOn, seesBox, type GameBox } from "../games/store.ts"; | |
| 15 | import { notFoundPage } from "./chrome.ts"; | |
| 16 | import { field, readForm } from "./form.ts"; | |
| 17 | import { html, type Html } from "./html.ts"; | |
| 18 | import { flashTo } from "./layout.ts"; | |
| 19 | import { boxOf } from "./pages/games.ts"; | |
| 20 | import { btn, row, rowList } from "./ui.ts"; | |
| 21 | ||
| 22 | /** | |
| 23 | * The client: one stream, and the words it brings written over the server's. No layout moves: the | |
| 24 | * lines are one line each. | |
| 25 | */ | |
| 26 | export const liveJs = /* js */ ` | |
| 27 | (function () { | |
| 28 | var r = document.getElementById('game-live'); | |
| 29 | if (!r || !window.EventSource) return; | |
| 30 | var head = r.querySelector('[data-live-head]'); | |
| 31 | new EventSource(r.getAttribute('data-stream')).addEventListener('live', function (e) { | |
| 32 | var d = JSON.parse(e.data); | |
| 33 | head.textContent = d.head; | |
| 34 | r.setAttribute('data-silent', d.silent ? 'yes' : 'no'); | |
| 35 | Array.prototype.forEach.call(r.querySelectorAll('[data-live-container]'), function (el) { | |
| 36 | var c = d.containers.filter(function (x) { return x.name === el.getAttribute('data-live-container'); })[0]; | |
| 37 | if (c) el.textContent = c.says; | |
| 38 | }); | |
| 39 | }); | |
| 40 | })(); | |
| 41 | `; | |
| 42 | ||
| 43 | /** The live state the person may see: the box's line, and the containers they hold a role on. */ | |
| 44 | function shown(ctx: Ctx, box: GameBox, live: BoxLive): BoxLive { | |
| 45 | const user = ctx.auth.user; | |
| 46 | return { ...live, containers: live.containers.filter((c) => mayDo(roleOn(ctx.app.db, user, box.id, c.name), "viewer")) }; | |
| 47 | } | |
| 48 | ||
| 49 | export function liveBlock(ctx: Ctx, box: GameBox): Html { | |
| 50 | const live = shown(ctx, box, boxLive(ctx.app.db, box)); | |
| 51 | return html`<section class="settings-block" id="game-live" data-stream="/games/${box.name}/@live" data-silent="${live.silent ? "yes" : "no"}"> | |
| 52 | <p role="status" data-live-head>${liveHead(live)}</p> | |
| 53 | ${live.containers.length === 0 | |
| 54 | ? null | |
| 55 | : rowList(live.containers.map((c) => row({ title: c.name, meta: html`<span data-live-container="${c.name}">${c.says}</span>` })))} | |
| 56 | </section>`; | |
| 57 | } | |
| 58 | ||
| 59 | // GET /games/:box/@live: the live state after each check-in, once when it changes. | |
| 60 | export function gameLiveStream(ctx: Ctx): Response { | |
| 61 | const got = boxOf(ctx, "viewer"); | |
| 62 | if (got instanceof Response) return got; | |
| 63 | const id = got.box.id; | |
| 64 | let sent = ""; | |
| 65 | return eventStream(ctx.app, ctx.request, (emit, close, ready) => | |
| 66 | watchBox(ctx.app, id, () => { | |
| 67 | if (!ready()) return; | |
| 68 | const box = boxNamed(ctx.app.db, got.box.name); | |
| 69 | if (box === undefined || !seesBox(ctx.app.db, ctx.auth.user, box.id)) return close(); | |
| 70 | const live = shown(ctx, box, boxLive(ctx.app.db, box)); | |
| 71 | const body = { head: liveHead(live), silent: live.silent, containers: live.containers.map((c) => ({ name: c.name, says: c.says })) }; | |
| 72 | const text = JSON.stringify(body); | |
| 73 | if (text !== sent) emit("live", body); | |
| 74 | sent = text; | |
| 75 | }), | |
| 76 | ); | |
| 77 | } | |
| 78 | ||
| 79 | /** The owner's power cycle: a link to its plan, or the plan with its confirm. */ | |
| 80 | export function cycleBlock(ctx: Ctx, box: GameBox, asked: boolean): Html { | |
| 81 | const planned = planCycle(ctx.app, ctx.auth.user, box); | |
| 82 | if (!planned.ok) return html``; | |
| 83 | const p = planned.value; | |
| 84 | if (!asked) | |
| 85 | return html`<section class="settings-block" id="cycle"><h2>Machine</h2> | |
| 86 | ${btn("Plan a power cycle", { href: `/games/${box.name}?cycle=1`, size: "sm", variant: "secondary" })}</section>`; | |
| 87 | return html`<section class="settings-block" id="cycle"><h2>Power cycle ${p.machine}</h2> | |
| 88 | <dl class="status-rows">${p.lines.map((l) => html`<div data-cycle-line><dt>${l.slice(0, l.indexOf(": "))}</dt><dd>${l.slice(l.indexOf(": ") + 2)}</dd></div>`)}</dl> | |
| 89 | ${p.refusal === "" | |
| 90 | ? html`<form method="post" action="/games/${box.name}/@cycle"> | |
| 91 | <input type="hidden" name="digest" value="${p.digest}" /> | |
| 92 | ${btn("Power cycle now", { variant: "primary", title: "Hard power off and on; the plan above is what it does" })} | |
| 93 | </form>` | |
| 94 | : html`<p role="status" data-cycle-refused>${p.refusal}</p>`} | |
| 95 | ${btn("Not now", { href: `/games/${box.name}`, size: "sm", variant: "ghost" })}</section>`; | |
| 96 | } | |
| 97 | ||
| 98 | // POST /games/:box/@cycle: the owner's confirm of a plan. | |
| 99 | export async function gameCycleSubmit(ctx: Ctx): Promise<Response> { | |
| 100 | const got = boxOf(ctx, "owner"); | |
| 101 | if (got instanceof Response) return got; | |
| 102 | if (roleOn(ctx.app.db, ctx.auth.user, got.box.id, "") !== "owner") return notFoundPage(ctx); | |
| 103 | const form = await readForm(ctx, "rw"); | |
| 104 | if (form instanceof Response) return form; | |
| 105 | const done = await performCycle(ctx.app, ctx.auth.user, got.box, field(form, "digest")); | |
| 106 | return flashTo(ctx, `/games/${got.box.name}`, done.ok ? { message: done.value } : { tone: "danger", message: done.error }); | |
| 107 | } |
src/web/pages/games.ts +4 −1
| @@ -29,6 +29,7 @@ import { lendState, lentRunnerOf, setLend } from "../../games/lend.ts"; | ||
| 29 | 29 | import { lendCannot } from "../../games/lend_why.ts"; |
| 30 | 30 | import { spareRow } from "../../games/spare_row.ts"; |
| 31 | 31 | import { healWords } from "../../games/heal.ts"; |
| 32 | import { cycleBlock, liveBlock, liveJs } from "../games_machine.ts"; | |
| 32 | 33 | import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts"; |
| 33 | 34 | import { pluginLines } from "../../games/plugins_loaded.ts"; |
| 34 | 35 | import { HELD_DOC, heldOn, startsNothing } from "../../games/hold.ts"; |
| @@ -305,11 +306,12 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 305 | 306 | title: `Games · ${box.name}`, |
| 306 | 307 | styleCss: TOPOLOGY_CSS, |
| 307 | 308 | // The owner's console streams its answers over the box's own sync. |
| 308 | ...(role === "owner" ? { scriptJs: door?.passkey === true ? terminalBlocksJs + passkeyJs : terminalBlocksJs } : {}), | |
| 309 | scriptJs: (role === "owner" ? (door?.passkey === true ? terminalBlocksJs + passkeyJs : terminalBlocksJs) : "") + liveJs, | |
| 309 | 310 | body: html`${pageHead(box.name, { |
| 310 | 311 | sub: `${box.repo}@${box.branch}:${box.path}${box.composeSha === "" ? "" : ` · running ${box.composeSha.slice(0, 10)}`}`, |
| 311 | 312 | })} |
| 312 | 313 | ${holdNotice(ctx, box)} |
| 314 | ${liveBlock(ctx, box)} | |
| 313 | 315 | ${cloud === undefined |
| 314 | 316 | ? null |
| 315 | 317 | // An admin goes on to the machine itself on Infrastructure, where its cost and end are |
| @@ -347,6 +349,7 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 347 | 349 | ${spareBlock(ctx, box)} |
| 348 | 350 | ${role === "owner" ? boxBlock(box, [...healWords(ctx.app.db, box), ...packCheckLines(ctx.app, box.id)]) : sharedBoxBlock(box, packCheckLines(ctx.app, box.id))} ${role === "owner" ? shellBlock(ctx, box) : null} |
| 349 | 351 | ${role === "owner" ? lendBlock(ctx, box) : null} |
| 352 | ${role === "owner" ? cycleBlock(ctx, box, ctx.url.searchParams.get("cycle") === "1") : null} | |
| 350 | 353 | ${sparkBlock(ctx, box, role === "owner")} |
| 351 | 354 | ${role === "owner" ? grantsBlock(ctx, box) : null}`, |
| 352 | 355 | })); |
test/budgets/unfixtured/games-box-live.json added +4
test/game-machine.test.ts added +236
| @@ -0,0 +1,236 @@ | ||
| 1 | /** | |
| 2 | * A machine stays trustworthy under load (#18465): the live line and each container's progress, and | |
| 3 | * the power cycle: planned, confirmed, audited, only for the box's owner, only on an account the | |
| 4 | * forge may write to, and not twice in five minutes. A stand-in cloud answers every call. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, 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 { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts"; | |
| 13 | import { net } from "../src/actions/pinned.ts"; | |
| 14 | import { digitalocean } from "../src/cloud/droplet.ts"; | |
| 15 | import { hetzner } from "../src/cloud/hetzner.ts"; | |
| 16 | import { ovh } from "../src/cloud/ovh.ts"; | |
| 17 | import { insertPinned, setRemote } from "../src/core/pinned.ts"; | |
| 18 | import { createSession } from "../src/core/sessions.ts"; | |
| 19 | import { createUser, type User } from "../src/core/users.ts"; | |
| 20 | import { AGAIN_MS, performCycle, planCycle } from "../src/games/cycle.ts"; | |
| 21 | import { liveOf, spanWords } from "../src/games/live.ts"; | |
| 22 | import { boxNamed, createGameBox, grant, recordSync, setGameBoxMachine, type GameBox } from "../src/games/store.ts"; | |
| 23 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 24 | import { quietLogs } from "./helpers/globals.ts"; | |
| 25 | ||
| 26 | quietLogs(); | |
| 27 | ||
| 28 | describe("the power cycle call of each vendor", () => { | |
| 29 | const asked = async (go: (call: (m: string, p: string, b?: unknown) => Promise<unknown>) => Promise<void>) => { | |
| 30 | const seen: unknown[][] = []; | |
| 31 | await go(async (...a) => (seen.push(a), {})); | |
| 32 | return seen; | |
| 33 | }; | |
| 34 | test("Hetzner resets, DigitalOcean power-cycles, OVHcloud reboots hard", async () => { | |
| 35 | expect(await asked((c) => hetzner.cycleMachine!(c, "42"))).toEqual([["POST", "/servers/42/actions/reset"]]); | |
| 36 | await expect(hetzner.cycleMachine!(async () => ({}), "../x")).rejects.toThrow(); | |
| 37 | expect(await asked((c) => digitalocean.cycleMachine!(c, "7"))).toEqual([["POST", "/droplets/7/actions", { type: "power_cycle" }]]); | |
| 38 | expect(await asked((c) => ovh.cycleMachine!(c, "i-1"))).toEqual([["POST", "/instance/i-1/reboot", { type: "hard" }]]); | |
| 39 | }); | |
| 40 | }); | |
| 41 | ||
| 42 | describe("live state", () => { | |
| 43 | const T = Date.parse("2026-12-04T03:10:00Z"); | |
| 44 | const iso = (ms: number) => new Date(ms).toISOString(); | |
| 45 | const svc = (name: string, state: string, health: string, asleep = false) => ({ name, state, health, startedAt: "", cpuPct: 0, memMiB: 0, upSince: null, memLimitMiB: null, cpuLimit: null, seenAt: "", asleep }); | |
| 46 | test("says the check-in age, load and memory, and calls a quiet box silent", () => { | |
| 47 | const box = { seenAt: iso(T - 4_000), host: { load1: 58.04, memMiB: 8192, memUsedMiB: 7900 } }; | |
| 48 | const l = liveOf(box, [], () => null, T); | |
| 49 | expect(l.checkIn).toBe("checked in 4 s ago"); | |
| 50 | expect(l.load).toBe("load 58.0"); | |
| 51 | expect(l.memory).toBe("memory 7.7 of 8.0 GiB used"); | |
| 52 | expect(l.silent).toBe(false); | |
| 53 | expect(liveOf({ ...box, seenAt: iso(T - 6 * 60_000) }, [], () => null, T)).toMatchObject({ checkIn: "checked in 6 min ago", silent: true }); | |
| 54 | expect(liveOf({ seenAt: "", host: {} }, [], () => null, T)).toMatchObject({ checkIn: "never checked in", load: "load unknown", memory: "memory unknown", silent: true }); | |
| 55 | expect(spanWords(2 * 3_600_000)).toBe("2 h"); | |
| 56 | }); | |
| 57 | test("a container is starting until its health check passes, with its log's movement; then ready", () => { | |
| 58 | const l = liveOf( | |
| 59 | { seenAt: iso(T), host: {} }, | |
| 60 | [svc("a", "running", "starting"), svc("b", "running", "starting"), svc("c", "running", "healthy"), svc("d", "exited", ""), svc("e", "exited", "", true)], | |
| 61 | (n) => (n === "a" ? iso(T - 10_000) : iso(T - 5 * 60_000)), | |
| 62 | T, | |
| 63 | ); | |
| 64 | expect(l.containers.map((c) => [c.name, c.progress, c.says])).toEqual([ | |
| 65 | ["a", "starting", "starting · its log moved 10 s ago"], | |
| 66 | ["b", "starting", "starting · its log has been still for 5 min"], | |
| 67 | ["c", "ready", "ready"], | |
| 68 | ["d", "stopped", "stopped"], | |
| 69 | ["e", "asleep", "asleep"], | |
| 70 | ]); | |
| 71 | }); | |
| 72 | }); | |
| 73 | ||
| 74 | describe("the power cycle", () => { | |
| 75 | let dir = ""; | |
| 76 | let app: App; | |
| 77 | let servers: Servers; | |
| 78 | let ada: User; | |
| 79 | let owner: User; | |
| 80 | let operator: User; | |
| 81 | let box: GameBox; | |
| 82 | const calls: string[] = []; | |
| 83 | let confirmed = ""; | |
| 84 | const saved = { fetch: net.fetch, cloud: cloudNet.fetch }; | |
| 85 | const as = (u: User) => ({ cookie: `forge_session=${createSession(app.db, u.id).token}` }); | |
| 86 | const audit = () => app.db.query<{ allowed: number; actor: string; plan: string }, []>("SELECT allowed, actor, plan FROM cloud_audit WHERE purpose = 'cycle:machine' ORDER BY id").all(); | |
| 87 | ||
| 88 | beforeAll(async () => { | |
| 89 | dir = mkdtempSync(join(tmpdir(), "forge-game-machine-")); | |
| 90 | app = createApp({ dataDir: dir, port: 0 }); | |
| 91 | servers = await serve(app); | |
| 92 | const mk = async (username: string, adminIfFirst: boolean): Promise<User> => { | |
| 93 | const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst }); | |
| 94 | if (!u.ok) throw new Error(u.error); | |
| 95 | return u.value; | |
| 96 | }; | |
| 97 | ada = await mk("ada", true); | |
| 98 | owner = await mk("olly", false); | |
| 99 | operator = await mk("opal", false); | |
| 100 | cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" } }), { status: 200 }); | |
| 101 | const a = await addAccount(app, ada, "digitalocean", "main", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"); | |
| 102 | if (!a.ok) throw new Error(String(a.error)); | |
| 103 | allowWrite(app, ada, "digitalocean", "main", true); | |
| 104 | net.fetch = async (url, init) => { | |
| 105 | calls.push(`${init?.method ?? "GET"} ${new URL(url).pathname} ${typeof init?.body === "string" ? init.body : ""}`.trim()); | |
| 106 | return new Response("{}", { status: 200 }); | |
| 107 | }; | |
| 108 | const p = insertPinned(app.db, { name: "mc-machine", target: "digitalocean", account: "main", app: "", source: "", version: "", config: {}, host: "", claimHash: "", claimExpires: "", datacenter: "nyc1", size: "s-4vcpu-8gb" }, ada.id); | |
| 109 | setRemote(app.db, "mc-machine", { remote: "555", state: "running" }); | |
| 110 | createGameBox(app.db, { name: "mc" }); | |
| 111 | box = boxNamed(app.db, "mc")!; | |
| 112 | setGameBoxMachine(app.db, box.id, { pinnedId: p.id, place: "", monthlyCents: 0 }); | |
| 113 | box = boxNamed(app.db, "mc")!; | |
| 114 | grant(app.db, box.id, owner.id, "owner"); | |
| 115 | grant(app.db, box.id, operator.id, "operator"); | |
| 116 | recordSync(app.db, box, { services: [{ name: "velocity", state: "running", health: "starting" }], host: { load1: 58, memMiB: 8192, memUsedMiB: 7900 } }); | |
| 117 | box = boxNamed(app.db, "mc")!; | |
| 118 | }); | |
| 119 | afterAll(async () => { | |
| 120 | Object.assign(net, { fetch: saved.fetch }); | |
| 121 | cloudNet.fetch = saved.cloud; | |
| 122 | servers.stop(); | |
| 123 | app.close(); | |
| 124 | await rm(dir, { recursive: true, force: true }); | |
| 125 | }); | |
| 126 | ||
| 127 | test("only the box's owner may plan it, and the plan says what is lost and kept", () => { | |
| 128 | expect(planCycle(app, operator, box)).toEqual({ ok: false, error: "Only an owner of the whole box may power cycle its machine." }); | |
| 129 | expect(planCycle(app, undefined, box).ok).toBe(false); | |
| 130 | const p = planCycle(app, owner, box); | |
| 131 | if (!p.ok) throw new Error(p.error); | |
| 132 | expect(p.value.refusal).toBe(""); | |
| 133 | expect(p.value.lines.map((l) => l.split(":")[0])).toEqual(["Will", "Lost", "Kept"]); | |
| 134 | expect(p.value.lines[0]).toContain("mc-machine"); | |
| 135 | }); | |
| 136 | ||
| 137 | test("an operator, a wrong plan and a stale plan reach no cloud and are audited as refused", async () => { | |
| 138 | const p = planCycle(app, owner, box); | |
| 139 | if (!p.ok) throw new Error(p.error); | |
| 140 | expect((await performCycle(app, operator, box, p.value.digest)).ok).toBe(false); | |
| 141 | expect((await performCycle(app, owner, box, "")).ok).toBe(false); | |
| 142 | expect((await performCycle(app, owner, box, p.value.digest.replace(/.$/, (c) => (c === "0" ? "1" : "0")))).ok).toBe(false); | |
| 143 | const old = planCycle(app, owner, box, Date.now() - 11 * 60_000); | |
| 144 | if (!old.ok) throw new Error(old.error); | |
| 145 | const stale = await performCycle(app, owner, box, old.value.digest); | |
| 146 | expect(stale).toMatchObject({ ok: false, error: expect.stringContaining("more than 10 minutes old") }); | |
| 147 | expect(calls).toEqual([]); | |
| 148 | expect(audit().every((r) => r.allowed === 0)).toBe(true); | |
| 149 | expect(audit()).toHaveLength(3); | |
| 150 | }); | |
| 151 | ||
| 152 | test("a confirmed plan power cycles the machine, once, and is audited with who and the plan", async () => { | |
| 153 | const p = planCycle(app, owner, box); | |
| 154 | if (!p.ok) throw new Error(p.error); | |
| 155 | const done = await performCycle(app, owner, box, p.value.digest); | |
| 156 | expect(done).toMatchObject({ ok: true }); | |
| 157 | confirmed = p.value.digest; | |
| 158 | expect(calls).toEqual(['POST /v2/droplets/555/actions {"type":"power_cycle"}']); | |
| 159 | const row = audit().at(-1)!; | |
| 160 | expect(row).toMatchObject({ allowed: 1, actor: owner.id }); | |
| 161 | expect(row.plan).toContain("Will:"); | |
| 162 | const events = app.db.query<{ payload: string }, []>("SELECT payload FROM event WHERE kind = 'game.cycle'").all().map((r) => JSON.parse(r.payload)); | |
| 163 | expect(events.at(-1)).toMatchObject({ box: "mc", machine: "mc-machine", ok: true }); | |
| 164 | // Not again while it comes up. | |
| 165 | const again = planCycle(app, owner, box); | |
| 166 | if (!again.ok) throw new Error(again.error); | |
| 167 | expect(again.value.refusal).toContain("was power cycled"); | |
| 168 | expect((await performCycle(app, owner, box, again.value.digest)).ok).toBe(false); | |
| 169 | expect(calls).toHaveLength(1); | |
| 170 | const later = planCycle(app, owner, box, Date.now() + AGAIN_MS + 1000); | |
| 171 | expect(later.ok && later.value.refusal).toBe(""); | |
| 172 | }); | |
| 173 | ||
| 174 | test("a confirmed plan is single-use: replayed after the wait, it is refused and no cloud is called", async () => { | |
| 175 | const later = Date.now() + AGAIN_MS + 1000; | |
| 176 | expect(planCycle(app, owner, box, later)).toMatchObject({ ok: true, value: { refusal: "" } }); | |
| 177 | const replay = await performCycle(app, owner, box, confirmed, later); | |
| 178 | expect(replay).toMatchObject({ ok: false }); | |
| 179 | expect(!replay.ok && replay.error).toContain("already used"); | |
| 180 | expect(calls).toHaveLength(1); | |
| 181 | }); | |
| 182 | ||
| 183 | test("a cloud call that fails does not lock the owner out of trying again", async () => { | |
| 184 | const t0 = Date.now() + 3 * AGAIN_MS; | |
| 185 | const p = planCycle(app, owner, box, t0); | |
| 186 | if (!p.ok) throw new Error(p.error); | |
| 187 | const keep = net.fetch; | |
| 188 | net.fetch = async () => new Response("{}", { status: 500 }); | |
| 189 | const failed = await performCycle(app, owner, box, p.value.digest, t0); | |
| 190 | net.fetch = keep; | |
| 191 | expect(failed.ok).toBe(false); | |
| 192 | const retry = planCycle(app, owner, box, t0 + 1000); | |
| 193 | expect(retry).toMatchObject({ ok: true, value: { refusal: "" } }); | |
| 194 | if (!retry.ok) throw new Error(retry.error); | |
| 195 | expect(await performCycle(app, owner, box, retry.value.digest, t0 + 1000)).toMatchObject({ ok: true }); | |
| 196 | }); | |
| 197 | ||
| 198 | test("a read-only account is refused by the action, not only hidden", () => { | |
| 199 | allowWrite(app, ada, "digitalocean", "main", false); | |
| 200 | const p = planCycle(app, owner, box, Date.now() + AGAIN_MS + 1000); | |
| 201 | expect(p.ok && p.value.refusal).not.toBe(""); | |
| 202 | allowWrite(app, ada, "digitalocean", "main", true); | |
| 203 | }); | |
| 204 | ||
| 205 | test("the box's page shows the live line and each container to a viewer, the plan only to the owner; the stream and the confirm are gated", async () => { | |
| 206 | const page = async (u: User, q = "") => await (await fetch(`${servers.url}/games/mc${q}`, { headers: as(u) })).text(); | |
| 207 | const op = await page(operator); | |
| 208 | expect(op).toContain('id="game-live"'); | |
| 209 | expect(op).toContain("load 58.0"); | |
| 210 | expect(op).toContain("memory 7.7 of 8.0 GiB used"); | |
| 211 | expect(op).toContain('data-live-container="velocity"'); | |
| 212 | expect(op).toContain("starting"); | |
| 213 | expect(op).not.toContain("Plan a power cycle"); | |
| 214 | expect(op).not.toContain("/@cycle"); | |
| 215 | const own = await page(owner); | |
| 216 | expect(own).toContain("Plan a power cycle"); | |
| 217 | // Just cycled: the plan says wait, and offers no button. | |
| 218 | expect(await page(owner, "?cycle=1")).toContain("data-cycle-refused"); | |
| 219 | app.db.run("DELETE FROM cloud_audit WHERE purpose = 'cycle:machine'"); | |
| 220 | const planned = await page(owner, "?cycle=1"); | |
| 221 | expect(planned).toContain('action="/games/mc/@cycle"'); | |
| 222 | expect(planned).toContain('name="digest"'); | |
| 223 | expect((await page(operator, "?cycle=1")).includes("/@cycle")).toBe(false); | |
| 224 | const post = (u: User, digest: string) => | |
| 225 | fetch(`${servers.url}/games/mc/@cycle`, { method: "POST", redirect: "manual", headers: { ...as(u), origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, body: `digest=${encodeURIComponent(digest)}` }); | |
| 226 | expect((await post(operator, "x")).status).toBe(404); | |
| 227 | const stream = await fetch(`${servers.url}/games/mc/@live`, { headers: as(operator) }); | |
| 228 | expect(stream.status).toBe(200); | |
| 229 | expect(stream.headers.get("content-type")).toContain("text/event-stream"); | |
| 230 | await stream.body?.cancel(); | |
| 231 | const nobody = await fetch(`${servers.url}/games/mc/@live`, { redirect: "manual" }); | |
| 232 | expect(nobody.status).not.toBe(200); | |
| 233 | const refused = await post(owner, "bad"); | |
| 234 | expect(refused.status).toBe(303); | |
| 235 | }); | |
| 236 | }); |
test/no-polling.test.ts +1
| @@ -332,6 +332,7 @@ const NOT_WALKED: Record<string, string> = { | ||
| 332 | 332 | "/games/:box": "a game box, which the seed does not make (test/games.test.ts covers it)", |
| 333 | 333 | "/games/:box/:service": "a game box, which the seed does not make (test/games.test.ts covers it)", |
| 334 | 334 | "/games/:box/@shell/stream": "a game box's shell output for its owner, which the seed does not make (test/game-console.test.ts covers it)", |
| 335 | "/games/:box/@live": "a game box's live state stream, which the seed does not make (test/game-machine.test.ts covers it)", | |
| 335 | 336 | "/games/:box/:service/stream": "a game box, which the seed does not make (test/games.test.ts covers it)", |
| 336 | 337 | "/games/:box/:service/config": "a game box, which the seed does not make (test/game-plugin-config-doors.test.ts covers it)", |
| 337 | 338 | "/games/:box/:service/map": "a game box's map, which the seed does not make (test/games-map.test.ts covers it)", |
test/pinned-ceiling.test.ts +1 −1
| @@ -369,7 +369,7 @@ describe("cloud account ceiling", () => { | ||
| 369 | 369 | // And one to stop or delete a machine or volume (actions/cloud_end.ts `endDriver`, handed to |
| 370 | 370 | // `endView`, which narrows the driver to stopMachine, deleteMachine and deleteVolume: an end |
| 371 | 371 | // cannot provision, so it takes money out of the bill, never in). |
| 372 | expect(uses).toBe(18); | |
| 372 | expect(uses).toBe(19); | |
| 373 | 373 | }); |
| 374 | 374 | }); |
| 375 | 375 |
test/security-floor-routes.test.ts +1
| @@ -76,6 +76,7 @@ const UNSEEDED: Record<string, string> = { | ||
| 76 | 76 | "/games/:box": "a game box, which the seed does not make (test/games.test.ts covers it)", |
| 77 | 77 | "/games/:box/:service": "a game box, which the seed does not make (test/games.test.ts covers it)", |
| 78 | 78 | "/games/:box/@shell/stream": "a game box's shell output for its owner, which the seed does not make (test/game-console.test.ts covers it)", |
| 79 | "/games/:box/@live": "a game box's live state stream, which the seed does not make (test/game-machine.test.ts covers it)", | |
| 79 | 80 | "/games/:box/:service/stream": "a game box, which the seed does not make (test/games.test.ts covers it)", |
| 80 | 81 | "/games/:box/:service/config": "a game box, which the seed does not make (test/game-plugin-config-doors.test.ts covers it)", |
| 81 | 82 | "/games/:box/:service/map": "a game box's map, which the seed does not make (test/games-map.test.ts covers it)", |
new above
offline
Medium: record(allowed=true) is written before the cloud call, and lastCycle counts it. A failed driver call (cloud error) still blocks a retry for 5 minutes. Count only calls that succeeded.