Public: anyone can read this; the crew can change it.
A game box whose volume may hold other worlds starts nothing and says why #17746
Merged 17h 9m ago, live in production
sold/game-hold → main 0 commits
16 files
changed +520
−47
- docs/features/game-box.md
- docs/features/games.md
- docs/features/infra.md
- src/cloud/containers.ts
- src/cloud/tree.ts
- src/games/agent.sh
- src/games/diag.ts
- src/games/hold.ts
- src/http/mcp/tools/games.ts
- src/tui/screens/games.ts
- src/web/pages/cloud_tree.ts
- src/web/pages/games.ts
- test/cloud-containers.test.ts
- test/game-diag.test.ts
- test/game-hold.test.ts
- test/game-volume.test.ts
docs/features/game-box.md +9 −2
| @@ -19,11 +19,18 @@ experiment. | ||
| 19 | 19 | - **Never blind:** compose up, pull and the power verbs run in a background job queue, one at a time, output to `.up.log`; the agent keeps syncing every 5 s whatever runs, and a failed up is not retried for the same compose. Every sync carries `diag`, about 8 KB: the job (label, since, running, last exit) and the tail of `.up.log`, `docker ps -a` and `docker images` (bounded), the agent's and Docker's journal, cloud-init's status, `df -h /`, where Docker's data root is mounted and whether the volume is, and the versions. The whole diag runs within one deadline (8 s; every docker read in a sync is capped at 5 s), and over it the sync carries `{"note":"diag ran over 8 s"}`, so a docker that hangs never holds the sync. A job interrupted under the agent (a stale pid with no exit status, or a pid that is now another program's, by its command line) is queued again, never marked failed. The forge keeps the latest (16 KB at most). The box's owner (and forge admins) read it whole; anyone else who may see one of its services reads only what it is doing ("Applying since …", "N of M running"), naming no container, image, error or journal. For the owner, `/games/<box>` has a Box section of plain lines ("Pulling …", "compose up failed: <its last error line>", "Docker's data is on the root disk, not the volume", "The volume is not mounted at …") over a folded run log of the raw tails; the terminal's Games shows the top line (`b` there opens the box: the same plain lines and raw tails) and the MCP games tool's `list` up to three. |
| 20 | 20 | - **The proxy's own jars:** a compose file that mounts `./jars:/forge-jars:ro` in the proxy and names the files in its `PLUGINS` comes with `jars: [{ name, url, sha256 }]` in the same answer. The agent fetches each into `/opt/forge-game/jars` and checks its sha256 before the up; one that is missing or wrong holds back the proxy alone. An up that succeeds does not prove that the plugin loaded: read the proxy's log for that. Every full sync's body says `"jars": true`, which an agent from before this does not. |
| 21 | 21 | - **The volume:** the box's worlds live on its cloud volume, never on the root disk a replace destroys. The boot runs `agent.sh --mount-volume` before Docker is installed, and the agent runs the same check once at each start: |
| 22 | - **Find:** the volume is the device the cloud attaches (`/dev/disk/by-id/scsi-0DO_Volume_*` on DigitalOcean, `scsi-0HC_Volume_*` on Hetzner), waited for up to a minute at boot. With none, nothing is mounted and the log says so. | |
| 22 | - **Find:** the volume is the device the cloud attaches (`/dev/disk/by-id/scsi-0DO_Volume_*` on DigitalOcean, `scsi-0HC_Volume_*` on Hetzner), waited for up to a minute at boot. With none, nothing is mounted, the log says so and a new box is held (below). | |
| 23 | 23 | - **Mounted means the volume holds the data directory:** `findmnt -n -o SOURCE --target <dir>` is the device, by-id links resolved. Another device mounted there is not the volume. |
| 24 | 24 | - **Format:** only a blank device is formatted (ext4, label `forge-data`). One with a filesystem is used as it is; one with any other signature (`wipefs` finds one) is refused, never formatted. |
| 25 | 25 | - **Mount:** at the data directory (the boot's `FORGE_GAME_DATA`, `/mnt/<volume>`), in `/etc/fstab` by UUID with `nofail` (once), and a systemd drop-in (`docker.service.d/forge-volume.conf`, `RequiresMountsFor=`) so Docker never starts without the volume after a reboot, rather than on the old copy under the mount point. |
| 26 | - **Move:** a data directory that already holds data on the root disk (a box made before this) is moved once: the volume is mounted aside, refused if it already holds anything, then compose stops, Docker stops, `rsync -aHAX` copies, and the volume is mounted at the data directory, put in fstab, the drop-in written and the compose sha dropped, all before Docker starts again; compose comes up at the next sync. The root disk's copy stays under the mount, untouched, until a person removes it. If rsync is missing, or compose, Docker or the copy fails, Docker starts again on the root disk's data as it was. If the final mount fails after the copy, Docker starts again on the root disk and the log says so with `failed:`. | |
| 26 | - **Move:** a data directory that already holds data on the root disk (a box made before this) is moved once: the volume is mounted aside, refused and held if it already holds anything, then compose stops, Docker stops, `rsync -aHAX` copies, and the volume is mounted at the data directory, put in fstab, the drop-in written and the compose sha dropped, all before Docker starts again; compose comes up at the next sync. The root disk's copy stays under the mount, untouched, until a person removes it. If rsync is missing, or compose, Docker or the copy fails, Docker starts again on the root disk's data as it was. If the final mount fails after the copy, Docker starts again on the root disk and the log says so with `failed:`. | |
| 27 | - **Held:** when the volume may hold other worlds than the root disk, the agent starts nothing: both hold data, the volume has a signature or a filesystem that cannot be mounted, or a new box has no volume. `/opt/forge-game/.volume.hold` says which (`other-worlds`, `signature`, `mount`, `no-volume`) and when the agent last looked; each sync's `diag.hold` carries it. The box still syncs, stops and pulls, and a start is answered with the reason. **Held does not mean stopped:** containers that already run are left alone, and Docker starts them again after a reboot. A volume that was blank or empty, an unfinished copy by this same machine (`.forge-copying` holds its machine id) and a box that ran without a volume do not hold. | |
| 28 | - **The usual case is after a replace:** the volume came late, Docker made its empty folders on the root disk, and the worlds are on the volume. Nothing on the root disk was played: play the volume's. | |
| 29 | - **Which side was played last?** `mkdir -p /mnt/look && mount -o ro /dev/disk/by-id/scsi-0DO_Volume_* /mnt/look` (`scsi-0HC_Volume_*` on Hetzner), then `find /mnt/look <data directory> -name level.dat -printf '%TY-%Tm-%Td %TH:%TM %p\n' | sort`. The newest is last. Then `umount /mnt/look`. A side with no `level.dat` has no world. | |
| 30 | - **Nothing is deleted either way.** Take a snapshot of the volume first, at the cloud. | |
| 31 | - **Play the volume's worlds:** `systemctl stop forge-game-agent docker.socket docker`, then `mv <data directory> <data directory>.aside`, then `( set -a; . /opt/forge-game/agent.env; bash /opt/forge-game/agent.sh --mount-volume )`, which must say `mounted`, then `systemctl start docker forge-game-agent`. Starting Docker before the volume is mounted puts new folders there, and the box is held again. | |
| 32 | - **Play this disk's worlds:** mount the volume as above without `-o ro`, `mkdir /mnt/look/forge-aside`, move everything else there except `lost+found` into it, `umount /mnt/look`, and `systemctl restart forge-game-agent`. The agent copies this disk's data beside `forge-aside`, which it does not count as data. The volume needs room for both. | |
| 33 | - **`no-volume`:** attach the volume; the agent sees it and looks again by itself. Docker has usually made its folders by then, so it ends as `other-worlds`: go on as above. **`signature`, `mount`:** look at the device on the machine, then `systemctl restart forge-game-agent`. | |
| 27 | 34 | - **Reading it:** every step is a line of `/opt/forge-game/.volume.log` (the last 40 kept), each step of a move also posted to the forge as the box's word. Each sync's diag carries the volume's device and the log's last 12 lines (`disk.device`, `disk.log`). The owner reads them under "The volume (.volume.log)" in `/games/<box>`'s run log and on the terminal's box screen, and a last line starting `failed:` or `refused:` comes first in the Box section and the Games screen's top line as "The volume: …". |
| 28 | 35 | - **Updating itself:** every sync answers `agentSha`, the sha256 of the agent this forge ships. An agent whose own sha differs fetches `GET /api/v1/games/agent/script` with its token, checks that the fetched script's sha is the one answered and that `bash -n` parses it, puts it in place (`agent.sh.next`, then a rename) and exits, and systemd starts the new one. A script whose sha is not the one answered is deleted and never runs; an agent already current fetches nothing. An agent older than this step does not update itself; it takes the new one with its machine's next replace. |
| 29 | 36 | - **`/forge` on the proxy:** the proxy's plugin leaves each request as `plugins/forge/outbox/<id>.json` (at most 2 KiB) and shows a player what it finds in `plugins/forge/inbox`. The agent reads and writes both inside the running `velocity` container, as `bungeecord`; with no running `velocity` service it does nothing there. A full sync's body carries the oldest 20 as `ask`, and only the files whose ids the answer's `asked` names are deleted: with no `asked` (an older forge) none is, and the plugin stops at 64 waiting. A file over 2 KiB, one that is no JSON object, or one whose `id` is not its file's name in lowercase is dropped, with one line in the agent's log that never holds its text. The answer's `told` (at most 20, 16 KiB each) goes to the inbox, each file put in place whole, none while 64 wait. A quick poll that says `"told": true` may be answered with `told` too; `ask` goes with full syncs only. Each answer has a number `n`: every body's `got` names those that are in the inbox, until a sync that named them is answered, and the forge hands an answer out again until then. The agent keeps the numbers for two hours (`/opt/forge-game/.told.json`), so a player does not see an answer twice. |
docs/features/games.md +2
| @@ -171,3 +171,5 @@ A game's own refusal is a failure: `op` with a name that does not exist ("That p | ||
| 171 | 171 | ## On a phone (#17656) |
| 172 | 172 | |
| 173 | 173 | `/games/<box>` opens on **How to join** (the box's machine name with Copy, and who is on, server by server), then one row a server: its name, its state in words, players, TPS, then memory, CPU and how long it has been up in the cloud tree's words (`containersIn` in `src/cloud/containers.ts`: "not known" for what the box did not say or once it is silent, nothing for a server that is not running) and the 24 h sparklines, and a quiet button (Start while it is not running, else Restart); Stop, Restart and Remove are behind **More**. A server's page leads with its state, the same memory, CPU and uptime line under it, which says so when the server is not running (the terminal's people part too), its main button (the page's one accent), who is on and **Why someone could not join** (each cause with who, how often and "Tell them": what to say). Console, Numbers, Sleep, World, Environment, Settings and Mods follow, each folded and one tap away; nothing was removed (the numbers stayed in the row). A start, stop or restart that was asked shows on the server ("Starting: asked 10 s ago", then "Started" or why not) until the server answers, and the page updates itself. The player form has no default: choose what to do, in the plain word with the game's own beside it in the choice only (Let in (whitelist), Make operator (op), Ban, Lift a ban (pardon)); headings and notes use the plain word. The terminal says the same: the state line, the address, the "Tell them" fixes and the plain words (`src/games/gist.ts`). No address shows when the box has no machine name. |
| 174 | ||
| 175 | **Held** (`src/games/hold.ts`): a box whose agent starts nothing until a person has looked at its volume (docs/features/game-box.md) says so first, on `/games/<box>`, on each of its servers' pages, at the top of the terminal's Games and box screens, on its machine in the cloud tree and as `held` in the `games` tool. Its owner reads why, when the agent last looked and the next step; anyone else only that its owner has to look. The agent sends a code (`diag.hold`), never a sentence, and one the forge does not know is said as held without a reason. Held is not stopped: containers that already run are left alone. An older agent sends nothing, and nothing is said. |
docs/features/infra.md +1 −1
| @@ -107,7 +107,7 @@ Every DigitalOcean and Hetzner account is read into provider ▸ account ▸ pro | ||
| 107 | 107 | - **Changed with the shared language:** `!web` and `!machine:i-111` negate and a leading `"` quotes (both were part of the word); `sort:`, `group:` and `created:` were text; `cost:=10`, `cost:>10,=20` and `cost:>10,<5` were refused; a sign left out and a long line's rest are now said; over MCP `cost:abc` and `cost:none` listed everything and are refused. `test/cloud-filter-lines.test.ts` holds each, and every line that kept its rows. |
| 108 | 108 | - **A resource** is at `/infra/-/<cloud>/<account>/<project>/<id>`, beside the tree, or full width on a phone: cost, state, what it is attached to and what it holds (an address its balancer, NAT gateway or task; an ECS service its balancer and cluster; a balancer the services known behind it, "Shared by" when there are several; a link AWS does not state is not drawn, which does not mean nothing uses it), an AWS list price's day, what it leaves out and whose file it is (or why there is none), the app an AWS resource is part of and how that is known (nothing when it is not), what it was made from, who made it, when it was created, when it was read, and Ask about this (a talk with those facts, fenced as data). |
| 109 | 109 | - **Created.** An EC2 instance's is when its primary network interface was attached, which is its first launch: AWS's `launchTime` is its last start and is not shown. "not known" when the cloud does not state a date, or the forge does not read one (an AWS address, function, table, cluster or zone). An S3 bucket's is "Created, or last changed", because AWS moves it when the bucket changes, its policy for one; a filter by `created:` uses that date all the same. |
| 110 | - **Containers.** A machine that is a game box opens into its containers (`src/cloud/containers.ts`), at `/infra/-/<cloud>/<account>/<project>/machine:<id>/container:<name>`: state, health, CPU, memory, how long it has been up, its image (the box owner's only) and a link to its page under /games, where it is changed. It is what the box's last full sync wrote, and nothing is asked of the box. The sync carries `upSince`, `memLimitMiB` and `cpuLimit` for each service, from one `docker inspect` that asks for those fields by name and never the whole answer, which holds the env (`services` in `src/games/agent.sh`): a limit of 0 is "no limit set", and one left out (an older agent) is "not known", as is a value out of its range. Without `upSince` the uptime is the diagnosis' word. "not known" is also said of figures the box could not measure, and of everything once the box is silent for two minutes ("not known: running 3 hours ago"). A container is in no count and no sum. The machine is the one the box's own row names, never found by name. Who sees which follows the games roles, and nobody sees the waker. | |
| 110 | - **Containers.** A machine that is a game box opens into its containers (`src/cloud/containers.ts`), at `/infra/-/<cloud>/<account>/<project>/machine:<id>/container:<name>`: state, health, CPU, memory, how long it has been up, its image (the box owner's only) and a link to its page under /games, where it is changed. It is what the box's last full sync wrote, and nothing is asked of the box. The sync carries `upSince`, `memLimitMiB` and `cpuLimit` for each service, from one `docker inspect` that asks for those fields by name and never the whole answer, which holds the env (`services` in `src/games/agent.sh`): a limit of 0 is "no limit set", and one left out (an older agent) is "not known", as is a value out of its range. Without `upSince` the uptime is the diagnosis' word. "not known" is also said of figures the box could not measure, and of everything once the box is silent for two minutes ("not known: running 3 hours ago"). A container is in no count and no sum. The machine is the one the box's own row names, never found by name. Who sees which follows the games roles, and nobody sees the waker. A held box (docs/features/games.md) says so on its machine: in its row, and first in its facts with the next step. | |
| 111 | 111 | - **Keys.** j and k move, Enter opens, h and l (or the arrows) close and open, `/` filters and Enter goes to the first match. |
| 112 | 112 | - **States.** No account (a link to /settings/cloud), not read yet, a failed read (one line: when, why, and how old what is shown is), a kind that could not be read with its reason (on its project and on the account, which says where; under the headline's sum, "Not everything is listed: 1 kind not read" links to that account, and text doors name it; a billed account's gaps count too, and change no sum), and a reading older than three of its duty's intervals. A project's note ("R2 is not switched on for this account") is a plain line and no trouble, on its account too when that has one project. **Check the account** (`a` in the terminal) opens the account: see [](cloud.md#what-was-not-read-17637). |
| 113 | 113 | - **Terminal.** `:` then Cloud resources, or `/` in Infra (`src/tui/screens/cloudtree.ts`): the same list, filter and facts, the List price, Old price, Price from and No price lines among them (both read `factsOf`); `tab` changes pane, `w` opens the web page, `P` reads every account. |
src/cloud/containers.ts +14 −5
| @@ -11,6 +11,7 @@ import type { Database } from "bun:sqlite"; | ||
| 11 | 11 | import { listPinned } from "../core/pinned.ts"; |
| 12 | 12 | import type { User } from "../core/users.ts"; |
| 13 | 13 | import { nowWords } from "../games/gist.ts"; |
| 14 | import { heldOn, type Held } from "../games/hold.ts"; | |
| 14 | 15 | import { listBoxes, mayDo, roleOn, seesBox, servicesOf, type GameBox, type GameService } from "../games/store.ts"; |
| 15 | 16 | import { agoWords } from "../kernel/ago.ts"; |
| 16 | 17 | |
| @@ -95,17 +96,25 @@ export function figuresOf(db: Database, viewer: User | undefined, box: GameBox, | ||
| 95 | 96 | return c === undefined ? "memory, CPU and uptime not known" : c.brief || "not running: no memory or CPU to show"; |
| 96 | 97 | } |
| 97 | 98 | |
| 98 | /** Every container `viewer` may see, by its machine as the cloud tree names it: `<cloud>/<account>/machine:<id>`. */ | |
| 99 | export function containersOf(db: Database, viewer: User | undefined, now = Date.now()): Map<string, readonly Container[]> { | |
| 100 | const out = new Map<string, readonly Container[]>(); | |
| 99 | /** What a game box puts on its machine: its containers, and why it starts none when it is held. */ | |
| 100 | export interface Inside { | |
| 101 | readonly page: string; | |
| 102 | readonly containers: readonly Container[]; | |
| 103 | readonly held?: Held; | |
| 104 | } | |
| 105 | ||
| 106 | /** What `viewer` may see inside each machine, by the machine as the cloud tree names it: `<cloud>/<account>/machine:<id>`. */ | |
| 107 | export function containersOf(db: Database, viewer: User | undefined, now = Date.now()): Map<string, Inside> { | |
| 108 | const out = new Map<string, Inside>(); | |
| 101 | 109 | const boxes = listBoxes(db).filter((b) => b.pinnedId !== "" && seesBox(db, viewer, b.id)); |
| 102 | 110 | if (boxes.length === 0) return out; |
| 103 | 111 | const machines = new Map(listPinned(db).filter((p) => p.state !== "retired" && p.remote !== "").map((p) => [p.id, p])); |
| 104 | 112 | for (const box of boxes) { |
| 105 | 113 | const m = machines.get(box.pinnedId); |
| 106 | 114 | if (m === undefined) continue; |
| 107 | const own = containersIn(db, viewer, box, now); | |
| 108 | if (own.length > 0) out.set(`${m.target}/${m.account}/machine:${m.remote}`, own); | |
| 115 | const containers = containersIn(db, viewer, box, now); | |
| 116 | const held = heldOn(db, viewer, box, now); | |
| 117 | if (containers.length > 0 || held !== undefined) out.set(`${m.target}/${m.account}/machine:${m.remote}`, { page: `/games/${box.name}`, containers, ...(held === undefined ? {} : { held }) }); | |
| 109 | 118 | } |
| 110 | 119 | return out; |
| 111 | 120 | } |
src/cloud/tree.ts +9 −4
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | * branch costs what its matches do at list price. |
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | import type { Container } from "./containers.ts"; | |
| 13 | import type { Container, Inside } from "./containers.ts"; | |
| 14 | 14 | import { dollars } from "./prices.ts"; |
| 15 | 15 | import { PROJECT_CLOUDS, readEveryMs, type AccountRead, type CloudResource, type ProjectView } from "./projects.ts"; |
| 16 | 16 | import { agoWords } from "../kernel/ago.ts"; |
| @@ -161,6 +161,8 @@ export interface CloudNode { | ||
| 161 | 161 | readonly resource?: CloudResource; |
| 162 | 162 | /** A container of the machine above it: no resource of the cloud's, so it counts and costs nothing. */ |
| 163 | 163 | readonly container?: Container; |
| 164 | /** A machine whose game box starts nothing: what it says, and the box's page. */ | |
| 165 | readonly held?: { readonly says: string; readonly next: string; readonly page: string }; | |
| 164 | 166 | /** When an account or a project was last read; "" when it has not been. */ |
| 165 | 167 | readonly readAt: string; |
| 166 | 168 | /** What a person must know of it before its numbers are believed. */ |
| @@ -292,7 +294,7 @@ const kindsOf = (unread: AccountRead["unread"]): number => new Set(listGaps(unre | ||
| 292 | 294 | * The tree of what matches `q`. With no filter every account the forge holds is there, so one that |
| 293 | 295 | * was never read shows as that and not as nothing; with one, only branches that hold a match. |
| 294 | 296 | */ |
| 295 | export function cloudTree(projects: readonly ProjectView[], reads: readonly AccountRead[], held: readonly HeldAccount[], q: CloudQuery, now: number, containers: ReadonlyMap<string, readonly Container[]> = new Map()): CloudNode { | |
| 297 | export function cloudTree(projects: readonly ProjectView[], reads: readonly AccountRead[], held: readonly HeldAccount[], q: CloudQuery, now: number, machines: ReadonlyMap<string, Inside> = new Map()): CloudNode { | |
| 296 | 298 | const filtering = q.line.terms.length > 0; |
| 297 | 299 | const own = groupBy(projects, (p) => `${p.provider}/${p.account}`); |
| 298 | 300 | const all = new Map<string, readonly [string, string]>([...projects.map((p) => [p.provider, p.account] as const), ...held.map((h) => [h.provider, h.name] as const)].map((a) => [a.join("/"), a])); |
| @@ -308,8 +310,9 @@ export function cloudTree(projects: readonly ProjectView[], reads: readonly Acco | ||
| 308 | 310 | .map((r): CloudNode => { |
| 309 | 311 | const tasks = tasksOf(r, p.resources); |
| 310 | 312 | const at = [...path, r.id]; |
| 311 | const children = (containers.get(`${provider}/${account}/${r.id}`) ?? []).map((c): CloudNode => ({ level: "container", path: [...at, `container:${c.name}`], name: c.name, money: NOTHING, count: 0, gaps: 0, note: "", children: [], container: c, readAt: c.readAt, trouble: [], alert: false, empty: 0 })); | |
| 312 | return { level: "resource", path: at, name: r.name || idOf(r), money: tasks === undefined ? moneyOf(r) : NOTHING, ...(tasks === undefined ? {} : { tasks }), count: 1, gaps: 0, note: "", children, resource: r, readAt: r.readAt, trouble: [], alert: false, empty: 0 }; | |
| 313 | const box = machines.get(`${provider}/${account}/${r.id}`); | |
| 314 | const children = (box?.containers ?? []).map((c): CloudNode => ({ level: "container", path: [...at, `container:${c.name}`], name: c.name, money: NOTHING, count: 0, gaps: 0, note: "", children: [], container: c, readAt: c.readAt, trouble: [], alert: false, empty: 0 })); | |
| 315 | return { level: "resource", path: at, name: r.name || idOf(r), money: tasks === undefined ? moneyOf(r) : NOTHING, ...(tasks === undefined ? {} : { tasks }), count: 1, gaps: 0, note: "", children, resource: r, readAt: r.readAt, trouble: [], alert: box?.held !== undefined, ...(box?.held === undefined ? {} : { held: { ...box.held, page: box.page } }), empty: 0 }; | |
| 313 | 316 | }); |
| 314 | 317 | const n = { ...branch("project", path, p.name, things, p.readAt, unreadTrouble(p.unread, href)), note: p.note }; |
| 315 | 318 | // A bill is the whole project's, so it stands in for its resources' prices, known or not. |
| @@ -571,10 +574,12 @@ export function linkedFacts(root: CloudNode, n: CloudNode): Fact[] { | ||
| 571 | 574 | if (n.container !== undefined) return containerFacts(n.container); |
| 572 | 575 | const r = n.resource; |
| 573 | 576 | if (r === undefined) return []; |
| 577 | const held: Fact[] = n.held === undefined ? [] : [{ label: "Held", value: n.held.says, href: n.held.page }, { label: "Next step", value: n.held.next }]; | |
| 574 | 578 | const project = nodeAt(root, n.path.slice(0, 3))?.name ?? r.project; |
| 575 | 579 | const ties = tiesOf(root, n).map((tie): Fact => ({ label: tie.label, value: tie.to.length === 0 ? tie.none : tie.to.map((e) => e.node?.name ?? e.id).join(", "), tie })); |
| 576 | 580 | const origin = (f: Fact): boolean => f.label === "Made from"; |
| 577 | 581 | return [ |
| 582 | ...held, | |
| 578 | 583 | { label: "Kind", value: r.kind }, |
| 579 | 584 | { label: "State", value: r.state }, |
| 580 | 585 | { label: "Size", value: r.size }, |
src/games/agent.sh +66 −16
| @@ -108,10 +108,12 @@ say_boot() { | ||
| 108 | 108 | # destroys). The cloud attaches the volume; the box itself formats it (only when blank, never over |
| 109 | 109 | # data), mounts it at the data directory and keeps it in fstab with nofail, before Docker starts. |
| 110 | 110 | # A box that started with its data on the root disk moves it there once, step by step, each step |
| 111 | # in .volume.log (and so in diag); any failure leaves the root disk's data as it was. No jq here: | |
| 112 | # the boot runs this before jq is installed. ---- | |
| 111 | # in .volume.log (and so in diag); any failure leaves the root disk's data as it was. When the volume | |
| 112 | # may hold other worlds than this disk, nothing is started (VOLUME_HOLD) until a person decides. No jq | |
| 113 | # here: the boot runs this before jq is installed. ---- | |
| 113 | 114 | |
| 114 | 115 | VOLUME_LOG="/.volume.log" |
| 116 | VOLUME_HOLD="/.volume.hold" | |
| 115 | 117 | vol_say() { |
| 116 | 118 | mkdir -p "" |
| 117 | 119 | printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >>"" |
| @@ -171,29 +173,50 @@ docker_needs_volume() { | ||
| 171 | 173 | mkdir -p "" && printf '[Unit]\nRequiresMountsFor=%s\n' "" >"/forge-volume.conf" && systemctl daemon-reload >/dev/null 2>&1 || |
| 172 | 174 | vol_say "failed: Docker could not be made to wait for the volume at " |
| 173 | 175 | } |
| 176 | # Start nothing: the volume may hold other worlds than this disk. The box still syncs, and its page says why. | |
| 177 | # The file says why, as a code the forge reads, and since when. | |
| 178 | HELD_READ="docs/features/game-box.md (Held) says how to choose, and both are kept until then" | |
| 179 | vol_hold() { | |
| 180 | printf '%s %s\n' "$1" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >"" | |
| 181 | vol_step "refused: $2: nothing is started; " | |
| 182 | } | |
| 174 | 183 | # Mount the volume at the data directory. At a fresh boot the directory is empty; one that holds |
| 175 | 184 | # data is moved (`volume_move`), never mounted over silently. |
| 176 | 185 | volume_mount() { |
| 177 | local dir dev="" i | |
| 186 | local dir dev="" i blank=0 | |
| 178 | 187 | dir="$(data_dir)" |
| 179 | 188 | [ -n "" ] || { vol_say "no data directory known; nothing mounted"; return 1; } |
| 189 | rm -f "" | |
| 180 | 190 | for ((i = 0; i < ; i++)); do |
| 181 | 191 | dev="$(volume_device)" |
| 182 | 192 | [ -n "" ] && break |
| 183 | 193 | sleep 1 |
| 184 | 194 | done |
| 185 | [ -n "" ] || { vol_say "no volume device attached; the data stays on the root disk"; return 1; } | |
| 195 | if [ -z "" ]; then | |
| 196 | # The boot always has a volume: without it, a box that never ran anything would start new worlds. | |
| 197 | if [ -z "" ] || [ -f "/.compose-sha" ]; then vol_say "no volume device attached; the data stays on the root disk"; return 1; fi | |
| 198 | vol_hold no-volume "no volume device is attached" | |
| 199 | return 1 | |
| 200 | fi | |
| 186 | 201 | if volume_here "" ""; then |
| 187 | 202 | vol_say "the volume is mounted at " |
| 188 | 203 | return 0 |
| 189 | 204 | fi |
| 190 | volume_fs "" || return 1 | |
| 205 | [ -n "$(blkid -o value -s TYPE "" 2>/dev/null)" ] || blank=1 | |
| 206 | if ! volume_fs ""; then | |
| 207 | [ -z "$(wipefs -n "" 2>/dev/null | tail -n +2)" ] || vol_hold signature " has a signature but no filesystem this box knows" | |
| 208 | return 1 | |
| 209 | fi | |
| 191 | 210 | if [ -d "" ] && [ -n "$(ls -A "" 2>/dev/null)" ]; then |
| 192 | volume_move "" "" | |
| 211 | volume_move "" "" "" | |
| 193 | 212 | return |
| 194 | 213 | fi |
| 195 | 214 | mkdir -p "" |
| 196 | mount "" "" || { vol_say "failed: mount "; return 1; } | |
| 215 | if ! mount "" ""; then | |
| 216 | vol_say "failed: mount " | |
| 217 | [ "" = 1 ] || vol_hold mount "the volume could not be mounted" | |
| 218 | return 1 | |
| 219 | fi | |
| 197 | 220 | volume_fstab "" "" |
| 198 | 221 | docker_needs_volume "" |
| 199 | 222 | vol_say "mounted at " |
| @@ -207,15 +230,26 @@ vol_step() { | ||
| 207 | 230 | # Move what the root disk holds at `dir` onto the volume, once. Compose and Docker are stopped so |
| 208 | 231 | # nothing writes meanwhile; the volume must be empty. The volume is mounted at `dir`, in fstab, |
| 209 | 232 | # and Docker made to wait for it, before Docker starts again. Any failure before that starts Docker |
| 210 | # again on the root disk's data, as it was, and says so with "failed:" (diag shows it). | |
| 233 | # again on the root disk's data, as it was, and says so with "failed:" (diag shows it). The copy | |
| 234 | # carries this machine's id until it is whole, so one that did not end is known as this disk's own. | |
| 211 | 235 | volume_move() { |
| 212 | local dev="$1" dir="$2" tmp="" rc | |
| 236 | local dev="$1" dir="$2" blank="$3" tmp="" rc me | |
| 237 | me="$(cat "" 2>/dev/null)" | |
| 213 | 238 | vol_step "moving to the volume " |
| 214 | 239 | mkdir -p "" |
| 215 | mount "" "" || { vol_step "failed: mount ; the data stays on the root disk"; return 1; } | |
| 216 | if [ -n "$(ls -A "" 2>/dev/null | grep -v '^lost+found$')" ]; then | |
| 240 | if ! mount "" ""; then | |
| 241 | vol_step "failed: mount ; the data stays on the root disk" | |
| 242 | [ "" = 1 ] || vol_hold mount "the volume could not be mounted" | |
| 243 | return 1 | |
| 244 | fi | |
| 245 | if [ -n "$(ls -A "" 2>/dev/null | grep -vE '^(lost\+found|forge-aside)$')" ]; then | |
| 246 | if [ -n "" ] && [ "$(cat "/.forge-copying" 2>/dev/null)" = "" ]; then | |
| 247 | umount "" | |
| 248 | vol_step "refused: the volume holds this box's own unfinished copy; the data stays on the root disk" | |
| 249 | return 1 | |
| 250 | fi | |
| 217 | 251 | umount "" |
| 218 | vol_step "refused: the volume already holds data; nothing was copied, the data stays on the root disk" | |
| 252 | vol_hold other-worlds "the volume holds worlds and this disk holds others" | |
| 219 | 253 | return 1 |
| 220 | 254 | fi |
| 221 | 255 | if ! command -v rsync >/dev/null 2>&1; then |
| @@ -238,6 +272,7 @@ volume_move() { | ||
| 238 | 272 | return 1 |
| 239 | 273 | fi |
| 240 | 274 | vol_step "copying to the volume" |
| 275 | printf '%s' "" >"/.forge-copying" | |
| 241 | 276 | rsync -aHAX --numeric-ids "/" "/" |
| 242 | 277 | rc= |
| 243 | 278 | if [ "" != 0 ]; then |
| @@ -256,6 +291,7 @@ volume_move() { | ||
| 256 | 291 | vol_step "failed: mount after the copy; Docker started again on the root disk's data, and the volume's copy is not used" |
| 257 | 292 | return 1 |
| 258 | 293 | fi |
| 294 | rm -f "/.forge-copying" | |
| 259 | 295 | volume_fstab "" "" |
| 260 | 296 | docker_needs_volume "" |
| 261 | 297 | # Compose comes up again at the next sync: its sha is no longer current. |
| @@ -268,7 +304,7 @@ volume_move() { | ||
| 268 | 304 | # The boot's own step, before Docker is installed: find, format if blank, mount, fstab. |
| 269 | 305 | if [ "" = "--mount-volume" ]; then |
| 270 | 306 | volume_mount |
| 271 | exit 0 | |
| 307 | exit | |
| 272 | 308 | fi |
| 273 | 309 | |
| 274 | 310 | # ---- self-update: the sync answers the sha256 of the forge's agent.sh; on a mismatch the agent |
| @@ -784,6 +820,12 @@ job_tick() { | ||
| 784 | 820 | line="$(head -n 1 "")" |
| 785 | 821 | tail -n +2 "" >".next" && mv ".next" "" |
| 786 | 822 | IFS='|' read -r id label sha args <<<"" |
| 823 | # Held: the volume may hold other worlds. An up is asked for again at each sync, so none is kept here. | |
| 824 | if [ -f "" ] && [ "" != stop ] && [ "" != pull ]; then | |
| 825 | [ -z "" ] || keep_result "" false "nothing is started: this box is held ($(cut -d' ' -f1 "")); " | |
| 826 | rm -f "/.compose-sha" | |
| 827 | return | |
| 828 | fi | |
| 787 | 829 | printf '%s' "" >"/.job.id" |
| 788 | 830 | printf '%s' "" >"/.job.sha" |
| 789 | 831 | printf '%s' "" >"/.job.label" |
| @@ -991,6 +1033,12 @@ diag() { | ||
| 991 | 1033 | }' 2>/dev/null || echo '{}' |
| 992 | 1034 | } |
| 993 | 1035 | |
| 1036 | # Whether the box is held, read outside the probes: a docker that hangs must not make it look free. | |
| 1037 | held() { | |
| 1038 | [ -f "" ] || { echo null; return; } | |
| 1039 | jq -Rsc '(split("\n")[0] // "" | split(" ")) as $w | {why: (if ($w[0] // "") | IN("no-volume", "signature", "mount", "other-worlds") then $w[0] else "unknown" end), since: ($w[1] // "")}' "" | |
| 1040 | } | |
| 1041 | ||
| 994 | 1042 | # The whole diag within one deadline (FORGE_GAME_DIAG_S, default 8 s): a probe that hangs (a docker |
| 995 | 1043 | # that does not answer) never holds the sync. Over it, an empty diag that says so. |
| 996 | 1044 | bounded_diag() { |
| @@ -1239,7 +1287,7 @@ sync() { | ||
| 1239 | 1287 | logs "" | json_or '{}' >"/.sync.logs" |
| 1240 | 1288 | json_or '[]' <"/.results" >"/.sync.results" |
| 1241 | 1289 | host | json_or '{}' >"/.sync.host" |
| 1242 | bounded_diag | json_or '{}' >"/.sync.diag" | |
| 1290 | bounded_diag | json_or '{}' | jq -c --argjson hold "$(held)" '. + {hold: $hold}' >"/.sync.diag" | |
| 1243 | 1291 | people | json_or '{}' >"/.sync.people" |
| 1244 | 1292 | metrics | json_or '{}' >"/.sync.metrics" |
| 1245 | 1293 | jq -c 'if type == "object" then . else {} end' "/snapshots.json" 2>/dev/null | json_or '{}' >"/.sync.snapshots" |
| @@ -1742,12 +1790,14 @@ wait_polling() { | ||
| 1742 | 1790 | |
| 1743 | 1791 | # Once at each start: a volume attached but not mounted at the data directory is mounted, or the |
| 1744 | 1792 | # data the root disk holds is moved onto it. |
| 1745 | if [ "" = 1 ] && [ -n "$(volume_device)" ] && [ -n "$(data_dir)" ] && ! volume_here "$(volume_device)" "$(data_dir)"; then | |
| 1746 | FORGE_GAME_VOLUME_WAIT=1 volume_mount || true | |
| 1793 | if [ "" = 1 ] && [ -n "$(volume_device)" ] && [ -n "$(data_dir)" ]; then | |
| 1794 | if volume_here "$(volume_device)" "$(data_dir)"; then rm -f ""; else FORGE_GAME_VOLUME_WAIT=1 volume_mount || true; fi | |
| 1747 | 1795 | fi |
| 1748 | 1796 | |
| 1749 | 1797 | while :; do |
| 1750 | 1798 | metadata_close |
| 1799 | # The volume a held box waited for is there: systemd starts the agent again, which looks at it. | |
| 1800 | ! grep -q '^no-volume ' "" 2>/dev/null || [ -z "$(volume_device)" ] || exit 0 | |
| 1751 | 1801 | job_tick |
| 1752 | 1802 | shell_tick |
| 1753 | 1803 | sync || echo "forge-game-agent: sync failed; again in s" >&2 |
src/games/diag.ts +20 −3
| @@ -20,13 +20,29 @@ export interface Diag { | ||
| 20 | 20 | readonly metadata?: "closed" | "open"; |
| 21 | 21 | readonly disk?: { readonly root?: string; readonly dataRoot?: string; readonly volume?: string; readonly mountOfDataRoot?: string; readonly volumeMounted?: boolean; readonly onVolume?: boolean; readonly device?: string; readonly log?: string }; |
| 22 | 22 | readonly versions?: { readonly docker?: string; readonly compose?: string }; |
| 23 | /** Why the agent starts nothing, as a code, and when it last looked; null when it is not held, and an older agent does not say. */ | |
| 24 | readonly hold?: Hold | null; | |
| 23 | 25 | } |
| 24 | 26 | |
| 25 | /** A diag as kept: its JSON, or a note when it is not an object or is over `DIAG_MOST`. */ | |
| 27 | const HOLDS = ["no-volume", "signature", "mount", "other-worlds"] as const; | |
| 28 | export interface Hold { | |
| 29 | readonly why: (typeof HOLDS)[number] | "unknown"; | |
| 30 | readonly since: string; | |
| 31 | } | |
| 32 | ||
| 33 | /** The hold a box's diag says, whatever it sent: a code the forge does not know is "unknown", never no hold. */ | |
| 34 | export function holdOf(d: { readonly hold?: unknown }): Hold | undefined { | |
| 35 | if (d.hold === undefined || d.hold === null) return undefined; | |
| 36 | const { why, since } = d.hold as { why?: unknown; since?: unknown }; | |
| 37 | return { why: HOLDS.find((w) => w === why) ?? "unknown", since: typeof since === "string" && /^\d{4}-\d\d-\d\dT[\d:.]{8,16}Z$/.test(since) && Number.isFinite(Date.parse(since)) ? since : "" }; | |
| 38 | } | |
| 39 | ||
| 40 | /** A diag as kept: its JSON, or a note, and the hold it named, when it is over `DIAG_MOST`; "{}" when it is no object. */ | |
| 26 | 41 | export function keptDiag(raw: unknown): string { |
| 27 | 42 | if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return "{}"; |
| 28 | 43 | const text = JSON.stringify(raw); |
| 29 | return text.length <= DIAG_MOST ? text : JSON.stringify({ note: `the box sent ${text.length} bytes of diagnosis; at most ${DIAG_MOST} are kept` }); | |
| 44 | const hold = holdOf(raw); | |
| 45 | return text.length <= DIAG_MOST ? text : JSON.stringify({ note: `the box sent ${text.length} bytes of diagnosis; at most ${DIAG_MOST} are kept`, ...(hold === undefined ? {} : { hold }) }); | |
| 30 | 46 | } |
| 31 | 47 | |
| 32 | 48 | export function readDiag(text: string): Diag { |
| @@ -107,7 +123,8 @@ export function boxStatus(d: Diag): string[] { | ||
| 107 | 123 | if (disk !== undefined && (disk.volume ?? "") !== "") { |
| 108 | 124 | // What the agent last did with the volume (format, mount, move), when it failed or refused. |
| 109 | 125 | const last = (disk.log ?? "").trim().split("\n").at(-1)?.replace(/^\S+ /, "") ?? ""; |
| 110 | if (/^(failed|refused):/.test(last)) out.push(`The volume: ${last}`); | |
| 126 | // A held box says this in its own words (`hold.ts`). | |
| 127 | if (/^(failed|refused):/.test(last) && holdOf(d) === undefined) out.push(`The volume: ${last}`); | |
| 111 | 128 | if (disk.volumeMounted === false) out.push(`The volume is not mounted at ${disk.volume}${disk.device ? "" : ": no volume device is attached"}`); |
| 112 | 129 | else if (disk.onVolume === false) out.push("Docker's data is on the root disk, not the volume"); |
| 113 | 130 | } |
src/games/hold.ts added +49
| @@ -0,0 +1,49 @@ | ||
| 1 | /** | |
| 2 | * A held box (#17532, #17610): its volume may hold other worlds than its own disk, so its agent | |
| 3 | * starts nothing until a person has looked. The agent says which case it is as a code (`diag.hold`, | |
| 4 | * docs/features/game-box.md, Held); the words and the next step are here, once, for /games, the | |
| 5 | * terminal, the cloud tree and the tools. Held is not stopped: what already runs is left alone. No | |
| 6 | * step deletes anything. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { Database } from "bun:sqlite"; | |
| 10 | import type { User } from "../core/users.ts"; | |
| 11 | import { agoWords } from "../kernel/ago.ts"; | |
| 12 | import { holdOf } from "./diag.ts"; | |
| 13 | import { mayDo, roleOn, type GameBox } from "./store.ts"; | |
| 14 | ||
| 15 | /** Said after "Held: ". */ | |
| 16 | export interface Held { | |
| 17 | readonly says: string; | |
| 18 | /** What to do, for the box's owner alone; "" for anyone else. */ | |
| 19 | readonly next: string; | |
| 20 | } | |
| 21 | ||
| 22 | const CASES: Record<string, readonly [why: string, next: string]> = { | |
| 23 | "no-volume": ["no volume is attached to its machine", "Attach the volume: the agent sees it and looks again by itself. If it then says that both sides hold data, choose which to play."], | |
| 24 | signature: ["its volume has a signature but no filesystem the agent knows", "Look at the device on the machine, then restart the agent there."], | |
| 25 | mount: ["its volume could not be mounted", "Look at the device on the machine, then restart the agent there."], | |
| 26 | "other-worlds": ["its volume holds data, and so does its own disk", "Take a snapshot of the volume at the cloud, see which side was played last, and move the other side aside. Nothing is deleted."], | |
| 27 | unknown: ["its agent did not say why", "Read /opt/forge-game/.volume.hold on the machine."], | |
| 28 | }; | |
| 29 | ||
| 30 | /** The steps in full, for a door with no link. */ | |
| 31 | export const HELD_STEPS = "The steps are in docs/features/game-box.md, under Held."; | |
| 32 | export const HELD_DOC = "features/game-box.md"; | |
| 33 | ||
| 34 | /** A box syncs every few seconds; past this it may have been let go since. */ | |
| 35 | const SILENT_MS = 2 * 60_000; | |
| 36 | ||
| 37 | /** What a held box says to `viewer`; undefined when it is not held, or its agent is too old to say. */ | |
| 38 | export function heldOn(db: Database, viewer: User | undefined, box: GameBox, now = Date.now()): Held | undefined { | |
| 39 | const hold = holdOf(box.diag); | |
| 40 | if (hold === undefined) return undefined; | |
| 41 | const heard = now - Date.parse(box.seenAt) > SILENT_MS ? ` The box was last heard from ${agoWords(box.seenAt, now)}, so whether it is still held is not known.` : ""; | |
| 42 | if (!mayDo(roleOn(db, viewer, box.id), "owner")) return { says: `nothing is started until its owner has looked.${heard}`, next: "" }; | |
| 43 | const [why, next] = CASES[hold.why]!; | |
| 44 | const looked = hold.since === "" ? "" : ` The agent last looked ${agoWords(hold.since, now)}.`; | |
| 45 | return { says: `${why}. Nothing is started; containers that already run are left alone.${looked}${heard}`, next }; | |
| 46 | } | |
| 47 | ||
| 48 | /** The same as lines, for a door with no link. */ | |
| 49 | export const heldLines = (h: Held | undefined): string[] => (h === undefined ? [] : h.next === "" ? [`Held: ${h.says}`] : [`Held: ${h.says}`, `Next: ${h.next} ${HELD_STEPS}`]); |
src/http/mcp/tools/games.ts +5 −1
Diff not shown — a line 2,480 characters wide (limit 2,000). +5 −1
View filesrc/tui/screens/games.ts +14 −8
| @@ -29,6 +29,7 @@ import { queueWorld, worldWords, type WorldOp } from "../../games/worlds.ts"; | ||
| 29 | 29 | import { lendWords, lentRunnerOf, setLend } from "../../games/lend.ts"; |
| 30 | 30 | import { spareRow } from "../../games/spare_row.ts"; |
| 31 | 31 | import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts"; |
| 32 | import { heldLines, heldOn } from "../../games/hold.ts"; | |
| 32 | 33 | import { cloudLine, pinnedOfBox } from "../../actions/cloud_says.ts"; |
| 33 | 34 | import { getUserByName } from "../../core/users.ts"; |
| 34 | 35 | import { commitServiceEnv, readCompose, serviceEnv } from "../../games/compose.ts"; |
| @@ -59,7 +60,7 @@ import { metricsSeries } from "../../games/metrics.ts"; | ||
| 59 | 60 | import type { Ctx, Screen } from "../app/app.ts"; |
| 60 | 61 | import { binding } from "../app/keys.ts"; |
| 61 | 62 | import { style } from "../term/style.ts"; |
| 62 | import { truncate } from "../term/width.ts"; | |
| 63 | import { truncate, wrap } from "../term/width.ts"; | |
| 63 | 64 | import type { Session } from "../session.ts"; |
| 64 | 65 | import { fill, len, split } from "../ui/layout.ts"; |
| 65 | 66 | import { ListState, confirmScreen, drawList, promptScreen, type ListRow } from "./common.ts"; |
| @@ -153,7 +154,6 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 153 | 154 | ], |
| 154 | 155 | render(area, s) { |
| 155 | 156 | const c = ctx.theme.c; |
| 156 | const [head, list] = split(area, "v", [len(1), fill(1)]); | |
| 157 | 157 | const all = rows(); |
| 158 | 158 | // A box that is up but not running its games says why, as /games does, before anything else. |
| 159 | 159 | const booting = listBoxes(f.app.db).find((b) => b.boot !== "" && seesBox(f.app.db, f.user, b.id)); |
| @@ -161,6 +161,9 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 161 | 161 | // The owner reads the box's own words; anyone else what it is doing, naming nothing inside it. |
| 162 | 162 | const lines = (b: GameBox) => (mayDo(roleOn(f.app.db, f.user, b.id), "owner") ? boxStatus(b.diag) : boxStatusShared(b.diag)); |
| 163 | 163 | const told = listBoxes(f.app.db).find((b) => seesBox(f.app.db, f.user, b.id) && lines(b).length > 0); |
| 164 | // A held box comes before both: it starts nothing until a person has looked. | |
| 165 | const held = note !== "" ? [] : listBoxes(f.app.db).filter((b) => seesBox(f.app.db, f.user, b.id)).flatMap((b) => heldLines(heldOn(f.app.db, f.user, b)).flatMap((l) => wrap(`${b.name}: ${l}`, area.w))).slice(0, 8); | |
| 166 | const [head, list] = split(area, "v", [len(Math.max(1, held.length)), fill(1)]); | |
| 164 | 167 | const said = |
| 165 | 168 | note !== "" |
| 166 | 169 | ? note |
| @@ -173,7 +176,8 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 173 | 176 | : all.length === 0 |
| 174 | 177 | ? emptyText("gameServices") |
| 175 | 178 | : joinLine(); |
| 176 | s.text(head!.x, head!.y, truncate(said, head!.w), style(booting !== undefined && note === "" && bootTroubled(booting) ? c.danger : c.mutedFg, c.bg), head!.x + head!.w); | |
| 179 | held.forEach((l, i) => s.text(head!.x, head!.y + i, truncate(l, head!.w), style(c.danger, c.bg), head!.x + head!.w)); | |
| 180 | if (held.length === 0) s.text(head!.x, head!.y, truncate(said, head!.w), style(booting !== undefined && note === "" && bootTroubled(booting) ? c.danger : c.mutedFg, c.bg), head!.x + head!.w); | |
| 177 | 181 | const brief = new Map([...new Map(all.map(({ box }) => [box.id, box])).values()].flatMap((b) => containersIn(f.app.db, f.user, b).map((c) => [`${b.id}/${c.name}`, c.brief] as const))); |
| 178 | 182 | const view: ListRow[] = all.map(({ box, service }) => ({ |
| 179 | 183 | title: `${box.name}/${service.name}`, |
| @@ -315,6 +319,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 315 | 319 | const { online, lists } = peopleOf(f.app.db, box.id, service); |
| 316 | 320 | const tag = (n: string) => `${n}${isBedrock(n) ? " (Bedrock)" : ""}${lists.ops.some((o) => o.name === n) ? " · op" : ""}`; |
| 317 | 321 | return [ |
| 322 | ...heldLines(heldOn(f.app.db, f.user, boxNamed(f.app.db, box.name) ?? box)), | |
| 318 | 323 | nowWords(servicesOf(f.app.db, box.id).find((x) => x.name === service), powerNow(f.app.db, box.id, service)), |
| 319 | 324 | figuresOf(f.app.db, f.user, boxNamed(f.app.db, box.name) ?? box, service), |
| 320 | 325 | ...findingsOf(f.app.db, box.id, service).flatMap((x) => [x.says, ...x.fix.map((l) => `Fix: ${l}`)]), |
| @@ -568,26 +573,27 @@ export function gameSettingsScreen(f: Session, ctx: Ctx, box: GameBox, service: | ||
| 568 | 573 | */ |
| 569 | 574 | export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen { |
| 570 | 575 | let top = 0; |
| 571 | const lines = (): string[] => { | |
| 576 | const lines = (w: number): string[] => { | |
| 572 | 577 | const b = listBoxes(f.app.db).find((x) => x.id === box.id) ?? box; |
| 578 | const held = heldLines(heldOn(f.app.db, f.user, b)).flatMap((l) => [...wrap(l, w), ""]); | |
| 573 | 579 | // The page's Spare rows, in the same words, first (kept a minute, so a redraw is free). |
| 574 | 580 | const lend = mayDo(roleOn(f.app.db, f.user, b.id), "owner") ? [lendWords(lentRunnerOf(f.app.db, b.id) !== undefined), ""] : []; |
| 575 | 581 | const spare = [spareRow(f.app.db, f.app.config.dataDir, b).map(([k, v]) => `${k}: ${v}.`).join(" "), ""]; |
| 576 | 582 | if (!mayDo(roleOn(f.app.db, f.user, b.id), "owner")) { |
| 577 | 583 | const shared = boxStatusShared(b.diag); |
| 578 | return [...spare, ...(shared.length === 0 ? ["The box has said nothing yet."] : shared)]; | |
| 584 | return [...held, ...spare, ...(shared.length === 0 ? ["The box has said nothing yet."] : shared)]; | |
| 579 | 585 | } |
| 580 | 586 | const plain = boxStatus(b.diag); |
| 581 | 587 | const tails = boxTails(b.diag); |
| 582 | if (plain.length + tails.length === 0) return [...lend, ...spare, "The box has sent no diagnosis yet: its agent sends one with every check-in."]; | |
| 583 | return [...lend, ...spare, ...plain, ...tails.flatMap(([k, v]) => ["", `== ${k}`, ...v.split("\n")])]; | |
| 588 | if (plain.length + tails.length === 0) return [...held, ...lend, ...spare, "The box has sent no diagnosis yet: its agent sends one with every check-in."]; | |
| 589 | return [...held, ...lend, ...spare, ...plain, ...tails.flatMap(([k, v]) => ["", `== ${k}`, ...v.split("\n")])]; | |
| 584 | 590 | }; |
| 585 | 591 | return { |
| 586 | 592 | title: `${box.name}: the box`, |
| 587 | 593 | keys: [binding(["j", "k"], "scroll"), binding(["l"], "run checks while servers sleep: switch")], |
| 588 | 594 | render(area, s) { |
| 589 | 595 | const c = ctx.theme.c; |
| 590 | const all = lines(); | |
| 596 | const all = lines(Math.max(10, area.w)); | |
| 591 | 597 | top = Math.max(0, Math.min(top, all.length - area.h)); |
| 592 | 598 | all.slice(top, top + area.h).forEach((l, i) => |
| 593 | 599 | s.text(area.x, area.y + i, truncate(l, area.w), style(l.startsWith("== ") ? c.mutedFg : c.fg, c.bg), area.x + area.w), |
src/web/pages/cloud_tree.ts +1 −1
| @@ -98,7 +98,7 @@ function level(v: CloudView, n: CloudNode, current: readonly string[], openAll: | ||
| 98 | 98 | const href = cloudHref(c.path, v.q); |
| 99 | 99 | const at = c.path.every((p, i) => current[i] === p); |
| 100 | 100 | const here = at && current.length === c.path.length; |
| 101 | const kind = c.container !== undefined ? c.container.state : c.resource === undefined ? "" : `${c.resource.kind}${unused(c.resource) ? " · unattached" : ""}${c.children.length === 0 ? "" : ` · ${containersSay(c)}`}`; | |
| 101 | const kind = c.container !== undefined ? c.container.state : c.resource === undefined ? "" : `${c.resource.kind}${c.held === undefined ? "" : " · held"}${unused(c.resource) ? " · unattached" : ""}${c.children.length === 0 ? "" : ` · ${containersSay(c)}`}`; | |
| 102 | 102 | if (kind !== "" && c.children.length === 0) |
| 103 | 103 | return html`<li><a class="ex-file" data-ex-file data-nav tabindex="-1" href="${href}" ${here ? raw('aria-current="page"') : null}><span class="truncate">${c.name}</span><span class="ex-kind">${kind}</span>${cost(c)}</a></li>`; |
| 104 | 104 | const open = at || (openAll && c.resource === undefined) || c.level === "cloud" || (c.level === "account" && c.children.length <= OPEN_ACCOUNT); |
src/web/pages/games.ts +11
| @@ -18,6 +18,8 @@ import { statusRow } from "./security.ts"; | ||
| 18 | 18 | import { lendState, lentRunnerOf, setLend } from "../../games/lend.ts"; |
| 19 | 19 | import { spareRow } from "../../games/spare_row.ts"; |
| 20 | 20 | import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts"; |
| 21 | import { HELD_DOC, heldOn } from "../../games/hold.ts"; | |
| 22 | import { docHref } from "./docs_link.ts"; | |
| 21 | 23 | import { commitSettings, planSettings, previewSettings, settingsOf, SETTINGS, type SettingValue, type SettingsPlan } from "../../games/settings.ts"; |
| 22 | 24 | import { |
| 23 | 25 | answersOf, |
| @@ -304,6 +306,7 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 304 | 306 | body: html`${pageHead(box.name, { |
| 305 | 307 | sub: `${box.repo}@${box.branch}:${box.path}${box.composeSha === "" ? "" : ` · running ${box.composeSha.slice(0, 10)}`}`, |
| 306 | 308 | })} |
| 309 | ${holdNotice(ctx, box)} | |
| 307 | 310 | ${cloud === undefined |
| 308 | 311 | ? null |
| 309 | 312 | // An admin goes on to the machine itself on Infrastructure, where its cost and end are |
| @@ -577,6 +580,7 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> { | ||
| 577 | 580 | styleCss: TOPOLOGY_CSS, |
| 578 | 581 | scriptJs: gamesConsoleJs, |
| 579 | 582 | body: html`${pageHead(service, { sub: `on ${box.name}`, actions: act ? power(box, service, seen) : undefined })} |
| 583 | ${holdNotice(ctx, box)} | |
| 580 | 584 | <p class="game-now" id="game-now" aria-live="polite">${nowWords(seen, powerNow(ctx.app.db, box.id, service))}</p> |
| 581 | 585 | <p class="muted small" id="game-figures">${figuresOf(ctx.app.db, ctx.auth.user, box, service)}</p> |
| 582 | 586 | ${held} |
| @@ -1337,6 +1341,13 @@ export const gameModPack = (ctx: Ctx): Promise<Response> => modsSubmit(ctx, (m, | ||
| 1337 | 1341 | // POST /games/:box/:service/mods/remove: a project, and what only it required. |
| 1338 | 1342 | export const gameModRemove = (ctx: Ctx): Promise<Response> => modsSubmit(ctx, (m, service, project) => planRemove(m, service, project)); |
| 1339 | 1343 | |
| 1344 | /** A box that starts nothing: why, and for its owner the next step. */ | |
| 1345 | function holdNotice(ctx: Ctx, box: GameBox): Html | null { | |
| 1346 | const held = heldOn(ctx.app.db, ctx.auth.user, box); | |
| 1347 | if (held === undefined) return null; | |
| 1348 | return html`<p class="notice" role="status" data-held>Held: ${held.says}${held.next === "" ? null : html` ${held.next} <a href="${docHref(HELD_DOC)}">The steps are under Held</a>.`}</p>`; | |
| 1349 | } | |
| 1350 | ||
| 1340 | 1351 | /** Why a compose change has not come to the box or its proxy, and a jar an undo may have left there. */ |
| 1341 | 1352 | const heldNotice = async (ctx: Ctx, box: GameBox, compose: { sha: string; text: string } | undefined): Promise<Html> => { |
| 1342 | 1353 | const words = [heldWords(ctx.app, box, compose), await leftWords(ctx.app, box, compose)].filter((w) => w !== ""); |
test/cloud-containers.test.ts +2 −2
| @@ -65,7 +65,7 @@ const at = (path: string[], v = view()): CloudNode => { | ||
| 65 | 65 | const facts = (path: string[]): Record<string, string> => Object.fromEntries(factsOf(view().whole, at(path)).map((f) => [f.label, f.value])); |
| 66 | 66 | const get = async (path: string[], part = ""): Promise<string> => |
| 67 | 67 | (await fetch(`${servers.url}/infra/-/${path.map(encodeURIComponent).join("/")}${part}`, { headers: { cookie: `forge_session=${createSession(app.db, alice.id).token}` } })).text(); |
| 68 | const names = (who: User | undefined): string[] => [...containersOf(app.db, who).values()].flat().map((c) => c.name); | |
| 68 | const names = (who: User | undefined): string[] => [...containersOf(app.db, who).values()].flatMap((m) => m.containers).map((c) => c.name); | |
| 69 | 69 | |
| 70 | 70 | beforeAll(async () => { |
| 71 | 71 | dir = mkdtempSync(join(tmpdir(), "forge-cloud-containers-")); |
| @@ -103,7 +103,7 @@ test("a person sees the containers their games role covers, and nobody the waker | ||
| 103 | 103 | grant(app.db, boxNamed(app.db, "mc")!.id, bob.id, "viewer", "hub"); |
| 104 | 104 | expect(names(bob)).toEqual(["hub"]); |
| 105 | 105 | // The box's diagnosis, and the images in it, are its owner's. |
| 106 | expect([...containersOf(app.db, bob).values()].flat()[0]!.image).toBe(""); | |
| 106 | expect([...containersOf(app.db, bob).values()][0]!.containers[0]!.image).toBe(""); | |
| 107 | 107 | // The cloud tree itself is a forge admin's. |
| 108 | 108 | expect(cloudResources(app, bob, "").ok).toBe(false); |
| 109 | 109 | }); |
test/game-diag.test.ts +1 −1
| @@ -174,7 +174,7 @@ esac | ||
| 174 | 174 | try { |
| 175 | 175 | expect(await agent.exited).toBe(0); |
| 176 | 176 | expect(box.bodies).toHaveLength(1); |
| 177 | expect(box.bodies[0]!["diag"]).toEqual({ note: "diag ran over 1 s" }); | |
| 177 | expect(box.bodies[0]!["diag"]).toEqual({ note: "diag ran over 1 s", hold: null }); | |
| 178 | 178 | // The hung probe was stopped at the deadline: the sync went out in seconds. |
| 179 | 179 | expect(Date.now() - started).toBeLessThan(4_500); |
| 180 | 180 | } finally { |
test/game-hold.test.ts added +187
| @@ -0,0 +1,187 @@ | ||
| 1 | /** | |
| 2 | * A held game box says so first, at every door (#17532): why, and the next step, to its owner; that | |
| 3 | * its owner has to look, to anyone else. The words come from a code, so no log line is read. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, expect, 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 { cloudResources } from "../src/actions/infra.ts"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { factsOf, nodeAt } from "../src/cloud/tree.ts"; | |
| 13 | import { insertPinned, setRemote } from "../src/core/pinned.ts"; | |
| 14 | import { createSession } from "../src/core/sessions.ts"; | |
| 15 | import { createToken } from "../src/core/tokens.ts"; | |
| 16 | import { createUser, type User } from "../src/core/users.ts"; | |
| 17 | import { boxStatus, DIAG_MOST, holdOf, keptDiag, readDiag } from "../src/games/diag.ts"; | |
| 18 | import { heldOn } from "../src/games/hold.ts"; | |
| 19 | import { boxNamed, createGameBox, grant, recordSync } from "../src/games/store.ts"; | |
| 20 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 21 | import { cloudLines } from "../src/tui/screens/cloudtree.ts"; | |
| 22 | import { gameBoxScreen, gamesScreen } from "../src/tui/screens/games.ts"; | |
| 23 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 24 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 25 | import { quietLogs } from "./helpers/globals.ts"; | |
| 26 | import { mcpTool } from "./helpers/mcp.ts"; | |
| 27 | import { settleApp } from "./helpers/tui.ts"; | |
| 28 | ||
| 29 | quietLogs(); | |
| 30 | ||
| 31 | let dir = ""; | |
| 32 | let app: App; | |
| 33 | let servers: Servers; | |
| 34 | let alice: User; | |
| 35 | let bob: User; | |
| 36 | const MACHINE = ["hetzner", "eu", "games", "machine:77"]; | |
| 37 | const since = new Date(Date.now() - 5 * 60_000).toISOString().replace(/\.\d+Z$/, "Z"); | |
| 38 | const sync = (hold: unknown, o: { at?: Date; services?: boolean } = {}): void => | |
| 39 | void recordSync(app.db, boxNamed(app.db, "mc")!, { services: o.services === false ? [] : [{ name: "hub", state: "running", health: "", startedAt: "", cpuPct: 1, memMiB: 900 }], diag: hold === undefined ? {} : { hold } }, o.at ?? new Date()); | |
| 40 | const person = async (username: string): Promise<User> => { | |
| 41 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst: true }); | |
| 42 | if (!made.ok) throw new Error(made.error); | |
| 43 | return made.value; | |
| 44 | }; | |
| 45 | const get = async (who: User, path: string): Promise<string> => (await fetch(`${servers.url}${path}`, { headers: { cookie: `forge_session=${createSession(app.db, who.id).token}` } })).text(); | |
| 46 | const notice = (page: string): string | undefined => /data-held>([\s\S]*?)<\/p>/.exec(page)?.[1]; | |
| 47 | const tty = async (who: User, box = false): Promise<string> => { | |
| 48 | const { app: tui, session } = createForgeApp(app, { sshUsername: who.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: who }, { terminal: headlessTerminal(100, 40), exitHooks: false }); | |
| 49 | tui.start(); | |
| 50 | tui.ctx.push(box ? gameBoxScreen(session, tui.ctx, boxNamed(app.db, "mc")!) : gamesScreen(session, tui.ctx)); | |
| 51 | await settleApp(tui); | |
| 52 | const text = tui.screen.toText().replace(/\s+/g, " "); | |
| 53 | tui.stop?.(); | |
| 54 | return text; | |
| 55 | }; | |
| 56 | const machine = () => { | |
| 57 | const v = cloudResources(app, alice, ""); | |
| 58 | if (!v.ok) throw new Error(v.error); | |
| 59 | return { v: v.value, n: nodeAt(v.value.root, MACHINE)! }; | |
| 60 | }; | |
| 61 | ||
| 62 | beforeAll(async () => { | |
| 63 | dir = mkdtempSync(join(tmpdir(), "forge-game-hold-")); | |
| 64 | app = createApp({ dataDir: dir, port: 0 }); | |
| 65 | alice = await person("alice"); | |
| 66 | bob = await person("bob"); | |
| 67 | const now = new Date().toISOString(); | |
| 68 | app.db.run("INSERT INTO cloud_account (provider, name, summary, write_allowed) VALUES ('hetzner', 'eu', '', 0)"); | |
| 69 | app.db.run("INSERT INTO cloud_project (cloud_provider, cloud_account_id, cloud_project_id, name, is_default, read_at) VALUES ('hetzner', 'eu', 'games', 'games', 1, ?1)", [now]); | |
| 70 | app.db.run( | |
| 71 | "INSERT INTO cloud_resource (cloud_provider, cloud_account_id, cloud_resource_id, cloud_project_id, kind, name, cloud_region, host_type, label, made_by, cents, created_at, read_at, state, attached_to, made_from) VALUES ('hetzner', 'eu', 'machine:77', 'games', 'machine', 'forge-mc', 'nbg1', 'cx43', '', 'found', 1200, ?1, ?1, 'running', '', '')", | |
| 72 | [now], | |
| 73 | ); | |
| 74 | const pinned = insertPinned(app.db, { name: "mc", target: "hetzner", account: "eu", app: "alice/game", source: "", version: "v1.0.0", config: {}, host: "mc.example.com", claimHash: "", claimExpires: "", datacenter: "nbg1", size: "cx43", boots: "game" }, alice.id); | |
| 75 | setRemote(app.db, pinned.name, { remote: "77" }); | |
| 76 | createGameBox(app.db, { name: "mc", repo: "alice/game", pinnedId: pinned.id }); | |
| 77 | grant(app.db, boxNamed(app.db, "mc")!.id, bob.id, "viewer", ""); | |
| 78 | servers = await serve(app); | |
| 79 | }); | |
| 80 | afterAll(async () => { | |
| 81 | servers.stop(); | |
| 82 | app.close(); | |
| 83 | await rm(dir, { recursive: true, force: true }); | |
| 84 | }); | |
| 85 | ||
| 86 | test("each code has its words and a next step, none of which deletes; a code it does not know is held, and null or nothing is not", () => { | |
| 87 | const said = ["no-volume", "signature", "mount", "other-worlds", "something-new"].map((why) => { | |
| 88 | sync({ why, since }); | |
| 89 | return heldOn(app.db, alice, boxNamed(app.db, "mc")!)!; | |
| 90 | }); | |
| 91 | expect(new Set(said.map((h) => h.says)).size).toBe(5); | |
| 92 | for (const h of said) { | |
| 93 | expect(h.says).toContain("Nothing is started; containers that already run are left alone. The agent last looked 5 minutes ago."); | |
| 94 | expect(h.next).not.toBe(""); | |
| 95 | expect(`${h.says} ${h.next}`.replace("Nothing is deleted.", "")).not.toMatch(/delet|empty|wipe|format|remove|unused|safe/i); | |
| 96 | } | |
| 97 | for (const odd of ["", "held", 1, {}, [], { why: "x".repeat(99), since: "yesterday" }]) expect(holdOf({ hold: odd })).toEqual({ why: "unknown", since: "" }); | |
| 98 | for (const none of [null, undefined]) { | |
| 99 | sync(none); | |
| 100 | expect(heldOn(app.db, alice, boxNamed(app.db, "mc")!)).toBeUndefined(); | |
| 101 | } | |
| 102 | }); | |
| 103 | ||
| 104 | test("a diag too big to keep still says the box is held, and the log's refusal is not said twice", () => { | |
| 105 | const big = readDiag(keptDiag({ upLog: "x".repeat(DIAG_MOST), hold: { why: "mount", since, more: "y".repeat(DIAG_MOST) } })); | |
| 106 | expect(holdOf(big)).toEqual({ why: "mount", since }); | |
| 107 | expect(holdOf(readDiag(keptDiag({ upLog: "x".repeat(DIAG_MOST), hold: null })))).toBeUndefined(); | |
| 108 | const disk = { volume: "/mnt/d", volumeMounted: false, onVolume: false, device: "/dev/sdb", log: `${since} refused: the volume holds worlds` }; | |
| 109 | expect(boxStatus({ disk, hold: { why: "other-worlds", since } })).toEqual(["The volume is not mounted at /mnt/d"]); | |
| 110 | }); | |
| 111 | ||
| 112 | test("the web: first on the box's page and on its server's, with a link that opens the steps; a viewer reads no reason", async () => { | |
| 113 | sync({ why: "other-worlds", since }); | |
| 114 | const page = await get(alice, "/games/mc"); | |
| 115 | expect(notice(page)).toContain("Held: its volume holds data, and so does its own disk. Nothing is started;"); | |
| 116 | expect(notice(page)).toContain("move the other side aside. Nothing is deleted."); | |
| 117 | expect(page.indexOf("data-held")).toBeLessThan(page.indexOf("How to join")); | |
| 118 | const href = /href="(\/docs\/[^"]+)"/.exec(notice(page)!)![1]!; | |
| 119 | const doc = await fetch(`${servers.url}${href}`); | |
| 120 | expect(doc.status).toBe(200); | |
| 121 | expect(await doc.text()).toContain("Which side was played last?"); | |
| 122 | expect(notice(await get(alice, "/games/mc/hub"))).toBe(notice(page)); | |
| 123 | for (const path of ["/games/mc", "/games/mc/hub"]) expect(notice(await get(bob, path))).toBe("Held: nothing is started until its owner has looked."); | |
| 124 | sync(null); | |
| 125 | expect(await get(alice, "/games/mc")).not.toContain("data-held"); | |
| 126 | }); | |
| 127 | ||
| 128 | test("the terminal: the Games list and the box's screen, the whole step, with no server yet as well", async () => { | |
| 129 | sync({ why: "other-worlds", since }); | |
| 130 | for (const text of [await tty(alice), await tty(alice, true)]) { | |
| 131 | expect(text).toContain("Held: its volume holds data, and so does its own disk."); | |
| 132 | expect(text).toContain("move the other side aside. Nothing is deleted. The steps are in docs/features/game-box.md, under Held."); | |
| 133 | } | |
| 134 | expect(await tty(bob)).toContain("mc: Held: nothing is started until its owner has looked."); | |
| 135 | expect(await tty(bob)).not.toContain("volume"); | |
| 136 | app.db.run("DELETE FROM game_service"); | |
| 137 | sync({ why: "no-volume", since }, { services: false }); | |
| 138 | expect(await tty(alice)).toContain("Attach the volume: the agent sees it and looks again by itself."); | |
| 139 | sync(null); | |
| 140 | expect(await tty(alice)).not.toContain("Held"); | |
| 141 | }); | |
| 142 | ||
| 143 | test("the machine in the tree: its row, its first facts, the closed branches above it, and a machine with no container yet", async () => { | |
| 144 | app.db.run("DELETE FROM game_service"); | |
| 145 | sync({ why: "mount", since }, { services: false }); | |
| 146 | const { v, n } = machine(); | |
| 147 | expect(n.children).toHaveLength(0); | |
| 148 | expect(factsOf(v.whole, n).slice(0, 2)).toEqual([ | |
| 149 | { label: "Held", value: "its volume could not be mounted. Nothing is started; containers that already run are left alone. The agent last looked 5 minutes ago." }, | |
| 150 | { label: "Next step", value: "Look at the device on the machine, then restart the agent there." }, | |
| 151 | ]); | |
| 152 | expect(nodeAt(v.root, MACHINE.slice(0, 3))!.alert).toBe(true); | |
| 153 | expect(cloudLines(v, n).join("\n")).toMatch(/Held +its volume could not be mounted/); | |
| 154 | const page = await get(alice, `/infra/-/${MACHINE.join("/")}`); | |
| 155 | expect(page).toContain('<dt>Held</dt><dd><a href="/games/mc">its volume could not be mounted.'); | |
| 156 | expect(page).toContain("machine · held"); | |
| 157 | sync(null); | |
| 158 | expect(machine().n.held).toBeUndefined(); | |
| 159 | expect(nodeAt(machine().v.root, MACHINE.slice(0, 3))!.alert).toBe(false); | |
| 160 | }); | |
| 161 | ||
| 162 | test("the tools say it, and a silent box's hold is told as what it last said", async () => { | |
| 163 | sync({ why: "other-worlds", since }); | |
| 164 | const token = createToken(app.db, alice.id, "t", "admin").token; | |
| 165 | const held = (await mcpTool(servers.url, token, "games", { action: "list" })).value.items[0].held; | |
| 166 | expect(held[0]).toContain("Held: its volume holds data"); | |
| 167 | expect(held[1]).toContain("Next: Take a snapshot of the volume"); | |
| 168 | expect((await mcpTool(servers.url, token, "infra", { action: "cloud", id: MACHINE.join("/") })).value.facts[0].label).toBe("Held"); | |
| 169 | sync({ why: "other-worlds", since }, { at: new Date(Date.now() - 3 * 3_600_000) }); | |
| 170 | expect(heldOn(app.db, bob, boxNamed(app.db, "mc")!)!.says).toBe("nothing is started until its owner has looked. The box was last heard from 3 hours ago, so whether it is still held is not known."); | |
| 171 | sync(null); | |
| 172 | expect((await mcpTool(servers.url, token, "games", { action: "list" })).value.items[0]).not.toHaveProperty("held"); | |
| 173 | }); | |
| 174 | ||
| 175 | test("a box that sends markup or a control code as its hold is held without a reason, and none of it reaches a door", async () => { | |
| 176 | const why = '<img src=x onerror="alert(1)">hostile'; | |
| 177 | sync({ why, since: "2026-12-03T01:02:03Z<script>hostile</script>\u001b[31m" }); | |
| 178 | expect(holdOf(boxNamed(app.db, "mc")!.diag)).toEqual({ why: "unknown", since: "" }); | |
| 179 | const token = createToken(app.db, alice.id, "x", "admin").token; | |
| 180 | const doors = [await get(alice, "/games/mc"), await get(alice, "/games/mc/hub"), await get(alice, `/infra/-/${MACHINE.join("/")}`), await tty(alice), await tty(alice, true), JSON.stringify((await mcpTool(servers.url, token, "games", { action: "list" })).value)]; | |
| 181 | for (const text of doors) { | |
| 182 | expect(text).toContain("its agent did not say why. Nothing is started;"); | |
| 183 | for (const raw of ["hostile", "onerror=", "alert(1)", "The agent last looked"]) expect(text).not.toContain(raw); | |
| 184 | } | |
| 185 | for (const path of ["/games/mc", "/games/mc/hub"]) expect(notice(await get(bob, path))).toBe("Held: nothing is started until its owner has looked."); | |
| 186 | sync(null); | |
| 187 | }); |
test/game-volume.test.ts +129 −3
| @@ -22,8 +22,10 @@ import { | ||
| 22 | 22 | mkdtempSync, |
| 23 | 23 | readFileSync, |
| 24 | 24 | readlinkSync, |
| 25 | renameSync, | |
| 25 | 26 | realpathSync, |
| 26 | 27 | symlinkSync, |
| 28 | unlinkSync, | |
| 27 | 29 | writeFileSync, |
| 28 | 30 | } from "node:fs"; |
| 29 | 31 | import { rm } from "node:fs/promises"; |
| @@ -31,6 +33,7 @@ import { tmpdir } from "node:os"; | ||
| 31 | 33 | import { join } from "node:path"; |
| 32 | 34 | import { AGENT_SH, AGENT_SHA, gameBootConfig } from "../src/games/boot.ts"; |
| 33 | 35 | import { boxStatus } from "../src/games/diag.ts"; |
| 36 | import { waitFor } from "./helpers/poll.ts"; | |
| 34 | 37 | |
| 35 | 38 | const AGENT = join(import.meta.dir, "../src/games/agent.sh"); |
| 36 | 39 | const BASH = Bun.which("bash"); |
| @@ -130,6 +133,9 @@ afterAll(async () => { | ||
| 130 | 133 | if (bins.with !== "") await rm(join(bins.with, ".."), { recursive: true, force: true }); |
| 131 | 134 | }); |
| 132 | 135 | |
| 136 | /** A machine-id the boxes here have: an unfinished copy on the volume names the box that made it. */ | |
| 137 | const MACHINE = "00112233445566778899aabbccddeeff"; | |
| 138 | ||
| 133 | 139 | /** A fake box: its stub PATH, its state, its data directory and its volume (a by-id link to a device). */ |
| 134 | 140 | function box(o: { data?: Record<string, string>; volume?: Record<string, string>; state?: string[]; rsync?: false } = {}) { |
| 135 | 141 | const root = realpathSync(mkdtempSync(join(tmpdir(), "forge-game-volume-"))); |
| @@ -153,6 +159,7 @@ function box(o: { data?: Record<string, string>; volume?: Record<string, string> | ||
| 153 | 159 | for (const [f, text] of Object.entries(o.volume)) writeFileSync(join(st, "volume", f), text); |
| 154 | 160 | } |
| 155 | 161 | for (const f of o.state ?? []) writeFileSync(join(st, f.split("=")[0]!), f.includes("=") ? `${f.split("=")[1]}\n` : ""); |
| 162 | writeFileSync(join(root, "machine-id"), `${MACHINE}\n`); | |
| 156 | 163 | writeFileSync(join(game, ".compose-sha"), "abc\n"); |
| 157 | 164 | writeFileSync(join(game, "compose.yml"), "services: {}\n"); |
| 158 | 165 | const env = { |
| @@ -168,6 +175,7 @@ function box(o: { data?: Record<string, string>; volume?: Record<string, string> | ||
| 168 | 175 | FORGE_GAME_FSTAB: join(root, "fstab"), |
| 169 | 176 | FORGE_GAME_SYSTEMD_DIR: join(root, "systemd"), |
| 170 | 177 | FORGE_GAME_VOLUME_WAIT: "1", |
| 178 | FORGE_GAME_MACHINE_ID: join(root, "machine-id"), | |
| 171 | 179 | FORGE_GAME_DOCKER: join(bin, "docker"), |
| 172 | 180 | }; |
| 173 | 181 | const read = (p: string): string => (existsSync(p) ? readFileSync(p, "utf8") : ""); |
| @@ -191,11 +199,35 @@ function box(o: { data?: Record<string, string>; volume?: Record<string, string> | ||
| 191 | 199 | onVolume: (f: string) => read(join(st, "volume", f)), |
| 192 | 200 | composeSha: () => existsSync(join(game, ".compose-sha")), |
| 193 | 201 | state: (f: string) => existsSync(join(st, f)), |
| 202 | held: () => existsSync(join(game, ".volume.hold")), | |
| 194 | 203 | }; |
| 195 | 204 | } |
| 196 | 205 | |
| 197 | 206 | const FSTAB_LINE = (dir: string) => `UUID=0f1e2d3c-volume ${dir} ext4 defaults,nofail,discard 0 2\n`; |
| 198 | 207 | |
| 208 | /** The whole agent on the box, one sync at a time, against a forge that answers with `answer`. */ | |
| 209 | function synced(b: ReturnType<typeof box>, answer: (n: number) => Record<string, unknown>) { | |
| 210 | const extra = join(b.root, "bin"); | |
| 211 | mkdirSync(extra); | |
| 212 | symlinkSync(Bun.which("curl")!, join(extra, "curl")); | |
| 213 | const bodies: Record<string, unknown>[] = []; | |
| 214 | const server = Bun.serve({ | |
| 215 | port: 0, | |
| 216 | hostname: "127.0.0.1", | |
| 217 | fetch: async (req) => { | |
| 218 | const body = (await req.json()) as Record<string, unknown>; | |
| 219 | if ("boot" in body) return new Response("{}"); | |
| 220 | bodies.push(body); | |
| 221 | return Response.json(answer(bodies.length)); | |
| 222 | }, | |
| 223 | }); | |
| 224 | const sync = async (): Promise<void> => { | |
| 225 | const env = { ...b.env, PATH: `${extra}:${b.env.PATH}:${process.env["PATH"] ?? ""}`, FORGE_URL: `http://127.0.0.1:${server.port}`, FORGE_GAME_ONCE: "1", FORGE_GAME_DIAG_S: "0" }; | |
| 226 | await Bun.spawn([BASH!, AGENT], { env, cwd: b.root, stdout: "ignore", stderr: "ignore" }).exited; | |
| 227 | }; | |
| 228 | return { bodies, sync, server }; | |
| 229 | } | |
| 230 | ||
| 199 | 231 | describe.skipIf(BASH === null || lacks.length > 0)("agent.sh --mount-volume", () => { |
| 200 | 232 | test("a blank device is formatted, mounted at the data directory, kept in fstab, and Docker waits for it", () => { |
| 201 | 233 | const b = box(); |
| @@ -212,7 +244,8 @@ describe.skipIf(BASH === null || lacks.length > 0)("agent.sh --mount-volume", () | ||
| 212 | 244 | |
| 213 | 245 | test("a device with a signature but no filesystem is refused, never formatted, never mounted", () => { |
| 214 | 246 | const b = box({ state: ["sig"] }); |
| 215 | expect(b.run().code).toBe(0); | |
| 247 | expect(b.run().code).toBe(1); | |
| 248 | expect(b.held()).toBe(true); | |
| 216 | 249 | expect(b.calls().some((c) => c.startsWith("mkfs"))).toBe(false); |
| 217 | 250 | expect(b.calls().some((c) => c.startsWith("mount "))).toBe(false); |
| 218 | 251 | expect(b.log()).toContain(`refused: ${b.dev} has a signature but no filesystem this box knows; nothing was formatted`); |
| @@ -221,8 +254,9 @@ describe.skipIf(BASH === null || lacks.length > 0)("agent.sh --mount-volume", () | ||
| 221 | 254 | |
| 222 | 255 | test("a volume that already holds data is refused: nothing is copied or stopped, and the root disk's data is as it was", () => { |
| 223 | 256 | const b = box({ data: { "level.dat": "the root disk's world" }, volume: { "level.dat": "another world" }, state: ["docker-active"] }); |
| 224 | expect(b.run().code).toBe(0); | |
| 225 | expect(b.log()).toContain("refused: the volume already holds data; nothing was copied, the data stays on the root disk"); | |
| 257 | expect(b.run().code).toBe(1); | |
| 258 | expect(b.held()).toBe(true); | |
| 259 | expect(b.log()).toContain("refused: the volume holds worlds and this disk holds others: nothing is started; docs/features/game-box.md (Held) says how to choose"); | |
| 226 | 260 | expect(b.file("level.dat")).toBe("the root disk's world"); |
| 227 | 261 | expect(b.onVolume("level.dat")).toBe("another world"); |
| 228 | 262 | expect(b.mountedOnVolume()).toBe(false); |
| @@ -314,6 +348,96 @@ describe.skipIf(BASH === null || lacks.length > 0)("agent.sh --mount-volume", () | ||
| 314 | 348 | expect(boxStatus({ disk: { volume: b.data, volumeMounted: false, device: b.dev, log: b.log() } })).toContain(`The volume: ${said}`); |
| 315 | 349 | }); |
| 316 | 350 | |
| 351 | test("games are held only when the volume may hold other worlds, never when it was empty or there is none", () => { | |
| 352 | const disk = { "level.dat": "world" }; | |
| 353 | const worlds = { "level.dat": "the worlds" }; | |
| 354 | const after = (o: Parameters<typeof box>[0], change: (b: ReturnType<typeof box>) => void = () => {}): boolean => { | |
| 355 | const b = box(o); | |
| 356 | change(b); | |
| 357 | b.run(); | |
| 358 | return b.held(); | |
| 359 | }; | |
| 360 | const fails = (b: ReturnType<typeof box>, at: string) => writeFileSync(join(b.root, "st", "fail-mount"), `${at}\n`); | |
| 361 | const gone = (b: ReturnType<typeof box>) => unlinkSync(b.dev); | |
| 362 | // Not mounted, and it has a filesystem: nobody knows what it holds. | |
| 363 | expect(after({ volume: worlds }, (b) => fails(b, b.data))).toBe(true); | |
| 364 | expect(after({ data: disk, volume: worlds }, (b) => fails(b, join(b.root, "move")))).toBe(true); | |
| 365 | // No device at the first boot of a box that never ran anything; one that ran goes on as it was. | |
| 366 | expect(after({}, (b) => { gone(b); unlinkSync(join(b.game, ".compose-sha")); })).toBe(true); | |
| 367 | expect(after({ data: disk }, gone)).toBe(false); | |
| 368 | // The volume was blank or empty, so this disk's data is the only data there is. | |
| 369 | expect(after({ data: disk }, (b) => fails(b, join(b.root, "move")))).toBe(false); | |
| 370 | expect(after({ data: disk, rsync: false })).toBe(false); | |
| 371 | expect(after({ data: disk, state: ["compose-fail"] })).toBe(false); | |
| 372 | // A copy of this disk that did not end, then the next start: still this disk's data. Another box's copy is not. | |
| 373 | const b = box({ data: disk, volume: {}, state: ["docker-active"] }); | |
| 374 | fails(b, b.data); | |
| 375 | b.run(); | |
| 376 | b.run(); | |
| 377 | expect(b.log()).toContain("refused: the volume holds this box's own unfinished copy; the data stays on the root disk"); | |
| 378 | expect(b.held()).toBe(false); | |
| 379 | writeFileSync(join(b.root, "machine-id"), "another\n"); | |
| 380 | b.run(); | |
| 381 | expect(b.held()).toBe(true); | |
| 382 | // The volume back where it belongs lets go, and a whole copy carries no mark. | |
| 383 | const ok = box({ data: disk, volume: {} }); | |
| 384 | writeFileSync(join(ok.game, ".volume.hold"), ""); | |
| 385 | expect(ok.run().code).toBe(0); | |
| 386 | expect(ok.held()).toBe(false); | |
| 387 | expect(ok.onVolume(".forge-copying")).toBe(""); | |
| 388 | }); | |
| 389 | ||
| 390 | test.skipIf(Bun.which("jq") === null || Bun.which("curl") === null)("a held box syncs and starts nothing; once the volume is right, it comes up", async () => { | |
| 391 | const b = box({ data: { "level.dat": "new and empty" }, volume: { "level.dat": "the worlds" } }); | |
| 392 | const { bodies, sync, server } = synced(b, (n) => ({ commands: n === 1 ? [{ id: "c1", kind: "start", service: "lobby", text: "" }] : [], composeSha: "def", compose: "services: {}\n" })); | |
| 393 | const started = () => b.calls().filter((c) => / (up|start) /.test(c) && c.startsWith("docker compose")); | |
| 394 | try { | |
| 395 | for (let i = 0; i < 4; i++) await sync(); | |
| 396 | expect(bodies).toHaveLength(4); | |
| 397 | expect(started()).toEqual([]); | |
| 398 | expect(bodies.flatMap((x) => x["results"] as { id: string; ok: boolean; output: string }[])).toEqual([ | |
| 399 | { id: "c1", ok: false, output: expect.stringMatching(/^nothing is started: this box is held \(other-worlds\); .*game-box\.md \(Held\)/) }, | |
| 400 | ]); | |
| 401 | expect(bodies.at(-1)!["composeSha"]).toBe(""); | |
| 402 | // The forge reads the code, not the sentence. | |
| 403 | expect(bodies.at(-1)!["diag"]).toEqual({ hold: { why: "other-worlds", since: expect.stringMatching(/^\d{4}-\d\d-\d\dT[\d:]+Z$/) } }); | |
| 404 | // A person moved the volume's worlds aside, on the volume: this disk's data moves there, and the games come up. | |
| 405 | const aside = join(b.root, "st", "volume", "forge-aside"); | |
| 406 | mkdirSync(aside); | |
| 407 | renameSync(join(b.root, "st", "volume", "level.dat"), join(aside, "level.dat")); | |
| 408 | for (let i = 0; i < 3; i++) await sync(); | |
| 409 | expect(await waitFor(() => started().length > 0, { within: 10_000, what: "the up" })).toBe(true); | |
| 410 | expect(b.file("level.dat")).toBe("new and empty"); | |
| 411 | expect(readFileSync(join(aside, "level.dat"), "utf8")).toBe("the worlds"); | |
| 412 | expect(bodies.at(-1)!["diag"]).toEqual({ hold: null }); | |
| 413 | } finally { | |
| 414 | server.stop(true); | |
| 415 | } | |
| 416 | }, 60_000); | |
| 417 | ||
| 418 | // Box mc on 2026-12-03: ext4 on /dev/sda at the data directory, Docker's root on it, no mark and no hold. | |
| 419 | test.skipIf(Bun.which("jq") === null || Bun.which("curl") === null)("a box whose volume is mounted is left alone at its next start: no hold, no copy, no mount, no restart, no up", async () => { | |
| 420 | const b = box({ volume: {}, state: ["docker-active"] }); | |
| 421 | mkdirSync(join(b.data, "docker", "volumes"), { recursive: true }); | |
| 422 | writeFileSync(join(b.data, "docker", "volumes", "level.dat"), "the worlds"); | |
| 423 | writeFileSync(join(b.root, "st", "mounts"), `${b.sda} ${b.data}\n`); | |
| 424 | const { bodies, sync, server } = synced(b, () => ({ commands: [], composeSha: "abc" })); | |
| 425 | try { | |
| 426 | for (let i = 0; i < 3; i++) await sync(); | |
| 427 | expect(bodies).toHaveLength(3); | |
| 428 | expect(bodies.every((x) => (x["diag"] as { hold: unknown }).hold === null && String(x["composeSha"]).trim() === "abc")).toBe(true); | |
| 429 | expect(b.held()).toBe(false); | |
| 430 | // Every stubbed tool that changes a machine writes itself down: none was called, and Docker was only asked. | |
| 431 | expect(b.calls().filter((c) => !c.startsWith("docker "))).toEqual([]); | |
| 432 | expect(b.calls().filter((c) => /^docker (run|start|stop|restart|kill|rm) | (up|start|stop|restart|down|pull|rm)( |$)/.test(c))).toEqual([]); | |
| 433 | expect(b.log()).toBe(""); | |
| 434 | expect(b.fstab()).toBe(""); | |
| 435 | expect(readFileSync(join(b.data, "docker", "volumes", "level.dat"), "utf8")).toBe("the worlds"); | |
| 436 | } finally { | |
| 437 | server.stop(true); | |
| 438 | } | |
| 439 | }, 60_000); | |
| 440 | ||
| 317 | 441 | test("mounted means the volume is the mount's source: a by-id link to it is, another device at the directory is not", () => { |
| 318 | 442 | const mine = box(); |
| 319 | 443 | mkdirSync(mine.data); |
| @@ -336,6 +460,8 @@ const SHA = Bun.which("sha256sum"); | ||
| 336 | 460 | describe.skipIf(BASH === null || lacks.length > 0 || CURL === null || SHA === null)("the boot's own lines, on a forge that is down at first", () => { |
| 337 | 461 | test("nothing is mounted or installed until the agent is there, and Docker starts on the volume that holds the worlds", async () => { |
| 338 | 462 | const b = box({ volume: { "level.dat": "the worlds" } }); |
| 463 | // cloud-init runs these lines with no set -e, so a volume that is not mounted ends no boot. | |
| 464 | expect(gameBootConfig({ forgeUrl: "https://forge.example", token: b.env.FORGE_GAME_TOKEN }, b.data)).not.toMatch(/set -e|--mount-volume *&&/); | |
| 339 | 465 | const extra = join(b.root, "bin"); |
| 340 | 466 | mkdirSync(extra); |
| 341 | 467 | symlinkSync(CURL!, join(extra, "curl")); |
new above
offline