Public: anyone can read this; the crew can change it.
Cloud pages: the missing permission, one thing's price, and where tax is #17651
Merged 21h 28m ago, live in production
sold/cloud-priya → main 0 commits 1 thread · 1 unresolved
9 files
changed +209
−20
docs/features/cloud.md +10
| @@ -27,6 +27,16 @@ Answers: `401` with no signed-in user, `403` for a read-only token (every vendor | ||
| 27 | 27 | |
| 28 | 28 | Not done: the route only lists. Attaching, rotating and removing stay on the page and in the terminal, where the token can be typed masked. |
| 29 | 29 | |
| 30 | ## What was not read (#17637) | |
| 31 | ||
| 32 | When the last read of an account could not see something, its row at `/settings/cloud` has a **Not read** line for each reason: what, where, why, the permission when the answer names one, and what to change (`readFixes` in `src/cloud/tree.ts`). | |
| 33 | ||
| 34 | 1. Press **Check the account** on a "Not read" line at `/infra`, or open Settings → Cloud accounts. | |
| 35 | 2. Make the change named. On AWS that is a managed policy on the key's user or role, or the single permission. A key the cloud does not accept needs a new one, with **Rotate**. | |
| 36 | 3. Press **Read now** on Infrastructure. A bill is asked for once a day, so its line goes after the next day's read. | |
| 37 | ||
| 38 | **In the terminal:** `enter` on an account of the Cloud accounts screen (`src/tui/screens/cloud.ts`) opens the same lines (`src/tui/screens/cloud_account.ts`), and so does `a` on Cloud resources. `r` on Cloud accounts rotates, and `P` on Cloud resources reads again. | |
| 39 | ||
| 30 | 40 | ## The project a forge is filed in (#16340) |
| 31 | 41 | |
| 32 | 42 | - A DigitalOcean account can name the cloud **project** its forges go in: a text field on its row at `/settings/cloud`, `P` on the terminal screen, `set_project` on the MCP `cloud_account` tool. Empty is the provider's default project. An admin only; the name is checked, and the project must exist when a forge is deployed, or the deploy is refused before anything is made. |
docs/features/infra.md +2 −2
| @@ -96,12 +96,12 @@ Every DigitalOcean and Hetzner account is read into provider ▸ account ▸ pro | ||
| 96 | 96 | |
| 97 | 97 | /infra leads with what every cloud costs a month and draws one tree: cloud ▸ account ▸ project or region ▸ resource, the costliest first, the cost rolled up at each level (`src/cloud/tree.ts`, pure; `src/web/pages/cloud_tree.ts`). It is the code browser's column and script. A page reads the database alone, never a provider, and nothing in it changes a resource. |
| 98 | 98 | |
| 99 | - **Cost.** An AWS region, account and cloud show the last whole month billed; everything else is a list price. A bill stands in for its resources' prices and is never added to them. The total says it in words ("November's AWS bill, list prices for the rest, 2 things without a price"). In a row a bill is unmarked, `list` is a list price, `≥` means part has no price, and `–` means no price of its own: never $0. A screen reader hears each in full. Under a filter the headline is what was found ("10 unattached volumes") and only resources' own prices are added. | |
| 99 | - **Cost.** An AWS region, account and cloud show the last whole month billed; everything else is a list price. A bill stands in for its resources' prices and is never added to them. The total says it in words ("November's AWS bill, list prices for the rest, 2 things without a price"). In a row a bill is unmarked, `list` is a list price, `≥` means part has no price, and `–` means no price of its own: never $0. One resource says "About $12.00 a month at list price", or "No list price is known for it" and which bill any cost is inside, with no region's total beside it. A bill's Tax line says it is included in the AWS total. A screen reader hears each in full. Under a filter the headline is what was found ("10 unattached volumes") and only resources' own prices are added. | |
| 100 | 100 | - **With nothing open** the pane is where the money goes, then what the forge runs; under a filter it is the matches. **Build** (`c`) is `/infra/build`: the compose form, a build's progress (`?plan=`), a DNS record, the code it is kept as and the pinned forges. `/pinned` redirects there, and so does `/infra?plan=`. |
| 101 | 101 | - **Filter.** `/`, then `kind:volume cloud:aws attached:no cost:>10 text`. Properties: kind, cloud, account, project, region, size, name, state, attached, made, for, app, cost. `!` negates, a comma means any of, `cost:unknown` is a value, and `app:unknown` finds what has no app known, on any cloud, which does not mean nothing uses it. It is in the URL as `?q=`. |
| 102 | 102 | - **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 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 read, and Ask about this (a talk with those facts, fenced as data). |
| 103 | 103 | - **Keys.** j and k move, Enter opens, h and l (or the arrows) close and open, `/` filters and Enter goes to the first match. |
| 104 | - **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. | |
| 104 | - **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). | |
| 105 | 105 | - **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. |
| 106 | 106 | - **Tool.** `infra` `{action: "list", id: "<filter line>"}` and `{action: "cloud", id: "<cloud>/<account>/<project>/<id>"}`. |
| 107 | 107 |
src/cloud/tree.ts +51 −5
| @@ -106,7 +106,7 @@ export function costSays(n: CloudNode): string { | ||
| 106 | 106 | if (m.billed + m.list === 0) return ""; |
| 107 | 107 | return [ |
| 108 | 108 | ...(m.billed > 0 ? [billSays(n)] : []), |
| 109 | ...(m.list === 0 ? [] : [m.billed > 0 ? "list prices for the rest" : n.resource === undefined ? "list prices" : "list price"]), | |
| 109 | ...(m.list === 0 ? [] : [m.billed > 0 ? "list prices for the rest" : "list prices"]), | |
| 110 | 110 | ...(m.unknown === 0 ? [] : [`${many(m.unknown, "thing")} without a price`]), |
| 111 | 111 | ].join(", "); |
| 112 | 112 | } |
| @@ -115,7 +115,17 @@ export function costSays(n: CloudNode): string { | ||
| 115 | 115 | * A node's cost as a line of text: "$603.62 a month: November's AWS bill, list prices for the |
| 116 | 116 | * rest". |
| 117 | 117 | */ |
| 118 | export const costLine = (n: CloudNode): string => (n.money.billed + n.money.list === 0 ? "" : `${dollars(n.money.cents)} a month: ${[costSays(n), unreadLine(n)].filter((x) => x !== "").join(". ")}`); | |
| 118 | export const costLine = (n: CloudNode): string => | |
| 119 | n.money.billed + n.money.list === 0 ? "" : n.resource !== undefined ? `About ${dollars(n.money.cents)} a month at list price` : `${dollars(n.money.cents)} a month: ${[costSays(n), unreadLine(n)].filter((x) => x !== "").join(". ")}`; | |
| 120 | ||
| 121 | /** | |
| 122 | * Said where no price is known. A bill it is inside is named with no sum: a region's total beside | |
| 123 | * one thing reads as that thing's cost. | |
| 124 | */ | |
| 125 | export function unpricedSays(v: CloudView, n: CloudNode): string { | |
| 126 | const inside = [3, 2].map((d) => (n.path.length >= d ? nodeAt(v.whole, n.path.slice(0, d)) : undefined)).find((x) => x?.month !== undefined); | |
| 127 | return `${n.resource === undefined ? "No prices known here." : "No list price is known for it."}${inside === undefined ? "" : ` Any cost is inside ${billSays(inside)}.`}`; | |
| 128 | } | |
| 119 | 129 | |
| 120 | 130 | export type Level = "cloud" | "account" | "project" | "resource"; |
| 121 | 131 | |
| @@ -219,6 +229,36 @@ const groupBy = <T>(all: readonly T[], key: (x: T) => string): Map<string, T[]> | ||
| 219 | 229 | const unreadTrouble = (unread: AccountRead["unread"], href: string, where: (own: AccountRead["unread"]) => string = () => ""): Trouble[] => |
| 220 | 230 | [...groupBy(unread, (u) => u.reason)].map(([reason, own]) => ({ says: `Not read: ${[...new Set(own.map((u) => u.kind))].join(", ")}${where(own)}${listGaps(own).length === 0 ? ", so the app some things are part of is not known" : ""}. ${reason}`, href, label: "Check the account", gap: "here" })); |
| 221 | 231 | |
| 232 | /** A key the cloud does not take at all, so no permission would help. */ | |
| 233 | const BAD_KEY = /answered 401\b|InvalidClientTokenId|UnrecognizedClient|SignatureDoesNotMatch|AuthFailure|ExpiredToken/; | |
| 234 | ||
| 235 | const NO_FIX = "No missing permission is named."; | |
| 236 | /** What to change for a reason, by the permission it names. */ | |
| 237 | function fixFor(provider: string, reason: string): string { | |
| 238 | const needs = /the key needs ([^;]+)/.exec(reason)?.[1]?.replace(/\.$/, ""); | |
| 239 | if (needs !== undefined && provider === "aws") | |
| 240 | return `In AWS IAM, attach the managed policy ${needs.startsWith("ce:") ? "AWSBillingReadOnlyAccess" : "ViewOnlyAccess"} to this key's user or role, or allow only ${needs}. If it has that already, an organization policy or a permissions boundary refuses it.`; | |
| 241 | if (needs !== undefined) return `At ${cloudName(provider)}, give this key ${needs}. If a key cannot be changed there, make a new one and press Rotate here.`; | |
| 242 | if (BAD_KEY.test(reason)) return `${cloudName(provider)} does not accept this key: make a new one and press Rotate here.`; | |
| 243 | return NO_FIX; | |
| 244 | } | |
| 245 | ||
| 246 | /** What the last read of an account could not see, with why and what to change: one a reason. */ | |
| 247 | export function readFixes(read: AccountRead): { readonly says: string; readonly fix: string }[] { | |
| 248 | const { provider } = read; | |
| 249 | const where = (own: AccountRead["unread"]): string => { | |
| 250 | const at = [...new Set(own.map((u) => u.project))]; | |
| 251 | return provider !== "aws" ? "" : ` in ${at.length > NAMED ? `${at.length} regions` : at.join(", ")}`; | |
| 252 | }; | |
| 253 | const again = (fix: string): string => (fix === NO_FIX ? `${fix} Press Read now on Infrastructure to try again.` : `${fix} After that, press Read now on Infrastructure.`); | |
| 254 | return [ | |
| 255 | ...(read.error === "" ? [] : [{ says: `The last read: ${read.error.replace(/\.$/, "")}.`, fix: again(fixFor(provider, read.error)) }]), | |
| 256 | ...[...groupBy(read.unread, (u) => u.reason)].map(([reason, own]) => ({ says: `${[...new Set(own.map((u) => u.kind))].join(", ")}${where(own)}: ${reason.replace(/\.$/, "")}.`, fix: again(fixFor(provider, reason)) })), | |
| 257 | // The bill is asked for once a day, so Read now does not read it. | |
| 258 | ...((read.bill?.error ?? "") === "" ? [] : [{ says: `Its bill: ${read.bill!.error.replace(/\.$/, "")}.`, fix: fixFor(provider, read.bill!.error) }]), | |
| 259 | ]; | |
| 260 | } | |
| 261 | ||
| 222 | 262 | /** Read only for the app a thing is part of: without them the list and its sum are as whole. */ |
| 223 | 263 | const PART_OF_ONLY: ReadonlySet<string> = new Set(["stack", "target-group", "interface"]); |
| 224 | 264 | const listGaps = (unread: AccountRead["unread"]): AccountRead["unread"] => unread.filter((u) => !PART_OF_ONLY.has(u.kind)); |
| @@ -520,8 +560,14 @@ export function linkedFacts(root: CloudNode, n: CloudNode): Fact[] { | ||
| 520 | 560 | /** The same as plain text, for a door with no links. */ |
| 521 | 561 | export const factsOf = (root: CloudNode, n: CloudNode): { readonly label: string; readonly value: string }[] => linkedFacts(root, n).map(({ label, value }) => ({ label, value })); |
| 522 | 562 | |
| 523 | /** AWS's names that do not say what they are; Cost Explorer does not itemise them, so "usually". */ | |
| 524 | const USUALLY = new Map([["EC2 - Other", "usually disks, snapshots, NAT gateways and data transfer"]]); | |
| 563 | /** | |
| 564 | * What a billed line's name does not say. Cost Explorer does not itemise "EC2 - Other", so | |
| 565 | * "usually"; a month's total is the sum of its lines, tax among them. | |
| 566 | */ | |
| 567 | const HINTS = new Map([["EC2 - Other", "usually disks, snapshots, NAT gateways and data transfer"], ["Tax", "included in the AWS total"]]); | |
| 568 | ||
| 569 | /** Whether a month's total holds a tax line, said beside it. */ | |
| 570 | export const taxSays = (m: { readonly from: string; readonly lines: readonly { readonly service: string }[] } | undefined): string => (m?.lines.some((l) => l.service === "Tax") === true ? `${monthName(m.from)}'s total includes tax` : ""); | |
| 525 | 571 | |
| 526 | 572 | /** Where the money goes: the largest sums known, billed services and priced resources together. */ |
| 527 | 573 | export interface Cost { |
| @@ -549,7 +595,7 @@ export function largestCosts(n: CloudNode, most: number): Cost[] { | ||
| 549 | 595 | const regions = new Map(x.children.map((c) => [c.path[2]!, c])); |
| 550 | 596 | for (const l of month.lines.slice(0, most)) { |
| 551 | 597 | const at = regions.get(l.region); |
| 552 | out.push({ says: l.service, where: `${cloudName(x.path[0]!)} ${l.region === "" ? "region not known" : at === undefined ? "no region" : l.region}`, hint: USUALLY.get(l.service) ?? "", path: at?.path ?? x.path, cents: Math.round(l.cents), from: "billed" }); | |
| 598 | out.push({ says: l.service, where: `${cloudName(x.path[0]!)} ${l.region === "" ? "region not known" : at === undefined ? "no region" : l.region}`, hint: HINTS.get(l.service) ?? "", path: at?.path ?? x.path, cents: Math.round(l.cents), from: "billed" }); | |
| 553 | 599 | } |
| 554 | 600 | return; |
| 555 | 601 | } |
src/tui/screens/cloud.ts +5 −2
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * Cloud accounts in the terminal, a forge admin's (#2199): each account with |
| 3 | 3 | * what it is used for, when it was verified and last used, and today's vendor |
| 4 | * calls, as Settings → Cloud accounts shows them. `a` attaches (verified, then | |
| 4 | * calls, as Settings → Cloud accounts shows them. `enter` opens one: what was not read and what to change. `a` attaches (verified, then | |
| 5 | 5 | * sealed), `C` connects a cloud the guided way (/cloud/connect: which cloud, where its key is |
| 6 | 6 | * made and what to tick, then the key; named for you), `v` re-verifies, `r` rotates, `n` renames, `x` removes — all through |
| 7 | 7 | * `actions/cloud.ts`, so the checks are the page's. A token is typed masked and |
| @@ -21,6 +21,7 @@ import { style } from "../term/style.ts"; | ||
| 21 | 21 | import { truncate } from "../term/width.ts"; |
| 22 | 22 | import type { Session } from "../session.ts"; |
| 23 | 23 | import { fill, len, split } from "../ui/layout.ts"; |
| 24 | import { accountScreen } from "./cloud_account.ts"; | |
| 24 | 25 | import { ListState, drawList, later, promptScreen, type ListRow } from "./common.ts"; |
| 25 | 26 | import type { PaletteEntry } from "./entries.ts"; |
| 26 | 27 | import { infraScreen } from "./infra.ts"; |
| @@ -140,6 +141,7 @@ export function cloudScreen(f: Session, ctx: Ctx): Screen { | ||
| 140 | 141 | title: "Cloud accounts", |
| 141 | 142 | keys: [ |
| 142 | 143 | binding(["j", "k"], "move cursor"), |
| 144 | binding(["enter"], "what was not read, and the fix"), | |
| 143 | 145 | binding(["a"], "attach"), |
| 144 | 146 | binding(["C"], "connect a cloud, guided"), |
| 145 | 147 | binding(["I"], "infrastructure: what runs on these accounts"), |
| @@ -191,7 +193,8 @@ export function cloudScreen(f: Session, ctx: Ctx): Screen { | ||
| 191 | 193 | const a = accounts()[state.index]; |
| 192 | 194 | if (a === undefined) return false; |
| 193 | 195 | const { provider, name } = a; |
| 194 | if (e.key === "v") { | |
| 196 | if (e.key === "enter") ctx.push(accountScreen(f, ctx, provider, name)); | |
| 197 | else if (e.key === "v") { | |
| 195 | 198 | say(`Verifying ${provider}/${name}…`); |
| 196 | 199 | void settle(reverify(f.app, f.user, provider, name), () => `Verified ${provider}/${name}.`); |
| 197 | 200 | } else if (e.key === "r") |
src/tui/screens/cloud_account.ts added +51
| @@ -0,0 +1,51 @@ | ||
| 1 | /** | |
| 2 | * One cloud account in the terminal (#17532, #17637): what its last read could not see, the | |
| 3 | * permission each names and what to change, as its row at /settings/cloud says it (`readFixes`). | |
| 4 | * `enter` on Cloud accounts opens it, and `a` on Cloud resources. A forge admin's, and read from the | |
| 5 | * forge's database alone. | |
| 6 | */ | |
| 7 | ||
| 8 | import { cloudOverview } from "../../cloud/overview.ts"; | |
| 9 | import { accountReads } from "../../cloud/projects.ts"; | |
| 10 | import { readFixes } from "../../cloud/tree.ts"; | |
| 11 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 12 | import { binding } from "../app/keys.ts"; | |
| 13 | import type { Session } from "../session.ts"; | |
| 14 | import { style } from "../term/style.ts"; | |
| 15 | import { wrap } from "../term/width.ts"; | |
| 16 | import { Scroll, ago, drawLines } from "./common.ts"; | |
| 17 | ||
| 18 | /** The account's lines; anyone but a forge admin gets none of them. */ | |
| 19 | export function accountLines(f: Session, provider: string, name: string): string[] { | |
| 20 | const all = cloudOverview(f.app, f.user); | |
| 21 | if (!all.ok) return ["Cloud accounts are a forge admin's."]; | |
| 22 | const a = all.value.accounts.find((x) => x.provider === provider && x.name === name); | |
| 23 | if (a === undefined) return [`No account ${provider}/${name} is attached.`]; | |
| 24 | const read = accountReads(f.app.db).find((r) => r.provider === provider && r.account === name); | |
| 25 | const fixes = read === undefined ? [] : readFixes(read); | |
| 26 | return [ | |
| 27 | a.summary, | |
| 28 | `${a.writeAllowed ? "Writes allowed" : "Read-only"} · ${read === undefined ? "its resources are not read yet" : `asked for its resources ${ago(read.askedAt)}`}`, | |
| 29 | ...fixes.flatMap((x) => ["", `Not read: ${x.says}`, x.fix]), | |
| 30 | "", | |
| 31 | fixes.length > 0 ? "Here, Rotate is r on Cloud accounts, and Read now is P on Cloud resources." : read === undefined ? "Press P on Cloud resources to read it." : "Its last read reports nothing missing.", | |
| 32 | ]; | |
| 33 | } | |
| 34 | ||
| 35 | export function accountScreen(f: Session, ctx: Ctx, provider: string, name: string): Screen { | |
| 36 | const scroll = new Scroll(); | |
| 37 | let room = 80; | |
| 38 | // Read once: a key only moves the page. | |
| 39 | const text = accountLines(f, provider, name); | |
| 40 | const lines = (): string[] => text.flatMap((l) => (l === "" ? [""] : wrap(l, room))); | |
| 41 | return { | |
| 42 | title: `${provider}/${name}`, | |
| 43 | keys: [binding(["j", "k"], "scroll"), binding(["esc"], "back")], | |
| 44 | render(area, s) { | |
| 45 | const c = ctx.theme.c; | |
| 46 | room = Math.max(10, area.w - 2); | |
| 47 | drawLines(s, area, c, scroll, lines().map((l) => [{ text: l, style: l.startsWith("Not read:") ? style(c.fg, c.bg) : style(c.mutedFg, c.bg) }])); | |
| 48 | }, | |
| 49 | key: (e) => scroll.key(e, lines().length), | |
| 50 | }; | |
| 51 | } |
src/tui/screens/cloudtree.ts +13 −4
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | 8 | import { cloudResources, readProjectsNow } from "../../actions/infra.ts"; |
| 9 | import { billSays, cloudName, costLine, costliestOf, factsOf, findingOf, isStale, largestCosts, moneyMark, nodeAt, unreadAccounts, unreadLine, unused, type CloudNode, type CloudView } from "../../cloud/tree.ts"; | |
| 9 | import { cloudName, costLine, costliestOf, factsOf, findingOf, isStale, largestCosts, moneyMark, nodeAt, unreadAccounts, unreadLine, unpricedSays, unused, type CloudNode, type CloudView } from "../../cloud/tree.ts"; | |
| 10 | 10 | import { dollars } from "../../cloud/prices.ts"; |
| 11 | 11 | import { keyOf } from "../../web/keymap.ts"; |
| 12 | 12 | import type { Ctx, Screen } from "../app/app.ts"; |
| @@ -15,6 +15,7 @@ import type { Session } from "../session.ts"; | ||
| 15 | 15 | import { style } from "../term/style.ts"; |
| 16 | 16 | import { truncate, wrap } from "../term/width.ts"; |
| 17 | 17 | import { fill, len, split } from "../ui/layout.ts"; |
| 18 | import { accountScreen } from "./cloud_account.ts"; | |
| 18 | 19 | import { Filter, ListState, Scroll, ago, drawLines, hitList, openOnWeb } from "./common.ts"; |
| 19 | 20 | import type { PaletteEntry } from "./entries.ts"; |
| 20 | 21 | import { drawTree } from "./workspace_draw.ts"; |
| @@ -35,13 +36,12 @@ const markOf = (n: CloudNode): string => { | ||
| 35 | 36 | |
| 36 | 37 | /** What a node says when it is open: its cost first, then its facts or its costliest resources. */ |
| 37 | 38 | export function cloudLines(v: CloudView, n: CloudNode): string[] { |
| 38 | const inside = [3, 2].map((d) => (n.path.length >= d ? nodeAt(v.whole, n.path.slice(0, d)) : undefined)).find((x) => x?.month !== undefined); | |
| 39 | const cost = costLine(n) || (n.count === 0 ? "No resources." : `No price of its own${inside === undefined ? "" : `: inside ${billSays(inside)}, ${dollars(inside.money.cents)} for ${inside.name}`}.`); | |
| 39 | const cost = costLine(n) || (n.count === 0 ? "No resources." : unpricedSays(v, n)); | |
| 40 | 40 | const head = [n.path.map((p, i) => (i === 0 ? cloudName(p) : (nodeAt(v.whole, n.path.slice(0, i + 1))?.name ?? p))).join(" ▸ "), cost]; |
| 41 | 41 | const read = n.readAt === "" ? "" : `Read ${ago(n.readAt)}${n.trouble.length === 0 && isStale(n.path[0]!, n.readAt, v.now) ? " (old)" : ""}`; |
| 42 | 42 | // A cloud's own line names its accounts' gaps, since there is no link to follow. |
| 43 | 43 | 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}` }))); |
| 44 | const trouble = [...n.trouble, ...under].map((t) => `! ${t.says} ${t.label}: ${t.href}`); | |
| 44 | const trouble = [...n.trouble, ...under].map((t) => `! ${t.says} ${t.label}: a, or ${t.href}`); | |
| 45 | 45 | if (n.resource !== undefined) return [...head, "", ...factsOf(v.whole, n).map((f) => `${f.label.padEnd(12)} ${f.value}`), `${"Created".padEnd(12)} ${n.resource.createdAt.slice(0, 10)}`, read]; |
| 46 | 46 | const goes = v.q.text === "" ? largestCosts(n, 6).filter((c) => c.from === "billed") : []; |
| 47 | 47 | const line = (sum: string, words: string): string => `${sum.padStart(13)} ${words}`; |
| @@ -106,6 +106,7 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 106 | 106 | binding(["h"], "collapse"), |
| 107 | 107 | binding([keyOf("search")], "filter: kind: cloud: region: cost:>10 text"), |
| 108 | 108 | binding(["tab"], "tree / what is open"), |
| 109 | binding(["a"], "check the account: what was not read, and the fix"), | |
| 109 | 110 | binding(["w"], "open on the web"), |
| 110 | 111 | binding(["P"], "read every account now"), |
| 111 | 112 | ], |
| @@ -193,6 +194,14 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 193 | 194 | return true; |
| 194 | 195 | } |
| 195 | 196 | if (n === undefined) return false; |
| 197 | if (e.key === "a") { | |
| 198 | const at = (focus === "pane" && opened !== undefined ? nodeAt(v.root, opened) : undefined) ?? n; | |
| 199 | // On a cloud, its one account, else the first with something to check. | |
| 200 | const account = at.path.length >= 2 ? at.path : (at.children.length === 1 ? at.children[0] : (at.children.find((x) => x.trouble.length > 0) ?? at.children[0]))?.path; | |
| 201 | if (account === undefined) return false; | |
| 202 | ctx.push(accountScreen(f, ctx, account[0]!, account[1]!)); | |
| 203 | return true; | |
| 204 | } | |
| 196 | 205 | if (e.key === "w") { |
| 197 | 206 | openOnWeb(f, ctx, `/infra/-/${n.path.map(encodeURIComponent).join("/")}`, n.name); |
| 198 | 207 | return true; |
src/web/pages/cloud.ts +10 −1
| @@ -25,6 +25,8 @@ import { lastReading } from "../../cloud/watch_read.ts"; | ||
| 25 | 25 | import { spendOf } from "../../cloud/ceiling.ts"; |
| 26 | 26 | import { warmOf } from "../../cloud/warm_pool.ts"; |
| 27 | 27 | import { dollars } from "../../cloud/prices.ts"; |
| 28 | import { accountReads, type AccountRead } from "../../cloud/projects.ts"; | |
| 29 | import { readFixes } from "../../cloud/tree.ts"; | |
| 28 | 30 | import { auditToday } from "../../core/cloud_audit.ts"; |
| 29 | 31 | import { |
| 30 | 32 | getCloudAccount, |
| @@ -84,7 +86,14 @@ function ceilingLine(db: Database, a: CloudAccount): string { | ||
| 84 | 86 | return `ceiling $${s.ceilingDollars} a month · ${dollars(s.monthlyCents)} counted from this account's machines and databases · ${s.leftCents >= 0 ? `${dollars(s.leftCents)} left` : `${dollars(-s.leftCents)} over`}`; |
| 85 | 87 | } |
| 86 | 88 | |
| 89 | /** What the last read could not see, each with the permission it names and what to change. */ | |
| 90 | function readFacts(reads: readonly AccountRead[], a: CloudAccount): { label: string; value: Html }[] { | |
| 91 | const read = reads.find((r) => r.provider === a.provider && r.account === a.name); | |
| 92 | return read === undefined ? [] : readFixes(read).map((f) => ({ label: "Not\u00a0read", value: html`${f.says}<br />${f.fix}` })); | |
| 93 | } | |
| 94 | ||
| 87 | 95 | function accountsCard(db: Database, accounts: CloudAccount[], reads: CloudRead[], uses: Map<string, VendorUse[]>): Html { |
| 96 | const inventory = accountReads(db); | |
| 88 | 97 | const rows = accounts.map((a) => { |
| 89 | 98 | const last = reads.find((r) => r.provider === a.provider && r.name === a.name); |
| 90 | 99 | return row({ |
| @@ -94,7 +103,7 @@ function accountsCard(db: Database, accounts: CloudAccount[], reads: CloudRead[] | ||
| 94 | 103 | meta: html`${a.summary}<br />${usedFor(uses.get(VENDOR_OF[a.provider]))}<br />${HOME[a.provider]}<br />verified ${a.verifiedAt ? time(a.verifiedAt) : "never"} · |
| 95 | 104 | ${last ? html`last used ${time(last.at)} by ${runWords(last.run)}` : "never used"} · |
| 96 | 105 | ${a.writeAllowed ? "writes allowed" : "read-only"}<br />${ceilingLine(db, a)}`, |
| 97 | facts: [...watchFacts(db, a), ...warmFacts(db, a)], | |
| 106 | facts: [...readFacts(inventory, a), ...watchFacts(db, a), ...warmFacts(db, a)], | |
| 98 | 107 | trail: html`<div class="row-fields"> |
| 99 | 108 | <form method="post" action="/settings/cloud/verify"> |
| 100 | 109 | ${hidden(a.provider, a.name)}${btn("Verify", { size: "sm", label: `Verify ${a.name}` })} |
src/web/pages/cloud_tree.ts +5 −4
| @@ -18,7 +18,6 @@ import { | ||
| 18 | 18 | isStale, |
| 19 | 19 | largestCosts, |
| 20 | 20 | lastMonth, |
| 21 | billSays, | |
| 22 | 21 | costSays, |
| 23 | 22 | findingOf, |
| 24 | 23 | moneyMark, |
| @@ -31,6 +30,8 @@ import { | ||
| 31 | 30 | unreadAccounts, |
| 32 | 31 | unreadSays, |
| 33 | 32 | nodeAt, |
| 33 | taxSays, | |
| 34 | unpricedSays, | |
| 34 | 35 | unused, |
| 35 | 36 | type CloudNode, |
| 36 | 37 | type CloudQuery, |
| @@ -174,10 +175,10 @@ function totalOf(v: CloudView): Html { | ||
| 174 | 175 | |
| 175 | 176 | /** A node's cost under its name. */ |
| 176 | 177 | function sum(v: CloudView, n: CloudNode): Html { |
| 178 | if (n.resource !== undefined && n.money.list > 0) return html`<p class="cloud-sum">About <span class="num">${dollars(n.money.cents)}</span> a month <span class="muted">at list price</span></p>`; | |
| 177 | 179 | if (n.money.billed + n.money.list > 0) return html`<p class="cloud-sum"><span class="num">${dollars(n.money.cents)}</span> a month <span class="muted">${costSays(n)}${unreadLinks(v, n)}</span></p>`; |
| 178 | 180 | if (n.money.unknown + n.money.unread === 0 && (n.path.length >= 2 || n.gaps === 0)) return html``; |
| 179 | const inside = [3, 2].map((d) => (n.path.length >= d ? nodeAt(v.whole, n.path.slice(0, d)) : undefined)).find((x) => x?.month !== undefined); | |
| 180 | return html`<p class="muted" data-unpriced>${n.resource === undefined ? "No prices known here" : "No price of its own"}${inside === undefined ? null : html`: it is inside ${billSays(inside)}, ${dollars(inside.money.cents)} for ${inside.name}`}.${unreadLinks(v, n)}</p>`; | |
| 181 | return html`<p class="muted" data-unpriced>${unpricedSays(v, n)}${unreadLinks(v, n)}</p>`; | |
| 181 | 182 | } |
| 182 | 183 | |
| 183 | 184 | /** The largest sums under a node, each a link to where it is. */ |
| @@ -234,7 +235,7 @@ function billLine(n: CloudNode): Html { | ||
| 234 | 235 | const now = months.find((m) => !m.whole); |
| 235 | 236 | const last = lastMonth(n); |
| 236 | 237 | if (now === undefined && last === undefined) return n.read?.bill?.readAt === "" ? html`<p class="muted small">Its bill is not read yet, so what it costs is not known.</p>` : (n.read?.bill ?? null) === null ? html`` : html`<p class="muted small">AWS listed no cost for this account.</p>`; |
| 237 | return html`<p class="muted small" data-bill>${now === undefined ? null : html`${monthName(now.from)} so far ${dollars(now.cents)} · `}Before credits · Bill read ${time(n.read!.bill!.readAt)}</p>`; | |
| 238 | 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>`; | |
| 238 | 239 | } |
| 239 | 240 | |
| 240 | 241 | /** What is open beside the tree: a branch's costliest resources, or one resource's facts. */ |
test/cloud-tree.test.ts +62 −2
| @@ -11,7 +11,7 @@ import { tmpdir } from "node:os"; | ||
| 11 | 11 | import { join } from "node:path"; |
| 12 | 12 | import { createApp, type App } from "../src/app.ts"; |
| 13 | 13 | import { cloudResources } from "../src/actions/infra.ts"; |
| 14 | import { costLine, costliestOf, factsOf, findingOf, largestCosts, moneyMark, moneyWords, nodeAt, type CloudNode, type CloudView } from "../src/cloud/tree.ts"; | |
| 14 | import { costLine, costliestOf, factsOf, findingOf, largestCosts, moneyMark, moneyWords, nodeAt, readFixes, type CloudNode, type CloudView } from "../src/cloud/tree.ts"; | |
| 15 | 15 | import { aboutContext, aboutLine } from "../src/core/talk_about.ts"; |
| 16 | 16 | import { createSession } from "../src/core/sessions.ts"; |
| 17 | 17 | import { createToken } from "../src/core/tokens.ts"; |
| @@ -22,6 +22,9 @@ import { cloudLines, cloudTreeScreen } from "../src/tui/screens/cloudtree.ts"; | ||
| 22 | 22 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; |
| 23 | 23 | import { mcpTool } from "./helpers/mcp.ts"; |
| 24 | 24 | import { statements } from "./helpers/statements.ts"; |
| 25 | import { cloudScreen } from "../src/tui/screens/cloud.ts"; | |
| 26 | import { accountLines } from "../src/tui/screens/cloud_account.ts"; | |
| 27 | import { Session } from "../src/tui/session.ts"; | |
| 25 | 28 | import { settleApp } from "./helpers/tui.ts"; |
| 26 | 29 | |
| 27 | 30 | let dir = ""; |
| @@ -186,7 +189,64 @@ describe("with accounts", () => { | ||
| 186 | 189 | test("under a filter a resource still says its ties and the bill it is in", async () => { |
| 187 | 190 | const pane = await (await get("/infra/-/aws/main/us-east-1/volume:vol-1?fragment=1&q=kind%3Avolume")).text(); |
| 188 | 191 | expect(pane).toContain('<a href="/infra/-/aws/main/us-east-1/machine:i-1?q=kind%3Avolume">api</a>'); |
| 189 | expect(pane).toContain("it is inside November's AWS bill, $40.00 for us-east-1"); | |
| 192 | // A region's total beside one volume would read as the volume's cost. | |
| 193 | expect(pane).toContain("No list price is known for it. Any cost is inside November's AWS bill."); | |
| 194 | expect(pane).not.toContain("$40.00"); | |
| 195 | expect(cloudLines(view(), at(view(), "aws", "main", "us-east-1", "volume:vol-1"))[1]).toBe("No list price is known for it. Any cost is inside November's AWS bill."); | |
| 196 | const priced = await (await get("/infra/-/digitalocean/main/site/machine:1?fragment=1")).text(); | |
| 197 | expect(priced).toContain('About <span class="num">$12.00</span> a month <span class="muted">at list price</span>'); | |
| 198 | expect(cloudLines(view(), at(view(), "digitalocean", "main", "site", "machine:1"))[1]).toBe("About $12.00 a month at list price"); | |
| 199 | }); | |
| 200 | ||
| 201 | test("tax is said to be inside the AWS total, in the list and beside the bill, and is in it", async () => { | |
| 202 | const aws = at(view(), "aws", "main"); | |
| 203 | expect(aws.money.cents).toBe(4700); | |
| 204 | expect(largestCosts(aws, 6).find((c) => c.says === "Tax")).toMatchObject({ cents: 500, hint: "included in the AWS total" }); | |
| 205 | expect(cloudLines(view(), aws).join("\n")).toContain("Tax · AWS no region · included in the AWS total"); | |
| 206 | expect(await (await get("/infra/-/aws/main?fragment=1")).text()).toContain("November's total includes tax · Before credits"); | |
| 207 | }); | |
| 208 | ||
| 209 | test("the terminal: a on Cloud resources and enter on Cloud accounts show the page's says and fix lines", async () => { | |
| 210 | const says = "Not read: database in us-east-1: the key needs rds:DescribeDBInstances."; | |
| 211 | const fix = "In AWS IAM, attach the managed policy ViewOnlyAccess to this key's user or role, or allow only rds:DescribeDBInstances."; | |
| 212 | const flat = (x: string): string => x.replace(/\s+/g, " "); | |
| 213 | const tree = flat(await drawn("/account:main cloud:aws\rja")); | |
| 214 | expect(tree).toContain(says); | |
| 215 | expect(tree).toContain(fix); | |
| 216 | expect(cloudLines(view(), at(view(), "aws", "main")).join("\n")).toContain("Check the account: a, or /settings/cloud#account-aws-main"); | |
| 217 | const terminal = headlessTerminal(60, 40); | |
| 218 | const session = { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice }; | |
| 219 | const { app: tui, session: s } = createForgeApp(app, session, { terminal, exitHooks: false }); | |
| 220 | onTestFinished(() => void tui.stop?.()); | |
| 221 | tui.start(); | |
| 222 | tui.ctx.push(cloudScreen(s, tui.ctx)); | |
| 223 | await settleApp(tui); | |
| 224 | terminal.feed("\r"); | |
| 225 | await settleApp(tui); | |
| 226 | expect(flat(tui.screen.toText())).toContain("aws/main"); | |
| 227 | expect(flat(tui.screen.toText())).toContain("ViewOnlyAccess to this key's user or role"); | |
| 228 | expect(accountLines(s, "hetzner", "eu").join("\n")).toContain("Hetzner Cloud does not accept this key"); | |
| 229 | expect(accountLines(s, "digitalocean", "main").at(-1)).toContain("Press P on Cloud resources"); | |
| 230 | expect(accountLines(new Session(app, { sshUsername: "nobody", remoteAddress: "127.0.0.1" }), "aws", "main")).toEqual(["Cloud accounts are a forge admin's."]); | |
| 231 | }); | |
| 232 | ||
| 233 | test("Check the account opens the account, which names each missing permission and what to change", async () => { | |
| 234 | const trouble = at(view(), "aws", "main").trouble.find((t) => t.says.startsWith("Not read: database"))!; | |
| 235 | expect(trouble.href).toBe("/settings/cloud#account-aws-main"); | |
| 236 | const page = await (await get("/settings/cloud")).text(); | |
| 237 | const row = (id: string): string => page.slice(page.indexOf(`id="${id}"`)).split("</li>")[0]!; | |
| 238 | expect(row("account-aws-main")).toContain("database in us-east-1: the key needs rds:DescribeDBInstances."); | |
| 239 | expect(row("account-aws-main")).toContain("attach the managed policy ViewOnlyAccess to this key's user or role, or allow only rds:DescribeDBInstances."); | |
| 240 | expect(row("account-hetzner-eu")).toContain("Hetzner Cloud does not accept this key: make a new one and press Rotate here."); | |
| 241 | expect(row("account-digitalocean-main")).not.toContain("Not\u00a0read"); | |
| 242 | const read = { provider: "aws", account: "x", askedAt: AT, error: "", unread: [], bill: { readAt: "", error: "AccessDenied: the key needs ce:GetCostAndUsage; asked again tomorrow (UTC)", requestsToday: 1, months: [] } }; | |
| 243 | expect(readFixes(read)[0]!.fix).toContain("AWSBillingReadOnlyAccess to this key's user or role, or allow only ce:GetCostAndUsage."); | |
| 244 | expect(readFixes(read)[0]!.fix).not.toContain("Read now"); | |
| 245 | const gap = { provider: "cloudflare", account: "x", project: "p", kind: "bucket", since: AT } as const; | |
| 246 | expect(readFixes({ ...read, provider: "cloudflare", bill: null, unread: [{ ...gap, reason: "answered 403: the key needs Workers R2 Storage Read" }, { ...gap, reason: "no answer in 10 seconds" }] }).map((f) => f.fix)).toEqual([ | |
| 247 | "At Cloudflare, give this key Workers R2 Storage Read. If a key cannot be changed there, make a new one and press Rotate here. After that, press Read now on Infrastructure.", | |
| 248 | "No missing permission is named. Press Read now on Infrastructure to try again.", | |
| 249 | ]); | |
| 190 | 250 | }); |
| 191 | 251 | |
| 192 | 252 | test("a filter's headline is what it found; Back's fragment is the pane alone; building is its own page", async () => { |
new above
offline
Both doors: readFixes is shown only on the page. Show it in src/tui/screens/cloud.ts too, so a terminal user sees the missing permission and the fix, and add its how-to to the cloud accounts feature doc.