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

A project's page is a table of its apps with state and ports, merged logs and its compose file, with Start all, Stop all and Update #18639

opened this

Merged 32m ago, live in production

scout/forge:scout/18603-a-project-s-page-is-a-table-of-its-apps → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/18603-a-project-s-page-is-a-table-of-its-apps was merged into main as 6cf4a8b.

Review

Sign in to review this change.
13 files changed +461 −5
docs/features/infra.md +1
@@ -116,6 +116,7 @@ Every DigitalOcean and Hetzner account is read into provider ▸ account ▸ pro
116116 - **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.
117117 - **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. A box whose agent update was put back to the one before (docs/features/games.md, the agent's trial) says so there too: its row reads "On its old agent:" and the agent's own reason, in the terminal's Infra the same words after the row's place, and in the `infra` tool's list as the machine's `agentBack`; a box whose agent is fine has no such field. A machine's pane lists its containers as one table, on the page and in the terminal alike (`CONTAINER_COLUMNS`, `containerCell`): name (a link to the container), state, CPU limit, memory limit and started, as an ago. A value not known, or no limit set, is an em dash, never 0.
118118 - **Logs.** A game box's container has a Logs tab with the same live reader and console as its service's page on `/games/<box>/<service>`. For an operator of the box, Restart (Start while it is not running) sits beside the container's name, and Stop is a tap further, under More, as on the games page. Each is a form posting, same origin, to `/infra/container/<box>/<container>/<restart|stop|start>`. That asks the box as `/games/<box>/<container>/power` does, and returns to the container (`src/web/pages/container_power.ts`). The games page keeps its own route and posts to it, since it returns to the games page. In the terminal the same request is `s`, `x` and `r` on the container's row in `src/tui/screens/games.ts`. A held box shows the start buttons disabled and says so. Someone with no role on the box is told so (`containerConsole` in `src/web/pages/games.ts`). The container's CPU, memory and uptime are on its Facts tab.
119 - **A project.** A game box's compose project has its own page, `/infra/project/<box>`: `docs/features/project.md`.
119120 - **A machine by name.** `/infra/<machine>` opens the machine in the tree, where its containers are listed. A machine the cloud has not been read for opens the tree's top.
120121 - **File.** A machine has two tabs, Facts and File (`?tab=file`; `[` and `]` in the terminal); a container has a third, Logs (`?tab=logs`): on the page, for someone with a role on its box, the live reader below; otherwise, in the terminal and in the `infra` tool, its newest 200 lines as its box last synced them (nothing is fetched from the box; control characters are dropped, the page escapes the rest), or a sentence saying none were synced and when the box last did. The `infra` tool returns the same lines as `logs` for a container. Only an admin sees the tree. File says which lines of which file declare the thing, links to them, and says whether that agrees with what the forge knows (`src/cloud/declared_in.ts`, `declared_read.ts`). Two kinds of file are read: an app's `infra.json`, against the forge's own record of the machine (the cloud is not asked), and a game box's compose file, against the commit the box last said it runs. When the branch is at another commit the tab says so, since its lines may not be what runs; a silent box is "not known". Of a service it shows the image, ports, volumes and the names of its environment, never a value. A thing in neither file is "in no file the forge reads", one that is part of a stack is "not known", and one in a repository the reader may not read is "in a file you cannot read", with nothing of it shown. The join goes through the forge's own rows and never by a resource's name. On the branch that is followed, the file's own page says to a forge admin "Declares 3: …" with a link to each node; to anyone else it is as before. Nothing is written.
121122 - **Keys.** j and k move, Enter opens, h and l (or the arrows) close and open, `/` filters and Enter goes to the first match.
docs/features/project.md added +26
@@ -0,0 +1,26 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: A project's page is a table of its apps with merged logs, its compose file, Start all, Stop all and Update (#18603)
4 ---
5 # A project's page (#18603)
6
7 A game box's compose project opens at `/infra/project/<box>`, from "Open its project" above a
8 machine's containers on Infrastructure.
9
10 - **Apps.** One table row per service: its state, always a word beside its colour (the forge's five states, `src/machines/five_states.ts`, drawn as the containers table draws them), and the ports its compose file publishes
11 (`src/games/project.ts`). A box silent for two minutes makes every app Can't tell. An app that needs
12 attention says why in a sentence and has the one button that helps, Restart or Start.
13 - **Logs and file.** The box's last synced lines of every app, merged oldest to newest with each line's
14 app named (the waker never), and the compose file, shown to the box's owner only since it can hold settings.
15 - **Buttons.** Start all, Stop all and Update (`src/actions/project.ts`, posting to
16 `/infra/project/<box>/<start-all|stop-all|update>`) each say in a sentence what they will do. Start
17 and stop need no dialog and come back with an Undo, the other one, which carries the apps the act touched and puts back those alone (an app left alone stays alone); Update has none and says so. They
18 ask the box through `askPower`, as the container tab does, so a held box refuses them the same way.
19 - **Who.** `may` decides, under the credential sent: an operator of the whole box. A read-only token
20 and a person without the grant are refused and nothing is asked. **Limit:** the page sits under /infra, so an operator who is not an admin cannot reach it; the buttons are theirs by grant, the page is not yet.
21 - **Logs cap.** The newest 200 lines of the apps shown, chosen in SQL.
22 - **Terminal.** None yet (No door: `src/tui/screens` is frozen, #18559, and the commit says so): `src/tui/screens` is frozen (#18559), so a terminal door is a command in
23 `src/cli` over a public API route, which this page does not have.
24
25 Not here: the container's own tab (`docs/features/infra.md`, Containers), and apps of a project that
26 is not a game box.
src/actions/project.ts added +82
@@ -0,0 +1,82 @@
1 /**
2 * A project's buttons (#18603): Start all, Stop all and Update, and the one button a "Needs
3 * attention" app offers. Each asks the box through `askPower`, the one question the games page and
4 * the container tab ask, so a held box, a crowded one and a refusal read the same everywhere.
5 * `may` decides first: an operator of the whole box, acting under the credential they sent.
6 * Stop and start offer their Undo (the other one); Update does not, and says so.
7 */
8
9 import type { App } from "../app.ts";
10 import type { Principal } from "../core/principal.ts";
11 import { userOf } from "../core/principal.ts";
12 import { composeServices, readCompose } from "../games/compose.ts";
13 import { mayOnGame } from "../games/game_may.ts";
14 import { askPower, type Power } from "../games/power.ts";
15 import { isWaker, servicesOf, SERVICE_NAME, type GameBox } from "../games/store.ts";
16 import { err, ok, type Result } from "../kernel/result.ts";
17
18 export const PROJECT_ACTS = ["start-all", "stop-all", "update", "restart", "start"] as const;
19 export type ProjectAct = (typeof PROJECT_ACTS)[number];
20 export const isProjectAct = (v: string): v is ProjectAct => (PROJECT_ACTS as readonly string[]).includes(v);
21
22 export interface Done {
23 readonly message: string;
24 /** The act that puts it back, when there is one. */
25 readonly undo?: "start-all" | "stop-all";
26 /** The apps this act touched: its Undo is for these alone, never for the rest. */
27 readonly touched?: readonly string[];
28 }
29
30 /** An Undo's `names` field, read back: only names that are valid app names. */
31 export const namesOf = (v: string): string[] => v.split(",").filter((n) => SERVICE_NAME.test(n));
32
33 const NO = "Your account may not operate this project.";
34
35 /** Every app of the box: its compose services and whatever the box reported, never the waker. */
36 async function appsOf(app: App, box: GameBox): Promise<string[]> {
37 const compose = await readCompose(app, box);
38 const declared = compose === undefined ? [] : composeServices(compose.text);
39 return [...new Set([...declared, ...servicesOf(app.db, box.id).map((s) => s.name)])].filter((n) => SERVICE_NAME.test(n) && !isWaker(n)).sort();
40 }
41
42 export async function projectAct(app: App, asking: Principal, box: GameBox, act: ProjectAct, service = "", only?: readonly string[]): Promise<Result<Done, string>> {
43 if (!mayOnGame(app.db, asking, box.id, "", "operator")) return err(NO);
44 const user = userOf(asking);
45 const ask = async (names: readonly string[], kinds: readonly Power[]): Promise<{ asked: number; refused: string; names: string[] }> => {
46 let asked = 0;
47 const names2: string[] = [];
48 let refused = "";
49 for (const n of names) {
50 let got = false;
51 for (const kind of kinds) {
52 const r = await askPower(app, user, box, n, kind);
53 if (r.ok) (asked++, (got = true));
54 else refused ||= r.error;
55 }
56 if (got) names2.push(n);
57 }
58 return { asked, refused, names: names2 };
59 };
60 if (act === "restart" || act === "start") {
61 if (!SERVICE_NAME.test(service) || !(await appsOf(app, box)).includes(service)) return err("No such app in this project.");
62 const r = await ask([service], [act]);
63 return r.asked === 0 ? err(r.refused) : ok({ message: `${act === "start" ? "Start" : "Restart"} ${service}: asked. It shows here when the machine answers.` });
64 }
65 const all = await appsOf(app, box);
66 const names = only === undefined ? all : all.filter((n) => only.includes(n));
67 if (names.length === 0) return err("This project has no apps yet.");
68 const running = new Set(servicesOf(app.db, box.id).filter((s) => s.state === "running" && !s.asleep).map((s) => s.name));
69 if (act === "start-all") {
70 const r = await ask(names.filter((n) => !running.has(n)), ["start"]);
71 if (r.asked === 0) return err(r.refused || "Every app is running already.");
72 return ok({ message: `Start all: asked ${r.asked} ${r.asked === 1 ? "app" : "apps"} to start.${r.refused === "" ? "" : ` Not asked: ${r.refused}`}`, undo: "stop-all", touched: r.names });
73 }
74 if (act === "stop-all") {
75 const r = await ask(names.filter((n) => running.has(n)), ["stop"]);
76 if (r.asked === 0) return err(r.refused || "Nothing is running to stop.");
77 return ok({ message: `Stop all: asked ${r.asked} ${r.asked === 1 ? "app" : "apps"} to stop.`, undo: "start-all", touched: r.names });
78 }
79 const r = await ask(names, ["pull", "recreate"]);
80 if (r.asked === 0) return err(r.refused);
81 return ok({ message: `Update: asked ${names.length} ${names.length === 1 ? "app" : "apps"} to pull their newest image and start again from it.${r.refused === "" ? "" : ` Not asked: ${r.refused}`}` });
82 }
src/core/empty_words.ts +2
@@ -98,6 +98,8 @@ const TABLE = {
9898 regValues: { sentence: "No values." },
9999 gameBoxes: { sentence: "Nothing runs here yet.", reason: "A game box is a machine on your cloud running a compose project; an admin starts one." },
100100 gameServices: { sentence: "Nothing has reported yet.", reason: "The box shows its services once its agent first syncs." },
101 projectApps: { sentence: "No app is listed in this project yet.", reason: "Its apps are the services of its compose file." },
102 projectLogs: { sentence: "No log lines have reached the forge yet.", reason: "The box sends them as it syncs." },
101103 gamePlugins: { sentence: "Nothing is installed.", reason: "Search Modrinth below, or upload a jar." },
102104 cloudResources: { sentence: "No cloud account is attached.", reason: "Attach one and the forge reads what it holds and what it costs." },
103105 gamePluginConfigs: { sentence: "No plugin config file is kept in the repository yet.", reason: "Add one below: it is a commit to the compose file." },
src/games/project.ts added +69
@@ -0,0 +1,69 @@
1 /**
2 * A project's page as plain data (#18603): a compose project is a game box's, and its apps are the
3 * services of its compose file. Each app has one of five states, always a word with a tone, and a
4 * "Needs attention" says why in plain words and names the one button that helps. Merged logs are
5 * the box's own synced lines, newest last, the service named on each. Nothing here asks the box;
6 * the buttons are `actions/project.ts`. The page, the terminal screen and the tests read this.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { parseCompose } from "../web/render/compose.ts";
11 import { isSilent } from "../cloud/containers.ts";
12 import { containerFive, type Told } from "../machines/five_states.ts";
13 import { isWaker, mayDo, roleOn, servicesOf, type GameBox, type GameService } from "./store.ts";
14 import type { User } from "../core/users.ts";
15
16 export interface ProjectApp {
outdated

Principles 4 and 7, and one way to do a thing: a second five-state vocabulary beside the forge's own (fiveBadge / machineFive, #18633). Reuse it for state and colour; keep only reason and fix here.

17 readonly name: string;
18 /** One of the forge's five states (`machines/five_states.ts`): word, reason and the one fix. */
19 readonly five: Told;
20 readonly ports: readonly string[];
21 }
22
23 export interface ProjectLine {
24 readonly service: string;
25 readonly line: string;
26 }
27
28 /**
29 * What each button does, in one sentence, as the page and the terminal say it before it is pressed.
30 */
31 export const SAYS = {
32 "start-all": "Start all starts every app in this project that is not running; the ones running are left alone.",
33 "stop-all": "Stop all stops every app in this project; their data stays, and Start all brings them back.",
34 update: "Update pulls the newest image of each app and starts each again from it, so every app restarts once; there is no Undo.",
35 } as const;
36
37 /** An app's state is its container's: the forge's one mapping, `containerFive`. */
38 export const stateOf = (s: GameService | undefined, silent: boolean): Told =>
39 containerFive({ state: s?.state ?? "", health: s?.health ?? "", asleep: s?.asleep === true, silent });
40
41 /**
42 * The apps a person may see on a box: the compose file's services and every one the box reported.
43 */
44 export function projectApps(db: Database, user: User | undefined, box: GameBox, composeText: string | undefined, now = Date.now()): ProjectApp[] {
45 const seen = servicesOf(db, box.id);
46 const parsed = composeText === undefined ? undefined : parseCompose(composeText);
47 const declared = parsed !== undefined && "services" in parsed ? parsed.services : [];
48 const names = [...new Set([...declared.map((d) => d.name), ...seen.map((s) => s.name)])].filter((n) => !isWaker(n) && mayDo(roleOn(db, user, box.id, n), "viewer")).sort();
49 const silent = isSilent(box.seenAt, now);
50 return names.map((name) => ({
51 name,
52 five: stateOf(seen.find((s) => s.name === name), silent),
53 ports: declared.find((d) => d.name === name)?.ports ?? [],
54 }));
55 }
56
57 /**
58 * The box's newest `limit` (200) synced lines of the named apps, chosen in SQL so a chatty hidden
59 * app never crowds them out, oldest first, merged by when each arrived.
60 */
61 export function mergedLogs(db: Database, boxId: string, apps: readonly string[], limit = 200): ProjectLine[] {
62 if (apps.length === 0) return [];
63 const marks = apps.map((_, i) => `?${i + 3}`).join(",");
64 return db
65 .query<{ service: string; line: string }, (string | number)[]>(`SELECT service, line FROM game_log WHERE box_id = ?1 AND service IN (${marks}) ORDER BY id DESC LIMIT ?2`)
66 .all(boxId, limit, ...apps)
67 .reverse()
68 .map((r) => ({ service: r.service, line: r.line }));
69 }
src/http/infra_routes.ts +52 −3
@@ -22,7 +22,7 @@ import { field, readForm } from "../web/form.ts";
2222 import { html, type Html } from "../web/html.ts";
2323 import { flashTo, fragment, page } from "../web/layout.ts";
2424 import { machineView } from "../actions/machine_view.ts";
25 import { INFRA_CSS, cloudPage, consolePage, endingPage, restoringPage, buildTray, placesRegion, composeForm, infraJs, buildPage, planTray, recordForm, resourcesPage, runningRegion, type ComposeState } from "../web/pages/infra.ts";
25 import { INFRA_CSS, projectPage, cloudPage, consolePage, endingPage, restoringPage, buildTray, placesRegion, composeForm, infraJs, buildPage, planTray, recordForm, resourcesPage, runningRegion, type ComposeState } from "../web/pages/infra.ts";
2626 import { cloudBranch, cloudHref, cloudList, cloudOverview, cloudPane, cloudTotal, cloudTreeJs } from "../web/pages/cloud_tree.ts";
2727 import { filesByNode } from "../cloud/declared_read.ts";
2828 import { logsOfContainer } from "../cloud/containers.ts";
@@ -38,9 +38,12 @@ import { pinnedBlock } from "./pinned_routes.ts";
3838 import { containerConsole } from "../web/pages/games.ts";
3939 import { backOf, isContainerAct, type ContainerAct } from "../web/pages/container_power.ts";
4040 import { askPower } from "../games/power.ts";
41 import { boxNamed, SERVICE_NAME, type GameBox } from "../games/store.ts";
41 import { isProjectAct, namesOf, projectAct } from "../actions/project.ts";
42 import { mergedLogs, projectApps } from "../games/project.ts";
43 import { readCompose } from "../games/compose.ts";
44 import { boxNamed, mayDo, roleOn, seesBox, SERVICE_NAME, type GameBox } from "../games/store.ts";
4245 import { mayOnGame } from "../games/game_may.ts";
43 import { askingFor } from "./page_may.ts";
46 import { askingFor, signedInPage } from "./page_may.ts";
4447 import { getPinned } from "../core/pinned.ts";
4548 import { LOG_READER_CSS, logReaderJs } from "../web/log_reader.ts";
4649 import { terminalBlocksJs } from "../web/terminal_blocks.ts";
@@ -451,6 +454,50 @@ async function infraComposeSave(ctx: Ctx): Promise<Response> {
451454 return flashTo(ctx, got.back, saved.ok ? { message: `Saved as commit ${saved.value.slice(0, 8)} on ${got.box.repo}.` } : { tone: "danger", message: saved.error });
452455 }
453456
457 // GET /infra/project/:box: a compose project as a table of its apps, with its merged logs and
458 // its compose file. Seeing it needs a grant on the box; its buttons need operator (`may`).
459 async function infraProject(ctx: Ctx): Promise<Response> {
460 if (!signedInPage(ctx)) return signInFirst(ctx);
461 const user = ctx.auth.user!;
462 const box = boxNamed(ctx.app.db, ctx.params.box ?? "");
463 if (box === undefined || !seesBox(ctx.app.db, user, box.id)) return notFoundPage(ctx);
464 const compose = await readCompose(ctx.app, box);
465 const apps = projectApps(ctx.app.db, user, box, compose?.text);
466 const role = roleOn(ctx.app.db, user, box.id, "");
467 return page({
468 ctx,
469 title: `${box.name} · project · forge`,
470 body: projectPage({
471 box: box.name,
472 repo: box.repo,
473 apps,
474 logs: mergedLogs(ctx.app.db, box.id, apps.map((a) => a.name)),
475 compose: compose?.text,
476 owner: mayDo(role, "owner"),
477 operate: mayOnGame(ctx.app.db, principalOfUser(user), box.id, "", "operator"),
478 }),
479 });
480 }
481
482 // POST /infra/project/:box/:act: Start all, Stop all, Update, or the one button of an app that
483 // needs attention. Same origin (readForm); `may` decides in `projectAct`, and a person with no
484 // grant on the box is told it does not exist.
485 async function infraProjectAct(ctx: Ctx): Promise<Response> {
486 if (!signedInPage(ctx)) return signInFirst(ctx);
487 const box = boxNamed(ctx.app.db, ctx.params.box ?? "");
488 const act = ctx.params.act ?? "";
489 if (box === undefined || !isProjectAct(act) || !seesBox(ctx.app.db, ctx.auth.user, box.id)) return notFoundPage(ctx);
490 const form = await readForm(ctx, "rw");
491 if (form instanceof Response) return form;
492 const back = `/infra/project/${box.name}`;
493 const done = await projectAct(ctx.app, askingFor(ctx), box, act, field(form, "service"), act === "start-all" || act === "stop-all" ? (field(form, "names") === "" ? undefined : namesOf(field(form, "names"))) : undefined);
494 if (!done.ok) return flashTo(ctx, back, { tone: "danger", message: done.error });
495 // The Undo carries the apps this act touched, so it puts back those and leaves the rest alone.
496 const names = (done.value.touched ?? []).join(",");
497 const undo = done.value.undo === undefined || names === "" || names.length > 200 ? undefined : { action: `${back}/${done.value.undo}`, label: "Undo", fields: { names } };
498 return flashTo(ctx, back, { message: done.value.message, ...(undo === undefined ? {} : { undo }) });
499 }
500
454501 // GET /infra/:name/ending: the offer to snapshot before End.
455502 function infraEnding(ctx: Ctx): Response {
456503 const denied = guard(ctx);
@@ -517,6 +564,8 @@ export function infraRoutes(router: Router<Handler>): void {
517564 router.add("POST", "/infra/record", infraRecord);
518565 router.add("POST", "/infra/rebuild", infraRebuild);
519566 router.add("POST", "/infra/projects", infraProjects);
567 router.add("GET", "/infra/project/:box", infraProject);
568 router.add("POST", "/infra/project/:box/:act", infraProjectAct);
520569 router.add("GET", "/infra/:name", infraMachineOpen);
521570 router.add("POST", "/infra/container/:box/:service/:act", infraContainerPower);
522571 router.add("POST", "/infra/container/:box/:service/console/:act", infraConsole);
src/http/lazy_lists.ts +2
@@ -671,6 +671,8 @@ export const OPERATIONS_ROUTES = [
671671 ["POST", "/infra/record"],
672672 ["POST", "/infra/rebuild"],
673673 ["POST", "/infra/projects"],
674 ["GET", "/infra/project/:box"],
675 ["POST", "/infra/project/:box/:act"],
674676 ["GET", "/infra/:name"],
675677 ["POST", "/infra/container/:box/:service/:act"],
676678 ["POST", "/infra/container/:box/:service/console/:act"],
src/web/pages/cloud_tree.ts +1 −1
@@ -340,7 +340,7 @@ export function cloudPane(v: CloudView, n: CloudNode, tab: NodeTab = tabOf(n, nu
340340 <div><dt>Last read</dt><dd>${readLine(v, n)}</dd></div>
341341 ${facts.filter((f) => f.label === "Id").map((f) => html`<div><dt>${f.label}</dt><dd>${copyField("cloud-id", f.value, "The provider's id", "Copy the id")}</dd></div>`)}
342342 </dl>
343 ${n.children.length === 0 ? null : html`<h2>${containersSay(n)}</h2><div class="table-scroll" role="region" tabindex="0" aria-label="Containers"><table class="table" data-dense>
343 ${n.children.length === 0 ? null : html`<h2>${containersSay(n)}</h2><p><a href="/infra/project/${n.children[0]!.container!.box}">Open its project: apps, merged logs and compose file</a></p><div class="table-scroll" role="region" tabindex="0" aria-label="Containers"><table class="table" data-dense>
344344 <thead><tr>${CONTAINER_COLUMNS.map((k) => html`<th scope="col">${k.label}</th>`)}</tr></thead>
345345 <tbody>${n.children.map((c) => html`<tr>${CONTAINER_COLUMNS.map((k) => html`<td>${k.field === "name" ? html`<a href="${cloudHref(c.path, v.q)}">${c.name}</a>` : k.field === "state" ? fiveBadge(c.container!.five) : containerCell(c.container!, k.field, v.now)}</td>`)}</tr>`)}</tbody>
346346 </table></div>`}
src/web/pages/infra.ts +38 −1
@@ -26,10 +26,12 @@ import { CLOUD_TREE_CSS, cloudLayout, cloudTotal } from "./cloud_tree.ts";
2626 import type { CloudView } from "../../cloud/tree.ts";
2727 import { html, raw, type Html } from "../html.ts";
2828 import { icon } from "../icons.ts";
29 import { fiveBlock } from "../five_badge.ts";
29 import { fiveBadge, fiveBlock } from "../five_badge.ts";
3030 import { machineFive } from "../../machines/five_states.ts";
3131 import { btn, crumbs, disclosure, field as textField, row, rowList, selectField } from "../ui.ts";
32 import { emptyLine } from "../empty_words.ts";
3233 import { DNS_NAME_PATTERN } from "../dns_name_pattern.ts";
34 import { SAYS, type ProjectApp, type ProjectLine } from "../../games/project.ts";
3335
3436 /**
3537 * The page's own styles (#16696), sent only with /infra (`styleCss`), as /search and /notes send
@@ -684,3 +686,38 @@ export const infraJs = /* js */ `
684686 });
685687 })();
686688 `;
689
690 /**
691 * A project's page (#18603), `/infra/project/<box>`: its apps as a table (state, always a word
692 * beside its colour, and ports), what each button will do in a sentence, the box's merged logs and,
693 * for its owner, its compose file. Start all and Stop all post without a dialog and come back with
694 * an Undo; Update says it has none. An app that needs attention says why and has the one button.
695 */
696 export function projectPage(v: { box: string; repo: string; apps: readonly ProjectApp[]; logs: readonly ProjectLine[]; compose: string | undefined; owner: boolean; operate: boolean }): Html {
697 const base = `/infra/project/${v.box}`;
698 const act = (a: keyof typeof SAYS, label: string, variant: "primary" | "ghost"): Html =>
699 html`<form method="post" action="${base}/${a}" class="stack">${btn(label, { variant, label: `${label} in ${v.box}` })}<p class="muted small">${SAYS[a]}</p></form>`;
700 return html`${pageHead(v.box, { sub: `A compose project from ${v.repo}: its apps, their logs and its file.` })}
701 ${v.operate ? html`<div class="row-fields">${act("start-all", "Start all", "ghost")}${act("stop-all", "Stop all", "ghost")}${act("update", "Update", "ghost")}</div>` : html`<p class="muted small">You may look at this project; its buttons are for its operators.</p>`}
702 <section id="project-apps" aria-label="Apps">
703 <h2>Apps</h2>
704 ${v.apps.length === 0
705 ? emptyLine("projectApps")
706 : html`<table class="table"><thead><tr><th scope="col">App</th><th scope="col">State</th><th scope="col">Ports</th></tr></thead><tbody>
707 ${v.apps.map(
708 (a) => html`<tr data-app="${a.name}"><th scope="row" class="mono">${a.name}</th>
709 <td>${fiveBadge(a.five)}${a.five.reason === "" ? null : html`<p class="small">${a.five.reason}</p>`}${v.operate && a.five.fix !== undefined && (a.five.fix.act === "start" || a.five.fix.act === "restart")
710 ? html`<form method="post" action="${base}/${a.five.fix.act}"><input type="hidden" name="service" value="${a.name}" />${btn(a.five.fix.label, { size: "sm", label: `${a.five.fix.label} ${a.name}` })}</form>`
711 : null}</td>
712 <td class="mono">${a.ports.length === 0 ? "none published" : a.ports.join(", ")}</td></tr>`,
713 )}</tbody></table>`}
714 </section>
715 <section id="project-logs" aria-label="Logs of every app">
716 <h2>Logs</h2>
717 ${v.logs.length === 0 ? emptyLine("projectLogs") : html`<pre class="mono small" tabindex="0">${v.logs.map((l) => `${l.service} ${l.line}\n`).join("")}</pre>`}
718 </section>
719 <section id="project-compose" aria-label="Compose file">
720 <h2>Compose file</h2>
721 ${!v.owner ? html`<p class="muted">The compose file is shown to the project's owner: it can hold settings.</p>` : v.compose === undefined ? html`<p class="muted">The compose file could not be read from ${v.repo} just now.</p>` : html`<pre class="mono small" tabindex="0">${v.compose}</pre>`}
722 </section>`;
723 }
test/infra-project.test.ts added +183
@@ -0,0 +1,183 @@
1 /**
2 * A project's page (#18603): a compose project's apps as a table (five states, each a word and a
3 * colour, with ports), merged logs, its compose file for its owner, and Start all, Stop all and
4 * Update, each asking the box as the container tab does, under `may`. One test per button, and a
5 * refusal for a person without the grant.
6 */
7 import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test";
8 import { mkdtempSync } from "node:fs";
9 import { rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { projectAct } from "../src/actions/project.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { principalOfUser } from "../src/core/principal.ts";
15 import { createSession } from "../src/core/sessions.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { mergedLogs, projectApps, SAYS, stateOf } from "../src/games/project.ts";
19 import { boxNamed, createGameBox, grant, recordSync, type SyncBody } from "../src/games/store.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21
22 let dir = "";
23 let app: App;
24 let servers: Servers;
25 let alice: User;
26 let bob: User;
27 const svc = (name: string, state: string, health = "") => ({ name, state, health, startedAt: "2026-11-01 10:00:00 +0000 UTC", cpuPct: 0, memMiB: 0 });
28 const SYNC: SyncBody = { services: [svc("hub", "running", "healthy"), svc("survival", "exited"), svc("lobby", "running", "unhealthy"), svc("warm", "running", "starting"), svc("forge-waker", "running")] };
29 const COMPOSE = "services:\n hub:\n image: itzg/minecraft-server\n ports:\n - '25565:25565'\n survival:\n image: itzg/minecraft-server\n";
30 const box = () => boxNamed(app.db, "mc")!;
31 const named = async (username: string, admin = false): Promise<User> => {
32 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", ...(admin ? { isAdmin: true } : {}) });
33 if (!made.ok) throw new Error(made.error);
34 return made.value;
35 };
36 const asked = (): string[] =>
37 app.db.query<{ service: string; kind: string }, []>("SELECT service, kind FROM game_command ORDER BY created_at, rowid").all().map((r) => `${r.kind} ${r.service}`);
38 const cookie = (u: User) => ({ cookie: `forge_session=${createSession(app.db, u.id).token}` });
39 const post = (path: string, headers: Record<string, string>, body = ""): Promise<Response> =>
40 fetch(`${servers.url}${path}`, { method: "POST", redirect: "manual", headers: { ...headers, origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, body });
41
42 beforeAll(async () => {
43 dir = mkdtempSync(join(tmpdir(), "forge-infra-project-"));
44 app = createApp({ dataDir: dir, port: 0 });
45 servers = await serve(app);
46 alice = await named("alice", true);
47 bob = await named("bob");
48 createGameBox(app.db, { name: "mc", repo: "alice/game", pinnedId: "" });
49 });
50 beforeEach(() => {
51 for (const t of ["game_service", "game_grant", "game_command", "game_log"]) app.db.run(`DELETE FROM ${t}`);
52 recordSync(app.db, box(), SYNC, new Date());
53 });
54 afterAll(async () => {
55 servers.stop();
56 app.close();
57 await rm(dir, { recursive: true, force: true });
58 });
59
60 test("each app has one of five states, a word and a colour, and a reason where it needs attention", () => {
61 const apps = projectApps(app.db, alice, box(), COMPOSE);
62 const by = Object.fromEntries(apps.map((a) => [a.name, a]));
63 expect(apps.map((a) => a.name)).toEqual(["hub", "lobby", "survival", "warm"]); // never the waker
64 expect(by["hub"]).toMatchObject({ five: { word: "Running" }, ports: ["25565:25565"] });
65 expect(by["survival"]).toMatchObject({ five: { word: "Stopped" }, ports: [] });
66 expect(by["warm"]!.five.word).toBe("Starting");
67 expect(by["lobby"]!.five).toMatchObject({ word: "Needs attention", fix: { act: "restart" } });
68 expect(by["lobby"]!.five.reason).toContain("health check");
69 expect(stateOf(undefined, true).word).toBe("Can't tell");
70 expect(projectApps(app.db, alice, box(), COMPOSE, Date.now() + 10 * 60_000).every((a) => a.five.word === "Can't tell")).toBe(true);
71 });
72
73 test("the page is a table of its apps with a word beside each colour, merged logs and the compose file for its owner", async () => {
74 app.db.run("INSERT INTO game_log (box_id, service, line, at) VALUES (?1, 'hub', 'hub says hi', ''), (?1, 'survival', 'survival says hi', ''), (?1, 'forge-waker', 'waker line', '')", [box().id]);
75 expect(mergedLogs(app.db, box().id, ["hub", "survival"]).map((l) => `${l.service}: ${l.line}`)).toEqual(["hub: hub says hi", "survival: survival says hi"]);
76 const res = await fetch(`${servers.url}/infra/project/mc`, { headers: cookie(alice) });
77 const text = await res.text();
78 expect(res.status).toBe(200);
79 for (const w of ["Running", "Stopped", "Starting", "Needs attention"]) expect(text).toContain(w);
80 expect(text).toContain("<th scope=\"col\">Ports</th>");
81 expect(text.indexOf("hub hub says hi")).toBeLessThan(text.indexOf("survival survival says hi"));
82 expect(text).not.toContain("waker line");
83 for (const a of ["start-all", "stop-all", "update"] as const) expect(text).toContain(SAYS[a].replace(/'/g, "&#39;"));
84 expect(text).toContain("/infra/project/mc/restart"); // the one button of the app that needs attention
85 });
86
87 test("Start all asks each app that is not running to start, and offers Stop all as its Undo", async () => {
88 const res = await post("/infra/project/mc/start-all", cookie(alice));
89 expect(res.status).toBe(303);
90 expect(asked()).toEqual(["start survival"]); // the running ones are left alone
91 expect(decodeURIComponent(res.headers.get("set-cookie") ?? "")).toContain("/infra/project/mc/stop-all");
92 const done = await projectAct(app, principalOfUser(alice), box(), "start-all");
93 expect(done.ok && done.value.undo).toBe("stop-all");
94 });
95
96 test("Stop all asks each running app to stop, and offers Start all as its Undo", async () => {
97 const res = await post("/infra/project/mc/stop-all", cookie(alice));
98 expect(res.status).toBe(303);
99 expect(asked().sort()).toEqual(["stop hub", "stop lobby", "stop warm"]);
100 expect(decodeURIComponent(res.headers.get("set-cookie") ?? "")).toContain("/infra/project/mc/start-all");
101 const done = await projectAct(app, principalOfUser(alice), box(), "stop-all");
102 expect(done.ok && done.value.undo).toBe("start-all");
103 });
104
105 test("Update pulls and recreates every app, and says it has no Undo", async () => {
106 const res = await post("/infra/project/mc/update", cookie(alice));
107 expect(res.status).toBe(303);
108 const got = asked();
109 for (const n of ["hub", "lobby", "survival", "warm"]) expect(got).toContain(`pull ${n}`), expect(got).toContain(`recreate ${n}`);
110 expect(got).not.toContain("pull forge-waker");
111 const done = await projectAct(app, principalOfUser(alice), box(), "update");
112 expect(done.ok && done.value.undo).toBeUndefined();
113 expect(SAYS.update).toContain("no Undo");
114 });
115
116 test("the one button of an app that needs attention restarts that app alone", async () => {
117 const res = await post("/infra/project/mc/restart", cookie(alice), "service=lobby");
118 expect(res.status).toBe(303);
119 expect(asked()).toEqual(["restart lobby"]);
120 const bad = await projectAct(app, principalOfUser(alice), box(), "restart", "forge-waker");
121 expect(bad.ok).toBe(false);
122 expect(asked()).toEqual(["restart lobby"]);
123 });
124
125 const raw = (state: string, health = "") => ({ name: "x", state, health, asleep: false }) as Parameters<typeof stateOf>[0];
126 test("restarting needs a Restart, dead needs a Start, and paused is stopped with no button", () => {
127 expect(stateOf(raw("restarting"), false)).toMatchObject({ word: "Needs attention", fix: { act: "restart" } });
128 expect(stateOf(raw("dead"), false)).toMatchObject({ word: "Needs attention", fix: { act: "start" } });
129 expect(stateOf(raw("paused"), false)).toMatchObject({ word: "Stopped" });
130 expect(stateOf(raw("paused"), false).fix).toBeUndefined();
131 });
132
133 test("the Start button of a dead app starts that app alone", async () => {
134 recordSync(app.db, box(), { services: [...(SYNC.services ?? []), svc("crashed", "dead")] }, new Date());
135 const text = await (await fetch(`${servers.url}/infra/project/mc`, { headers: cookie(alice) })).text();
136 expect(text).toContain("/infra/project/mc/start");
137 const res = await post("/infra/project/mc/start", cookie(alice), "service=crashed");
138 expect(res.status).toBe(303);
139 expect(asked()).toEqual(["start crashed"]);
140 });
141
142 test("an Undo puts back only the apps its act touched", async () => {
143 // Start all touched survival alone: its Undo stops survival, never hub, lobby or warm.
144 const res = await post("/infra/project/mc/start-all", cookie(alice));
145 const flash = decodeURIComponent(res.headers.get("set-cookie") ?? "");
146 expect(flash).toContain("survival");
147 const done = await projectAct(app, principalOfUser(alice), box(), "start-all");
148 expect(done.ok && done.value.touched).toEqual(["survival"]);
149 app.db.run("DELETE FROM game_command");
150 recordSync(app.db, box(), { services: [svc("hub", "running", "healthy"), svc("survival", "running"), svc("lobby", "running", "unhealthy"), svc("warm", "running", "healthy")] }, new Date());
151 await post("/infra/project/mc/stop-all", cookie(alice), "names=survival");
152 expect(asked()).toEqual(["stop survival"]);
153 // Stop all touched running apps; its Undo starts those, and an app already stopped stays stopped.
154 app.db.run("DELETE FROM game_command");
155 recordSync(app.db, box(), SYNC, new Date());
156 await post("/infra/project/mc/start-all", cookie(alice), "names=hub,survival");
157 expect(asked()).toEqual(["start survival"]); // hub was running: left alone
158 });
159
160 test("merged logs keep the newest lines of the named apps however chatty a hidden one is", () => {
161 const ins = app.db.query("INSERT INTO game_log (box_id, service, line, at) VALUES (?1, ?2, ?3, '')");
162 ins.run(box().id, "hub", "first");
163 for (let i = 0; i < 900; i++) ins.run(box().id, "forge-waker", `w${i}`);
164 expect(mergedLogs(app.db, box().id, ["hub"], 5).map((l) => l.line)).toEqual(["first"]);
165 });
166
167 test("a person without the grant, a viewer, and a read-only token are refused and nothing is asked", async () => {
168 // A person with no grant: refused by may, not by the page.
169 for (const act of ["start-all", "stop-all", "update"] as const) expect((await projectAct(app, principalOfUser(bob), box(), act)).ok).toBe(false);
170 // Everyday accounts do not reach /infra at all.
171 const everyday = { value: await named("carol") };
172 expect((await post("/infra/project/mc/stop-all", cookie(everyday.value))).status).toBe(403);
173 grant(app.db, box().id, everyday.value.id, "viewer");
174 expect((await projectAct(app, principalOfUser(everyday.value), box(), "stop-all")).ok).toBe(false);
175 // An admin's read-only token may look and not act.
176 const ro = { authorization: `Bearer ${createToken(app.db, alice.id, "ro", "ro").token}` };
177 const res = await post("/infra/project/mc/stop-all", ro);
178 expect(res.status).not.toBe(200);
179 expect(asked()).toEqual([]);
180 // An operator may.
181 grant(app.db, box().id, everyday.value.id, "operator");
182 expect((await projectAct(app, principalOfUser(everyday.value), box(), "stop-all")).ok).toBe(true);
183 });
test/no-polling.test.ts +1
@@ -310,6 +310,7 @@ const NOT_WALKED: Record<string, string> = {
310310 "/talk/dev/:token": "a frame proxied from a running dev cell, not a page; the seed starts none",
311311 "/talk/dev/:token/*path": "a file proxied from a running dev cell, not a page; the seed starts none",
312312 "/infra/end/:act/*path": "the plan of a stop or delete, a page for a cloud resource the seed does not have; the action word is not in the seed",
313 "/infra/project/:box": "a project page for one game box; the seed holds no box (test/infra-project.test.ts seeds one and reads it, test/pages-budget.test.ts gives the budget walk its own)",
313314 "/tabforge-link/:id": "a shared tab-forge app named by a random id the seed does not hold (test/tab-share.test.ts covers it)",
314315 "/tab/v/:hash/:file": "a content-hashed browser-tab bundle file, JS or wasm, not a page; the hash is one the seed cannot guess",
315316 "/edge/config/:file": "a published config file for the edge, JSON or a key, not a page; the seed publishes none",
test/pages-budget.test.ts +3
@@ -17,6 +17,7 @@
1717 * so no reading answers here while the pages are asked, and a page that waits
1818 * for one is over `AFTER_IDLE_MS` by construction, on any machine.
1919 */
20 import { createGameBox } from "../src/games/store.ts";
2021 import { mintRepoInvite } from "../src/core/invites.ts";
2122 import { holdName, move, newId, newTicket } from "../src/billing/orders.ts";
2223 import { fileReport } from "../src/actions/reports.ts";
@@ -222,6 +223,8 @@ beforeAll(async () => {
222223 [id, kind, new Date().toISOString(), on],
223224 );
224225 FIXTURE["/infra/-/*path"] = "/infra/-/aws/main/us-east-1/volume%3Avol-1"; // a bare ":" reads as unfilled
226 createGameBox(app.db, { name: "fixture-box", repo: "alice/forge", pinnedId: "" }); // a project's page (#18603)
227 FIXTURE["/infra/project/:box"] = "/infra/project/fixture-box";
225228 FIXTURE["/infra/end/:act/*path"] = "/infra/end/delete/aws/main/us-east-1/volume%3Avol-1";
226229 servers = await serve(app);
227230 const signin = await fetch(`${servers.url}/signin`, {
test/security-floor-routes.test.ts +1
@@ -73,6 +73,7 @@ const UNSEEDED: Record<string, string> = {
7373 "/tabforge-link/:id": "a shared tab-forge app named by a random id the seed does not hold (test/tab-share.test.ts covers it)",
7474 "/tab/v/:hash/:file": "a vendored file of the browser-tab forge, named by its content hash, which the seed does not hold (test/tab.test.ts covers it)",
7575 "/infra/end/:act/*path": "the plan of a stop or delete for a cloud resource, which the seed does not have (test/cloud-end.test.ts covers it)",
76 "/infra/project/:box": "one game box's project page, which the seed has no box for (test/infra-project.test.ts covers it)",
7677 "/games/:box": "a game box, which the seed does not make (test/games.test.ts covers it)",
7778 "/games/:box/:service": "a game box, which the seed does not make (test/games.test.ts covers it)",
7879 "/games/:box/@shell/stream": "a game box's shell output for its owner, which the seed does not make (test/game-console.test.ts covers it)",

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

Keyboard shortcuts

Docs