Public: anyone can read this; the crew can change it.
Spend tools: stop and delete from the cost row, planned and confirmed, and a budget per cloud account that warns at 80% #18067
Closed 15h 57m ago
scout/forge:scout/18046-spend-tools-stop-and-delete-from-the-cos → main 12 commits fork 4 threads · 4 unresolved
17 files
changed +514
−9
- docs/features/spend-tools.md
- src/actions/infra.ts
- src/actions/spend_end.ts
- src/cloud/projects.ts
- src/cloud/tree.ts
- src/core/account_purge.ts
- src/core/event_audience.ts
- src/core/migration-pins/20261204052000-cloud-spend-tools.pin
- src/core/migrations/20261204052000-cloud-spend-tools.ts
- src/http/infra_routes.ts
- src/http/lazy_lists.ts
- src/http/mcp/tools/infra.ts
- src/tui/screens/cloudtree.ts
- src/web/pages/cloud_tree.ts
- src/web/pages/infra.ts
- test/pinned-ceiling.test.ts
- test/spend-tools.test.ts
docs/features/spend-tools.md added +20
| @@ -0,0 +1,20 @@ | ||
| 1 | --- | |
| 2 | topic: Hosting forges for others, and getting paid | |
| 3 | row: Spend tools | |
| 4 | --- | |
| 5 | # Spend tools (#18046) | |
| 6 | ||
| 7 | A forge admin acts on a cost from where it is shown, from where it is shown. Admin only, like the rest of `/infra`; anyone else finds nothing. | |
| 8 | ||
| 9 | ## Stop and Delete from the cost row | |
| 10 | ||
| 11 | On `/infra`'s costliest table and on a resource's own page (`src/web/pages/cloud_tree.ts`), a machine or a volume found on a **write-allowed** DigitalOcean or Hetzner account has **Stop** and **Delete** (a volume only Delete, and only when no machine holds it). Neither is ever offered for a read-only account, and a machine the forge made is ended on Pinned forges, where its record and DNS follow it. | |
| 12 | ||
| 13 | Pressing one only asks for a **plan** (`planEnd`, `src/actions/spend_end.ts`): what will be deleted at the provider, what it costs now (the vendor's billed number or the forge's estimate from prices, and when it was read), what is lost (a volume's data is never recovered), and what stays and keeps billing. The plan is kept as a row for half an hour. **Stop** deletes the machine and keeps its disks, since a powered-off machine keeps billing at both clouds; **Delete** takes the volumes attached to it too, and is confirmed only by typing the name back. | |
| 14 | ||
| 15 | Confirming (`confirmEnd`) does the plan once. Every refusal on a read-only account and every end is a cloud audit row (`end:stop`, `end:delete`, `…:refused`) naming who, what and the plan confirmed, and a `cloud.end` event. | |
| 16 | ||
| 17 | - Terminal: Cloud resources (`src/tui/screens/cloudtree.ts`): `t` plans a stop, `X` a delete, `Y` confirms; a delete asks `Y` twice. | |
| 18 | - Agent: the `infra` tool, `plan` with `want: {end: <resource id from list>, how: stop|delete}`, then `apply` its id (a delete with `names: [<the name>]`). `apply` is held for the owner's yes like every spending action. | |
| 19 | ||
| 20 | A monthly budget with its 80% and 100% notices is `cloud-budget.md`'s, not this page's. |
src/actions/infra.ts +1 −1
| @@ -903,7 +903,7 @@ export function cloudResources(app: App, actor: User | undefined, line: string, | ||
| 903 | 903 | const [projects, reads] = [projectsOf(app.db), accountReads(app.db)]; |
| 904 | 904 | const inside = containersOf(app.db, who.value, now); |
| 905 | 905 | const whole = cloudTree(projects, reads, held, parseCloudQuery(""), now, inside); |
| 906 | return ok({ root: q.text === "" ? whole : cloudTree(projects, reads, held, q, now, inside), whole, q, unknown: cloudUnknowns(whole, q, now), held: held.length, now }); | |
| 906 | return ok({ root: q.text === "" ? whole : cloudTree(projects, reads, held, q, now, inside), whole, q, unknown: cloudUnknowns(whole, q, now), held: held.length, now, writable: new Set(held.filter((a) => a.writeAllowed).map((a) => `${a.provider}/${a.name}`)) }); | |
| 907 | 907 | } |
| 908 | 908 | |
| 909 | 909 | /** |
src/actions/spend_end.ts added +156
| @@ -0,0 +1,156 @@ | ||
| 1 | /** | |
| 2 | * Stop or delete a cloud resource from where its cost is shown (#18046): a machine or a volume | |
| 3 | * found on a DigitalOcean or Hetzner account the forge may write to. Every end is planned first | |
| 4 | * (what goes, what it costs now, what is lost, what stays and keeps billing), kept as a row, and | |
| 5 | * then confirmed by a forge admin; Delete is only confirmed by typing the name, and neither is | |
| 6 | * ever planned for a read-only account. Both are cloud-audit rows (who, what, the plan confirmed) | |
| 7 | * and a `cloud.end` event. Stop means the machine is deleted and its disks kept: a powered-off | |
| 8 | * machine keeps billing at both clouds, so it would save nothing. A machine the forge made is a | |
| 9 | * pinned forge's, ended on Pinned forges, where its record and DNS follow it. | |
| 10 | */ | |
| 11 | ||
| 12 | import type { App } from "../app.ts"; | |
| 13 | import { recordAudit } from "../core/cloud_audit.ts"; | |
| 14 | import { getCloudAccount, NO_ACCOUNT, READ_ONLY } from "../core/cloud_account.ts"; | |
| 15 | import type { User } from "../core/users.ts"; | |
| 16 | import { driverOf } from "../cloud/drivers.ts"; | |
| 17 | import { caller, gone, type Driver } from "../cloud/machine.ts"; | |
| 18 | import type { Fetch } from "../cloud/providers.ts"; | |
| 19 | import { dollars } from "../cloud/prices.ts"; | |
| 20 | import { nodeAt, pathIn, resourcesOf, type CloudNode } from "../cloud/tree.ts"; | |
| 21 | import { id as newId } from "../kernel/id.ts"; | |
| 22 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 23 | import { cloudResources } from "./infra.ts"; | |
| 24 | import { admin, withCloud } from "./pinned.ts"; | |
| 25 | ||
| 26 | export type How = "stop" | "delete"; | |
| 27 | ||
| 28 | /** The clouds whose driver can end a machine and a volume. */ | |
| 29 | const ENDS = ["digitalocean", "hetzner"]; | |
| 30 | /** A plan is confirmed within this long, or planned again: prices and state move. */ | |
| 31 | export const PLAN_MS = 30 * 60_000; | |
| 32 | const ID = /^[A-Za-z0-9-]{1,64}$/; | |
| 33 | ||
| 34 | interface Step { | |
| 35 | readonly kind: "machine" | "volume"; | |
| 36 | readonly remote: string; | |
| 37 | readonly name: string; | |
| 38 | } | |
| 39 | ||
| 40 | export interface EndPlan { | |
| 41 | readonly id: string; | |
| 42 | readonly how: How; | |
| 43 | readonly provider: string; | |
| 44 | readonly account: string; | |
| 45 | /** The resource as `list` names it, `cloud/account/project/kind:id`. */ | |
| 46 | readonly path: string; | |
| 47 | readonly name: string; | |
| 48 | readonly steps: readonly Step[]; | |
| 49 | /** What the resource costs a month now, cents; null when not known, which is never $0. */ | |
| 50 | readonly cents: number | null; | |
| 51 | readonly costSays: string; | |
| 52 | /** What is lost for good, and what stays (and keeps billing). */ | |
| 53 | readonly loses: readonly string[]; | |
| 54 | readonly keeps: readonly string[]; | |
| 55 | /** What the owner types to confirm a delete. */ | |
| 56 | readonly confirmWord: string; | |
| 57 | /** The plan in one sentence, the words the confirm shows and the audit row keeps. */ | |
| 58 | readonly says: string; | |
| 59 | } | |
| 60 | ||
| 61 | const remoteOf = (n: CloudNode): string => n.resource!.id.slice(n.resource!.kind.length + 1); | |
| 62 | ||
| 63 | /** Whether the cost row of `n` may offer these ends: the page asks this to draw its buttons. */ | |
| 64 | export function endable(n: CloudNode, writable: ReadonlySet<string> | undefined): readonly How[] { | |
| 65 | const r = n.resource; | |
| 66 | if (r === undefined || writable?.has(`${n.path[0]}/${n.path[1]}`) !== true || !ENDS.includes(r.provider) || r.madeBy === "forge" || r.label !== "") return []; | |
| 67 | if (r.kind === "machine") return ["stop", "delete"]; | |
| 68 | return r.kind === "volume" && r.attachedTo?.length === 0 ? ["delete"] : []; | |
| 69 | } | |
| 70 | ||
| 71 | function build(n: CloudNode, whole: CloudNode, how: How): Result<Omit<EndPlan, "id">, string> { | |
| 72 | const r = n.resource!; | |
| 73 | const [provider, account] = [r.provider, r.account]; | |
| 74 | const label = `${r.kind} ${n.name}`; | |
| 75 | if (!ID.test(remoteOf(n))) return err(`The provider's id for ${label} is not one the forge may name back to it.`); | |
| 76 | // A volume says which machine it is attached to; a machine's disks are the volumes that say it. | |
| 77 | const disks = r.kind === "machine" ? resourcesOf(whole).filter((x) => x.resource!.kind === "volume" && x.path[1] === account && x.path[0] === provider && x.resource!.attachedTo?.includes(r.id) === true && ID.test(remoteOf(x))) : []; | |
| 78 | const step = (x: CloudNode): Step => ({ kind: x.resource!.kind as "machine" | "volume", remote: remoteOf(x), name: x.name }); | |
| 79 | const steps = how === "delete" ? [n, ...disks].map(step) : [step(n)]; | |
| 80 | const diskCost = disks.reduce((sum, d) => sum + (d.resource!.cents ?? 0), 0); | |
| 81 | const cents = how === "delete" ? (disks.some((d) => d.resource!.cents === null) || r.cents === null ? null : r.cents + diskCost) : r.cents; | |
| 82 | const costSays = cents === null ? "its cost is not known" : `${dollars(cents)} a month, ${r.costFrom === "billed" ? "the vendor's billed number" : "the forge's estimate from list prices"}, read ${n.readAt === "" ? "never" : n.readAt}`; | |
| 83 | const loses = r.kind === "volume" ? [`everything on the volume ${n.name}: it cannot be recovered`] : how === "delete" ? [`the machine ${n.name}, and everything on its own disk`, ...disks.map((d) => `everything on the volume ${d.name}: it cannot be recovered`)] : [`the machine ${n.name}, and everything on its own disk: it is deleted, not powered off`]; | |
| 84 | const keeps = r.kind === "machine" && how === "stop" ? disks.map((d) => `the volume ${d.name}, which keeps billing until it is deleted`) : []; | |
| 85 | const unseen: string[] = []; | |
| 86 | if (r.kind === "machine") keeps.push("any address or snapshot it had, which the forge does not end here"); | |
| 87 | const says = `${how === "stop" ? "Stop" : "Delete"} ${label} on ${provider}/${account}: ${steps.map((s) => `${s.kind} ${s.name}`).join(" and ")} will be deleted at the provider. It costs ${costSays}. Lost: ${loses.join("; ")}.${keeps.length === 0 ? "" : ` Stays: ${keeps.join("; ")}.`}${unseen.length === 0 ? "" : ` Not known: ${unseen.join("; ")}.`}`; | |
| 88 | return ok({ how, provider, account, path: n.path.join("/"), name: n.name, steps, cents, costSays, loses, keeps: [...keeps, ...unseen], confirmWord: n.name, says }); | |
| 89 | } | |
| 90 | ||
| 91 | /** | |
| 92 | * Plan an end of the resource `path`; nothing is done, and a read-only account is refused here, | |
| 93 | * audited. | |
| 94 | */ | |
| 95 | export function planEnd(app: App, actor: User | undefined, path: string, how: unknown): Result<EndPlan, string> { | |
| 96 | const who = admin(actor); | |
| 97 | if (!who.ok) return who; | |
| 98 | if (how !== "stop" && how !== "delete") return err("Say how: stop or delete."); | |
| 99 | const seen = cloudResources(app, actor, ""); | |
| 100 | if (!seen.ok) return seen; | |
| 101 | const n = nodeAt(seen.value.whole, pathIn(path)); | |
| 102 | if (n?.resource === undefined) return err("No such resource: pick it from the list."); | |
| 103 | const r = n.resource; | |
| 104 | const account = getCloudAccount(app.db, r.provider, r.account); | |
| 105 | if (account === undefined) return err(NO_ACCOUNT); | |
| 106 | if (!ENDS.includes(r.provider)) return err(`The forge ends machines and volumes on DigitalOcean and Hetzner; end this one in ${r.provider}'s console.`); | |
| 107 | if (!account.writeAllowed) { | |
| 108 | recordAudit(app.db, { provider: r.provider, account: r.account, purpose: `end:${how}:refused`, target: `${who.value.id ?? ""} ${n.path.join("/")}: read-only`, bytesOut: 0, allowed: false }); | |
| 109 | return err(READ_ONLY); | |
| 110 | } | |
| 111 | if (r.madeBy === "forge" || r.label !== "") return err(`${n.name} is a forge's machine or disk: end it on Pinned forges (/infra), where its record and DNS follow it.`); | |
| 112 | if (r.kind !== "machine" && r.kind !== "volume") return err(`The forge ends machines and volumes here, not a ${r.kind}.`); | |
| 113 | if (r.kind === "volume" && how === "stop") return err("A volume is not stopped: delete it, or leave it."); | |
| 114 | if (r.kind === "volume" && r.attachedTo === null) return err("Whether the volume is attached is not known yet: read the account again, then plan."); | |
| 115 | if (r.kind === "volume" && r.attachedTo!.length > 0) return err("The volume is attached to a machine: end the machine first."); | |
| 116 | const built = build(n, seen.value.whole, how); | |
| 117 | if (!built.ok) return built; | |
| 118 | const plan: EndPlan = { id: newId(), ...built.value }; | |
| 119 | app.db.query("INSERT INTO cloud_end_plan (id, at, by, provider, account, body) VALUES (?1,?2,?3,?4,?5,?6)").run(plan.id, new Date().toISOString(), who.value.id ?? "", plan.provider, plan.account, JSON.stringify(plan)); | |
| 120 | return ok(plan); | |
| 121 | } | |
| 122 | ||
| 123 | /** A plan as it was kept, while it can still be confirmed. */ | |
| 124 | export function endPlanById(app: App, planId: string, now = Date.now()): EndPlan | undefined { | |
| 125 | const row = app.db.query<{ at: string; body: string; state: string }, [string]>("SELECT at, body, state FROM cloud_end_plan WHERE id = ?1").get(planId); | |
| 126 | return row == null || row.state !== "planned" || now - Date.parse(row.at) > PLAN_MS ? undefined : (JSON.parse(row.body) as EndPlan); | |
| 127 | } | |
| 128 | ||
| 129 | /** | |
| 130 | * Delete each step at the provider, in order; a thing already gone counts as done. Makes nothing, | |
| 131 | * so no ceiling holds it. | |
| 132 | */ | |
| 133 | async function endResource(d: Driver, f: Fetch, token: string, steps: readonly Step[]): Promise<void> { | |
| 134 | const call = caller(d, f, token); | |
| 135 | for (const s of steps) await gone(() => (s.kind === "machine" ? d.deleteMachine(call, s.remote) : d.deleteVolume(call, s.remote))); | |
| 136 | } | |
| 137 | ||
| 138 | /** | |
| 139 | * Do what a plan said, after the owner confirmed it: a delete only with the name typed back. The | |
| 140 | * plan runs once; each step is the driver's own call, a thing already gone counting as done. | |
| 141 | */ | |
| 142 | export async function confirmEnd(app: App, actor: User | undefined, planId: string, typed: unknown = ""): Promise<Result<string, string>> { | |
| 143 | const who = admin(actor); | |
| 144 | if (!who.ok) return who; | |
| 145 | const plan = endPlanById(app, planId); | |
| 146 | if (plan === undefined) return err("That plan is not one this forge showed lately (or it was done): plan it again."); | |
| 147 | if (plan.how === "delete" && typed !== plan.confirmWord) return err(`A delete is confirmed by typing its name, ${plan.confirmWord}.`); | |
| 148 | const claimed = app.db.query("UPDATE cloud_end_plan SET state = 'confirmed', confirmed_at = ?2, confirmed_by = ?3 WHERE id = ?1 AND state = 'planned'").run(planId, new Date().toISOString(), who.value.id ?? ""); | |
| 149 | if (claimed.changes === 0) return err("That plan was already confirmed."); | |
| 150 | const done = await withCloud(app, who.value, { target: plan.provider, account: plan.account }, `end:${plan.how}`, (f, token) => endResource(driverOf(plan.provider), f, token, plan.steps)); | |
| 151 | // The audit row says who, what and the plan confirmed, whether the cloud did it or refused. | |
| 152 | recordAudit(app.db, { provider: plan.provider, account: plan.account, purpose: `end:${plan.how}`, target: `${who.value.id ?? ""} confirmed plan ${plan.id}: ${plan.says}`, bytesOut: 0, allowed: done.ok }); | |
| 153 | app.bus.append({ kind: "cloud.end", actorId: who.value.id, payload: { plan: plan.id, how: plan.how, provider: plan.provider, account: plan.account, path: plan.path, steps: plan.steps, cents: plan.cents, ok: done.ok } }); | |
| 154 | app.db.query("UPDATE cloud_end_plan SET state = ?2 WHERE id = ?1").run(planId, done.ok ? "done" : "failed"); | |
| 155 | return done.ok ? ok(`${plan.how === "stop" ? "Stopped" : "Deleted"} ${plan.name}: ${plan.steps.map((s) => `${s.kind} ${s.name}`).join(" and ")} deleted at ${plan.provider}. The list shows it gone at the account's next read.`) : err(done.error); | |
| 156 | } |
src/cloud/projects.ts +4
| @@ -191,6 +191,8 @@ async function readDigitalOcean(f: Fetch, token: string): Promise<Read> { | ||
| 191 | 191 | gib: Number(x.size_gigabytes) || VOLUME_GIB, |
| 192 | 192 | project: owner.get(`do:volume:${String(x.id)}`) ?? fallback, |
| 193 | 193 | label: doLabel(x.tags), |
| 194 | // The droplets it is attached to, as the volume says; unset when the answer does not say. | |
| 195 | ...(Array.isArray(x.droplet_ids) ? { attachedTo: x.droplet_ids.map((d: unknown) => `machine:${text(d)}`) } : {}), | |
| 194 | 196 | })), |
| 195 | 197 | ].filter((t) => t.id !== ""), |
| 196 | 198 | gaps: [], |
| @@ -222,6 +224,8 @@ async function readHetzner(f: Fetch, token: string, project: string): Promise<Re | ||
| 222 | 224 | datacenter: text(x.location?.name), |
| 223 | 225 | size: "", |
| 224 | 226 | gib: Number(x.size) || VOLUME_GIB, |
| 227 | // The server it is attached to (null when none); unset when the answer does not say. | |
| 228 | ...(x.server === undefined ? {} : { attachedTo: x.server === null ? [] : [`machine:${text(x.server)}`] }), | |
| 225 | 229 | })), |
| 226 | 230 | ...walls.map((x) => ({ ...base(x), kind: "firewall" as const, datacenter: "", size: "", gib: 0 })), |
| 227 | 231 | ...ips.map((x) => ({ |
src/cloud/tree.ts +5
| @@ -373,6 +373,11 @@ export interface CloudView { | ||
| 373 | 373 | readonly files?: ReadonlyMap<string, readonly Filed[]>; |
| 374 | 374 | /** The open container's recent lines, set only when its Logs tab is asked for. */ |
| 375 | 375 | readonly logs?: Logged; |
| 376 | /** | |
| 377 | * The accounts (`provider/name`) the forge may write to: where a cost row offers Stop and Delete | |
| 378 | * (#18046). | |
| 379 | */ | |
| 380 | readonly writable?: ReadonlySet<string>; | |
| 376 | 381 | } |
| 377 | 382 | |
| 378 | 383 | /** |
src/core/account_purge.ts +2
| @@ -67,6 +67,8 @@ export const COVERED: Readonly<Record<string, Coverage>> = { | ||
| 67 | 67 | "allocation_entry.actor_id": FORMER, |
| 68 | 68 | "allocation_weekly.set_by": FORMER, |
| 69 | 69 | "cloud_watch_ack.by": FORMER, |
| 70 | "cloud_end_plan.by": FORMER, | |
| 71 | "cloud_end_plan.confirmed_by": FORMER, | |
| 70 | 72 | "cloud_resource.made_by": { do: "none", why: "who made a thing at a cloud provider: \"forge\" or \"found\", never an account" }, |
| 71 | 73 | "config_change.by": FORMER, |
| 72 | 74 | "crew_device.added_by": FORMER, |
src/core/event_audience.ts +1
| @@ -330,6 +330,7 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 330 | 330 | // configuration, the admins' to hear (`cloud/budget.ts`, #18101). |
| 331 | 331 | kind === "cloud.budget" || |
| 332 | 332 | kind === "cloud.budget_notice" || |
| 333 | kind === "cloud.end" || | |
| 333 | 334 | // An admin acknowledging a resource as not the forge's (`cloud/watch.ts`, #16329). |
| 334 | 335 | kind === "cloud.watch_acknowledged" || |
| 335 | 336 | kind === "cloud.project" || |
src/core/migration-pins/20261204052000-cloud-spend-tools.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | b5112232696c1b43c92063663dd4783d79b4585f651785e94a54d15be30fab7a |
src/core/migrations/20261204052000-cloud-spend-tools.ts added +15
| @@ -0,0 +1,15 @@ | ||
| 1 | // The plans for stopping or deleting a cloud resource from the cost row, kept as planned | |
| 2 | // and as confirmed. Additive. | |
| 3 | export default ` | |
| 4 | CREATE TABLE IF NOT EXISTS cloud_end_plan ( | |
| 5 | id TEXT PRIMARY KEY, | |
| 6 | at TEXT NOT NULL, | |
| 7 | by TEXT NOT NULL, | |
| 8 | provider TEXT NOT NULL, | |
| 9 | account TEXT NOT NULL, | |
| 10 | body TEXT NOT NULL, | |
| 11 | state TEXT NOT NULL DEFAULT 'planned', | |
| 12 | confirmed_at TEXT, | |
| 13 | confirmed_by TEXT | |
| 14 | ); | |
| 15 | `; |
src/http/infra_routes.ts +30 −1
| @@ -9,6 +9,7 @@ import { cloudFactsAll } from "../actions/cloud_says.ts"; | ||
| 9 | 9 | import { infraCode } from "../cloud/infra_read.ts"; |
| 10 | 10 | import { buildOf, cloudResources, machineOf, providerConsole, readProjectsNow, type ComposeChoices, composeChoices, domainOf, infraOf, nameFor, planCompose, planRecord, pointsOf, rebuild, recordAccounts, startBuild } from "../actions/infra.ts"; |
| 11 | 11 | import { dropRecord } from "../actions/dns_record.ts"; |
| 12 | import { confirmEnd, planEnd } from "../actions/spend_end.ts"; | |
| 12 | 13 | import { deleteSnapshot, endWithSnapshot, restoreSnapshot } from "../actions/infra_snapshot.ts"; |
| 13 | 14 | import { deployWords, clearPinned, endsWords, keepPinned, retirePinned, retireWords } from "../actions/pinned.ts"; |
| 14 | 15 | import { timePhase, timePhaseAsync } from "../core/route_timing.ts"; |
| @@ -19,7 +20,7 @@ import { field, readForm } from "../web/form.ts"; | ||
| 19 | 20 | import { html, type Html } from "../web/html.ts"; |
| 20 | 21 | import { flashTo, fragment, page } from "../web/layout.ts"; |
| 21 | 22 | import { machineView } from "../actions/machine_view.ts"; |
| 22 | import { INFRA_CSS, cloudPage, consolePage, endingPage, restoringPage, buildTray, placesRegion, composeForm, infraJs, buildPage, planTray, recordForm, resourcesPage, runningRegion, type ComposeState } from "../web/pages/infra.ts"; | |
| 23 | import { INFRA_CSS, cloudPage, consolePage, endingPage, endPlanPage, restoringPage, buildTray, placesRegion, composeForm, infraJs, buildPage, planTray, recordForm, resourcesPage, runningRegion, type ComposeState } from "../web/pages/infra.ts"; | |
| 23 | 24 | import { cloudBranch, cloudList, cloudOverview, cloudPane, cloudTotal, cloudTreeJs } from "../web/pages/cloud_tree.ts"; |
| 24 | 25 | import { filesByNode } from "../cloud/declared_read.ts"; |
| 25 | 26 | import { logsOfContainer } from "../cloud/containers.ts"; |
| @@ -281,6 +282,32 @@ async function infraProjects(ctx: Ctx): Promise<Response> { | ||
| 281 | 282 | ); |
| 282 | 283 | } |
| 283 | 284 | |
| 285 | // POST /infra/end/plan: what a stop or a delete of a found machine or volume would do; nothing is | |
| 286 | // done. | |
| 287 | async function infraEndPlan(ctx: Ctx): Promise<Response> { | |
| 288 | const denied = guard(ctx); | |
| 289 | if (denied) return denied; | |
| 290 | const form = await readForm(ctx, "admin"); | |
| 291 | if (form instanceof Response) return form; | |
| 292 | const planned = planEnd(ctx.app, ctx.auth.user, field(form, "id").slice(0, 300), field(form, "how")); | |
| 293 | if (!planned.ok) return planned.error === "not_found" ? notFoundPage(ctx) : flashTo(ctx, "/infra", { tone: "danger", message: planned.error }); | |
| 294 | const shown = page({ ctx, title: `${planned.value.how === "stop" ? "Stop" : "Delete"} ${planned.value.name}?`, body: endPlanPage(planned.value) }); | |
| 295 | shown.headers.set("cache-control", "no-store"); | |
| 296 | return shown; | |
| 297 | } | |
| 298 | ||
| 299 | // POST /infra/end/confirm: the owner's word on a plan (a delete with its name typed); then it is | |
| 300 | // done. | |
| 301 | async function infraEndConfirm(ctx: Ctx): Promise<Response> { | |
| 302 | const denied = guard(ctx); | |
| 303 | if (denied) return denied; | |
| 304 | const form = await readForm(ctx, "admin"); | |
| 305 | if (form instanceof Response) return form; | |
| 306 | const done = await confirmEnd(ctx.app, ctx.auth.user, field(form, "plan").slice(0, 40), field(form, "typed").slice(0, 200)); | |
| 307 | if (!done.ok && done.error === "not_found") return notFoundPage(ctx); | |
| 308 | return flashTo(ctx, "/infra", done.ok ? { tone: "success", message: done.value } : { tone: "danger", message: done.error }); | |
| 309 | } | |
| 310 | ||
| 284 | 311 | // POST /infra/:name/keep and /infra/:name/end (End now arrives from the confirm page). |
| 285 | 312 | async function infraMachine(ctx: Ctx): Promise<Response> { |
| 286 | 313 | const denied = guard(ctx); |
| @@ -382,6 +409,8 @@ export function infraRoutes(router: Router<Handler>): void { | ||
| 382 | 409 | router.add("POST", "/infra/record", infraRecord); |
| 383 | 410 | router.add("POST", "/infra/rebuild", infraRebuild); |
| 384 | 411 | router.add("POST", "/infra/projects", infraProjects); |
| 412 | router.add("POST", "/infra/end/plan", infraEndPlan); | |
| 413 | router.add("POST", "/infra/end/confirm", infraEndConfirm); | |
| 385 | 414 | router.add("GET", "/infra/:name/ending", infraEnding); |
| 386 | 415 | router.add("GET", "/infra/:name/cloud", infraCloud); |
| 387 | 416 | router.add("POST", "/infra/snapshot/:id/:act", infraSnapshot); |
src/http/lazy_lists.ts +2
| @@ -637,6 +637,8 @@ export const OPERATIONS_ROUTES = [ | ||
| 637 | 637 | ["POST", "/infra/record"], |
| 638 | 638 | ["POST", "/infra/rebuild"], |
| 639 | 639 | ["POST", "/infra/projects"], |
| 640 | ["POST", "/infra/end/plan"], | |
| 641 | ["POST", "/infra/end/confirm"], | |
| 640 | 642 | ["GET", "/infra/:name/ending"], |
| 641 | 643 | ["GET", "/infra/:name/cloud"], |
| 642 | 644 | ["POST", "/infra/snapshot/:id/:act"], |
src/http/mcp/tools/infra.ts +11 −1
| @@ -7,6 +7,7 @@ import { logsOfContainer } from "../../../cloud/containers.ts"; | ||
| 7 | 7 | import { CLOUD_PROPS, CONTAINER_COST, costLine, costliestOf, cutSays, factsOf, findingOf, listedOf, moneyWords, nodeAt, orderSays, pathIn, readingOf, tabsOf, tiesOf, type CloudNode } from "../../../cloud/tree.ts"; |
| 8 | 8 | import { buildOf, cloudResources, firewallWant, gameWant, planDatabase, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts"; |
| 9 | 9 | import { machineView } from "../../../actions/machine_view.ts"; |
| 10 | import { confirmEnd, endPlanById, planEnd } from "../../../actions/spend_end.ts"; | |
| 10 | 11 | import { bindBucket, readBucket } from "../../../actions/bucket.ts"; |
| 11 | 12 | import { endsWords, keepPinned } from "../../../actions/pinned.ts"; |
| 12 | 13 | import { lookAtRecords, lookWords } from "../../../actions/dns_record.ts"; |
| @@ -56,7 +57,7 @@ function named(whole: CloudNode, nodes: readonly CloudNode[], args: Args, says: | ||
| 56 | 57 | export const tool: Tool = { |
| 57 | 58 | name: "infra", |
| 58 | 59 | listedTo: "admin", |
| 59 | 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?}`.", | |
| 60 | 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?}`; `plan` `{end: id, how: stop|delete}` a found machine or volume, `apply` it (delete: `names` [name]).", | |
| 60 | 61 | description: "Machines, spend.", |
| 61 | 62 | inputSchema: { |
| 62 | 63 | type: "object", |
| @@ -196,6 +197,11 @@ export const tool: Tool = { | ||
| 196 | 197 | } |
| 197 | 198 | if (action === "plan") { |
| 198 | 199 | const w = (typeof args["want"] === "object" && args["want"] !== null ? args["want"] : {}) as Record<string, unknown>; |
| 200 | // Stop or delete a found machine or volume: planned here, done by `apply` of the plan's id. | |
| 201 | if (w["end"] !== undefined) { | |
| 202 | const ended = planEnd(ctx.app, user, s(w["end"], 300), w["how"]); | |
| 203 | return ended.ok ? good({ id: ended.value.id, says: ended.value.says, steps: ended.value.steps, costs: ended.value.costSays, loses: ended.value.loses, stays: ended.value.keeps, confirm: ended.value.how === "delete" ? `apply with names: ["${ended.value.confirmWord}"]` : "apply" }) : bad("refused", ended.error); | |
| 204 | } | |
| 199 | 205 | // A DNS record on a Cloudflare account: an A record, or an SRV record for a game server's |
| 200 | 206 | // address. |
| 201 | 207 | if (w["dns"] === true) { |
| @@ -284,6 +290,10 @@ export const tool: Tool = { | ||
| 284 | 290 | : bindBucket(ctx.app, user, s(b["repo"], 140), provider, s(b["region"], 20), s(b["name"], 80)); |
| 285 | 291 | return done.ok ? good({ says: done.value.says, url: done.value.url, cents: done.value.cents }) : bad("refused", done.error); |
| 286 | 292 | } |
| 293 | if (action === "apply" && endPlanById(ctx.app, id) !== undefined) { | |
| 294 | const done = await confirmEnd(ctx.app, user, id, names[0] ?? ""); | |
| 295 | return done.ok ? good({ says: done.value }) : bad("refused", done.error); | |
| 296 | } | |
| 287 | 297 | if (action === "apply") { |
| 288 | 298 | const p = planById(ctx.app, id); |
| 289 | 299 | if (p === undefined) return bad("no_plan", "That plan is not one this forge showed lately: plan it again, then apply its id."); |
src/tui/screens/cloudtree.ts +38 −2
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | |
| 8 | 8 | import { cloudResources, readProjectsNow } from "../../actions/infra.ts"; |
| 9 | 9 | import { cloudCell, CLOUD_COLUMNS, FIRST_COLUMNS, firstCell, 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 { confirmEnd, endable, planEnd, type EndPlan } from "../../actions/spend_end.ts"; | |
| 10 | 11 | import { noFileSays, placeSays } from "../../cloud/declared_in.ts"; |
| 11 | 12 | import { filesByNode } from "../../cloud/declared_read.ts"; |
| 12 | 13 | import { CONTAINER_COLUMNS, containerCell, logsOfContainer } from "../../cloud/containers.ts"; |
| @@ -71,7 +72,7 @@ export function cloudLines(v: CloudView, n: CloudNode, width = 80, tab: NodeTab | ||
| 71 | 72 | const facts = factsOf(v.whole, n).map((f) => `${f.label.padEnd(12)} ${f.value}`); |
| 72 | 73 | if (n.container !== undefined) return [...head, "", ...facts, read]; |
| 73 | 74 | if (n.resource !== undefined) |
| 74 | return [...head, "", ...facts, `${createdLabel(n.resource).padEnd(12)} ${n.resource.createdAt.slice(0, 10) || "not known"}`, read, ...(n.children.length === 0 ? [] : ["", containersSay(n), ...tableLines(CONTAINER_COLUMNS.map((k) => ({ field: { name: k.field, type: "text" }, label: k.label })), v.q.line, n.children.map((c) => CONTAINER_COLUMNS.map((k) => containerCell(c.container!, k.field, v.now))), width)])]; | |
| 75 | return [...head, ...(endable(n, v.writable).length === 0 ? [] : [`Plan to end it: ${endable(n, v.writable).map((h) => (h === "stop" ? "t stops it" : "X deletes it")).join(", ")}; nothing is done until you confirm`]), "", ...facts, `${createdLabel(n.resource).padEnd(12)} ${n.resource.createdAt.slice(0, 10) || "not known"}`, read,...(n.children.length === 0 ? [] : ["", containersSay(n), ...tableLines(CONTAINER_COLUMNS.map((k) => ({ field: { name: k.field, type: "text" }, label: k.label })), v.q.line, n.children.map((c) => CONTAINER_COLUMNS.map((k) => containerCell(c.container!, k.field, v.now))), width)])]; | |
| 75 | 76 | // The first page is the page's own table: resource, kind, where, and a cost in words. |
| 76 | 77 | const first = n.path.length === 0; |
| 77 | 78 | const columns = first ? FIRST_COLUMNS : CLOUD_COLUMNS; |
| @@ -104,6 +105,11 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 104 | 105 | let tab: NodeTab | null = null; |
| 105 | 106 | let filesSay = READING; |
| 106 | 107 | const lines = (v: CloudView, n: CloudNode): string[] => cloudLines(tabOf(n, tab) === "logs" && n.container !== undefined ? { ...v, logs: logsOfContainer(f.app.db, n.container) } : v, n, room, tabOf(n, tab), filesSay).flatMap((l) => (l.length <= room ? [l] : wrap(l, room))); |
| 108 | /** | |
| 109 | * A stop or delete planned and waiting for Y; `armed` once a delete has been asked to be sure. | |
| 110 | */ | |
| 111 | let pending: { readonly plan: EndPlan; armed: boolean } | undefined; | |
| 112 | const planLines = (): string[] => (pending === undefined ? [] : [...wrap(pending.plan.says, room), "", pending.plan.how === "delete" && !pending.armed ? "Y: ask me once more to delete · esc: cancel" : pending.plan.how === "delete" ? `Y again deletes ${pending.plan.name} for good · esc: cancel` : "Y: stop it · esc: cancel", ""]); | |
| 107 | 113 | let reading: CloudView | undefined; |
| 108 | 114 | let kept: { readonly query: string; readonly view: CloudView | undefined } | undefined; |
| 109 | 115 | |
| @@ -163,6 +169,7 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 163 | 169 | binding(["tab"], "tree / what is open"), |
| 164 | 170 | binding(["[", "]"], "facts / file"), |
| 165 | 171 | binding(["a"], "check the account: what was not read, and the fix"), |
| 172 | binding(["t", "X"], "plan to stop / delete the resource (Y confirms; a delete asks twice)"), | |
| 166 | 173 | binding(["w"], "open on the web"), |
| 167 | 174 | binding(["P"], "read every account now"), |
| 168 | 175 | ], |
| @@ -219,13 +226,30 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 219 | 226 | if (at !== undefined) { |
| 220 | 227 | if (tabOf(at, tab) === "file") readFiles(v); |
| 221 | 228 | room = Math.max(10, right.w - 2); |
| 222 | 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) }])); | |
| 229 | drawLines(s, { ...right, x: right.x + 1, w: Math.max(0, right.w - 1) }, c, pane, [...planLines(), ...lines(v, at)].map((text) => [{ text, style: style(c.fg, c.bg) }])); | |
| 223 | 230 | } |
| 224 | 231 | } |
| 225 | 232 | }, |
| 226 | 233 | key(e) { |
| 227 | 234 | const v = view(); |
| 228 | 235 | if (v === undefined) return false; |
| 236 | if (pending !== undefined && (e.key === "esc" || e.key === "Y")) { | |
| 237 | if (e.key === "esc") { | |
| 238 | pending = undefined; | |
| 239 | note = "Nothing was done."; | |
| 240 | } else if (pending.plan.how === "delete" && !pending.armed) pending.armed = true; | |
| 241 | else { | |
| 242 | const { plan } = pending; | |
| 243 | pending = undefined; | |
| 244 | note = `Ending ${plan.name}…`; | |
| 245 | void confirmEnd(f.app, f.user, plan.id, plan.confirmWord).then((done) => { | |
| 246 | note = done.ok ? done.value : done.error; | |
| 247 | kept = undefined; | |
| 248 | ctx.invalidate(); | |
| 249 | }); | |
| 250 | } | |
| 251 | return true; | |
| 252 | } | |
| 229 | 253 | if (focus === "tree" && filter.key(e)) { |
| 230 | 254 | state.index = 0; |
| 231 | 255 | return true; |
| @@ -264,6 +288,18 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 264 | 288 | return true; |
| 265 | 289 | } |
| 266 | 290 | if (n === undefined) return false; |
| 291 | if (e.key === "t" || e.key === "X") { | |
| 292 | const at = (focus === "pane" && opened !== undefined ? nodeAt(v.root, opened) : undefined) ?? n; | |
| 293 | const planned = planEnd(f.app, f.user, at.path.join("/"), e.key === "t" ? "stop" : "delete"); | |
| 294 | if (planned.ok) { | |
| 295 | pending = { plan: planned.value, armed: false }; | |
| 296 | pane.top = 0; | |
| 297 | focus = "pane"; | |
| 298 | opened = at.path; | |
| 299 | note = ""; | |
| 300 | } else note = planned.error; | |
| 301 | return true; | |
| 302 | } | |
| 267 | 303 | if (e.key === "[" || e.key === "]") { |
| 268 | 304 | const at = (opened === undefined ? undefined : nodeAt(v.root, opened)) ?? n; |
| 269 | 305 | const has = tabsOf(at); |
src/web/pages/cloud_tree.ts +15 −2
| @@ -54,6 +54,7 @@ import { | ||
| 54 | 54 | } from "../../cloud/tree.ts"; |
| 55 | 55 | import { CONTAINER_COLUMNS, containerCell } from "../../cloud/containers.ts"; |
| 56 | 56 | import { dollars } from "../../cloud/prices.ts"; |
| 57 | import { endable } from "../../actions/spend_end.ts"; | |
| 57 | 58 | import { emptySection } from "../empty_words.ts"; |
| 58 | 59 | import { html, raw, type Html } from "../html.ts"; |
| 59 | 60 | import { icon } from "../icons.ts"; |
| @@ -240,6 +241,18 @@ function listed(v: CloudView, n: CloudNode): Html { | ||
| 240 | 241 | ${all.length > PANE_ROWS ? html`<p class="muted small">The first ${PANE_ROWS}, ${orderSays(v.q)}: filter to see the rest.</p>` : null}`; |
| 241 | 242 | } |
| 242 | 243 | |
| 244 | /** | |
| 245 | * Stop and Delete beside a cost, for what the forge may end here (`endable`): each a form that asks | |
| 246 | * for a plan, never for the end itself. Nothing for a read-only account. | |
| 247 | */ | |
| 248 | function endButtons(v: CloudView, n: CloudNode): Html | null { | |
| 249 | const ways = endable(n, v.writable); | |
| 250 | if (ways.length === 0) return null; | |
| 251 | return html`<span class="row-actions">${ways.map( | |
| 252 | (how) => html`<form method="post" action="/infra/end/plan" class="inline-form"><input type="hidden" name="id" value="${n.path.join("/")}" /><input type="hidden" name="how" value="${how}" />${btn(how === "stop" ? "Stop" : "Delete", { variant: "ghost", size: "sm", label: `Plan to ${how} ${n.name}: nothing is done until you confirm` })}</form>`, | |
| 253 | )}</span>`; | |
| 254 | } | |
| 255 | ||
| 243 | 256 | /** The costliest resources in one table, in the tree's order, narrowed by the filter line. */ |
| 244 | 257 | function costliestTable(v: CloudView): Html { |
| 245 | 258 | const all = listedOf(v, v.root); |
| @@ -250,7 +263,7 @@ function costliestTable(v: CloudView): Html { | ||
| 250 | 263 | columns: FIRST_COLUMNS, |
| 251 | 264 | line: v.q.line, |
| 252 | 265 | rows: all.slice(0, PANE_ROWS), |
| 253 | cell: (c, field) => (field === "name" ? html`<a href="${cloudHref(c.path, v.q)}">${c.name}</a>` : field === "cost" ? costMark(c) : firstCell(c, field)), | |
| 266 | cell: (c, field) => (field === "name" ? html`<a href="${cloudHref(c.path, v.q)}">${c.name}</a>` : field === "cost" ? html`${costMark(c)} ${endButtons(v, c)}` : firstCell(c, field)), | |
| 254 | 267 | href: (text) => cloudHref([], { ...v.q, text }), |
| 255 | 268 | caption: `Resources, ${orderSays(v.q)}`, |
| 256 | 269 | })} |
| @@ -316,7 +329,7 @@ export function cloudPane(v: CloudView, n: CloudNode, tab: NodeTab = tabOf(n, nu | ||
| 316 | 329 | <thead><tr>${CONTAINER_COLUMNS.map((k) => html`<th scope="col">${k.label}</th>`)}</tr></thead> |
| 317 | 330 | <tbody>${n.children.map((c) => html`<tr>${CONTAINER_COLUMNS.map((k) => html`<td>${k.field === "name" ? html`<a href="${cloudHref(c.path, v.q)}">${c.name}</a>` : containerCell(c.container!, k.field, v.now)}</td>`)}</tr>`)}</tbody> |
| 318 | 331 | </table></div>`} |
| 319 | <div class="form-actions">${btn("Ask about this", { href: `/talk?about=${encodeURIComponent(`cloud:${n.path.join("/")}`)}` })}</div> | |
| 332 | <div class="form-actions">${btn("Ask about this", { href: `/talk?about=${encodeURIComponent(`cloud:${n.path.join("/")}`)}` })}${endButtons(v, n)}</div> | |
| 320 | 333 | </section>`; |
| 321 | 334 | } |
| 322 | 335 |
src/web/pages/infra.ts +21
| @@ -17,6 +17,7 @@ import type { CodeFile } from "../../cloud/infra_read.ts"; | ||
| 17 | 17 | import { restoredName, type SnapshotView } from "../../actions/infra_snapshot.ts"; |
| 18 | 18 | import { ENDED_DAYS, pointsOf, type RecordFields, type Build, type ComposeChoices, type InfraView, type Planned, type Running } from "../../actions/infra.ts"; |
| 19 | 19 | import type { MachineView } from "../../actions/machine_view.ts"; |
| 20 | import type { EndPlan } from "../../actions/spend_end.ts"; | |
| 20 | 21 | import { actionLine, viewRows } from "../../cloud/provider_detail.ts"; |
| 21 | 22 | import { dollars } from "../../cloud/prices.ts"; |
| 22 | 23 | import { pageHead } from "../chrome.ts"; |
| @@ -323,6 +324,26 @@ export function endingPage(r: Running): Html { | ||
| 323 | 324 | </div>`; |
| 324 | 325 | } |
| 325 | 326 | |
| 327 | /** | |
| 328 | * What a stop or a delete will do, before it does it (#18046): what goes, what it costs now, what | |
| 329 | * is lost and what stays, then the owner's confirmation. A delete asks for the name typed back. | |
| 330 | */ | |
| 331 | export function endPlanPage(p: EndPlan): Html { | |
| 332 | const word = p.how === "stop" ? "Stop" : "Delete"; | |
| 333 | return html`<div class="narrow-wide" data-end-plan="${p.id}"> | |
| 334 | ${pageHead(`${word} ${p.name}?`)} | |
| 335 | <p>${p.says}</p> | |
| 336 | ${p.steps.map((s) => html`<p>Deleted at ${p.provider}: ${s.kind} <strong>${s.name}</strong></p>`)} | |
| 337 | <p class="muted small">It costs ${p.costSays}. The figure is read from the provider's list; the provider's bill is the truth. Nothing is done until you confirm below, and the plan is good for half an hour.</p> | |
| 338 | <form method="post" action="/infra/end/confirm" class="form-actions"> | |
| 339 | <input type="hidden" name="plan" value="${p.id}" /> | |
| 340 | ${p.how === "delete" ? textField({ name: "typed", label: `Type ${p.confirmWord} to delete`, required: true, autocomplete: "off" }) : null} | |
| 341 | ${btn(`${word} ${p.name}`, { variant: p.how === "delete" ? "danger" : "primary" })} | |
| 342 | ${btn("Cancel", { href: "/infra", variant: "ghost" })} | |
| 343 | </form> | |
| 344 | </div>`; | |
| 345 | } | |
| 346 | ||
| 326 | 347 | /** A restore whose name points elsewhere: where, read before the press that moves it. */ |
| 327 | 348 | export function restoringPage(id: string, name: string, words: string, points: string): Html { |
| 328 | 349 | return html`<div class="narrow-wide"> |
test/pinned-ceiling.test.ts +4 −2
| @@ -353,7 +353,7 @@ describe("cloud account ceiling", () => { | ||
| 353 | 353 | if (/^import\b[^\n]*$/.test(text.slice(text.lastIndexOf("\n", m.index) + 1, m.index))) continue; |
| 354 | 354 | uses++; |
| 355 | 355 | const before = text.slice(Math.max(0, m.index - 80), m.index); |
| 356 | if (!/\bcapped\(app, [\w.]+, $/.test(before) && !/\b(?:read|retire|strays|ensureFirewall|removeFirewall|snapshotKind|takeSnapshot|readSnapshot|dropSnapshot|viewOf|bootRefusal)\((?:app, )?$/.test(before)) bare.push(`${file.slice(src.length + 1)}: …${before.slice(-40)}driverOf(`); | |
| 356 | if (!/\bcapped\(app, [\w.]+, $/.test(before) && !/\b(?:read|retire|strays|ensureFirewall|removeFirewall|snapshotKind|takeSnapshot|readSnapshot|dropSnapshot|viewOf|bootRefusal|endResource)\((?:app, )?$/.test(before)) bare.push(`${file.slice(src.length + 1)}: …${before.slice(-40)}driverOf(`); | |
| 357 | 357 | } |
| 358 | 358 | } |
| 359 | 359 | expect(bare).toEqual([]); |
| @@ -366,7 +366,9 @@ describe("cloud account ceiling", () => { | ||
| 366 | 366 | // view of a machine (#17151), handed to `viewOf`. A bare driverOf still fails the pattern |
| 367 | 367 | // above; only those call names are let through. |
| 368 | 368 | // And the size of a boot config, measured in the plan and sent nowhere. |
| 369 | expect(uses).toBe(17); | |
| 369 | // And the end of a found machine or volume from the cost row (#18046, `endResource`): it only | |
| 370 | // deletes. | |
| 371 | expect(uses).toBe(18); | |
| 370 | 372 | }); |
| 371 | 373 | }); |
| 372 | 374 |
test/spend-tools.test.ts added +188
| @@ -0,0 +1,188 @@ | ||
| 1 | /** | |
| 2 | * Spend tools (#18046): a stop and a delete planned from a cost row and refused on a read-only | |
| 3 | * account, done only after the owner's confirmation (a delete only with the name typed) and | |
| 4 | * audited. The vendor is a stand-in fetch. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts"; | |
| 12 | import { cloudResources } from "../src/actions/infra.ts"; | |
| 13 | import { net } from "../src/actions/pinned.ts"; | |
| 14 | import { confirmEnd, planEnd } from "../src/actions/spend_end.ts"; | |
| 15 | import { nodeAt, pathIn } from "../src/cloud/tree.ts"; | |
| 16 | import { cloudLines } from "../src/tui/screens/cloudtree.ts"; | |
| 17 | import { readProjects } from "../src/cloud/projects.ts"; | |
| 18 | import { READ_ONLY } from "../src/core/cloud_account.ts"; | |
| 19 | import { createSession } from "../src/core/sessions.ts"; | |
| 20 | import { createToken } from "../src/core/tokens.ts"; | |
| 21 | import { createUser, type User } from "../src/core/users.ts"; | |
| 22 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 23 | import { quietLogs } from "./helpers/globals.ts"; | |
| 24 | import { mcpTool } from "./helpers/mcp.ts"; | |
| 25 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 26 | ||
| 27 | quietLogs(); | |
| 28 | ||
| 29 | const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status }); | |
| 30 | const NOW = Date.parse("2026-12-04T12:00:00Z"); | |
| 31 | ||
| 32 | /** What the stand-in DigitalOcean shows: a droplet with a volume, a lone volume. */ | |
| 33 | const DO: Record<string, unknown> = { | |
| 34 | "/v2/projects": { projects: [{ id: "p1", name: "default", is_default: true }] }, | |
| 35 | "/v2/projects/p1/resources": { resources: [] }, | |
| 36 | "/v2/droplets": { droplets: [{ id: 333, name: "old-test", created_at: "2025-01-01T00:00:00Z", region: { slug: "nyc3" }, size_slug: "s-1vcpu-2gb", tags: [] }] }, | |
| 37 | "/v2/volumes": { | |
| 38 | volumes: [ | |
| 39 | { id: "vol-on", name: "disk-on", created_at: "2025-01-01T00:00:00Z", region: { slug: "nyc3" }, size_gigabytes: 10, tags: [], droplet_ids: [333] }, | |
| 40 | { id: "vol-free", name: "disk-free", created_at: "2025-01-01T00:00:00Z", region: { slug: "nyc3" }, size_gigabytes: 10, tags: [], droplet_ids: [] }, | |
| 41 | ], | |
| 42 | }, | |
| 43 | }; | |
| 44 | const shows = async (url: string | URL | Request): Promise<Response> => { | |
| 45 | const body = DO[new URL(String(url)).pathname]; | |
| 46 | return body === undefined ? json({}, 404) : json(body); | |
| 47 | }; | |
| 48 | ||
| 49 | describe("spend tools", () => { | |
| 50 | let dir = ""; | |
| 51 | let app: App; | |
| 52 | let alice: User; | |
| 53 | let bob: User; | |
| 54 | let servers: Servers; | |
| 55 | const calls: string[] = []; | |
| 56 | const path = (kind: string, id: string, account = "main") => `digitalocean/${account}/p1/${kind}:${id}`; | |
| 57 | const audit = () => app.db.query<{ purpose: string; target: string; allowed: number; account: string }, []>("SELECT purpose, target, allowed, account FROM cloud_audit WHERE purpose LIKE 'end:%' ORDER BY id").all(); | |
| 58 | ||
| 59 | beforeAll(async () => { | |
| 60 | dir = await mkdtemp(join(tmpdir(), "forge-spend-")); | |
| 61 | app = createApp({ dataDir: dir, port: 0 }); | |
| 62 | servers = await serve(app); | |
| 63 | await seedPlaces(app.db); | |
| 64 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 65 | if (!made.ok) throw new Error(made.error); | |
| 66 | alice = made.value; | |
| 67 | const other = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 68 | if (!other.ok) throw new Error(other.error); | |
| 69 | bob = other.value; | |
| 70 | cloudNet.fetch = async () => json({ account: { email: "[email protected]", status: "active" } }); | |
| 71 | for (const name of ["main", "ro"]) { | |
| 72 | const added = await addAccount(app, alice, "digitalocean", name, `dop_v1_9Zq4TxLm7Kp2Vb8nWcR5${name}`); | |
| 73 | if (!added.ok) throw new Error(String(added.error)); | |
| 74 | await readProjects(app.db, "digitalocean", name, shows, "t", new Date(NOW - 60_000)); | |
| 75 | } | |
| 76 | allowWrite(app, alice, "digitalocean", "main", true); | |
| 77 | net.fetch = async (url, init) => { | |
| 78 | calls.push(`${init?.method ?? "GET"} ${new URL(url).pathname}`); | |
| 79 | return new Response(null, { status: 204 }); | |
| 80 | }; | |
| 81 | }, 30_000); | |
| 82 | ||
| 83 | afterAll(async () => { | |
| 84 | servers.stop(); | |
| 85 | app.close(); | |
| 86 | await rm(dir, { recursive: true, force: true }); | |
| 87 | }); | |
| 88 | ||
| 89 | test("a stop is planned with what it costs and what stays, and nothing is done until confirmed", async () => { | |
| 90 | const plan = planEnd(app, alice, path("machine", "333"), "stop"); | |
| 91 | if (!plan.ok) throw new Error(plan.error); | |
| 92 | expect(plan.value.says).toContain("Stop machine old-test on digitalocean/main"); | |
| 93 | expect(plan.value.says).toContain("the forge's estimate from list prices"); | |
| 94 | expect(plan.value.steps).toEqual([{ kind: "machine", remote: "333", name: "old-test" }]); | |
| 95 | expect(plan.value.keeps.join(" ")).toContain("the volume disk-on, which keeps billing"); | |
| 96 | expect(calls).toEqual([]); | |
| 97 | const done = await confirmEnd(app, alice, plan.value.id); | |
| 98 | expect(done.ok).toBe(true); | |
| 99 | expect(calls).toEqual(["DELETE /v2/droplets/333"]); | |
| 100 | // The plan is done once. | |
| 101 | expect((await confirmEnd(app, alice, plan.value.id)).ok).toBe(false); | |
| 102 | expect(calls).toHaveLength(1); | |
| 103 | }); | |
| 104 | ||
| 105 | test("a delete takes its volumes' data, is confirmed only by the name typed, and is audited with the plan", async () => { | |
| 106 | calls.length = 0; | |
| 107 | const plan = planEnd(app, alice, path("machine", "333"), "delete"); | |
| 108 | if (!plan.ok) throw new Error(plan.error); | |
| 109 | expect(plan.value.steps.map((s) => s.kind)).toEqual(["machine", "volume"]); | |
| 110 | expect(plan.value.loses.join(" ")).toContain("everything on the volume disk-on: it cannot be recovered"); | |
| 111 | const early = await confirmEnd(app, alice, plan.value.id); | |
| 112 | expect(early).toMatchObject({ ok: false }); | |
| 113 | expect(calls).toEqual([]); | |
| 114 | expect((await confirmEnd(app, alice, plan.value.id, "wrong")).ok).toBe(false); | |
| 115 | expect(calls).toEqual([]); | |
| 116 | const done = await confirmEnd(app, alice, plan.value.id, "old-test"); | |
| 117 | expect(done.ok).toBe(true); | |
| 118 | expect(calls).toEqual(["DELETE /v2/droplets/333", "DELETE /v2/volumes/vol-on"]); | |
| 119 | const rows = audit().filter((r) => r.purpose === "end:delete"); | |
| 120 | expect(rows).toHaveLength(1); | |
| 121 | expect(rows[0]).toMatchObject({ allowed: 1, account: "main" }); | |
| 122 | expect(rows[0]!.target).toContain(alice.id); | |
| 123 | expect(rows[0]!.target).toContain(`plan ${plan.value.id}`); | |
| 124 | expect(rows[0]!.target).toContain("Delete machine old-test"); | |
| 125 | }); | |
| 126 | ||
| 127 | test("a lone volume is deleted; an attached one and a stop of a volume are refused", () => { | |
| 128 | const attached = planEnd(app, alice, path("volume", "vol-on"), "delete"); | |
| 129 | expect(attached).toMatchObject({ ok: false }); | |
| 130 | expect(planEnd(app, alice, path("volume", "vol-free"), "stop")).toMatchObject({ ok: false }); | |
| 131 | const free = planEnd(app, alice, path("volume", "vol-free"), "delete"); | |
| 132 | expect(free.ok && free.value.loses[0]).toContain("everything on the volume disk-free"); | |
| 133 | }); | |
| 134 | ||
| 135 | test("a read-only account is refused both, audited, and nothing reaches the vendor", async () => { | |
| 136 | calls.length = 0; | |
| 137 | for (const how of ["stop", "delete"] as const) expect(planEnd(app, alice, path("machine", "333", "ro"), how)).toEqual({ ok: false, error: READ_ONLY }); | |
| 138 | expect(planEnd(app, alice, path("volume", "vol-free", "ro"), "delete")).toEqual({ ok: false, error: READ_ONLY }); | |
| 139 | expect(audit().filter((r) => r.account === "ro").map((r) => [r.purpose, r.allowed])).toEqual([["end:stop:refused", 0], ["end:delete:refused", 0], ["end:delete:refused", 0]]); | |
| 140 | expect(calls).toEqual([]); | |
| 141 | }); | |
| 142 | ||
| 143 | test("the page offers Stop and Delete only on the write-allowed account, plans without doing, and confirms", async () => { | |
| 144 | calls.length = 0; | |
| 145 | const cookie = `forge_session=${createSession(app.db, alice.id).token}`; | |
| 146 | const first = await (await fetch(`${servers.url}/infra?fragment=1`, { headers: { cookie } })).text(); | |
| 147 | expect(first).toContain(`value="${path("machine", "333")}"`); | |
| 148 | expect(first).not.toContain(`value="${path("machine", "333", "ro")}"`); | |
| 149 | const post = (to: string, form: Record<string, string>) => | |
| 150 | fetch(`${servers.url}${to}`, { method: "POST", redirect: "manual", headers: { cookie, origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(form) }); | |
| 151 | const planned = await post("/infra/end/plan", { id: path("machine", "333"), how: "delete" }); | |
| 152 | const shown = await planned.text(); | |
| 153 | expect(shown).toContain("Delete old-test?"); | |
| 154 | expect(shown).toContain("Type old-test to delete"); | |
| 155 | expect(calls).toEqual([]); | |
| 156 | const plan = /name="plan" value="([a-z0-9]+)"/.exec(shown)![1]!; | |
| 157 | await post("/infra/end/confirm", { plan, typed: "nope" }); | |
| 158 | expect(calls).toEqual([]); | |
| 159 | await post("/infra/end/confirm", { plan, typed: "old-test" }); | |
| 160 | expect(calls).toEqual(["DELETE /v2/droplets/333", "DELETE /v2/volumes/vol-on"]); | |
| 161 | }); | |
| 162 | ||
| 163 | test("the infra tool plans an end, and applies it by the plan's id", async () => { | |
| 164 | calls.length = 0; | |
| 165 | const token = createToken(app.db, alice.id, "admin", "admin").token; | |
| 166 | const planned = await mcpTool(servers.url, token, "infra", { action: "plan", want: { end: path("machine", "333"), how: "stop" } }); | |
| 167 | expect(planned.value.says).toContain("Stop machine old-test"); | |
| 168 | expect(calls).toEqual([]); | |
| 169 | const refused = await mcpTool(servers.url, token, "infra", { action: "plan", want: { end: path("machine", "333", "ro"), how: "stop" } }); | |
| 170 | expect(refused.error).toContain("read-only"); | |
| 171 | const done = await mcpTool(servers.url, token, "infra", { action: "apply", id: planned.value.id }); | |
| 172 | expect(done.value.says).toContain("Stopped old-test"); | |
| 173 | expect(calls).toEqual(["DELETE /v2/droplets/333"]); | |
| 174 | }); | |
| 175 | ||
| 176 | test("the terminal shows the end keys on a writable resource only", () => { | |
| 177 | const v = cloudResources(app, alice, ""); | |
| 178 | if (!v.ok) throw new Error(v.error); | |
| 179 | const mine = cloudLines(v.value, nodeAt(v.value.whole, pathIn(path("machine", "333")))!, 120).join("\n"); | |
| 180 | expect(mine).toContain("t stops it, X deletes it"); | |
| 181 | expect(cloudLines(v.value, nodeAt(v.value.whole, pathIn(path("machine", "333", "ro")))!, 120).join("\n")).not.toContain("X deletes it"); | |
| 182 | }); | |
| 183 | ||
| 184 | test("only a forge admin plans or confirms", async () => { | |
| 185 | expect(planEnd(app, bob, path("machine", "333"), "stop")).toMatchObject({ ok: false }); | |
| 186 | expect(await confirmEnd(app, bob, "anything")).toMatchObject({ ok: false }); | |
| 187 | }); | |
| 188 | }); |
new above
offline
Non-blocking:
unseenis never filled; dead code.