Public: anyone can read this; the crew can change it.
Every cloud account has a monthly ceiling, $50 by default, and the forge refuses a create that would cross it #16232
sold/cloud-ceiling → main 5 commits
15 files
changed +432
−10
- src/actions/cloud_ceiling.ts
- src/actions/pinned.ts
- src/cloud/ceiling.ts
- src/cloud/overview.ts
- src/cloud/prices.ts
- src/core/cloud_account.ts
- src/core/event_audience.ts
- src/core/migration-pins/20261123140000-cloud-account-ceiling.pin
- src/core/migrations/20261123140000-cloud-account-ceiling.ts
- src/http/marks/settings.json
- src/http/mcp/tools/cloud_account.ts
- src/http/settings_routes.ts
- src/web/pages/cloud.ts
- src/web/pages/cloud_ceiling.ts
- test/pinned-ceiling.test.ts
src/actions/cloud_ceiling.ts added +22
| @@ -0,0 +1,22 @@ | ||
| 1 | /** | |
| 2 | * The monthly spend ceiling of a cloud account (cloud/ceiling.ts), as a forge admin changes it: | |
| 3 | * whole US dollars, recorded as an event with the old and new value. Anyone who is not a forge | |
| 4 | * admin is told `not_found`. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import { getCloudAccount, setCeilingDollars } from "../core/cloud_account.ts"; | |
| 9 | import type { User } from "../core/users.ts"; | |
| 10 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 11 | ||
| 12 | export const MAX_CEILING_DOLLARS = 100_000; | |
| 13 | ||
| 14 | export function setCeiling(app: App, actor: User | undefined, provider: string, name: string, dollars: unknown): Result<string, string> { | |
| 15 | if (actor?.isAdmin !== true) return err("not_found"); | |
| 16 | if (typeof dollars !== "number" || !Number.isInteger(dollars) || dollars < 0 || dollars > MAX_CEILING_DOLLARS) | |
| 17 | return err(`A ceiling is a whole number of US dollars a month, from 0 to ${MAX_CEILING_DOLLARS}.`); | |
| 18 | const before = getCloudAccount(app.db, provider, name); | |
| 19 | if (!before || !setCeilingDollars(app.db, provider, name, dollars)) return err("No such credential."); | |
| 20 | app.bus.append({ kind: "cloud.ceiling", actorId: actor.id, payload: { provider, name, from: before.ceilingDollars, to: dollars } }); | |
| 21 | return ok(`ceiling is $${dollars} a month`); | |
| 22 | } |
src/actions/pinned.ts +4 −2
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | |
| 12 | 12 | import type { App } from "../app.ts"; |
| 13 | 13 | import { gatedFetch } from "../cloud/gate.ts"; |
| 14 | import { capped, CeilingRefusal } from "../cloud/ceiling.ts"; | |
| 14 | 15 | import { driverOf } from "../cloud/drivers.ts"; |
| 15 | 16 | import { provision, read, replace } from "../cloud/machine.ts"; |
| 16 | 17 | import type { Fetch } from "../cloud/providers.ts"; |
| @@ -56,6 +57,7 @@ async function withCloud<T>(app: App, who: User, p: Pinned, purpose: string, go: | ||
| 56 | 57 | try { |
| 57 | 58 | return ok(await go(gatedFetch(app.db, { provider: p.target, account: p.account }, `pinned:${purpose}`, net.fetch), token)); |
| 58 | 59 | } catch (e) { |
| 60 | if (e instanceof CeilingRefusal) return err(e.message); | |
| 59 | 61 | return err(`The cloud refused: ${e instanceof Error ? e.message.slice(0, 200) : "failed"}`); |
| 60 | 62 | } |
| 61 | 63 | } |
| @@ -99,7 +101,7 @@ export async function deployPinned( | ||
| 99 | 101 | app.bus.append({ kind: "pinned.deployed", actorId: who.value.id, payload: { name: p.name, target: p.target, version: p.version } }); |
| 100 | 102 | if (old?.volume) setRemote(app.db, p.name, { volume: old.volume }); |
| 101 | 103 | const made = await withCloud(app, who.value, p, "deploy", (f, token) => |
| 102 | provision(driverOf(p.target), f, token, getPinned(app.db, p.name)!, { | |
| 104 | provision(capped(app, p.name, driverOf(p.target)), f, token, getPinned(app.db, p.name)!, { | |
| 103 | 105 | ...(old?.volume ? { have: old.volume } : {}), |
| 104 | 106 | onVolume: (volume) => setRemote(app.db, p.name, { volume }), |
| 105 | 107 | }), |
| @@ -133,7 +135,7 @@ async function change( | ||
| 133 | 135 | app.bus.append({ kind: kind === "update" ? "pinned.update" : "pinned.rollback", actorId: who.value.id, payload: { name, from: c.fromVersion, to: c.toVersion } }); |
| 134 | 136 | } |
| 135 | 137 | const after = getPinned(app.db, name)!; |
| 136 | const done = await withCloud(app, who.value, after, kind, (f, token) => replace(driverOf(after.target), f, token, after, { onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }) })); | |
| 138 | const done = await withCloud(app, who.value, after, kind, (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, after, { onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }) })); | |
| 137 | 139 | if (!done.ok) { |
| 138 | 140 | setRemote(app.db, name, { state: "failed" }); |
| 139 | 141 | return done; |
src/cloud/ceiling.ts added +117
| @@ -0,0 +1,117 @@ | ||
| 1 | /** | |
| 2 | * The spend ceiling of a cloud account: what the forge reckons the account costs a month from the | |
| 3 | * machines and volumes the forge made on it and has not retired, and the refusal to make one more | |
| 4 | * thing that would take it over (cloud providers send alerts, not caps, so the forge is the cap). | |
| 5 | * Whole US dollars for the ceiling, whole US cents for money, integer arithmetic throughout. The | |
| 6 | * check runs in `capped`, the driver's own `plan` step: after what to order is read, before | |
| 7 | * anything is made. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { Database } from "bun:sqlite"; | |
| 11 | import type { App } from "../app.ts"; | |
| 12 | import { getCloudAccount } from "../core/cloud_account.ts"; | |
| 13 | import { getPinned, listPinned } from "../core/pinned.ts"; | |
| 14 | import { dearestMachine, machineCents, volumeCents, type PricedRow } from "./prices.ts"; | |
| 15 | import { SIZE as DROPLET_SIZE } from "./droplet.ts"; | |
| 16 | import type { Driver } from "./machine.ts"; | |
| 17 | ||
| 18 | export const DEFAULT_CEILING_DOLLARS = 50; | |
| 19 | ||
| 20 | /** Where the ceiling is raised, named in every refusal. */ | |
| 21 | export const CEILING_PAGE = "/settings/cloud"; | |
| 22 | ||
| 23 | /** A refusal in words meant to be shown as they are; withCloud passes it on whole. */ | |
| 24 | export class CeilingRefusal extends Error {} | |
| 25 | ||
| 26 | export const dollars = (cents: number): string => `$${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`; | |
| 27 | ||
| 28 | /** The size a machine was recorded with at creation; none for a machine made before sizes were kept. */ | |
| 29 | function recordedSize(db: Database, pinnedId: string): string | undefined { | |
| 30 | return db.query<{ size: string }, [string]>("SELECT size FROM pinned_size WHERE pinned_id = ?1").get(pinnedId)?.size; | |
| 31 | } | |
| 32 | ||
| 33 | function noteSize(db: Database, pinnedId: string, size: string): void { | |
| 34 | db.query("INSERT INTO pinned_size (pinned_id, size) VALUES (?1, ?2) ON CONFLICT(pinned_id) DO UPDATE SET size = excluded.size").run(pinnedId, size); | |
| 35 | } | |
| 36 | ||
| 37 | /** | |
| 38 | * What a row's machine costs a month, cents (none when it has none). A machine of no recorded | |
| 39 | * size, or of one the table no longer lists, is counted at the dearest size the cloud has in the | |
| 40 | * table: the reckoning errs high. | |
| 41 | */ | |
| 42 | function machineOfRow(db: Database, p: PricedRow & { id: string }): number { | |
| 43 | if (p.remote === "") return 0; | |
| 44 | return machineCents(p.target, recordedSize(db, p.id) ?? "") ?? dearestMachine(p.target)?.cents ?? 0; | |
| 45 | } | |
| 46 | ||
| 47 | /** What one pinned row costs a month, cents: its machine and its volume, when it has them. */ | |
| 48 | export const rowCents = (db: Database, p: PricedRow & { id: string }): number => | |
| 49 | machineOfRow(db, p) + (p.volume === "" ? 0 : (volumeCents(p.target) ?? 0)); | |
| 50 | ||
| 51 | /** What the forge reckons an account costs a month, in cents: the sum over its own pinned rows. */ | |
| 52 | export function accountCents(db: Database, provider: string, account: string): number { | |
| 53 | return listPinned(db) | |
| 54 | .filter((p) => p.target === provider && p.account === account) | |
| 55 | .reduce((sum, p) => sum + rowCents(db, p), 0); | |
| 56 | } | |
| 57 | ||
| 58 | export interface Spend { | |
| 59 | readonly ceilingDollars: number; | |
| 60 | readonly monthlyCents: number; | |
| 61 | /** Cents left under the ceiling; negative when over it. */ | |
| 62 | readonly leftCents: number; | |
| 63 | } | |
| 64 | ||
| 65 | export function spendOf(db: Database, provider: string, account: string): Spend { | |
| 66 | const ceilingDollars = getCloudAccount(db, provider, account)?.ceilingDollars ?? DEFAULT_CEILING_DOLLARS; | |
| 67 | const monthlyCents = accountCents(db, provider, account); | |
| 68 | return { ceilingDollars, monthlyCents, leftCents: ceilingDollars * 100 - monthlyCents }; | |
| 69 | } | |
| 70 | ||
| 71 | /** The size each driver orders when it decides nothing at plan time. */ | |
| 72 | const FIXED_SIZE: Readonly<Record<string, string>> = { digitalocean: DROPLET_SIZE }; | |
| 73 | ||
| 74 | /** | |
| 75 | * Refuse, in a plain sentence, when making the machine named by `plan` for pinned forge `name` | |
| 76 | * would put its account over the ceiling. The machine it replaces (this row's own) comes off, and | |
| 77 | * its volume is counted once, so a replace of a same-size machine adds nothing; a forge already | |
| 78 | * over a lowered ceiling may still be replaced by what costs no more. | |
| 79 | */ | |
| 80 | export function admit(app: App, name: string, plan: unknown): void { | |
| 81 | const p = getPinned(app.db, name); | |
| 82 | if (!p) return; | |
| 83 | const who = `${p.target}/${p.account}`; | |
| 84 | const size = typeof plan === "string" ? plan : FIXED_SIZE[p.target]; | |
| 85 | const price = size === undefined ? undefined : machineCents(p.target, size); | |
| 86 | const volume = volumeCents(p.target); | |
| 87 | if (size === undefined || price === undefined || volume === undefined) | |
| 88 | throw new CeilingRefusal(`The forge does not know what ${size ?? "the machine"} costs a month on ${p.target}, so it cannot hold ${who} to its ceiling; nothing was made.`); | |
| 89 | const { ceilingDollars, monthlyCents } = spendOf(app.db, p.target, p.account); | |
| 90 | const add = price + (p.volume === "" ? volume : 0) - machineOfRow(app.db, p); | |
| 91 | if (add <= 0 || monthlyCents + add <= ceilingDollars * 100) return; | |
| 92 | throw new CeilingRefusal( | |
| 93 | `${who} is held to $${ceilingDollars} a month and runs ${dollars(monthlyCents)} now; this would add ${dollars(add)}, which is over it, so nothing was made. ` + | |
| 94 | `Raise the ceiling at ${CEILING_PAGE} if you mean to spend more. This is the forge's own reckoning from list prices; the provider's bill is the truth.`, | |
| 95 | ); | |
| 96 | } | |
| 97 | ||
| 98 | /** | |
| 99 | * The driver, held to the account's ceiling: its `plan` checks before the first thing is made, and | |
| 100 | * the size of each machine it makes is kept so a replace can be counted against it. | |
| 101 | */ | |
| 102 | export function capped<P>(app: App, name: string, d: Driver<P>): Driver<P> { | |
| 103 | return { | |
| 104 | ...d, | |
| 105 | async plan(call) { | |
| 106 | const plan = await d.plan(call); | |
| 107 | admit(app, name, plan); | |
| 108 | return plan; | |
| 109 | }, | |
| 110 | async createMachine(call, p, volume, plan) { | |
| 111 | const remote = await d.createMachine(call, p, volume, plan); | |
| 112 | const size = typeof plan === "string" ? plan : FIXED_SIZE[p.target]; | |
| 113 | if (size !== undefined) noteSize(app.db, p.id, size); | |
| 114 | return remote; | |
| 115 | }, | |
| 116 | }; | |
| 117 | } |
src/cloud/overview.ts +6
| @@ -12,6 +12,7 @@ import { listCloudAccounts, recentCloudReads } from "../core/cloud_account.ts"; | ||
| 12 | 12 | import type { User } from "../core/users.ts"; |
| 13 | 13 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 14 | 14 | import { usedFor, type VendorUse } from "./declared.ts"; |
| 15 | import { spendOf } from "./ceiling.ts"; | |
| 15 | 16 | import { VENDOR_OF, type Provider } from "./providers.ts"; |
| 16 | 17 | |
| 17 | 18 | export interface AccountRow { |
| @@ -23,6 +24,10 @@ export interface AccountRow { | ||
| 23 | 24 | readonly lastUsedAt: string | null; |
| 24 | 25 | readonly writeAllowed: boolean; |
| 25 | 26 | readonly callsToday: number; |
| 27 | /** The forge's own reckoning from list prices (the provider's bill is the truth): the ceiling in whole dollars, the monthly cost in cents, and the cents left. */ | |
| 28 | readonly ceilingDollars: number; | |
| 29 | readonly monthlyCents: number; | |
| 30 | readonly leftCents: number; | |
| 26 | 31 | } |
| 27 | 32 | |
| 28 | 33 | export interface CloudOverview { |
| @@ -48,6 +53,7 @@ export function cloudOverview( | ||
| 48 | 53 | lastUsedAt: reads.find((r) => r.provider === a.provider && r.name === a.name)?.at ?? null, |
| 49 | 54 | writeAllowed: a.writeAllowed, |
| 50 | 55 | callsToday: today.filter((r) => r.provider === a.provider && r.account === a.name).length, |
| 56 | ...spendOf(app.db, a.provider, a.name), | |
| 51 | 57 | })); |
| 52 | 58 | return ok({ accounts, today }); |
| 53 | 59 | } |
src/cloud/prices.ts added +72
| @@ -0,0 +1,72 @@ | ||
| 1 | /** | |
| 2 | * What a pinned forge's machine and volume cost a month, per cloud: the one table the spend ceiling | |
| 3 | * (ceiling.ts) reckons from. Each price is the vendor's own amount and currency, as data, in cents | |
| 4 | * of that currency; `usdCents` is the only place one becomes dollars. They are list prices read | |
| 5 | * 2026-11-23 from the providers' public pages. The forge's reckoning is not the bill; the | |
| 6 | * provider's bill is the truth. A size the drivers can order that is missing here is refused, | |
| 7 | * never counted as free. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { Pinned } from "../core/pinned.ts"; | |
| 11 | ||
| 12 | export type Currency = "USD" | "EUR"; | |
| 13 | export interface Amount { | |
| 14 | readonly amountCents: number; | |
| 15 | readonly currency: Currency; | |
| 16 | } | |
| 17 | ||
| 18 | export interface Prices { | |
| 19 | /** Monthly list price of each size the driver can order, by the id the cloud's API uses. */ | |
| 20 | readonly machines: Readonly<Record<string, Amount>>; | |
| 21 | /** Monthly list price of `per` GiB of volume (a whole number of cents needs a round quantity). */ | |
| 22 | readonly volume: Amount & { readonly per: number }; | |
| 23 | } | |
| 24 | ||
| 25 | export const PRICES: Readonly<Record<string, Prices>> = { | |
| 26 | // https://www.digitalocean.com/pricing/droplets, /pricing/volume-block-storage: $12.00, $0.10/GiB. | |
| 27 | digitalocean: { machines: { "s-1vcpu-2gb": { amountCents: 1200, currency: "USD" } }, volume: { amountCents: 1000, currency: "USD", per: 100 } }, | |
| 28 | // https://www.hetzner.com/cloud: CX23 5.99, CX33 8.99, CPX11 (US) 17.99. The volume price, | |
| 29 | // 0.0572 a GiB-month (5.72 per 100 GiB), is UNVERIFIED: a third-party source, not Hetzner's page. | |
| 30 | hetzner: { | |
| 31 | machines: { cx23: { amountCents: 599, currency: "EUR" }, cx33: { amountCents: 899, currency: "EUR" }, cpx11: { amountCents: 1799, currency: "EUR" } }, | |
| 32 | volume: { amountCents: 572, currency: "EUR", per: 100 }, | |
| 33 | }, | |
| 34 | }; | |
| 35 | ||
| 36 | /** | |
| 37 | * EUR in USD, in thousandths: a deliberately high fixed rate, so the ceiling errs toward refusing. | |
| 38 | * The price catalog (#16203) replaces it with a fetched daily rate and deletes this constant. | |
| 39 | */ | |
| 40 | const EUR_USD_PERMILLE = 1200; | |
| 41 | ||
| 42 | /** The size of the volume each driver asks for (both write 10 in their createVolume). */ | |
| 43 | export const VOLUME_GIB = 10; | |
| 44 | ||
| 45 | /** | |
| 46 | * The one conversion to dollars: `amountCents` of `currency` (for `per` units of it, when the | |
| 47 | * amount is a price per quantity) as whole US cents, rounded up. USD passes through unconverted. | |
| 48 | */ | |
| 49 | export function usdCents(amountCents: number, currency: Currency, rate = currency === "EUR" ? EUR_USD_PERMILLE : 1000, per = 1): number { | |
| 50 | return Math.ceil((amountCents * rate) / (1000 * per)); | |
| 51 | } | |
| 52 | ||
| 53 | /** A machine's monthly cost in US cents; undefined when the cloud or the size is not in the table. */ | |
| 54 | export function machineCents(cloud: string, size: string): number | undefined { | |
| 55 | const p = PRICES[cloud]?.machines[size]; | |
| 56 | return p ? usdCents(p.amountCents, p.currency) : undefined; | |
| 57 | } | |
| 58 | ||
| 59 | /** The monthly cost of the volumes of `gib` GiB, in US cents; undefined when the cloud is not in the table. */ | |
| 60 | export function volumeCents(cloud: string, gib = VOLUME_GIB): number | undefined { | |
| 61 | const t = PRICES[cloud]; | |
| 62 | return t ? usdCents(t.volume.amountCents * gib, t.volume.currency, undefined, t.volume.per) : undefined; | |
| 63 | } | |
| 64 | ||
| 65 | /** The dearest size in the table for a cloud: what a machine of unrecorded size is counted at. */ | |
| 66 | export function dearestMachine(cloud: string): { size: string; cents: number } | undefined { | |
| 67 | const t = PRICES[cloud]; | |
| 68 | const all = Object.keys(t?.machines ?? {}).map((size) => ({ size, cents: machineCents(cloud, size)! })); | |
| 69 | return all.sort((a, b) => b.cents - a.cents)[0]; | |
| 70 | } | |
| 71 | ||
| 72 | export type PricedRow = Pick<Pinned, "target" | "remote" | "volume">; |
src/core/cloud_account.ts +9
| @@ -50,6 +50,8 @@ export interface CloudAccount { | ||
| 50 | 50 | readonly summary: string; |
| 51 | 51 | readonly verifiedAt: string | null; |
| 52 | 52 | readonly writeAllowed: boolean; |
| 53 | /** The most the forge will let this account cost a month, whole US dollars (ceiling.ts). */ | |
| 54 | readonly ceilingDollars: number; | |
| 53 | 55 | } |
| 54 | 56 | |
| 55 | 57 | interface Row { |
| @@ -58,6 +60,7 @@ interface Row { | ||
| 58 | 60 | summary: string; |
| 59 | 61 | verified_at: string | null; |
| 60 | 62 | write_allowed: number; |
| 63 | ceiling_dollars: number; | |
| 61 | 64 | } |
| 62 | 65 | |
| 63 | 66 | const toAccount = (r: Row): CloudAccount => ({ |
| @@ -66,6 +69,7 @@ const toAccount = (r: Row): CloudAccount => ({ | ||
| 66 | 69 | summary: r.summary, |
| 67 | 70 | verifiedAt: r.verified_at, |
| 68 | 71 | writeAllowed: r.write_allowed === 1, |
| 72 | ceilingDollars: r.ceiling_dollars, | |
| 69 | 73 | }); |
| 70 | 74 | |
| 71 | 75 | export function listCloudAccounts(db: Database): CloudAccount[] { |
| @@ -121,6 +125,11 @@ export function setWriteAllowed( | ||
| 121 | 125 | ); |
| 122 | 126 | } |
| 123 | 127 | |
| 128 | export function setCeilingDollars(db: Database, provider: string, name: string, dollars: number): boolean { | |
| 129 | table(db); | |
| 130 | return db.query("UPDATE cloud_account SET ceiling_dollars = ?3 WHERE provider = ?1 AND name = ?2").run(provider, name, dollars).changes > 0; | |
| 131 | } | |
| 132 | ||
| 124 | 133 | export function renameCloudAccount( |
| 125 | 134 | db: Database, |
| 126 | 135 | provider: string, |
src/core/event_audience.ts +1
| @@ -299,6 +299,7 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 299 | 299 | kind === "forge.upstream" || |
| 300 | 300 | kind === "forge.updates_taken" || |
| 301 | 301 | kind === "cloud.write_allowed" || |
| 302 | kind === "cloud.ceiling" || | |
| 302 | 303 | // A bet's name, share and what is left are the owner's plan (#8713). |
| 303 | 304 | kind.startsWith("bet.") || |
| 304 | 305 | // A pinned forge's deploy, update and rollback name the owner's cloud (#8697). |
src/core/migration-pins/20261123140000-cloud-account-ceiling.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | f1a13b8af4ce84c052fa49aefd82e50e1959bd6dde0925baf1be646d565c0567 |
src/core/migrations/20261123140000-cloud-account-ceiling.ts added +19
| @@ -0,0 +1,19 @@ | ||
| 1 | // A monthly spend ceiling on every cloud account, in whole US dollars, 50 for each account that | |
| 2 | // exists and each that is added. Also the size of each machine a pinned forge was given, so a | |
| 3 | // replace can be counted against the machine it replaces. The cloud_account table is otherwise | |
| 4 | // made on first use; made here too, in its same shape, so the column has a table to join. Additive. | |
| 5 | export default ` | |
| 6 | CREATE TABLE IF NOT EXISTS cloud_account ( | |
| 7 | provider TEXT NOT NULL, | |
| 8 | name TEXT NOT NULL, | |
| 9 | summary TEXT NOT NULL DEFAULT '', | |
| 10 | verified_at TEXT, | |
| 11 | write_allowed INTEGER NOT NULL DEFAULT 0, | |
| 12 | PRIMARY KEY (provider, name) | |
| 13 | ); | |
| 14 | ALTER TABLE cloud_account ADD COLUMN ceiling_dollars INTEGER NOT NULL DEFAULT 50; | |
| 15 | CREATE TABLE IF NOT EXISTS pinned_size ( | |
| 16 | pinned_id TEXT PRIMARY KEY, | |
| 17 | size TEXT NOT NULL | |
| 18 | ); | |
| 19 | `; |
src/http/marks/settings.json +1
src/http/mcp/tools/cloud_account.ts +9 −5
| @@ -1,23 +1,25 @@ | ||
| 1 | 1 | import { addAccount, allowWrite, auditAccount, removeAccount, renameAccount, reverify, rotateAccount } from "../../../actions/cloud.ts"; |
| 2 | import { setCeiling } from "../../../actions/cloud_ceiling.ts"; | |
| 2 | 3 | import { PROVIDERS } from "../../../cloud/providers.ts"; |
| 3 | 4 | import { scopeAllows } from "../../../core/tokens.ts"; |
| 4 | 5 | import { good, bad, type Tool, str } from "../shared.ts"; |
| 5 | 6 | |
| 6 | 7 | export const tool: Tool = { |
| 7 | 8 | name: "cloud_account", |
| 8 | doc: "`{ verb, provider, name, value?, to?, allowed?, repo? }`: change a cloud account: `attach` or `rotate` a token (`value`), `verify` it, `rename` it (`to`), `remove` it, `allow_writes` (`allowed` true or false) or `audit` (`repo` owner/name); a forge admin with an admin-scope token; answers a one-line `says`", | |
| 9 | doc: "`{ verb, provider, name, value?, to?, allowed?, repo?, dollars? }`: 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) or `audit` (`repo` owner/name); a forge admin with an admin-scope token; answers a one-line `says`", | |
| 9 | 10 | description: |
| 10 | 11 | "Change a cloud account by `verb` (admin).", |
| 11 | 12 | inputSchema: { |
| 12 | 13 | type: "object", |
| 13 | 14 | properties: { |
| 14 | verb: { type: "string", enum: ["attach", "verify", "rotate", "rename", "remove", "allow_writes", "audit"] }, | |
| 15 | verb: { type: "string", enum: ["attach", "verify", "rotate", "rename", "remove", "allow_writes", "set_ceiling", "audit"] }, | |
| 15 | 16 | provider: { type: "string", enum: [...PROVIDERS] }, |
| 16 | 17 | name: { type: "string", maxLength: 32 }, |
| 17 | 18 | value: { type: "string", maxLength: 4096, description: "For attach, rotate." }, |
| 18 | 19 | to: { type: "string", maxLength: 32 }, |
| 19 | 20 | allowed: { type: "boolean" }, |
| 20 | 21 | repo: { type: "string", maxLength: 200 }, |
| 22 | dollars: { type: "integer", minimum: 0, maximum: 100000, description: "For set_ceiling." }, | |
| 21 | 23 | }, |
| 22 | 24 | required: ["verb", "provider", "name"], |
| 23 | 25 | }, |
| @@ -44,10 +46,12 @@ export const tool: Tool = { | ||
| 44 | 46 | ? removeAccount(ctx.app, user, provider, name) |
| 45 | 47 | : verb === "allow_writes" |
| 46 | 48 | ? allowWrite(ctx.app, user, provider, name, args["allowed"] === true) |
| 47 | : verb === "audit" | |
| 48 | ? await auditAccount(ctx.app, user, provider, name, str(args["repo"])) | |
| 49 | : verb === "set_ceiling" | |
| 50 | ? setCeiling(ctx.app, user, provider, name, args["dollars"]) | |
| 51 | : verb === "audit" | |
| 52 | ? await auditAccount(ctx.app, user, provider, name, str(args["repo"])) | |
| 49 | 53 | : undefined; |
| 50 | if (done === undefined) return bad("bad_verb", "verb is attach, verify, rotate, rename, remove, allow_writes or audit"); | |
| 54 | if (done === undefined) return bad("bad_verb", "verb is attach, verify, rotate, rename, remove, allow_writes, set_ceiling or audit"); | |
| 51 | 55 | if (!done.ok) return bad("refused", done.error); |
| 52 | 56 | const v = done.value as unknown; |
| 53 | 57 | const said = |
src/http/settings_routes.ts +2
| @@ -75,6 +75,7 @@ import { | ||
| 75 | 75 | cloudVerify, |
| 76 | 76 | cloudWrite, |
| 77 | 77 | } from "../web/pages/cloud.ts"; |
| 78 | import { cloudCeiling } from "../web/pages/cloud_ceiling.ts"; | |
| 78 | 79 | import { |
| 79 | 80 | subscriptionAdd, |
| 80 | 81 | subscriptionDelete, |
| @@ -234,6 +235,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 234 | 235 | router.add("POST", "/settings/cloud", cloudAdd); |
| 235 | 236 | router.add("POST", "/settings/cloud/verify", cloudVerify); |
| 236 | 237 | router.add("POST", "/settings/cloud/write", cloudWrite); |
| 238 | router.add("POST", "/settings/cloud/ceiling", cloudCeiling); | |
| 237 | 239 | router.add("POST", "/settings/cloud/audit", cloudAudit); |
| 238 | 240 | router.add("GET", "/settings/cloud/audit", cloudAuditPage); |
| 239 | 241 | router.add("POST", "/settings/cloud/rotate", cloudRotate); |
src/web/pages/cloud.ts +17 −3
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | * event. "Write allowed" is off until someone turns it on here. |
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | import type { Database } from "bun:sqlite"; | |
| 9 | 10 | import { sshOn } from "../../settings/ssh.ts"; |
| 10 | 11 | import { |
| 11 | 12 | addAccount, |
| @@ -18,6 +19,7 @@ import { | ||
| 18 | 19 | } from "../../actions/cloud.ts"; |
| 19 | 20 | import { LABEL, PROVIDERS, VENDOR_OF, isProvider, shape } from "../../cloud/providers.ts"; |
| 20 | 21 | import { HOME, usedFor, usesByVendor, type VendorUse } from "../../cloud/declared.ts"; |
| 22 | import { dollars, spendOf } from "../../cloud/ceiling.ts"; | |
| 21 | 23 | import { auditToday } from "../../core/cloud_audit.ts"; |
| 22 | 24 | import { |
| 23 | 25 | listCloudAccounts, |
| @@ -51,7 +53,12 @@ const hidden = (provider: string, name: string): Html => | ||
| 51 | 53 | html`<input type="hidden" name="provider" value="${provider}" /> |
| 52 | 54 | <input type="hidden" name="name" value="${name}" />`; |
| 53 | 55 | |
| 54 | function accountsCard(accounts: CloudAccount[], reads: CloudRead[], uses: Map<string, VendorUse[]>): Html { | |
| 56 | function ceilingLine(db: Database, a: CloudAccount): string { | |
| 57 | const s = spendOf(db, a.provider, a.name); | |
| 58 | return `ceiling $${s.ceilingDollars} a month · the forge reckons ${dollars(s.monthlyCents)} now · ${s.leftCents >= 0 ? `${dollars(s.leftCents)} left` : `${dollars(-s.leftCents)} over`}`; | |
| 59 | } | |
| 60 | ||
| 61 | function accountsCard(db: Database, accounts: CloudAccount[], reads: CloudRead[], uses: Map<string, VendorUse[]>): Html { | |
| 55 | 62 | const rows = accounts.map((a) => { |
| 56 | 63 | const last = reads.find((r) => r.provider === a.provider && r.name === a.name); |
| 57 | 64 | return row({ |
| @@ -59,7 +66,7 @@ function accountsCard(accounts: CloudAccount[], reads: CloudRead[], uses: Map<st | ||
| 59 | 66 | title: html`${LABEL[a.provider]} / <span class="mono">${a.name}</span>`, |
| 60 | 67 | meta: html`${a.summary}<br />${usedFor(uses.get(VENDOR_OF[a.provider]))}<br />${HOME[a.provider]}<br />verified ${a.verifiedAt ? time(a.verifiedAt) : "never"} · |
| 61 | 68 | ${last ? html`last used ${time(last.at)} by ${runWords(last.run)}` : "never used"} · |
| 62 | ${a.writeAllowed ? "writes allowed" : "read-only"}`, | |
| 69 | ${a.writeAllowed ? "writes allowed" : "read-only"}<br />${ceilingLine(db, a)}`, | |
| 63 | 70 | trail: html`<div class="row-fields"> |
| 64 | 71 | <form method="post" action="/settings/cloud/verify"> |
| 65 | 72 | ${hidden(a.provider, a.name)}${btn("Verify", { size: "sm", label: `Verify ${a.name}` })} |
| @@ -69,6 +76,12 @@ function accountsCard(accounts: CloudAccount[], reads: CloudRead[], uses: Map<st | ||
| 69 | 76 | <input type="hidden" name="allowed" value="${a.writeAllowed ? "0" : "1"}" /> |
| 70 | 77 | ${btn(a.writeAllowed ? "Turn writes off" : "Allow writes", { size: "sm", label: `Write switch for ${a.name}` })} |
| 71 | 78 | </form> |
| 79 | <form method="post" action="/settings/cloud/ceiling" class="row-fields"> | |
| 80 | ${hidden(a.provider, a.name)} | |
| 81 | <input class="input mono" type="number" name="dollars" value="${a.ceilingDollars}" min="0" max="100000" step="1" | |
| 82 | aria-label="Monthly ceiling in US dollars for ${a.name}" required /> | |
| 83 | ${btn("Set ceiling", { size: "sm", label: `Set the ceiling of ${a.name}` })} | |
| 84 | </form> | |
| 72 | 85 | <form method="post" action="/settings/cloud/audit" class="row-fields"> |
| 73 | 86 | ${hidden(a.provider, a.name)} |
| 74 | 87 | <input class="input" type="text" name="repo" placeholder="owner/repo for findings" |
| @@ -98,6 +111,7 @@ function accountsCard(accounts: CloudAccount[], reads: CloudRead[], uses: Map<st | ||
| 98 | 111 | }); |
| 99 | 112 | return html`<section class="settings-block"> |
| 100 | 113 | <h2>Cloud accounts</h2> |
| 114 | <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> | |
| 101 | 115 | <p class="muted small">Paste a credential once; the forge checks it read-only, seals it, and never shows it again.</p> |
| 102 | 116 | ${rows.length > 0 |
| 103 | 117 | ? html`<ul class="list setting-list">${rows}</ul>` |
| @@ -154,7 +168,7 @@ export async function cloudPage(ctx: Ctx): Promise<Response> { | ||
| 154 | 168 | body: html`<div class="page-head"><h1>Cloud accounts</h1></div> |
| 155 | 169 | ${settingsLayout( |
| 156 | 170 | accountSections("cloud", { admin: true, ssh: sshOn(ctx.app.db) }), |
| 157 | html`${accountsCard(accounts, reads, uses)}${readsCard(reads)} | |
| 171 | html`${accountsCard(ctx.app.db, accounts, reads, uses)}${readsCard(reads)} | |
| 158 | 172 | <p class="muted small"><a href="/settings/cloud/audit">Every vendor call today</a> · <a href="/pinned">Pinned forges</a> · <a href="/deploy-to">Deploy a pinned forge</a></p>`, |
| 159 | 173 | "Account settings", |
| 160 | 174 | )}`, |
src/web/pages/cloud_ceiling.ts added +17
| @@ -0,0 +1,17 @@ | ||
| 1 | /** POST /settings/cloud/ceiling: set an account's monthly spend ceiling, whole US dollars. */ | |
| 2 | ||
| 3 | import { setCeiling } from "../../actions/cloud_ceiling.ts"; | |
| 4 | import type { Ctx } from "../../http/context.ts"; | |
| 5 | import { notFoundPage, signInFirst } from "../chrome.ts"; | |
| 6 | import { field, readForm } from "../form.ts"; | |
| 7 | import { flashTo } from "../layout.ts"; | |
| 8 | ||
| 9 | export async function cloudCeiling(ctx: Ctx): Promise<Response> { | |
| 10 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 11 | if (!ctx.auth.user.isAdmin) return notFoundPage(ctx); | |
| 12 | const form = await readForm(ctx, "admin"); | |
| 13 | if (form instanceof Response) return form; | |
| 14 | const raw = field(form, "dollars").trim(); | |
| 15 | const r = setCeiling(ctx.app, ctx.auth.user, field(form, "provider"), field(form, "name"), /^\d{1,6}$/.test(raw) ? Number(raw) : NaN); | |
| 16 | return flashTo(ctx, "/settings/cloud", r.ok ? { message: `Saved: ${r.value}.` } : { tone: "danger", message: r.error }); | |
| 17 | } |
test/pinned-ceiling.test.ts added +135
| @@ -0,0 +1,135 @@ | ||
| 1 | /** | |
| 2 | * The spend ceiling of a cloud account: $50 a month for every account until an admin changes it, | |
| 3 | * reckoned from the forge's own pinned rows at list prices, and enforced before anything is made. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts"; | |
| 11 | import { setCeiling } from "../src/actions/cloud_ceiling.ts"; | |
| 12 | import { deployPinned, net, updatePinned } from "../src/actions/pinned.ts"; | |
| 13 | import { cloudOverview } from "../src/cloud/overview.ts"; | |
| 14 | import { machineCents, volumeCents } from "../src/cloud/prices.ts"; | |
| 15 | import { getCloudAccount } from "../src/core/cloud_account.ts"; | |
| 16 | import { getPinned } from "../src/core/pinned.ts"; | |
| 17 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 18 | import { quietLogs } from "./helpers/globals.ts"; | |
| 19 | ||
| 20 | quietLogs(); | |
| 21 | ||
| 22 | const V1 = "a".repeat(40); | |
| 23 | const V2 = "b".repeat(40); | |
| 24 | const SOURCE = "https://forge.example.org/trevato/forge"; | |
| 25 | ||
| 26 | describe("cloud account ceiling", () => { | |
| 27 | let dataDir = ""; | |
| 28 | let app: App; | |
| 29 | const calls: string[] = []; | |
| 30 | let hetznerType = "cx23"; | |
| 31 | let seq = 1000; | |
| 32 | ||
| 33 | const admin = () => getUserByName(app.db, "alice")!; | |
| 34 | const input = (name: string, over: Record<string, unknown> = {}) => ({ | |
| 35 | name, target: "digitalocean", account: "main", app: "alice/shop", source: SOURCE, version: V1, config: {}, ...over, | |
| 36 | }); | |
| 37 | const error = (r: unknown) => String((r as { error: unknown }).error); | |
| 38 | ||
| 39 | beforeAll(async () => { | |
| 40 | dataDir = await mkdtemp(join(tmpdir(), "forge-ceiling-")); | |
| 41 | app = createApp({ dataDir, port: 0 }); | |
| 42 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 43 | if (!made.ok) throw new Error(made.error); | |
| 44 | cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" }, servers: [], meta: { pagination: { total_entries: 0 } } }), { status: 200 }); | |
| 45 | for (const [provider, token] of [["digitalocean", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"], ["hetzner", "hcloud_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9"]] as const) { | |
| 46 | const added = await addAccount(app, admin(), provider, "main", token); | |
| 47 | if (!added.ok) throw new Error(String(added.error)); | |
| 48 | allowWrite(app, admin(), provider, "main", true); | |
| 49 | } | |
| 50 | net.fetch = async (url, init) => { | |
| 51 | const u = new URL(url); | |
| 52 | const method = init?.method ?? "GET"; | |
| 53 | calls.push(`${method} ${u.host}${u.pathname}`); | |
| 54 | const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status }); | |
| 55 | if (u.pathname === "/v1/server_types") return json({ server_types: [{ id: 9, name: hetznerType, architecture: "x86", memory: 4, prices: [{ location: "nbg1", price_monthly: { gross: "5.0" } }] }] }); | |
| 56 | if (u.pathname === "/v1/datacenters") return json({ datacenters: [{ location: { name: "nbg1" }, server_types: { available: [9] } }] }); | |
| 57 | if (u.pathname === "/v2/volumes" || u.pathname === "/v1/volumes") return json({ volume: { id: ++seq } }, 201); | |
| 58 | if (method === "DELETE") return new Response(null, { status: 204 }); | |
| 59 | if (u.pathname === "/v1/servers") return json({ server: { id: ++seq } }, 201); | |
| 60 | return json({ droplet: { id: ++seq } }, 202); | |
| 61 | }; | |
| 62 | }, 30_000); | |
| 63 | ||
| 64 | afterAll(async () => { | |
| 65 | app.close(); | |
| 66 | await rm(dataDir, { recursive: true, force: true }); | |
| 67 | }); | |
| 68 | ||
| 69 | test("every account has a $50 ceiling with no setup, and nothing reckoned yet", () => { | |
| 70 | expect(getCloudAccount(app.db, "digitalocean", "main")?.ceilingDollars).toBe(50); | |
| 71 | const o = cloudOverview(app, admin()); | |
| 72 | expect(o.ok && o.value.accounts.find((a) => a.provider === "digitalocean")).toMatchObject({ ceilingDollars: 50, monthlyCents: 0, leftCents: 5000 }); | |
| 73 | }); | |
| 74 | ||
| 75 | test("EUR is counted as USD times 1.2, rounded up to the cent", () => { | |
| 76 | expect(machineCents("hetzner", "cx23")).toBe(719); // 5.99 * 1.2 = 7.188 | |
| 77 | expect(volumeCents("hetzner")).toBe(69); // 10 GiB * 0.0572 * 1.2 = 0.686 | |
| 78 | expect(machineCents("digitalocean", "s-1vcpu-2gb")).toBe(1200); | |
| 79 | expect(volumeCents("digitalocean")).toBe(100); | |
| 80 | expect(machineCents("digitalocean", "s-9vcpu")).toBeUndefined(); | |
| 81 | }); | |
| 82 | ||
| 83 | test("deploys under the ceiling pass, and the page-ready reckoning counts them", async () => { | |
| 84 | for (const n of ["one", "two", "three"]) expect((await deployPinned(app, admin(), input(n))).ok).toBe(true); | |
| 85 | const o = cloudOverview(app, admin()); | |
| 86 | expect(o.ok && o.value.accounts.find((a) => a.provider === "digitalocean")).toMatchObject({ monthlyCents: 3900, leftCents: 1100 }); | |
| 87 | }); | |
| 88 | ||
| 89 | test("the deploy that would cross the ceiling is refused before any provider call", async () => { | |
| 90 | calls.length = 0; | |
| 91 | const r = await deployPinned(app, admin(), input("four")); | |
| 92 | expect(r).toMatchObject({ ok: false }); | |
| 93 | expect(error(r)).toBe( | |
| 94 | "digitalocean/main is held to $50 a month and runs $39.00 now; this would add $13.00, which is over it, so nothing was made. " + | |
| 95 | "Raise the ceiling at /settings/cloud if you mean to spend more. This is the forge's own reckoning from list prices; the provider's bill is the truth.", | |
| 96 | ); | |
| 97 | expect(calls).toHaveLength(0); | |
| 98 | }); | |
| 99 | ||
| 100 | test("raising the ceiling lets it through", async () => { | |
| 101 | expect(setCeiling(app, admin(), "digitalocean", "main", 52).ok).toBe(true); | |
| 102 | expect((await deployPinned(app, admin(), input("four"))).ok).toBe(true); | |
| 103 | expect(getPinned(app.db, "four")?.state).toBe("running"); | |
| 104 | }); | |
| 105 | ||
| 106 | test("a replace of a same-size machine passes at the ceiling", async () => { | |
| 107 | const o = cloudOverview(app, admin()); | |
| 108 | expect(o.ok && o.value.accounts.find((a) => a.provider === "digitalocean")?.leftCents).toBe(0); | |
| 109 | const r = await updatePinned(app, admin(), "one", { version: V2 }); | |
| 110 | expect(r.ok).toBe(true); | |
| 111 | expect(calls.filter((c) => c.startsWith("DELETE")).length).toBeGreaterThan(0); | |
| 112 | }); | |
| 113 | ||
| 114 | test("a ceiling is whole dollars, and only an admin sets it", () => { | |
| 115 | for (const bad of [1.5, -1, "50", 1e9]) expect(setCeiling(app, admin(), "digitalocean", "main", bad).ok).toBe(false); | |
| 116 | expect(setCeiling(app, undefined, "digitalocean", "main", 10)).toMatchObject({ ok: false, error: "not_found" }); | |
| 117 | expect(setCeiling(app, admin(), "digitalocean", "nope", 10)).toMatchObject({ ok: false }); | |
| 118 | }); | |
| 119 | ||
| 120 | test("a size with no price is refused, never counted as free", async () => { | |
| 121 | hetznerType = "cx99"; | |
| 122 | calls.length = 0; | |
| 123 | const r = await deployPinned(app, admin(), input("odd", { target: "hetzner" })); | |
| 124 | expect(r).toMatchObject({ ok: false }); | |
| 125 | expect(error(r)).toContain("does not know what cx99 costs a month on hetzner"); | |
| 126 | expect(calls.every((c) => c.startsWith("GET"))).toBe(true); | |
| 127 | hetznerType = "cx23"; | |
| 128 | }); | |
| 129 | ||
| 130 | test("Hetzner is reckoned in dollars at the high rate: a deploy adds $7.19 and $0.69", async () => { | |
| 131 | expect((await deployPinned(app, admin(), input("het", { target: "hetzner" }))).ok).toBe(true); | |
| 132 | const o = cloudOverview(app, admin()); | |
| 133 | expect(o.ok && o.value.accounts.find((a) => a.provider === "hetzner")).toMatchObject({ monthlyCents: 788, ceilingDollars: 50 }); | |
| 134 | }); | |
| 135 | }); |
new above
offline