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

As code: infra.json in a repo, written by the UI, reconciled on merge (#16696) #17149

opened this

Merged 45h 19m ago, live in production

scout/forge:scout/17075-as-code-infra-json-in-a-repo-written-by → main 0 commits fork

  • Merged. scout/17075-as-code-infra-json-in-a-repo-written-by was merged into main as 4fec00e.

Review

Sign in to review this change.
13 files changed +504 −6
docs/features/infra.md +4
@@ -40,6 +40,10 @@ Build refuses a plan that changed since it was shown, so nobody builds what they
4040
4141 Build runs in the background and appends `infra.applied` (the wants and each step's sentence), then one `infra.step` per step (started, done or failed), or `infra.refused` when it was refused before its first step. The tray is a live region on those events: each step shows as it happens, then "Ready at" its name with the link. A build that stopped says why with Build again, which plans the same wants against what exists now and skips what is done.
4242
43 ## As code (#17075, read-only so far)
44
45 An app's repo may hold `infra.json` at its root on the main branch: `{"version": 1, "machines": [{"name", "account", "place", "host"?}]}`. Every machine in it runs that app, so a file cannot name another repo's machines. The schema is closed (an unknown key is refused), capped at 64 KiB and 50 machines, and every problem is said with its path (`src/cloud/infra_file.ts`). `/infra` shows an **As code** block per file: what applying it would add, change or remove, or that a name is blocked because another app runs it, which is never applied (only this app's running machines are ever removed); nothing is applied. The terminal's Infrastructure screen lists the same (`src/tui/screens/infra.ts`), `GET /api/v1/admin/infra/code` returns it, and the `infra` tool's `code` action says it. Reading is `src/cloud/infra_read.ts`: apps are read in parallel and a (repo, tip) already read is served from memory. Not yet: a lifetime in the file (the diff cannot compare it), the page writing the file as a commit, and reconciling on merge to main.
46
4347 ## A database (#17074)
4448
4549 Managed Postgres on DigitalOcean is a second kind of thing the plan builds, for an app. Compose it with `b` in the terminal's Infrastructure screen (an app, a region of a writable DigitalOcean account, a size), with the `infra` tool's `plan` and a `want` of `{database: true, app, where: "digitalocean/main@nyc1", size?, name?, secret?}`, or with `POST /api/v1/admin/infra/plan` and `database: true`. The page does not compose one yet; its account meters and the `infra` list count and name each database.
src/cloud/infra_file.ts added +130
@@ -0,0 +1,130 @@
1 /**
2 * `infra.json` (#17075, phase 4 of #16696): what an app's repo says should run on its owner's own
3 * cloud, and how that differs from what runs. This is the schema and the diff, both pure; reading
4 * the file out of a repo is `cloud/infra_read.ts`.
5 *
6 * { "version": 1, "machines": [ { "name": "shop-1", "account": "digitalocean/main",
7 * "place": "digitalocean:fra1:s-1vcpu-1gb", "host": "shop.example.com" } ] }
8 *
9 * The file sits in the root of an app's repo, and every machine in it runs that app: the file never
10 * names an app, so it cannot move another repo's machines. The schema is closed (an unknown key is
11 * refused, so a typo is not read as "no host"), every problem is said with its path, and the file
12 * is capped, because the repo is written by people the forge may not trust.
13 */
14
15 import { NAME } from "../core/pinned.ts";
16 import { err, ok, type Result } from "../kernel/result.ts";
17
18 /** The file's name at the repo root. */
19 export const INFRA_FILE = "infra.json";
20 /** The most bytes read of it and the most machines it may declare. */
21 export const MAX_BYTES = 64 * 1024;
22 export const MAX_MACHINES = 50;
23
24 /** One machine the file declares. */
25 export interface Declared {
26 readonly name: string;
27 /** `provider/name` of a cloud account. */
28 readonly account: string;
29 /** A Places id, `provider:datacenter:size`. */
30 readonly place: string;
31 readonly host: string;
32 }
33
34 /** What the forge has of a machine, as the diff compares it. */
35 export interface Existing {
36 readonly name: string;
37 readonly app: string;
38 readonly account: string;
39 readonly place: string;
40 readonly host: string;
41 readonly state: string;
42 }
43
44 /**
45 * `blocked` is a declared machine that cannot be made as written; it is never something to apply.
46 */
47 type ChangeKind = "add" | "change" | "remove" | "same" | "blocked";
48
49 export interface Change {
50 readonly kind: ChangeKind;
51 readonly name: string;
52 readonly says: string;
53 }
54
55 const KEYS = new Set(["version", "machines"]);
56 // No lifetime yet: a field the diff cannot compare would say "matches" falsely (#17075).
57 const MACHINE_KEYS = new Set(["name", "account", "place", "host"]);
58 const ACCOUNT = /^[a-z0-9]+\/[A-Za-z0-9._-]{1,60}$/;
59 const PLACE = /^[a-z0-9]+:[A-Za-z0-9._-]{1,40}:[A-Za-z0-9._-]{1,60}$/;
60 const HOST = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
61
62 const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
63
64 /** The machines a file declares, or every problem with it, each naming where. */
65 export function parseInfra(text: string): Result<Declared[], string[]> {
66 if (Buffer.byteLength(text, "utf8") > MAX_BYTES) return err([`${INFRA_FILE} is over ${MAX_BYTES / 1024} KiB`]);
67 let data: unknown;
68 try {
69 data = JSON.parse(text);
70 } catch {
71 return err([`${INFRA_FILE} is not JSON`]);
72 }
73 if (!isObject(data)) return err(["the file is not an object"]);
74 const bad: string[] = [];
75 for (const k of Object.keys(data)) if (!KEYS.has(k)) bad.push(`${k}: not a key of the file`);
76 if (data["version"] !== 1) bad.push("version: must be 1");
77 const list = data["machines"];
78 if (!Array.isArray(list)) return err([...bad, "machines: must be a list"]);
79 if (list.length > MAX_MACHINES) return err([...bad, `machines: at most ${MAX_MACHINES}`]);
80 const out: Declared[] = [];
81 const seen = new Set<string>();
82 list.forEach((m: unknown, i) => {
83 const at = `machines[${i}]`;
84 if (!isObject(m)) return void bad.push(`${at}: not an object`);
85 for (const k of Object.keys(m)) if (!MACHINE_KEYS.has(k)) bad.push(`${at}.${k}: not a key of a machine`);
86 const str = (k: string, re: RegExp, why: string, required = true): string => {
87 const v = m[k];
88 if (v === undefined && !required) return "";
89 if (typeof v !== "string" || !re.test(v)) bad.push(`${at}.${k}: ${why}`);
90 return typeof v === "string" ? v : "";
91 };
92 const name = str("name", NAME, "lowercase letters, digits and dashes, starting with a letter");
93 const account = str("account", ACCOUNT, "an account as provider/name");
94 const place = str("place", PLACE, "a place as provider:datacenter:size");
95 const host = str("host", HOST, "a host name", false);
96 if (name !== "" && seen.has(name)) bad.push(`${at}.name: ${name} is declared twice`);
97 seen.add(name);
98 out.push({ name, account, place, host });
99 });
100 return bad.length > 0 ? err(bad) : ok(out);
101 }
102
103 /**
104 * What applying the file would change, for one app: a machine declared and not there is added; one
105 * there with another account, place or host is changed; one of this app's that is running and no
106 * longer declared is removed; the rest is the same. Retired machines are not "there". Read-only:
107 * nothing here makes or ends anything.
108 */
109 export function diffOf(app: string, declared: readonly Declared[], have: readonly Existing[]): Change[] {
110 const live = new Map(have.filter((h) => h.state !== "retired").map((h) => [h.name, h]));
111 const out: Change[] = [];
112 for (const d of declared) {
113 const h = live.get(d.name);
114 if (h === undefined) {
115 out.push({ kind: "add", name: d.name, says: `add ${d.name} at ${d.place}` });
116 } else if (h.app !== app) {
117 out.push({ kind: "blocked", name: d.name, says: `${d.name} already runs ${h.app}: pick another name` });
118 } else {
119 const moved = [
120 h.account !== d.account ? `account ${h.account} → ${d.account}` : "",
121 h.place !== d.place ? `place ${h.place} → ${d.place}` : "",
122 d.host !== "" && h.host !== d.host ? `host ${h.host} → ${d.host}` : "",
123 ].filter(Boolean);
124 out.push(moved.length === 0 ? { kind: "same", name: d.name, says: `${d.name} is as declared` } : { kind: "change", name: d.name, says: `change ${d.name}: ${moved.join(", ")}` });
125 }
126 }
127 const names = new Set(declared.map((d) => d.name));
128 for (const h of live.values()) if (h.app === app && !names.has(h.name)) out.push({ kind: "remove", name: h.name, says: `remove ${h.name}: it runs but ${INFRA_FILE} does not declare it` });
129 return out;
130 }
src/cloud/infra_read.ts added +108
@@ -0,0 +1,108 @@
1 /**
2 * `infra.json` against what runs (#17075, #16696 phase 4), read-only: for each app whose repo holds
3 * the file at its main branch, what the file declares and what applying it would change. Pure
4 * parsing and diffing is `cloud/infra_file.ts`; this reads the repos and the pinned rows. Every
5 * door shows these: the /infra page, the terminal screen, `GET /api/v1/admin/infra/code` and the
6 * `infra` tool's `code`.
7 */
8
9 import type { App } from "../app.ts";
10 import { countLine } from "../core/gate_triage.ts";
11 import { type Change, type Declared, diffOf, type Existing, INFRA_FILE, MAX_BYTES, parseInfra } from "./infra_file.ts";
12 import { listApps } from "../core/apps.ts";
13 import { listPinned, placeIdOf } from "../core/pinned.ts";
14 import { getRepoById } from "../core/repos.ts";
15 import type { User } from "../core/users.ts";
16 import { blobForRender } from "../git/read.ts";
17 import { resolveOid } from "../git/merge.ts";
18 import { repoDir } from "../git/repos.ts";
19 import { err, ok, type Result } from "../kernel/result.ts";
20
21 /**
22 * One app's file: its changes, or why it could not be read. Apps without the file are not listed.
23 */
24 export interface CodeFile {
25 readonly app: string;
26 readonly problems: readonly string[];
27 readonly changes: readonly Change[];
28 /** One sentence: "3 changes: 1 to add, …", or the first problem. */
29 readonly says: string;
30 }
31
32 function codeSays(changes: readonly Change[]): string {
33 if (changes.every((c) => c.kind === "same")) return "matches what runs";
34 const n = (k: Change["kind"]): number => changes.filter((c) => c.kind === k).length;
35 return countLine([[n("add"), "to add"], [n("change"), "to change"], [n("remove"), "to remove"], [n("blocked"), "blocked"]]);
36 }
37
38 /** What one blob at one tip parsed to: kept per (repo, tip), so an unchanged tip costs no read. */
39 type Read = { readonly kind: "missing" } | { readonly kind: "bad"; readonly problems: readonly string[] } | { readonly kind: "ok"; readonly declared: readonly Declared[] };
40 /** Per forge (an app object), not per process: two forges must not share what they read. */
41 const readsOf = new WeakMap<App, Map<string, Read>>();
42 const MAX_READS = 1000;
43 /**
44 * A branch tip is looked up at most once in this long per repo, so /infra costs no ref lookup per
45 * app.
46 */
47 const TIP_MS = 5000;
48 const tipsOf = new WeakMap<App, Map<string, { at: number; tip: string | undefined }>>();
49
50 async function tipOf(app: App, dir: string, branch: string): Promise<string | undefined> {
51 let tips = tipsOf.get(app);
52 if (tips === undefined) tipsOf.set(app, (tips = new Map()));
53 const hit = tips.get(dir);
54 if (hit !== undefined && Date.now() - hit.at < TIP_MS) return hit.tip;
55 const tip = await resolveOid(dir, `refs/heads/${branch}`);
56 if (tips.size >= MAX_READS) tips.clear();
57 tips.set(dir, { at: Date.now(), tip });
58 return tip;
59 }
60
61 async function readOne(app: App, dir: string, tip: string): Promise<Read> {
62 let reads = readsOf.get(app);
63 if (reads === undefined) readsOf.set(app, (reads = new Map()));
64 const key = `${dir}@${tip}`;
65 const hit = reads.get(key);
66 if (hit !== undefined) return hit;
67 const blob = await blobForRender(dir, tip, INFRA_FILE, MAX_BYTES);
68 let r: Read;
69 if (blob.kind === "missing") r = { kind: "missing" };
70 else {
71 const parsed = blob.kind === "text" ? parseInfra(new TextDecoder().decode(blob.body)) : err([`${INFRA_FILE} is not a text file under ${MAX_BYTES / 1024} KiB`]);
72 r = parsed.ok ? { kind: "ok", declared: parsed.value } : { kind: "bad", problems: parsed.error };
73 }
74 if (reads.size >= MAX_READS) reads.clear();
75 reads.set(key, r);
76 return r;
77 }
78
79 /** Every app's `infra.json` as it stands on its main branch, diffed against the machines now. */
80 export async function infraCode(app: App, actor: User | undefined): Promise<Result<CodeFile[], string>> {
81 if (actor?.isAdmin !== true) return err("not_found");
82 const have: Existing[] = listPinned(app.db).map((p) => ({
83 name: p.name,
84 app: p.app,
85 account: `${p.target}/${p.account}`,
86 place: placeIdOf(p),
87 host: p.host,
88 state: p.state,
89 }));
90 // Apps are read in parallel; a tip already read costs no blob read, and the tip itself is looked
91 // up at most every few seconds.
92 const found = await Promise.all(
93 listApps(app.db).map(async (a): Promise<CodeFile | undefined> => {
94 const repo = getRepoById(app.db, a.repoId);
95 if (repo === undefined) return undefined;
96 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
97 const tip = await tipOf(app, dir, repo.defaultBranch);
98 if (tip === undefined) return undefined;
99 const read = await readOne(app, dir, tip);
100 if (read.kind === "missing") return undefined;
101 const name = `${repo.ownerName}/${repo.name}`;
102 if (read.kind === "bad") return { app: name, problems: read.problems, changes: [], says: `${INFRA_FILE} is refused: ${read.problems[0]}` };
103 const changes = diffOf(name, read.declared, have);
104 return { app: name, problems: [], changes, says: codeSays(changes) };
105 }),
106 );
107 return ok(found.filter((f): f is CodeFile => f !== undefined));
108 }
src/contract/openapi/routes/getApiV1AdminInfraCode.ts added +14
@@ -0,0 +1,14 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: "/api/v1/admin/infra/code",
6 summary: "Each app's infra.json from its repo's main branch, checked",
7 detail: "Read from the root of each app's repo main branch, read-only: each file's problems as rows and its difference from what runs; nothing is changed",
8 auth: true,
9 role: "admin",
10 refusals: {
11 not_found: "only a forge administrator sees this route",
12 },
13 refuses: [404],
14 };
src/contract/openapi/routes/index.ts +1
@@ -50,6 +50,7 @@ export { route as getApiV1AdminCapacity } from "./getApiV1AdminCapacity.ts";
5050 export { route as getApiV1AdminCrawlers } from "./getApiV1AdminCrawlers.ts";
5151 export { route as getApiV1AdminDrills } from "./getApiV1AdminDrills.ts";
5252 export { route as getApiV1AdminInfra } from "./getApiV1AdminInfra.ts";
53 export { route as getApiV1AdminInfraCode } from "./getApiV1AdminInfraCode.ts";
5354 export { route as getApiV1AdminInvites } from "./getApiV1AdminInvites.ts";
5455 export { route as getApiV1AdminKpisProbe } from "./getApiV1AdminKpisProbe.ts";
5556 export { route as getApiV1AdminLimits } from "./getApiV1AdminLimits.ts";
src/core/gate_triage.ts +6 −1
@@ -59,10 +59,15 @@ export function tally(items: readonly Triaged[]): { close: number; keep: number;
5959 return n;
6060 }
6161
62 /** Counts as one line, `3 close · 1 keep`: a name with none is left out. */
63 export function countLine(counts: readonly (readonly [number, string])[]): string {
64 return counts.filter(([n]) => n > 0).map(([n, name]) => `${n} ${name}`).join(" · ");
65 }
66
6267 /** The tally as one line, `3 close · 1 keep`: a verdict with none is left out. */
6368 export function tallyLine(items: readonly Triaged[]): string {
6469 const n = tally(items);
65 return [`${n.close} close`, `${n.keep} keep`, `${n.merge} merge`].filter((p) => !p.startsWith("0 ")).join(" · ");
70 return countLine([[n.close, "close"], [n.keep, "keep"], [n.merge, "merge"]]);
6671 }
6772
6873 const STOP = new Set(
src/http/api/admin.ts +10
@@ -25,6 +25,7 @@ import { changePlans, measuredPlans } from "../../actions/plans.ts";
2525 import { setAccountCeilings, setAccountGrant } from "../../actions/model_grant.ts";
2626 import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, keepPinned, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, claimPinned, deployPinned, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned } from "../../actions/pinned.ts";
2727 import { TARGETS } from "../../cloud/targets.ts";
28 import { infraCode } from "../../cloud/infra_read.ts";
2829 import { buildOf, infraOf, nameFor, planById, planCompose, planDatabase, startBuild } from "../../actions/infra.ts";
2930 import { changeQuotas, readQuotas } from "../../actions/quotas.ts";
3031 import { allowRequest, declineRequest, listRequests } from "../../actions/requests.ts";
@@ -143,6 +144,15 @@ export function adminRoutes(router: Router<Handler>): void {
143144 return json({ ...seen.value, ...(plan === null ? {} : { build: buildOf(ctx.app, ctx.auth.user, plan) ?? null }) });
144145 });
145146
147 // infra.json in each app's repo against what runs (#17075): what applying it would change.
148 // Read-only.
149 router.add("GET", "/api/v1/admin/infra/code", async (ctx) => {
150 const denied = accountAdmin(ctx, "ro");
151 if (denied) return denied;
152 const files = await infraCode(ctx.app, ctx.auth.user);
153 return files.ok ? json({ files: files.value }) : notFound();
154 });
155
146156 // The plan of one more machine: the tray the page shows, as data. Nothing is made.
147157 router.add("POST", "/api/v1/admin/infra/plan", async (ctx) => {
148158 const denied = accountAdmin(ctx, "admin");
src/http/infra_routes.ts +3 −1
@@ -4,6 +4,7 @@
44 * `actions/infra.ts` (or `actions/pinned.ts` for Keep and End now) the terminal, API and MCP call.
55 */
66
7 import { infraCode } from "../cloud/infra_read.ts";
78 import { buildOf, machineOf, type ComposeChoices, composeChoices, domainOf, infraOf, nameFor, planCompose, rebuild, startBuild } from "../actions/infra.ts";
89 import { deleteSnapshot, endWithSnapshot, restoreSnapshot } from "../actions/infra_snapshot.ts";
910 import { clearPinned, endsWords, keepPinned, retirePinned, retireWords } from "../actions/pinned.ts";
@@ -65,7 +66,8 @@ async function render(
6566 if (!planned.ok) return notFoundPage(ctx);
6667 compose = composeForm(choices, state, planTray(planned.value), domainOf(ctx.app));
6768 }
68 const body = infraPage(view.value, compose, build, { composing: o.composing });
69 const code = await infraCode(ctx.app, user);
70 const body = infraPage(view.value, compose, build, { composing: o.composing, code: code.ok ? code.value : [] });
6971 return page({ ctx, title: "Infrastructure", scriptJs: SCRIPT, styleCss: INFRA_CSS, body, ...(o.flash ? { flash: o.flash } : {}) }, status);
7072 }
7173
src/http/mcp/tools/infra.ts +8 −2
@@ -1,3 +1,4 @@
1 import { infraCode } from "../../../cloud/infra_read.ts";
12 import { buildOf, firewallWant, gameWant, planDatabase, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts";
23 import { bindBucket, readBucket } from "../../../actions/bucket.ts";
34 import { endsWords, keepPinned } from "../../../actions/pinned.ts";
@@ -16,11 +17,11 @@ export const tool: Tool = {
1617 name: "infra",
1718 listedTo: "admin",
1819 doc: "`{ action, id?, want?, question?, names?, result?, bucket? }`: `list` (its `says` names every machine), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a firewall `{firewall: name}` or a game box `{game: true, where, name?, repo?, host?}` or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `keep`, `begin`, `attach`, `record_result`; `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.",
19 description: "Cloud machines and spend.",
20 description: "Cloud machines, spend",
2021 inputSchema: {
2122 type: "object",
2223 properties: {
23 action: { type: "string", enum: ["list", "show", "plan", "apply", "keep", "begin", "attach", "record_result", "price", "bind"] },
24 action: { type: "string", enum: ["list", "show", "plan", "apply", "keep", "begin", "attach", "record_result", "code", "price", "bind"] },
2425 id: { type: "string" },
2526 want: { type: "object" },
2627 question: { type: "string" },
@@ -46,6 +47,11 @@ export const tool: Tool = {
4647 // One paragraph that names every machine first, so a reader of the groups alone misses nothing.
4748 return good({ says: infraSays(v.value), ...experiments, ...rest });
4849 }
50 if (action === "code") {
51 // infra.json in each app's repo against what runs: what applying it would change. Read-only.
52 const files = await infraCode(ctx.app, user);
53 return files.ok ? good({ says: files.value.length === 0 ? "no app's repo holds an infra.json" : files.value.map((k) => `${k.app}: ${k.says}`).join("; "), files: files.value }) : bad("not_found", "no such tool here");
54 }
4955 if (action === "show") {
5056 if (id === "") return bad("no_id", "show takes an id: a plan's, an experiment's, or a machine's name");
5157 if (id.startsWith("plan-")) {
src/tui/screens/infra.ts +17 −1
@@ -10,6 +10,7 @@
1010 * else sees nothing.
1111 */
1212
13 import { infraCode, type CodeFile } from "../../cloud/infra_read.ts";
1314 import { buildOf, composeChoices, databaseChoices, infraOf, nameFor, planCompose, planDatabase, startBuild, type Compose, type Planned, type Running } from "../../actions/infra.ts";
1415 import { deleteSnapshot, endWithSnapshot, restoredName, restoreSnapshot } from "../../actions/infra_snapshot.ts";
1516 import { LIFETIME_DAYS, clearPinned, endsWords, keepPinned, retirePinned, retireWords } from "../../actions/pinned.ts";
@@ -36,6 +37,16 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
3637 note = text;
3738 ctx.invalidate();
3839 };
40 // `infra.json` against what runs (#17075): read from the repos, so it arrives after the first
41 // paint.
42 let code: readonly CodeFile[] = [];
43 const loadCode = (): void => {
44 void infraCode(f.app, f.user).then((r) => {
45 if (r.ok) code = r.value;
46 ctx.invalidate();
47 });
48 };
49 loadCode();
3950 const machines = (): Running[] => {
4051 const v = infraOf(f.app, f.user);
4152 return v.ok ? v.value.groups.flatMap((g) => g.machines) : [];
@@ -240,7 +251,10 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
240251 "database.bound",
241252 ],
242253 },
243 () => ctx.invalidate(),
254 () => {
255 loadCode();
256 ctx.invalidate();
257 },
244258 );
245259 },
246260 render(area, s) {
@@ -291,6 +305,8 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
291305 ...v.value.databases.map((d) => ({ title: `${d.name} · ${month(d.monthlyCents)}`, secondary: `database · ${d.app} · ${d.where} · ${d.says}`, meta: d.account })),
292306 // What ended: each retired machine says what it still bills, a kept disk or nothing left.
293307 ...v.value.ended.map((m) => ({ title: `ended: ${m.name} · ${month(m.monthlyCents)}`, secondary: `${m.name} is ${m.billing}`, meta: m.account })),
308 // infra.json in an app's repo: what applying it would change (read-only).
309 ...code.map((k) => ({ title: `infra.json in ${k.app}: ${k.says}`, secondary: [...k.problems, ...k.changes.filter((x) => x.kind !== "same").map((x) => x.says)].join(" · "), tone: k.problems.length > 0 ? ("danger" as const) : ("default" as const), meta: "" })),
294310 ];
295311 rows.push(...v.value.snapshots.map((x) => ({ title: `snapshot: ${x.name} · ${x.state === "ready" && x.cents > 0 ? month(x.cents) : x.state}`, secondary: x.says, meta: `${x.target}/${x.account}` })));
296312 if (v.value.snapshotsHidden > 0) rows.push({ title: `${v.value.snapshotsHidden} older snapshots are not listed: only the newest 200 are shown`, meta: "" });
src/web/pages/infra.ts +20 −1
@@ -12,6 +12,7 @@
1212 */
1313
1414 import { LIFETIME_DAYS } from "../../actions/pinned.ts";
15 import type { CodeFile } from "../../cloud/infra_read.ts";
1516 import { restoredName, type SnapshotView } from "../../actions/infra_snapshot.ts";
1617 import { ENDED_DAYS, type Build, type ComposeChoices, type InfraView, type Planned, type Running } from "../../actions/infra.ts";
1718 import { dollars } from "../../cloud/prices.ts";
@@ -460,12 +461,30 @@ export function buildTray(b: Build): Html {
460461 </div>`;
461462 }
462463
464 /**
465 * infra.json in an app's repo against what runs (#17075): what applying it would change; read-only.
466 */
467 export function codeRegion(files: readonly CodeFile[]): Html {
468 if (files.length === 0) return html``;
469 return html`<section class="settings-block" data-code>
470 <h2>As code</h2>
471 ${rowList(
472 files.flatMap((k) => [
473 row({ title: k.app, meta: html`${k.says}` }),
474 ...k.problems.map((p) => row({ title: `infra.json is refused: ${p}` })),
475 ...k.changes.filter((c) => c.kind !== "same").map((c) => row({ title: c.says })),
476 ]),
477 )}
478 </section>`;
479 }
480
463481 /** The whole page: the head sentence, what runs, then compose (closed once something runs) or a build. */
464 export function infraPage(v: InfraView, compose: Html, build: Build | undefined, s: { composing: boolean }): Html {
482 export function infraPage(v: InfraView, compose: Html, build: Build | undefined, s: { composing: boolean; code?: readonly CodeFile[] }): Html {
465483 const open = s.composing || v.groups.length === 0;
466484 return html`${pageHead("Infrastructure", { sub: "What runs on your own cloud, what it's for, what it costs, and when it ends." })}
467485 <div data-infra>
468486 ${runningRegion(v)}
487 ${codeRegion(s.code ?? [])}
469488 ${build !== undefined
470489 ? buildTray(build)
471490 : html`<section class="settings-block" data-compose-block>
test/infra-file.test.ts added +182
@@ -0,0 +1,182 @@
1 /**
2 * infra.json (#17075, phase 4 of #16696): the schema, the diff, and the read-only doors that show
3 * it.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { infraCode } from "../src/cloud/infra_read.ts";
11 import { commitToBranch } from "../src/actions/repos.ts";
12 import { diffOf, MAX_BYTES, parseInfra, type Existing } from "../src/cloud/infra_file.ts";
13 import { createApp as createAppRecord } from "../src/core/apps.ts";
14 import { createRepo } from "../src/core/repos.ts";
15 import { createSession } from "../src/core/sessions.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import type { Ctx } from "../src/http/context.ts";
18 import { tool } from "../src/http/mcp/tools/infra.ts";
19 import { serve, type Servers } from "../src/http/server.ts";
20 import { createForgeApp } from "../src/tui/forge.ts";
21 import { infraScreen } from "../src/tui/screens/infra.ts";
22 import { headlessTerminal } from "../src/tui/term/terminal.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24 import { settleApp } from "./helpers/tui.ts";
25
26 quietLogs();
27
28 const machine = { name: "shop-1", account: "digitalocean/main", place: "digitalocean:fra1:s-1vcpu-1gb" };
29 const file = (over: Record<string, unknown> = {}): string => JSON.stringify({ version: 1, machines: [{ ...machine, ...over }] });
30
31 describe("the schema", () => {
32 test("a good file is read, with an optional host", () => {
33 const r = parseInfra(file({ host: "shop.example.com" }));
34 expect(r.ok && r.value).toEqual([{ ...machine, host: "shop.example.com" }]);
35 });
36 test("every problem is said with its path", () => {
37 const r = parseInfra(JSON.stringify({ version: 2, extra: 1, machines: [{ name: "Bad Name", account: "x", place: "y", host: "nope", lifetimeDays: 30, typo: 1 }] }));
38 expect(r.ok).toBe(false);
39 const says = r.ok ? "" : r.error.join("|");
40 for (const part of ["version: must be 1", "extra: not a key", "machines[0].name", "machines[0].account", "machines[0].place", "machines[0].host", "machines[0].lifetimeDays: not a key", "machines[0].typo"])
41 expect(says).toContain(part);
42 });
43 test("not JSON, not an object, too big, twice declared and too many are refused", () => {
44 expect(parseInfra("{").ok).toBe(false);
45 expect(parseInfra("[]").ok).toBe(false);
46 expect(parseInfra(" ".repeat(MAX_BYTES + 1)).ok).toBe(false);
47 const dup = parseInfra(JSON.stringify({ version: 1, machines: [machine, machine] }));
48 expect(dup.ok ? "" : dup.error.join()).toContain("declared twice");
49 const many = parseInfra(JSON.stringify({ version: 1, machines: Array.from({ length: 51 }, (_, i) => ({ ...machine, name: `m${i}` })) }));
50 expect(many.ok).toBe(false);
51 });
52 });
53
54 describe("the diff", () => {
55 const have = (over: Partial<Existing> = {}): Existing => ({ ...machine, app: "ada/shop", host: "a.example.com", state: "running", ...over });
56 const declared = (over: Record<string, unknown> = {}) => {
57 const r = parseInfra(file(over));
58 if (!r.ok) throw new Error(r.error.join());
59 return r.value;
60 };
61 test("add, same, change, remove, and retired machines are not there", () => {
62 expect(diffOf("ada/shop", declared(), []).map((c) => c.kind)).toEqual(["add"]);
63 expect(diffOf("ada/shop", declared({ host: "a.example.com" }), [have()]).map((c) => c.kind)).toEqual(["same"]);
64 const moved = diffOf("ada/shop", declared({ place: "digitalocean:nyc3:s-1vcpu-1gb" }), [have()]);
65 expect(moved[0]?.says).toContain("place digitalocean:fra1:s-1vcpu-1gb → digitalocean:nyc3:s-1vcpu-1gb");
66 expect(diffOf("ada/shop", [], [have()]).map((c) => c.kind)).toEqual(["remove"]);
67 expect(diffOf("ada/shop", declared(), [have({ state: "retired" })]).map((c) => c.kind)).toEqual(["add"]);
68 });
69 test("another app's machines are never removed, and a taken name is said", () => {
70 expect(diffOf("ada/shop", [], [have({ app: "ada/ledger" })])).toEqual([]);
71 const taken = diffOf("ada/shop", declared(), [have({ app: "ada/ledger" })])[0];
72 expect(taken?.says).toContain("already runs ada/ledger");
73 expect(taken?.kind).toBe("blocked");
74 });
75 });
76
77 describe("the doors", () => {
78 let dataDir = "";
79 let app: App;
80 let admin: User;
81 let servers: Servers;
82 let cookie = "";
83 beforeAll(async () => {
84 dataDir = await mkdtemp(join(tmpdir(), "forge-infra-file-"));
85 app = createApp({ dataDir, port: 0, url: "https://forge.example.net" });
86 const u = await createUser(app.db, { username: "ada", email: "[email protected]", password: "a-good-passphrase", origin: "seed", isAdmin: true, trusted: true });
87 if (!u.ok) throw new Error(u.error);
88 admin = u.value;
89 const r = await createRepo(app.db, app.reposRoot, { ownerId: admin.id, name: "shop", visibility: "public" });
90 if (!r.ok) throw new Error(String(r.error));
91 const c = await commitToBranch(app, admin, r.value, { message: "seed", files: [{ path: "forge.json", content: "{}\n" }, { path: "infra.json", content: file() }] });
92 if (!c.ok) throw new Error(JSON.stringify(c.error));
93 createAppRecord(app.db, { repoId: r.value.id, slug: "shop", access: "public" });
94 servers = await serve(app);
95 cookie = `forge_session=${createSession(app.db, admin.id).token}`;
96 }, 30_000);
97 afterAll(async () => {
98 await servers.stop();
99 await rm(dataDir, { recursive: true, force: true });
100 });
101
102 test("the read finds the file in the repo and says what applying it would add; only an admin reads", async () => {
103 const r = await infraCode(app, admin);
104 expect(r.ok && r.value).toMatchObject([{ app: "ada/shop", says: "1 to add", problems: [] }]);
105 expect((await infraCode(app, undefined)).ok).toBe(false);
106 });
107 test("/infra shows it, the API returns it, and a visitor gets neither", async () => {
108 const page = await (await fetch(`${servers.url}/infra`, { headers: { cookie } })).text();
109 expect(page).toContain("As code");
110 expect(page).toContain("add shop-1 at digitalocean:fra1:s-1vcpu-1gb");
111 const api = await fetch(`${servers.url}/api/v1/admin/infra/code`, { headers: { cookie } });
112 expect(((await api.json()) as { files: { app: string }[] }).files[0]?.app).toBe("ada/shop");
113 expect((await fetch(`${servers.url}/api/v1/admin/infra/code`)).status).toBe(404);
114 });
115 test("the tool's code action and the terminal screen say the same", async () => {
116 const url = new URL("http://forge.test/mcp");
117 const ctx: Ctx = { app, request: new Request(url.href), url, params: {}, auth: { user: admin, scope: "admin", via: "token" }, theme: undefined };
118 const said = (await tool.run(ctx, admin, { action: "code" })) as { ok: true; value: { says: string } };
119 expect(said.value.says).toBe("ada/shop: 1 to add");
120 const { app: tui, session } = createForgeApp(app, { sshUsername: "ada", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin }, { terminal: headlessTerminal(160, 24), exitHooks: false });
121 tui.start();
122 tui.ctx.push(infraScreen(session, tui.ctx));
123 await settleApp(tui);
124 await settleApp(tui);
125 expect(tui.screen.toText()).toContain("infra.json in ada/shop: 1 to add");
126 tui.stop?.();
127 });
128 test("a non-admin gets 404 from the API, no block on the page, no tool result and no terminal rows", async () => {
129 const b = await createUser(app.db, { username: "bob", email: "[email protected]", password: "a-good-passphrase", origin: "seed", isAdmin: false, trusted: true });
130 if (!b.ok) throw new Error(b.error);
131 const bob = b.value;
132 const bobCookie = `forge_session=${createSession(app.db, bob.id).token}`;
133 const denied = await fetch(`${servers.url}/api/v1/admin/infra/code`, { headers: { cookie: bobCookie } });
134 // The route's admin role is refused by the router (403 not_admin) before the handler, whose own
135 // check answers 404.
136 expect(denied.status).toBe(403);
137 expect((await denied.clone().text())).toContain("not_admin");
138 expect(await denied.text()).not.toContain("ada/shop");
139 const page = await fetch(`${servers.url}/infra`, { headers: { cookie: bobCookie } });
140 expect(page.status).toBe(403);
141 expect(await page.text()).not.toContain("As code");
142 const url = new URL("http://forge.test/mcp");
143 const ctx: Ctx = { app, request: new Request(url.href), url, params: {}, auth: { user: bob, scope: "admin", via: "token" }, theme: undefined };
144 const said = (await tool.run(ctx, bob, { action: "code" })) as { ok: boolean; error?: string };
145 expect(said.ok).toBe(false);
146 expect(JSON.stringify(said)).not.toContain("ada/shop");
147 const { app: tui, session } = createForgeApp(app, { sshUsername: "bob", remoteAddress: "127.0.0.1", fingerprint: "SHA256:bob", user: bob }, { terminal: headlessTerminal(160, 24), exitHooks: false });
148 tui.start();
149 tui.ctx.push(infraScreen(session, tui.ctx));
150 await settleApp(tui);
151 await settleApp(tui);
152 expect(tui.screen.toText()).not.toContain("infra.json in");
153 tui.stop?.();
154 });
155 test("a malformed file is refused with its path on the page and the API; a repo with no infra.json yields nothing", async () => {
156 for (const [name, content] of [["broken", JSON.stringify({ version: 1, machines: [{ ...machine, typo: 1 }] })], ["plain", undefined]] as const) {
157 const r = await createRepo(app.db, app.reposRoot, { ownerId: admin.id, name, visibility: "public" });
158 if (!r.ok) throw new Error(String(r.error));
159 const files = [{ path: "forge.json", content: "{}\n" }, ...(content === undefined ? [] : [{ path: "infra.json", content }])];
160 const c = await commitToBranch(app, admin, r.value, { message: "seed", files });
161 if (!c.ok) throw new Error(JSON.stringify(c.error));
162 createAppRecord(app.db, { repoId: r.value.id, slug: name, access: "public" });
163 }
164 const page = await (await fetch(`${servers.url}/infra`, { headers: { cookie } })).text();
165 expect(page).toContain("infra.json is refused: machines[0].typo: not a key of a machine");
166 const api = (await (await fetch(`${servers.url}/api/v1/admin/infra/code`, { headers: { cookie } })).json()) as { files: { app: string; problems: string[] }[] };
167 expect(api.files.find((f) => f.app === "ada/broken")?.problems[0]).toContain("machines[0].typo");
168 expect(api.files.some((f) => f.app === "ada/plain")).toBe(false);
169 });
170 test("a second read of an unchanged tip gives the same answer", async () => {
171 const a = await infraCode(app, admin);
172 const b = await infraCode(app, admin);
173 expect(b).toEqual(a);
174 });
175 });
176
177 describe("what is declared and not compared is not accepted", () => {
178 test("lifetimeDays is refused as an unknown key, so 'matches what runs' is never false for it", () => {
179 const r = parseInfra(file({ lifetimeDays: 30 }));
180 expect(r.ok ? "" : r.error.join()).toContain("machines[0].lifetimeDays: not a key of a machine");
181 });
182 });
test/route-timing-coverage.test.ts +1
@@ -30,6 +30,7 @@ const UNTIMED: Record<string, string> = {
3030 "/api/v1/repos/:owner/:name/app/registry": "an app's installed registry items, one indexed read; no page to phase",
3131 "/api/v1/repos/:owner/:name/app/registry/updates": "an app's items behind the registry, one indexed read and a catalogue compare; no page to phase",
3232 "/api/v1/admin/plans": "an admin's plans with the measured median, two indexed reads; no page to phase",
33 "/api/v1/admin/infra/code": "each app's infra.json read from its repo's main branch (cached per tip) and diffed read-only; no page to phase",
3334 "/metrics": "Prometheus text exposition, scraped by token; not a page read",
3435 };
3536

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

Keyboard shortcuts

Docs