Public: anyone can read this; the crew can change it.

Data: managed Postgres on DigitalOcean as an infra kind (#16696) #17128

opened this

Merged 45h 39m ago, live in production

mason/forge:mason/17074-data-managed-postgres-on-digitalocean-as → main 0 commits fork

  • Merged. mason/17074-data-managed-postgres-on-digitalocean-as was merged into main as f35086a.

Review

Sign in to review this change.
16 files changed +1122 −60
docs/features/infra.md +8
@@ -34,6 +34,14 @@ Build refuses a plan that changed since it was shown, so nobody builds what they
3434
3535 Build runs in the background and appends `infra.applied` (the wants and each step's sentence), then one `infra.step` per step (started, done or failed), or `infra.refused` when it was refused before its first step. The tray is a live region on those events: each step shows as it happens, then "Ready at" its name with the link. A build that stopped says why with Build again, which plans the same wants against what exists now and skips what is done.
3636
37 ## A database (#17074)
38
39 Managed Postgres on DigitalOcean is a second kind of thing the plan builds, for an app. Compose it with `b` in the terminal's Infrastructure screen (an app, a region of a writable DigitalOcean account, a size), with the `infra` tool's `plan` and a `want` of `{database: true, app, where: "digitalocean/main@nyc1", size?, name?, secret?}`, or with `POST /api/v1/admin/infra/plan` and `database: true`. The page does not compose one yet; its account meters and the `infra` list count and name each database.
40
41 The plan reads the size's list price (`src/cloud/database.ts`: 1 vCPU/1 GB $15, 1/2 $30, 2/4 $60, 4/8 $120 a month; DigitalOcean's API gives no price, so they are held there) and holds it to the account's ceiling in the ceiling's own sentence. Its steps are three: create the cluster, wait until it is online (a few minutes), then give the app its URL as a secret of its own (`DATABASE_URL`, or the `secret` named), in the production environment only: a preview never holds the production database. The URL is read from DigitalOcean when it is given and kept only in the app's sealed variables, never on the forge's row or in an event. A stopped build is finished by building the same plan again, which skips what exists and never makes a second cluster.
42
43 Deleting a database, and the data in it, is not here yet: do it at DigitalOcean, and the forge's row stays until that is built.
44
3745 ## Buckets (#17073)
3846
3947 Phase 3's first kind, DigitalOcean Spaces (`src/cloud/bucket.ts`; a new provider is one more row of `BUCKETS`). In Talk or MCP, `infra` `price` with `bucket: {region, name, stored_gib?, out_gib?}` says what a bucket costs a month and where it would answer: the provider's list price ($5 with 250 GiB stored and 1 TiB out in it, 2¢ and 1¢ a GiB over), held as numbers because Spaces has no price endpoint. `bind` with `repo` sets that app's secret `BUCKET_URL` to the bucket's address (`src/actions/bucket.ts`), which restarts the app as any secret change does. Not done yet: making the bucket from a plan (it needs Spaces keys, which the forge does not hold), Hetzner and B2, and the page and terminal doors; make the bucket at the provider and keep its keys as the app's secrets.
src/actions/database.ts added +159
@@ -0,0 +1,159 @@
1 /**
2 * Managed databases (#17074): the three things the infrastructure plan does to the world for a
3 * database, as a forge admin: make the cluster at DigitalOcean, read it until it is online, and
4 * hand its URL to the app as a sealed secret. Each opens the account's token for its one call
5 * (`secret.read` names it) and goes through the gated fetch, like the pinned deploy. The URL is
6 * read from the provider each time it is needed and never kept on a row or in an event.
7 */
8
9 import type { App } from "../app.ts";
10 import { refusalOf, spendOf } from "../cloud/ceiling.ts";
11 import { createCluster, databaseCents, findCluster, readCluster } from "../cloud/database.ts";
12 import { gatedFetch } from "../cloud/gate.ts";
13 import { getCloudAccount, NO_ACCOUNT, READ_ONLY, secretNameOf } from "../core/cloud_account.ts";
14 import { databaseNamed, insertDatabase, setDatabase, type ManagedDatabase } from "../core/managed_database.ts";
15 import { resolveSecrets } from "../core/secret_store.ts";
16 import { getRepo } from "../core/repos.ts";
17 import type { User } from "../core/users.ts";
18 import { err, ok, type Result } from "../kernel/result.ts";
19 import { oneAtATime } from "../spawn/own_code.ts";
20 import { orphanRefusal } from "../cloud/watch_read.ts";
21 import type { Call } from "../cloud/machine.ts";
22 import { net } from "./pinned.ts";
23 import { setAppEnvVar } from "./apps.ts";
24
25 const API = "https://api.digitalocean.com/v2";
26 const DIGITALOCEAN = "digitalocean";
27
28 /** Why nothing is made: the database's account must be a DigitalOcean one. */
29 export const ONLY_DIGITALOCEAN = "Managed Postgres is made on DigitalOcean accounts only.";
30
31 const admin = (a: User | undefined): Result<User, string> => (a?.isAdmin === true ? ok(a) : err("not_found"));
32
33 /** A call to DigitalOcean with the account's token, opened for this one use. */
34 function callOf(app: App, who: User, d: ManagedDatabase, purpose: string): Result<Call, string> {
35 const [provider = "", ...rest] = d.account.split("/");
36 const name = rest.join("/");
37 const account = getCloudAccount(app.db, provider, name);
38 if (account === undefined || provider !== DIGITALOCEAN) return err(account === undefined ? NO_ACCOUNT : ONLY_DIGITALOCEAN);
39 const secret = secretNameOf(account.provider, account.name);
40 const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: who.id, run: `database:${purpose}` })[secret];
41 if (token === undefined) return err("No such credential.");
42 const f = gatedFetch(app.db, { provider, account: name }, `database:${purpose}`, net.fetch);
43 const host = new URL(API).host;
44 return ok(async (method, path, body) => {
45 const res = await f(`${API}${path}`, {
46 method,
47 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
48 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
49 signal: AbortSignal.timeout(20_000),
50 });
51 if (!res.ok) throw new Error(`${host} answered ${res.status}`);
52 return res.status === 204 ? {} : await res.json();
53 });
54 }
55
56 const refused = (e: unknown): string => `The cloud refused: ${e instanceof Error ? e.message.slice(0, 200) : "failed"}`;
57
58 /**
59 * Make the cluster for a database that is wanted: its row first, so a stop leaves a trace, then the
60 * provider, asked only when it holds none already for this name. Held to the account's ceiling
61 * inside the account's one-at-a-time turn, as a machine is, so two builds together cannot both fit
62 * under a ceiling with room for one.
63 */
64 export function createDatabase(
65 app: App,
66 actor: User | undefined,
67 w: Pick<ManagedDatabase, "name" | "account" | "region" | "size" | "app" | "secret">,
68 ): Promise<Result<string, string>> {
69 const who = admin(actor);
70 if (!who.ok) return Promise.resolve(who);
71 return oneAtATime(app, `database-account:${w.account}`, async () => {
72 const [provider = "", ...rest] = w.account.split("/");
73 const account = getCloudAccount(app.db, provider, rest.join("/"));
74 if (account === undefined) return err(NO_ACCOUNT);
75 if (!account.writeAllowed) return err(READ_ONLY);
76 const had = databaseNamed(app.db, w.name);
77 if (had === undefined || had.remote === "") {
78 const price = databaseCents(w.size);
79 const spend = spendOf(app.db, provider, account.name);
80 const no = refusalOf({
81 provider,
82 account: account.name,
83 place: { id: `${provider}:${w.region}:${w.size}`, size: w.size, datacenter: w.region },
84 orphan: orphanRefusal(app.db, provider, account.name),
85 price,
86 closed: undefined,
87 ceilingDollars: spend.ceilingDollars,
88 monthlyCents: spend.monthlyCents,
89 counted: had === undefined ? 0 : (price ?? 0),
90 held: 0,
91 });
92 if (no !== undefined) return err(no);
93 }
94 insertDatabase(app.db, w);
95 const row = databaseNamed(app.db, w.name)!;
96 const call = callOf(app, who.value, row, "create");
97 if (!call.ok) return call;
98 try {
99 const have = row.remote !== "" ? row.remote : ((await findCluster(call.value, w.name))?.id ?? (await createCluster(call.value, w)));
100 setDatabase(app.db, w.name, { remote: have });
101 app.bus.append({ kind: "database.created", actorId: who.value.id, payload: { name: w.name, account: w.account, region: w.region, size: w.size } });
102 return ok(have);
103 } catch (e) {
104 if (databaseNamed(app.db, w.name)?.remote === "") setDatabase(app.db, w.name, { state: "failed" });
105 return err(refused(e));
106 }
107 });
108 }
109
110 /**
111 * Read the cluster once: `online` (recorded) or still `creating`; the provider's refusal otherwise.
112 */
113 export async function pollDatabase(app: App, actor: User | undefined, name: string): Promise<Result<"creating" | "online", string>> {
114 const who = admin(actor);
115 if (!who.ok) return who;
116 const row = databaseNamed(app.db, name);
117 if (row === undefined || row.remote === "") return err(`${name} has no cluster yet.`);
118 if (row.state === "online") return ok("online");
119 const call = callOf(app, who.value, row, "read");
120 if (!call.ok) return call;
121 try {
122 const c = await readCluster(call.value, row.remote);
123 if (c.status !== "online") return ok("creating");
124 setDatabase(app.db, name, { state: "online" });
125 return ok("online");
126 } catch (e) {
127 return err(refused(e));
128 }
129 }
130
131 /**
132 * Give the app the cluster's URL as one of its own secrets (`secret` on the row, DATABASE_URL by
133 * default), in the production environment only: a preview never holds the production database.
134 * Setting it redeploys the app so it starts holding it. The URL is read from the provider now, put
135 * in the app's sealed variables and nowhere else; the events name the secret, never its value.
136 */
137 export async function bindDatabase(app: App, actor: User | undefined, name: string): Promise<Result<string, string>> {
138 const who = admin(actor);
139 if (!who.ok) return who;
140 const row = databaseNamed(app.db, name);
141 if (row === undefined || row.remote === "") return err(`${name} has no cluster yet.`);
142 const call = callOf(app, who.value, row, "bind");
143 if (!call.ok) return call;
144 let uri: string;
145 try {
146 uri = (await readCluster(call.value, row.remote)).uri;
147 } catch (e) {
148 return err(refused(e));
149 }
150 if (uri === "") return err(`${name} is not online yet, so it has no URL to give ${row.app}.`);
151 const [owner = "", repoName = ""] = row.app.split("/");
152 const repo = getRepo(app.db, owner, repoName);
153 if (repo === undefined) return err(`${row.app} is not an app on this forge.`);
154 const put = await setAppEnvVar(app, who.value, repo, row.secret, uri, "production", "secret");
155 if (!put.ok) return err(put.error === "not_found" ? `${row.app} is not an app on this forge.` : `${row.secret} cannot be set on ${row.app}: ${put.error}.`);
156 setDatabase(app.db, name, { boundAt: new Date().toISOString() });
157 app.bus.append({ kind: "database.bound", actorId: who.value.id, payload: { name, app: row.app, secret: row.secret } });
158 return ok(row.secret);
159 }
src/actions/infra.ts +109 −11
@@ -16,7 +16,9 @@
1616 import type { App } from "../app.ts";
1717 import { billingSentence, billsOf, existsAtProvider, type Bills } from "../cloud/billing.ts";
1818 import { experiments, type Experiments } from "../cloud/experiments.ts";
19 import { apply, DNS_BY_HAND, plan, readInfra, type MachineWant, type Plan, type Reads, type Refusal } from "../cloud/plan.ts";
19 import { apply, DNS_BY_HAND, plan, readInfra, type DatabaseWant, type MachineWant, type Plan, type Reads, type Refusal, type Want } from "../cloud/plan.ts";
20 import { DATABASE_SIZES, databaseCents, databaseShape, DEFAULT_DATABASE_SIZE } from "../cloud/database.ts";
21 import { DATABASE_NAME, DEFAULT_SECRET, listDatabases } from "../core/managed_database.ts";
2022 import { keptPlaces } from "../cloud/places_read.ts";
2123 import { dollars } from "../cloud/prices.ts";
2224 import { LABEL, isProvider } from "../cloud/providers.ts";
@@ -78,6 +80,22 @@ export interface Running {
7880 readonly game?: true;
7981 }
8082
83 /** One managed Postgres database, as every door shows it. */
84 export interface Database {
85 readonly name: string;
86 readonly account: string;
87 readonly app: string;
88 /** Where and what, in plain words: "nyc1 · 1 vCPU, 1 GB". */
89 readonly where: string;
90 readonly monthlyCents: number;
91 readonly state: "creating" | "online" | "failed";
92 /** The app secret its URL is given as, and whether it was. */
93 readonly secret: string;
94 readonly bound: boolean;
95 /** One sentence: "online; its URL is the secret DATABASE_URL of alice/shop". */
96 readonly says: string;
97 }
98
8199 /** What a group of machines is for: an experiment's question, or the app they run. */
82100 export interface Purpose {
83101 readonly kind: "experiment" | "app";
@@ -100,6 +118,8 @@ export interface InfraView {
100118 readonly meters: readonly Meter[];
101119 readonly drift: readonly Drift[];
102120 readonly groups: readonly Purpose[];
121 /** The managed databases the forge made, with what each costs and how far it is. */
122 readonly databases: readonly Database[];
103123 /**
104124 * Every retired machine, newest first, each saying what it still bills: its kept disk, or nothing
105125 * left. Kept so "does test1 still cost anything?" is answered from a row, never from an absence.
@@ -230,11 +250,27 @@ function reckon(app: App, now: Date): { view: InfraView; rows: Map<string, Runni
230250 .sort((a, b) =>
231251 a.kind === b.kind ? b.monthlyCents - a.monthlyCents || a.title.localeCompare(b.title) : a.kind === "experiment" ? -1 : 1,
232252 );
253 const databases = listDatabases(db).map((d): Database => {
254 const size = DATABASE_SIZES.find((x) => x.slug === d.size);
255 const bound = d.boundAt !== "";
256 return {
257 name: d.name,
258 account: d.account,
259 app: d.app,
260 where: `${d.region} · ${size === undefined ? d.size : databaseShape(size)}`,
261 monthlyCents: d.remote !== "" || d.state === "creating" ? (databaseCents(d.size) ?? 0) : 0,
262 state: d.state,
263 secret: d.secret,
264 bound,
265 says: `${d.state}; ${bound ? `its URL is the secret ${d.secret} of ${d.app}` : `${d.app} has not been given its URL yet`}`,
266 };
267 });
233268 const makers = new Set<string>(TARGETS.filter((t) => t.status === "first").map((t) => t.id));
234269 const accounts = listCloudAccounts(db).filter((a) => makers.has(a.provider));
235270 // What each account costs: its rows' monthly cost, as the ceiling reckons them (`rowCents`).
236271 const spend = new Map<string, number>();
237272 for (const p of pinned) spend.set(`${p.target}/${p.account}`, (spend.get(`${p.target}/${p.account}`) ?? 0) + (cents.get(p.name) ?? 0));
273 for (const d of databases) spend.set(d.account, (spend.get(d.account) ?? 0) + d.monthlyCents);
238274 const meters = accounts
239275 .map((a): Meter => {
240276 const account = `${a.provider}/${a.name}`;
@@ -260,7 +296,7 @@ function reckon(app: App, now: Date): { view: InfraView; rows: Map<string, Runni
260296 return [{ account, says: `At ${LABEL[a.provider]}, not in your infrastructure: ${what}`, href: accountHref(account) }];
261297 });
262298 ended.sort((a, b) => (retiredAt.get(b.name) ?? "").localeCompare(retiredAt.get(a.name) ?? "") || a.name.localeCompare(b.name));
263 return { view: { meters, drift, groups: ordered, ended, endedEarlier, experiments: x, snapshots: listSnapshots(db).map(snapshotView), snapshotsHidden: Math.max(0, countSnapshots(db) - 200) }, rows };
299 return { view: { meters, drift, groups: ordered, databases, ended, endedEarlier, experiments: x, snapshots: listSnapshots(db).map(snapshotView), snapshotsHidden: Math.max(0, countSnapshots(db) - 200) }, rows };
264300 }
265301
266302 /** Most names a group of `infraSays` lists before "and N more". */
@@ -278,9 +314,10 @@ export function infraSays(v: InfraView): string {
278314 const running = machines.filter((m) => m.clear === "");
279315 const dead = machines.filter((m) => m.clear !== "");
280316 const kept = v.snapshots.filter((x) => x.state === "ready");
281 const total = [...machines, ...v.ended].reduce((s, m) => s + m.monthlyCents, 0) + kept.reduce((s, x) => s + x.cents, 0);
317 const total = [...machines, ...v.ended, ...v.databases].reduce((s, m) => s + m.monthlyCents, 0) + kept.reduce((s, x) => s + x.cents, 0);
282318 return [
283319 `Running: ${running.length === 0 ? "none" : named(running.map((m) => `${m.name} (${m.billing})`))}.`,
320 v.databases.length === 0 ? "" : `Databases: ${named(v.databases.map((d) => `${d.name} (${d.says})`))}.`,
284321 dead.length === 0 ? "" : `Dead rows (nothing exists at the provider): ${named(dead.map((m) => m.name))}; clear them with \`plan\` and their names.`,
285322 v.ended.length === 0 ? "" : `Ended in the last ${ENDED_DAYS} days: ${named(v.ended.map((m) => `${m.name} (${m.billing})`))}.`,
286323 v.endedEarlier === 0 ? "" : `${plural(v.endedEarlier, "machine")} ended earlier and bill nothing.`,
@@ -464,6 +501,66 @@ export function gameWant(g: { readonly name: string; readonly where: string; rea
464501 return ok({ kind: "machine", game: true, name: g.name, account, place, app: repo, source: "", ...(g.host ? { host: g.host } : {}) });
465502 }
466503
504 /** A managed database as every door sends it: plain strings, read by `databaseWantOf`. */
505 export interface DatabaseCompose {
506 readonly app: string;
507 /** `account@region`, as `DatabaseChoices.regions` lists. */
508 readonly where: string;
509 /** A size slug; empty is the smallest. */
510 readonly size: string;
511 /** Empty is a fresh name made from the app's. */
512 readonly name: string;
513 /** The app secret the URL goes in; empty is DATABASE_URL. */
514 readonly secret: string;
515 }
516
517 export interface DatabaseChoices {
518 /** Every app of this forge, `owner/name`. */
519 readonly apps: readonly string[];
520 /** `account@region` for each region of each writable DigitalOcean account. */
521 readonly regions: readonly { readonly value: string; readonly where: string }[];
522 readonly sizes: readonly { readonly slug: string; readonly shape: string; readonly costCents: number }[];
523 }
524
525 /**
526 * What a database can be composed from now: the apps, the regions of the writable DigitalOcean
527 * accounts, the sizes and their prices.
528 */
529 export function databaseChoices(app: App): DatabaseChoices {
530 const db = app.db;
531 const apps = listApps(db)
532 .flatMap((a) => {
533 const repo = getRepoById(db, a.repoId);
534 return repo === undefined ? [] : [`${repo.ownerName}/${repo.name}`];
535 })
536 .sort();
537 const cities = new Map<string, string>();
538 for (const p of keptPlaces(db, keptRate(db, "EUR"))) if (p.provider === "digitalocean") cities.set(p.datacenter, p.city);
539 const regions = listCloudAccounts(db)
540 .filter((a) => a.provider === "digitalocean" && a.writeAllowed)
541 .flatMap((a) => [...cities].sort(([x], [y]) => x.localeCompare(y)).map(([region, city]) => ({ value: `digitalocean/${a.name}@${region}`, where: `${city} (${region}) on ${a.name}` })));
542 return { apps, regions, sizes: DATABASE_SIZES.map((s) => ({ slug: s.slug, shape: databaseShape(s), costCents: databaseCents(s.slug) ?? 0 })) };
543 }
544
545 /** The want a database compose describes, or what it still lacks in one sentence. */
546 export function databaseWantOf(c: DatabaseCompose): Result<DatabaseWant, string> {
547 const [account = "", region = ""] = c.where.split("@");
548 if (account === "" || region === "") return err("Pick where it runs: an account and a region.");
549 if (c.app === "") return err("Pick the app it is for.");
550 const name = c.name === "" ? nameFor(c.app) : c.name;
551 if (!DATABASE_NAME.test(name)) return err("A name is lowercase letters, digits and dashes, starting with a letter.");
552 return ok({ kind: "database", name, account, region, size: c.size === "" ? DEFAULT_DATABASE_SIZE : c.size, app: c.app, ...(c.secret === "" || c.secret === DEFAULT_SECRET ? {} : { secret: c.secret }) });
553 }
554
555 /** Plan a database compose against what exists now; nothing is made. */
556 export function planDatabase(app: App, actor: User | undefined, c: DatabaseCompose): Result<Planned, string> {
557 const who = admin(actor);
558 if (!who.ok) return who;
559 const want = databaseWantOf(c);
560 if (!want.ok) return ok({ plan: plan([], [], NOTHING), lacks: want.error, summary: "", fixes: [], needs: [] });
561 return planWants(app, actor, [want.value]);
562 }
563
467564 /** A plan with the sentences and links every door shows beside it. */
468565 export interface Planned {
469566 readonly plan: Plan;
@@ -494,6 +591,7 @@ export function summaryOf(p: Plan): string {
494591 const adds = [
495592 count("machine") > 0 ? `+ ${plural(count("machine"), "machine")}` : "",
496593 count("disk") > 0 ? `+ ${plural(count("disk"), "disk")}` : "",
594 count("database") > 0 ? `+ ${plural(count("database"), "database")}` : "",
497595 count("retire") > 0 ? `− ${plural(count("retire"), "machine")}` : "",
498596 count("clear") > 0 ? `clear ${plural(count("clear"), "dead row")}` : "",
499597 ]
@@ -513,7 +611,7 @@ const needOf = (says: string): { says: string; href: string; label: string } =>
513611 says === DNS_BY_HAND ? { says: "Its address needs a DNS record:", href: "/cloud/connect/cloudflare", label: "connect Cloudflare to have it written for you" } : { says, href: "", label: "" };
514612
515613 /** Where a refusal is fixed: the exact control (errors meet settings), or nothing to link. */
516 function fixOf(r: Refusal, wants: readonly MachineWant[]): { why: string; href: string; label: string } {
614 function fixOf(r: Refusal, wants: readonly Want[]): { why: string; href: string; label: string } {
517615 const account = wants.find((w) => w.name === r.name)?.account ?? "";
518616 const provider = account.split("/")[0] ?? "";
519617 const label = isProvider(provider) ? LABEL[provider] : account;
@@ -535,16 +633,16 @@ export async function planCompose(app: App, actor: User | undefined, c: Compose,
535633 const want = await wantOf(app, c, choices);
536634 // A compose that lacks something plans nothing, and reads nothing to do it.
537635 if (!want.ok) return ok({ plan: plan([], [], NOTHING), lacks: want.error, summary: "", fixes: [], needs: [] });
538 const { have, reads } = readInfra(app);
539 return ok(planned(app, plan([want.value], have, reads)));
636 const { have, reads, databases } = readInfra(app);
637 return ok(planned(app, plan([want.value], have, reads, { databases })));
540638 }
541639
542640 /** Plan wants as given (the API and MCP send them whole). */
543 export function planWants(app: App, actor: User | undefined, wants: readonly MachineWant[], complete = false, clears: readonly string[] = []): Result<Planned, string> {
641 export function planWants(app: App, actor: User | undefined, wants: readonly Want[], complete = false, clears: readonly string[] = []): Result<Planned, string> {
544642 const who = admin(actor);
545643 if (!who.ok) return who;
546 const { have, reads } = readInfra(app);
547 return ok(planned(app, plan(wants, have, reads, { complete, clears })));
644 const { have, reads, databases } = readInfra(app);
645 return ok(planned(app, plan(wants, have, reads, { complete, clears, databases })));
548646 }
549647
550648 function planned(app: App, p: Plan): Planned {
@@ -601,7 +699,7 @@ export interface Build {
601699 readonly state: "running" | "done" | "failed";
602700 /** Where what it built answers, once done. */
603701 readonly urls: readonly string[];
604 readonly wants: readonly MachineWant[];
702 readonly wants: readonly Want[];
605703 /** The dead rows the plan clears. */
606704 readonly clears: readonly string[];
607705 }
@@ -617,7 +715,7 @@ export function buildOf(app: App, actor: User | undefined, planId: string): Buil
617715 .all(planId);
618716 const start = rows.map((r) => r.kind).lastIndexOf("infra.applied");
619717 if (start < 0) return undefined;
620 const head = JSON.parse(rows[start]!.payload) as { steps: string[]; wants: MachineWant[]; clears?: string[]; summary?: string; etaSeconds?: number; needs?: string[] };
718 const head = JSON.parse(rows[start]!.payload) as { steps: string[]; wants: Want[]; clears?: string[]; summary?: string; etaSeconds?: number; needs?: string[] };
621719 const steps = head.steps.map((says, index) => ({ index, says, state: "waiting" as StepState, why: "" }));
622720 let refused = "";
623721 for (const r of rows.slice(start + 1)) {
src/cloud/ceiling.ts +12 −2
@@ -18,7 +18,9 @@
1818 import type { Database } from "bun:sqlite";
1919 import type { App } from "../app.ts";
2020 import { getCloudAccount } from "../core/cloud_account.ts";
21 import { listDatabases } from "../core/managed_database.ts";
2122 import { getPinned, listPinned, placeIdOf, type Pinned } from "../core/pinned.ts";
23 import { databaseCents } from "./database.ts";
2224 import type { Driver } from "./machine.ts";
2325 import { DO_VOLUME_USD_PER_GIB, OVH_VOLUME_USD_PER_GIB, VOLUME_GIB } from "./places.ts";
2426 import { keptPlaces } from "./places_read.ts";
@@ -123,11 +125,19 @@ export function rowCents(p: Row, prices: Priced): number {
123125 return prices.forge(placeIdOf(p)) ?? unlisted() ?? 0;
124126 }
125127
126 /** What the forge reckons an account costs a month, in cents: the sum over its own pinned rows. */
128 /**
129 * What the forge reckons an account costs a month, in cents: the sum over its own pinned rows and
130 * its managed databases. A database counts from the moment its row is written (it is about to be
131 * one) at its size's list price; one that failed before a cluster was made costs nothing.
132 */
127133 export function accountCents(db: Database, provider: string, account: string, prices: Priced = priced(db)): number {
128 return listPinned(db)
134 const machines = listPinned(db)
129135 .filter((p) => p.target === provider && p.account === account)
130136 .reduce((sum, p) => sum + rowCents(p, prices), 0);
137 const databases = listDatabases(db)
138 .filter((d) => d.account === `${provider}/${account}` && (d.remote !== "" || d.state === "creating"))
139 .reduce((sum, d) => sum + (databaseCents(d.size) ?? 0), 0);
140 return machines + databases;
131141 }
132142
133143 export interface Spend {
src/cloud/database.ts added +87
@@ -0,0 +1,87 @@
1 /**
2 * Managed Postgres on DigitalOcean (#17074, phase 3 of #16696): the sizes it is sold in with their
3 * list prices, and the four calls the forge makes (DigitalOcean API v2): POST /databases, GET
4 * /databases?tag_name= and GET /databases/{id} (its status and connection URI). The sequence is the
5 * infrastructure plan's (`plan.ts`); the caller owns the token and the fetch (`machine.ts`'s
6 * `Call`).
7 *
8 * Prices: DigitalOcean's databases API lists sizes and regions but no price, so the list prices for
9 * one-node Postgres clusters are held here, in US dollars a month, as published at
10 * digitalocean.com/pricing/managed-databases. The ceiling counts them like any other price (rounded
11 * up, since the figure guards spending); the provider's bill is the truth.
12 */
13
14 import { forgeTag, type Call } from "./machine.ts";
15 import { toUsd } from "./prices.ts";
16
17 export interface DatabaseSize {
18 readonly slug: string;
19 readonly vcpus: number;
20 readonly gib: number;
21 /** List price a month for one node, US dollars. */
22 readonly usd: number;
23 }
24
25 export const DATABASE_SIZES: readonly DatabaseSize[] = [
26 { slug: "db-s-1vcpu-1gb", vcpus: 1, gib: 1, usd: 15 },
27 { slug: "db-s-1vcpu-2gb", vcpus: 1, gib: 2, usd: 30 },
28 { slug: "db-s-2vcpu-4gb", vcpus: 2, gib: 4, usd: 60 },
29 { slug: "db-s-4vcpu-8gb", vcpus: 4, gib: 8, usd: 120 },
30 ];
31
32 export const DEFAULT_DATABASE_SIZE = "db-s-1vcpu-1gb";
33
34 /** A DigitalOcean region slug (`nyc1`, `fra1`). */
35 export const REGION = /^[a-z]{3}[0-9]$/;
36
37 export const sizeOf = (slug: string): DatabaseSize | undefined => DATABASE_SIZES.find((s) => s.slug === slug);
38
39 /**
40 * What a size costs a month, US cents rounded up; undefined for a size the forge has no price for.
41 */
42 export const databaseCents = (slug: string): number | undefined => {
43 const s = sizeOf(slug);
44 return s === undefined ? undefined : toUsd(s.usd, "USD", undefined, "up").usdCents;
45 };
46
47 /** "1 vCPU, 2 GB", as machines are worded. */
48 export const databaseShape = (s: DatabaseSize): string => `${s.vcpus} vCPU, ${s.gib} GB`;
49
50 /** The size slugs, for a refusal that names the choices. */
51 export const SIZE_SLUGS = DATABASE_SIZES.map((s) => s.slug).join(", ");
52
53 const ID = /^[A-Za-z0-9-]{1,64}$/;
54
55 /** Where a cluster is, as the provider reports it. */
56 export interface Cluster {
57 readonly id: string;
58 /** `creating` until the provider says `online`. */
59 readonly status: string;
60 /** The connection URI, only once the cluster has one. */
61 readonly uri: string;
62 }
63
64 const clusterOf = (x: any): Cluster | undefined =>
65 typeof x?.id === "string" && ID.test(x.id)
66 ? { id: x.id, status: String(x.status ?? ""), uri: typeof x?.connection?.uri === "string" ? x.connection.uri : "" }
67 : undefined;
68
69 /** The cluster the forge already made for `name`, if any: a retried create never makes a second. */
70 export async function findCluster(call: Call, name: string): Promise<Cluster | undefined> {
71 const all: unknown[] = (await call("GET", `/databases?tag_name=${encodeURIComponent(forgeTag(name))}`)).databases ?? [];
72 return all.map(clusterOf).find((c) => c !== undefined);
73 }
74
75 /** Ask for a one-node Postgres cluster, tagged with the forge's name for it. */
76 export async function createCluster(call: Call, d: { name: string; region: string; size: string }): Promise<string> {
77 const made = clusterOf((await call("POST", "/databases", { name: `forge-${d.name}`, engine: "pg", version: "16", region: d.region, size: d.size, num_nodes: 1, tags: [forgeTag(d.name)] })).database);
78 if (made === undefined) throw new Error("DigitalOcean answered without a cluster id");
79 return made.id;
80 }
81
82 /** Read a cluster back: its status and, once online, its connection URI. */
83 export async function readCluster(call: Call, id: string): Promise<Cluster> {
84 const c = clusterOf((await call("GET", `/databases/${encodeURIComponent(id)}`)).database);
85 if (c === undefined) throw new Error("DigitalOcean answered without that cluster");
86 return c;
87 }
src/cloud/plan.ts +207 −12
@@ -19,14 +19,19 @@
1919 * exists. The forge has no generic job queue (timers call apps over HTTP), so this is the job: the
2020 * plan is the intent, reality is the progress, the outbox is the record.
2121 *
22 * Kinds: a machine with its disk is the one there is. `Want` and `Have` are unions on `kind`, so a
23 * firewall, a DNS record or a bucket is one more member with its own steps and refusals.
22 * Kinds: a machine with its disk, and a managed Postgres database (#17074) bound to an app. `Want`
23 * is a union on `kind`, so a firewall, a DNS record or a bucket is one more member with its own
24 * steps and refusals. A database's want and what exists of it (`DatabaseHave`) travel beside the
25 * machines', in `plan`'s options and `Reads.database`, so the machine plan is untouched by them.
2426 */
2527
2628 import type { App } from "../app.ts";
2729 import { clearPinned, deployPinned, LIFETIME_DAYS, LIFETIME_WORDS, MAX_LIFETIME_DAYS, retirePinned } from "../actions/pinned.ts";
2830 import { stuckWords, WATCH } from "../actions/pinned_watch.ts";
31 import { bindDatabase, createDatabase, ONLY_DIGITALOCEAN, pollDatabase } from "../actions/database.ts";
32 import { getRepo } from "../core/repos.ts";
2933 import { getCloudAccount, listCloudAccounts, NO_ACCOUNT, READ_ONLY } from "../core/cloud_account.ts";
34 import { DATABASE_NAME, DEFAULT_SECRET, databaseNamed, listDatabases } from "../core/managed_database.ts";
3035 import { dnsOf, getPinned, HOST_NEEDED, listPinned, NAME_TAKEN, placeIdOf, type Pinned } from "../core/pinned.ts";
3136 import { watchOf } from "../core/pinned_watch.ts";
3237 import type { User } from "../core/users.ts";
@@ -34,6 +39,8 @@ import { err, ok, type Result } from "../kernel/result.ts";
3439 import { getBaseDomain } from "../settings/pinned_domain.ts";
3540 import { accountCents, priced, refusalOf, rowCents } from "./ceiling.ts";
3641 import { attachMachine, beginExperiment, EXPERIMENT_WORDS, experiments } from "./experiments.ts";
42 import { isAppEnvName, isReservedAppEnvName } from "../core/app_env.ts";
43 import { databaseCents, databaseShape, REGION, SIZE_SLUGS, sizeOf } from "./database.ts";
3744 import { keptPlaces } from "./places_read.ts";
3845 import { shapeWords, VOLUME_GIB } from "./places.ts";
3946 import { keptRate } from "./rates.ts";
@@ -76,7 +83,24 @@ export interface MachineWant {
7683 readonly game?: boolean | undefined;
7784 }
7885
79 export type Want = MachineWant;
86 /** A managed Postgres cluster on a DigitalOcean account, its URL given to an app as a secret. */
87 export interface DatabaseWant {
88 readonly kind: "database";
89 /** The database's name, which is its identity: one resource a name. */
90 readonly name: string;
91 /** The cloud account it is made on, `digitalocean/name`. */
92 readonly account: string;
93 /** The provider's region slug, `nyc1`. */
94 readonly region: string;
95 /** The provider's size slug, `db-s-1vcpu-1gb`. */
96 readonly size: string;
97 /** The app it is bound to, `owner/name`: it is given the URL. */
98 readonly app: string;
99 /** The app secret the URL is put in; absent is `DATABASE_URL`. */
100 readonly secret?: string | undefined;
101 }
102
103 export type Want = MachineWant | DatabaseWant;
80104
81105 /** A machine the forge made (a pinned row), as the plan needs it. */
82106 export interface MachineHave {
@@ -105,6 +129,28 @@ export interface MachineHave {
105129
106130 export type Have = MachineHave;
107131
132 /** A database the forge made (a `managed_database` row), as the plan needs it. */
133 export interface DatabaseHave {
134 readonly name: string;
135 readonly account: string;
136 readonly region: string;
137 readonly size: string;
138 readonly app: string;
139 readonly secret: string;
140 /** What exists of it: the cluster at the provider, online, its URL given to the app. */
141 readonly made: boolean;
142 readonly online: boolean;
143 readonly bound: boolean;
144 /** What it costs a month now, US cents. */
145 readonly cents: number;
146 }
147
148 /** What the forge holds about databases, handed to `plan`. */
149 export interface DatabaseReads {
150 /** Whether `owner/name` is an app on this forge. */
151 app(app: string): boolean;
152 }
153
108154 /** One cloud account as the plan reads it. */
109155 export interface AccountRead {
110156 readonly writable: boolean;
@@ -131,9 +177,11 @@ export interface Reads {
131177 where(place: string): { readonly city: string; readonly shape: string } | undefined;
132178 /** Undefined for no such experiment. */
133179 experiment(id: string): { readonly state: "running" | "done"; readonly question: string } | undefined;
180 /** What a database want needs read; absent, no database can be planned. */
181 readonly database?: DatabaseReads | undefined;
134182 }
135183
136 export type StepKind = "disk" | "machine" | "attach" | "dns" | "ready" | "address" | "retire" | "clear";
184 export type StepKind = "disk" | "machine" | "attach" | "dns" | "ready" | "address" | "retire" | "clear" | "database" | "online" | "bind";
137185
138186 export interface Step {
139187 readonly index: number;
@@ -193,6 +241,8 @@ export interface Plan {
193241 */
194242 const BOOT_SECONDS: Readonly<Record<string, number>> = { digitalocean: 240, hetzner: 240, ovh: 300 };
195243 const BOOT_DEFAULT = 300;
244 /** Seconds from asking DigitalOcean for a Postgres cluster until it is online. */
245 const DATABASE_SECONDS = 420;
196246 /** Seconds until a new machine has a public address, when that is all the plan waits for. */
197247 const ADDRESS_SECONDS = 60;
198248 /** The sentence of a DNS record the forge cannot write. */
@@ -201,6 +251,9 @@ export const DNS_BY_HAND = "Its address needs a DNS record: connect Cloudflare t
201251 const CALL_SECONDS = 20;
202252 const RETIRE_SECONDS = 30;
203253
254 const DATABASE_NAME_WORDS = "A database's name is lowercase letters, digits and dashes, starting with a letter.";
255 const SECRET_NAME_WORDS = "A secret's name is capital letters, digits and underscores, starting with a letter, and not one the forge sets itself.";
256
204257 const providerOf = (account: string): string => account.slice(0, Math.max(0, account.indexOf("/")));
205258 const partsOf = (place: string): { provider: string; datacenter: string; size: string } => {
206259 const [provider = "", datacenter = "", size = ""] = place.split(":");
@@ -225,7 +278,12 @@ const same = (w: MachineWant, h: MachineHave): boolean =>
225278 * data stays the typed-name confirm on its own page). Creates come before retires, and the
226279 * ceiling is checked on the creates without the retires' savings, as the deploy itself will.
227280 */
228 export function plan(wants: readonly Want[], have: readonly Have[], reads: Reads, o: { complete?: boolean; clears?: readonly string[] } = {}): Plan {
281 export function plan(
282 wants: readonly Want[],
283 have: readonly Have[],
284 reads: Reads,
285 o: { complete?: boolean; clears?: readonly string[]; databases?: readonly DatabaseHave[] } = {},
286 ): Plan {
229287 const complete = o.complete === true;
230288 const clears = [...new Set(o.clears ?? [])];
231289 const byName = new Map(have.map((h) => [h.name, h]));
@@ -254,6 +312,66 @@ export function plan(wants: readonly Want[], have: readonly Have[], reads: Reads
254312 if (l) l.refused = true;
255313 };
256314 const step = (list: Step[], s: Omit<Step, "index">) => list.push({ ...s, index: 0 });
315 const haveDb = new Map((o.databases ?? []).map((d) => [d.name, d]));
316
317 /**
318 * A database: made at the provider, online, then its URL given to its app, each only where it is
319 * not already so.
320 */
321 const wantDatabase = (w: DatabaseWant): void => {
322 const a = reads.account(w.account);
323 if (a === undefined) return refuse(w.name, NO_ACCOUNT);
324 const l = ledger(w.account, a);
325 const secret = w.secret ?? DEFAULT_SECRET;
326 // A database and a machine share one namespace of names.
327 if (byName.has(w.name)) return refuse(w.name, NAME_TAKEN, w.account);
328 const h = haveDb.get(w.name);
329 if (h !== undefined && (h.account !== w.account || h.region !== w.region || h.size !== w.size || h.app !== w.app || h.secret !== secret))
330 return refuse(w.name, NAME_TAKEN, w.account);
331 if (!DATABASE_NAME.test(w.name)) return refuse(w.name, DATABASE_NAME_WORDS, w.account);
332 const provider = providerOf(w.account);
333 if (provider !== "digitalocean") return refuse(w.name, ONLY_DIGITALOCEAN, w.account);
334 if (!a.writable) return refuse(w.name, READ_ONLY, w.account);
335 if (!REGION.test(w.region)) return refuse(w.name, `${w.region === "" ? "No region" : w.region} is not a DigitalOcean region: name one like nyc1.`, w.account);
336 const size = sizeOf(w.size);
337 if (size === undefined) return refuse(w.name, `No managed Postgres size ${w.size || "was named"}: choose one of ${SIZE_SLUGS}.`, w.account);
338 if (!isAppEnvName(secret) || isReservedAppEnvName(secret)) return refuse(w.name, SECRET_NAME_WORDS, w.account);
339 if (reads.database?.app(w.app) !== true) return refuse(w.name, `${w.app} is not an app on this forge, so it cannot be given a database.`, w.account);
340 if (h === undefined || !h.made) {
341 const price = databaseCents(w.size);
342 const counted = h?.cents ?? 0;
343 const no = refusalOf({
344 provider,
345 account: w.account.slice(provider.length + 1),
346 place: { id: `${provider}:${w.region}:${w.size}`, size: w.size, datacenter: w.region },
347 orphan: a.orphan,
348 price,
349 closed: undefined,
350 ceilingDollars: a.ceilingDollars,
351 monthlyCents: a.monthlyCents,
352 counted,
353 held: l.held,
354 });
355 const add = price === undefined ? 0 : Math.max(0, price - counted);
356 l.after += add;
357 if (no !== undefined) return refuse(w.name, no, w.account);
358 l.held += add;
359 step(creates, {
360 kind: "database",
361 name: w.name,
362 account: w.account,
363 cents: add,
364 says: `Create a managed Postgres (${databaseShape(size)}) in ${w.region}`,
365 });
366 calls += 1;
367 }
368 if (h?.online !== true) {
369 step(waits, { kind: "online", name: w.name, account: w.account, says: `Wait until ${w.name} is online`, cents: 0 });
370 boots.push(DATABASE_SECONDS);
371 }
372 if (h?.bound !== true)
373 step(waits, { kind: "bind", name: w.name, account: w.account, says: `Give ${w.app} its URL as the secret ${secret}`, cents: 0 });
374 };
257375
258376 for (const w of wants) {
259377 if (seen.has(w.name)) {
@@ -261,6 +379,10 @@ export function plan(wants: readonly Want[], have: readonly Have[], reads: Reads
261379 continue;
262380 }
263381 seen.add(w.name);
382 if (w.kind === "database") {
383 wantDatabase(w);
384 continue;
385 }
264386 const h = byName.get(w.name);
265387 const a = reads.account(w.account);
266388 if (a === undefined) {
@@ -473,6 +595,8 @@ export interface Hands {
473595 /** The same wants planned again against what stands now. */
474596 replan(p: Plan): Plan;
475597 deploy(w: MachineWant): Promise<Result<unknown, string>>;
598 /** What a database want's steps do; absent, a plan with databases is not built here. */
599 readonly database?: DatabaseHands | undefined;
476600 retire(name: string): Promise<Result<unknown, string>>;
477601 /** Clear a dead row: failed, nothing at its provider. */
478602 clear(name: string): Result<unknown, string>;
@@ -484,6 +608,17 @@ export interface Hands {
484608 now(): number;
485609 }
486610
611 /** What `apply` does to the world for a database. */
612 export interface DatabaseHands {
613 create(w: DatabaseWant): Promise<Result<unknown, string>>;
614 /** One read of the cluster: online, or still being made. */
615 poll(name: string): Promise<Result<"creating" | "online", string>>;
616 /** Give the app the cluster's URL as its secret. */
617 bind(name: string): Promise<Result<unknown, string>>;
618 /** What exists of it now; undefined when there is no row. */
619 facts(name: string): { readonly made: boolean; readonly online: boolean; readonly bound: boolean } | undefined;
620 }
621
487622 export interface Applied {
488623 readonly planId: string;
489624 /** Steps this run did, and those it found done already. */
@@ -496,7 +631,13 @@ export interface Applied {
496631 /** How long `apply` waits on the watch for DNS and an answer before it fails the step. */
497632 const waitBoundMs = (): number => WATCH.boundMs + 2 * WATCH.everyMs;
498633
499 const doneBy = (s: Step, w: Want | undefined, f: Facts | undefined): boolean => {
634 /** How long `apply` waits for a new cluster to come online before it stops the step. */
635 const DATABASE_WAIT_MS = 20 * 60_000;
636
637 const doneByDatabase = (s: Step, f: { readonly made: boolean; readonly online: boolean; readonly bound: boolean } | undefined): boolean =>
638 f !== undefined && (s.kind === "database" ? f.made : s.kind === "online" ? f.online : f.bound);
639
640 const doneBy = (s: Step, w: MachineWant | undefined, f: Facts | undefined): boolean => {
500641 if (s.kind === "retire") return f === undefined || f.state === "retired";
501642 if (s.kind === "clear") return f === undefined;
502643 if (f === undefined) return false;
@@ -513,6 +654,10 @@ const doneBy = (s: Step, w: Want | undefined, f: Facts | undefined): boolean =>
513654 return f.answered;
514655 case "address":
515656 return f.address || f.answered;
657 case "database":
658 case "online":
659 case "bind":
660 return false; // a database's steps are read from its own facts (`doneByDatabase`)
516661 }
517662 };
518663
@@ -542,12 +687,14 @@ export async function apply(
542687 `${dearer.account} would cost ${dollars(dearer.afterCents)} a month after this, more than the plan showed (${dollars(shown.get(dearer.account) ?? dearer.beforeCents)}); nothing was built. Look at the plan again.`,
543688 );
544689
545 const wants = new Map(p.wants.map((w) => [w.name, w]));
690 const wants = new Map(p.wants.flatMap((w) => (w.kind === "machine" ? [[w.name, w] as const] : [])));
691 const databases = new Map(p.wants.flatMap((w) => (w.kind === "database" ? [[w.name, w] as const] : [])));
692 const isDatabase = (s: Step): boolean => s.kind === "database" || s.kind === "online" || s.kind === "bind";
546693 const done: number[] = [];
547694 const skipped: number[] = [];
548695 const say = (s: Step, state: StepEvent["state"], why?: string) =>
549696 hands.emit({ planId: p.id, index: s.index, state, says: s.says, ...(why === undefined ? {} : { why }) });
550 const finished = (s: Step) => doneBy(s, wants.get(s.name), hands.facts(s.name));
697 const finished = (s: Step) => (isDatabase(s) ? doneByDatabase(s, hands.database?.facts(s.name)) : doneBy(s, wants.get(s.name), hands.facts(s.name)));
551698 const failed = (s: Step, why: string): Result<Applied, string> => {
552699 say(s, "failed", why);
553700 return ok({ planId: p.id, done, skipped, failed: { index: s.index, why } });
@@ -573,6 +720,30 @@ export async function apply(
573720 done.push(g.index);
574721 }
575722 i += group.length - 1;
723 } else if (isDatabase(s)) {
724 const dbh = hands.database;
725 if (dbh === undefined) return failed(s, "This forge cannot build databases.");
726 say(s, "started");
727 if (s.kind === "database") {
728 const r = await dbh.create(databases.get(s.name)!);
729 if (!r.ok) return failed(s, r.error);
730 } else if (s.kind === "online") {
731 const since = hands.now();
732 for (;;) {
733 const r = await dbh.poll(s.name);
734 if (!r.ok) return failed(s, r.error);
735 if (r.value === "online") break;
736 if (hands.now() - since >= DATABASE_WAIT_MS)
737 return failed(s, `${s.name} is not online after ${DATABASE_WAIT_MS / 60_000} minutes: build the plan again to keep waiting.`);
738 await hands.sleep();
739 }
740 } else {
741 const r = await dbh.bind(s.name);
742 if (!r.ok) return failed(s, r.error);
743 }
744 if (!finished(s)) return failed(s, `${s.name} is not ${s.kind === "database" ? "made" : s.kind === "online" ? "online" : "bound"} yet.`);
745 say(s, "done");
746 done.push(s.index);
576747 } else if (s.kind === "attach") {
577748 say(s, "started");
578749 const r = hands.join(wants.get(s.name)!);
@@ -633,7 +804,7 @@ export async function apply(
633804 }
634805
635806 /** What exists and what the forge holds, from its database, for `plan`. */
636 export function readInfra(app: App): { have: Have[]; reads: Reads } {
807 export function readInfra(app: App): { have: Have[]; reads: Reads; databases: DatabaseHave[] } {
637808 const db = app.db;
638809 const prices = priced(db);
639810 const exps = experiments(db).items;
@@ -659,6 +830,20 @@ export function readInfra(app: App): { have: Have[]; reads: Reads } {
659830 keptCents: rowCents({ ...p, state: "retired" }, prices),
660831 };
661832 });
833 const databases = listDatabases(db).map(
834 (d): DatabaseHave => ({
835 name: d.name,
836 account: d.account,
837 region: d.region,
838 size: d.size,
839 app: d.app,
840 secret: d.secret,
841 made: d.remote !== "",
842 online: d.state === "online",
843 bound: d.boundAt !== "",
844 cents: d.remote !== "" || d.state === "creating" ? (databaseCents(d.size) ?? 0) : 0,
845 }),
846 );
662847 const base = getBaseDomain(db);
663848 const places = new Map(keptPlaces(db, keptRate(db, "EUR")).map((p) => [p.id, p]));
664849 const reads: Reads = {
@@ -687,8 +872,9 @@ export function readInfra(app: App): { have: Have[]; reads: Reads } {
687872 const e = exps.find((x) => x.id === id);
688873 return e === undefined ? undefined : { state: e.state, question: e.question };
689874 },
875 database: { app: (name) => name.split("/").length === 2 && getRepo(db, name.split("/")[0]!, name.split("/")[1]!) !== undefined },
690876 };
691 return { have, reads };
877 return { have, reads, databases };
692878 }
693879
694880 function factsOf(app: App, p: Pinned, exps = experiments(app.db).items): Facts {
@@ -712,8 +898,17 @@ function factsOf(app: App, p: Pinned, exps = experiments(app.db).items): Facts {
712898 function handsOf(app: App, actor: User | undefined): Hands {
713899 return {
714900 replan: (p) => {
715 const { have, reads } = readInfra(app);
716 return plan(p.wants, have, reads, { complete: p.complete, clears: p.clears });
901 const { have, reads, databases } = readInfra(app);
902 return plan(p.wants, have, reads, { complete: p.complete, clears: p.clears, databases });
903 },
904 database: {
905 create: (w) => createDatabase(app, actor, { name: w.name, account: w.account, region: w.region, size: w.size, app: w.app, secret: w.secret ?? DEFAULT_SECRET }),
906 poll: (name) => pollDatabase(app, actor, name),
907 bind: (name) => bindDatabase(app, actor, name),
908 facts: (name) => {
909 const d = databaseNamed(app.db, name);
910 return d === undefined ? undefined : { made: d.remote !== "", online: d.state === "online", bound: d.boundAt !== "" };
911 },
717912 },
718913 deploy: (w) => {
719914 const provider = providerOf(w.account);
src/contract/openapi/routes/postApiV1AdminInfraPlan.ts +1 −1
@@ -4,7 +4,7 @@ export const route: Route = {
44 method: "post",
55 path: "/api/v1/admin/infra/plan",
66 summary: "Plan one more machine: its steps, cost against each ceiling, time to ready and refusals",
7 detail: "Takes `app`, `where` (`account@place`), `question` or `experiment`, `days` (or `none` for an app) and `name`; nothing is made",
7 detail: "Takes `app`, `where` (`account@place`), `question` or `experiment`, `days` (or `none` for an app) and `name`; or, with `database: true`, a managed Postgres database: `app` (its URL is given to it as a secret), `where` (`account@region`), `size`, `name`, `secret`; nothing is made",
88 auth: true,
99 role: "admin",
1010 refusals: {
src/core/event_audience.ts +2
@@ -328,6 +328,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
328328 kind.startsWith("pinned.") ||
329329 // What is built on the owner's own cloud, step by step, and what it costs (#16696).
330330 kind.startsWith("infra.") ||
331 // A managed database made and bound for an app names the owner's cloud account (#17074).
332 kind.startsWith("database.") ||
331333 // Which of a person's connected accounts a mirror syncs through is too.
332334 kind.startsWith("origin.") ||
333335 // A forge's plan and the billing provider are the admins' books (#11134).
src/core/managed_database.ts added +78
@@ -0,0 +1,78 @@
1 /**
2 * Managed databases (#17074): the rows of the clusters the forge made on a cloud account, and how
3 * far each got. Plain data in and out; the provider calls are `cloud/database.ts`, the sequence is
4 * the infrastructure plan's (`cloud/plan.ts`). A row is written before the provider is asked, so a
5 * run that stopped is finished by planning the same database again.
6 */
7
8 import type { Database } from "bun:sqlite";
9
10 /** A database's name: lowercase letters, digits and dashes, starting with a letter. */
11 export const DATABASE_NAME = /^[a-z][a-z0-9-]{0,39}$/;
12 /** The variable the app is given its URL as, unless the want names another. */
13 export const DEFAULT_SECRET = "DATABASE_URL";
14
15 export interface ManagedDatabase {
16 readonly name: string;
17 /** The cloud account, `provider/name`. */
18 readonly account: string;
19 readonly region: string;
20 readonly size: string;
21 /** The app it is bound to, `owner/name`. */
22 readonly app: string;
23 readonly secret: string;
24 /** The cluster's id at the provider; empty until it was made. */
25 readonly remote: string;
26 readonly state: "creating" | "online" | "failed";
27 /** When its URL was given to the app, ISO; empty until then. */
28 readonly boundAt: string;
29 readonly createdAt: string;
30 }
31
32 interface Row {
33 name: string;
34 account: string;
35 region: string;
36 size: string;
37 app: string;
38 secret: string;
39 remote: string;
40 state: ManagedDatabase["state"];
41 bound_at: string;
42 created_at: string;
43 }
44
45 const toDatabase = (r: Row): ManagedDatabase => ({
46 name: r.name,
47 account: r.account,
48 region: r.region,
49 size: r.size,
50 app: r.app,
51 secret: r.secret,
52 remote: r.remote,
53 state: r.state,
54 boundAt: r.bound_at,
55 createdAt: r.created_at,
56 });
57
58 export function databaseNamed(db: Database, name: string): ManagedDatabase | undefined {
59 const row = db.query<Row, [string]>("SELECT * FROM managed_database WHERE name = ?1").get(name);
60 return row === null ? undefined : toDatabase(row);
61 }
62
63 export const listDatabases = (db: Database): ManagedDatabase[] =>
64 db.query<Row, []>("SELECT * FROM managed_database ORDER BY created_at, name").all().map(toDatabase);
65
66 /** Record a database about to be made; a name already held keeps its row. */
67 export function insertDatabase(db: Database, d: Pick<ManagedDatabase, "name" | "account" | "region" | "size" | "app" | "secret">): void {
68 db.query(
69 "INSERT INTO managed_database (name, account, region, size, app, secret) VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT(name) DO UPDATE SET state = 'creating' WHERE state = 'failed' AND remote = ''",
70 ).run(d.name, d.account, d.region, d.size, d.app, d.secret);
71 }
72
73 /** Record how far a database got. */
74 export function setDatabase(db: Database, name: string, to: { remote?: string; state?: ManagedDatabase["state"]; boundAt?: string }): void {
75 db.query(
76 "UPDATE managed_database SET remote = COALESCE(?2, remote), state = COALESCE(?3, state), bound_at = COALESCE(?4, bound_at) WHERE name = ?1",
77 ).run(name, to.remote ?? null, to.state ?? null, to.boundAt ?? null);
78 }
src/core/migration-pins/20261201170000-managed-database.pin added +1
@@ -0,0 +1,1 @@
1 256956b9a6de66a57f7cbbfb5b35d47e3fa9b8719efc345890a79c840e83ada3
src/core/migrations/20261201170000-managed-database.ts added +18
@@ -0,0 +1,18 @@
1 // A managed database the forge made on a cloud account (#17074, phase 3 of #16696): one row a
2 // cluster, its account and place, the app it is bound to, and how far it got (made at the provider,
3 // online, its URL handed to the app). Additive: one table. The URL is never kept here; it goes to
4 // the app as a sealed secret.
5 export default `
6 CREATE TABLE managed_database (
7 name TEXT PRIMARY KEY,
8 account TEXT NOT NULL,
9 region TEXT NOT NULL,
10 size TEXT NOT NULL,
11 app TEXT NOT NULL,
12 secret TEXT NOT NULL DEFAULT 'DATABASE_URL',
13 remote TEXT NOT NULL DEFAULT '',
14 state TEXT NOT NULL DEFAULT 'creating' CHECK (state IN ('creating','online','failed')),
15 bound_at TEXT NOT NULL DEFAULT '',
16 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
17 );
18 `;
src/generated/migrations.ts +2
@@ -450,6 +450,7 @@ import m445 from "../core/migrations/20261201130000-game-box-boot.ts";
450450 import m446 from "../core/migrations/20261201140000-app-registry-item.ts";
451451 import m447 from "../core/migrations/20261201140000-infra-snapshot.ts";
452452 import m448 from "../core/migrations/20261201140000-scan-finding-excerpt.ts";
453 import m449 from "../core/migrations/20261201170000-managed-database.ts";
453454
454455 /** Each migration file's name and its default export, in name order. */
455456 export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
@@ -902,4 +903,5 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
902903 ["20261201140000-app-registry-item.ts", m446],
903904 ["20261201140000-infra-snapshot.ts", m447],
904905 ["20261201140000-scan-finding-excerpt.ts", m448],
906 ["20261201170000-managed-database.ts", m449],
905907 ];
src/http/api/admin.ts +10 −1
@@ -25,7 +25,7 @@ import { changePlans, measuredPlans } from "../../actions/plans.ts";
2525 import { setAccountCeilings, setAccountGrant } from "../../actions/model_grant.ts";
2626 import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, keepPinned, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, claimPinned, deployPinned, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned } from "../../actions/pinned.ts";
2727 import { TARGETS } from "../../cloud/targets.ts";
28 import { buildOf, infraOf, nameFor, planById, planCompose, startBuild } from "../../actions/infra.ts";
28 import { buildOf, infraOf, nameFor, planById, planCompose, planDatabase, startBuild } from "../../actions/infra.ts";
2929 import { changeQuotas, readQuotas } from "../../actions/quotas.ts";
3030 import { allowRequest, declineRequest, listRequests } from "../../actions/requests.ts";
3131 import { setRole } from "../../actions/roles.ts";
@@ -149,6 +149,15 @@ export function adminRoutes(router: Router<Handler>): void {
149149 if (denied) return denied;
150150 const i = await body(ctx.request);
151151 const app = str(i.app).slice(0, 140);
152 // A managed Postgres database (#17074): `where` is `account@region`, the URL goes to `app` as a
153 // secret.
154 if (i.database === true) {
155 const made = planDatabase(ctx.app, ctx.auth.user, { app, where: str(i.where).slice(0, 260), size: str(i.size).slice(0, 40), name: str(i.name).slice(0, 40), secret: str(i.secret).slice(0, 128) });
156 if (!made.ok) return pinnedFail(made.error);
157 if (made.value.lacks !== "") return apiError("refused", 422, made.value.lacks);
158 const d = made.value;
159 return json({ id: d.plan.id, summary: d.summary, steps: d.plan.steps, refusals: d.fixes, byAccount: d.plan.byAccount, deltaCents: d.plan.deltaCents, etaSeconds: d.plan.etaSeconds });
160 }
152161 const question = str(i.question).slice(0, 300);
153162 const experiment = str(i.experiment).slice(0, 60);
154163 const planned = await planCompose(ctx.app, ctx.auth.user, {
src/http/mcp/tools/infra.ts +10 −2
@@ -1,4 +1,4 @@
1 import { buildOf, gameWant, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts";
1 import { buildOf, gameWant, planDatabase, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts";
22 import { bindBucket, readBucket } from "../../../actions/bucket.ts";
33 import { endsWords, keepPinned } from "../../../actions/pinned.ts";
44 import { EXPERIMENT_WORDS, attachMachine, beginExperiment, findExperiment, recordResult } from "../../../cloud/experiments.ts";
@@ -15,7 +15,7 @@ const s = (v: unknown, max: number): string => str(v).slice(0, max);
1515 export const tool: Tool = {
1616 name: "infra",
1717 listedTo: "admin",
18 doc: "`{ action, id?, want?, question?, names?, result?, bucket? }`: `list`, `show` an `id`, `plan` a `want` `{app, where, question?, experiment?, days?}` or a game box `{game: true, where, name?, repo?, host?}` or dead `names`, `apply` its `id`, `keep`, `begin`, `attach`, `record_result`; `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.",
18 doc: "`{ action, id?, want?, question?, names?, result?, bucket? }`: `list` (its `says` names every machine), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a game box `{game: true, where, name?, repo?, host?}` or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `keep`, `begin`, `attach`, `record_result`; `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.",
1919 description: "Machines and spend.",
2020 inputSchema: {
2121 type: "object",
@@ -68,6 +68,14 @@ export const tool: Tool = {
6868 }
6969 if (action === "plan") {
7070 const w = (typeof args["want"] === "object" && args["want"] !== null ? args["want"] : {}) as Record<string, unknown>;
71 // A managed Postgres database (#17074): its URL becomes the app's secret once it is online.
72 if (w["database"] === true) {
73 const planned = planDatabase(ctx.app, user, { app: s(w["app"], 140), where: s(w["where"], 260), size: s(w["size"], 40), name: s(w["name"], 40), secret: s(w["secret"], 128) });
74 if (!planned.ok) return bad("not_found", "no such tool here");
75 const p = planned.value;
76 if (p.lacks !== "") return bad("incomplete", p.lacks);
77 return good({ id: p.plan.id, says: p.summary, steps: p.plan.steps.map((x) => x.says), refusals: p.fixes, byAccount: p.plan.byAccount, deltaCents: p.plan.deltaCents, etaSeconds: p.plan.etaSeconds });
78 }
7179 // A game box: Docker and the game agent on the owner's cloud, running a compose file.
7280 if (w["game"] === true) {
7381 const want = gameWant({ name: s(w["name"], 40) || nameFor(s(w["repo"], 140) || "trevato/game"), where: s(w["where"], 260), repo: s(w["repo"], 140), host: s(w["host"], 253) });
src/tui/screens/infra.ts +94 −31
@@ -4,11 +4,13 @@
44 * and when it ends. `n` composes one more (an app, a place, a reason, how long), shows the plan
55 * the page's tray shows (the one line, each step, every refusal) and builds it only on Build; the
66 * build's steps then lead the list as their `infra.step` events arrive. `+` keeps the selected
7 * machine 7 more days, `x` ends it now after a confirm. All through `actions/infra.ts` and
8 * `actions/pinned.ts`, as the page, the API and the `infra` tool do. Anyone else sees nothing.
7 * machine 7 more days, `x` ends it now after a confirm, `b` composes a managed Postgres database
8 * for an app (an app, a region, a size) and plans it the same way (#17074). All through
9 * `actions/infra.ts` and `actions/pinned.ts`, as the page, the API and the `infra` tool do. Anyone
10 * else sees nothing.
911 */
1012
11 import { buildOf, composeChoices, infraOf, nameFor, planCompose, startBuild, type Compose, type Running } from "../../actions/infra.ts";
13 import { buildOf, composeChoices, databaseChoices, infraOf, nameFor, planCompose, planDatabase, startBuild, type Compose, type Planned, type Running } from "../../actions/infra.ts";
1214 import { deleteSnapshot, endWithSnapshot, restoredName, restoreSnapshot } from "../../actions/infra_snapshot.ts";
1315 import { LIFETIME_DAYS, clearPinned, endsWords, keepPinned, retirePinned, retireWords } from "../../actions/pinned.ts";
1416 import type { SnapshotView } from "../../actions/infra_snapshot.ts";
@@ -44,6 +46,83 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
4446 return v.ok ? { ended: v.value.ended.length, snapshots: [...v.value.snapshots] } : { ended: 0, snapshots: [] };
4547 };
4648
49 /**
50 * The plan the page's tray shows: the one line, each step, every refusal, and Build only when it
51 * can.
52 */
53 const present = (parent: Screen, p: Planned): void => {
54 const ready = p.lacks === "" && p.plan.refusals.length === 0 && p.plan.steps.length > 0;
55 const body =
56 p.lacks !== ""
57 ? [p.lacks]
58 : [
59 p.summary,
60 "",
61 ...p.plan.steps.map((s) => ` ${s.says}`),
62 ...p.fixes.flatMap((x) => ["", x.why, ...(x.href === "" ? [] : [`${x.label}: ${x.href}`])]),
63 ...p.needs.flatMap((n) => ["", `${n.says} ${n.label}${n.href === "" ? "" : ` (${n.href})`}`]),
64 ];
65 ctx.push(
66 confirmScreen(ctx, parent, {
67 title: ready ? "The plan" : "Not yet",
68 body,
69 width: 96,
70 actions: ready ? [{ label: "Build" }, { label: "Cancel" }] : [{ label: "Close" }],
71 onChoose: (i) => {
72 if (!ready || i !== 0) return;
73 const started = startBuild(f.app, f.user, p.plan);
74 if (!started.ok) return say(started.error);
75 building = started.value;
76 say("Building: each step shows as it happens.");
77 },
78 }),
79 );
80 };
81
82 /**
83 * A managed Postgres database: the app that is given its URL, where, and how big; then the plan.
84 */
85 const composeDatabase = (parent: Screen): Screen => {
86 const c = databaseChoices(f.app);
87 if (c.apps.length === 0) {
88 say("No app to give a database to yet.");
89 return parent;
90 }
91 if (c.regions.length === 0) {
92 say("No DigitalOcean account can make a database: allow writes on one in Cloud accounts.");
93 return parent;
94 }
95 const draft = { app: "", where: "", size: "", name: "", secret: "" };
96 return pickerScreen(ctx, parent, {
97 title: "A database for",
98 items: c.apps.map((a) => ({ id: a, label: a })),
99 onPick: ([app = ""]) => {
100 draft.app = app;
101 void later(ctx, () =>
102 pickerScreen(ctx, parent, {
103 title: "Where",
104 items: c.regions.map((r) => ({ id: r.value, label: r.where })),
105 onPick: ([where = ""]) => {
106 draft.where = where;
107 void later(ctx, () =>
108 pickerScreen(ctx, parent, {
109 title: "Size",
110 items: c.sizes.map((z) => ({ id: z.slug, label: z.shape, hint: month(z.costCents) })),
111 onPick: ([size = ""]) => {
112 draft.size = size;
113 const planned = planDatabase(f.app, f.user, draft);
114 if (!planned.ok) return say(planned.error);
115 present(parent, planned.value);
116 },
117 }),
118 );
119 },
120 }),
121 );
122 },
123 });
124 };
125
47126 /** The compose, one question at a time; each answer narrows the next, and the plan comes last. */
48127 const compose = (parent: Screen): Screen => {
49128 const c = composeChoices(f.app);
@@ -68,33 +147,7 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
68147 const showPlan = async (): Promise<void> => {
69148 const planned = await planCompose(f.app, f.user, draft);
70149 if (!planned.ok) return say(planned.error);
71 const p = planned.value;
72 const ready = p.lacks === "" && p.plan.refusals.length === 0 && p.plan.steps.length > 0;
73 const body =
74 p.lacks !== ""
75 ? [p.lacks]
76 : [
77 p.summary,
78 "",
79 ...p.plan.steps.map((s) => ` ${s.says}`),
80 ...p.fixes.flatMap((x) => ["", x.why, ...(x.href === "" ? [] : [`${x.label}: ${x.href}`])]),
81 ...p.needs.flatMap((n) => ["", `${n.says} ${n.label}${n.href === "" ? "" : ` (${n.href})`}`]),
82 ];
83 ctx.push(
84 confirmScreen(ctx, parent, {
85 title: ready ? "The plan" : "Not yet",
86 body,
87 width: 96,
88 actions: ready ? [{ label: "Build" }, { label: "Cancel" }] : [{ label: "Close" }],
89 onChoose: (i) => {
90 if (!ready || i !== 0) return;
91 const started = startBuild(f.app, f.user, p.plan);
92 if (!started.ok) return say(started.error);
93 building = started.value;
94 say("Building: each step shows as it happens.");
95 },
96 }),
97 );
150 present(parent, planned.value);
98151 };
99152 const howLong = (): Screen =>
100153 pickerScreen(ctx, parent, {
@@ -159,6 +212,7 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
159212 keys: [
160213 binding(["j", "k"], "move cursor"),
161214 binding(["n"], "new"),
215 binding(["b"], "new database"),
162216 binding(["+"], `keep ${LIFETIME_DAYS} more days`),
163217 binding(["x"], "end now"),
164218 binding(["c"], "clear a dead row"),
@@ -182,6 +236,8 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
182236 "pinned.ended",
183237 "pinned.experiment_attached",
184238 "pinned.experiment_begun",
239 "database.created",
240 "database.bound",
185241 ],
186242 },
187243 () => ctx.invalidate(),
@@ -231,13 +287,15 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
231287 meta: m.account,
232288 })),
233289 ),
290 // A managed database: where it is, what it costs, and whether its app has the URL.
291 ...v.value.databases.map((d) => ({ title: `${d.name} · ${month(d.monthlyCents)}`, secondary: `database · ${d.app} · ${d.where} · ${d.says}`, meta: d.account })),
234292 // What ended: each retired machine says what it still bills, a kept disk or nothing left.
235293 ...v.value.ended.map((m) => ({ title: `ended: ${m.name} · ${month(m.monthlyCents)}`, secondary: `${m.name} is ${m.billing}`, meta: m.account })),
236294 ];
237295 rows.push(...v.value.snapshots.map((x) => ({ title: `snapshot: ${x.name} · ${x.state === "ready" && x.cents > 0 ? month(x.cents) : x.state}`, secondary: x.says, meta: `${x.target}/${x.account}` })));
238296 if (v.value.snapshotsHidden > 0) rows.push({ title: `${v.value.snapshotsHidden} older snapshots are not listed: only the newest 200 are shown`, meta: "" });
239297 if (rows.length === 0 && progress.length === 0)
240 rows.push({ title: "Nothing runs on your own cloud yet. Press n to build something.", meta: "" });
298 rows.push({ title: "Nothing runs on your own cloud yet. Press n to build something, b for a database.", meta: "" });
241299 drawList(s, list!, c, state, [...progress, ...rows]);
242300 },
243301 key(e) {
@@ -305,6 +363,11 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
305363 if (next !== screen) ctx.push(next);
306364 return true;
307365 }
366 if (e.key === "b") {
367 const next = composeDatabase(screen);
368 if (next !== screen) ctx.push(next);
369 return true;
370 }
308371 if (e.key !== "+" && e.key !== "x" && e.key !== "c") return false;
309372 const picked = all[state.index - progress - drift];
310373 if (picked === undefined) {
test/managed-database.test.ts added +324
@@ -0,0 +1,324 @@
1 /**
2 * Managed Postgres on DigitalOcean as an infra kind (#17074, phase 3 of #16696): the price read,
3 * the plan's steps and refusals (pure), and a build on a real forge against a recorded
4 * DigitalOcean:
5 * the cluster is made once, read until online, and its URL becomes the app's secret, never kept on
6 * a row or in an event; the ceiling counts it; every door that plans a database reads the same
7 * plan.
8 */
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts";
15 import { net } from "../src/actions/pinned.ts";
16 import { WATCH } from "../src/actions/pinned_watch.ts";
17 import { databaseChoices, databaseWantOf, infraOf, infraSays, planDatabase, summaryOf } from "../src/actions/infra.ts";
18 import { accountCents } from "../src/cloud/ceiling.ts";
19 import { databaseCents, DATABASE_SIZES } from "../src/cloud/database.ts";
20 import { apply, plan, readInfra, type DatabaseHave, type Have, type DatabaseWant, type Reads } from "../src/cloud/plan.ts";
21 import { NO_ACCOUNT, READ_ONLY } from "../src/core/cloud_account.ts";
22 import { databaseNamed } from "../src/core/managed_database.ts";
23 import { createApp as createAppRecord } from "../src/core/apps.ts";
24 import { createRepo } from "../src/core/repos.ts";
25 import { listAppEnvNames, resolveAppEnv } from "../src/core/app_env.ts";
26 import { createUser, getUserByName } from "../src/core/users.ts";
27 import { NAME_TAKEN } from "../src/core/pinned.ts";
28 import { Router } from "../src/http/router.ts";
29 import type { Handler } from "../src/http/context.ts";
30 import { adminRoutes } from "../src/http/api/admin.ts";
31 import { tool } from "../src/http/mcp/tools/infra.ts";
32 import { createForgeApp } from "../src/tui/forge.ts";
33 import { infraScreen } from "../src/tui/screens/infra.ts";
34 import { headlessTerminal } from "../src/tui/term/terminal.ts";
35 import { settleApp } from "./helpers/tui.ts";
36 import { quietLogs } from "./helpers/globals.ts";
37 import { seedPlaces } from "./helpers/places-fixture.ts";
38
39 quietLogs();
40
41 const URI = "postgresql://doadmin:[email protected]:25060/defaultdb?sslmode=require";
42
43 function reads(over: { writable?: boolean; ceilingDollars?: number; monthlyCents?: number; apps?: string[] } = {}): Reads {
44 return {
45 account: (a) =>
46 a === "digitalocean/main"
47 ? { writable: over.writable ?? true, ceilingDollars: over.ceilingDollars ?? 50, monthlyCents: over.monthlyCents ?? 0 }
48 : a === "hetzner/main"
49 ? { writable: true, ceilingDollars: 50, monthlyCents: 0 }
50 : undefined,
51 price: () => undefined,
52 closed: () => undefined,
53 host: () => "",
54 dnsAuto: true,
55 where: () => undefined,
56 experiment: () => undefined,
57 database: { app: (a) => (over.apps ?? ["alice/shop"]).includes(a) },
58 };
59 }
60 const want = (over: Partial<DatabaseWant> = {}): DatabaseWant => ({
61 kind: "database",
62 name: "shop-db",
63 account: "digitalocean/main",
64 region: "nyc1",
65 size: "db-s-1vcpu-1gb",
66 app: "alice/shop",
67 ...over,
68 });
69 const have = (over: Partial<DatabaseHave> = {}): DatabaseHave => ({
70 name: "shop-db",
71 account: "digitalocean/main",
72 region: "nyc1",
73 size: "db-s-1vcpu-1gb",
74 app: "alice/shop",
75 secret: "DATABASE_URL",
76 made: false,
77 online: false,
78 bound: false,
79 cents: 0,
80 ...over,
81 });
82 const why = (p: ReturnType<typeof plan>) => p.refusals.map((r) => r.why);
83
84 describe("the price read", () => {
85 test("each size has a list price in whole cents, and an unknown size has none", () => {
86 expect(databaseCents("db-s-1vcpu-1gb")).toBe(1500);
87 expect(databaseCents("db-s-4vcpu-8gb")).toBe(12000);
88 expect(databaseCents("db-s-99vcpu")).toBeUndefined();
89 expect(DATABASE_SIZES.map((s) => s.slug)).toContain("db-s-2vcpu-4gb");
90 });
91 });
92
93 describe("planning a database", () => {
94 test("makes it, waits for it, hands the app its URL, and says what it costs", () => {
95 const p = plan([want()], [], reads());
96 expect(p.refusals).toEqual([]);
97 expect(p.steps.map((s) => s.kind)).toEqual(["database", "online", "bind"]);
98 expect(p.steps[0]!.says).toBe("Create a managed Postgres (1 vCPU, 1 GB) in nyc1");
99 expect(p.steps[2]!.says).toBe("Give alice/shop its URL as the secret DATABASE_URL");
100 expect(p.deltaCents).toBe(1500);
101 expect(p.byAccount[0]).toMatchObject({ beforeCents: 0, afterCents: 1500, ceilingCents: 5000, fits: true });
102 expect(p.etaSeconds).toBeGreaterThan(300);
103 expect(summaryOf(p)).toContain("+ 1 database · +$15.00 a month · $15.00 of $50");
104 });
105
106 test("a secret of another name is the one the step names", () => {
107 expect(plan([want({ secret: "PG_URL" })], [], reads()).steps[2]!.says).toBe("Give alice/shop its URL as the secret PG_URL");
108 });
109
110 test("skips what exists, and a finished database is nothing to build", () => {
111 const part = plan([want()], [], reads(), { databases: [have({ made: true, cents: 1500 })] });
112 expect(part.steps.map((s) => s.kind)).toEqual(["online", "bind"]);
113 expect(part.deltaCents).toBe(0);
114 expect(plan([want()], [], reads(), { databases: [have({ made: true, online: true, bound: true, cents: 1500 })] }).steps).toEqual([]);
115 });
116
117 test("refuses in words: no account, read-only, other cloud, region, size, secret name, unknown app, name held", () => {
118 expect(why(plan([want({ account: "digitalocean/none" })], [], reads()))).toEqual([NO_ACCOUNT]);
119 expect(why(plan([want()], [], reads({ writable: false })))[0]).toBe(READ_ONLY);
120 expect(why(plan([want({ account: "hetzner/main" })], [], reads()))[0]).toContain("DigitalOcean accounts only");
121 expect(why(plan([want({ region: "New York" })], [], reads()))[0]).toContain("is not a DigitalOcean region");
122 expect(why(plan([want({ size: "huge" })], [], reads()))[0]).toContain("db-s-1vcpu-1gb");
123 expect(why(plan([want({ secret: "lower" })], [], reads()))[0]).toContain("capital letters");
124 expect(why(plan([want({ app: "bob/none" })], [], reads()))[0]).toContain("is not an app on this forge");
125 expect(why(plan([want({ name: "Bad Name" })], [], reads()))[0]).toContain("lowercase letters");
126 expect(why(plan([want({ size: "db-s-2vcpu-4gb" })], [], reads(), { databases: [have()] }))).toEqual([NAME_TAKEN]);
127 expect(why(plan([want(), want()], [], reads()))).toEqual([NAME_TAKEN]);
128 // A name a machine already holds is not given to a database.
129 const machine: Have = {
130 kind: "machine", name: "shop-db", account: "digitalocean/main", place: "x", app: "", source: "", version: "", host: "", state: "running",
131 volume: true, machine: true, dns: false, answered: true, experiment: "", question: "", cents: 0, keptCents: 0,
132 };
133 expect(why(plan([want()], [machine], reads()))).toEqual([NAME_TAKEN]);
134 // Refused for a reason that is not the ceiling: no create is planned.
135 expect(plan([want({ region: "x" })], [], reads()).steps).toEqual([]);
136 });
137
138 test("is held to the account's ceiling in the ceiling's own sentence", () => {
139 const p = plan([want({ size: "db-s-2vcpu-4gb" })], [], reads({ ceilingDollars: 50, monthlyCents: 0 }));
140 expect(why(p)[0]).toMatch(/digitalocean\/main is held to \$50 a month and runs \$0\.00 now; this would add \$60\.00/);
141 expect(p.byAccount[0]).toMatchObject({ afterCents: 6000, fits: false });
142 // Two that each fit alone but not together: the second is refused.
143 const two = plan([want({ name: "a" }), want({ name: "b" }), want({ name: "c" }), want({ name: "d" })], [], reads({ ceilingDollars: 50 }));
144 expect(two.steps.filter((s) => s.kind === "database").map((s) => s.name)).toEqual(["a", "b", "c"]);
145 expect(two.refusals.map((r) => r.name)).toEqual(["d"]);
146 });
147
148 test("without database reads, no database can be planned", () => {
149 const r = { ...reads(), database: undefined };
150 expect(why(plan([want()], [], r))[0]).toContain("is not an app on this forge");
151 });
152 });
153
154 describe("a database on a forge", () => {
155 let dataDir = "";
156 let app: App;
157 let calls: string[] = [];
158 let status = "creating";
159 let fail: number | undefined;
160 const saved = { sleep: WATCH.sleep, everyMs: WATCH.everyMs };
161 const admin = () => getUserByName(app.db, "alice")!;
162 const doFetch = async (url: string | URL | Request, init?: RequestInit): Promise<Response> => {
163 const u = new URL(String(url));
164 const m = init?.method ?? "GET";
165 calls.push(`${m} ${u.pathname}${u.search}`);
166 if (fail !== undefined && m === "POST") return new Response("no", { status: fail });
167 if (m === "GET" && u.pathname === "/v2/databases") return Response.json({ databases: [] });
168 if (m === "POST" && u.pathname === "/v2/databases") return Response.json({ database: { id: "c-1", status: "creating" } });
169 if (m === "GET" && u.pathname === "/v2/databases/c-1")
170 return Response.json({ database: { id: "c-1", status, ...(status === "online" ? { connection: { uri: URI } } : {}) } });
171 return new Response("?", { status: 404 });
172 };
173 beforeAll(async () => {
174 dataDir = await mkdtemp(join(tmpdir(), "forge-database-"));
175 app = createApp({ dataDir, port: 0 });
176 await seedPlaces(app.db);
177 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
178 if (!made.ok) throw new Error(made.error);
179 const r = await createRepo(app.db, app.reposRoot, { ownerId: admin().id, name: "shop", visibility: "public" });
180 if (!r.ok) throw new Error(String(r.error));
181 createAppRecord(app.db, { repoId: r.value.id, slug: "shop", access: "public" });
182 cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" } }), { status: 200 });
183 const added = await addAccount(app, admin(), "digitalocean", "main", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5");
184 if (!added.ok) throw new Error(String(added.error));
185 allowWrite(app, admin(), "digitalocean", "main", true);
186 net.fetch = doFetch as typeof net.fetch;
187 // The cluster comes online while the build waits on it.
188 WATCH.everyMs = 1;
189 WATCH.sleep = async () => void (status = "online");
190 }, 30_000);
191 afterAll(async () => {
192 WATCH.sleep = saved.sleep;
193 WATCH.everyMs = saved.everyMs;
194 await rm(dataDir, { recursive: true, force: true });
195 });
196
197 test("every door's choices and compose read the same plan", () => {
198 const c = databaseChoices(app);
199 expect(c.apps).toEqual(["alice/shop"]);
200 expect(c.regions.length).toBeGreaterThan(0);
201 expect(c.regions[0]!.value).toMatch(/^digitalocean\/main@[a-z]{3}\d$/);
202 expect(c.sizes.map((s) => s.costCents)).toEqual([1500, 3000, 6000, 12000]);
203 const lacks = planDatabase(app, admin(), { app: "alice/shop", where: "", size: "", name: "", secret: "" });
204 expect(lacks.ok && lacks.value.lacks).toContain("Pick where");
205 expect(databaseWantOf({ app: "alice/shop", where: "digitalocean/main@nyc1", size: "", name: "", secret: "" })).toMatchObject({ ok: true, value: { kind: "database", size: "db-s-1vcpu-1gb" } });
206 const ok1 = planDatabase(app, admin(), { app: "alice/shop", where: "digitalocean/main@nyc1", size: "", name: "shop-db", secret: "" });
207 expect(ok1.ok && ok1.value.plan.refusals).toEqual([]);
208 expect(planDatabase(app, undefined, { app: "alice/shop", where: "digitalocean/main@nyc1", size: "", name: "", secret: "" })).toEqual({ ok: false, error: "not_found" });
209 });
210
211 test("a refused create leaves no cluster, and a retry makes exactly one", async () => {
212 const planned = planDatabase(app, admin(), { app: "alice/shop", where: "digitalocean/main@nyc1", size: "", name: "shop-db", secret: "" });
213 if (!planned.ok) throw new Error(planned.error);
214 const p = planned.value.plan;
215 fail = 422;
216 const bad = await apply(app, admin(), p);
217 expect(bad.ok && bad.value.failed?.why).toContain("The cloud refused");
218 expect(databaseNamed(app.db, "shop-db")).toMatchObject({ remote: "", state: "failed" });
219 expect(accountCents(app.db, "digitalocean", "main")).toBe(0);
220 fail = undefined;
221 calls = [];
222 status = "creating";
223 const good = await apply(app, admin(), p);
224 expect(good.ok && good.value.failed).toBeUndefined();
225 expect(calls.filter((c) => c.startsWith("POST"))).toEqual(["POST /v2/databases"]);
226 const told = app.db.query<{ payload: string }, []>("SELECT payload FROM event WHERE kind = 'infra.step' ORDER BY seq").all().map((r) => JSON.parse(r.payload) as { state: string; says: string });
227 expect(told.filter((e) => e.state === "done").map((e) => e.says)).toEqual([
228 "Create a managed Postgres (1 vCPU, 1 GB) in nyc1",
229 "Wait until shop-db is online",
230 "Give alice/shop its URL as the secret DATABASE_URL",
231 ]);
232 });
233
234 test("the URL is the app's secret, and nowhere else: not on the row, not in an event", () => {
235 const row = databaseNamed(app.db, "shop-db")!;
236 expect(row).toMatchObject({ remote: "c-1", state: "online" });
237 expect(row.boundAt).not.toBe("");
238 expect(JSON.stringify(row)).not.toContain("s3cret-pw");
239 const appId = app.db.query<{ id: string }, []>("SELECT app.id FROM app JOIN repo ON repo.id = app.repo_id WHERE repo.name = 'shop'").get()!.id;
240 expect(resolveAppEnv(app.db, dataDir, appId, "production")["DATABASE_URL"]).toBe(URI);
241 expect(resolveAppEnv(app.db, dataDir, appId, "preview")["DATABASE_URL"]).toBeUndefined();
242 expect(listAppEnvNames(app.db, appId).find((n) => n.name === "DATABASE_URL")).toMatchObject({ kind: "secret", scope: "production" });
243 const events = app.db.query<{ payload: string }, []>("SELECT payload FROM event").all().map((e) => e.payload).join("\n");
244 expect(events).not.toContain("s3cret-pw");
245 expect(app.db.query("SELECT 1 FROM event WHERE kind = 'database.bound'").get()).not.toBeNull();
246 });
247
248 test("the account's month counts it, so the ceiling and the meter agree", () => {
249 expect(accountCents(app.db, "digitalocean", "main")).toBe(1500);
250 expect(readInfra(app).reads.account("digitalocean/main")?.monthlyCents).toBe(1500);
251 const v = infraOf(app, admin());
252 if (!v.ok) throw new Error(v.error);
253 expect(v.value.databases).toEqual([expect.objectContaining({ name: "shop-db", monthlyCents: 1500, state: "online", bound: true })]);
254 expect(v.value.meters.find((m) => m.account === "digitalocean/main")?.monthlyCents).toBe(1500);
255 expect(infraSays(v.value)).toContain("Databases: shop-db (online; its URL is the secret DATABASE_URL of alice/shop)");
256 expect(infraSays(v.value)).toContain("$15.00 a month");
257 });
258
259 test("the terminal's d key composes it: app, region, size, then the plan with Build", async () => {
260 const { app: tui, session } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin() }, { terminal: headlessTerminal(160, 30), exitHooks: false });
261 tui.start();
262 tui.ctx.push(infraScreen(session, tui.ctx));
263 await settleApp(tui);
264 const press = (key: string) => tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
265 expect(tui.screen.toText()).toContain("shop-db · $15.00/mo");
266 expect(tui.screen.toText()).toContain("database · alice/shop · nyc1 · 1 vCPU, 1 GB · online; its URL is the secret DATABASE_URL of alice/shop");
267 press("b");
268 await settleApp(tui);
269 expect(tui.screen.toText()).toContain("A database for");
270 press("enter");
271 await settleApp(tui);
272 expect(tui.screen.toText()).toContain("Where");
273 press("enter");
274 await settleApp(tui);
275 expect(tui.screen.toText()).toContain("Size");
276 press("j");
277 press("enter");
278 await settleApp(tui);
279 const text = tui.screen.toText();
280 expect(text).toContain("The plan");
281 expect(text).toContain("Create a managed Postgres (1 vCPU, 2 GB)");
282 tui.stop?.();
283 });
284
285 test("the infra tool and the API plan the same database; a want the plan refuses says why", async () => {
286 const url = new URL("http://forge.test/mcp");
287 const ctx = { app, request: new Request(url.href), url, params: {}, auth: { user: admin(), scope: "admin", via: "token" }, theme: undefined } as unknown as Parameters<typeof tool.run>[0];
288 const planned = (await tool.run(ctx, admin(), { action: "plan", want: { database: true, app: "alice/shop", where: "digitalocean/main@sfo3", name: "second" } })) as any;
289 expect(planned.ok).toBe(true);
290 expect(planned.value.steps).toEqual(["Create a managed Postgres (1 vCPU, 1 GB) in sfo3", "Wait until second is online", "Give alice/shop its URL as the secret DATABASE_URL"]);
291 const lacking = (await tool.run(ctx, admin(), { action: "plan", want: { database: true, app: "alice/shop" } })) as any;
292 expect(lacking.ok).toBe(false);
293 const refused = (await tool.run(ctx, admin(), { action: "plan", want: { database: true, app: "alice/shop", where: "digitalocean/main@sfo3", size: "huge" } })) as any;
294 expect(refused.value.refusals[0].why).toContain("db-s-1vcpu-1gb");
295 });
296
297 test("the API route: a non-admin gets not_found, no where is 422, a valid body is a plan of three steps", async () => {
298 const router = new Router<Handler>();
299 adminRoutes(router);
300 const route = router.handlerOf("POST", "/api/v1/admin/infra/plan")!;
301 const ask = (user: unknown, body: unknown) => {
302 const url = new URL("http://forge.test/api/v1/admin/infra/plan");
303 const request = new Request(url.href, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
304 return route({ app, request, url, params: {}, auth: { user, scope: "admin", via: "token" } } as unknown as Parameters<Handler>[0]);
305 };
306 const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
307 if (!bob.ok) throw new Error(bob.error);
308 expect((await ask(getUserByName(app.db, "bob"), { database: true, app: "alice/shop" })).status).toBe(404);
309 const lacking = await ask(admin(), { database: true, app: "alice/shop" });
310 expect(lacking.status).toBe(422);
311 const ok = await ask(admin(), { database: true, app: "alice/shop", where: "digitalocean/main@sfo3", name: "third" });
312 expect(ok.status).toBe(200);
313 const planned = (await ok.json()) as { steps: unknown[]; refusals: unknown[] };
314 expect(planned.steps).toHaveLength(3);
315 expect(planned.refusals).toEqual([]);
316 });
317
318 test("planning it again finds nothing to build", () => {
319 const again = planDatabase(app, admin(), { app: "alice/shop", where: "digitalocean/main@nyc1", size: "", name: "shop-db", secret: "" });
320 expect(again.ok && again.value.plan.steps).toEqual([]);
321 expect(again.ok && again.value.plan.deltaCents).toBe(0);
322 });
323 });
324

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs