Public: anyone can read this; the crew can change it.
Spend 1: a monthly budget per cloud account, one notice at 80% and one at 100% #18121
Merged 16h 49m ago, live in production
torque/forge:torque/18101-spend-1-a-monthly-budget-per-cloud-accou → main 0 commits fork
25 files
changed +889
−140
- docs/features/cloud-budget.md
- docs/features/infra.md
- src/actions/cloud_ceiling.ts
- src/actions/infra.ts
- src/cloud/budget.ts
- src/core/cloud_account.ts
- src/core/event_audience.ts
- src/core/migration-pins/20261204060000-cloud-budget.pin
- src/core/migrations/20261204060000-cloud-budget.ts
- src/crew/notify.ts
- src/generated/duties.ts
- src/generated/screens.ts
- src/http/lazy_lists.ts
- src/http/marks/settings.json
- src/http/mcp/tools/cloud_account.ts
- src/http/settings_routes.ts
- src/maintain/duties/cloud_budget.ts
- src/tui/screens/budgets.ts
- src/tui/screens/infra.ts
- src/web/pages/cloud.ts
- src/web/pages/infra.ts
- test/cloud-budget.test.ts
- test/infra-page.test.ts
- test/palette-roster.test.ts
- test/tui-budgets.test.ts
docs/features/cloud-budget.md added +18
| @@ -0,0 +1,18 @@ | ||
| 1 | --- | |
| 2 | topic: Hosting forges for others, and getting paid | |
| 3 | row: Cloud budgets | |
| 4 | --- | |
| 5 | ||
| 6 | # Cloud budgets (#18101) | |
| 7 | ||
| 8 | A monthly dollar budget on each cloud account, and one notice at 80% and one at 100% of it. Where each door is: | |
| 9 | ||
| 10 | - **Web:** Cloud accounts (`/settings/cloud`, `src/web/pages/cloud.ts`): "Set budget" beside the ceiling, whole US dollars, empty for none. /infra (`src/web/pages/infra.ts`) shows each account's standing under its figure. | |
| 11 | - **Terminal:** the Cloud budgets screen (`src/tui/screens/budgets.ts`, palette "Cloud budgets", admins): each account's standing, and `b` sets or takes away a budget. The Infrastructure line (`src/tui/screens/infra.ts`) carries the same words. | |
| 12 | - **Agents:** the `cloud_account` MCP tool, verb `set_budget` with `dollars` (omit it for none). | |
| 13 | ||
| 14 | Beside its ceiling, a budget only tells; nothing is stopped (the ceiling is what refuses). | |
| 15 | ||
| 16 | - **What is measured:** the month's projected spend. For DigitalOcean, Hetzner and OVHcloud it is the forge's own estimate from list prices (a month's cost of what it made), marked "the forge's estimate from list prices, not the vendor's bill, as of <day the prices were read>". For AWS and Azure it is the vendor's billed spend so far this month, projected by days (billed x days in month / days elapsed), marked "<vendor>'s billed … as of <day the bill was read>". | |
| 17 | - **Unknown, never $0:** a bill never read or last read with an error, prices never read, a machine with no price, or a cloud whose cost the forge does not read, shows "spend unknown: <why>". /infra shows the same line under each account's figure, and Cloud accounts shows it beside the ceiling. | |
| 18 | - **Notices:** the hourly `cloud-budget` duty (`src/maintain/duties/cloud_budget.ts`, `src/cloud/budget.ts`) claims one row per account, month and threshold in `cloud_budget_notice`, then the admins' notifier URL is told once at 80% and once at 100% (`cloudBudgetLines` in `src/crew/notify.ts`). A second reading in the month, or a restart, sends none; a jump past both sends the 100% notice alone; the next month starts afresh. |
docs/features/infra.md +4
| @@ -16,6 +16,10 @@ What runs on your own cloud, what it's for, what it costs, and when it ends; and | ||
| 16 | 16 | - **API:** `GET /api/v1/admin/infra` (`?plan=<id>` adds a build's steps), `POST /api/v1/admin/infra/plan`, `POST /api/v1/admin/infra/apply` (202). Keep is `POST /api/v1/admin/pinned/:name/keep`. |
| 17 | 17 | - **Agents:** the `infra` MCP tool, in Talk's slot where `experiments` was: `list` (first `says`: one paragraph naming what runs, the dead rows, what ended in the last 30 days with each one's billing sentence, and the total, at most ten names a group then "and N more", so a reader of `says` alone misses no machine; then everything `experiments` listed, plus each machine's end and what it bills for, and `ended`: what retired in the last 30 days or still bills, so a question about one is answered from its row; a dead row's `clear` sentence), `show` (an experiment, a plan id's build, or a machine by name, running or ended, with its billing sentence; a name with no row says "nothing called … has existed here" only when no event ever named it), `plan` a `want`, `check` (looks at the DNS records against Cloudflare now), `apply` a plan id (a plan of dead row `names` clears them; Talk offers it, the person allows it), `keep`, `begin`, `attach`, `record_result`. Only `apply` spends money, so the forge asks the person first. |
| 18 | 18 | |
| 19 | ## Budget (#18101) | |
| 20 | ||
| 21 | Each account's month against its monthly budget is a line under its figure here; how it is set and what it says is in [](cloud-budget.md). | |
| 22 | ||
| 19 | 23 | ## Firewalls (#17070) |
| 20 | 24 | |
| 21 | 25 | A cloud firewall around a machine that stands: DigitalOcean's and Hetzner's, free at both, opening ports 80 and 443 to the world and nothing else inbound (the machine's own firewall stays; this is the second layer, outside it). It is a kind in the plan (`src/cloud/plan.ts`): one `firewall` step, no monthly change, refused when the machine is not there, the account is another or read-only, an orphan stands on it, or the cloud (OVHcloud) has none. It applies by the forge's tag or label, so a machine an Update replaces is behind it too. Its lifetime is the machine's: retiring a forge, by hand or when its end comes, deletes it. Ask for it through the `infra` tool: `plan` with `want: {firewall: "<machine name>"}`, then `apply` its id. The terminal and web compose forms do not offer it yet. |
src/actions/cloud_ceiling.ts +16 −1
| @@ -5,7 +5,8 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import type { App } from "../app.ts"; |
| 8 | import { getCloudAccount, setCeilingDollars, setProjectName } from "../core/cloud_account.ts"; | |
| 8 | import { getCloudAccount, setBudgetDollars, setCeilingDollars, setProjectName } from "../core/cloud_account.ts"; | |
| 9 | import { MAX_BUDGET_DOLLARS } from "../cloud/budget.ts"; | |
| 9 | 10 | import type { User } from "../core/users.ts"; |
| 10 | 11 | import { ackWatch } from "../cloud/watch.ts"; |
| 11 | 12 | import { MAX_WARM, setWarmTarget, warmTargets } from "../cloud/warm_pool.ts"; |
| @@ -23,6 +24,20 @@ export function setCeiling(app: App, actor: User | undefined, provider: string, | ||
| 23 | 24 | return ok(`ceiling is $${dollars} a month`); |
| 24 | 25 | } |
| 25 | 26 | |
| 27 | /** | |
| 28 | * The monthly budget of a cloud account (cloud/budget.ts): whole US dollars from 1, recorded as an | |
| 29 | * event with the old and new value; null takes it away. A budget only tells; nothing is stopped. | |
| 30 | */ | |
| 31 | export function setBudget(app: App, actor: User | undefined, provider: string, name: string, dollars: unknown): Result<string, string> { | |
| 32 | if (actor?.isAdmin !== true) return err("not_found"); | |
| 33 | if (dollars !== null && (typeof dollars !== "number" || !Number.isInteger(dollars) || dollars < 1 || dollars > MAX_BUDGET_DOLLARS)) | |
| 34 | return err(`A budget is a whole number of US dollars a month, from 1 to ${MAX_BUDGET_DOLLARS}; leave it empty for none.`); | |
| 35 | const before = getCloudAccount(app.db, provider, name); | |
| 36 | if (!before || !setBudgetDollars(app.db, provider, name, dollars)) return err("No such credential."); | |
| 37 | app.bus.append({ kind: "cloud.budget", actorId: actor.id, payload: { provider, name, from: before.budgetDollars, to: dollars } }); | |
| 38 | return ok(dollars === null ? "no budget; nothing will be said at 80% or 100%" : `budget is $${dollars} a month; you are told once at 80% and once at 100% of the month's projected spend, and nothing is stopped`); | |
| 39 | } | |
| 40 | ||
| 26 | 41 | const PLACE = /^[a-z]{3,20}:[a-z0-9-]{2,20}:[a-z0-9._-]{2,40}$/; |
| 27 | 42 | |
| 28 | 43 | export function setWarm(app: App, actor: User | undefined, provider: string, name: string, place: unknown, count: unknown): Result<string, string> { |
src/actions/infra.ts +22 −3
| @@ -20,6 +20,8 @@ import { cloudTree, cloudUnknowns, parseCloudQuery, type CloudView } from "../cl | ||
| 20 | 20 | import { requestConsole, type ProviderConsole } from "../cloud/provider_console.ts"; |
| 21 | 21 | import { gatedFetch } from "../cloud/gate.ts"; |
| 22 | 22 | import { resolveSecrets } from "../core/secret_store.ts"; |
| 23 | import { standingOf, type Standing } from "../cloud/budget.ts"; | |
| 24 | import { priced } from "../cloud/ceiling.ts"; | |
| 23 | 25 | import { billingSentence, billsOf, existsAtProvider, type Bills } from "../cloud/billing.ts"; |
| 24 | 26 | import { specWordsOf } from "../cloud/dns_record.ts"; |
| 25 | 27 | import { experiments, type Experiments } from "../cloud/experiments.ts"; |
| @@ -56,6 +58,16 @@ export interface Meter { | ||
| 56 | 58 | readonly monthlyCents: number; |
| 57 | 59 | readonly ceilingCents: number; |
| 58 | 60 | readonly writable: boolean; |
| 61 | /** | |
| 62 | * Whether the forge makes machines on this cloud, so its own reckoning of `monthlyCents` means | |
| 63 | * something; false for a cloud it only reads. | |
| 64 | */ | |
| 65 | readonly makes: boolean; | |
| 66 | /** | |
| 67 | * The month's budget against its projected spend, each figure with its source and date | |
| 68 | * (`cloud/budget.ts`); spend `unknown` is never 0. | |
| 69 | */ | |
| 70 | readonly budget: Standing; | |
| 59 | 71 | } |
| 60 | 72 | |
| 61 | 73 | /** One machine that bills, as every door shows it. */ |
| @@ -288,12 +300,17 @@ function reckon(app: App, now: Date): { view: InfraView; rows: Map<string, Runni | ||
| 288 | 300 | }; |
| 289 | 301 | }); |
| 290 | 302 | const makers = new Set<string>(TARGETS.filter((t) => t.status === "first").map((t) => t.id)); |
| 291 | const accounts = listCloudAccounts(db).filter((a) => makers.has(a.provider)); | |
| 303 | const all = listCloudAccounts(db); | |
| 304 | const accounts = all.filter((a) => makers.has(a.provider)); | |
| 292 | 305 | // What each account costs: its rows' monthly cost, as the ceiling reckons them (`rowCents`). |
| 293 | 306 | const spend = new Map<string, number>(); |
| 294 | 307 | for (const p of pinned) spend.set(`${p.target}/${p.account}`, (spend.get(`${p.target}/${p.account}`) ?? 0) + (cents.get(p.name) ?? 0)); |
| 295 | 308 | for (const d of databases) spend.set(d.account, (spend.get(d.account) ?? 0) + d.monthlyCents); |
| 296 | const meters = accounts | |
| 309 | const reads = accountReads(db, now); | |
| 310 | const prices = priced(db); | |
| 311 | // An account that has a budget is listed whatever its cloud, so its spend is never hidden. | |
| 312 | const meters = all | |
| 313 | .filter((a) => makers.has(a.provider) || a.budgetDollars !== null) | |
| 297 | 314 | .map((a): Meter => { |
| 298 | 315 | const account = `${a.provider}/${a.name}`; |
| 299 | 316 | return { |
| @@ -303,9 +320,11 @@ function reckon(app: App, now: Date): { view: InfraView; rows: Map<string, Runni | ||
| 303 | 320 | monthlyCents: spend.get(account) ?? 0, |
| 304 | 321 | ceilingCents: a.ceilingDollars * 100, |
| 305 | 322 | writable: a.writeAllowed, |
| 323 | makes: makers.has(a.provider), | |
| 324 | budget: standingOf(db, a, now, prices, reads), | |
| 306 | 325 | }; |
| 307 | 326 | }) |
| 308 | .filter((m) => m.writable || m.monthlyCents > 0); | |
| 327 | .filter((m) => m.writable || m.monthlyCents > 0 || m.budget.budgetDollars !== null); | |
| 309 | 328 | const drift = accounts.flatMap((a): Drift[] => { |
| 310 | 329 | const orphans = lastReading(db, a.provider, a.name)?.resources.filter((r) => r.verdict === "orphan") ?? []; |
| 311 | 330 | if (orphans.length === 0) return []; |
src/cloud/budget.ts added +177
| @@ -0,0 +1,177 @@ | ||
| 1 | /** | |
| 2 | * The monthly budget of a cloud account (#18101): a dollar figure an admin sets beside the ceiling, | |
| 3 | * and the one notice at 80% and the one at 100% of it. Nothing is stopped: a budget tells, the | |
| 4 | * ceiling (`ceiling.ts`) refuses. | |
| 5 | * | |
| 6 | * What is measured is the month's projected spend, and every figure says where it comes from: | |
| 7 | * - "billed": the vendor's own bill (AWS, Azure) for this month so far, projected to the month's | |
| 8 | * end by days: projected = month-to-date x days in month / days elapsed (UTC; the day in | |
| 9 | * progress counts as elapsed). As of the time the bill was read. | |
| 10 | * - "estimate": the forge's own reckoning from the machines and databases it made, at list prices | |
| 11 | * (`accountCents`), already a month's cost. As of the day the price catalog was read. | |
| 12 | * An account whose spend could not be read is `unknown` with the reason, never $0: a cloud whose | |
| 13 | * bill the forge does not read and does not make machines on, a bill never read or last read with | |
| 14 | * an error, a machine or database the catalog has no price for. | |
| 15 | * | |
| 16 | * A notice is claimed by writing its row (account, month, percent) before it is made, so a second | |
| 17 | * reading in the month, or a restart, sends none. A reading that jumps over 80% to past 100% sends | |
| 18 | * the 100% notice alone, and a lower threshold is never sent after a higher one in the same month. | |
| 19 | */ | |
| 20 | ||
| 21 | import type { Database } from "bun:sqlite"; | |
| 22 | import type { EventBus } from "../core/events.ts"; | |
| 23 | import { listCloudAccounts, type CloudAccount } from "../core/cloud_account.ts"; | |
| 24 | import { listDatabases } from "../core/managed_database.ts"; | |
| 25 | import { listPinned, placeIdOf } from "../core/pinned.ts"; | |
| 26 | import { accountReads, type AccountRead } from "./projects.ts"; | |
| 27 | import { databaseCents } from "./database.ts"; | |
| 28 | import { accountCents, priced, type Priced } from "./ceiling.ts"; | |
| 29 | import { readTimes } from "./places_read.ts"; | |
| 30 | import { dollars } from "./prices.ts"; | |
| 31 | import { LABEL, isProvider } from "./providers.ts"; | |
| 32 | import { TARGETS } from "./targets.ts"; | |
| 33 | ||
| 34 | /** The thresholds a notice is sent at, in percent of the budget. */ | |
| 35 | export const THRESHOLDS = [80, 100] as const; | |
| 36 | export const MAX_BUDGET_DOLLARS = 100_000; | |
| 37 | ||
| 38 | export type Source = "billed" | "estimate"; | |
| 39 | ||
| 40 | export type Spend = | |
| 41 | | { readonly kind: "known"; readonly cents: number; readonly source: Source; /** ISO time of the reading it rests on. */ readonly asOf: string; /** The sentence for the figure, with its source. */ readonly how: string } | |
| 42 | | { readonly kind: "unknown"; readonly why: string }; | |
| 43 | ||
| 44 | export interface Standing { | |
| 45 | readonly provider: string; | |
| 46 | readonly account: string; | |
| 47 | readonly budgetDollars: number | null; | |
| 48 | readonly spend: Spend; | |
| 49 | /** Spend over budget in whole percent, rounded down; null with no budget or no spend read. */ | |
| 50 | readonly percent: number | null; | |
| 51 | } | |
| 52 | ||
| 53 | const MAKERS: ReadonlySet<string> = new Set(TARGETS.filter((t) => t.status === "first").map((t) => t.id)); | |
| 54 | const day = (iso: string): string => iso.slice(0, 10); | |
| 55 | const label = (provider: string): string => (isProvider(provider) ? LABEL[provider] : provider); | |
| 56 | ||
| 57 | /** | |
| 58 | * Projected month end from the month so far: cents x days in month / days elapsed (the day in | |
| 59 | * progress counts). | |
| 60 | */ | |
| 61 | export function projectCents(monthToDateCents: number, now: Date): number { | |
| 62 | const days = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0)).getUTCDate(); | |
| 63 | return Math.round((monthToDateCents * days) / now.getUTCDate()); | |
| 64 | } | |
| 65 | ||
| 66 | /** | |
| 67 | * Whether the catalog prices every machine and database an account holds; else the first thing it | |
| 68 | * does not. | |
| 69 | */ | |
| 70 | function unpriced(db: Database, provider: string, account: string, prices: Priced): string | undefined { | |
| 71 | for (const p of listPinned(db)) { | |
| 72 | if (p.target !== provider || p.account !== account || (p.remote === "" && p.volume === "")) continue; | |
| 73 | const unlisted = prices.sameSize(p.target, p.size) ?? prices.dearest(p.target, p.datacenter); | |
| 74 | const known = p.state === "retired" ? (p.volume === "" ? 0 : (prices.volume(p.target) ?? prices.forge(placeIdOf(p)) ?? unlisted)) : (prices.forge(placeIdOf(p)) ?? unlisted); | |
| 75 | if (known === undefined) return `the forge has no price for ${p.size} in ${p.datacenter} on ${label(provider)}`; | |
| 76 | } | |
| 77 | for (const d of listDatabases(db)) | |
| 78 | if (d.account === `${provider}/${account}` && (d.remote !== "" || d.state === "creating") && databaseCents(d.size) === undefined) return `the forge has no price for the ${d.size} database ${d.name}`; | |
| 79 | return undefined; | |
| 80 | } | |
| 81 | ||
| 82 | function billed(read: AccountRead | undefined, provider: string, now: Date): Spend { | |
| 83 | const bill = read?.bill; | |
| 84 | if (bill === undefined || bill === null || bill.readAt === "") return { kind: "unknown", why: `${label(provider)}'s bill has not been read yet` }; | |
| 85 | const start = `${now.toISOString().slice(0, 7)}-01`; | |
| 86 | const month = bill.months.find((m) => m.from === start); | |
| 87 | if (month === undefined && bill.error !== "") return { kind: "unknown", why: `${label(provider)}'s bill could not be read: ${bill.error}` }; | |
| 88 | const sofar = month?.cents ?? 0; | |
| 89 | const cents = projectCents(sofar, now); | |
| 90 | return { kind: "known", cents, source: "billed", asOf: bill.readAt, how: `${dollars(cents)} projected for the month: ${label(provider)}'s billed ${dollars(sofar)} so far${month?.estimated === true ? " (the vendor marks it an estimate that may still change)" : ""}, as of ${day(bill.readAt)}` }; | |
| 91 | } | |
| 92 | ||
| 93 | function estimated(db: Database, provider: string, account: string, prices: Priced): Spend { | |
| 94 | const read = readTimes(db)[provider]; | |
| 95 | if (read === undefined) return { kind: "unknown", why: `the forge has not read ${label(provider)}'s prices` }; | |
| 96 | const no = unpriced(db, provider, account, prices); | |
| 97 | if (no !== undefined) return { kind: "unknown", why: no }; | |
| 98 | const cents = accountCents(db, provider, account, prices); | |
| 99 | return { kind: "known", cents, source: "estimate", asOf: read, how: `${dollars(cents)} a month: the forge's estimate from list prices, not ${label(provider)}'s bill, as of ${day(read)}` }; | |
| 100 | } | |
| 101 | ||
| 102 | /** One account's budget against what the month is projected to cost, from the database alone. */ | |
| 103 | export function standingOf(db: Database, a: Pick<CloudAccount, "provider" | "name" | "budgetDollars">, now: Date, prices: Priced = priced(db), reads: readonly AccountRead[] = accountReads(db, now)): Standing { | |
| 104 | const { provider, name: account, budgetDollars } = a; | |
| 105 | const spend: Spend = MAKERS.has(provider) | |
| 106 | ? estimated(db, provider, account, prices) | |
| 107 | : provider === "aws" || provider === "azure" | |
| 108 | ? billed(reads.find((r) => r.provider === provider && r.account === account), provider, now) | |
| 109 | : { kind: "unknown", why: `the forge reads no cost for ${label(provider)}` }; | |
| 110 | const percent = budgetDollars === null || budgetDollars <= 0 || spend.kind === "unknown" ? null : Math.floor(spend.cents / budgetDollars); | |
| 111 | return { provider, account, budgetDollars, spend, percent }; | |
| 112 | } | |
| 113 | ||
| 114 | /** The standing in a sentence: "budget $40: 50% ..." or "budget $40: spend unknown (why)". */ | |
| 115 | export function standingWords(s: Standing): string { | |
| 116 | const head = s.budgetDollars === null ? "no budget set" : `budget $${s.budgetDollars} a month`; | |
| 117 | if (s.spend.kind === "unknown") return `${head}; spend unknown: ${s.spend.why}`; | |
| 118 | return `${head}${s.percent === null ? "" : `, ${s.percent}% of it`}; ${s.spend.how}`; | |
| 119 | } | |
| 120 | ||
| 121 | export interface Notice { | |
| 122 | readonly provider: string; | |
| 123 | readonly account: string; | |
| 124 | readonly month: string; | |
| 125 | readonly percent: number; | |
| 126 | readonly spendCents: number; | |
| 127 | readonly budgetDollars: number; | |
| 128 | readonly source: Source; | |
| 129 | } | |
| 130 | ||
| 131 | /** | |
| 132 | * Read every account with a budget against the month and claim the notice each has newly reached: | |
| 133 | * the row is written first, then a `cloud.budget_notice` event says so (the notifier tells the | |
| 134 | * admins from it). Returns what was claimed; a reading that reaches nothing new returns nothing. | |
| 135 | */ | |
| 136 | export function noticeBudgets(db: Database, bus: EventBus, now: Date): Notice[] { | |
| 137 | const month = now.toISOString().slice(0, 7); | |
| 138 | const prices = priced(db); | |
| 139 | const reads = accountReads(db, now); | |
| 140 | const claim = db.query("INSERT OR IGNORE INTO cloud_budget_notice (provider, account, month, percent, noticed_at, spend_cents, budget_dollars, source) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)"); | |
| 141 | const top = db.query<{ top: number | null }, [string, string, string]>("SELECT MAX(percent) AS top FROM cloud_budget_notice WHERE provider = ?1 AND account = ?2 AND month = ?3"); | |
| 142 | const made: Notice[] = []; | |
| 143 | for (const a of listCloudAccounts(db)) { | |
| 144 | if (a.budgetDollars === null || a.budgetDollars <= 0) continue; | |
| 145 | const s = standingOf(db, a, now, prices, reads); | |
| 146 | if (s.spend.kind === "unknown" || s.percent === null) continue; | |
| 147 | const reached = Math.max(0, ...THRESHOLDS.filter((t) => s.percent! >= t)); | |
| 148 | if (reached === 0 || reached <= (top.get(a.provider, a.name, month)?.top ?? 0)) continue; | |
| 149 | const row = { provider: a.provider, account: a.name, month, percent: reached, spendCents: s.spend.cents, budgetDollars: a.budgetDollars, source: s.spend.source }; | |
| 150 | if (claim.run(a.provider, a.name, month, reached, now.toISOString(), row.spendCents, row.budgetDollars, row.source).changes === 0) continue; | |
| 151 | bus.append({ kind: "cloud.budget_notice", payload: row }); | |
| 152 | made.push(row); | |
| 153 | } | |
| 154 | return made; | |
| 155 | } | |
| 156 | ||
| 157 | /** The sentence a notice is told in; it says the figure's source and that nothing was stopped. */ | |
| 158 | export function noticeWords(n: Notice): string { | |
| 159 | const from = n.source === "billed" ? `${label(n.provider)}'s billed spend so far, projected to the month's end` : "the forge's estimate from list prices, not the vendor's bill"; | |
| 160 | return `Cloud account ${n.provider}/${n.account} is at ${n.percent >= 100 ? "100%" : "80%"} of its $${n.budgetDollars} monthly budget: ${dollars(n.spendCents)} projected for ${n.month} (${from}). Nothing was stopped.`; | |
| 161 | } | |
| 162 | ||
| 163 | /** | |
| 164 | * This month's notices, each as an ask line for the notifier; the id holds the month so each is | |
| 165 | * news once. | |
| 166 | */ | |
| 167 | export function budgetNotices(db: Database, now: Date): { id: string; line: string; items: readonly string[]; link: string }[] { | |
| 168 | return db | |
| 169 | .query<{ provider: string; account: string; month: string; percent: number; spendCents: number; budgetDollars: number; source: string }, [string]>( | |
| 170 | "SELECT provider, account, month, percent, spend_cents AS spendCents, budget_dollars AS budgetDollars, source FROM cloud_budget_notice WHERE month = ?1 ORDER BY noticed_at, percent", | |
| 171 | ) | |
| 172 | .all(now.toISOString().slice(0, 7)) | |
| 173 | .map((n) => { | |
| 174 | const id = `budget:${n.provider}/${n.account}:${n.month}:${n.percent}`; | |
| 175 | return { id, line: noticeWords({ ...n, source: n.source as Source }), items: [id], link: "/infra" }; | |
| 176 | }); | |
| 177 | } |
src/core/cloud_account.ts +13
| @@ -57,6 +57,11 @@ export interface CloudAccount { | ||
| 57 | 57 | readonly writeAllowed: boolean; |
| 58 | 58 | /** The most the forge will let this account cost a month, whole US dollars (ceiling.ts). */ |
| 59 | 59 | readonly ceilingDollars: number; |
| 60 | /** | |
| 61 | * The monthly budget the owner is told about at 80% and 100%, whole US dollars; null when none is | |
| 62 | * set (cloud/budget.ts). | |
| 63 | */ | |
| 64 | readonly budgetDollars: number | null; | |
| 60 | 65 | /** |
| 61 | 66 | * The cloud project its machines and volumes are filed in (DigitalOcean); empty is the provider's |
| 62 | 67 | * default. |
| @@ -71,6 +76,7 @@ interface Row { | ||
| 71 | 76 | verified_at: string | null; |
| 72 | 77 | write_allowed: number; |
| 73 | 78 | ceiling_dollars: number; |
| 79 | budget_dollars: number | null; | |
| 74 | 80 | project: string; |
| 75 | 81 | } |
| 76 | 82 | |
| @@ -81,6 +87,7 @@ const toAccount = (r: Row): CloudAccount => ({ | ||
| 81 | 87 | verifiedAt: r.verified_at, |
| 82 | 88 | writeAllowed: r.write_allowed === 1, |
| 83 | 89 | ceilingDollars: r.ceiling_dollars, |
| 90 | budgetDollars: r.budget_dollars ?? null, | |
| 84 | 91 | project: r.project ?? "", |
| 85 | 92 | }); |
| 86 | 93 | |
| @@ -142,6 +149,12 @@ export function setCeilingDollars(db: Database, provider: string, name: string, | ||
| 142 | 149 | return db.query("UPDATE cloud_account SET ceiling_dollars = ?3 WHERE provider = ?1 AND name = ?2").run(provider, name, dollars).changes > 0; |
| 143 | 150 | } |
| 144 | 151 | |
| 152 | /** Set the monthly budget in whole US dollars; null takes it away. */ | |
| 153 | export function setBudgetDollars(db: Database, provider: string, name: string, dollars: number | null): boolean { | |
| 154 | table(db); | |
| 155 | return db.query("UPDATE cloud_account SET budget_dollars = ?3 WHERE provider = ?1 AND name = ?2").run(provider, name, dollars).changes > 0; | |
| 156 | } | |
| 157 | ||
| 145 | 158 | export function setProjectName(db: Database, provider: string, name: string, project: string): boolean { |
| 146 | 159 | table(db); |
| 147 | 160 | return db.query("UPDATE cloud_account SET project = ?3 WHERE provider = ?1 AND name = ?2").run(provider, name, project).changes > 0; |
src/core/event_audience.ts +4
| @@ -325,6 +325,10 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 325 | 325 | kind === "forge.updates_taken" || |
| 326 | 326 | kind === "cloud.write_allowed" || |
| 327 | 327 | kind === "cloud.ceiling" || |
| 328 | // A cloud account's monthly budget and its 80% / 100% notices are spend | |
| 329 | // configuration, the admins' to hear (`cloud/budget.ts`, #18101). | |
| 330 | kind === "cloud.budget" || | |
| 331 | kind === "cloud.budget_notice" || | |
| 328 | 332 | // An admin acknowledging a resource as not the forge's (`cloud/watch.ts`, #16329). |
| 329 | 333 | kind === "cloud.watch_acknowledged" || |
| 330 | 334 | kind === "cloud.project" || |
src/core/migration-pins/20261204060000-cloud-budget.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 614cc5349e37cf51b97265b3495728a201673a31c3a5669ecc2e435fb8e97aae |
src/core/migrations/20261204060000-cloud-budget.ts added +27
| @@ -0,0 +1,27 @@ | ||
| 1 | // A monthly budget in whole US dollars on a cloud account, null until an admin sets one (#18101), | |
| 2 | // and the notices sent against it: one row per account, month and threshold (80 or 100), written | |
| 3 | // before the notice is made, so a restart or a second reading never sends it twice. The | |
| 4 | // cloud_account table is otherwise made on first use; made here too, in its same shape, so the | |
| 5 | // column has a table to join. Additive. | |
| 6 | export default ` | |
| 7 | CREATE TABLE IF NOT EXISTS cloud_account ( | |
| 8 | provider TEXT NOT NULL, | |
| 9 | name TEXT NOT NULL, | |
| 10 | summary TEXT NOT NULL DEFAULT '', | |
| 11 | verified_at TEXT, | |
| 12 | write_allowed INTEGER NOT NULL DEFAULT 0, | |
| 13 | PRIMARY KEY (provider, name) | |
| 14 | ); | |
| 15 | ALTER TABLE cloud_account ADD COLUMN budget_dollars INTEGER; | |
| 16 | CREATE TABLE cloud_budget_notice ( | |
| 17 | provider TEXT NOT NULL, | |
| 18 | account TEXT NOT NULL, | |
| 19 | month TEXT NOT NULL, | |
| 20 | percent INTEGER NOT NULL, | |
| 21 | noticed_at TEXT NOT NULL, | |
| 22 | spend_cents INTEGER NOT NULL, | |
| 23 | budget_dollars INTEGER NOT NULL, | |
| 24 | source TEXT NOT NULL, | |
| 25 | PRIMARY KEY (provider, account, month, percent) | |
| 26 | ) WITHOUT ROWID; | |
| 27 | `; |
src/crew/notify.ts +12
| @@ -21,6 +21,7 @@ | ||
| 21 | 21 | */ |
| 22 | 22 | |
| 23 | 23 | import { watchNeeds } from "../cloud/watch.ts"; |
| 24 | import { budgetNotices } from "../cloud/budget.ts"; | |
| 24 | 25 | import { blockedLines } from "../actions/egress_refused.ts"; |
| 25 | 26 | import { scheduleLines } from "../actions/schedules.ts"; |
| 26 | 27 | import { newAccountLines } from "../actions/accounts.ts"; |
| @@ -67,6 +68,8 @@ const BACKOFF_MAX_MS = HOUR_MS; | ||
| 67 | 68 | |
| 68 | 69 | /** Events after which the set of asks may have changed. */ |
| 69 | 70 | const WAKES = new Set([ |
| 71 | // A cloud account reached 80% or 100% of its monthly budget (`cloud/budget.ts`). | |
| 72 | "cloud.budget_notice", | |
| 70 | 73 | "clog.started", |
| 71 | 74 | "run.finished", |
| 72 | 75 | "app.serving", |
| @@ -273,6 +276,14 @@ export function cloudWatchLines( | ||
| 273 | 276 | }); |
| 274 | 277 | } |
| 275 | 278 | |
| 279 | /** | |
| 280 | * The admin hears once, per account and month, at 80% and at 100% of a cloud budget (#18101); the | |
| 281 | * rows are the cloud budget duty's. | |
| 282 | */ | |
| 283 | export function cloudBudgetLines(app: App, user: User, now = Date.now()): { id: string; line: string; items: readonly string[]; link: string }[] { | |
| 284 | return !user.isAdmin || user.kind !== "user" ? [] : budgetNotices(app.db, new Date(now)); | |
| 285 | } | |
| 286 | ||
| 276 | 287 | /** The admin hears of a snapshot that did not land off the box, or a stale mirror, once per cause. */ |
| 277 | 288 | export function mirrorLines( |
| 278 | 289 | app: App, |
| @@ -546,6 +557,7 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier { | ||
| 546 | 557 | ...domainDrillLines(app, user, now(), options.forgeUrl), |
| 547 | 558 | ...mirrorLines(app, user, now()), |
| 548 | 559 | ...cloudWatchLines(app, user, now()), |
| 560 | ...cloudBudgetLines(app, user, now()), | |
| 549 | 561 | ...redLines(app, user, now()), |
| 550 | 562 | ...alarmLines(app, user, now(), options.alarms?.()), |
| 551 | 563 | ...clogLines(app, user), |
src/generated/duties.ts +1
| @@ -11,6 +11,7 @@ export const DUTY_MODULES: readonly (readonly [string, () => { duty?: unknown }] | ||
| 11 | 11 | ["backup_growth.ts", () => require("../maintain/duties/backup_growth.ts")], |
| 12 | 12 | ["chapter_stall.ts", () => require("../maintain/duties/chapter_stall.ts")], |
| 13 | 13 | ["client_keys.ts", () => require("../maintain/duties/client_keys.ts")], |
| 14 | ["cloud_budget.ts", () => require("../maintain/duties/cloud_budget.ts")], | |
| 14 | 15 | ["cloud_projects.ts", () => require("../maintain/duties/cloud_projects.ts")], |
| 15 | 16 | ["cloud_watch.ts", () => require("../maintain/duties/cloud_watch.ts")], |
| 16 | 17 | ["daily_proof.ts", () => require("../maintain/duties/daily_proof.ts")], |
src/generated/screens.ts +125 −123
| @@ -19,123 +19,124 @@ import * as s14 from "../tui/screens/bills.ts"; | ||
| 19 | 19 | import * as s15 from "../tui/screens/boards.ts"; |
| 20 | 20 | import * as s16 from "../tui/screens/bottleneck.ts"; |
| 21 | 21 | import * as s17 from "../tui/screens/buckets.ts"; |
| 22 | import * as s18 from "../tui/screens/bugs.ts"; | |
| 23 | import * as s19 from "../tui/screens/bulk.ts"; | |
| 24 | import * as s20 from "../tui/screens/captain.ts"; | |
| 25 | import * as s21 from "../tui/screens/childcredit.ts"; | |
| 26 | import * as s22 from "../tui/screens/claim_link.ts"; | |
| 27 | import * as s23 from "../tui/screens/claim_start.ts"; | |
| 28 | import * as s24 from "../tui/screens/client_clouds.ts"; | |
| 29 | import * as s25 from "../tui/screens/cloud.ts"; | |
| 30 | import * as s26 from "../tui/screens/cloudtree.ts"; | |
| 31 | import * as s27 from "../tui/screens/codes.ts"; | |
| 32 | import * as s28 from "../tui/screens/connections.ts"; | |
| 33 | import * as s29 from "../tui/screens/controls.ts"; | |
| 34 | import * as s30 from "../tui/screens/cores.ts"; | |
| 35 | import * as s31 from "../tui/screens/crewbudgets.ts"; | |
| 36 | import * as s32 from "../tui/screens/crewfallback.ts"; | |
| 37 | import * as s33 from "../tui/screens/crewhandover.ts"; | |
| 38 | import * as s34 from "../tui/screens/crewkey.ts"; | |
| 39 | import * as s35 from "../tui/screens/crewsplits.ts"; | |
| 40 | import * as s36 from "../tui/screens/crewtop.ts"; | |
| 41 | import * as s37 from "../tui/screens/dataset.ts"; | |
| 42 | import * as s38 from "../tui/screens/design.ts"; | |
| 43 | import * as s39 from "../tui/screens/design_gallery.ts"; | |
| 44 | import * as s40 from "../tui/screens/devices.ts"; | |
| 45 | import * as s41 from "../tui/screens/disks.ts"; | |
| 46 | import * as s42 from "../tui/screens/displays.ts"; | |
| 47 | import * as s43 from "../tui/screens/domains.ts"; | |
| 48 | import * as s44 from "../tui/screens/dotfiles.ts"; | |
| 49 | import * as s45 from "../tui/screens/drift.ts"; | |
| 50 | import * as s46 from "../tui/screens/dutybudgets.ts"; | |
| 51 | import * as s47 from "../tui/screens/dutyswitch.ts"; | |
| 52 | import * as s48 from "../tui/screens/economics.ts"; | |
| 53 | import * as s49 from "../tui/screens/edgeonly.ts"; | |
| 54 | import * as s50 from "../tui/screens/experiments.ts"; | |
| 55 | import * as s51 from "../tui/screens/featurefeed.ts"; | |
| 56 | import * as s52 from "../tui/screens/features.ts"; | |
| 57 | import * as s53 from "../tui/screens/featureswitch.ts"; | |
| 58 | import * as s54 from "../tui/screens/feed.ts"; | |
| 59 | import * as s55 from "../tui/screens/flowsall.ts"; | |
| 60 | import * as s56 from "../tui/screens/footing.ts"; | |
| 61 | import * as s57 from "../tui/screens/forgeready.ts"; | |
| 62 | import * as s58 from "../tui/screens/forges.ts"; | |
| 63 | import * as s59 from "../tui/screens/forgeview.ts"; | |
| 64 | import * as s60 from "../tui/screens/front.ts"; | |
| 65 | import * as s61 from "../tui/screens/frontms.ts"; | |
| 66 | import * as s62 from "../tui/screens/funnel.ts"; | |
| 67 | import * as s63 from "../tui/screens/games.ts"; | |
| 68 | import * as s64 from "../tui/screens/gifts.ts"; | |
| 69 | import * as s65 from "../tui/screens/health_voice.ts"; | |
| 70 | import * as s66 from "../tui/screens/home_pins.ts"; | |
| 71 | import * as s67 from "../tui/screens/hostreach.ts"; | |
| 72 | import * as s68 from "../tui/screens/infra.ts"; | |
| 73 | import * as s69 from "../tui/screens/inventory.ts"; | |
| 74 | import * as s70 from "../tui/screens/invites.ts"; | |
| 75 | import * as s71 from "../tui/screens/knobs.ts"; | |
| 76 | import * as s72 from "../tui/screens/lapsed.ts"; | |
| 77 | import * as s73 from "../tui/screens/limits.ts"; | |
| 78 | import * as s74 from "../tui/screens/loopstalls.ts"; | |
| 79 | import * as s75 from "../tui/screens/madefrom.ts"; | |
| 80 | import * as s76 from "../tui/screens/maintainruns.ts"; | |
| 81 | import * as s77 from "../tui/screens/maintenance.ts"; | |
| 82 | import * as s78 from "../tui/screens/maintenanceweek.ts"; | |
| 83 | import * as s79 from "../tui/screens/mergedbranches.ts"; | |
| 84 | import * as s80 from "../tui/screens/mirrorpacks.ts"; | |
| 85 | import * as s81 from "../tui/screens/model.ts"; | |
| 86 | import * as s82 from "../tui/screens/money.ts"; | |
| 87 | import * as s83 from "../tui/screens/newissue.ts"; | |
| 88 | import * as s84 from "../tui/screens/next.ts"; | |
| 89 | import * as s85 from "../tui/screens/nowlist.ts"; | |
| 90 | import * as s86 from "../tui/screens/offers.ts"; | |
| 91 | import * as s87 from "../tui/screens/offsite.ts"; | |
| 92 | import * as s88 from "../tui/screens/orggrants.ts"; | |
| 93 | import * as s89 from "../tui/screens/orgteams.ts"; | |
| 94 | import * as s90 from "../tui/screens/originahead.ts"; | |
| 95 | import * as s91 from "../tui/screens/owner.ts"; | |
| 96 | import * as s92 from "../tui/screens/packrepos.ts"; | |
| 97 | import * as s93 from "../tui/screens/payments.ts"; | |
| 98 | import * as s94 from "../tui/screens/people.ts"; | |
| 99 | import * as s95 from "../tui/screens/pinned.ts"; | |
| 100 | import * as s96 from "../tui/screens/planner.ts"; | |
| 101 | import * as s97 from "../tui/screens/planrow.ts"; | |
| 102 | import * as s98 from "../tui/screens/plans.ts"; | |
| 103 | import * as s99 from "../tui/screens/previewdirs.ts"; | |
| 104 | import * as s100 from "../tui/screens/profile.ts"; | |
| 105 | import * as s101 from "../tui/screens/quotas.ts"; | |
| 106 | import * as s102 from "../tui/screens/recoverykit.ts"; | |
| 107 | import * as s103 from "../tui/screens/refused.ts"; | |
| 108 | import * as s104 from "../tui/screens/registry_items.ts"; | |
| 109 | import * as s105 from "../tui/screens/repolist.ts"; | |
| 110 | import * as s106 from "../tui/screens/requests.ts"; | |
| 111 | import * as s107 from "../tui/screens/resilience.ts"; | |
| 112 | import * as s108 from "../tui/screens/returning.ts"; | |
| 113 | import * as s109 from "../tui/screens/returns.ts"; | |
| 114 | import * as s110 from "../tui/screens/scorecard.ts"; | |
| 115 | import * as s111 from "../tui/screens/scrapes.ts"; | |
| 116 | import * as s112 from "../tui/screens/secrets.ts"; | |
| 117 | import * as s113 from "../tui/screens/sentinel.ts"; | |
| 118 | import * as s114 from "../tui/screens/series.ts"; | |
| 119 | import * as s115 from "../tui/screens/ship_time.ts"; | |
| 120 | import * as s116 from "../tui/screens/slowpages.ts"; | |
| 121 | import * as s117 from "../tui/screens/sold.ts"; | |
| 122 | import * as s118 from "../tui/screens/spend.ts"; | |
| 123 | import * as s119 from "../tui/screens/stalepulls.ts"; | |
| 124 | import * as s120 from "../tui/screens/subscriptions.ts"; | |
| 125 | import * as s121 from "../tui/screens/system.ts"; | |
| 126 | import * as s122 from "../tui/screens/tab.ts"; | |
| 127 | import * as s123 from "../tui/screens/teams.ts"; | |
| 128 | import * as s124 from "../tui/screens/telemetry.ts"; | |
| 129 | import * as s125 from "../tui/screens/tell_undo.ts"; | |
| 130 | import * as s126 from "../tui/screens/traces.ts"; | |
| 131 | import * as s127 from "../tui/screens/traffic.ts"; | |
| 132 | import * as s128 from "../tui/screens/trafficview.ts"; | |
| 133 | import * as s129 from "../tui/screens/valves.ts"; | |
| 134 | import * as s130 from "../tui/screens/waiting.ts"; | |
| 135 | import * as s131 from "../tui/screens/waiting_for_me.ts"; | |
| 136 | import * as s132 from "../tui/screens/wayback.ts"; | |
| 137 | import * as s133 from "../tui/screens/weekcard.ts"; | |
| 138 | import * as s134 from "../tui/screens/whocan.ts"; | |
| 22 | import * as s18 from "../tui/screens/budgets.ts"; | |
| 23 | import * as s19 from "../tui/screens/bugs.ts"; | |
| 24 | import * as s20 from "../tui/screens/bulk.ts"; | |
| 25 | import * as s21 from "../tui/screens/captain.ts"; | |
| 26 | import * as s22 from "../tui/screens/childcredit.ts"; | |
| 27 | import * as s23 from "../tui/screens/claim_link.ts"; | |
| 28 | import * as s24 from "../tui/screens/claim_start.ts"; | |
| 29 | import * as s25 from "../tui/screens/client_clouds.ts"; | |
| 30 | import * as s26 from "../tui/screens/cloud.ts"; | |
| 31 | import * as s27 from "../tui/screens/cloudtree.ts"; | |
| 32 | import * as s28 from "../tui/screens/codes.ts"; | |
| 33 | import * as s29 from "../tui/screens/connections.ts"; | |
| 34 | import * as s30 from "../tui/screens/controls.ts"; | |
| 35 | import * as s31 from "../tui/screens/cores.ts"; | |
| 36 | import * as s32 from "../tui/screens/crewbudgets.ts"; | |
| 37 | import * as s33 from "../tui/screens/crewfallback.ts"; | |
| 38 | import * as s34 from "../tui/screens/crewhandover.ts"; | |
| 39 | import * as s35 from "../tui/screens/crewkey.ts"; | |
| 40 | import * as s36 from "../tui/screens/crewsplits.ts"; | |
| 41 | import * as s37 from "../tui/screens/crewtop.ts"; | |
| 42 | import * as s38 from "../tui/screens/dataset.ts"; | |
| 43 | import * as s39 from "../tui/screens/design.ts"; | |
| 44 | import * as s40 from "../tui/screens/design_gallery.ts"; | |
| 45 | import * as s41 from "../tui/screens/devices.ts"; | |
| 46 | import * as s42 from "../tui/screens/disks.ts"; | |
| 47 | import * as s43 from "../tui/screens/displays.ts"; | |
| 48 | import * as s44 from "../tui/screens/domains.ts"; | |
| 49 | import * as s45 from "../tui/screens/dotfiles.ts"; | |
| 50 | import * as s46 from "../tui/screens/drift.ts"; | |
| 51 | import * as s47 from "../tui/screens/dutybudgets.ts"; | |
| 52 | import * as s48 from "../tui/screens/dutyswitch.ts"; | |
| 53 | import * as s49 from "../tui/screens/economics.ts"; | |
| 54 | import * as s50 from "../tui/screens/edgeonly.ts"; | |
| 55 | import * as s51 from "../tui/screens/experiments.ts"; | |
| 56 | import * as s52 from "../tui/screens/featurefeed.ts"; | |
| 57 | import * as s53 from "../tui/screens/features.ts"; | |
| 58 | import * as s54 from "../tui/screens/featureswitch.ts"; | |
| 59 | import * as s55 from "../tui/screens/feed.ts"; | |
| 60 | import * as s56 from "../tui/screens/flowsall.ts"; | |
| 61 | import * as s57 from "../tui/screens/footing.ts"; | |
| 62 | import * as s58 from "../tui/screens/forgeready.ts"; | |
| 63 | import * as s59 from "../tui/screens/forges.ts"; | |
| 64 | import * as s60 from "../tui/screens/forgeview.ts"; | |
| 65 | import * as s61 from "../tui/screens/front.ts"; | |
| 66 | import * as s62 from "../tui/screens/frontms.ts"; | |
| 67 | import * as s63 from "../tui/screens/funnel.ts"; | |
| 68 | import * as s64 from "../tui/screens/games.ts"; | |
| 69 | import * as s65 from "../tui/screens/gifts.ts"; | |
| 70 | import * as s66 from "../tui/screens/health_voice.ts"; | |
| 71 | import * as s67 from "../tui/screens/home_pins.ts"; | |
| 72 | import * as s68 from "../tui/screens/hostreach.ts"; | |
| 73 | import * as s69 from "../tui/screens/infra.ts"; | |
| 74 | import * as s70 from "../tui/screens/inventory.ts"; | |
| 75 | import * as s71 from "../tui/screens/invites.ts"; | |
| 76 | import * as s72 from "../tui/screens/knobs.ts"; | |
| 77 | import * as s73 from "../tui/screens/lapsed.ts"; | |
| 78 | import * as s74 from "../tui/screens/limits.ts"; | |
| 79 | import * as s75 from "../tui/screens/loopstalls.ts"; | |
| 80 | import * as s76 from "../tui/screens/madefrom.ts"; | |
| 81 | import * as s77 from "../tui/screens/maintainruns.ts"; | |
| 82 | import * as s78 from "../tui/screens/maintenance.ts"; | |
| 83 | import * as s79 from "../tui/screens/maintenanceweek.ts"; | |
| 84 | import * as s80 from "../tui/screens/mergedbranches.ts"; | |
| 85 | import * as s81 from "../tui/screens/mirrorpacks.ts"; | |
| 86 | import * as s82 from "../tui/screens/model.ts"; | |
| 87 | import * as s83 from "../tui/screens/money.ts"; | |
| 88 | import * as s84 from "../tui/screens/newissue.ts"; | |
| 89 | import * as s85 from "../tui/screens/next.ts"; | |
| 90 | import * as s86 from "../tui/screens/nowlist.ts"; | |
| 91 | import * as s87 from "../tui/screens/offers.ts"; | |
| 92 | import * as s88 from "../tui/screens/offsite.ts"; | |
| 93 | import * as s89 from "../tui/screens/orggrants.ts"; | |
| 94 | import * as s90 from "../tui/screens/orgteams.ts"; | |
| 95 | import * as s91 from "../tui/screens/originahead.ts"; | |
| 96 | import * as s92 from "../tui/screens/owner.ts"; | |
| 97 | import * as s93 from "../tui/screens/packrepos.ts"; | |
| 98 | import * as s94 from "../tui/screens/payments.ts"; | |
| 99 | import * as s95 from "../tui/screens/people.ts"; | |
| 100 | import * as s96 from "../tui/screens/pinned.ts"; | |
| 101 | import * as s97 from "../tui/screens/planner.ts"; | |
| 102 | import * as s98 from "../tui/screens/planrow.ts"; | |
| 103 | import * as s99 from "../tui/screens/plans.ts"; | |
| 104 | import * as s100 from "../tui/screens/previewdirs.ts"; | |
| 105 | import * as s101 from "../tui/screens/profile.ts"; | |
| 106 | import * as s102 from "../tui/screens/quotas.ts"; | |
| 107 | import * as s103 from "../tui/screens/recoverykit.ts"; | |
| 108 | import * as s104 from "../tui/screens/refused.ts"; | |
| 109 | import * as s105 from "../tui/screens/registry_items.ts"; | |
| 110 | import * as s106 from "../tui/screens/repolist.ts"; | |
| 111 | import * as s107 from "../tui/screens/requests.ts"; | |
| 112 | import * as s108 from "../tui/screens/resilience.ts"; | |
| 113 | import * as s109 from "../tui/screens/returning.ts"; | |
| 114 | import * as s110 from "../tui/screens/returns.ts"; | |
| 115 | import * as s111 from "../tui/screens/scorecard.ts"; | |
| 116 | import * as s112 from "../tui/screens/scrapes.ts"; | |
| 117 | import * as s113 from "../tui/screens/secrets.ts"; | |
| 118 | import * as s114 from "../tui/screens/sentinel.ts"; | |
| 119 | import * as s115 from "../tui/screens/series.ts"; | |
| 120 | import * as s116 from "../tui/screens/ship_time.ts"; | |
| 121 | import * as s117 from "../tui/screens/slowpages.ts"; | |
| 122 | import * as s118 from "../tui/screens/sold.ts"; | |
| 123 | import * as s119 from "../tui/screens/spend.ts"; | |
| 124 | import * as s120 from "../tui/screens/stalepulls.ts"; | |
| 125 | import * as s121 from "../tui/screens/subscriptions.ts"; | |
| 126 | import * as s122 from "../tui/screens/system.ts"; | |
| 127 | import * as s123 from "../tui/screens/tab.ts"; | |
| 128 | import * as s124 from "../tui/screens/teams.ts"; | |
| 129 | import * as s125 from "../tui/screens/telemetry.ts"; | |
| 130 | import * as s126 from "../tui/screens/tell_undo.ts"; | |
| 131 | import * as s127 from "../tui/screens/traces.ts"; | |
| 132 | import * as s128 from "../tui/screens/traffic.ts"; | |
| 133 | import * as s129 from "../tui/screens/trafficview.ts"; | |
| 134 | import * as s130 from "../tui/screens/valves.ts"; | |
| 135 | import * as s131 from "../tui/screens/waiting.ts"; | |
| 136 | import * as s132 from "../tui/screens/waiting_for_me.ts"; | |
| 137 | import * as s133 from "../tui/screens/wayback.ts"; | |
| 138 | import * as s134 from "../tui/screens/weekcard.ts"; | |
| 139 | import * as s135 from "../tui/screens/whocan.ts"; | |
| 139 | 140 | |
| 140 | 141 | /** Each screen file that declares palette entries: its module and the export names. */ |
| 141 | 142 | export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readonly string[]])[] = [ |
| @@ -161,8 +162,8 @@ export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readon | ||
| 161 | 162 | [s19, ["entry"]], |
| 162 | 163 | [s20, ["entry"]], |
| 163 | 164 | [s21, ["entry"]], |
| 164 | [s22, ["entry","recoveryEntry"]], | |
| 165 | [s23, ["entry"]], | |
| 165 | [s22, ["entry"]], | |
| 166 | [s23, ["entry","recoveryEntry"]], | |
| 166 | 167 | [s24, ["entry"]], |
| 167 | 168 | [s25, ["entry"]], |
| 168 | 169 | [s26, ["entry"]], |
| @@ -220,11 +221,11 @@ export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readon | ||
| 220 | 221 | [s78, ["entry"]], |
| 221 | 222 | [s79, ["entry"]], |
| 222 | 223 | [s80, ["entry"]], |
| 223 | [s81, ["modelGrantEntry","modelCeilingEntry"]], | |
| 224 | [s82, ["entry"]], | |
| 224 | [s81, ["entry"]], | |
| 225 | [s82, ["modelGrantEntry","modelCeilingEntry"]], | |
| 225 | 226 | [s83, ["entry"]], |
| 226 | [s84, ["nextAllEntry"]], | |
| 227 | [s85, ["entry"]], | |
| 227 | [s84, ["entry"]], | |
| 228 | [s85, ["nextAllEntry"]], | |
| 228 | 229 | [s86, ["entry"]], |
| 229 | 230 | [s87, ["entry"]], |
| 230 | 231 | [s88, ["entry"]], |
| @@ -274,4 +275,5 @@ export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readon | ||
| 274 | 275 | [s132, ["entry"]], |
| 275 | 276 | [s133, ["entry"]], |
| 276 | 277 | [s134, ["entry"]], |
| 278 | [s135, ["entry"]], | |
| 277 | 279 | ]; |
src/http/lazy_lists.ts +1
| @@ -107,6 +107,7 @@ export const SETTINGS_ROUTES = [ | ||
| 107 | 107 | ["POST", "/settings/cloud/verify"], |
| 108 | 108 | ["POST", "/settings/cloud/write"], |
| 109 | 109 | ["POST", "/settings/cloud/ceiling"], |
| 110 | ["POST", "/settings/cloud/budget"], | |
| 110 | 111 | ["POST", "/settings/cloud/watch-ack"], |
| 111 | 112 | ["POST", "/settings/cloud/project"], |
| 112 | 113 | ["POST", "/settings/cloud/audit"], |
src/http/marks/settings.json +1
src/http/mcp/tools/cloud_account.ts +7 −5
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | import { addAccount, allowWrite, auditAccount, removeAccount, renameAccount, reverify, rotateAccount } from "../../../actions/cloud.ts"; |
| 2 | import { setCeiling, setProject, setWarm } from "../../../actions/cloud_ceiling.ts"; | |
| 2 | import { setBudget, setCeiling, setProject, setWarm } from "../../../actions/cloud_ceiling.ts"; | |
| 3 | 3 | import { PROVIDERS } from "../../../cloud/providers.ts"; |
| 4 | 4 | import { scopeAllows } from "../../../core/tokens.ts"; |
| 5 | 5 | import { good, bad, type Tool, str } from "../shared.ts"; |
| @@ -7,13 +7,13 @@ import { good, bad, type Tool, str } from "../shared.ts"; | ||
| 7 | 7 | export const tool: Tool = { |
| 8 | 8 | name: "cloud_account", |
| 9 | 9 | listedTo: "admin", |
| 10 | doc: "`{ verb, provider, name, value?, to?, allowed?, repo?, dollars?, place?, count?, project? }`: change a cloud account: `attach` or `rotate` a token (`value`), `verify` it, `rename` it (`to`), `remove` it, `allow_writes` (`allowed` true or false), `set_ceiling` (`dollars`: the most the forge lets it cost a month, whole US dollars, 50 until changed) `set_project` (`project`: the DigitalOcean project its forges are filed in, empty for the default; a Hetzner token already has one), `set_warm` (`place`, `count`: how many prepared machines to keep booted and waiting at a place, 0 until set, counted against the ceiling and shown beside it), or `audit` (`repo` owner/name); a forge admin with an admin-scope token; answers a one-line `says`", | |
| 10 | doc: "`{ verb, provider, name, value?, to?, allowed?, repo?, dollars?, place?, count?, project? }`: change a cloud account: `attach` or `rotate` a token (`value`), `verify` it, `rename` it (`to`), `remove` it, `allow_writes` (`allowed` true or false), `set_ceiling` (`dollars`: the most the forge lets it cost a month, whole US dollars, 50 until changed) `set_budget` (`dollars`: a monthly budget, whole US dollars; the owner is told once at 80% and once at 100% of the projected spend for the month, nothing is stopped; omit `dollars` for none) `set_project` (`project`: the DigitalOcean project its forges are filed in, empty for the default; a Hetzner token already has one), `set_warm` (`place`, `count`: how many prepared machines to keep booted and waiting at a place, 0 until set, counted against the ceiling and shown beside it), or `audit` (`repo` owner/name); a forge admin with an admin-scope token; answers a one-line `says`", | |
| 11 | 11 | description: |
| 12 | 12 | "Change a cloud account by `verb` (admin).", |
| 13 | 13 | inputSchema: { |
| 14 | 14 | type: "object", |
| 15 | 15 | properties: { |
| 16 | verb: { type: "string", enum: ["attach", "verify", "rotate", "rename", "remove", "allow_writes", "set_ceiling", "set_project", "set_warm", "audit"] }, | |
| 16 | verb: { type: "string", enum: ["attach", "verify", "rotate", "rename", "remove", "allow_writes", "set_ceiling", "set_budget", "set_project", "set_warm", "audit"] }, | |
| 17 | 17 | provider: { type: "string", enum: [...PROVIDERS] }, |
| 18 | 18 | name: { type: "string", maxLength: 32 }, |
| 19 | 19 | value: { type: "string", maxLength: 4096, description: "For attach, rotate." }, |
| @@ -23,7 +23,7 @@ export const tool: Tool = { | ||
| 23 | 23 | place: { type: "string", maxLength: 100, description: "For set_warm: provider:datacenter:size." }, |
| 24 | 24 | count: { type: "integer", minimum: 0, maximum: 10, description: "For set_warm." }, |
| 25 | 25 | project: { type: "string", maxLength: 100, description: "For set_project." }, |
| 26 | dollars: { type: "integer", minimum: 0, maximum: 100000, description: "For set_ceiling." }, | |
| 26 | dollars: { type: "integer", minimum: 0, maximum: 100000, description: "set_ceiling; set_budget (omit to clear it)." }, | |
| 27 | 27 | }, |
| 28 | 28 | required: ["verb", "provider", "name"], |
| 29 | 29 | }, |
| @@ -55,6 +55,8 @@ export const tool: Tool = { | ||
| 55 | 55 | ? allowWrite(ctx.app, user, provider, name, args["allowed"] === true) |
| 56 | 56 | : verb === "set_ceiling" |
| 57 | 57 | ? setCeiling(ctx.app, user, provider, name, args["dollars"]) |
| 58 | : verb === "set_budget" | |
| 59 | ? setBudget(ctx.app, user, provider, name, args["dollars"] ?? null) | |
| 58 | 60 | : verb === "set_project" |
| 59 | 61 | ? setProject(ctx.app, user, provider, name, args["project"]) |
| 60 | 62 | : verb === "set_warm" |
| @@ -62,7 +64,7 @@ export const tool: Tool = { | ||
| 62 | 64 | : verb === "audit" |
| 63 | 65 | ? await auditAccount(ctx.app, user, provider, name, str(args["repo"])) |
| 64 | 66 | : undefined; |
| 65 | if (done === undefined) return bad("bad_verb", "verb is attach, verify, rotate, rename, remove, allow_writes, set_ceiling, set_project, set_warm or audit"); | |
| 67 | if (done === undefined) return bad("bad_verb", "verb is attach, verify, rotate, rename, remove, allow_writes, set_ceiling, set_budget, set_project, set_warm or audit"); | |
| 66 | 68 | if (!done.ok) return bad("refused", done.error); |
| 67 | 69 | const v = done.value as unknown; |
| 68 | 70 | const said = |
src/http/settings_routes.ts +2
| @@ -72,6 +72,7 @@ import { | ||
| 72 | 72 | cloudAdd, |
| 73 | 73 | cloudAudit, |
| 74 | 74 | cloudAuditPage, |
| 75 | cloudBudget, | |
| 75 | 76 | cloudCeiling, |
| 76 | 77 | cloudWatchAck, |
| 77 | 78 | cloudProject, |
| @@ -260,6 +261,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 260 | 261 | router.add("POST", "/settings/cloud/verify", cloudVerify); |
| 261 | 262 | router.add("POST", "/settings/cloud/write", cloudWrite); |
| 262 | 263 | router.add("POST", "/settings/cloud/ceiling", cloudCeiling); |
| 264 | router.add("POST", "/settings/cloud/budget", cloudBudget); | |
| 263 | 265 | router.add("POST", "/settings/cloud/watch-ack", cloudWatchAck); |
| 264 | 266 | router.add("POST", "/settings/cloud/project", cloudProject); |
| 265 | 267 | router.add("POST", "/settings/cloud/audit", cloudAudit); |
src/maintain/duties/cloud_budget.ts added +21
| @@ -0,0 +1,21 @@ | ||
| 1 | /** | |
| 2 | * Cloud budget (#18101): once an hour, read each cloud account that has a monthly budget against | |
| 3 | * the month's projected spend and claim the notice it newly reached, at 80% or 100% | |
| 4 | * (`cloud/budget.ts`). The claim is a row, so a second reading in the month, or a restart, finds | |
| 5 | * nothing new; the notifier tells the admins from the event it appends. Quiet otherwise. Nothing is | |
| 6 | * stopped. | |
| 7 | */ | |
| 8 | ||
| 9 | import { noticeBudgets, noticeWords } from "../../cloud/budget.ts"; | |
| 10 | import type { Duty } from "../duty.ts"; | |
| 11 | ||
| 12 | export const duty: Duty = { | |
| 13 | name: "cloud-budget", | |
| 14 | intervalMs: 3_600_000, | |
| 15 | timeoutMs: 30_000, | |
| 16 | budget: { runsPerDay: 24, dollarsPerDay: 0, reason: "hourly is 24 a day; it reads only what the forge already kept, and makes no call to a provider" }, | |
| 17 | async run({ db, bus, now }) { | |
| 18 | const made = noticeBudgets(db, bus, now); | |
| 19 | return { findings: [], actions: made.map(noticeWords) }; | |
| 20 | }, | |
| 21 | }; |
src/tui/screens/budgets.ts added +95
| @@ -0,0 +1,95 @@ | ||
| 1 | /** | |
| 2 | * Cloud budgets, in the terminal (#18101): each cloud account's monthly budget against the month's | |
| 3 | * projected spend, every figure with its source and date, and `b` to set or take away one, through | |
| 4 | * `setBudget`, the action the cloud page and the `cloud_account` MCP tool use. A forge admin's | |
| 5 | * only. | |
| 6 | */ | |
| 7 | ||
| 8 | import { setBudget } from "../../actions/cloud_ceiling.ts"; | |
| 9 | import { standingOf, standingWords } from "../../cloud/budget.ts"; | |
| 10 | import { listCloudAccounts } from "../../core/cloud_account.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 { wrap } from "../term/width.ts"; | |
| 15 | import { dialog } from "../ui/widgets.ts"; | |
| 16 | import { later, promptScreen } from "./common.ts"; | |
| 17 | import type { PaletteEntry } from "./entries.ts"; | |
| 18 | ||
| 19 | const WIDTH = 96; | |
| 20 | const INNER = WIDTH - 6; | |
| 21 | ||
| 22 | /** | |
| 23 | * A dollars answer: empty takes the budget away (null); anything but whole digits is NaN, which the | |
| 24 | * action refuses. | |
| 25 | */ | |
| 26 | export const budgetOf = (text: string): number | null => (text.trim() === "" ? null : /^\d{1,7}$/.test(text.trim()) ? Number(text.trim()) : Number.NaN); | |
| 27 | ||
| 28 | /** One line an account: "aws/main: budget $100 a month, 80% of it; $80.60 projected …". */ | |
| 29 | export function budgetLines(session: Session, now = new Date()): string[] { | |
| 30 | const accounts = listCloudAccounts(session.app.db); | |
| 31 | return accounts.length === 0 ? ["No cloud account is connected."] : accounts.flatMap((a) => wrap(`${a.provider}/${a.name}: ${standingWords(standingOf(session.app.db, a, now))}`, INNER)); | |
| 32 | } | |
| 33 | ||
| 34 | export function budgetsScreen(session: Session, ctx: Ctx): Screen { | |
| 35 | let note = ""; | |
| 36 | const say = (t: string): void => { | |
| 37 | note = t; | |
| 38 | ctx.invalidate(); | |
| 39 | }; | |
| 40 | const set = (): void => | |
| 41 | ctx.push( | |
| 42 | promptScreen(ctx, screen, { | |
| 43 | title: "Budget 1/2", | |
| 44 | label: "Account (provider/name)", | |
| 45 | onSubmit: (account) => { | |
| 46 | const [provider = "", name = ""] = account.trim().split("/"); | |
| 47 | return later(ctx, () => | |
| 48 | promptScreen(ctx, screen, { | |
| 49 | title: "Budget 2/2", | |
| 50 | label: `Monthly budget in US dollars for ${provider}/${name} (empty for none)`, | |
| 51 | onSubmit: (dollars) => { | |
| 52 | const r = setBudget(session.app, session.user, provider, name, budgetOf(dollars)); | |
| 53 | if (!r.ok) return r.error; | |
| 54 | say(r.value); | |
| 55 | return undefined; | |
| 56 | }, | |
| 57 | }), | |
| 58 | ); | |
| 59 | }, | |
| 60 | }), | |
| 61 | ); | |
| 62 | const screen: Screen = { | |
| 63 | title: "Cloud budgets", | |
| 64 | get keys() { | |
| 65 | return [binding(["b"], "set a budget"), binding(["enter", "esc", "q"], "close")]; | |
| 66 | }, | |
| 67 | render(area, s) { | |
| 68 | const buttons = dialog(s, area, ctx.theme.c, { | |
| 69 | title: "Cloud budgets", | |
| 70 | body: [...(note === "" ? [] : [...wrap(note, INNER), ""]), ...budgetLines(session), "", "b sets or takes away a budget. A budget only tells: nothing is stopped."], | |
| 71 | actions: [{ label: "Close" }], | |
| 72 | selected: 0, | |
| 73 | width: WIDTH, | |
| 74 | }); | |
| 75 | buttons.forEach((rect) => ctx.hit(rect, () => ctx.pop())); | |
| 76 | }, | |
| 77 | key(e) { | |
| 78 | if (e.ctrl || e.alt) return true; | |
| 79 | if (e.key === "enter" || e.key === "esc" || e.key === "q") ctx.pop(); | |
| 80 | else if (e.key === "b") set(); | |
| 81 | return true; | |
| 82 | }, | |
| 83 | }; | |
| 84 | return screen; | |
| 85 | } | |
| 86 | ||
| 87 | /** Offered to a forge admin, who alone sees the cloud accounts. */ | |
| 88 | export const entry: PaletteEntry = { | |
| 89 | rank: 246, | |
| 90 | id: "budgets", | |
| 91 | title: "Cloud budgets", | |
| 92 | hint: "each cloud account's monthly budget against its projected spend", | |
| 93 | offered: (session) => session.user?.isAdmin === true, | |
| 94 | run: (session, ctx) => ctx.push(budgetsScreen(session, ctx)), | |
| 95 | }; |
src/tui/screens/infra.ts +2 −1
| @@ -12,6 +12,7 @@ | ||
| 12 | 12 | * else sees nothing. |
| 13 | 13 | */ |
| 14 | 14 | |
| 15 | import { standingWords } from "../../cloud/budget.ts"; | |
| 15 | 16 | import { dropRecord, lookAtRecords, lookWords } from "../../actions/dns_record.ts"; |
| 16 | 17 | import { infraCode, type CodeFile } from "../../cloud/infra_read.ts"; |
| 17 | 18 | import { buildOf, composeChoices, providerConsole, databaseChoices, infraOf, cloudResources, nameFor, planCompose, planDatabase, planRecord, recordAccounts, startBuild, type Compose, type Planned, type Running } from "../../actions/infra.ts"; |
| @@ -415,7 +416,7 @@ function infraWithCompose(f: Session, ctx: Ctx): { screen: Screen; compose: (par | ||
| 415 | 416 | return; |
| 416 | 417 | } |
| 417 | 418 | const meters = v.value.meters |
| 418 | .map((m) => `${dollars(m.monthlyCents)} of ${dollars(m.ceilingCents).replace(/\.00$/, "")} on ${m.label}`) | |
| 419 | .map((m) => `${m.makes ? `${m.budget.spend.kind === "unknown" ? "unknown" : dollars(m.monthlyCents)} of ${dollars(m.ceilingCents).replace(/\.00$/, "")} on ${m.label}` : m.label} (${standingWords(m.budget)})`) | |
| 419 | 420 | .join(" · "); |
| 420 | 421 | const text = note !== "" ? note : total !== "" ? `${total} (${keyOf("search")} for all)${meters === "" ? "" : ` · ${meters}`}` : meters !== "" ? meters : "No cloud account can make a machine yet."; |
| 421 | 422 | s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); |
src/web/pages/cloud.ts +21 −3
| @@ -23,6 +23,7 @@ import { HOME, usedFor, usesByVendor, type VendorUse } from "../../cloud/declare | ||
| 23 | 23 | import { watchLine } from "../../cloud/watch.ts"; |
| 24 | 24 | import { lastReading } from "../../cloud/watch_read.ts"; |
| 25 | 25 | import { spendOf } from "../../cloud/ceiling.ts"; |
| 26 | import { standingOf, standingWords } from "../../cloud/budget.ts"; | |
| 26 | 27 | import { warmOf } from "../../cloud/warm_pool.ts"; |
| 27 | 28 | import { dollars } from "../../cloud/prices.ts"; |
| 28 | 29 | import { accountReads, type AccountRead } from "../../cloud/projects.ts"; |
| @@ -39,7 +40,7 @@ import { nameFrame, notePhase, takeSessionTime, timePhase, timePhaseAsync } from | ||
| 39 | 40 | import type { Ctx } from "../../http/context.ts"; |
| 40 | 41 | import { notFoundPage, pageHead, settingsLayout, signInFirst } from "../chrome.ts"; |
| 41 | 42 | import { field, readForm } from "../form.ts"; |
| 42 | import { acknowledgeWatch, setCeiling, setProject } from "../../actions/cloud_ceiling.ts"; | |
| 43 | import { acknowledgeWatch, setBudget, setCeiling, setProject } from "../../actions/cloud_ceiling.ts"; | |
| 43 | 44 | import { html, type Html } from "../html.ts"; |
| 44 | 45 | import { flashTo, page } from "../layout.ts"; |
| 45 | 46 | import { btn, confirmAction, field as input, icon, row, rowList, time } from "../ui.ts"; |
| @@ -102,7 +103,7 @@ function accountsCard(db: Database, accounts: CloudAccount[], reads: CloudRead[] | ||
| 102 | 103 | title: html`${LABEL[a.provider]} / <span class="mono">${a.name}</span>`, |
| 103 | 104 | meta: html`${a.summary}<br />${usedFor(uses.get(VENDOR_OF[a.provider]))}<br />${HOME[a.provider]}<br />verified ${a.verifiedAt ? time(a.verifiedAt) : "never"} · |
| 104 | 105 | ${last ? html`last used ${time(last.at)} by ${runWords(last.run)}` : "never used"} · |
| 105 | ${a.writeAllowed ? "writes allowed" : "read-only"}<br />${ceilingLine(db, a)}`, | |
| 106 | ${a.writeAllowed ? "writes allowed" : "read-only"}<br />${ceilingLine(db, a)}<br />${standingWords(standingOf(db, a, new Date()))}`, | |
| 106 | 107 | facts: [...readFacts(inventory, a), ...watchFacts(db, a), ...warmFacts(db, a)], |
| 107 | 108 | trail: html`<div class="row-fields"> |
| 108 | 109 | <form method="post" action="/settings/cloud/verify"> |
| @@ -119,6 +120,12 @@ function accountsCard(db: Database, accounts: CloudAccount[], reads: CloudRead[] | ||
| 119 | 120 | aria-label="Monthly ceiling in US dollars for ${a.name}" required /> |
| 120 | 121 | ${btn("Set ceiling", { size: "sm", label: `Set the ceiling of ${a.name}` })} |
| 121 | 122 | </form> |
| 123 | <form method="post" action="/settings/cloud/budget" class="row-fields"> | |
| 124 | ${hidden(a.provider, a.name)} | |
| 125 | <input class="input mono" type="number" name="dollars" value="${a.budgetDollars ?? ""}" min="1" max="100000" step="1" placeholder="none" | |
| 126 | aria-label="Monthly budget in US dollars for ${a.name}; empty for none" /> | |
| 127 | ${btn("Set budget", { size: "sm", label: `Set the budget of ${a.name}` })} | |
| 128 | </form> | |
| 122 | 129 | ${(lastReading(db, a.provider, a.name)?.resources ?? []).some((r) => r.verdict === "orphan" || r.verdict === "outside") |
| 123 | 130 | ? html`<form method="post" action="/settings/cloud/watch-ack"> |
| 124 | 131 | ${hidden(a.provider, a.name)}${btn("Acknowledge as not the forge's", { size: "sm", label: `Acknowledge what the watch shows at ${a.name} as not the forge's` })} |
| @@ -161,7 +168,7 @@ function accountsCard(db: Database, accounts: CloudAccount[], reads: CloudRead[] | ||
| 161 | 168 | }); |
| 162 | 169 | return html`<section class="settings-block"> |
| 163 | 170 | <h2>Cloud accounts</h2> |
| 164 | <p class="muted small">Each account has a monthly spend ceiling, $50 until you change it: the forge refuses to make a machine or volume that would take it past. The cost shown is the forge's own reckoning from list prices; the provider's bill is the truth.</p> | |
| 171 | <p class="muted small">Each account has a monthly spend ceiling, $50 until you change it: the forge refuses to make a machine or volume that would take it past. A budget is only a notice: set one and you are told once at 80% and once at 100% of the projected spend for the month, and nothing is stopped. The cost shown is the forge's own reckoning from list prices; the provider's bill is the truth.</p> | |
| 165 | 172 | <p class="muted small">Paste a credential once; the forge checks it read-only, seals it, and never shows it again. The quickest way: <a href="/cloud/connect">Connect a cloud</a>. What runs on them and what it costs: <a href="/infra">Infrastructure</a>.</p> |
| 166 | 173 | ${rows.length > 0 |
| 167 | 174 | ? html`<ul class="list setting-list">${rows}</ul>` |
| @@ -272,6 +279,17 @@ export async function cloudCeiling(ctx: Ctx): Promise<Response> { | ||
| 272 | 279 | return flashTo(ctx, "/settings/cloud", r.ok ? { message: `Saved: ${r.value}.` } : { tone: "danger", message: r.error }); |
| 273 | 280 | } |
| 274 | 281 | |
| 282 | // POST /settings/cloud/budget: an account's monthly budget, whole US dollars; empty takes it away. | |
| 283 | export async function cloudBudget(ctx: Ctx): Promise<Response> { | |
| 284 | const denied = requireAdmin(ctx); | |
| 285 | if (denied) return denied; | |
| 286 | const form = await readForm(ctx, "admin"); | |
| 287 | if (form instanceof Response) return form; | |
| 288 | const raw = field(form, "dollars").trim(); | |
| 289 | const r = setBudget(ctx.app, ctx.auth.user, field(form, "provider"), field(form, "name"), raw === "" ? null : /^\d{1,7}$/.test(raw) ? Number(raw) : NaN); | |
| 290 | return flashTo(ctx, "/settings/cloud", r.ok ? { message: `Saved: ${r.value}.` } : { tone: "danger", message: r.error }); | |
| 291 | } | |
| 292 | ||
| 275 | 293 | // POST /settings/cloud/watch-ack: what the hourly watch shows there is not the forge's (#16329). |
| 276 | 294 | export async function cloudWatchAck(ctx: Ctx): Promise<Response> { |
| 277 | 295 | const denied = requireAdmin(ctx); |
src/web/pages/infra.ts +11 −3
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | * shown, so nobody builds what they did not see. |
| 12 | 12 | */ |
| 13 | 13 | |
| 14 | import { standingWords } from "../../cloud/budget.ts"; | |
| 14 | 15 | import { LIFETIME_DAYS } from "../../actions/pinned.ts"; |
| 15 | 16 | import type { CodeFile } from "../../cloud/infra_read.ts"; |
| 16 | 17 | import { restoredName, type SnapshotView } from "../../actions/infra_snapshot.ts"; |
| @@ -115,9 +116,16 @@ const ceiling = (cents: number): string => dollars(cents).replace(/\.00$/, ""); | ||
| 115 | 116 | function meters(v: InfraView): Html { |
| 116 | 117 | if (v.meters.length === 0) return html``; |
| 117 | 118 | const many = new Set(v.meters.map((m) => m.provider)).size < v.meters.length; |
| 118 | return html`<div data-meters>${v.meters.map( | |
| 119 | (m) => html`<p${m.monthlyCents > m.ceilingCents ? raw(' data-over="1"') : null}>${money(m.monthlyCents)} of ${ceiling(m.ceilingCents)} a month on ${m.label}${many ? html` <span class="mono muted">${m.account.split("/")[1]}</span>` : null}</p>`, | |
| 120 | )}</div>`; | |
| 119 | return html`<div data-meters>${v.meters.map((m) => { | |
| 120 | const who = many ? html` <span class="mono muted">${m.account.split("/")[1]}</span>` : null; | |
| 121 | // The figure is the forge's own reckoning of what it made; unread, it says so and is never $0. | |
| 122 | const figure = !m.makes | |
| 123 | ? html`${m.label}${who}` | |
| 124 | : m.budget.spend.kind === "unknown" | |
| 125 | ? html`<span class="num">unknown</span> of ${ceiling(m.ceilingCents)} a month on ${m.label}${who}` | |
| 126 | : html`${money(m.monthlyCents)} of ${ceiling(m.ceilingCents)} a month on ${m.label}${who}`; | |
| 127 | return html`<p${m.makes && m.monthlyCents > m.ceilingCents ? raw(' data-over="1"') : null}>${figure}<br /><span class="muted small" data-budget>${standingWords(m.budget)}</span></p>`; | |
| 128 | })}</div>`; | |
| 121 | 129 | } |
| 122 | 130 | |
| 123 | 131 | /** |
test/cloud-budget.test.ts added +225
| @@ -0,0 +1,225 @@ | ||
| 1 | /** | |
| 2 | * The monthly budget of a cloud account (#18101): one notice at 80% and one at 100% of the month's | |
| 3 | * projected spend, once per account per month, kept in the database; spend that could not be read | |
| 4 | * is unknown, never $0; every figure names its source. Worked by hand in the comments. | |
| 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 { setBudget } from "../src/actions/cloud_ceiling.ts"; | |
| 13 | import { infraOf } from "../src/actions/infra.ts"; | |
| 14 | import { deployPinned, net } from "../src/actions/pinned.ts"; | |
| 15 | import { noticeBudgets, noticeWords, projectCents, standingOf, standingWords } from "../src/cloud/budget.ts"; | |
| 16 | import { getCloudAccount, recordVerified } from "../src/core/cloud_account.ts"; | |
| 17 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 18 | import { cloudBudgetLines, setNotifyUrl, startNotifier } from "../src/crew/notify.ts"; | |
| 19 | import { duty } from "../src/maintain/duties/cloud_budget.ts"; | |
| 20 | import { quietLogs } from "./helpers/globals.ts"; | |
| 21 | import { ownNet } from "./helpers/own-net.ts"; | |
| 22 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 23 | import { recordCloud } from "./helpers/recorded-cloud.ts"; | |
| 24 | ||
| 25 | quietLogs(); | |
| 26 | ownNet(); | |
| 27 | ||
| 28 | const DEC = new Date("2026-12-10T12:00:00Z"); // day 10 of 31 | |
| 29 | const bill = (db: App["db"], monthStart: string, cents: number, readAt: string, error = "") => { | |
| 30 | db.run("DELETE FROM cloud_cost WHERE cloud_account_id = 'main'"); | |
| 31 | if (cents > 0) db.run("INSERT INTO cloud_cost VALUES ('aws', 'main', ?1, '2099-01-01', 'EC2', 'us-east-1', ?2, 0)", [monthStart, cents * 10_000]); | |
| 32 | db.run("INSERT INTO cloud_read (cloud_provider, cloud_account_id, asked_at, cost_read_at, cost_error) VALUES ('aws', 'main', ?1, ?1, ?2) ON CONFLICT DO UPDATE SET asked_at = ?1, cost_read_at = ?1, cost_error = ?2", [readAt, error]); | |
| 33 | }; | |
| 34 | ||
| 35 | describe("cloud budget", () => { | |
| 36 | let dir = ""; | |
| 37 | let app: App; | |
| 38 | const admin = (): User => getUserByName(app.db, "alice")!; | |
| 39 | const events = () => app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM event WHERE kind = 'cloud.budget_notice'").get()!.n; | |
| 40 | ||
| 41 | beforeAll(async () => { | |
| 42 | dir = await mkdtemp(join(tmpdir(), "forge-budget-")); | |
| 43 | app = createApp({ dataDir: dir, port: 0 }); | |
| 44 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 45 | if (!made.ok) throw new Error(made.error); | |
| 46 | recordVerified(app.db, "aws", "main", "test"); | |
| 47 | }); | |
| 48 | afterAll(async () => { | |
| 49 | app.close(); | |
| 50 | await rm(dir, { recursive: true, force: true }); | |
| 51 | }); | |
| 52 | ||
| 53 | test("a projection is the month so far times days in the month over days elapsed", () => { | |
| 54 | // $26.00 over 10 of 31 days: 2600 x 31 / 10 = 8060 cents. | |
| 55 | expect(projectCents(2600, DEC)).toBe(8060); | |
| 56 | expect(projectCents(100, new Date("2026-02-28T00:00:00Z"))).toBe(100); | |
| 57 | }); | |
| 58 | ||
| 59 | test("a budget is whole dollars from 1, set by an admin only, and null takes it away", () => { | |
| 60 | expect(setBudget(app, undefined, "aws", "main", 100)).toEqual({ ok: false, error: "not_found" }); | |
| 61 | for (const bad of [0, -5, 1.5, "100", 1_000_001]) expect(setBudget(app, admin(), "aws", "main", bad).ok).toBe(false); | |
| 62 | expect(setBudget(app, admin(), "aws", "nope", 100).ok).toBe(false); | |
| 63 | expect(setBudget(app, admin(), "aws", "main", 100).ok).toBe(true); | |
| 64 | expect(getCloudAccount(app.db, "aws", "main")?.budgetDollars).toBe(100); | |
| 65 | expect(setBudget(app, admin(), "aws", "main", null).ok).toBe(true); | |
| 66 | expect(getCloudAccount(app.db, "aws", "main")?.budgetDollars).toBeNull(); | |
| 67 | setBudget(app, admin(), "aws", "main", 100); | |
| 68 | }); | |
| 69 | ||
| 70 | test("an account whose bill was never read, or failed to read, is unknown, not 0, and sends nothing", () => { | |
| 71 | const s = standingOf(app.db, getCloudAccount(app.db, "aws", "main")!, DEC); | |
| 72 | expect(s.spend).toMatchObject({ kind: "unknown" }); | |
| 73 | expect(s.percent).toBeNull(); | |
| 74 | expect(standingWords(s)).toContain("spend unknown: AWS's bill has not been read yet"); | |
| 75 | expect(standingWords(s)).not.toContain("$0"); | |
| 76 | bill(app.db, "2026-11-01", 4000, "2026-12-10T06:00:00Z", "AccessDenied"); | |
| 77 | expect(standingOf(app.db, getCloudAccount(app.db, "aws", "main")!, DEC).spend).toMatchObject({ kind: "unknown", why: expect.stringContaining("could not be read: AccessDenied") }); | |
| 78 | expect(noticeBudgets(app.db, app.bus, DEC)).toEqual([]); | |
| 79 | const meter = infraOf(app, admin(), DEC); | |
| 80 | expect(meter.ok && meter.value.meters.find((m) => m.account === "aws/main")?.budget.spend.kind).toBe("unknown"); | |
| 81 | }); | |
| 82 | ||
| 83 | test("crossing 80% and 100% sends exactly one notice at each; a second reading in the month sends none", () => { | |
| 84 | // Budget $100. $20 of 10 days projects to $62: 62%, nothing. | |
| 85 | bill(app.db, "2026-12-01", 2000, "2026-12-10T06:00:00Z"); | |
| 86 | expect(noticeBudgets(app.db, app.bus, DEC)).toEqual([]); | |
| 87 | // $26 projects to $80.60: 80%, one notice. | |
| 88 | bill(app.db, "2026-12-01", 2600, "2026-12-10T06:00:00Z"); | |
| 89 | const first = noticeBudgets(app.db, app.bus, DEC); | |
| 90 | expect(first).toMatchObject([{ provider: "aws", account: "main", percent: 80, spendCents: 8060, budgetDollars: 100, source: "billed" }]); | |
| 91 | expect(events()).toBe(1); | |
| 92 | // A second reading, an hour and a day later, the same standing: none. | |
| 93 | expect(noticeBudgets(app.db, app.bus, new Date("2026-12-10T13:00:00Z"))).toEqual([]); | |
| 94 | expect(noticeBudgets(app.db, app.bus, new Date("2026-12-10T23:00:00Z"))).toEqual([]); | |
| 95 | // $33 projects to $102.30: 100%, one more. | |
| 96 | bill(app.db, "2026-12-01", 3300, "2026-12-10T18:00:00Z"); | |
| 97 | const second = noticeBudgets(app.db, app.bus, DEC); | |
| 98 | expect(second).toMatchObject([{ percent: 100, spendCents: 10230 }]); | |
| 99 | expect(noticeBudgets(app.db, app.bus, DEC)).toEqual([]); | |
| 100 | expect(events()).toBe(2); | |
| 101 | // A budget raised and lowered again, or spend that falls back to 80, does not send 80 | |
| 102 | // after 100. | |
| 103 | bill(app.db, "2026-12-01", 2700, "2026-12-10T19:00:00Z"); | |
| 104 | expect(noticeBudgets(app.db, app.bus, DEC)).toEqual([]); | |
| 105 | expect(events()).toBe(2); | |
| 106 | }); | |
| 107 | ||
| 108 | test("the notice says its source, the figure and that nothing was stopped; the notifier's lines are the same, once each per month", () => { | |
| 109 | const lines = cloudBudgetLines(app, admin(), DEC.getTime()); | |
| 110 | expect(lines.map((l) => l.id)).toEqual(["budget:aws/main:2026-12:80", "budget:aws/main:2026-12:100"]); | |
| 111 | expect(lines[0]!.line).toBe("Cloud account aws/main is at 80% of its $100 monthly budget: $80.60 projected for 2026-12 (AWS's billed spend so far, projected to the month's end). Nothing was stopped."); | |
| 112 | expect(lines[1]!.line).toContain("100%"); | |
| 113 | expect(lines[0]!.link).toBe("/infra"); | |
| 114 | expect(cloudBudgetLines(app, { ...admin(), isAdmin: false }, DEC.getTime())).toEqual([]); | |
| 115 | // Last month's notices are not this month's. | |
| 116 | expect(cloudBudgetLines(app, admin(), new Date("2027-01-02T00:00:00Z").getTime())).toEqual([]); | |
| 117 | }); | |
| 118 | ||
| 119 | test("a new month is a new notice", () => { | |
| 120 | const jan = new Date("2027-01-10T12:00:00Z"); | |
| 121 | bill(app.db, "2027-01-01", 2600, "2027-01-10T06:00:00Z"); | |
| 122 | expect(noticeBudgets(app.db, app.bus, jan)).toMatchObject([{ month: "2027-01", percent: 80 }]); | |
| 123 | expect(noticeBudgets(app.db, app.bus, jan)).toEqual([]); | |
| 124 | }); | |
| 125 | ||
| 126 | test("the hourly duty claims and reports the notice, and is quiet once it has", async () => { | |
| 127 | setBudget(app, admin(), "aws", "main", 50); | |
| 128 | const feb = new Date("2027-02-10T12:00:00Z"); | |
| 129 | bill(app.db, "2027-02-01", 2000, "2027-02-10T06:00:00Z"); // $20 over 10 of 28 days = $56 of $50 | |
| 130 | const ran = await duty.run({ db: app.db, bus: app.bus, now: feb, app }); | |
| 131 | expect(ran.actions).toHaveLength(1); | |
| 132 | expect(ran.actions[0]).toContain("100% of its $50"); | |
| 133 | expect((await duty.run({ db: app.db, bus: app.bus, now: feb, app })).actions).toEqual([]); | |
| 134 | }); | |
| 135 | ||
| 136 | test("the infra table shows spend against budget with its source and date", () => { | |
| 137 | const m = infraOf(app, admin(), new Date("2027-02-10T13:00:00Z")); | |
| 138 | const meter = m.ok ? m.value.meters.find((x) => x.account === "aws/main") : undefined; | |
| 139 | expect(meter?.makes).toBe(false); | |
| 140 | expect(standingWords(meter!.budget)).toBe("budget $50 a month, 112% of it; $56.00 projected for the month: AWS's billed $20.00 so far, as of 2027-02-10"); | |
| 141 | }); | |
| 142 | ||
| 143 | test("a restart does not tell again: the marker is in the database, and the notifier sends one line once", async () => { | |
| 144 | const sent: string[] = []; | |
| 145 | setNotifyUrl(app.db, admin().id, "https://ntfy.example.test/topic"); | |
| 146 | let now = Date.parse("2027-03-10T12:00:00Z"); | |
| 147 | const boot = async () => { | |
| 148 | const n = startNotifier(app, { forgeUrl: "https://forge.example.test", now: () => now, drainingSince: () => null, causes: () => [], alarms: () => [], send: async (_u, body) => (sent.push(body), true) }); | |
| 149 | await n.settled(); | |
| 150 | return n; | |
| 151 | }; | |
| 152 | let n = await boot(); | |
| 153 | bill(app.db, "2027-03-01", 1300, "2027-03-10T06:00:00Z"); // $13 x 31 / 10 = $40.30 of $50: 80% | |
| 154 | noticeBudgets(app.db, app.bus, new Date(now)); | |
| 155 | await n.settled(); | |
| 156 | await n.tick(); | |
| 157 | expect(sent.filter((b) => b.includes("80% of its $50"))).toHaveLength(1); | |
| 158 | await n.tick(); | |
| 159 | await n.close(); | |
| 160 | n = await boot(); | |
| 161 | noticeBudgets(app.db, app.bus, new Date(now)); | |
| 162 | await n.tick(); | |
| 163 | expect(sent.filter((b) => b.includes("80% of its $50"))).toHaveLength(1); | |
| 164 | await n.close(); | |
| 165 | }); | |
| 166 | ||
| 167 | test("noticeWords names the forge's estimate as not the vendor's bill", () => { | |
| 168 | expect(noticeWords({ provider: "digitalocean", account: "main", month: "2026-12", percent: 80, spendCents: 4100, budgetDollars: 50, source: "estimate" })).toContain("the forge's estimate from list prices, not the vendor's bill"); | |
| 169 | }); | |
| 170 | }); | |
| 171 | ||
| 172 | describe("cloud budget on an account the forge makes machines on", () => { | |
| 173 | let dir = ""; | |
| 174 | let app: App; | |
| 175 | const cloud = recordCloud(); | |
| 176 | const admin = (): User => getUserByName(app.db, "alice")!; | |
| 177 | ||
| 178 | beforeAll(async () => { | |
| 179 | dir = await mkdtemp(join(tmpdir(), "forge-budget-do-")); | |
| 180 | app = createApp({ dataDir: dir, port: 0 }); | |
| 181 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 182 | if (!made.ok) throw new Error(made.error); | |
| 183 | cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" } }), { status: 200 }); | |
| 184 | const added = await addAccount(app, admin(), "digitalocean", "main", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"); | |
| 185 | if (!added.ok) throw new Error(String(added.error)); | |
| 186 | allowWrite(app, admin(), "digitalocean", "main", true); | |
| 187 | net.fetch = cloud.fetch; | |
| 188 | }, 30_000); | |
| 189 | afterAll(async () => { | |
| 190 | app.close(); | |
| 191 | await rm(dir, { recursive: true, force: true }); | |
| 192 | }); | |
| 193 | ||
| 194 | const input = (name: string) => ({ name, host: `${name}.forge.test`, target: "digitalocean", account: "main", app: "alice/shop", source: "https://forge.example.org/trevato/forge", version: "a".repeat(40), config: {} }); | |
| 195 | ||
| 196 | test("with the price catalog never read, the estimate is unknown, never $0", () => { | |
| 197 | setBudget(app, admin(), "digitalocean", "main", 15); | |
| 198 | const s = standingOf(app.db, getCloudAccount(app.db, "digitalocean", "main")!, DEC); | |
| 199 | expect(s.spend).toEqual({ kind: "unknown", why: "the forge has not read DigitalOcean's prices" }); | |
| 200 | expect(noticeBudgets(app.db, app.bus, DEC)).toEqual([]); | |
| 201 | const v = infraOf(app, admin(), DEC); | |
| 202 | expect(v.ok && v.value.meters.find((m) => m.account === "digitalocean/main")?.budget.spend.kind).toBe("unknown"); | |
| 203 | }); | |
| 204 | ||
| 205 | test("the forge's own estimate crosses 80% and then 100%, each once, and says it is an estimate", async () => { | |
| 206 | await seedPlaces(app.db); | |
| 207 | // No machine yet: a read catalog and nothing made is a real $0. | |
| 208 | const none = standingOf(app.db, getCloudAccount(app.db, "digitalocean", "main")!, DEC); | |
| 209 | expect(none.spend).toMatchObject({ kind: "known", cents: 0, source: "estimate" }); | |
| 210 | expect(noticeBudgets(app.db, app.bus, DEC)).toEqual([]); | |
| 211 | // One forge is $13 of $15: 86%. | |
| 212 | expect((await deployPinned(app, admin(), input("one"))).ok).toBe(true); | |
| 213 | const at80 = noticeBudgets(app.db, app.bus, DEC); | |
| 214 | expect(at80).toMatchObject([{ percent: 80, spendCents: 1300, source: "estimate" }]); | |
| 215 | expect(standingWords(standingOf(app.db, getCloudAccount(app.db, "digitalocean", "main")!, DEC))).toContain("the forge's estimate from list prices, not DigitalOcean's bill, as of "); | |
| 216 | expect(noticeBudgets(app.db, app.bus, DEC)).toEqual([]); | |
| 217 | // Two forges are $26 of $15: 173%. | |
| 218 | expect((await deployPinned(app, admin(), input("two"))).ok).toBe(true); | |
| 219 | expect(noticeBudgets(app.db, app.bus, DEC)).toMatchObject([{ percent: 100, spendCents: 2600 }]); | |
| 220 | expect(noticeBudgets(app.db, app.bus, DEC)).toEqual([]); | |
| 221 | // Nothing was stopped: a third forge still deploys while over the budget (the $50 ceiling is | |
| 222 | // another matter). | |
| 223 | expect((await deployPinned(app, admin(), input("three"))).ok).toBe(true); | |
| 224 | }); | |
| 225 | }); |
test/infra-page.test.ts +3 −1
| @@ -276,7 +276,7 @@ describe("infrastructure", () => { | ||
| 276 | 276 | ["app", "ada/shop", ["plain"]], |
| 277 | 277 | ]); |
| 278 | 278 | expect(v.value.groups[1]!.machines[0]).toMatchObject({ endsAt: null, monthlyCents: 1300, bills: "machine" }); |
| 279 | expect(v.value.meters).toEqual([ | |
| 279 | expect(v.value.meters).toMatchObject([ | |
| 280 | 280 | { |
| 281 | 281 | account: "digitalocean/main", |
| 282 | 282 | provider: "digitalocean", |
| @@ -284,6 +284,8 @@ describe("infrastructure", () => { | ||
| 284 | 284 | monthlyCents: 2600, |
| 285 | 285 | ceilingCents: 5000, |
| 286 | 286 | writable: true, |
| 287 | makes: true, | |
| 288 | budget: { budgetDollars: null }, | |
| 287 | 289 | }, |
| 288 | 290 | ]); |
| 289 | 291 | expect(v.value.drift).toEqual([ |
test/palette-roster.test.ts +2
| @@ -226,6 +226,7 @@ test("a site-admin person is offered the whole roster", () => { | ||
| 226 | 226 | ["payments", "Payments", "what was charged for the forges you claimed"], |
| 227 | 227 | ["ship-time", "Ship time", "median time from the crew's first run to done"], |
| 228 | 228 | ["buckets", "Buckets", "an object bucket's price a month, and binding it to an app"], |
| 229 | ["budgets", "Cloud budgets", "each cloud account's monthly budget against its projected spend"], | |
| 229 | 230 | ["edge-only-accounts", "Edge-only accounts", "who would be locked out if the platform edge sign-in went off"], |
| 230 | 231 | ["way-back-links", "Way-back links", "a link that signs in an account the edge made, once the edge is gone"], |
| 231 | 232 | ["traffic-sources", "Traffic sources", "where people come from and where they go, for the forge"], |
| @@ -363,6 +364,7 @@ test("a site-admin agent is offered the roster without the person-only entries", | ||
| 363 | 364 | ["ship-time", "Ship time", "median time from the crew's first run to done"], |
| 364 | 365 | ["traces", "Traces", "every crew run, newest first"], |
| 365 | 366 | ["buckets", "Buckets", "an object bucket's price a month, and binding it to an app"], |
| 367 | ["budgets", "Cloud budgets", "each cloud account's monthly budget against its projected spend"], | |
| 366 | 368 | ["maintenance-runs", "Maintenance duty runs", "what each duty found, did and probed"], |
| 367 | 369 | ["who-can", "Who may do what", "your role and every grant you hold"], |
| 368 | 370 | ["traffic-sources", "Traffic sources", "where people come from and where they go, for the forge"], |
test/tui-budgets.test.ts added +78
| @@ -0,0 +1,78 @@ | ||
| 1 | /** | |
| 2 | * Cloud budgets (#18101) in the terminal: an admin reads each account's standing and sets a budget; | |
| 3 | * anyone else is not offered it. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { getCloudAccount, recordVerified } from "../src/core/cloud_account.ts"; | |
| 11 | import { createUser, type User } from "../src/core/users.ts"; | |
| 12 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 13 | import { budgetOf } from "../src/tui/screens/budgets.ts"; | |
| 14 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 15 | import { quietLogs } from "./helpers/globals.ts"; | |
| 16 | import { settleApp } from "./helpers/tui.ts"; | |
| 17 | ||
| 18 | quietLogs(); | |
| 19 | ||
| 20 | let dir: string; | |
| 21 | let forge: App; | |
| 22 | let alice: User; | |
| 23 | let bob: User; | |
| 24 | ||
| 25 | beforeAll(async () => { | |
| 26 | dir = await mkdtemp(join(tmpdir(), "forge-tui-budgets-")); | |
| 27 | forge = createApp({ dataDir: dir, port: 0 }); | |
| 28 | const make = async (username: string, adminIfFirst: boolean): Promise<User> => { | |
| 29 | const made = await createUser(forge.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst }); | |
| 30 | if (!made.ok) throw new Error(made.error); | |
| 31 | return made.value; | |
| 32 | }; | |
| 33 | alice = await make("alice", true); | |
| 34 | bob = await make("bob", false); | |
| 35 | recordVerified(forge.db, "aws", "main", "test"); | |
| 36 | }); | |
| 37 | ||
| 38 | afterAll(async () => { | |
| 39 | forge?.close(); | |
| 40 | await rm(dir, { recursive: true, force: true }); | |
| 41 | }); | |
| 42 | ||
| 43 | const open = async (user: User) => { | |
| 44 | const terminal = headlessTerminal(160, 40); | |
| 45 | const { app } = createForgeApp(forge, { sshUsername: "t", remoteAddress: "127.0.0.1", user }, { terminal, exitHooks: false }); | |
| 46 | app.start(); | |
| 47 | const key = (k: string) => app.dispatch({ type: "key", key: k, ctrl: k.startsWith("ctrl+"), alt: false, shift: false }); | |
| 48 | const type = async (text: string) => { | |
| 49 | for (const ch of text) key(ch); | |
| 50 | key("enter"); | |
| 51 | await settleApp(app); | |
| 52 | }; | |
| 53 | await settleApp(app); | |
| 54 | app.dispatch({ type: "key", key: "k", ctrl: true, alt: false, shift: false }); | |
| 55 | for (const ch of "Cloud budgets") key(ch); | |
| 56 | key("enter"); | |
| 57 | await settleApp(app); | |
| 58 | return { key, type, text: () => app.screen.toText().replace(/\s+/g, " ") }; | |
| 59 | }; | |
| 60 | ||
| 61 | test("a dollars answer is whole digits, or empty for none", () => { | |
| 62 | expect([budgetOf(""), budgetOf(" 40 "), budgetOf("4.5")]).toEqual([null, 40, Number.NaN]); | |
| 63 | }); | |
| 64 | ||
| 65 | test("an admin reads an unread account as unknown and sets a budget", async () => { | |
| 66 | const t = await open(alice); | |
| 67 | expect(t.text()).toContain("aws/main: no budget set; spend unknown: AWS's bill has not been read yet"); | |
| 68 | t.key("b"); | |
| 69 | await t.type("aws/main"); | |
| 70 | await t.type("75"); | |
| 71 | expect(getCloudAccount(forge.db, "aws", "main")?.budgetDollars).toBe(75); | |
| 72 | expect(t.text()).toContain("budget is $75 a month"); | |
| 73 | }); | |
| 74 | ||
| 75 | test("someone who is not an admin is not offered the screen", async () => { | |
| 76 | const t = await open(bob); | |
| 77 | expect(t.text()).not.toContain("aws/main"); | |
| 78 | }); |
new above
offline