Public: anyone can read this; the crew can change it.
Cloud says: every machine shows what its provider reports, even when its agent is silent #17156
Merged 37h 32m ago, live in production
sold/provider-view → main 0 commits 4 threads · 4 unresolved
17 files
changed +1148
−28
- docs/features/games.md
- docs/features/infra.md
- src/actions/cloud_says.ts
- src/cloud/provider_view.ts
- src/core/event_audience.ts
- src/games/store.ts
- src/http/infra_routes.ts
- src/http/mcp/tools/games.ts
- src/http/mcp/tools/infra.ts
- src/http/sse.ts
- src/tui/screens/games.ts
- src/tui/screens/infra.ts
- src/web/pages/games.ts
- src/web/pages/infra.ts
- test/cloud-says-doors.test.ts
- test/provider-view.test.ts
- test/timers-named.test.ts
docs/features/games.md +4
| @@ -33,6 +33,10 @@ The policy is the label `forge.sleep: "true"` with `restart: "no"` in the compos | ||
| 33 | 33 | |
| 34 | 34 | Warm again takes all of it away; the same labels always give the same file. Only an itzg/minecraft-server server can sleep; the proxy never does. Nothing chosen means warm. `/games/<box>` says "asleep (wakes on join)" for a sleeping server whose container has stopped. |
| 35 | 35 | |
| 36 | ## What the cloud says | |
| 37 | ||
| 38 | A box owner, and only an owner, sees what the provider says about the box machine (the same facts as on /infra, see docs/features/infra.md): as "Its machine" on `/games/<box>`, a line a box on the terminal Games screen, and as `cloud` on each box of the `games` tool `list`. The machine is the one the box own row names (its `pinnedId`), never one found by name. | |
| 39 | ||
| 36 | 40 | ## Secrets |
| 37 | 41 | |
| 38 | 42 | The Velocity forwarding secret (`forwarding.env`) and an RCON password a service (`rcon-<service>.env`) are generated once, sealed like every forge secret and sent only in the sync's `env`, never committed. A box token is shown once and stored hashed. An uploaded jar is kept by the forge at `/games/jar/<id>/<name>`; the compose a box gets carries it signed for 6 hours, and only for the box that uploaded it. A jar must be a `.jar` (a zip), at most 64 MiB, and a box keeps at most 20 jars and 256 MiB. |
docs/features/infra.md +8
| @@ -22,6 +22,14 @@ The hourly watch reads each account's firewalls too: one named `forge-<name>` th | ||
| 22 | 22 | |
| 23 | 23 | All four read `infraOf` and plan through `planCompose` in `src/actions/infra.ts`, which plans with `src/cloud/plan.ts`; only a forge admin sees them. |
| 24 | 24 | |
| 25 | ## What the cloud says (#17151) | |
| 26 | ||
| 27 | Each machine with an id at its provider shows what the provider itself says, as a fact under its row: **DigitalOcean** — "running · 4 vCPU 8 GB · Ubuntu 24.04 · nyc1 · 104.236.196.18 · volume forge_mc attached · last powered on at 17:44". It is read with the account sealed key, GETs only (DigitalOcean `droplets/<id>`, its actions and volumes; Hetzner `servers/<id>`, its actions and volumes), and kept 30 s. | |
| 28 | ||
| 29 | No page waits on a provider: a page draws the reading as kept (with its age once older than 30 s, or "reading…" before the first), a stale one is read in the background, and when that read says something new an `infra.cloud` event has the live region draw again. A failed read keeps the last good one and says it failed. Only a tool waits for a fresh reading, at most 1.5 s (`src/cloud/provider_view.ts`, `src/actions/cloud_says.ts`). | |
| 30 | ||
| 31 | It shows to admins on each machine row here, in the terminal Infra screen (a line a machine), and as `cloud` in the `infra` tool `list` and `show` (each line at most 400 characters). | |
| 32 | ||
| 25 | 33 | ## Snapshots (#17072) |
| 26 | 34 | |
| 27 | 35 | A snapshot is an infra kind of its own, offered before an End and restored from its row. Where a cloud can snapshot a volume (DigitalOcean) it is the forge's data volume, 10 GiB at $0.06 a GiB a month ($0.60); Hetzner cannot snapshot a volume, so its snapshot is the server's own disk, billed by its size at €0.0119 a GB a month, converted at the day's rate; the words say which. A cloud with no snapshots (OVHcloud here) keeps the plain End. |
src/actions/cloud_says.ts added +102
| @@ -0,0 +1,102 @@ | ||
| 1 | /** | |
| 2 | * What the cloud says (#17151 V2): the provider's own view of a pinned forge's or a game box's | |
| 3 | * machine, for /infra, /games/<box>, the terminal and the `infra` and `games` tools. Read with the | |
| 4 | * account's sealed key through the audited gate (`cloud/gate.ts`), GETs only, no new scope; kept | |
| 5 | * and worded by `cloud/provider_view.ts`. | |
| 6 | * | |
| 7 | * No page waits on a provider: a page draws the reading as kept, a stale one is read in the | |
| 8 | * background, and when that read says something new the page's live region draws again: the forge's | |
| 9 | * admins hear `infra.cloud` (/infra; `infra.*` is theirs in `core/event_audience.ts`), and each owner | |
| 10 | * of a game box on the machine who is not an admin hears `game.cloud` (/games/<box>), raised as | |
| 11 | * their own (`actor`), so nobody hears of a machine they may not see. Only a tool, asked once, | |
| 12 | * waits for a fresh reading, at most 1.5 s. | |
| 13 | */ | |
| 14 | ||
| 15 | import type { App } from "../app.ts"; | |
| 16 | import { gatedFetch } from "../cloud/gate.ts"; | |
| 17 | import { isProvider } from "../cloud/providers.ts"; | |
| 18 | import { READ_PROVIDERS, readMachine, saidFacts, saidLine, sayFor, sayKept, type ProviderView } from "../cloud/provider_view.ts"; | |
| 19 | import { secretNameOf } from "../core/cloud_account.ts"; | |
| 20 | import { getPinned, listPinned, type Pinned } from "../core/pinned.ts"; | |
| 21 | import { resolveSecrets } from "../core/secret_store.ts"; | |
| 22 | import { boxOwnersOfMachine } from "../games/store.ts"; | |
| 23 | import { net } from "./pinned.ts"; | |
| 24 | ||
| 25 | const PURPOSE = "infra:cloud-says"; | |
| 26 | /** The longest line a tool answers with. */ | |
| 27 | export const CLOUD_LINE_MAX = 400; | |
| 28 | /** The event a fresh reading that says something new raises for the admins: /infra's live region draws again. */ | |
| 29 | export const CLOUD_EVENT = "infra.cloud"; | |
| 30 | /** The same for each owner of a game box on the machine who is not an admin: /games/<box>'s live region. */ | |
| 31 | export const GAME_CLOUD_EVENT = "game.cloud"; | |
| 32 | ||
| 33 | /** Whether the forge can ask the provider about this row's machine. */ | |
| 34 | const readable = (row: Pinned): boolean => | |
| 35 | row.remote !== "" && (READ_PROVIDERS as readonly string[]).includes(row.target) && isProvider(row.target); | |
| 36 | ||
| 37 | const reader = (app: App, row: Pinned) => async (): Promise<ProviderView> => { | |
| 38 | if (!isProvider(row.target)) throw new Error(`${row.target} is not read here`); | |
| 39 | const secret = secretNameOf(row.target, row.account); | |
| 40 | const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { run: PURPOSE })[secret]; | |
| 41 | if (token === undefined) throw new Error(`the key of ${row.target}/${row.account} could not be opened`); | |
| 42 | return readMachine(row.target, gatedFetch(app.db, { provider: row.target, account: row.account }, PURPOSE, net.fetch), token, row.remote); | |
| 43 | }; | |
| 44 | ||
| 45 | const keyOf = (row: Pinned): string => `${row.id}:${row.remote}`; | |
| 46 | /** | |
| 47 | * A fresh reading said something new: the admins hear it, and each box-wide owner of a game box on | |
| 48 | * this machine who is not an admin hears it as their own event. The kinds are CLOUD_EVENT and GAME_CLOUD_EVENT, written | |
| 49 | * out so the event-audience scan reads them in place. | |
| 50 | */ | |
| 51 | const changed = (app: App, row: Pinned) => (): void => { | |
| 52 | app.bus.append({ kind: "infra.cloud", payload: { name: row.name } }); | |
| 53 | for (const o of boxOwnersOfMachine(app.db, row.id)) app.bus.append({ kind: "game.cloud", actorId: o.userId, payload: { box: o.box } }); | |
| 54 | }; | |
| 55 | ||
| 56 | /** The row's reading as kept, as a fact for a page's `dl` ({label: "DigitalOcean", value}); undefined when it has no machine to ask about. */ | |
| 57 | export function cloudFacts(app: App, row: Pinned, now = Date.now()): { label: string; value: string } | undefined { | |
| 58 | if (!readable(row)) return undefined; | |
| 59 | return saidFacts(sayKept(app, keyOf(row), reader(app, row), { changed: changed(app, row) }), row.target, now); | |
| 60 | } | |
| 61 | ||
| 62 | /** The same in one line, as kept: the terminal. */ | |
| 63 | export function cloudLine(app: App, row: Pinned, now = Date.now()): string | undefined { | |
| 64 | if (!readable(row)) return undefined; | |
| 65 | return saidLine(sayKept(app, keyOf(row), reader(app, row), { changed: changed(app, row) }), row.target, now); | |
| 66 | } | |
| 67 | ||
| 68 | /** One line for a tool, read fresh when stale and waited for at most 1.5 s, bounded to `CLOUD_LINE_MAX`. */ | |
| 69 | export async function cloudLineFresh(app: App, row: Pinned, now = Date.now()): Promise<string | undefined> { | |
| 70 | if (!readable(row)) return undefined; | |
| 71 | return saidLine(await sayFor(app, keyOf(row), reader(app, row), { changed: changed(app, row) }), row.target, now).slice( | |
| 72 | 0, | |
| 73 | CLOUD_LINE_MAX, | |
| 74 | ); | |
| 75 | } | |
| 76 | ||
| 77 | /** Each named row's fact as kept, by name: the /infra list and its live region. */ | |
| 78 | export function cloudFactsAll(app: App, names: readonly string[]): Map<string, { label: string; value: string }> { | |
| 79 | const out = new Map<string, { label: string; value: string }>(); | |
| 80 | for (const name of names) { | |
| 81 | const row = getPinned(app.db, name); | |
| 82 | const fact = row === undefined ? undefined : cloudFacts(app, row); | |
| 83 | if (fact !== undefined) out.set(name, fact); | |
| 84 | } | |
| 85 | return out; | |
| 86 | } | |
| 87 | ||
| 88 | /** Each named row's line for a tool, read side by side, each waited for at most 1.5 s. */ | |
| 89 | export async function cloudLinesFresh(app: App, names: readonly string[]): Promise<Record<string, string>> { | |
| 90 | const rows = names.map((n) => getPinned(app.db, n)).filter((r): r is Pinned => r !== undefined); | |
| 91 | const lines = await Promise.all(rows.map(async (r) => [r.name, await cloudLineFresh(app, r)] as const)); | |
| 92 | return Object.fromEntries(lines.filter((x): x is readonly [string, string] => x[1] !== undefined)); | |
| 93 | } | |
| 94 | ||
| 95 | /** | |
| 96 | * A game box's machine: the row its own `pinnedId` names, and nothing else. A box named like | |
| 97 | * another machine never reads that machine (#17156 review). | |
| 98 | */ | |
| 99 | export function pinnedOfBox(app: App, box: { pinnedId: string }): Pinned | undefined { | |
| 100 | if (box.pinnedId === "") return undefined; | |
| 101 | return listPinned(app.db).find((p) => p.id === box.pinnedId); | |
| 102 | } |
src/cloud/provider_view.ts added +364
| @@ -0,0 +1,364 @@ | ||
| 1 | /** | |
| 2 | * The cloud's own view of one machine (#17151 V2): what the provider says about a pinned forge's or | |
| 3 | * a game box's machine, read with the account's sealed key, never written. DigitalOcean | |
| 4 | * (`droplets/<id>`, its actions, its volumes) and Hetzner (`servers/<id>`, its actions, its | |
| 5 | * volumes): power, size, image, region, addresses, created time, the attached volumes and the five | |
| 6 | * latest actions. | |
| 7 | * | |
| 8 | * A reading is kept per row for `FRESH_MS` and read again when a page opens after that; a page | |
| 9 | * waits at most `WAIT_MS` for it and otherwise shows the last reading with its age. Everything a | |
| 10 | * provider says is cleaned to plain, bounded words before it is kept. | |
| 11 | */ | |
| 12 | ||
| 13 | import type { Fetch } from "./providers.ts"; | |
| 14 | ||
| 15 | /** A reading this young is answered without asking the provider again. */ | |
| 16 | export const FRESH_MS = 30_000; | |
| 17 | /** The longest a page waits for a reading before it shows the last one. */ | |
| 18 | export const WAIT_MS = 1_500; | |
| 19 | const ACTIONS = 5; | |
| 20 | const VOLUMES = 4; | |
| 21 | ||
| 22 | export const READ_PROVIDERS = ["digitalocean", "hetzner"] as const; | |
| 23 | const LABEL: Record<string, string> = { digitalocean: "DigitalOcean", hetzner: "Hetzner" }; | |
| 24 | ||
| 25 | export interface CloudAction { | |
| 26 | readonly type: string; | |
| 27 | readonly status: string; | |
| 28 | readonly startedAt: string; | |
| 29 | readonly completedAt: string; | |
| 30 | } | |
| 31 | ||
| 32 | export interface ProviderView { | |
| 33 | readonly provider: string; | |
| 34 | readonly id: string; | |
| 35 | readonly status: string; | |
| 36 | readonly vcpus: number; | |
| 37 | readonly memoryMiB: number; | |
| 38 | readonly image: string; | |
| 39 | readonly region: string; | |
| 40 | readonly ipv4Public: string; | |
| 41 | readonly ipv4Private: string; | |
| 42 | readonly createdAt: string; | |
| 43 | readonly volumes: readonly string[]; | |
| 44 | readonly actions: readonly CloudAction[]; | |
| 45 | } | |
| 46 | ||
| 47 | const clean = (v: unknown, max = 80): string => | |
| 48 | typeof v === "string" || typeof v === "number" | |
| 49 | ? String(v) | |
| 50 | .slice(0, max) | |
| 51 | .replace(/[^A-Za-z0-9 ._:/()+-]/g, "?") | |
| 52 | : ""; | |
| 53 | const count = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : 0); | |
| 54 | const obj = (v: unknown): Record<string, unknown> => (typeof v === "object" && v !== null ? (v as Record<string, unknown>) : {}); | |
| 55 | const list = (v: unknown): unknown[] => (Array.isArray(v) ? v : []); | |
| 56 | ||
| 57 | const newestFirst = (a: CloudAction, b: CloudAction): number => (b.startedAt < a.startedAt ? -1 : b.startedAt > a.startedAt ? 1 : 0); | |
| 58 | ||
| 59 | /** DigitalOcean's droplet, its actions and its volumes' answers, as one view. */ | |
| 60 | export function fromDigitalOcean(droplet: unknown, actions: unknown, volumes: readonly unknown[]): ProviderView { | |
| 61 | const d = obj(obj(droplet)["droplet"]); | |
| 62 | const v4 = list(obj(d["networks"])["v4"]).map(obj); | |
| 63 | const image = obj(d["image"]); | |
| 64 | const version = /\d+(\.\d+)?/.exec(clean(image["name"]))?.[0] ?? ""; | |
| 65 | return { | |
| 66 | provider: "digitalocean", | |
| 67 | id: clean(d["id"]), | |
| 68 | status: clean(d["status"]), | |
| 69 | vcpus: count(d["vcpus"]), | |
| 70 | memoryMiB: count(d["memory"]), | |
| 71 | image: [clean(image["distribution"]), version].filter(Boolean).join(" ") || clean(image["slug"]), | |
| 72 | region: clean(obj(d["region"])["slug"]), | |
| 73 | ipv4Public: clean(v4.find((n) => n["type"] === "public")?.["ip_address"]), | |
| 74 | ipv4Private: clean(v4.find((n) => n["type"] === "private")?.["ip_address"]), | |
| 75 | createdAt: clean(d["created_at"]), | |
| 76 | volumes: volumes | |
| 77 | .map((x) => clean(obj(obj(x)["volume"])["name"])) | |
| 78 | .filter(Boolean) | |
| 79 | .slice(0, VOLUMES), | |
| 80 | actions: list(obj(actions)["actions"]) | |
| 81 | .map(obj) | |
| 82 | .map((a) => ({ | |
| 83 | type: clean(a["type"]), | |
| 84 | status: clean(a["status"]), | |
| 85 | startedAt: clean(a["started_at"]), | |
| 86 | completedAt: clean(a["completed_at"]), | |
| 87 | })) | |
| 88 | .sort(newestFirst) | |
| 89 | .slice(0, ACTIONS), | |
| 90 | }; | |
| 91 | } | |
| 92 | ||
| 93 | /** Hetzner's server, its actions and its volumes' answers, as one view. */ | |
| 94 | export function fromHetzner(server: unknown, actions: unknown, volumes: readonly unknown[]): ProviderView { | |
| 95 | const s = obj(obj(server)["server"]); | |
| 96 | const type = obj(s["server_type"]); | |
| 97 | const dc = obj(s["datacenter"]); | |
| 98 | return { | |
| 99 | provider: "hetzner", | |
| 100 | id: clean(s["id"]), | |
| 101 | status: clean(s["status"]), | |
| 102 | vcpus: count(type["cores"]), | |
| 103 | memoryMiB: Math.round(count(type["memory"]) * 1024), | |
| 104 | image: clean(obj(s["image"])["description"]) || clean(obj(s["image"])["name"]), | |
| 105 | region: clean(obj(dc["location"])["name"]) || clean(dc["name"]), | |
| 106 | ipv4Public: clean(obj(obj(s["public_net"])["ipv4"])["ip"]), | |
| 107 | ipv4Private: clean(obj(list(s["private_net"])[0])["ip"]), | |
| 108 | createdAt: clean(s["created"]), | |
| 109 | volumes: volumes | |
| 110 | .map((x) => clean(obj(obj(x)["volume"])["name"])) | |
| 111 | .filter(Boolean) | |
| 112 | .slice(0, VOLUMES), | |
| 113 | actions: list(obj(actions)["actions"]) | |
| 114 | .map(obj) | |
| 115 | .map((a) => ({ | |
| 116 | type: clean(a["command"]), | |
| 117 | status: clean(a["status"]), | |
| 118 | startedAt: clean(a["started"]), | |
| 119 | completedAt: clean(a["finished"]), | |
| 120 | })) | |
| 121 | .sort(newestFirst) | |
| 122 | .slice(0, ACTIONS), | |
| 123 | }; | |
| 124 | } | |
| 125 | ||
| 126 | async function get(f: Fetch, token: string, url: string): Promise<unknown> { | |
| 127 | const res = await f(url, { headers: { authorization: `Bearer ${token}` } }); | |
| 128 | if (res.status === 404) throw new Error("it no longer exists there"); | |
| 129 | if (!res.ok) throw new Error(`it answered ${res.status}`); | |
| 130 | return res.json(); | |
| 131 | } | |
| 132 | ||
| 133 | /** Read one machine from its provider: GETs only. Throws with a plain reason when it cannot. */ | |
| 134 | export async function readMachine(provider: string, f: Fetch, token: string, id: string): Promise<ProviderView> { | |
| 135 | if (!/^[0-9a-z-]{1,64}$/i.test(id)) throw new Error("its id is not one the provider gives"); | |
| 136 | if (provider === "digitalocean") { | |
| 137 | const api = "https://api.digitalocean.com/v2"; | |
| 138 | const [droplet, actions] = await Promise.all([ | |
| 139 | get(f, token, `${api}/droplets/${id}`), | |
| 140 | get(f, token, `${api}/droplets/${id}/actions?per_page=${ACTIONS}`), | |
| 141 | ]); | |
| 142 | const ids = list(obj(obj(droplet)["droplet"])["volume_ids"]) | |
| 143 | .map((v) => clean(v)) | |
| 144 | .filter((v) => /^[0-9a-z-]{1,64}$/i.test(v)) | |
| 145 | .slice(0, VOLUMES); | |
| 146 | const volumes = await Promise.all(ids.map((v) => get(f, token, `${api}/volumes/${v}`).catch(() => ({ volume: { name: v } })))); | |
| 147 | return fromDigitalOcean(droplet, actions, volumes); | |
| 148 | } | |
| 149 | if (provider === "hetzner") { | |
| 150 | const api = "https://api.hetzner.cloud/v1"; | |
| 151 | const [server, actions] = await Promise.all([ | |
| 152 | get(f, token, `${api}/servers/${id}`), | |
| 153 | get(f, token, `${api}/servers/${id}/actions?sort=id:desc&per_page=${ACTIONS}`), | |
| 154 | ]); | |
| 155 | const ids = list(obj(obj(server)["server"])["volumes"]) | |
| 156 | .map((v) => clean(v)) | |
| 157 | .filter((v) => /^[0-9]{1,20}$/.test(v)) | |
| 158 | .slice(0, VOLUMES); | |
| 159 | const volumes = await Promise.all(ids.map((v) => get(f, token, `${api}/volumes/${v}`).catch(() => ({ volume: { name: v } })))); | |
| 160 | return fromHetzner(server, actions, volumes); | |
| 161 | } | |
| 162 | throw new Error(`${provider} is not read here`); | |
| 163 | } | |
| 164 | ||
| 165 | // ---- words ------------------------------------------------------------------------------------ | |
| 166 | ||
| 167 | const gb = (mib: number): string => { | |
| 168 | const g = mib / 1024; | |
| 169 | return Number.isInteger(g) ? String(g) : g.toFixed(1); | |
| 170 | }; | |
| 171 | ||
| 172 | /** "17:44" today (UTC), else "2026-11-30 17:44". */ | |
| 173 | export function clock(iso: string, now: number): string { | |
| 174 | const t = Date.parse(iso); | |
| 175 | if (!Number.isFinite(t)) return ""; | |
| 176 | const at = new Date(t).toISOString(); | |
| 177 | return at.slice(0, 10) === new Date(now).toISOString().slice(0, 10) ? at.slice(11, 16) : `${at.slice(0, 10)} ${at.slice(11, 16)}`; | |
| 178 | } | |
| 179 | ||
| 180 | /** How long ago, in words: "12 s", "3 min", "2 h". */ | |
| 181 | export function age(ms: number): string { | |
| 182 | const s = Math.max(0, Math.round(ms / 1000)); | |
| 183 | return s < 60 ? `${s} s` : s < 3600 ? `${Math.round(s / 60)} min` : `${Math.round(s / 3600)} h`; | |
| 184 | } | |
| 185 | ||
| 186 | /** What a machine's power state means, in plain words. */ | |
| 187 | const STATE: Record<string, string> = { | |
| 188 | active: "running", | |
| 189 | running: "running", | |
| 190 | new: "being created", | |
| 191 | initializing: "being created", | |
| 192 | starting: "starting", | |
| 193 | stopping: "stopping", | |
| 194 | off: "off", | |
| 195 | archive: "archived", | |
| 196 | deleting: "being deleted", | |
| 197 | rebuilding: "being rebuilt", | |
| 198 | migrating: "moving", | |
| 199 | }; | |
| 200 | ||
| 201 | /** What a finished action did, in plain words; an unknown one has its underscores spaced. */ | |
| 202 | const DONE: Record<string, string> = { | |
| 203 | create: "created", | |
| 204 | create_server: "created", | |
| 205 | power_on: "powered on", | |
| 206 | start_server: "powered on", | |
| 207 | power_off: "powered off", | |
| 208 | stop_server: "powered off", | |
| 209 | shutdown: "shut down", | |
| 210 | shutdown_server: "shut down", | |
| 211 | reboot: "rebooted", | |
| 212 | reboot_server: "rebooted", | |
| 213 | power_cycle: "power-cycled", | |
| 214 | reset_server: "reset", | |
| 215 | resize: "resized", | |
| 216 | change_type: "resized", | |
| 217 | rebuild: "rebuilt", | |
| 218 | rebuild_server: "rebuilt", | |
| 219 | snapshot: "snapshotted", | |
| 220 | create_image: "imaged", | |
| 221 | attach_volume: "had a volume attached", | |
| 222 | detach_volume: "had a volume detached", | |
| 223 | enable_backups: "had backups turned on", | |
| 224 | disable_backups: "had backups turned off", | |
| 225 | }; | |
| 226 | const spaced = (t: string): string => t.replace(/_/g, " "); | |
| 227 | ||
| 228 | const actionWords = (a: CloudAction, now: number): string => | |
| 229 | a.completedAt !== "" && /^(completed|success)$/.test(a.status) | |
| 230 | ? `${DONE[a.type] ?? spaced(a.type)} at ${clock(a.completedAt, now)}` | |
| 231 | : /^(in-progress|running)$/.test(a.status) | |
| 232 | ? `${spaced(a.type)} under way since ${clock(a.startedAt, now)}` | |
| 233 | : `${spaced(a.type)} ${a.status === "errored" || a.status === "error" ? "failed" : a.status}${a.completedAt === "" ? "" : ` at ${clock(a.completedAt, now)}`}`; | |
| 234 | ||
| 235 | /** The provider's name: "DigitalOcean". */ | |
| 236 | export const providerLabel = (provider: string): string => LABEL[provider] ?? provider; | |
| 237 | ||
| 238 | /** | |
| 239 | * What the provider says, after its name: "running · 4 vCPU 8 GB · Ubuntu 24.04 · nyc3 · | |
| 240 | * 104.236.196.18 · volume forge_mc attached · last powered on at 17:44". | |
| 241 | */ | |
| 242 | export function viewFacts(v: ProviderView, now: number): string { | |
| 243 | const parts = [ | |
| 244 | STATE[v.status] ?? (v.status || "in an unknown state"), | |
| 245 | v.vcpus > 0 ? `${v.vcpus} vCPU ${gb(v.memoryMiB)} GB` : "", | |
| 246 | v.image, | |
| 247 | v.region, | |
| 248 | v.ipv4Public === "" ? "no public address" : `${v.ipv4Public}${v.ipv4Private === "" ? "" : ` (private ${v.ipv4Private})`}`, | |
| 249 | v.volumes.length === 0 ? "no volume attached" : `${v.volumes.length === 1 ? "volume" : "volumes"} ${v.volumes.join(", ")} attached`, | |
| 250 | v.actions.length === 0 ? "" : `last ${actionWords(v.actions[0]!, now)}`, | |
| 251 | ]; | |
| 252 | return parts.filter(Boolean).join(" · "); | |
| 253 | } | |
| 254 | ||
| 255 | // ---- the kept reading ------------------------------------------------------------------------- | |
| 256 | ||
| 257 | export interface Said { | |
| 258 | /** The last good reading, and when it was read (ms). */ | |
| 259 | readonly view?: ProviderView; | |
| 260 | readonly readAt?: number; | |
| 261 | /** Why the latest read failed, when it did. */ | |
| 262 | readonly error?: string; | |
| 263 | } | |
| 264 | ||
| 265 | interface Entry { | |
| 266 | view?: ProviderView; | |
| 267 | readAt?: number; | |
| 268 | error?: string; | |
| 269 | /** When the latest attempt ended, success or not: the clock `FRESH_MS` runs on. */ | |
| 270 | triedAt: number; | |
| 271 | pending?: Promise<void>; | |
| 272 | } | |
| 273 | ||
| 274 | const KEPT = new WeakMap<object, Map<string, Entry>>(); | |
| 275 | ||
| 276 | const entryOf = (owner: object, key: string): Entry => { | |
| 277 | let rows = KEPT.get(owner); | |
| 278 | if (rows === undefined) KEPT.set(owner, (rows = new Map())); | |
| 279 | let e = rows.get(key); | |
| 280 | if (e === undefined) rows.set(key, (e = { triedAt: 0 })); | |
| 281 | return e; | |
| 282 | }; | |
| 283 | ||
| 284 | const said = (e: Entry): Said => ({ | |
| 285 | ...(e.view === undefined ? {} : { view: e.view, readAt: e.readAt! }), | |
| 286 | ...(e.error === undefined ? {} : { error: e.error }), | |
| 287 | }); | |
| 288 | ||
| 289 | /** What a reading says, without when: whether a fresh read changed anything. */ | |
| 290 | const gist = (e: Entry): string => JSON.stringify([e.view ?? null, e.error ?? null]); | |
| 291 | ||
| 292 | /** | |
| 293 | * Start a read unless one is running or the last attempt is younger than `FRESH_MS`; `changed` | |
| 294 | * hears when the read said something new (a page that showed the old reading draws again). | |
| 295 | */ | |
| 296 | function refresh(e: Entry, read: () => Promise<ProviderView>, now: () => number, changed?: () => void): Promise<void> | undefined { | |
| 297 | if (e.pending !== undefined) return e.pending; | |
| 298 | if (now() - e.triedAt < FRESH_MS) return undefined; | |
| 299 | const before = gist(e); | |
| 300 | e.pending = read() | |
| 301 | .then( | |
| 302 | (v) => { | |
| 303 | e.view = v; | |
| 304 | e.readAt = now(); | |
| 305 | delete e.error; | |
| 306 | }, | |
| 307 | (err: unknown) => { | |
| 308 | e.error = err instanceof Error ? clean(err.message, 160) : "the read failed"; | |
| 309 | }, | |
| 310 | ) | |
| 311 | .finally(() => { | |
| 312 | e.triedAt = now(); | |
| 313 | delete e.pending; | |
| 314 | if (changed !== undefined && gist(e) !== before) changed(); | |
| 315 | }); | |
| 316 | return e.pending; | |
| 317 | } | |
| 318 | ||
| 319 | /** | |
| 320 | * The reading of one row (`owner` is the app; `key` the row), read again when older than | |
| 321 | * `FRESH_MS`, waiting at most `waitMs` for it; past that, the last reading as it is. | |
| 322 | */ | |
| 323 | export async function sayFor( | |
| 324 | owner: object, | |
| 325 | key: string, | |
| 326 | read: () => Promise<ProviderView>, | |
| 327 | o: { waitMs?: number; now?: () => number; changed?: () => void } = {}, | |
| 328 | ): Promise<Said> { | |
| 329 | const now = o.now ?? Date.now; | |
| 330 | const e = entryOf(owner, key); | |
| 331 | const going = refresh(e, read, now, o.changed); | |
| 332 | if (going !== undefined) { | |
| 333 | let timer: ReturnType<typeof setTimeout> | undefined; | |
| 334 | await Promise.race([going, new Promise<void>((done) => (timer = setTimeout(done, o.waitMs ?? WAIT_MS)))]); | |
| 335 | clearTimeout(timer); | |
| 336 | } | |
| 337 | return said(e); | |
| 338 | } | |
| 339 | ||
| 340 | /** | |
| 341 | * The reading as kept, never waiting (every page and the terminal): a stale one starts a read, and | |
| 342 | * `changed` hears when it says something new. | |
| 343 | */ | |
| 344 | export function sayKept(owner: object, key: string, read: () => Promise<ProviderView>, o: { now?: () => number; changed?: () => void } = {}): Said { | |
| 345 | const e = entryOf(owner, key); | |
| 346 | void refresh(e, read, o.now ?? Date.now, o.changed); | |
| 347 | return said(e); | |
| 348 | } | |
| 349 | ||
| 350 | /** A reading as a fact: the provider's name, and what it says with its age once older than `FRESH_MS`, or why there is none. */ | |
| 351 | export function saidFacts(s: Said, provider: string, now: number): { label: string; value: string } { | |
| 352 | const label = providerLabel(provider); | |
| 353 | if (s.view === undefined) return { label, value: s.error === undefined ? "reading…" : `could not be read: ${s.error}` }; | |
| 354 | const old = now - s.readAt!; | |
| 355 | const facts = viewFacts(s.view, now); | |
| 356 | if (s.error !== undefined) return { label, value: `${facts} (read ${age(old)} ago; the latest read failed: ${s.error})` }; | |
| 357 | return { label, value: old > FRESH_MS ? `${facts} (read ${age(old)} ago)` : facts }; | |
| 358 | } | |
| 359 | ||
| 360 | /** The same in one line for a tool or the terminal: "DigitalOcean: running · …". */ | |
| 361 | export const saidLine = (s: Said, provider: string, now: number): string => { | |
| 362 | const f = saidFacts(s, provider, now); | |
| 363 | return `${f.label}: ${f.value}`; | |
| 364 | }; |
src/core/event_audience.ts +4 −1
| @@ -423,7 +423,10 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 423 | 423 | // A conversation's own plan changed (`keep_plan` from Talk): the person's alone. |
| 424 | 424 | kind === "conversation.plan" || |
| 425 | 425 | // A person's own dev cell changed state (`apps/dev_cell.ts`): theirs alone. |
| 426 | kind === "dev.state" | |
| 426 | kind === "dev.state" || | |
| 427 | // A fresh reading of a game box's machine, raised for each of the box's owners who is not an | |
| 428 | // admin (admins hear `infra.cloud`): one owner's alone (`actions/cloud_says.ts`). | |
| 429 | kind === "game.cloud" | |
| 427 | 430 | ) |
| 428 | 431 | return "actor"; |
| 429 | 432 | // A run's summary, an app's serving state and its pictures can carry the |
src/games/store.ts +10
| @@ -213,6 +213,16 @@ export function roleOn(db: Database, user: User | undefined, boxId: string, serv | ||
| 213 | 213 | } |
| 214 | 214 | export const mayDo = (role: Role | undefined, need: Role): boolean => role !== undefined && RANK[role] >= RANK[need]; |
| 215 | 215 | |
| 216 | /** The box-wide owners, not forge admins, of each game box on the machine `pinnedId` names. */ | |
| 217 | export const boxOwnersOfMachine = (db: Database, pinnedId: string): { userId: string; box: string }[] => | |
| 218 | db | |
| 219 | .query<{ user_id: string; name: string }, [string]>( | |
| 220 | `SELECT DISTINCT g.user_id, b.name FROM game_grant g JOIN game_box b ON b.id = g.box_id JOIN user u ON u.id = g.user_id | |
| 221 | WHERE b.pinned_id = ?1 AND g.role = 'owner' AND g.service = '' AND u.is_admin = 0`, | |
| 222 | ) | |
| 223 | .all(pinnedId) | |
| 224 | .map((r) => ({ userId: r.user_id, box: r.name })); | |
| 225 | ||
| 216 | 226 | /** Whether `user` sees a box at all: any grant on it (box-wide or one service), or forge admin. */ |
| 217 | 227 | export function seesBox(db: Database, user: User | undefined, boxId: string): boolean { |
| 218 | 228 | if (user === undefined) return false; |
src/http/infra_routes.ts +6 −2
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | * `actions/infra.ts` (or `actions/pinned.ts` for Keep and End now) the terminal, API and MCP call. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { cloudFactsAll } from "../actions/cloud_says.ts"; | |
| 7 | 8 | import { infraCode } from "../cloud/infra_read.ts"; |
| 8 | 9 | import { buildOf, machineOf, projectsView, providerConsole, readProjectsNow, type ComposeChoices, composeChoices, domainOf, infraOf, nameFor, planCompose, planRecord, rebuild, recordAccounts, startBuild } from "../actions/infra.ts"; |
| 9 | 10 | import { dropRecord } from "../actions/dns_record.ts"; |
| @@ -69,7 +70,9 @@ async function render( | ||
| 69 | 70 | } |
| 70 | 71 | const code = await infraCode(ctx.app, user); |
| 71 | 72 | const projects = timePhase(ctx.request, "projects", () => projectsView(ctx.app, user)); |
| 72 | const body = infraPage(view.value, compose, build, { composing: o.composing, code: code.ok ? code.value : [], records: recordForm(recordAccounts(ctx.app)), projects: projects.ok ? projects.value : [] }); | |
| 73 | // What each provider says, as kept: no page waits on a provider; a fresh reading redraws the live region. | |
| 74 | const cloud = cloudFactsAll(ctx.app, view.value.groups.flatMap((g) => g.machines.map((m) => m.name))); | |
| 75 | const body = infraPage(view.value, compose, build, { composing: o.composing, code: code.ok ? code.value : [], records: recordForm(recordAccounts(ctx.app)), projects: projects.ok ? projects.value : [], cloud }); | |
| 73 | 76 | return page({ ctx, title: "Infrastructure", scriptJs: SCRIPT, styleCss: INFRA_CSS, body, ...(o.flash ? { flash: o.flash } : {}) }, status); |
| 74 | 77 | } |
| 75 | 78 | |
| @@ -101,7 +104,8 @@ function infraLive(ctx: Ctx): Response { | ||
| 101 | 104 | return fragment(placesRegion(composeChoices(ctx.app), (ctx.url.searchParams.get("where") ?? "").slice(0, 260), q), { request: ctx.request }); |
| 102 | 105 | } |
| 103 | 106 | const view = infraOf(ctx.app, ctx.auth.user); |
| 104 | return view.ok ? fragment(runningRegion(view.value), { request: ctx.request }) : fragment(html``, { status: 404 }); | |
| 107 | if (!view.ok) return fragment(html``, { status: 404 }); | |
| 108 | return fragment(runningRegion(view.value, cloudFactsAll(ctx.app, view.value.groups.flatMap((g) => g.machines.map((m) => m.name)))), { request: ctx.request }); | |
| 105 | 109 | } |
| 106 | 110 | |
| 107 | 111 | // POST /infra/plan: the tray for what the form says now (a fragment for the page's script), or the |
src/http/mcp/tools/games.ts +23 −14
| @@ -1,3 +1,4 @@ | ||
| 1 | import { cloudLineFresh, pinnedOfBox } from "../../../actions/cloud_says.ts"; | |
| 1 | 2 | import { addPlugin, pluginSays, commitServiceEnv } from "../../../games/compose.ts"; |
| 2 | 3 | import { boxStatus, boxStatusShared } from "../../../games/diag.ts"; |
| 3 | 4 | import { commitSettings, previewSettings, serviceSettings } from "../../../games/settings.ts"; |
| @@ -33,22 +34,30 @@ export const tool: Tool = { | ||
| 33 | 34 | async run(ctx, user, args) { |
| 34 | 35 | const action = str(args["action"]); |
| 35 | 36 | const db = ctx.app.db; |
| 36 | if (action === "list") | |
| 37 | if (action === "list") { | |
| 38 | const boxes = listBoxes(db).filter((b) => seesBox(db, user, b.id)); | |
| 39 | // The cloud's own view of each box's machine, for its owners; one bounded line each. | |
| 40 | const cloud = await Promise.all( | |
| 41 | boxes.map(async (b) => { | |
| 42 | const row = roleOn(db, user, b.id, "") === "owner" ? pinnedOfBox(ctx.app, b) : undefined; | |
| 43 | return row === undefined ? undefined : await cloudLineFresh(ctx.app, row); | |
| 44 | }), | |
| 45 | ); | |
| 37 | 46 | return good({ |
| 38 | items: listBoxes(db) | |
| 39 | .filter((b) => seesBox(db, user, b.id)) | |
| 40 | .map((b) => ({ | |
| 41 | name: b.name, | |
| 42 | place: b.place, | |
| 43 | monthlyCents: b.monthlyCents, | |
| 44 | seenAt: b.seenAt, | |
| 45 | host: b.host, | |
| 46 | // The box's state in words, at most three lines: the owner's own, anyone else's naming | |
| 47 | // no container, image, error or journal. | |
| 48 | status: (mayDo(roleOn(db, user, b.id), "owner") ? boxStatus(b.diag) : boxStatusShared(b.diag)).slice(0, 3), | |
| 49 | services: servicesOf(db, b.id).filter((s) => mayDo(roleOn(db, user, b.id, s.name), "viewer")), | |
| 50 | })), | |
| 47 | items: boxes.map((b, i) => ({ | |
| 48 | name: b.name, | |
| 49 | place: b.place, | |
| 50 | monthlyCents: b.monthlyCents, | |
| 51 | seenAt: b.seenAt, | |
| 52 | host: b.host, | |
| 53 | // The box's state in words, at most three lines: the owner's own, anyone else's naming | |
| 54 | // no container, image, error or journal. | |
| 55 | status: (mayDo(roleOn(db, user, b.id), "owner") ? boxStatus(b.diag) : boxStatusShared(b.diag)).slice(0, 3), | |
| 56 | ...(cloud[i] === undefined ? {} : { cloud: cloud[i] }), | |
| 57 | services: servicesOf(db, b.id).filter((s) => mayDo(roleOn(db, user, b.id, s.name), "viewer")), | |
| 58 | })), | |
| 51 | 59 | }); |
| 60 | } | |
| 52 | 61 | const box = boxNamed(db, str(args["box"])); |
| 53 | 62 | const service = str(args["service"]); |
| 54 | 63 | if (box === undefined || !seesBox(db, user, box.id) || !SERVICE_NAME.test(service)) return bad("not_found", "no such box or service here"); |
src/http/mcp/tools/infra.ts +6 −2
| @@ -1,3 +1,4 @@ | ||
| 1 | import { cloudLinesFresh } from "../../../actions/cloud_says.ts"; | |
| 1 | 2 | import { infraCode } from "../../../cloud/infra_read.ts"; |
| 2 | 3 | import { projectsOf, projectsSays } from "../../../cloud/projects.ts"; |
| 3 | 4 | import { buildOf, firewallWant, gameWant, planDatabase, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts"; |
| @@ -66,7 +67,8 @@ export const tool: Tool = { | ||
| 66 | 67 | }; |
| 67 | 68 | }), |
| 68 | 69 | }; |
| 69 | return good({ says: infraSays(v.value), ...experiments, ...rest, projects }); | |
| 70 | const cloud = await cloudLinesFresh(ctx.app, v.value.groups.flatMap((g) => g.machines.map((m) => m.name))); | |
| 71 | return good({ says: infraSays(v.value), ...experiments, ...rest, projects, cloud }); | |
| 70 | 72 | } |
| 71 | 73 | if (action === "check") { |
| 72 | 74 | // Compare the DNS records the forge made with Cloudflare now, as the hourly watch does. |
| @@ -92,7 +94,9 @@ export const tool: Tool = { | ||
| 92 | 94 | // A machine by name, running or ended, with its billing sentence; never "no such experiment" for one. |
| 93 | 95 | const m = machineOf(ctx.app, user, id); |
| 94 | 96 | if (!m.ok) return bad("not_found", "no such tool here"); |
| 95 | return m.value !== undefined ? good({ machine: m.value, says: `${m.value.name} is ${m.value.billing}.` }) : bad("not_found", `${goneWords(ctx.app, id)}.`); | |
| 97 | if (m.value === undefined) return bad("not_found", `${goneWords(ctx.app, id)}.`); | |
| 98 | const cloud = (await cloudLinesFresh(ctx.app, [m.value.name]))[m.value.name]; | |
| 99 | return good({ machine: m.value, says: `${m.value.name} is ${m.value.billing}.`, ...(cloud === undefined ? {} : { cloud }) }); | |
| 96 | 100 | } |
| 97 | 101 | if (action === "plan" && args["want"] === undefined && names.length > 0) { |
| 98 | 102 | // Dead rows to clear (failed, nothing at their provider): a plan like any other, applied by id. |
src/http/sse.ts +3 −2
| @@ -290,8 +290,9 @@ export function viewerStream( | ||
| 290 | 290 | }, gone.signal); |
| 291 | 291 | const unsubscribe = app.bus.subscribe((event: ForgeEvent) => { |
| 292 | 292 | // A repo-less event reaches a page only when one listens for it; the audience filter below |
| 293 | // keeps the admins' (`infra.*` and `pinned.*`: what runs on the owner's cloud, #16696) theirs. | |
| 294 | if (event.repoId === null ? !(event.kind.startsWith("backup.") || event.kind.startsWith("infra.") || event.kind.startsWith("pinned.") || event.kind === "cloud.place_pinned" || (viewer !== undefined && event.kind.startsWith("desk."))) : !visible(event.repoId)) return; | |
| 293 | // keeps the admins' (`infra.*` and `pinned.*`: what runs on the owner's cloud, #16696) theirs, | |
| 294 | // and `game.cloud` its one box owner's. | |
| 295 | if (event.repoId === null ? !(event.kind.startsWith("backup.") || event.kind.startsWith("infra.") || event.kind === "game.cloud" || event.kind.startsWith("pinned.") || event.kind === "cloud.place_pinned" || (viewer !== undefined && event.kind.startsWith("desk."))) : !visible(event.repoId)) return; | |
| 295 | 296 | if (!meant(event)) return; |
| 296 | 297 | send(event); |
| 297 | 298 | }, "ordered"); |
src/tui/screens/games.ts +11 −1
| @@ -17,6 +17,7 @@ import { commitPolicy, policyOf, stateWords } from "../../games/sleep.ts"; | ||
| 17 | 17 | import { SHELL_SERVICE, queueShell } from "../../games/shell.ts"; |
| 18 | 18 | import { onSync } from "../../games/notify.ts"; |
| 19 | 19 | import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts"; |
| 20 | import { cloudLine, pinnedOfBox } from "../../actions/cloud_says.ts"; | |
| 20 | 21 | import { getUserByName } from "../../core/users.ts"; |
| 21 | 22 | import { addPlugin, commitServiceEnv, pluginSays, pluginsOf, readCompose, serviceEnv } from "../../games/compose.ts"; |
| 22 | 23 | import { commitSettings, planSettings, settingsOf, type SettingsPlan, type SettingValue } from "../../games/settings.ts"; |
| @@ -50,6 +51,14 @@ import type { PaletteEntry } from "./entries.ts"; | ||
| 50 | 51 | export function gamesScreen(f: Session, ctx: Ctx): Screen { |
| 51 | 52 | const state = new ListState(); |
| 52 | 53 | let note = ""; |
| 54 | /** What each box's provider says of its machine, as kept, one row a box the person owns. */ | |
| 55 | const machines = (): ListRow[] => | |
| 56 | listBoxes(f.app.db).flatMap((b) => { | |
| 57 | if (roleOn(f.app.db, f.user, b.id, "") !== "owner") return []; | |
| 58 | const row = pinnedOfBox(f.app, b); | |
| 59 | const line = row === undefined ? undefined : cloudLine(f.app, row); | |
| 60 | return line === undefined ? [] : [{ title: `${b.name}'s machine`, secondary: line, meta: "" }]; | |
| 61 | }); | |
| 53 | 62 | const rows = () => |
| 54 | 63 | listBoxes(f.app.db) |
| 55 | 64 | .filter((b) => seesBox(f.app.db, f.user, b.id)) |
| @@ -94,7 +103,8 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 94 | 103 | secondary: `${stateWords(service.state, service.asleep)} · ${Math.round(service.memMiB)} MiB · ${service.cpuPct.toFixed(1)}% CPU`, |
| 95 | 104 | meta: box.seenAt.slice(11, 19), |
| 96 | 105 | })); |
| 97 | drawList(s, list!, c, state, view); | |
| 106 | // The machines after the services: the cursor moves over the services only. | |
| 107 | drawList(s, list!, c, state, [...view, ...machines()]); | |
| 98 | 108 | }, |
| 99 | 109 | key(e) { |
| 100 | 110 | const all = rows(); |
src/tui/screens/infra.ts +10
| @@ -20,6 +20,8 @@ import { planMinecraft } from "../../actions/minecraft.ts"; | ||
| 20 | 20 | import { LIFETIME_DAYS, clearPinned, endsWords, keepPinned, retirePinned, retireWords } from "../../actions/pinned.ts"; |
| 21 | 21 | import type { SnapshotView } from "../../actions/infra_snapshot.ts"; |
| 22 | 22 | import { dollars } from "../../cloud/prices.ts"; |
| 23 | import { cloudLine } from "../../actions/cloud_says.ts"; | |
| 24 | import { getPinned } from "../../core/pinned.ts"; | |
| 23 | 25 | import type { Ctx, Screen } from "../app/app.ts"; |
| 24 | 26 | import { binding } from "../app/keys.ts"; |
| 25 | 27 | import { style } from "../term/style.ts"; |
| @@ -419,6 +421,14 @@ export function infraScreen(f: Session, ctx: Ctx): Screen { | ||
| 419 | 421 | ), |
| 420 | 422 | // A managed database: where it is, what it costs, and whether its app has the URL. |
| 421 | 423 | ...v.value.databases.map((d) => ({ title: `${d.name} · ${month(d.monthlyCents)}`, secondary: `database · ${d.app} · ${d.where} · ${d.says}`, meta: d.account })), |
| 424 | // The provider's own view, as kept (a stale one is read for next time): one row a machine that has one. | |
| 425 | ...v.value.groups.flatMap((g) => | |
| 426 | g.machines.flatMap((m) => { | |
| 427 | const row = getPinned(f.app.db, m.name); | |
| 428 | const line = row === undefined ? undefined : cloudLine(f.app, row); | |
| 429 | return line === undefined ? [] : [{ title: `${m.name}, as its provider says`, secondary: line, meta: "" }]; | |
| 430 | }), | |
| 431 | ), | |
| 422 | 432 | // What ended: each retired machine says what it still bills, a kept disk or nothing left. |
| 423 | 433 | ...v.value.ended.map((m) => ({ title: `ended: ${m.name} · ${month(m.monthlyCents)}`, secondary: `${m.name} is ${m.billing}`, meta: m.account })), |
| 424 | 434 | // DNS records, last: what each says, and what Cloudflare no longer agrees with. |
src/web/pages/games.ts +7
| @@ -48,6 +48,7 @@ import { flashTo, page } from "../layout.ts"; | ||
| 48 | 48 | import { badge, btn, disclosure, field as input, row, rowList, time } from "../ui.ts"; |
| 49 | 49 | import { onSync } from "../../games/notify.ts"; |
| 50 | 50 | import { canSleep, commitPolicy, EMPTY_SECONDS, policyOf, stateWords } from "../../games/sleep.ts"; |
| 51 | import { CLOUD_EVENT, cloudFacts, GAME_CLOUD_EVENT, pinnedOfBox } from "../../actions/cloud_says.ts"; | |
| 51 | 52 | import { emptyLine } from "../empty_words.ts"; |
| 52 | 53 | |
| 53 | 54 | const dollars = (cents: number): string => `$${(cents / 100).toFixed(2)}`; |
| @@ -119,6 +120,9 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 119 | 120 | const names = [...new Set([...seen.map((s) => s.name), ...(compose === undefined ? [] : composeServices(compose.text))])].sort(); |
| 120 | 121 | const user = ctx.auth.user!; |
| 121 | 122 | const visible = names.filter((n) => mayDo(roleOn(ctx.app.db, user, box.id, n), "viewer")); |
| 123 | // What the provider says of the box's machine, for its owners only, as kept: the page never waits on it. | |
| 124 | const machine = role === "owner" ? pinnedOfBox(ctx.app, box) : undefined; | |
| 125 | const cloud = machine === undefined ? undefined : cloudFacts(ctx.app, machine); | |
| 122 | 126 | return timePhase(ctx.request, "render", () => page({ |
| 123 | 127 | ctx, |
| 124 | 128 | title: `Games · ${box.name}`, |
| @@ -127,6 +131,9 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 127 | 131 | body: html`${pageHead(box.name, { |
| 128 | 132 | sub: `${box.repo}@${box.branch}:${box.path}${box.composeSha === "" ? "" : ` · running ${box.composeSha.slice(0, 10)}`}`, |
| 129 | 133 | })} |
| 134 | ${cloud === undefined | |
| 135 | ? null | |
| 136 | : html`<div id="game-machine" data-live="${CLOUD_EVENT},${GAME_CLOUD_EVENT}">${rowList([row({ title: "Its machine", facts: [cloud] })])}</div>`} | |
| 130 | 137 | ${visible.length === 0 |
| 131 | 138 | ? emptyLine("gameServices") |
| 132 | 139 | : rowList( |
src/web/pages/infra.ts +11 −6
| @@ -161,9 +161,11 @@ const machineActions = (r: Running): Html => | ||
| 161 | 161 | </form>`} |
| 162 | 162 | </div>`; |
| 163 | 163 | |
| 164 | function machineRow(r: Running): Html { | |
| 164 | function machineRow(r: Running, cloud: { label: string; value: string } | undefined): Html { | |
| 165 | 165 | const ends = r.endsAt === null ? "No end" : `Ends ${r.ends}`; |
| 166 | 166 | return row({ |
| 167 | // What its provider says of it, as a fact: "DigitalOcean — running · 4 vCPU 8 GB · …". | |
| 168 | ...(cloud === undefined ? {} : { facts: [cloud] }), | |
| 167 | 169 | id: `machine-${r.name}`, |
| 168 | 170 | title: html`<span class="mono">${r.name}</span>`, |
| 169 | 171 | meta: r.clear !== "" |
| @@ -175,8 +177,11 @@ function machineRow(r: Running): Html { | ||
| 175 | 177 | }); |
| 176 | 178 | } |
| 177 | 179 | |
| 178 | /** The running list, grouped by purpose; the region the page swaps on `pinned.*` and `infra.*`. */ | |
| 179 | export function runningRegion(v: InfraView): Html { | |
| 180 | /** | |
| 181 | * The running list, grouped by purpose; the region the page swaps on `pinned.*` and `infra.*`. | |
| 182 | * `cloud` is what each machine's provider says of it, by name (`actions/cloud_says.ts`). | |
| 183 | */ | |
| 184 | export function runningRegion(v: InfraView, cloud: ReadonlyMap<string, { label: string; value: string }> = new Map()): Html { | |
| 180 | 185 | return html`<div id="infra-running" data-live="pinned.*,infra.*" data-live-src="/infra/live?part=running"> |
| 181 | 186 | ${meters(v)} |
| 182 | 187 | ${v.drift.map((d) => html`<p data-drift>${icon("alert")} <a href="${d.href}">${d.says}</a></p>`)} |
| @@ -186,7 +191,7 @@ export function runningRegion(v: InfraView): Html { | ||
| 186 | 191 | (g) => |
| 187 | 192 | html`<section class="settings-block" data-purpose="${g.kind}"> |
| 188 | 193 | <h2>${g.title}</h2> |
| 189 | ${rowList(g.machines.map(machineRow))} | |
| 194 | ${rowList(g.machines.map((m) => machineRow(m, cloud.get(m.name))))} | |
| 190 | 195 | </section>`, |
| 191 | 196 | )} |
| 192 | 197 | ${v.records.length === 0 |
| @@ -591,12 +596,12 @@ export function infraPage( | ||
| 591 | 596 | v: InfraView, |
| 592 | 597 | compose: Html, |
| 593 | 598 | build: Build | undefined, |
| 594 | s: { composing: boolean; records?: Html; code?: readonly CodeFile[]; projects?: readonly ProjectView[] }, | |
| 599 | s: { composing: boolean; records?: Html; code?: readonly CodeFile[]; projects?: readonly ProjectView[]; cloud?: ReadonlyMap<string, { label: string; value: string }> }, | |
| 595 | 600 | ): Html { |
| 596 | 601 | const open = s.composing || v.groups.length === 0; |
| 597 | 602 | return html`${pageHead("Infrastructure", { sub: "What runs on your own cloud, what it's for, what it costs, and when it ends." })} |
| 598 | 603 | <div data-infra> |
| 599 | ${runningRegion(v)} | |
| 604 | ${runningRegion(v, s.cloud)} | |
| 600 | 605 | ${projectsRegion(s.projects ?? [])} |
| 601 | 606 | ${codeRegion(s.code ?? [])} |
| 602 | 607 | ${build !== undefined |
test/cloud-says-doors.test.ts added +285
| @@ -0,0 +1,285 @@ | ||
| 1 | /** | |
| 2 | * What the cloud says, on every door (#17151 V2, #17156 review): /infra shows each machine's | |
| 3 | * provider facts to an admin and nothing to anyone else, and neither it nor its live region waits on | |
| 4 | * a slow provider; a fresh reading raises `infra.cloud` for each admin and `game.cloud` for each | |
| 5 | * non-admin owner of a box on the machine, so the live regions draw again; a game box's | |
| 6 | * page and the `games` tool show its machine to the box's owners only, and only the machine its own | |
| 7 | * row names (a box named after another machine reads nothing of it); the `infra` tool's list and | |
| 8 | * show carry the line; and both terminal screens show one line a machine, one a box. | |
| 9 | */ | |
| 10 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 11 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 12 | import { tmpdir } from "node:os"; | |
| 13 | import { join } from "node:path"; | |
| 14 | import { createApp, type App } from "../src/app.ts"; | |
| 15 | import { addAccount, net as cloudNet } from "../src/actions/cloud.ts"; | |
| 16 | import { CLOUD_EVENT, cloudLineFresh, pinnedOfBox } from "../src/actions/cloud_says.ts"; | |
| 17 | import { net } from "../src/actions/pinned.ts"; | |
| 18 | import { listEvents } from "../src/core/events.ts"; | |
| 19 | import { getPinned, insertPinned, setRemote } from "../src/core/pinned.ts"; | |
| 20 | import { createSession } from "../src/core/sessions.ts"; | |
| 21 | import { createToken } from "../src/core/tokens.ts"; | |
| 22 | import { createUser, type User } from "../src/core/users.ts"; | |
| 23 | import { boxNamed, createGameBox, grant } from "../src/games/store.ts"; | |
| 24 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 25 | import { viewerStream } from "../src/http/sse.ts"; | |
| 26 | import { gamesScreen } from "../src/tui/screens/games.ts"; | |
| 27 | import { infraScreen } from "../src/tui/screens/infra.ts"; | |
| 28 | import { quietCtx, screenText, sessionFor } from "./helpers/tui-text.ts"; | |
| 29 | import { quietLogs } from "./helpers/globals.ts"; | |
| 30 | import { pollUntil } from "./helpers/poll.ts"; | |
| 31 | ||
| 32 | quietLogs(); | |
| 33 | ||
| 34 | const KEY = "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"; | |
| 35 | const DROPLET = (id: number, ip: string) => ({ | |
| 36 | droplet: { | |
| 37 | id, | |
| 38 | status: "active", | |
| 39 | vcpus: 4, | |
| 40 | memory: 8192, | |
| 41 | created_at: "2026-12-01T17:42:10Z", | |
| 42 | image: { name: "24.04 (LTS) x64", distribution: "Ubuntu" }, | |
| 43 | region: { slug: "nyc1" }, | |
| 44 | networks: { v4: [{ ip_address: ip, type: "public" }] }, | |
| 45 | volume_ids: [], | |
| 46 | }, | |
| 47 | }); | |
| 48 | const ACTIONS = { | |
| 49 | actions: [{ type: "power_on", status: "completed", started_at: "2026-12-01T17:43:00Z", completed_at: "2026-12-01T17:43:20Z" }], | |
| 50 | }; | |
| 51 | /** Each machine's own droplet, by id; a request for one in `hang` never answers. */ | |
| 52 | const answer = | |
| 53 | (hang: ReadonlySet<string>) => | |
| 54 | async (url: string): Promise<Response> => { | |
| 55 | const id = /droplets\/(\d+)/.exec(url)?.[1] ?? ""; | |
| 56 | if (hang.has(id)) return new Promise<Response>(() => {}); | |
| 57 | return Response.json(url.includes("/actions") ? ACTIONS : DROPLET(Number(id), id === "111" ? "104.236.196.18" : "203.0.113.9")); | |
| 58 | }; | |
| 59 | ||
| 60 | let dataDir = ""; | |
| 61 | let app: App; | |
| 62 | let http: ForgeHttp; | |
| 63 | let ada: User; | |
| 64 | let bob: User; | |
| 65 | const saved = net.fetch; | |
| 66 | const cookieOf = (u: User): string => `forge_session=${createSession(app.db, u.id).token}`; | |
| 67 | const get = (path: string, u?: User) => | |
| 68 | http.handle(new Request(`http://forge.test${path}`, { headers: u === undefined ? {} : { cookie: cookieOf(u) } })); | |
| 69 | const machine = (name: string, remote: string) => { | |
| 70 | insertPinned( | |
| 71 | app.db, | |
| 72 | { | |
| 73 | name, | |
| 74 | target: "digitalocean", | |
| 75 | account: "main", | |
| 76 | app: "", | |
| 77 | source: "", | |
| 78 | version: "", | |
| 79 | config: {}, | |
| 80 | host: "", | |
| 81 | claimHash: "", | |
| 82 | claimExpires: "", | |
| 83 | datacenter: "nyc1", | |
| 84 | size: "s-4vcpu-8gb", | |
| 85 | }, | |
| 86 | ada.id, | |
| 87 | ); | |
| 88 | setRemote(app.db, name, { remote, state: "running" }); | |
| 89 | return getPinned(app.db, name)!; | |
| 90 | }; | |
| 91 | const tool = async (u: User, name: string, args: Record<string, unknown>): Promise<{ text: string; value: any }> => { | |
| 92 | const res = await http.handle( | |
| 93 | new Request("http://forge.test/mcp", { | |
| 94 | method: "POST", | |
| 95 | headers: { | |
| 96 | "content-type": "application/json", | |
| 97 | accept: "application/json, text/event-stream", | |
| 98 | authorization: `Bearer ${createToken(app.db, u.id, "t", u.isAdmin ? "admin" : "rw").token}`, | |
| 99 | }, | |
| 100 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }), | |
| 101 | }), | |
| 102 | ); | |
| 103 | const body = (await res.json()) as any; | |
| 104 | const text: string = body.result?.content?.[0]?.text ?? JSON.stringify(body.error ?? body); | |
| 105 | let value: any; | |
| 106 | try { | |
| 107 | value = JSON.parse(text); | |
| 108 | } catch { | |
| 109 | value = undefined; | |
| 110 | } | |
| 111 | return { text, value }; | |
| 112 | }; | |
| 113 | ||
| 114 | beforeAll(async () => { | |
| 115 | dataDir = await mkdtemp(join(tmpdir(), "forge-cloud-says-doors-")); | |
| 116 | app = createApp({ dataDir, port: 0 }); | |
| 117 | http = forgeHttp(app); | |
| 118 | const a = await createUser(app.db, { | |
| 119 | username: "ada", | |
| 120 | email: "[email protected]", | |
| 121 | password: "a-good-passphrase", | |
| 122 | origin: "seed", | |
| 123 | isAdmin: true, | |
| 124 | trusted: true, | |
| 125 | }); | |
| 126 | const b = await createUser(app.db, { | |
| 127 | username: "bob", | |
| 128 | email: "[email protected]", | |
| 129 | password: "a-good-passphrase", | |
| 130 | origin: "seed", | |
| 131 | trusted: true, | |
| 132 | }); | |
| 133 | if (!a.ok || !b.ok) throw new Error("users"); | |
| 134 | [ada, bob] = [a.value, b.value]; | |
| 135 | cloudNet.fetch = async () => Response.json({ account: { email: "[email protected]", status: "active" } }); | |
| 136 | const acct = await addAccount(app, ada, "digitalocean", "main", KEY); | |
| 137 | if (!acct.ok) throw new Error(String(acct.error)); | |
| 138 | net.fetch = answer(new Set()); | |
| 139 | // The game box's own machine, and an admin's forge that no game box owns. | |
| 140 | const mc = machine("mc", "111"); | |
| 141 | machine("ledger", "222"); | |
| 142 | createGameBox(app.db, { name: "net", pinnedId: mc.id }); | |
| 143 | // Bob's box, named after the admin's machine, with no machine of its own. | |
| 144 | const spy = createGameBox(app.db, { name: "ledger" }); | |
| 145 | grant(app.db, spy.id, bob.id, "owner"); | |
| 146 | grant(app.db, boxNamed(app.db, "net")!.id, bob.id, "viewer"); | |
| 147 | // Warm both readings, as a first page open would start them. | |
| 148 | for (const n of ["mc", "ledger"]) await cloudLineFresh(app, getPinned(app.db, n)!); | |
| 149 | }, 30_000); | |
| 150 | ||
| 151 | afterAll(async () => { | |
| 152 | net.fetch = saved; | |
| 153 | app.close(); | |
| 154 | await rm(dataDir, { recursive: true, force: true }); | |
| 155 | }); | |
| 156 | ||
| 157 | describe("/infra", () => { | |
| 158 | test("an admin sees each machine's provider facts in a dl row, in plain words; anyone else sees nothing of it", async () => { | |
| 159 | const page = await (await get("/infra", ada)).text(); | |
| 160 | expect(page).toContain("<dt>DigitalOcean</dt>"); | |
| 161 | // The action's day shows once it is not today's. | |
| 162 | expect(page).toMatch(/running · 4 vCPU 8 GB · Ubuntu 24\.04 · nyc1 · 104\.236\.196\.18 · no volume attached · last powered on at (2026-12-01 )?17:43/); | |
| 163 | expect(page).not.toContain("Cloud says"); | |
| 164 | expect(page).not.toContain("power_on"); | |
| 165 | const other = await get("/infra", bob); | |
| 166 | expect([403, 404]).toContain(other.status); | |
| 167 | expect(await other.text()).not.toContain("104.236.196.18"); | |
| 168 | const live = await get("/infra/live?part=running", bob); | |
| 169 | // The route mark answers a non-admin first (403); the handler itself would 404. | |
| 170 | expect([403, 404]).toContain(live.status); | |
| 171 | expect(await live.text()).not.toContain("104.236.196.18"); | |
| 172 | }); | |
| 173 | ||
| 174 | test("a slow provider holds neither the page nor its live region; the fresh reading raises infra.cloud", async () => { | |
| 175 | const hang = new Set(["333"]); | |
| 176 | net.fetch = answer(hang); | |
| 177 | machine("slow1", "333"); | |
| 178 | for (const path of ["/infra", "/infra/live?part=running"]) { | |
| 179 | const started = performance.now(); | |
| 180 | const text = await (await get(path, ada)).text(); | |
| 181 | expect(performance.now() - started, path).toBeLessThan(1_000); | |
| 182 | expect(text, path).toContain("reading…"); | |
| 183 | } | |
| 184 | // A machine whose read answers raises the event once it is in. | |
| 185 | const before = listEvents(app.db, { kind: CLOUD_EVENT }).length; | |
| 186 | machine("quick1", "444"); | |
| 187 | await get("/infra/live?part=running", ada); | |
| 188 | // The page started the read and did not wait; a tool read joins that same read, which raises the event as it settles. | |
| 189 | await cloudLineFresh(app, getPinned(app.db, "quick1")!); | |
| 190 | expect(listEvents(app.db, { kind: CLOUD_EVENT }).length).toBeGreaterThan(before); | |
| 191 | net.fetch = answer(new Set()); | |
| 192 | }); | |
| 193 | ||
| 194 | test("the infra tool's list and show carry each machine's line", async () => { | |
| 195 | const list = await tool(ada, "infra", { action: "list" }); | |
| 196 | expect(list.value.cloud["mc"]).toStartWith("DigitalOcean: running · 4 vCPU 8 GB"); | |
| 197 | const show = await tool(ada, "infra", { action: "show", id: "mc" }); | |
| 198 | expect(show.value.cloud).toStartWith("DigitalOcean: running"); | |
| 199 | expect(show.value.cloud.length).toBeLessThanOrEqual(400); | |
| 200 | }); | |
| 201 | }); | |
| 202 | ||
| 203 | describe("a game box", () => { | |
| 204 | test("a box reads only the machine its own row names: one named after another machine reads nothing", () => { | |
| 205 | expect(pinnedOfBox(app, boxNamed(app.db, "ledger")!)).toBeUndefined(); | |
| 206 | expect(pinnedOfBox(app, boxNamed(app.db, "net")!)?.name).toBe("mc"); | |
| 207 | }); | |
| 208 | ||
| 209 | test("its owner sees the machine on the page; a viewer, a guest and the owner of a box named after another machine see none", async () => { | |
| 210 | const owner = await (await get("/games/net", ada)).text(); | |
| 211 | expect(owner).toContain('data-live="infra.cloud,game.cloud"'); | |
| 212 | expect(owner).toContain("<dt>DigitalOcean</dt>"); | |
| 213 | expect(owner).toContain("104.236.196.18"); | |
| 214 | const viewer = await (await get("/games/net", bob)).text(); | |
| 215 | expect(viewer).not.toContain("104.236.196.18"); | |
| 216 | expect(viewer).not.toContain("<dt>DigitalOcean</dt>"); | |
| 217 | expect(await (await get("/games/net")).text()).not.toContain("104.236.196.18"); | |
| 218 | const spy = await get("/games/ledger", bob); | |
| 219 | expect(spy.status).toBe(200); | |
| 220 | const text = await spy.text(); | |
| 221 | expect(text).not.toContain("203.0.113.9"); | |
| 222 | expect(text).not.toContain("<dt>DigitalOcean</dt>"); | |
| 223 | }); | |
| 224 | ||
| 225 | test("a fresh reading reaches a non-admin owner's /events as game.cloud, and not a viewer's or another box's owner", async () => { | |
| 226 | const carol = await createUser(app.db, { username: "carol", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true }); | |
| 227 | if (!carol.ok) throw new Error("carol"); | |
| 228 | const fresh = machine("fresh1", "555"); | |
| 229 | const box = createGameBox(app.db, { name: "fresh", pinnedId: fresh.id }); | |
| 230 | grant(app.db, box.id, carol.value.id, "owner"); | |
| 231 | grant(app.db, box.id, bob.id, "viewer"); | |
| 232 | const listen = (u: User) => { | |
| 233 | const reader = viewerStream(app, u, new Request("http://forge.test/events")).body!.getReader(); | |
| 234 | const state = { text: "" }; | |
| 235 | const decoder = new TextDecoder(); | |
| 236 | const reading = (async () => { | |
| 237 | for (;;) { | |
| 238 | const { value, done } = await reader.read(); | |
| 239 | if (done) return; | |
| 240 | state.text += decoder.decode(value); | |
| 241 | } | |
| 242 | })(); | |
| 243 | return { state, close: async () => (await reader.cancel(), await reading.catch(() => undefined)) }; | |
| 244 | }; | |
| 245 | const carolHears = listen(carol.value); | |
| 246 | const bobHears = listen(bob); | |
| 247 | await pollUntil(() => carolHears.state.text.includes(": connected") && bobHears.state.text.includes(": connected"), "both streams connected", 2000); | |
| 248 | // The owner's page listens for it, and starts the read without waiting; the tool's read joins it, | |
| 249 | // and the reading is new. | |
| 250 | expect(await (await get("/games/fresh", carol.value)).text()).toContain('data-live="infra.cloud,game.cloud"'); | |
| 251 | await cloudLineFresh(app, getPinned(app.db, "fresh1")!); | |
| 252 | // One append reaches every stream it is for, so once the owner has it, any leak to the viewer is | |
| 253 | // already in the viewer's stream too. | |
| 254 | await pollUntil(() => carolHears.state.text.includes('"kind":"game.cloud"'), "the owner's game.cloud", 2000); | |
| 255 | expect(carolHears.state.text).toContain('"kind":"game.cloud"'); | |
| 256 | expect(carolHears.state.text).toContain('"box":"fresh"'); | |
| 257 | expect(carolHears.state.text).not.toContain('"kind":"infra.cloud"'); | |
| 258 | expect(bobHears.state.text).not.toContain("game.cloud"); | |
| 259 | expect(bobHears.state.text).not.toContain("infra.cloud"); | |
| 260 | await carolHears.close(); | |
| 261 | await bobHears.close(); | |
| 262 | }); | |
| 263 | ||
| 264 | test("the games tool gives its owner the line, and nobody else", async () => { | |
| 265 | const owner = await tool(ada, "games", { action: "list" }); | |
| 266 | expect(owner.value.items.find((b: { name: string }) => b.name === "net").cloud).toStartWith("DigitalOcean: running"); | |
| 267 | expect(owner.value.items.find((b: { name: string }) => b.name === "ledger").cloud).toBeUndefined(); | |
| 268 | const other = await tool(bob, "games", { action: "list" }); | |
| 269 | expect(other.text).not.toContain("104.236.196.18"); | |
| 270 | expect(other.text).not.toContain("203.0.113.9"); | |
| 271 | }); | |
| 272 | }); | |
| 273 | ||
| 274 | describe("the terminal", () => { | |
| 275 | test("Infra shows one line a machine; Games one line a box its person owns", () => { | |
| 276 | const infra = screenText(infraScreen(sessionFor(app, ada), quietCtx()), 200, 60); | |
| 277 | expect(infra).toContain("mc, as its provider says"); | |
| 278 | expect(infra).toContain("ledger, as its provider says"); | |
| 279 | const games = screenText(gamesScreen(sessionFor(app, ada), quietCtx()), 200, 40); | |
| 280 | expect(games).toContain("net's machine"); | |
| 281 | expect(games).toContain("DigitalOcean: running · 4 vCPU 8 GB"); | |
| 282 | expect(screenText(gamesScreen(sessionFor(app, bob), quietCtx()), 200, 40)).not.toContain("DigitalOcean"); | |
| 283 | }); | |
| 284 | }); | |
| 285 |
test/provider-view.test.ts added +293
| @@ -0,0 +1,293 @@ | ||
| 1 | /** | |
| 2 | * "Cloud says" (#17151 V2): the provider's own view of a machine. Recorded DigitalOcean and Hetzner | |
| 3 | * answers become one plain line; the reading is kept 30 s, a slow provider never holds a caller | |
| 4 | * past its wait (the last reading shows with its age), a failed read keeps the last good one, and | |
| 5 | * every answer is bounded however much the provider says. End to end: a pinned row's line on | |
| 6 | * /infra and in the `infra` tool, read with the account's sealed key, GETs only. | |
| 7 | */ | |
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { addAccount, net as cloudNet } from "../src/actions/cloud.ts"; | |
| 14 | import { CLOUD_LINE_MAX, cloudLineFresh } from "../src/actions/cloud_says.ts"; | |
| 15 | import { net } from "../src/actions/pinned.ts"; | |
| 16 | import { | |
| 17 | FRESH_MS, | |
| 18 | fromDigitalOcean, | |
| 19 | fromHetzner, | |
| 20 | readMachine, | |
| 21 | saidFacts, | |
| 22 | saidLine, | |
| 23 | sayFor, | |
| 24 | viewFacts, | |
| 25 | type ProviderView, | |
| 26 | } from "../src/cloud/provider_view.ts"; | |
| 27 | import { getPinned, insertPinned, setRemote } from "../src/core/pinned.ts"; | |
| 28 | import { createUser, type User } from "../src/core/users.ts"; | |
| 29 | ||
| 30 | const NOW = Date.parse("2026-12-01T18:00:00Z"); | |
| 31 | /** The account's key as sealed: a made-up value of DigitalOcean's shape. */ | |
| 32 | const KEY = "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"; | |
| 33 | ||
| 34 | // Recorded shapes (ids, addresses and names changed): GET /v2/droplets/<id>, its actions, a volume. | |
| 35 | const DO_DROPLET = { | |
| 36 | droplet: { | |
| 37 | id: 512345678, | |
| 38 | name: "forge-mc", | |
| 39 | memory: 8192, | |
| 40 | vcpus: 4, | |
| 41 | disk: 160, | |
| 42 | status: "active", | |
| 43 | created_at: "2026-12-01T17:42:10Z", | |
| 44 | image: { id: 1, name: "24.04 (LTS) x64", distribution: "Ubuntu", slug: "ubuntu-24-04-x64" }, | |
| 45 | size_slug: "s-4vcpu-8gb", | |
| 46 | region: { name: "New York 1", slug: "nyc1" }, | |
| 47 | networks: { | |
| 48 | v4: [ | |
| 49 | { ip_address: "10.116.0.4", netmask: "255.255.240.0", gateway: "", type: "private" }, | |
| 50 | { ip_address: "104.236.196.18", netmask: "255.255.192.0", gateway: "104.236.192.1", type: "public" }, | |
| 51 | ], | |
| 52 | v6: [], | |
| 53 | }, | |
| 54 | volume_ids: ["3d80cb72-342b-4aaa-b92e-4e4abb24a933"], | |
| 55 | }, | |
| 56 | }; | |
| 57 | const DO_ACTIONS = { | |
| 58 | actions: [ | |
| 59 | { | |
| 60 | id: 2, | |
| 61 | status: "completed", | |
| 62 | type: "power_on", | |
| 63 | started_at: "2026-12-01T17:43:00Z", | |
| 64 | completed_at: "2026-12-01T17:43:20Z", | |
| 65 | resource_id: 512345678, | |
| 66 | }, | |
| 67 | { | |
| 68 | id: 3, | |
| 69 | status: "completed", | |
| 70 | type: "create", | |
| 71 | started_at: "2026-12-01T17:42:10Z", | |
| 72 | completed_at: "2026-12-01T17:44:05Z", | |
| 73 | resource_id: 512345678, | |
| 74 | }, | |
| 75 | ], | |
| 76 | meta: { total: 2 }, | |
| 77 | }; | |
| 78 | const DO_VOLUME = { volume: { id: "3d80cb72-342b-4aaa-b92e-4e4abb24a933", name: "forge_mc", size_gigabytes: 50 } }; | |
| 79 | ||
| 80 | // GET /v1/servers/<id>, its actions (sort=id:desc), a volume. | |
| 81 | const HZ_SERVER = { | |
| 82 | server: { | |
| 83 | id: 4242, | |
| 84 | name: "forge-relay", | |
| 85 | status: "running", | |
| 86 | created: "2026-11-30T09:15:00+00:00", | |
| 87 | server_type: { name: "cx22", cores: 2, memory: 4.0, disk: 40 }, | |
| 88 | image: { name: "ubuntu-24.04", description: "Ubuntu 24.04", os_flavor: "ubuntu" }, | |
| 89 | datacenter: { name: "fsn1-dc14", location: { name: "fsn1", city: "Falkenstein" } }, | |
| 90 | public_net: { ipv4: { ip: "49.12.0.7" }, ipv6: { ip: "2a01:4f8::/64" } }, | |
| 91 | private_net: [], | |
| 92 | volumes: [99], | |
| 93 | }, | |
| 94 | }; | |
| 95 | const HZ_ACTIONS = { | |
| 96 | actions: [{ id: 77, command: "start_server", status: "running", progress: 40, started: "2026-12-01T17:58:00+00:00", finished: null }], | |
| 97 | }; | |
| 98 | const HZ_VOLUME = { volume: { id: 99, name: "forge-relay-data", size: 10 } }; | |
| 99 | ||
| 100 | describe("the provider's words", () => { | |
| 101 | test("DigitalOcean: a droplet, its newest action, its volume, in plain words", () => { | |
| 102 | const v = fromDigitalOcean(DO_DROPLET, DO_ACTIONS, [DO_VOLUME]); | |
| 103 | expect(v.actions[0]!.type).toBe("power_on"); | |
| 104 | expect(viewFacts(v, NOW)).toBe( | |
| 105 | "running · 4 vCPU 8 GB · Ubuntu 24.04 · nyc1 · 104.236.196.18 (private 10.116.0.4) · volume forge_mc attached · last powered on at 17:43", | |
| 106 | ); | |
| 107 | }); | |
| 108 | ||
| 109 | test("Hetzner: a server, a running action, a volume", () => { | |
| 110 | const v = fromHetzner(HZ_SERVER, HZ_ACTIONS, [HZ_VOLUME]); | |
| 111 | expect(viewFacts(v, NOW)).toBe( | |
| 112 | "running · 2 vCPU 4 GB · Ubuntu 24.04 · fsn1 · 49.12.0.7 · volume forge-relay-data attached · last start server under way since 17:58", | |
| 113 | ); | |
| 114 | }); | |
| 115 | ||
| 116 | test("an action of another day names its date; nothing known is said plainly", () => { | |
| 117 | const v = fromDigitalOcean({ droplet: { ...DO_DROPLET.droplet, networks: { v4: [] }, volume_ids: [] } }, DO_ACTIONS, []); | |
| 118 | expect(viewFacts(v, Date.parse("2026-12-03T08:00:00Z"))).toContain( | |
| 119 | "no public address · no volume attached · last powered on at 2026-12-01 17:43", | |
| 120 | ); | |
| 121 | }); | |
| 122 | ||
| 123 | test("reads are GETs with the key in a header, never in the URL", async () => { | |
| 124 | const asked: string[] = []; | |
| 125 | const f = async (url: string, init?: RequestInit): Promise<Response> => { | |
| 126 | expect(init?.method ?? "GET").toBe("GET"); | |
| 127 | expect(new Headers(init?.headers).get("authorization")).toBe("Bearer dop_v1_secret"); | |
| 128 | asked.push(url); | |
| 129 | const body = url.includes("/actions") ? DO_ACTIONS : url.includes("/volumes/") ? DO_VOLUME : DO_DROPLET; | |
| 130 | return Response.json(body); | |
| 131 | }; | |
| 132 | const v = await readMachine("digitalocean", f, "dop_v1_secret", "512345678"); | |
| 133 | expect(v.volumes).toEqual(["forge_mc"]); | |
| 134 | expect(asked.sort()).toEqual([ | |
| 135 | "https://api.digitalocean.com/v2/droplets/512345678", | |
| 136 | "https://api.digitalocean.com/v2/droplets/512345678/actions?per_page=5", | |
| 137 | "https://api.digitalocean.com/v2/volumes/3d80cb72-342b-4aaa-b92e-4e4abb24a933", | |
| 138 | ]); | |
| 139 | expect(asked.some((u) => u.includes("secret"))).toBe(false); | |
| 140 | const hz = async (url: string): Promise<Response> => | |
| 141 | Response.json(url.includes("/actions") ? HZ_ACTIONS : url.includes("/volumes/") ? HZ_VOLUME : HZ_SERVER); | |
| 142 | expect((await readMachine("hetzner", hz, "t", "4242")).region).toBe("fsn1"); | |
| 143 | await expect(readMachine("digitalocean", async () => new Response("", { status: 404 }), "t", "1")).rejects.toThrow( | |
| 144 | "it no longer exists there", | |
| 145 | ); | |
| 146 | await expect(readMachine("digitalocean", f, "t", "../account")).rejects.toThrow("its id is not one the provider gives"); | |
| 147 | }); | |
| 148 | ||
| 149 | test("however much a provider says, the line stays bounded", () => { | |
| 150 | const long = "x".repeat(5_000); | |
| 151 | const v = fromDigitalOcean( | |
| 152 | { droplet: { ...DO_DROPLET.droplet, status: long, image: { distribution: long, name: long } } }, | |
| 153 | { | |
| 154 | actions: Array.from({ length: 500 }, (_, i) => ({ | |
| 155 | type: long, | |
| 156 | status: "completed", | |
| 157 | started_at: `2026-12-01T17:${String(i % 60).padStart(2, "0")}:00Z`, | |
| 158 | completed_at: "2026-12-01T17:59:00Z", | |
| 159 | })), | |
| 160 | }, | |
| 161 | Array.from({ length: 50 }, () => ({ volume: { name: long } })), | |
| 162 | ); | |
| 163 | expect(v.actions.length).toBe(5); | |
| 164 | expect(v.volumes.length).toBe(4); | |
| 165 | expect(viewFacts(v, NOW).length).toBeLessThan(800); | |
| 166 | }); | |
| 167 | }); | |
| 168 | ||
| 169 | describe("the kept reading", () => { | |
| 170 | const view = fromDigitalOcean(DO_DROPLET, DO_ACTIONS, [DO_VOLUME]); | |
| 171 | ||
| 172 | test("read once within 30 s, again after", async () => { | |
| 173 | const owner = {}; | |
| 174 | let clock = NOW; | |
| 175 | let reads = 0; | |
| 176 | const read = async (): Promise<ProviderView> => (reads++, view); | |
| 177 | await sayFor(owner, "row", read, { now: () => clock }); | |
| 178 | await sayFor(owner, "row", read, { now: () => clock }); | |
| 179 | expect(reads).toBe(1); | |
| 180 | clock += FRESH_MS + 1; | |
| 181 | const s = await sayFor(owner, "row", read, { now: () => clock }); | |
| 182 | expect(reads).toBe(2); | |
| 183 | expect(saidFacts(s, "digitalocean", clock)).toEqual({ label: "DigitalOcean", value: viewFacts(view, clock) }); | |
| 184 | }); | |
| 185 | ||
| 186 | test("a slow provider never holds the page: the last reading shows with its age", async () => { | |
| 187 | const owner = {}; | |
| 188 | let clock = NOW; | |
| 189 | await sayFor(owner, "row", async () => view, { now: () => clock }); | |
| 190 | clock += 3 * 60_000; | |
| 191 | let finish: (v: ProviderView) => void = () => {}; | |
| 192 | const slow = (): Promise<ProviderView> => new Promise((done) => (finish = done)); | |
| 193 | const started = performance.now(); | |
| 194 | const s = await sayFor(owner, "row", slow, { now: () => clock, waitMs: 50 }); | |
| 195 | expect(performance.now() - started).toBeLessThan(1_000); | |
| 196 | expect(saidFacts(s, "digitalocean", clock).value).toEndWith("(read 3 min ago)"); | |
| 197 | finish(view); | |
| 198 | // A first read that is slow says it is reading, not a guess. | |
| 199 | const first = await sayFor({}, "row", slow, { waitMs: 20 }); | |
| 200 | expect(saidLine(first, "hetzner", NOW)).toBe("Hetzner: reading…"); | |
| 201 | }); | |
| 202 | ||
| 203 | test("a failed read keeps the last good one and says it failed", async () => { | |
| 204 | const owner = {}; | |
| 205 | let clock = NOW; | |
| 206 | await sayFor(owner, "row", async () => view, { now: () => clock }); | |
| 207 | clock += FRESH_MS + 1; | |
| 208 | const s = await sayFor(owner, "row", async () => Promise.reject(new Error("it answered 503")), { now: () => clock }); | |
| 209 | expect(saidFacts(s, "digitalocean", clock).value).toContain("(read 30 s ago; the latest read failed: it answered 503)"); | |
| 210 | const none = await sayFor({}, "row", async () => Promise.reject(new Error("it answered 401"))); | |
| 211 | expect(saidLine(none, "digitalocean", NOW)).toBe("DigitalOcean: could not be read: it answered 401"); | |
| 212 | }); | |
| 213 | }); | |
| 214 | ||
| 215 | describe("a pinned row's machine, end to end", () => { | |
| 216 | let dataDir = ""; | |
| 217 | let app: App; | |
| 218 | let admin: User; | |
| 219 | const saved = net.fetch; | |
| 220 | beforeAll(async () => { | |
| 221 | dataDir = await mkdtemp(join(tmpdir(), "forge-provider-view-")); | |
| 222 | app = createApp({ dataDir, port: 0 }); | |
| 223 | const u = await createUser(app.db, { | |
| 224 | username: "ada", | |
| 225 | email: "[email protected]", | |
| 226 | password: "a-good-passphrase", | |
| 227 | origin: "seed", | |
| 228 | isAdmin: true, | |
| 229 | trusted: true, | |
| 230 | }); | |
| 231 | if (!u.ok) throw new Error(u.error); | |
| 232 | admin = u.value; | |
| 233 | cloudNet.fetch = async () => Response.json({ account: { email: "[email protected]", status: "active" } }); | |
| 234 | const a = await addAccount(app, admin, "digitalocean", "main", KEY); | |
| 235 | if (!a.ok) throw new Error(String(a.error)); | |
| 236 | insertPinned( | |
| 237 | app.db, | |
| 238 | { | |
| 239 | name: "mc", | |
| 240 | target: "digitalocean", | |
| 241 | account: "main", | |
| 242 | app: "", | |
| 243 | source: "", | |
| 244 | version: "", | |
| 245 | config: {}, | |
| 246 | host: "", | |
| 247 | claimHash: "", | |
| 248 | claimExpires: "", | |
| 249 | datacenter: "nyc1", | |
| 250 | size: "s-4vcpu-8gb", | |
| 251 | }, | |
| 252 | admin.id, | |
| 253 | ); | |
| 254 | setRemote(app.db, "mc", { remote: "512345678", state: "running" }); | |
| 255 | }, 30_000); | |
| 256 | afterAll(async () => { | |
| 257 | net.fetch = saved; | |
| 258 | app.close(); | |
| 259 | await rm(dataDir, { recursive: true, force: true }); | |
| 260 | }); | |
| 261 | ||
| 262 | test("the sealed key reads it; the line is bounded for a tool", async () => { | |
| 263 | const keys: string[] = []; | |
| 264 | net.fetch = async (url, init) => { | |
| 265 | keys.push(new Headers(init?.headers).get("authorization") ?? ""); | |
| 266 | return Response.json(url.includes("/actions") ? DO_ACTIONS : url.includes("/volumes/") ? DO_VOLUME : DO_DROPLET); | |
| 267 | }; | |
| 268 | const line = await cloudLineFresh(app, getPinned(app.db, "mc")!, NOW); | |
| 269 | expect(line).toStartWith("DigitalOcean: running · 4 vCPU 8 GB · Ubuntu 24.04"); | |
| 270 | expect(keys.every((k) => k === `Bearer ${KEY}`)).toBe(true); | |
| 271 | expect(line!.length).toBeLessThanOrEqual(CLOUD_LINE_MAX); | |
| 272 | // A row with no machine yet has nothing to ask about. | |
| 273 | insertPinned( | |
| 274 | app.db, | |
| 275 | { | |
| 276 | name: "new1", | |
| 277 | target: "digitalocean", | |
| 278 | account: "main", | |
| 279 | app: "", | |
| 280 | source: "", | |
| 281 | version: "", | |
| 282 | config: {}, | |
| 283 | host: "", | |
| 284 | claimHash: "", | |
| 285 | claimExpires: "", | |
| 286 | datacenter: "nyc1", | |
| 287 | size: "s-1vcpu-2gb", | |
| 288 | }, | |
| 289 | admin.id, | |
| 290 | ); | |
| 291 | expect(await cloudLineFresh(app, getPinned(app.db, "new1")!)).toBeUndefined(); | |
| 292 | }); | |
| 293 | }); |
test/timers-named.test.ts +1
| @@ -118,6 +118,7 @@ const ALLOWED: readonly Allowed[] = [ | ||
| 118 | 118 | ...allow("setTimeout", "retries removing one emptied cgroup directory: one rmdir", [["src/apps/cgroup.ts", "() => removeDir(dir"]]), |
| 119 | 119 | ...allow("setTimeout", SLEEP, [ |
| 120 | 120 | ["src/kernel/breathe.ts", "done"], |
| 121 | ["src/cloud/provider_view.ts", "done"], | |
| 121 | 122 | ["src/core/v1_proof.ts", "done"], |
| 122 | 123 | ["src/maintenance/checks.ts", "done"], |
| 123 | 124 | ["src/chaos/faults.ts", "r"], |
new above
offline
HIGH: falling back to the row named like the box lets a non-admin box owner read another user's machine (IPs, volumes, actions) by choosing a box name. Resolve only through
pinnedId, or check the row's owner, and test it.