Public: anyone can read this; the crew can change it.
Cloud tree: a File tab says which lines declare a machine or a container #17777
Merged 9h 9m ago, live in production
sold/leaf-files-1 → main 0 commits
13 files
changed +717
−40
- docs/features/infra.md
- src/cloud/containers.ts
- src/cloud/declared_in.ts
- src/cloud/declared_read.ts
- src/cloud/infra_read.ts
- src/cloud/tree.ts
- src/http/infra_routes.ts
- src/http/mcp/tools/infra.ts
- src/tui/screens/cloudtree.ts
- src/web/declares.ts
- src/web/pages/cloud_tree.ts
- src/web/pages/repo.ts
- test/cloud-files.test.ts
docs/features/infra.md +1
| @@ -110,6 +110,7 @@ Every DigitalOcean and Hetzner account is read into provider ▸ account ▸ pro | ||
| 110 | 110 | - **A resource** is at `/infra/-/<cloud>/<account>/<project>/<id>`, beside the tree, or full width on a phone: cost, state, what it is attached to and what it holds (an address its balancer, NAT gateway or task; an ECS service its balancer and cluster; a balancer the services known behind it, "Shared by" when there are several; a link AWS does not state is not drawn, which does not mean nothing uses it), an AWS list price's day, what it leaves out and whose file it is (or why there is none), the app an AWS resource is part of and how that is known (nothing when it is not), what it was made from, who made it, when it was created, when it was read, and Ask about this (a talk with those facts, fenced as data). |
| 111 | 111 | - **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. |
| 112 | 112 | - **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. |
| 113 | - **File.** A machine and a container have two tabs, Facts and File (`?tab=file`; `[` and `]` in the terminal). 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. | |
| 113 | 114 | - **Keys.** j and k move, Enter opens, h and l (or the arrows) close and open, `/` filters and Enter goes to the first match. |
| 114 | 115 | - **States.** No account (a link to /settings/cloud), not read yet, a failed read (one line: when, why, and how old what is shown is), a kind that could not be read with its reason (on its project and on the account, which says where; under the headline's sum, "Not everything is listed: 1 kind not read" links to that account, and text doors name it; a billed account's gaps count too, and change no sum), and a reading older than three of its duty's intervals. A project's note ("R2 is not switched on for this account") is a plain line and no trouble, on its account too when that has one project. **Check the account** (`a` in the terminal) opens the account: see [](cloud.md#what-was-not-read-17637). |
| 115 | 116 | - **Terminal.** `:` then Cloud resources, or `/` in Infra (`src/tui/screens/cloudtree.ts`): the same list, filter and facts, the List price, Old price, Price from and No price lines among them (both read `factsOf`); `tab` changes pane, `w` opens the web page, `P` reads every account. |
src/cloud/containers.ts +3 −1
| @@ -36,6 +36,8 @@ export interface Container { | ||
| 36 | 36 | |
| 37 | 37 | /** A box syncs every few seconds; past this its last word is no longer what runs now. */ |
| 38 | 38 | const SILENT_MS = 2 * 60_000; |
| 39 | /** Whether a box's last full sync, at `seenAt` ("" for none), is too old to say what runs now. */ | |
| 40 | export const isSilent = (seenAt: string, now: number): boolean => seenAt === "" || now - Date.parse(seenAt) > SILENT_MS; | |
| 39 | 41 | const UNKNOWN = "not known"; |
| 40 | 42 | const STOPPED = "none, it is not running"; |
| 41 | 43 | |
| @@ -61,7 +63,7 @@ export function containersIn(db: Database, viewer: User | undefined, box: GameBo | ||
| 61 | 63 | const all = servicesOf(db, box.id); |
| 62 | 64 | // A row stays when its container is gone; the newest full sync names the ones there are. |
| 63 | 65 | const newest = all.map((s) => s.seenAt).sort().at(-1); |
| 64 | const silent = newest === undefined || now - Date.parse(newest) > SILENT_MS; | |
| 66 | const silent = isSilent(newest ?? "", now); | |
| 65 | 67 | // The diagnosis names images to the box's owner alone (`diag.ts`). |
| 66 | 68 | const owner = mayDo(roleOn(db, viewer, box.id), "owner"); |
| 67 | 69 | return all |
src/cloud/declared_in.ts added +119
| @@ -0,0 +1,119 @@ | ||
| 1 | /** | |
| 2 | * Which file declares a node of the cloud tree, and whether what the forge knows of the node agrees | |
| 3 | * (#17532). Pure: text in, declarations with their lines out. `declared_read.ts` reads git and the | |
| 4 | * forge's rows and joins the two by id. A file's values that may be secret never leave here: of a | |
| 5 | * compose service the names of its environment, and neither their values nor a build's address. | |
| 6 | */ | |
| 7 | ||
| 8 | import { parseCompose } from "../web/render/compose.ts"; | |
| 9 | import { isMap, isScalar, isSeq, parseAllDocuments } from "../web/render/vendor/yaml.mjs"; | |
| 10 | import { yamlTooLarge } from "../web/render/yaml-config.ts"; | |
| 11 | import type { CloudNode, Fact } from "./tree.ts"; | |
| 12 | ||
| 13 | /** | |
| 14 | * `same` is what the forge recorded or the box said, never the cloud's answer, which is not compared | |
| 15 | * yet. `ahead` is a box whose branch is at another commit than it runs; `add` has no node yet. | |
| 16 | */ | |
| 17 | export type FileState = "same" | "differs" | "ahead" | "add" | "unknown"; | |
| 18 | ||
| 19 | /** Where a declaration is, its lines counted from 1. */ | |
| 20 | export interface FilePlace { | |
| 21 | readonly repo: string; | |
| 22 | readonly branch: string; | |
| 23 | readonly path: string; | |
| 24 | readonly line: number; | |
| 25 | readonly end: number; | |
| 26 | } | |
| 27 | ||
| 28 | /** One declaration and the node it names. */ | |
| 29 | export interface Filed { | |
| 30 | readonly kind: "machine" | "box" | "service"; | |
| 31 | readonly name: string; | |
| 32 | readonly state: FileState; | |
| 33 | /** The state in a sentence, with why. */ | |
| 34 | readonly says: string; | |
| 35 | /** Left out where the reader may not read the repository: then no field is here either. */ | |
| 36 | readonly at?: FilePlace; | |
| 37 | /** What the file says, names and not secrets. */ | |
| 38 | readonly fields: readonly Fact[]; | |
| 39 | /** The node's path in the tree; none when no read of its cloud has it. */ | |
| 40 | readonly node?: readonly string[]; | |
| 41 | } | |
| 42 | ||
| 43 | /** Said of a node nothing declares: only two kinds of file are read, and a stack's own is neither. */ | |
| 44 | export const noFileSays = (n: CloudNode): string => { | |
| 45 | const of = n.resource?.partOf ?? null; | |
| 46 | return of === null ? "In no file the forge reads: those are infra.json and a game box's compose file." : `Not known: it is part of ${of.app}, ${of.by}, whose files the forge does not read.`; | |
| 47 | }; | |
| 48 | export const UNREADABLE = "In a file you cannot read."; | |
| 49 | ||
| 50 | /** "docker-compose.yml, lines 4 to 12, on main of ada/game". */ | |
| 51 | export const placeSays = (p: FilePlace): string => `${p.path}, ${p.line === p.end ? `line ${p.line}` : `lines ${p.line} to ${p.end}`}, on ${p.branch} of ${p.repo}`; | |
| 52 | ||
| 53 | /** The file's own page at its lines, as source: a compose file is otherwise drawn as a table. */ | |
| 54 | export const placeHref = (p: FilePlace): string => | |
| 55 | `/${p.repo}/blob/${encodeURIComponent(p.branch)}/${p.path.split("/").map(encodeURIComponent).join("/")}?view=source#L${p.line}${p.end > p.line ? `-L${p.end}` : ""}`; | |
| 56 | ||
| 57 | /** A commit as it is shown. */ | |
| 58 | export const shortSha = (sha: string): string => sha.slice(0, 10); | |
| 59 | ||
| 60 | /** The first and last line of each entry under the top-level `key` of a YAML or JSON text, by its name. */ | |
| 61 | export function linesUnder(text: string, key: string): Map<string, readonly [number, number]> { | |
| 62 | const out = new Map<string, readonly [number, number]>(); | |
| 63 | if (yamlTooLarge(text) !== undefined) return out; | |
| 64 | const top = parseAllDocuments(text)[0]?.contents; | |
| 65 | const under = isMap(top) ? top.items.find((p) => isScalar(p.key) && p.key.value === key)?.value : undefined; | |
| 66 | const line = (at: number): number => text.slice(0, at).split("\n").length; | |
| 67 | const add = (name: unknown, from: unknown, to: unknown): void => { | |
| 68 | const range = (n: unknown) => (isScalar(n) || isMap(n) || isSeq(n) ? (n.range ?? undefined) : undefined); | |
| 69 | const start = range(from)?.[0]; | |
| 70 | const end = range(to)?.[1] ?? range(from)?.[1]; | |
| 71 | if (typeof name !== "string" || start === undefined || end === undefined) return; | |
| 72 | // A block's end is where the next thing starts, so the blank before it is not its own. | |
| 73 | out.set(name, [line(start), line(start + text.slice(start, end).trimEnd().length)]); | |
| 74 | }; | |
| 75 | if (isMap(under)) for (const p of under.items) add(isScalar(p.key) ? p.key.value : undefined, p.key, p.value); | |
| 76 | if (isSeq(under)) | |
| 77 | for (const item of under.items) { | |
| 78 | const name = isMap(item) ? item.items.find((p) => isScalar(p.key) && p.key.value === "name")?.value : undefined; | |
| 79 | add(isScalar(name) ? name.value : undefined, item, item); | |
| 80 | } | |
| 81 | return out; | |
| 82 | } | |
| 83 | ||
| 84 | /** A compose file's services: each one's lines and what it says, or why the file is not read. */ | |
| 85 | export function servicesIn(text: string): Map<string, { readonly lines: readonly [number, number]; readonly fields: readonly Fact[] }> | string { | |
| 86 | const doc = parseCompose(text); | |
| 87 | if ("error" in doc) return doc.error; | |
| 88 | const lines = linesUnder(text, "services"); | |
| 89 | return new Map( | |
| 90 | doc.services.flatMap((s) => { | |
| 91 | const own = lines.get(s.name); | |
| 92 | if (own === undefined) return []; | |
| 93 | const fields: Fact[] = [ | |
| 94 | // A build's context may be an address with a token in it. | |
| 95 | { label: "Image", value: s.built ? "built from the repository or an address the file names" : s.source }, | |
| 96 | { label: "Ports", value: s.ports.join(", ") }, | |
| 97 | { label: "Volumes", value: s.volumes.join(", ") }, | |
| 98 | { label: "Depends on", value: s.dependsOn.join(", ") }, | |
| 99 | { label: "Environment", value: s.env.length === 0 ? "" : `${s.env.join(", ")} (names only)` }, | |
| 100 | ]; | |
| 101 | return [[s.name, { lines: own, fields: fields.filter((f) => f.value !== "") }] as const]; | |
| 102 | }), | |
| 103 | ); | |
| 104 | } | |
| 105 | ||
| 106 | /** Whether what a box runs is what its branch holds, by the commit it last said it runs. */ | |
| 107 | export function boxState(o: { ran: string; head: string; branch: string; heard: string; silent: boolean }): { readonly state: FileState; readonly says: string } { | |
| 108 | if (!/^[0-9a-f]{7,64}$/.test(o.ran)) return { state: "unknown", says: "Not known: the box has not said which commit it runs." }; | |
| 109 | if (o.silent) return { state: "unknown", says: `Not known: the box was last heard ${o.heard}, and ran ${shortSha(o.ran)} then.` }; | |
| 110 | if (o.ran === o.head) return { state: "same", says: `The box runs ${o.branch} as it is, at ${shortSha(o.ran)}.` }; | |
| 111 | return { state: "ahead", says: `${o.branch} is at ${shortSha(o.head)} and the box runs ${shortSha(o.ran)}, so these lines may not be what runs.` }; | |
| 112 | } | |
| 113 | ||
| 114 | /** "Declares 3: 2 as the forge knows them, 1 to add". */ | |
| 115 | export function declaresSay(all: readonly Filed[]): string { | |
| 116 | const words: readonly (readonly [FileState, string])[] = [["same", "as the forge knows them"], ["differs", "differ from the forge's record"], ["ahead", "not as the box runs them"], ["add", "to add"], ["unknown", "not known"]]; | |
| 117 | const parts = words.map(([state, w]) => [all.filter((f) => f.state === state).length, w] as const).filter(([n]) => n > 0); | |
| 118 | return `Declares ${all.length}: ${parts.map(([n, w]) => `${n} ${w}`).join(", ")}`; | |
| 119 | } |
src/cloud/declared_read.ts added +106
| @@ -0,0 +1,106 @@ | ||
| 1 | /** | |
| 2 | * The join of the cloud tree with the files that declare its nodes (#17532), for a forge admin: | |
| 3 | * `infra.json`'s machines through the forge's own record of each, and a game box's compose file | |
| 4 | * through the machine its row names. Never by a resource's name. It reads git and the forge's | |
| 5 | * database, asks no provider and no box, and changes nothing. The page, the terminal, the `infra` | |
| 6 | * tool and the file's own page all draw this. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { App } from "../app.ts"; | |
| 10 | import { listPinned } from "../core/pinned.ts"; | |
| 11 | import { canRead, getRepo } from "../core/repos.ts"; | |
| 12 | import type { User } from "../core/users.ts"; | |
| 13 | import { readCompose } from "../games/compose.ts"; | |
| 14 | import { listBoxes, servicesOf } from "../games/store.ts"; | |
| 15 | import { agoWords } from "../kernel/ago.ts"; | |
| 16 | import { isSilent } from "./containers.ts"; | |
| 17 | import { boxState, servicesIn, UNREADABLE, type Filed } from "./declared_in.ts"; | |
| 18 | import { diffOf, INFRA_FILE } from "./infra_file.ts"; | |
| 19 | import { infraFiles, recorded } from "./infra_read.ts"; | |
| 20 | import { resourcesOf, type CloudNode } from "./tree.ts"; | |
| 21 | ||
| 22 | /** What each change of `diffOf` is as a state; what is in no file is no declaration. */ | |
| 23 | const STATE = { same: "same", change: "differs", add: "add", blocked: "unknown" } as const; | |
| 24 | ||
| 25 | /** One declaration as a reader who may not read its repository sees it. */ | |
| 26 | const hidden = (f: Filed): Filed => ({ kind: f.kind, name: "", state: "unknown", says: UNREADABLE, fields: [], ...(f.node === undefined ? {} : { node: f.node }) }); | |
| 27 | ||
| 28 | /** Every declaration the forge reads, or those in the repository `only` (`owner/name`). */ | |
| 29 | export async function filedIn(app: App, actor: User | undefined, whole: CloudNode, now = Date.now(), only?: string): Promise<Filed[]> { | |
| 30 | if (actor?.isAdmin !== true) return []; | |
| 31 | const machines = new Map(resourcesOf(whole).map((n) => [`${n.path[0]}/${n.path[1]}/${n.resource!.id}`, n])); | |
| 32 | const pinned = listPinned(app.db).filter((p) => p.state !== "retired"); | |
| 33 | const nodeOf = (p: (typeof pinned)[number] | undefined): CloudNode | undefined => (p === undefined || p.remote === "" ? undefined : machines.get(`${p.target}/${p.account}/machine:${p.remote}`)); | |
| 34 | const placed = (n: CloudNode | undefined): { node?: readonly string[] } => (n === undefined ? {} : { node: n.path }); | |
| 35 | const reads = (name: string): boolean => { | |
| 36 | const [owner = "", repo = ""] = name.split("/"); | |
| 37 | const found = getRepo(app.db, owner, repo); | |
| 38 | // One that is gone holds nothing to keep back, and is said to be gone. | |
| 39 | return found === undefined || canRead(app.db, found, actor); | |
| 40 | }; | |
| 41 | const have = recorded(app); | |
| 42 | ||
| 43 | const fromInfra = (await infraFiles(app, only)).flatMap(({ repo, read }): Filed[] => { | |
| 44 | const name = `${repo.ownerName}/${repo.name}`; | |
| 45 | const own = pinned.filter((p) => p.app === name); | |
| 46 | const file = { repo: name, branch: repo.defaultBranch, path: INFRA_FILE }; | |
| 47 | const out: Filed[] = | |
| 48 | read.kind === "bad" | |
| 49 | ? own.map((p) => ({ kind: "machine", name: p.name, state: "unknown", says: `Not known: ${INFRA_FILE} is refused. ${read.problems[0]}.`, at: { ...file, line: 1, end: 1 }, fields: [], ...placed(nodeOf(p)) })) | |
| 50 | : diffOf(name, read.declared, have).flatMap((c): Filed[] => { | |
| 51 | const d = read.declared.find((x) => x.name === c.name); | |
| 52 | if (c.kind === "unfiled" || d === undefined) return []; | |
| 53 | const [line, end] = read.lines.get(c.name) ?? [1, 1]; | |
| 54 | const fields = [{ label: "Name", value: d.name }, { label: "Account", value: d.account }, { label: "Place", value: d.place }, { label: "Host", value: d.host }].filter((f) => f.value !== ""); | |
| 55 | return [{ kind: "machine", name: c.name, state: STATE[c.kind], says: `${c.says}.`, at: { ...file, line, end }, fields, ...(c.kind === "blocked" ? {} : placed(nodeOf(own.find((p) => p.name === c.name)))) }]; | |
| 56 | }); | |
| 57 | return canRead(app.db, repo, actor) ? out : out.map(hidden); | |
| 58 | }); | |
| 59 | ||
| 60 | const boxes = listBoxes(app.db).filter((b) => only === undefined || b.repo === only); | |
| 61 | const fromBoxes = await Promise.all( | |
| 62 | boxes.map(async (box): Promise<Filed[]> => { | |
| 63 | const machine = nodeOf(pinned.find((p) => p.id === box.pinnedId)); | |
| 64 | const inside = machine?.children ?? []; | |
| 65 | const file = { repo: box.repo, branch: box.branch, path: box.path }; | |
| 66 | const whole = { kind: "box", name: box.name, ...placed(machine) } as const; | |
| 67 | const each = (names: readonly string[], rest: (name: string) => Omit<Filed, "kind" | "name" | "node">): Filed[] => | |
| 68 | names.map((name) => ({ kind: "service", name, ...rest(name), ...placed(inside.find((c) => c.name === name)) })); | |
| 69 | const none = (why: string): Filed[] => { | |
| 70 | const says = { state: "unknown", says: `Not known: ${why}`, fields: [] } as const; | |
| 71 | return [{ ...whole, ...says }, ...each(inside.map((c) => c.name), () => says)]; | |
| 72 | }; | |
| 73 | const read = async (): Promise<Filed[]> => { | |
| 74 | const compose = await readCompose(app, box); | |
| 75 | if (compose === undefined) return none(`${box.path} is not on ${box.branch} of ${box.repo}.`); | |
| 76 | const services = servicesIn(compose.text); | |
| 77 | if (typeof services === "string") return none(`${box.path} on ${box.branch} of ${box.repo} is not read: ${services}.`); | |
| 78 | const heard = servicesOf(app.db, box.id).map((s) => s.seenAt).sort().at(-1) ?? ""; | |
| 79 | const is = boxState({ ran: box.composeSha, head: compose.sha, branch: box.branch, heard: agoWords(heard, now), silent: isSilent(heard, now) }); | |
| 80 | const gone = inside.map((c) => c.name).filter((name) => !services.has(name)); | |
| 81 | return [ | |
| 82 | { ...whole, ...is, at: { ...file, line: 1, end: compose.text.trimEnd().split("\n").length }, fields: [{ label: "Services", value: [...services.keys()].join(", ") }] }, | |
| 83 | ...each([...services.keys()], (name) => { | |
| 84 | const s = services.get(name)!; | |
| 85 | return { ...is, at: { ...file, line: s.lines[0], end: s.lines[1] }, fields: s.fields }; | |
| 86 | }), | |
| 87 | ...each(gone, () => ({ state: "unknown", says: `Not known: ${box.path} on ${box.branch} of ${box.repo} has no service of this name.`, fields: [] })), | |
| 88 | ]; | |
| 89 | }; | |
| 90 | const out = await read(); | |
| 91 | return reads(box.repo) ? out : out.map(hidden); | |
| 92 | }), | |
| 93 | ); | |
| 94 | return [...fromInfra, ...fromBoxes.flat()]; | |
| 95 | } | |
| 96 | ||
| 97 | /** The same by node, as `CloudView.files` holds it. */ | |
| 98 | export async function filesByNode(app: App, actor: User | undefined, whole: CloudNode, now = Date.now()): Promise<ReadonlyMap<string, readonly Filed[]>> { | |
| 99 | const out = new Map<string, Filed[]>(); | |
| 100 | for (const f of await filedIn(app, actor, whole, now)) { | |
| 101 | if (f.node === undefined) continue; | |
| 102 | const key = f.node.join("/"); | |
| 103 | out.set(key, [...(out.get(key) ?? []), f]); | |
| 104 | } | |
| 105 | return out; | |
| 106 | } |
src/cloud/infra_read.ts +36 −21
| @@ -8,10 +8,11 @@ | ||
| 8 | 8 | |
| 9 | 9 | import type { App } from "../app.ts"; |
| 10 | 10 | import { countLine } from "../core/gate_triage.ts"; |
| 11 | import { linesUnder } from "./declared_in.ts"; | |
| 11 | 12 | import { type Change, type Declared, diffOf, type Existing, INFRA_FILE, MAX_BYTES, parseInfra } from "./infra_file.ts"; |
| 12 | 13 | import { listApps } from "../core/apps.ts"; |
| 13 | 14 | import { listPinned, placeIdOf } from "../core/pinned.ts"; |
| 14 | import { getRepoById } from "../core/repos.ts"; | |
| 15 | import { getRepoById, type Repo } from "../core/repos.ts"; | |
| 15 | 16 | import type { User } from "../core/users.ts"; |
| 16 | 17 | import { blobForRender } from "../git/read.ts"; |
| 17 | 18 | import { resolveOid } from "../git/merge.ts"; |
| @@ -36,7 +37,7 @@ function codeSays(changes: readonly Change[]): string { | ||
| 36 | 37 | } |
| 37 | 38 | |
| 38 | 39 | /** 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 | type Read = { readonly kind: "missing" } | { readonly kind: "bad"; readonly problems: readonly string[] } | { readonly kind: "ok"; readonly declared: readonly Declared[]; readonly lines: ReadonlyMap<string, readonly [number, number]> }; | |
| 40 | 41 | /** Per forge (an app object), not per process: two forges must not share what they read. */ |
| 41 | 42 | const readsOf = new WeakMap<App, Map<string, Read>>(); |
| 42 | 43 | const MAX_READS = 1000; |
| @@ -68,41 +69,55 @@ async function readOne(app: App, dir: string, tip: string): Promise<Read> { | ||
| 68 | 69 | let r: Read; |
| 69 | 70 | if (blob.kind === "missing") r = { kind: "missing" }; |
| 70 | 71 | 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 }; | |
| 72 | const text = blob.kind === "text" ? new TextDecoder().decode(blob.body) : ""; | |
| 73 | const parsed = blob.kind === "text" ? parseInfra(text) : err([`${INFRA_FILE} is not a text file under ${MAX_BYTES / 1024} KiB`]); | |
| 74 | r = parsed.ok ? { kind: "ok", declared: parsed.value, lines: linesUnder(text, "machines") } : { kind: "bad", problems: parsed.error }; | |
| 73 | 75 | } |
| 74 | 76 | if (reads.size >= MAX_READS) reads.clear(); |
| 75 | 77 | reads.set(key, r); |
| 76 | 78 | return r; |
| 77 | 79 | } |
| 78 | 80 | |
| 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. | |
| 81 | /** An app's repository with its `infra.json` as its main branch holds it: read, or refused. */ | |
| 82 | export interface InfraFile { | |
| 83 | readonly repo: Repo; | |
| 84 | readonly read: Exclude<Read, { readonly kind: "missing" }>; | |
| 85 | } | |
| 86 | ||
| 87 | /** | |
| 88 | * Every app's `infra.json`, or that of the repository `only` (`owner/name`). Apps are read in | |
| 89 | * parallel; a tip already read costs no blob read, and the tip itself is looked up at most every few | |
| 90 | * seconds. | |
| 91 | */ | |
| 92 | export async function infraFiles(app: App, only?: string): Promise<InfraFile[]> { | |
| 92 | 93 | const found = await Promise.all( |
| 93 | listApps(app.db).map(async (a): Promise<CodeFile | undefined> => { | |
| 94 | listApps(app.db).map(async (a): Promise<InfraFile | undefined> => { | |
| 94 | 95 | const repo = getRepoById(app.db, a.repoId); |
| 95 | if (repo === undefined) return undefined; | |
| 96 | if (repo === undefined || (only !== undefined && only !== `${repo.ownerName}/${repo.name}`)) return undefined; | |
| 96 | 97 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); |
| 97 | 98 | const tip = await tipOf(app, dir, repo.defaultBranch); |
| 98 | 99 | if (tip === undefined) return undefined; |
| 99 | 100 | const read = await readOne(app, dir, tip); |
| 100 | if (read.kind === "missing") return undefined; | |
| 101 | return read.kind === "missing" ? undefined : { repo, read }; | |
| 102 | }), | |
| 103 | ); | |
| 104 | return found.filter((f): f is InfraFile => f !== undefined); | |
| 105 | } | |
| 106 | ||
| 107 | /** The forge's own record of every machine, as a file is compared with it. */ | |
| 108 | export const recorded = (app: App): Existing[] => | |
| 109 | listPinned(app.db).map((p) => ({ name: p.name, app: p.app, account: `${p.target}/${p.account}`, place: placeIdOf(p), host: p.host, state: p.state })); | |
| 110 | ||
| 111 | /** Every app's `infra.json` as it stands on its main branch, diffed against the machines now. */ | |
| 112 | export async function infraCode(app: App, actor: User | undefined): Promise<Result<CodeFile[], string>> { | |
| 113 | if (actor?.isAdmin !== true) return err("not_found"); | |
| 114 | const have = recorded(app); | |
| 115 | return ok( | |
| 116 | (await infraFiles(app)).map(({ repo, read }): CodeFile => { | |
| 101 | 117 | const name = `${repo.ownerName}/${repo.name}`; |
| 102 | 118 | if (read.kind === "bad") return { app: name, problems: read.problems, changes: [], says: `${INFRA_FILE} is refused: ${read.problems[0]}` }; |
| 103 | 119 | const changes = diffOf(name, read.declared, have); |
| 104 | 120 | return { app: name, problems: [], changes, says: codeSays(changes) }; |
| 105 | 121 | }), |
| 106 | 122 | ); |
| 107 | return ok(found.filter((f): f is CodeFile => f !== undefined)); | |
| 108 | 123 | } |
src/cloud/tree.ts +13
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | 13 | import type { Container, Inside } from "./containers.ts"; |
| 14 | import type { Filed } from "./declared_in.ts"; | |
| 14 | 15 | import { dollars } from "./prices.ts"; |
| 15 | 16 | import { PROJECT_CLOUDS, readEveryMs, type AccountRead, type CloudResource, type ProjectView } from "./projects.ts"; |
| 16 | 17 | import { agoWords } from "../kernel/ago.ts"; |
| @@ -368,6 +369,8 @@ export interface CloudView { | ||
| 368 | 369 | /** How many accounts the forge holds; none is its own state. */ |
| 369 | 370 | readonly held: number; |
| 370 | 371 | readonly now: number; |
| 372 | /** What declares each node, by its path joined with slashes (`declared_read.ts`); unset until a door reads it. */ | |
| 373 | readonly files?: ReadonlyMap<string, readonly Filed[]>; | |
| 371 | 374 | } |
| 372 | 375 | |
| 373 | 376 | /** |
| @@ -580,6 +583,16 @@ export interface Fact { | ||
| 580 | 583 | readonly href?: string; |
| 581 | 584 | } |
| 582 | 585 | |
| 586 | /** A node's tabs beside the tree. */ | |
| 587 | export type NodeTab = "facts" | "file"; | |
| 588 | ||
| 589 | /** The tabs a node has, in the order every door shows them; none when its facts are all there is. */ | |
| 590 | export const tabsOf = (n: CloudNode): readonly { readonly id: NodeTab; readonly label: string }[] => | |
| 591 | n.container !== undefined || n.resource?.kind === "machine" ? [{ id: "facts", label: "Facts" }, { id: "file", label: "File" }] : []; | |
| 592 | ||
| 593 | /** The tab asked for, when the node has it; its first otherwise, and for null, nothing asked. */ | |
| 594 | export const tabOf = (n: CloudNode, asked: string | null): NodeTab => (tabsOf(n).find((t) => t.id === asked) ?? tabsOf(n)[0])?.id ?? "facts"; | |
| 595 | ||
| 583 | 596 | /** A container's cost, said where a resource says its own. */ |
| 584 | 597 | export const CONTAINER_COST = "Its cost is inside its machine's."; |
| 585 | 598 |
src/http/infra_routes.ts +7 −3
| @@ -21,7 +21,8 @@ import { flashTo, fragment, page } from "../web/layout.ts"; | ||
| 21 | 21 | import { machineView } from "../actions/machine_view.ts"; |
| 22 | 22 | import { INFRA_CSS, cloudPage, consolePage, endingPage, buildTray, placesRegion, composeForm, infraJs, buildPage, planTray, recordForm, resourcesPage, runningRegion, type ComposeState } from "../web/pages/infra.ts"; |
| 23 | 23 | import { cloudBranch, cloudList, cloudOverview, cloudPane, cloudTotal, cloudTreeJs } from "../web/pages/cloud_tree.ts"; |
| 24 | import { nodeAt, type CloudView } from "../cloud/tree.ts"; | |
| 24 | import { filesByNode } from "../cloud/declared_read.ts"; | |
| 25 | import { nodeAt, tabOf, type CloudView } from "../cloud/tree.ts"; | |
| 25 | 26 | import { pinnedBlock } from "./pinned_routes.ts"; |
| 26 | 27 | import type { Ctx, Handler } from "./context.ts"; |
| 27 | 28 | import type { Router } from "./router.ts"; |
| @@ -76,7 +77,7 @@ function placeOf(pathname: string): string[] | undefined { | ||
| 76 | 77 | |
| 77 | 78 | // GET /infra/-/<cloud>/<account>/<project>/<id>, or any level above it: the tree with that open |
| 78 | 79 | // beside it. `?fragment=1` is what opens alone, `?fragment=explorer` a branch's rows. |
| 79 | function infraResource(ctx: Ctx): Response { | |
| 80 | async function infraResource(ctx: Ctx): Promise<Response> { | |
| 80 | 81 | const denied = guard(ctx); |
| 81 | 82 | if (denied) return denied; |
| 82 | 83 | const path = placeOf(ctx.url.pathname) ?? []; |
| @@ -87,7 +88,10 @@ function infraResource(ctx: Ctx): Response { | ||
| 87 | 88 | const part = ctx.url.searchParams.get("fragment"); |
| 88 | 89 | if (node === undefined) return part === null ? notFoundPage(ctx) : fragment(html``, { status: 404 }); |
| 89 | 90 | if (part === "explorer") return fragment(cloudBranch(tree, node), { request: ctx.request }); |
| 90 | const pane = timePhase(ctx.request, "render", () => cloudPane(tree, node)); | |
| 91 | // Git is read only when the File tab is what was asked for. | |
| 92 | const tab = tabOf(node, ctx.url.searchParams.get("tab")); | |
| 93 | const view = tab !== "file" ? tree : { ...tree, files: await timePhaseAsync(ctx.request, "files", () => filesByNode(ctx.app, ctx.auth.user, tree.whole, tree.now)) }; | |
| 94 | const pane = timePhase(ctx.request, "render", () => cloudPane(view, node, tab)); | |
| 91 | 95 | if (part === "1") return fragment(pane, { request: ctx.request }); |
| 92 | 96 | return page({ ctx, title: `${node.name} · Infrastructure`, wide: true, scriptJs: SCRIPT, styleCss: INFRA_CSS, body: resourcesPage(tree, node.path, pane), noDock: true }); |
| 93 | 97 | } |
src/http/mcp/tools/infra.ts +9 −4
| @@ -1,7 +1,9 @@ | ||
| 1 | 1 | import { cloudLinesFresh } from "../../../actions/cloud_says.ts"; |
| 2 | import { noFileSays } from "../../../cloud/declared_in.ts"; | |
| 3 | import { filesByNode } from "../../../cloud/declared_read.ts"; | |
| 2 | 4 | import { infraCode } from "../../../cloud/infra_read.ts"; |
| 3 | 5 | import { accountReads, projectsOf, projectsSays } from "../../../cloud/projects.ts"; |
| 4 | import { CLOUD_PROPS, CONTAINER_COST, costLine, costliestOf, cutSays, factsOf, findingOf, listedOf, moneyWords, nodeAt, orderSays, pathIn, readingOf, tiesOf, type CloudNode } from "../../../cloud/tree.ts"; | |
| 6 | import { CLOUD_PROPS, CONTAINER_COST, costLine, costliestOf, cutSays, factsOf, findingOf, listedOf, moneyWords, nodeAt, orderSays, pathIn, readingOf, tabsOf, tiesOf, type CloudNode } from "../../../cloud/tree.ts"; | |
| 5 | 7 | import { buildOf, cloudResources, firewallWant, gameWant, planDatabase, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts"; |
| 6 | 8 | import { machineView } from "../../../actions/machine_view.ts"; |
| 7 | 9 | import { bindBucket, readBucket } from "../../../actions/bucket.ts"; |
| @@ -53,7 +55,7 @@ function named(whole: CloudNode, nodes: readonly CloudNode[], args: Args, says: | ||
| 53 | 55 | export const tool: Tool = { |
| 54 | 56 | name: "infra", |
| 55 | 57 | listedTo: "admin", |
| 56 | doc: "`{ action, id?, want?, question?, names?, result?, bucket?, cursor? }`: `list` (its `says` names every machine; with a filter line as `id`, like `kind:volume cost:>10 sort:-created`, the cloud resources it leaves, each with `partOf`, its app, and `attachedTo`; 50 a page, `cursor` for the next), `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 DNS record `{dns: true, name, account, type: A|SRV, host, value, port?}` or a game box `{game: true, where, repo, name?, host?}` or Minecraft Java `{design: minecraft, players, where, domain, dns, repo, eula: true, name?, version?}` (its `compose` comes back with the plan) or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `check` DNS records, `code` (infra.json against the forge's record), `keep`, `begin`, `attach`, `record_result`; `cloud` a machine's name as `id` (its provider's view: power, size, IPs, actions) or a resource's `id` from `list` (as last read; a game box's machine names its `containers`, each by the `id` this takes); `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.", | |
| 58 | doc: "`{ action, id?, want?, question?, names?, result?, bucket?, cursor? }`: `list` (its `says` names every machine; with a filter line as `id`, like `kind:volume cost:>10 sort:-created`, the cloud resources it leaves, each with `partOf`, its app, and `attachedTo`; 50 a page, `cursor` for the next), `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 DNS record `{dns: true, name, account, type: A|SRV, host, value, port?}` or a game box `{game: true, where, repo, name?, host?}` or Minecraft Java `{design: minecraft, players, where, domain, dns, repo, eula: true, name?, version?}` (its `compose` comes back with the plan) or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `check` DNS records, `code` (infra.json against the forge's record), `keep`, `begin`, `attach`, `record_result`; `cloud` a machine's name as `id` (its provider's view: power, size, IPs, actions) or a resource's `id` from `list` (as last read; a game box's machine names its `containers`, each by the `id` this takes; `file` is what declares a machine or a container, env names only); `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.", | |
| 57 | 59 | description: "Machines, spend.", |
| 58 | 60 | inputSchema: { |
| 59 | 61 | type: "object", |
| @@ -159,9 +161,12 @@ export const tool: Tool = { | ||
| 159 | 161 | const n = v.ok ? nodeAt(v.value.root, pathIn(id)) : undefined; |
| 160 | 162 | if (!v.ok || n === undefined) return bad("not_found", "No such cloud resource was read: list with a filter as id names them."); |
| 161 | 163 | const r = n.resource; |
| 162 | if (n.container !== undefined) return good({ says: `${n.name}: ${n.container.state}. ${CONTAINER_COST}`, facts: factsOf(v.value.root, n), readAt: n.readAt }); | |
| 164 | // Which file declares it and whether that agrees, as its File tab says. | |
| 165 | const filed = tabsOf(n).length === 0 ? [] : ((await filesByNode(ctx.app, user, v.value.whole, v.value.now)).get(n.path.join("/")) ?? []); | |
| 166 | const file = tabsOf(n).length === 0 ? {} : { file: filed.length === 0 ? [{ says: noFileSays(n) }] : filed.map(({ node: _, ...f }) => f) }; | |
| 167 | if (n.container !== undefined) return good({ says: `${n.name}: ${n.container.state}. ${CONTAINER_COST}`, facts: factsOf(v.value.root, n), ...file, readAt: n.readAt }); | |
| 163 | 168 | const containers = r === undefined ? [] : n.children.flatMap(({ path, container: c }) => (c === undefined ? [] : [{ id: path.join("/"), name: c.name, state: c.state, cpu: c.cpu, memory: c.memory, uptime: c.uptime, page: c.page }])); |
| 164 | return named(v.value.whole, r === undefined ? costliestOf(n) : [], args, `${n.name}: ${costLine(n) || moneyWords(n.money) || "no resources"}`, { facts: factsOf(v.value.root, n), ...(containers.length === 0 ? {} : { containers }), readAt: n.readAt, trouble: n.trouble.map((t) => t.says), ...(n.note === "" ? {} : { note: n.note }) }); | |
| 169 | return named(v.value.whole, r === undefined ? costliestOf(n) : [], args, `${n.name}: ${costLine(n) || moneyWords(n.money) || "no resources"}`, { facts: factsOf(v.value.root, n), ...file, ...(containers.length === 0 ? {} : { containers }), readAt: n.readAt, trouble: n.trouble.map((t) => t.says), ...(n.note === "" ? {} : { note: n.note }) }); | |
| 165 | 170 | } |
| 166 | 171 | const seen = await machineView(ctx.app, user, id); |
| 167 | 172 | return seen.ok ? good({ says: seen.value.says, cloud: seen.value.view }) : bad("refused", seen.error.message); |
src/tui/screens/cloudtree.ts +52 −3
| @@ -6,7 +6,9 @@ | ||
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | 8 | import { cloudResources, readProjectsNow } from "../../actions/infra.ts"; |
| 9 | import { cloudCell, CLOUD_COLUMNS, cloudName, CONTAINER_COST, containersSay, costLine, createdLabel, cutSays, factsOf, findingOf, isStale, largestCosts, listedOf, moneyMark, nodeAt, orderSays, readingOf, unreadAccounts, unreadLine, unpricedSays, type CloudNode, type CloudView } from "../../cloud/tree.ts"; | |
| 9 | import { cloudCell, CLOUD_COLUMNS, cloudName, CONTAINER_COST, containersSay, costLine, createdLabel, cutSays, factsOf, findingOf, isStale, largestCosts, listedOf, moneyMark, nodeAt, orderSays, readingOf, tabOf, tabsOf, unreadAccounts, unreadLine, unpricedSays, type CloudNode, type CloudView, type NodeTab } from "../../cloud/tree.ts"; | |
| 10 | import { noFileSays, placeSays } from "../../cloud/declared_in.ts"; | |
| 11 | import { filesByNode } from "../../cloud/declared_read.ts"; | |
| 10 | 12 | import { dollars } from "../../cloud/prices.ts"; |
| 11 | 13 | import { keyOf } from "../../web/keymap.ts"; |
| 12 | 14 | import type { Ctx, Screen } from "../app/app.ts"; |
| @@ -41,14 +43,29 @@ const markOf = (n: CloudNode): string => { | ||
| 41 | 43 | /** The most resources an open node names. */ |
| 42 | 44 | const PANE_LINES = 200; |
| 43 | 45 | |
| 46 | const READING = "Reading the files…"; | |
| 47 | /** Without the error's own words: a parser's may quote the file. */ | |
| 48 | const NOT_READ = "The files could not be read. ] and [ come back here and try again."; | |
| 49 | ||
| 50 | /** The File tab: what declares the node, as the page says it; `unset` while the files are not here. */ | |
| 51 | function fileLines(v: CloudView, n: CloudNode, unset: string): string[] { | |
| 52 | if (v.files === undefined) return [unset]; | |
| 53 | const all = v.files.get(keyAt(n.path)) ?? []; | |
| 54 | if (all.length === 0) return [noFileSays(n)]; | |
| 55 | return all.flatMap((f, i) => [...(i > 0 ? [""] : []), f.says, ...(f.at === undefined ? [] : [placeSays(f.at)]), ...f.fields.map((x) => `${x.label.padEnd(12)} ${x.value}`)]); | |
| 56 | } | |
| 57 | ||
| 44 | 58 | /** What a node says when it is open: its cost first, then its facts or its costliest resources. */ |
| 45 | export function cloudLines(v: CloudView, n: CloudNode, width = 80): string[] { | |
| 59 | export function cloudLines(v: CloudView, n: CloudNode, width = 80, tab: NodeTab = tabOf(n, null), unset = READING): string[] { | |
| 46 | 60 | const cost = n.container !== undefined ? CONTAINER_COST : costLine(n) || (n.count === 0 ? "No resources." : unpricedSays(v, n)); |
| 47 | 61 | const head = [n.path.map((p, i) => (i === 0 ? cloudName(p) : (nodeAt(v.whole, n.path.slice(0, i + 1))?.name ?? p))).join(" ▸ "), cost]; |
| 48 | 62 | const read = n.readAt === "" ? "" : `Read ${ago(n.readAt)}${n.trouble.length === 0 && isStale(n.path[0]!, n.readAt, v.now) ? " (old)" : ""}`; |
| 49 | 63 | // A cloud's own line names its accounts' gaps, since there is no link to follow. |
| 50 | 64 | const under = n.path.length >= 2 ? [] : unreadAccounts(n).flatMap((a) => a.trouble.filter((t) => t.gap !== undefined).map((t) => ({ ...t, says: `${a.name}: ${t.says}` }))); |
| 51 | 65 | const trouble = [...n.trouble, ...under].map((t) => `! ${t.says} ${t.label}: a, or ${t.href}`); |
| 66 | const has = tabsOf(n); | |
| 67 | if (has.length > 0) head.push("", has.map((t) => (t.id === tab ? `[${t.label}]` : ` ${t.label} `)).join(" ")); | |
| 68 | if (tab === "file") return [...head, "", ...fileLines(v, n, unset)]; | |
| 52 | 69 | const facts = factsOf(v.whole, n).map((f) => `${f.label.padEnd(12)} ${f.value}`); |
| 53 | 70 | if (n.container !== undefined) return [...head, "", ...facts, read]; |
| 54 | 71 | if (n.resource !== undefined) |
| @@ -78,7 +95,11 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 78 | 95 | let note = ""; |
| 79 | 96 | /** The pane's width as last drawn: a reason is read whole, so its line wraps. */ |
| 80 | 97 | let room = 80; |
| 81 | const lines = (v: CloudView, n: CloudNode): string[] => cloudLines(v, n, room).flatMap((l) => (l.length <= room ? [l] : wrap(l, room))); | |
| 98 | /** The tab asked for; it stays while other nodes open, as far as they have it. */ | |
| 99 | let tab: NodeTab | null = null; | |
| 100 | let filesSay = READING; | |
| 101 | const lines = (v: CloudView, n: CloudNode): string[] => cloudLines(v, n, room, tabOf(n, tab), filesSay).flatMap((l) => (l.length <= room ? [l] : wrap(l, room))); | |
| 102 | let reading: CloudView | undefined; | |
| 82 | 103 | let kept: { readonly query: string; readonly view: CloudView | undefined } | undefined; |
| 83 | 104 | |
| 84 | 105 | /** |
| @@ -91,6 +112,22 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 91 | 112 | } |
| 92 | 113 | return kept.view; |
| 93 | 114 | }; |
| 115 | /** Git is read once a view, when a File tab is first asked for. */ | |
| 116 | const readFiles = (v: CloudView): void => { | |
| 117 | if (v.files !== undefined || reading === v) return; | |
| 118 | reading = v; | |
| 119 | filesSay = READING; | |
| 120 | void filesByNode(f.app, f.user, v.whole, v.now) | |
| 121 | .then( | |
| 122 | (files) => { | |
| 123 | if (kept?.view === v) kept = { ...kept, view: { ...v, files } }; | |
| 124 | }, | |
| 125 | () => { | |
| 126 | if (reading === v) filesSay = NOT_READ; | |
| 127 | }, | |
| 128 | ) | |
| 129 | .then(() => ctx.invalidate()); | |
| 130 | }; | |
| 94 | 131 | const isOpen = (v: CloudView, n: CloudNode): boolean => chosen.get(keyAt(n.path)) ?? (n.level === "cloud" || (n.level === "account" && n.children.length <= 12) || (n.resource === undefined && v.q.text !== "" && v.root.count <= OPEN_ALL)); |
| 95 | 132 | /** The rows on screen, each with its node. */ |
| 96 | 133 | const rows = (v: CloudView): { readonly node: CloudNode; readonly row: Node }[] => { |
| @@ -119,6 +156,7 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 119 | 156 | binding([keyOf("search")], "filter: kind: cloud: region: cost:>10 text"), |
| 120 | 157 | binding([keyOf("sort")], "sort the list: name, cost, -created"), |
| 121 | 158 | binding(["tab"], "tree / what is open"), |
| 159 | binding(["[", "]"], "facts / file"), | |
| 122 | 160 | binding(["a"], "check the account: what was not read, and the fix"), |
| 123 | 161 | binding(["w"], "open on the web"), |
| 124 | 162 | binding(["P"], "read every account now"), |
| @@ -172,6 +210,7 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 172 | 210 | if (right !== undefined) { |
| 173 | 211 | const at = shown ?? all[state.index]?.node; |
| 174 | 212 | if (at !== undefined) { |
| 213 | if (tabOf(at, tab) === "file") readFiles(v); | |
| 175 | 214 | room = Math.max(10, right.w - 2); |
| 176 | 215 | drawLines(s, { ...right, x: right.x + 1, w: Math.max(0, right.w - 1) }, c, pane, lines(v, at).map((text) => [{ text, style: style(c.fg, c.bg) }])); |
| 177 | 216 | } |
| @@ -218,6 +257,16 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 218 | 257 | return true; |
| 219 | 258 | } |
| 220 | 259 | if (n === undefined) return false; |
| 260 | if (e.key === "[" || e.key === "]") { | |
| 261 | const at = (opened === undefined ? undefined : nodeAt(v.root, opened)) ?? n; | |
| 262 | const has = tabsOf(at); | |
| 263 | if (has.length === 0) return false; | |
| 264 | if (filesSay === NOT_READ) reading = undefined; | |
| 265 | const i = has.findIndex((t) => t.id === tabOf(at, tab)); | |
| 266 | tab = has[(i + (e.key === "]" ? 1 : has.length - 1)) % has.length]!.id; | |
| 267 | pane.top = 0; | |
| 268 | return true; | |
| 269 | } | |
| 221 | 270 | if (e.key === "a") { |
| 222 | 271 | const at = (focus === "pane" && opened !== undefined ? nodeAt(v.root, opened) : undefined) ?? n; |
| 223 | 272 | // On a cloud, its one account, else the first with something to check. |
src/web/declares.ts added +51
| @@ -0,0 +1,51 @@ | ||
| 1 | /** | |
| 2 | * The file half of a cloud node (#17532): a node's File tab, and the line on a file's own page that | |
| 3 | * says what it declares. Both draw `cloud/declared_read.ts` and add nothing; a forge admin's alone. | |
| 4 | */ | |
| 5 | ||
| 6 | import type { App } from "../app.ts"; | |
| 7 | import { cloudResources } from "../actions/infra.ts"; | |
| 8 | import { declaresSay, noFileSays, placeHref, placeSays, type Filed } from "../cloud/declared_in.ts"; | |
| 9 | import { filedIn } from "../cloud/declared_read.ts"; | |
| 10 | import { INFRA_FILE } from "../cloud/infra_file.ts"; | |
| 11 | import type { CloudNode, CloudView } from "../cloud/tree.ts"; | |
| 12 | import { listApps } from "../core/apps.ts"; | |
| 13 | import type { Repo } from "../core/repos.ts"; | |
| 14 | import type { User } from "../core/users.ts"; | |
| 15 | import { listBoxes } from "../games/store.ts"; | |
| 16 | import { html, type Html } from "./html.ts"; | |
| 17 | import { cloudHref } from "./pages/cloud_tree.ts"; | |
| 18 | ||
| 19 | /** What declares a node: each declaration's state, where it is, and what it says. */ | |
| 20 | export function fileTab(v: CloudView, n: CloudNode): Html { | |
| 21 | const all = v.files?.get(n.path.join("/")) ?? []; | |
| 22 | if (all.length === 0) return html`<p data-no-file>${noFileSays(n)}</p>`; | |
| 23 | return html`${all.map( | |
| 24 | (f) => html`<section data-filed="${f.state}"> | |
| 25 | <p>${f.says}</p> | |
| 26 | ${f.at === undefined ? null : html`<p><a class="mono" href="${placeHref(f.at)}">${placeSays(f.at)}</a></p>`} | |
| 27 | ${f.fields.length === 0 ? null : html`<dl class="cloud-facts">${f.fields.map((x) => html`<div><dt>${x.label}</dt><dd class="mono">${x.value}</dd></div>`)}</dl>`} | |
| 28 | </section>`, | |
| 29 | )}`; | |
| 30 | } | |
| 31 | ||
| 32 | /** The most nodes the line on a file's page names. */ | |
| 33 | const NAMED = 12; | |
| 34 | ||
| 35 | /** | |
| 36 | * "Declares 2: 1 as the forge knows them, 1 to add", each a link to its node. Only on the branch | |
| 37 | * that is followed, so an older commit's page never speaks of what runs now. | |
| 38 | */ | |
| 39 | export async function declaresLine(app: App, user: User | undefined, repo: Repo, ref: string, path: string): Promise<Html | undefined> { | |
| 40 | if (user?.isAdmin !== true) return undefined; | |
| 41 | const name = `${repo.ownerName}/${repo.name}`; | |
| 42 | const infra = path === INFRA_FILE && ref === repo.defaultBranch && listApps(app.db).some((a) => a.repoId === repo.id); | |
| 43 | if (!infra && !listBoxes(app.db).some((b) => b.repo === name && b.branch === ref && b.path === path)) return undefined; | |
| 44 | const v = cloudResources(app, user, ""); | |
| 45 | if (!v.ok) return undefined; | |
| 46 | // A box is its whole file; its services are what the file declares. | |
| 47 | const all = (await filedIn(app, user, v.value.whole, v.value.now, name)).filter((f) => f.kind !== "box" && f.at?.branch === ref && f.at.path === path); | |
| 48 | if (all.length === 0) return undefined; | |
| 49 | const link = (f: Filed): Html => (f.node === undefined ? html`${f.name}` : html`<a href="${cloudHref(f.node, v.value.q, "file")}">${f.name}</a>`); | |
| 50 | return html`<p class="muted small mb" data-declares>${declaresSay(all)}. ${all.slice(0, NAMED).map((f, i) => html`${i > 0 ? ", " : ""}${link(f)}`)}${all.length > NAMED ? ` and ${all.length - NAMED} more` : ""}</p>`; | |
| 51 | } |
src/web/pages/cloud_tree.ts +18 −8
| @@ -37,12 +37,15 @@ import { | ||
| 37 | 37 | unreadAccounts, |
| 38 | 38 | unreadSays, |
| 39 | 39 | nodeAt, |
| 40 | tabOf, | |
| 41 | tabsOf, | |
| 40 | 42 | taxSays, |
| 41 | 43 | unpricedSays, |
| 42 | 44 | unused, |
| 43 | 45 | type CloudNode, |
| 44 | 46 | type CloudQuery, |
| 45 | 47 | type CloudView, |
| 48 | type NodeTab, | |
| 46 | 49 | type Tie, |
| 47 | 50 | type Trouble, |
| 48 | 51 | } from "../../cloud/tree.ts"; |
| @@ -52,7 +55,8 @@ import { html, raw, type Html } from "../html.ts"; | ||
| 52 | 55 | import { icon } from "../icons.ts"; |
| 53 | 56 | import { keyOf } from "../keymap.ts"; |
| 54 | 57 | import { listTable } from "../list.ts"; |
| 55 | import { btn, copyField, crumbs, hintAttr, row, rowList, time } from "../ui.ts"; | |
| 58 | import { btn, copyField, crumbs, hintAttr, row, rowList, tabs, time } from "../ui.ts"; | |
| 59 | import { fileTab } from "../declares.ts"; | |
| 56 | 60 | import { codeLayout, COLUMN_WINDOW } from "./explorer.ts"; |
| 57 | 61 | import { treeStep } from "./family_tree_js.ts"; |
| 58 | 62 | |
| @@ -68,8 +72,10 @@ const OPEN_ACCOUNT = 12; | ||
| 68 | 72 | const withQuery = (path: string, q: CloudQuery): string => (q.text === "" ? path : `${path}?q=${encodeURIComponent(q.text)}`); |
| 69 | 73 | |
| 70 | 74 | /** A node's page. */ |
| 71 | export const cloudHref = (path: readonly string[], q: CloudQuery): string => | |
| 72 | withQuery(path.length === 0 ? "/infra" : `/infra/-/${path.map((p) => encodeURIComponent(p).replaceAll("%3A", ":")).join("/")}`, q); | |
| 75 | export const cloudHref = (path: readonly string[], q: CloudQuery, tab?: NodeTab): string => { | |
| 76 | const at = withQuery(path.length === 0 ? "/infra" : `/infra/-/${path.map((p) => encodeURIComponent(p).replaceAll("%3A", ":")).join("/")}`, q); | |
| 77 | return tab === undefined ? at : `${at}${at.includes("?") ? "&" : "?"}tab=${tab}`; | |
| 78 | }; | |
| 73 | 79 | |
| 74 | 80 | /** |
| 75 | 81 | * A sum at the end of a row: an exception is marked, quietly, and said in full to a screen reader. |
| @@ -247,8 +253,8 @@ function billLine(n: CloudNode): Html { | ||
| 247 | 253 | return html`<p class="muted small" data-bill>${now === undefined ? null : html`${monthName(now.from)} so far ${dollars(now.cents)} · `}${taxSays(last ?? now) === "" ? null : html`${taxSays(last ?? now)} · `}Before credits · Bill read ${time(n.read!.bill!.readAt)}</p>`; |
| 248 | 254 | } |
| 249 | 255 | |
| 250 | /** What is open beside the tree: a branch's costliest resources, or one resource's facts. */ | |
| 251 | export function cloudPane(v: CloudView, n: CloudNode): Html { | |
| 256 | /** What is open beside the tree: a branch's costliest resources, or one resource's facts or file. */ | |
| 257 | export function cloudPane(v: CloudView, n: CloudNode, tab: NodeTab = tabOf(n, null)): Html { | |
| 252 | 258 | const r = n.resource; |
| 253 | 259 | if (r === undefined && n.container === undefined) { |
| 254 | 260 | return html`<section id="code-pane" data-path="${n.name}" data-cloud-pane="${n.level}"> |
| @@ -263,11 +269,15 @@ export function cloudPane(v: CloudView, n: CloudNode): Html { | ||
| 263 | 269 | ${listed(v, n)} |
| 264 | 270 | </section>`; |
| 265 | 271 | } |
| 266 | const facts = linkedFacts(v.whole, n); | |
| 267 | return html`<section id="code-pane" data-path="${n.name}" data-cloud-pane="resource"> | |
| 268 | ${trail(v, n)} | |
| 272 | const has = tabsOf(n); | |
| 273 | const head = html`${trail(v, n)} | |
| 269 | 274 | <h2>${n.name}</h2> |
| 270 | 275 | ${sum(v, n)} |
| 276 | ${has.length === 0 ? null : tabs(has.map((t) => ({ label: t.label, href: cloudHref(n.path, v.q, t.id), current: t.id === tab })), `${n.name}'s tabs`)}`; | |
| 277 | if (tab === "file") return html`<section id="code-pane" data-path="${n.name}" data-cloud-pane="resource">${head}${fileTab(v, n)}</section>`; | |
| 278 | const facts = linkedFacts(v.whole, n); | |
| 279 | return html`<section id="code-pane" data-path="${n.name}" data-cloud-pane="resource"> | |
| 280 | ${head} | |
| 271 | 281 | <dl class="cloud-facts"> |
| 272 | 282 | ${facts.filter((f) => f.label !== "Id").map((f) => html`<div><dt>${f.label}</dt><dd>${f.href !== undefined ? html`<a href="${f.href}">${f.value}</a>` : f.tie === undefined || f.tie.to.length === 0 ? f.value : ends(f.tie, v)}</dd></div>`)} |
| 273 | 283 | ${r === undefined ? null : html`<div><dt>${createdLabel(r)}</dt><dd>${r.createdAt === "" ? "not known" : time(r.createdAt, { date: true })}</dd></div>`} |
src/web/pages/repo.ts +6
| @@ -171,6 +171,7 @@ import { | ||
| 171 | 171 | TREE_ALL_WINDOW, |
| 172 | 172 | treeWindow, |
| 173 | 173 | } from "./explorer.ts"; |
| 174 | import { declaresLine } from "../declares.ts"; | |
| 174 | 175 | |
| 175 | 176 | export { crumbsFor, loadRepo, repoBase }; |
| 176 | 177 | export { pathCrumbs, refMenu, refSet, refSetFrom } from "./refs.ts"; |
| @@ -1333,6 +1334,8 @@ export function renderBlob( | ||
| 1333 | 1334 | rows?: CodeRows; |
| 1334 | 1335 | /** The files at the ref, for a renderer that links paths. */ |
| 1335 | 1336 | exists?: (path: string) => boolean; |
| 1337 | /** What the file declares in the cloud tree, for a forge admin. */ | |
| 1338 | declares?: Html; | |
| 1336 | 1339 | }, |
| 1337 | 1340 | ): Html { |
| 1338 | 1341 | const base = scope.base; |
| @@ -1443,6 +1446,7 @@ export function renderBlob( | ||
| 1443 | 1446 | () => html`<p class="muted small mb">Showing the source: ${fellBack}</p>`, |
| 1444 | 1447 | )} |
| 1445 | 1448 | ${when(plainWhy !== undefined, () => html`<p class="muted small mb" data-plain-why>${plainWhy}</p>`)} |
| 1449 | ${o.declares ?? null} | |
| 1446 | 1450 | ${content} |
| 1447 | 1451 | </div>`; |
| 1448 | 1452 | } |
| @@ -2044,7 +2048,9 @@ export async function blobPage(ctx: Ctx): Promise<Response> { | ||
| 2044 | 2048 | if (rows !== undefined) notePhase(ctx.request, "highlight", performance.now() - began); |
| 2045 | 2049 | } |
| 2046 | 2050 | const exists = needsPaths(kindByName(path)) ? await pathsAt(scope, ref) : undefined; |
| 2051 | const declares = await declaresLine(ctx.app, ctx.auth.user, repo, ref, path); | |
| 2047 | 2052 | const pane = renderBlob(scope, { |
| 2053 | ...(declares !== undefined ? { declares } : {}), | |
| 2048 | 2054 | ...(rows !== undefined ? { rows } : {}), |
| 2049 | 2055 | ...(exists !== undefined ? { exists } : {}), |
| 2050 | 2056 | refs, |
test/cloud-files.test.ts added +296
| @@ -0,0 +1,296 @@ | ||
| 1 | /** | |
| 2 | * The File tab and the "Declares" line (#17532): a machine or a container names the lines of the file | |
| 3 | * that declares it, and the file names its nodes, at the page, the terminal and the `infra` tool | |
| 4 | * alike. Environment names only, at every door; nothing of a file the reader may not read; and what | |
| 5 | * is not known says so. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, beforeEach, expect, onTestFinished, 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 { cloudResources } from "../src/actions/infra.ts"; | |
| 13 | import { commitToBranch } from "../src/actions/repos.ts"; | |
| 14 | import { createApp, type App } from "../src/app.ts"; | |
| 15 | import { boxState, linesUnder, servicesIn } from "../src/cloud/declared_in.ts"; | |
| 16 | import { filedIn, filesByNode } from "../src/cloud/declared_read.ts"; | |
| 17 | import { nodeAt, tabOf, tabsOf, type CloudView } from "../src/cloud/tree.ts"; | |
| 18 | import { createApp as createAppRecord } from "../src/core/apps.ts"; | |
| 19 | import { insertPinned, setRemote } from "../src/core/pinned.ts"; | |
| 20 | import { createRepo, type Repo } from "../src/core/repos.ts"; | |
| 21 | import { createSession } from "../src/core/sessions.ts"; | |
| 22 | import { createToken } from "../src/core/tokens.ts"; | |
| 23 | import { createUser, type User } from "../src/core/users.ts"; | |
| 24 | import { readCompose } from "../src/games/compose.ts"; | |
| 25 | import { boxNamed, createGameBox, recordSync } from "../src/games/store.ts"; | |
| 26 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 27 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 28 | import { cloudLines, cloudTreeScreen } from "../src/tui/screens/cloudtree.ts"; | |
| 29 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 30 | import { mcpTool } from "./helpers/mcp.ts"; | |
| 31 | import { settleApp } from "./helpers/tui.ts"; | |
| 32 | ||
| 33 | const COMPOSE = `# the network | |
| 34 | services: | |
| 35 | hub: | |
| 36 | image: itzg/minecraft-server:java21 | |
| 37 | ports: ["25565:25565"] | |
| 38 | environment: | |
| 39 | MOTD: hidden-motd-value | |
| 40 | RCON_PASSWORD: "hidden-rcon-value" | |
| 41 | ||
| 42 | bot: | |
| 43 | build: https://[email protected]/bot.git | |
| 44 | environment: | |
| 45 | - BOT_KEY=hidden-bot-value | |
| 46 | volumes: {} | |
| 47 | `; | |
| 48 | const SECRET = /hidden-/; | |
| 49 | const PLACE = "hetzner:nbg1:cx43"; | |
| 50 | const INFRA = `{ | |
| 51 | "version": 1, | |
| 52 | "machines": [ | |
| 53 | { "name": "shop-1", "account": "hetzner/eu", "place": "${PLACE}" }, | |
| 54 | { "name": "shop-2", "account": "hetzner/eu", "place": "${PLACE}" } | |
| 55 | ] | |
| 56 | } | |
| 57 | `; | |
| 58 | const AT = ["hetzner", "eu", "games"]; | |
| 59 | const BOX = [...AT, "machine:77"]; | |
| 60 | const HUB = [...BOX, "container:hub"]; | |
| 61 | const SHOP = [...AT, "machine:78"]; | |
| 62 | const LOOSE = [...AT, "machine:79"]; | |
| 63 | const THEIRS = [...AT, "machine:80"]; | |
| 64 | ||
| 65 | let dir = ""; | |
| 66 | let app: App; | |
| 67 | let servers: Servers; | |
| 68 | let alice: User; | |
| 69 | let bob: User; | |
| 70 | let game: Repo; | |
| 71 | let shop: Repo; | |
| 72 | ||
| 73 | const person = async (username: string): Promise<User> => { | |
| 74 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst: true }); | |
| 75 | if (!made.ok) throw new Error(made.error); | |
| 76 | return made.value; | |
| 77 | }; | |
| 78 | const repo = async (owner: User, name: string, visibility: "public" | "private", path: string, content: string): Promise<Repo> => { | |
| 79 | const r = await createRepo(app.db, app.reposRoot, { ownerId: owner.id, name, visibility }); | |
| 80 | if (!r.ok) throw new Error(String(r.error)); | |
| 81 | await write(owner, r.value, path, content); | |
| 82 | return r.value; | |
| 83 | }; | |
| 84 | const write = async (who: User, r: Repo, path: string, content: string): Promise<void> => { | |
| 85 | const c = await commitToBranch(app, who, r, { message: `write ${path}`, files: [{ path, content }] }); | |
| 86 | if (!c.ok) throw new Error(JSON.stringify(c.error)); | |
| 87 | }; | |
| 88 | const sync = (box: string, composeSha: string, at = new Date()): void => | |
| 89 | void recordSync(app.db, boxNamed(app.db, box)!, { composeSha, services: ["hub", "bot"].map((name) => ({ name, state: "running", health: "", startedAt: "", cpuPct: 1, memMiB: 100 })) }, at); | |
| 90 | const head = async (box = "mc"): Promise<string> => (await readCompose(app, boxNamed(app.db, box)!))!.sha; | |
| 91 | const view = async (): Promise<CloudView> => { | |
| 92 | const v = cloudResources(app, alice, ""); | |
| 93 | if (!v.ok) throw new Error(v.error); | |
| 94 | return { ...v.value, files: await filesByNode(app, alice, v.value.whole) }; | |
| 95 | }; | |
| 96 | const filed = async (path: string[]) => (await view()).files!.get(path.join("/")) ?? []; | |
| 97 | const get = async (path: string, who: User = alice): Promise<string> => (await fetch(`${servers.url}${path}`, { headers: { cookie: `forge_session=${createSession(app.db, who.id).token}` } })).text(); | |
| 98 | const pane = (page: string): string => page.split('id="code-pane"')[1]!; | |
| 99 | const nodeUrl = (path: string[], rest = "?tab=file"): string => `/infra/-/${path.map(encodeURIComponent).join("/")}${rest}`; | |
| 100 | const pin = (name: string, of: string, remote: string, boots: "game" | "forge") => { | |
| 101 | const p = insertPinned(app.db, { name, target: "hetzner", account: "eu", app: of, source: "", version: "v1.0.0", config: {}, host: `${name}.example.com`, claimHash: "", claimExpires: "", datacenter: "nbg1", size: "cx43", boots }, alice.id); | |
| 102 | setRemote(app.db, name, { remote }); | |
| 103 | return p; | |
| 104 | }; | |
| 105 | ||
| 106 | beforeAll(async () => { | |
| 107 | dir = mkdtempSync(join(tmpdir(), "forge-cloud-files-")); | |
| 108 | app = createApp({ dataDir: dir, port: 0 }); | |
| 109 | servers = await serve(app); | |
| 110 | alice = await person("alice"); | |
| 111 | bob = await person("bob"); | |
| 112 | const now = new Date().toISOString(); | |
| 113 | app.db.run("INSERT INTO cloud_account (provider, name, summary, write_allowed) VALUES ('hetzner', 'eu', '', 0)"); | |
| 114 | app.db.run("INSERT INTO cloud_project (cloud_provider, cloud_account_id, cloud_project_id, name, is_default, read_at) VALUES ('hetzner', 'eu', 'games', 'games', 1, ?1)", [now]); | |
| 115 | // The unfiled machine has a declared machine's name: a name is never what joins them. | |
| 116 | for (const [id, name] of [["machine:77", "mc"], ["machine:78", "web"], ["machine:79", "shop-2"], ["machine:80", "theirs"], ["volume:5", "disk"]]) | |
| 117 | app.db.run( | |
| 118 | "INSERT INTO cloud_resource (cloud_provider, cloud_account_id, cloud_resource_id, cloud_project_id, kind, name, cloud_region, host_type, label, made_by, cents, created_at, read_at, state, attached_to, made_from) VALUES ('hetzner', 'eu', ?1, 'games', ?2, ?3, 'nbg1', 'cx43', '', 'found', 1200, ?4, ?4, 'running', '', '')", | |
| 119 | [id!, id!.split(":")[0]!, name!, now], | |
| 120 | ); | |
| 121 | game = await repo(alice, "game", "public", "docker-compose.yml", COMPOSE); | |
| 122 | shop = await repo(alice, "shop", "public", "infra.json", INFRA); | |
| 123 | const secret = await repo(bob, "secret", "private", "docker-compose.yml", COMPOSE); | |
| 124 | app.db.run("INSERT INTO origin (id, user_id, kind, api_url, web_url, login, token_enc, read_only) VALUES ('o1', ?1, 'github', 'https://api.example.com', 'https://example.com', 'octo', 'x', 1)", [bob.id]); | |
| 125 | app.db.run("UPDATE repo SET origin_id = 'o1', origin_full_name = 'octo/secret' WHERE id = ?1", [secret.id]); | |
| 126 | createAppRecord(app.db, { repoId: shop.id, slug: "shop", access: "public" }); | |
| 127 | createGameBox(app.db, { name: "mc", repo: "alice/game", pinnedId: pin("mc", "alice/game", "77", "game").id }); | |
| 128 | createGameBox(app.db, { name: "theirs", repo: "bob/secret", pinnedId: pin("theirs", "bob/secret", "80", "game").id }); | |
| 129 | pin("shop-1", "alice/shop", "78", "forge"); | |
| 130 | }, 60_000); | |
| 131 | beforeEach(async () => { | |
| 132 | app.db.run("DELETE FROM game_service"); | |
| 133 | sync("mc", await head()); | |
| 134 | sync("theirs", await head("theirs")); | |
| 135 | }); | |
| 136 | afterAll(async () => { | |
| 137 | servers.stop(); | |
| 138 | app.close(); | |
| 139 | await rm(dir, { recursive: true, force: true }); | |
| 140 | }); | |
| 141 | ||
| 142 | test("each entry's own lines, in YAML and in JSON, without the blank after it", () => { | |
| 143 | expect([...linesUnder(COMPOSE, "services")]).toEqual([["hub", [3, 8]], ["bot", [10, 13]]]); | |
| 144 | expect([...linesUnder(INFRA, "machines")]).toEqual([["shop-1", [4, 4]], ["shop-2", [5, 5]]]); | |
| 145 | expect([...linesUnder("a: [", "a")]).toEqual([]); | |
| 146 | expect(servicesIn("services: [")).toBe("it is not valid YAML"); | |
| 147 | }); | |
| 148 | ||
| 149 | test("a machine and a container have Facts and File, in that order; nothing else has tabs", async () => { | |
| 150 | const v = await view(); | |
| 151 | for (const path of [BOX, HUB]) expect(tabsOf(nodeAt(v.whole, path)!).map((t) => t.id)).toEqual(["facts", "file"]); | |
| 152 | for (const path of [AT, [...AT, "volume:5"]]) expect(tabsOf(nodeAt(v.whole, path)!)).toEqual([]); | |
| 153 | expect(tabOf(nodeAt(v.whole, HUB)!, "nonsense")).toBe("facts"); | |
| 154 | expect(tabOf(nodeAt(v.whole, AT)!, "file")).toBe("facts"); | |
| 155 | }); | |
| 156 | ||
| 157 | test("a container is its service's lines, and says the box runs them only at the commit it runs", async () => { | |
| 158 | const sha = await head(); | |
| 159 | expect(await filed(HUB)).toMatchObject([{ kind: "service", name: "hub", state: "same", says: `The box runs main as it is, at ${sha.slice(0, 10)}.`, at: { repo: "alice/game", branch: "main", path: "docker-compose.yml", line: 3, end: 8 } }]); | |
| 160 | expect((await filed(HUB))[0]!.fields).toContainEqual({ label: "Environment", value: "MOTD, RCON_PASSWORD (names only)" }); | |
| 161 | expect((await filed(BOX)).map((f) => [f.kind, f.state])).toEqual([["box", "same"]]); | |
| 162 | // The branch moves on: the same lines are no longer what is said to run. | |
| 163 | await write(alice, game, "README.md", "moved\n"); | |
| 164 | const next = await head(); | |
| 165 | expect(next).not.toBe(sha); | |
| 166 | expect((await filed(HUB))[0]).toMatchObject({ state: "ahead", says: `main is at ${next.slice(0, 10)} and the box runs ${sha.slice(0, 10)}, so these lines may not be what runs.` }); | |
| 167 | }); | |
| 168 | ||
| 169 | test("a box that is silent, or has not said what it runs, is not known", async () => { | |
| 170 | const sha = await head(); | |
| 171 | app.db.run("DELETE FROM game_service"); | |
| 172 | sync("mc", sha, new Date(Date.now() - 3 * 3_600_000)); | |
| 173 | expect((await filed(BOX))[0]).toMatchObject({ state: "unknown", says: `Not known: the box was last heard 3 hours ago, and ran ${sha.slice(0, 10)} then.` }); | |
| 174 | app.db.run("DELETE FROM game_service"); | |
| 175 | sync("mc", ""); | |
| 176 | expect((await filed(BOX))[0]!.says).toBe("Not known: the box has not said which commit it runs."); | |
| 177 | // What a box sends as its commit is never drawn unless it is one. | |
| 178 | expect(boxState({ ran: "\u001b[31mred", head: sha, branch: "main", heard: "now", silent: false }).says).not.toContain("red"); | |
| 179 | }); | |
| 180 | ||
| 181 | test("infra.json's machine is joined by the forge's own row, never by a name", async () => { | |
| 182 | const at = { repo: "alice/shop", branch: "main", path: "infra.json", line: 4, end: 4 }; | |
| 183 | expect(await filed(SHOP)).toMatchObject([{ kind: "machine", name: "shop-1", state: "same", says: "shop-1 is as the forge recorded it.", at }]); | |
| 184 | expect(await filed(LOOSE)).toEqual([]); | |
| 185 | const all = await filedIn(app, alice, (await view()).whole, Date.now(), "alice/shop"); | |
| 186 | expect(all.map((f) => [f.name, f.state, f.node?.join("/")])).toEqual([["shop-1", "same", SHOP.join("/")], ["shop-2", "add", undefined]]); | |
| 187 | expect(await get(nodeUrl(LOOSE))).toContain("In no file the forge reads"); | |
| 188 | }); | |
| 189 | ||
| 190 | test("a refused infra.json leaves its machines not known, with the reason", async () => { | |
| 191 | const bad = await repo(alice, "bad", "public", "infra.json", INFRA.replace('"version": 1', '"version": 2')); | |
| 192 | createAppRecord(app.db, { repoId: bad.id, slug: "bad", access: "public" }); | |
| 193 | pin("bad-1", "alice/bad", "79", "forge"); | |
| 194 | expect(await filed(LOOSE)).toMatchObject([{ name: "bad-1", state: "unknown", says: "Not known: infra.json is refused. version: must be 1." }]); | |
| 195 | }); | |
| 196 | ||
| 197 | test("in a file you cannot read: nothing of the file, its repository or its names is shown", async () => { | |
| 198 | // An app's token that acts for an admin reads no read-only mirror it was not granted (#10521). | |
| 199 | const asApp: User = { ...alice, appId: "app-1" }; | |
| 200 | const v = await view(); | |
| 201 | for (const path of [THEIRS, [...THEIRS, "container:hub"]]) { | |
| 202 | const files = await filesByNode(app, asApp, v.whole); | |
| 203 | expect(files.get(path.join("/"))).toEqual([{ kind: path === THEIRS ? "box" : "service", name: "", state: "unknown", says: "In a file you cannot read.", fields: [], node: path }]); | |
| 204 | const shown = cloudLines({ ...v, files }, nodeAt(v.whole, path)!, 80, "file").join("\n"); | |
| 205 | expect(shown).toContain("In a file you cannot read."); | |
| 206 | for (const word of ["bob/secret", "docker-compose", "RCON_PASSWORD"]) expect(shown).not.toContain(word); | |
| 207 | } | |
| 208 | expect((await filed(THEIRS))[0]!.at?.repo).toBe("bob/secret"); | |
| 209 | }); | |
| 210 | ||
| 211 | test("a repository that is gone is said to be, not called unreadable", async () => { | |
| 212 | app.db.run("UPDATE game_box SET repo = 'bob/gone' WHERE name = 'theirs'"); | |
| 213 | expect((await filed(THEIRS))[0]!.says).toBe("Not known: docker-compose.yml is not on main of bob/gone."); | |
| 214 | app.db.run("UPDATE game_box SET repo = 'bob/secret' WHERE name = 'theirs'"); | |
| 215 | }); | |
| 216 | ||
| 217 | test("no environment value and no build address at any door", async () => { | |
| 218 | const token = createToken(app.db, alice.id, "files", "admin").token; | |
| 219 | for (const path of [BOX, HUB, [...BOX, "container:bot"]]) { | |
| 220 | const v = await view(); | |
| 221 | const tool = (await mcpTool(servers.url, token, "infra", { action: "cloud", id: path.join("/") })).value; | |
| 222 | const page = pane(await get(nodeUrl(path))); | |
| 223 | const text = cloudLines(v, nodeAt(v.whole, path)!, 80, "file").join("\n"); | |
| 224 | for (const shown of [page, text, JSON.stringify(tool), JSON.stringify([...v.files!])]) expect(shown).not.toMatch(SECRET); | |
| 225 | // Each door says the same state and the same place. | |
| 226 | const says = v.files!.get(path.join("/"))![0]!.says; | |
| 227 | for (const shown of [page, text, JSON.stringify(tool.file)]) expect(shown).toContain(says); | |
| 228 | } | |
| 229 | expect(pane(await get(nodeUrl(HUB)))).toContain('href="/alice/game/blob/main/docker-compose.yml?view=source#L3-L8"'); | |
| 230 | expect(pane(await get(nodeUrl([...BOX, "container:bot"])))).toContain("BOT_KEY"); | |
| 231 | }); | |
| 232 | ||
| 233 | test("the page: File is a link tab, Facts stays the first, and a filter stays in the link", async () => { | |
| 234 | const facts = pane(await get(nodeUrl(HUB, "?q=kind:machine"))); | |
| 235 | expect(facts).toContain("container:hub?q=kind%3Amachine&tab=file"); | |
| 236 | // Each tab names itself, so each can be linked whichever is first; with none asked, the first is open. | |
| 237 | expect(facts).toContain("container:hub?q=kind%3Amachine&tab=facts"); | |
| 238 | expect(pane(await get(nodeUrl(HUB, "?tab=facts")))).toContain("Uptime"); | |
| 239 | expect(facts).toContain("Uptime"); | |
| 240 | expect(facts).not.toContain("data-filed"); | |
| 241 | expect(pane(await get(nodeUrl(HUB)))).not.toContain("Uptime"); | |
| 242 | // Only an admin has the tree. | |
| 243 | expect(await get(nodeUrl(HUB), bob)).not.toContain("docker-compose.yml"); | |
| 244 | }); | |
| 245 | ||
| 246 | test("the file's page says what it declares to an admin alone, on the branch that is followed", async () => { | |
| 247 | const line = async (path: string, who: User = alice): Promise<string | undefined> => /<p class="muted small mb" data-declares>.*?<\/p>/s.exec(await get(path, who))?.[0]; | |
| 248 | const compose = await line("/alice/game/blob/main/docker-compose.yml"); | |
| 249 | expect(compose).toContain("Declares 2: 2 as the forge knows them."); | |
| 250 | expect(compose).toContain('href="/infra/-/hetzner/eu/games/machine:77/container:hub?tab=file"'); | |
| 251 | const infra = await line("/alice/shop/blob/main/infra.json"); | |
| 252 | expect(infra).toContain("Declares 2: 1 as the forge knows them, 1 to add."); | |
| 253 | expect(infra).toContain('machine:78?tab=file">shop-1</a>'); | |
| 254 | expect(await line("/alice/game/blob/main/docker-compose.yml", bob)).toBeUndefined(); | |
| 255 | expect(await line(`/alice/game/blob/${await head()}/docker-compose.yml`)).toBeUndefined(); | |
| 256 | expect(await line("/alice/game/blob/main/README.md")).toBeUndefined(); | |
| 257 | }); | |
| 258 | ||
| 259 | /** The terminal's cloud screen with the machine "web" open; closed when the test ends. */ | |
| 260 | const openWeb = async () => { | |
| 261 | const terminal = headlessTerminal(200, 40); | |
| 262 | const { app: tui, session } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice }, { terminal, exitHooks: false }); | |
| 263 | onTestFinished(() => void tui.stop?.()); | |
| 264 | tui.start(); | |
| 265 | tui.ctx.push(cloudTreeScreen(session, tui.ctx)); | |
| 266 | await settleApp(tui); | |
| 267 | const press = async (keys: string): Promise<string> => { | |
| 268 | for (const k of keys) terminal.feed(k); | |
| 269 | await settleApp(tui); | |
| 270 | await settleApp(tui); | |
| 271 | return tui.screen.toText(); | |
| 272 | }; | |
| 273 | terminal.feed("/kind:machine web\r"); | |
| 274 | await settleApp(tui); | |
| 275 | return { press, first: await press("jjjl") }; | |
| 276 | }; | |
| 277 | ||
| 278 | test("the terminal: ] goes to File and [ back, and git is read for it alone", async () => { | |
| 279 | const { press, first } = await openWeb(); | |
| 280 | expect(first).toContain("[Facts] File"); | |
| 281 | expect(await press("]")).toContain("infra.json, line 4, on main of alice/shop"); | |
| 282 | expect(await press("[")).toContain("[Facts] File"); | |
| 283 | }); | |
| 284 | ||
| 285 | test("the terminal: files that could not be read are said to be, and ] tries again", async () => { | |
| 286 | const { press } = await openWeb(); | |
| 287 | app.db.run("ALTER TABLE game_box RENAME TO game_box_away"); | |
| 288 | try { | |
| 289 | const failed = await press("]"); | |
| 290 | expect(failed).toContain("The files could not be read."); | |
| 291 | expect(failed).not.toContain("game_box"); | |
| 292 | } finally { | |
| 293 | app.db.run("ALTER TABLE game_box_away RENAME TO game_box"); | |
| 294 | } | |
| 295 | expect(await press("]]")).toContain("infra.json, line 4, on main of alice/shop"); | |
| 296 | }); |
new above
offline