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

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

opened this

Parked 47h 17m ago

scout/forge:scout/17074-data-managed-postgres-on-digitalocean-as → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
12 files changed +619 −4
docs/features/managed-database.md added +26
@@ -0,0 +1,26 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: Managed Postgres
4 ---
5 # Managed Postgres
6
7 A managed PostgreSQL database on your own DigitalOcean account is an infrastructure kind (#17074,
8 phase 3 of #16696). It is planned before money, like a machine: each step, what it adds a month
9 against the account's ceiling (the ceiling's own refusal words), and the time to ready.
10
11 Through Talk or the MCP `infra` tool (admins; `src/http/mcp/tools/infra.ts`, `src/actions/database.ts`):
12
13 1. `plan` a `want` of `{database: true, where: "digitalocean/main@nyc3:db-s-1vcpu-1gb", name: "shopdb", app: "alice/shop"}`.
14 It answers the plan's id, its steps (create, wait until online, bind), `deltaCents` and the refusals.
15 2. `apply` that `id` with the same `want`. The person is asked first. The forge makes the database
16 once (a repeat finds it and only binds), waits until it is online, and writes its connection URL as
17 `alice/shop`'s secret `DATABASE_URL`. The URL is never shown, logged or put in an event.
18
19 Sizes and prices (one node, PostgreSQL 16) are DigitalOcean's published list prices, copied on
20 `DB_PRICED_ON` in `src/cloud/database.ts`: the API lists sizes but not prices. A made database is a row
21 of `managed_database` that the account's spend counts (`accountCents`). The forge's reckoning is not the
22 bill; DigitalOcean's is the truth.
23
24 Not yet: retiring or resizing a database, backups, Spaces and the other clouds, and a terminal
25 composer for it (the terminal's `infra` screen shows the machines it builds; Talk and MCP make a
26 database).
src/actions/database.ts added +139
@@ -0,0 +1,139 @@
1 /**
2 * Managed Postgres, planned and built (#17074, phase 3 of #16696): the same actions the `infra`
3 * tool calls. A plan reads what the forge holds (`cloud/database.ts`, pure); a build checks the
4 * plan against what stands now, makes the database at the account's cloud once (recorded the moment
5 * it exists, so the ceiling counts it and a repeat finds it), waits until it is online, then
6 * writes its connection URL as the app's secret. The URL is opened only here and is never in a
7 * return, an event or a log. Each step is one `infra.step` event, as a machine's are.
8 */
9
10 import type { App } from "../app.ts";
11 import { accountCents, priced } from "../cloud/ceiling.ts";
12 import { createDatabase, databaseWant, DB_SIZES, findDatabase, planDatabase, readDatabase, URL_SECRET, type DatabasePlan, type DatabaseReads, type DatabaseWant } from "../cloud/database.ts";
13 import { digitalocean } from "../cloud/droplet.ts";
14 import { gatedFetch } from "../cloud/gate.ts";
15 import { caller, type Call } from "../cloud/machine.ts";
16 import { orphanRefusal } from "../cloud/watch_read.ts";
17 import { getCloudAccount, secretNameOf } from "../core/cloud_account.ts";
18 import { getManagedDatabase, recordManagedDatabase } from "../core/managed_database.ts";
19 import { getRepo } from "../core/repos.ts";
20 import { resolveSecrets } from "../core/secret_store.ts";
21 import type { User } from "../core/users.ts";
22 import { err, ok, type Result } from "../kernel/result.ts";
23 import { net } from "./pinned.ts";
24 import { putSecret } from "./secrets.ts";
25
26 /**
27 * How long a build waits for the database to come online, and how often it looks; tests shorten
28 * both.
29 */
30 export const DB_WAIT = { waitMs: 15 * 60_000, everyMs: 10_000, sleep: (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms)) };
31
32 /**
33 * What a person or an agent says: where (`digitalocean/main@nyc3:db-s-1vcpu-1gb`), a name, the app.
34 */
35 export interface DatabaseAsk {
36 readonly name: string;
37 readonly where: string;
38 readonly app: string;
39 }
40
41 function readsOf(app: App): DatabaseReads {
42 const prices = priced(app.db);
43 return {
44 account: (account) => {
45 const i = account.indexOf("/");
46 const provider = account.slice(0, Math.max(0, i));
47 const name = account.slice(i + 1);
48 const a = i > 0 ? getCloudAccount(app.db, provider, name) : undefined;
49 if (a === undefined) return undefined;
50 return { writable: a.writeAllowed, ceilingDollars: a.ceilingDollars, monthlyCents: accountCents(app.db, provider, name, prices), orphan: orphanRefusal(app.db, provider, name) };
51 },
52 appExists: (a) => {
53 const [owner = "", name = ""] = a.split("/");
54 return getRepo(app.db, owner, name) !== undefined;
55 },
56 have: (name) => getManagedDatabase(app.db, name),
57 };
58 }
59
60 /** The plan for a database wanted for an app, or what the ask lacks; admins only. */
61 export function planManagedDatabase(app: App, actor: User | undefined, g: DatabaseAsk): Result<DatabasePlan, string> {
62 if (!actor?.isAdmin) return err("not_found");
63 const w = databaseWant(g);
64 return w.ok ? ok(planDatabase(w.value, readsOf(app))) : err(w.error);
65 }
66
67 /** "create… · +$15.00 a month · $15.00 of $50 · ready in about 7 min": the tray's line. */
68 export function summaryOf(p: DatabasePlan): string {
69 const usd = (c: number): string => (c / 100).toFixed(2);
70 return `${p.steps.map((s) => s.says).join("; ")} · +$${usd(p.deltaCents)} a month · $${usd(p.afterCents)} of $${p.ceilingCents / 100} · ready in about ${Math.max(1, Math.round(p.etaSeconds / 60))} min`;
71 }
72
73 const event = (app: App, actor: User, p: DatabasePlan, index: number, state: "started" | "done" | "failed", why?: string): void => {
74 void app.bus.append({ kind: "infra.step", actorId: actor.id, payload: { planId: p.id, index, state, says: p.steps[index]?.says ?? "", ...(why === undefined ? {} : { why }) } });
75 };
76
77 /**
78 * Build the plan `id` for `g`: refused when the plan now differs from the one shown, or has a
79 * refusal. Safe to run again: what exists is found and bound, never made twice.
80 */
81 export async function buildManagedDatabase(app: App, actor: User | undefined, g: DatabaseAsk, id: string): Promise<Result<string, string>> {
82 if (!actor?.isAdmin) return err("not_found");
83 const planned = planManagedDatabase(app, actor, g);
84 if (!planned.ok) return planned;
85 const p = planned.value;
86 if (p.id !== id) return err("That plan is not the one this forge shows now: plan it again, then apply its id.");
87 if (p.refusals.length > 0) return err(p.refusals.join(" "));
88 const w = p.want;
89 const slash = w.account.indexOf("/");
90 const provider = w.account.slice(0, slash);
91 const account = w.account.slice(slash + 1);
92 const acct = getCloudAccount(app.db, provider, account);
93 if (acct === undefined) return err("No such credential.");
94 const secret = secretNameOf(acct.provider, acct.name);
95 const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: actor.id, run: "database:create" })[secret];
96 if (token === undefined) return err("No such credential.");
97 const call = caller(digitalocean, gatedFetch(app.db, { provider, account }, "database:create", net.fetch), token);
98 const last = p.steps.length - 1;
99 let at = 0;
100 try {
101 const url = await ensure(app, actor, p, w, call, (i) => (at = i));
102 at = last;
103 event(app, actor, p, last, "started");
104 const set = putSecret(app, actor, "repo", w.app, URL_SECRET, url);
105 if (!set.ok) throw new Error(`The secret ${URL_SECRET} was not written (${set.error}).`);
106 event(app, actor, p, last, "done");
107 return ok(`${w.name} is online, and its connection URL is ${w.app}'s secret ${URL_SECRET}.`);
108 } catch (e) {
109 const why = e instanceof Error ? e.message.slice(0, 200) : "failed";
110 event(app, actor, p, at, "failed", why);
111 return err(`The database was not finished: ${why}`);
112 }
113 }
114
115 /** Find or make the database, wait until it is online, and return its URL. */
116 async function ensure(app: App, actor: User, p: DatabasePlan, w: DatabaseWant, call: Call, at: (i: number) => void): Promise<string> {
117 let row = getManagedDatabase(app.db, w.name);
118 const making = p.steps[0]?.kind === "create";
119 if (row === undefined) {
120 at(0);
121 event(app, actor, p, 0, "started");
122 const found = await findDatabase(call, w.name);
123 const remote = found !== "" ? found : await createDatabase(call, w);
124 recordManagedDatabase(app.db, { name: w.name, account: w.account, region: w.region, size: w.size, app: w.app, remote, monthlyCents: DB_SIZES[w.size]!.cents, createdAt: new Date().toISOString() });
125 row = getManagedDatabase(app.db, w.name)!;
126 event(app, actor, p, 0, "done");
127 }
128 if (making) at(1);
129 if (making) event(app, actor, p, 1, "started");
130 for (let waited = 0; ; waited += DB_WAIT.everyMs) {
131 const r = await readDatabase(call, row.remote);
132 if (r.status === "online" && r.url !== "") {
133 if (making) event(app, actor, p, 1, "done");
134 return r.url;
135 }
136 if (waited >= DB_WAIT.waitMs) throw new Error("It is still not online; build the same plan again to keep waiting for it.");
137 await DB_WAIT.sleep(DB_WAIT.everyMs);
138 }
139 }
src/cloud/ceiling.ts +8 −2
@@ -18,6 +18,7 @@
1818 import type { Database } from "bun:sqlite";
1919 import type { App } from "../app.ts";
2020 import { getCloudAccount } from "../core/cloud_account.ts";
21 import { databaseCents } from "../core/managed_database.ts";
2122 import { getPinned, listPinned, placeIdOf, type Pinned } from "../core/pinned.ts";
2223 import type { Driver } from "./machine.ts";
2324 import { DO_VOLUME_USD_PER_GIB, OVH_VOLUME_USD_PER_GIB, VOLUME_GIB } from "./places.ts";
@@ -123,11 +124,16 @@ export function rowCents(p: Row, prices: Priced): number {
123124 return prices.forge(placeIdOf(p)) ?? unlisted() ?? 0;
124125 }
125126
126 /** What the forge reckons an account costs a month, in cents: the sum over its own pinned rows. */
127 /**
128 * What the forge reckons an account costs a month, in cents: the sum over its own pinned rows and
129 * managed databases.
130 */
127131 export function accountCents(db: Database, provider: string, account: string, prices: Priced = priced(db)): number {
128 return listPinned(db)
132 const machines = listPinned(db)
129133 .filter((p) => p.target === provider && p.account === account)
130134 .reduce((sum, p) => sum + rowCents(p, prices), 0);
135 // Managed databases (#17074) are priced when made and recorded at that price.
136 return machines + databaseCents(db, `${provider}/${account}`);
131137 }
132138
133139 export interface Spend {
src/cloud/database.ts added +200
@@ -0,0 +1,200 @@
1 /**
2 * Managed PostgreSQL on DigitalOcean as an infrastructure kind (#17074, phase 3 of #16696): the
3 * price read, the plan step and the calls. Plan before money: `planDatabase` is pure, says each
4 * step, what the account costs a month before and after against its ceiling (the ceiling's own
5 * refusal sentences, `refusalOf`), and the time to ready. Binding is `actions/database.ts`, which
6 * writes the connection URL as an app secret and never returns it.
7 *
8 * Price read: DigitalOcean's API lists a database's sizes but not their prices, so the prices here
9 * are its published list prices for one node (`DB_PRICED_ON`), kept in this table the way
10 * OVHcloud's volume price is (`places.ts`). A size not in the table has no price, and the ceiling
11 * refuses what it cannot price. The forge's reckoning is not the bill; the provider's bill is the
12 * truth.
13 */
14
15 import { NO_ACCOUNT, READ_ONLY } from "../core/cloud_account.ts";
16 import type { ManagedDatabase } from "../core/managed_database.ts";
17 import { NAME_TAKEN } from "../core/pinned.ts";
18 import { refusalOf } from "./ceiling.ts";
19 import { type Call } from "./machine.ts";
20 import { dollars } from "./prices.ts";
21 import type { AccountRead } from "./plan.ts";
22
23 /** The day the list prices below were copied from DigitalOcean's pricing. */
24 export const DB_PRICED_ON = "2026-12-01";
25
26 export interface DatabaseSize {
27 readonly vcpu: number;
28 readonly memoryGiB: number;
29 readonly diskGiB: number;
30 /** US cents a month, one node. */
31 readonly cents: number;
32 }
33
34 /** DigitalOcean's managed PostgreSQL sizes, by slug, one node each. */
35 export const DB_SIZES: Readonly<Record<string, DatabaseSize>> = {
36 "db-s-1vcpu-1gb": { vcpu: 1, memoryGiB: 1, diskGiB: 10, cents: 1500 },
37 "db-s-1vcpu-2gb": { vcpu: 1, memoryGiB: 2, diskGiB: 25, cents: 3000 },
38 "db-s-2vcpu-4gb": { vcpu: 2, memoryGiB: 4, diskGiB: 38, cents: 6000 },
39 "db-s-4vcpu-8gb": { vcpu: 4, memoryGiB: 8, diskGiB: 115, cents: 12000 },
40 };
41
42 /** The version made: the newest DigitalOcean offers when this was written. */
43 export const PG_VERSION = "16";
44 /** The secret the connection URL is written to, in the app's own scope. */
45 export const URL_SECRET = "DATABASE_URL";
46 /** Seconds from the create to online; DigitalOcean's own range is 5 to 10 minutes. */
47 export const DB_ETA_SECONDS = 420;
48
49 const NAME = /^[a-z][a-z0-9-]{0,38}$/;
50 const REGION = /^[a-z]{3}[0-9]$/;
51 const APP = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
52
53 /** A managed PostgreSQL database wanted for an app. */
54 export interface DatabaseWant {
55 readonly name: string;
56 /** The cloud account, `provider/name`; only `digitalocean` makes databases. */
57 readonly account: string;
58 readonly region: string;
59 /** A key of `DB_SIZES`. */
60 readonly size: string;
61 /** The app it is bound to, `owner/name`. */
62 readonly app: string;
63 }
64
65 /** `account@region:size` as a person or an agent says where, with the name and app it is for. */
66 export function databaseWant(g: { readonly name: string; readonly where: string; readonly app: string }): { ok: true; value: DatabaseWant } | { ok: false; error: string } {
67 const [account = "", spot = ""] = g.where.split("@");
68 const [region = "", size = ""] = spot.split(":");
69 if (!account.startsWith("digitalocean/")) return { ok: false, error: "Managed Postgres is made on a DigitalOcean account: name it as digitalocean/<account>@<region>:<size>." };
70 if (!REGION.test(region)) return { ok: false, error: "Name a DigitalOcean region such as nyc3." };
71 if (DB_SIZES[size] === undefined) return { ok: false, error: `Pick one of the sizes: ${Object.keys(DB_SIZES).join(", ")}.` };
72 if (!NAME.test(g.name)) return { ok: false, error: "A name is lowercase letters, digits and dashes, starting with a letter." };
73 if (!APP.test(g.app)) return { ok: false, error: "Name the app it is for as owner/name." };
74 return { ok: true, value: { name: g.name, account, region, size, app: g.app } };
75 }
76
77 export interface DatabaseStep {
78 readonly index: number;
79 readonly kind: "create" | "wait" | "bind";
80 readonly says: string;
81 /** What it adds a month, US cents. */
82 readonly cents: number;
83 }
84
85 export interface DatabasePlan {
86 /** Stable for the same want against the same standing. */
87 readonly id: string;
88 readonly want: DatabaseWant;
89 readonly steps: readonly DatabaseStep[];
90 readonly beforeCents: number;
91 readonly afterCents: number;
92 readonly ceilingCents: number;
93 readonly deltaCents: number;
94 readonly etaSeconds: number;
95 readonly refusals: readonly string[];
96 }
97
98 /**
99 * What the plan reads: the account, whether the app exists, and the database already made under the
100 * name.
101 */
102 export interface DatabaseReads {
103 account(account: string): AccountRead | undefined;
104 appExists(app: string): boolean;
105 have(name: string): ManagedDatabase | undefined;
106 }
107
108 const sizeWords = (s: DatabaseSize): string => `${s.vcpu} vCPU, ${s.memoryGiB} GB, ${s.diskGiB} GB disk`;
109
110 /**
111 * What would run to have `want`, and what it costs. Nothing refused is made; a database that exists
112 * is only bound.
113 */
114 export function planDatabase(want: DatabaseWant, reads: DatabaseReads): DatabasePlan {
115 const size = DB_SIZES[want.size];
116 const a = reads.account(want.account);
117 const have = reads.have(want.name);
118 const refusals: string[] = [];
119 if (a === undefined) refusals.push(NO_ACCOUNT);
120 else if (!a.writable) refusals.push(READ_ONLY);
121 if (!reads.appExists(want.app)) refusals.push(`${want.app} is not an app on this forge.`);
122 if (have !== undefined && (have.account !== want.account || have.region !== want.region || have.size !== want.size || have.app !== want.app))
123 refusals.push(NAME_TAKEN);
124 if (a !== undefined && a.writable && refusals.length === 0 && have === undefined) {
125 const no = refusalOf({
126 provider: "digitalocean",
127 account: want.account.slice("digitalocean/".length),
128 place: { id: `digitalocean:${want.region}:${want.size}`, size: want.size, datacenter: want.region },
129 orphan: a.orphan,
130 price: size?.cents,
131 closed: undefined,
132 ceilingDollars: a.ceilingDollars,
133 monthlyCents: a.monthlyCents,
134 counted: 0,
135 held: 0,
136 });
137 if (no !== undefined) refusals.push(no);
138 }
139 const steps: Omit<DatabaseStep, "index">[] = [];
140 if (have === undefined && size !== undefined)
141 steps.push(
142 { kind: "create", says: `Create a PostgreSQL ${PG_VERSION} database (${sizeWords(size)}) in ${want.region}, ${dollars(size.cents)} a month`, cents: size.cents },
143 { kind: "wait", says: "Wait until it is online", cents: 0 },
144 );
145 steps.push({ kind: "bind", says: `Bind its connection URL to ${want.app} as the secret ${URL_SECRET}`, cents: 0 });
146 const before = a?.monthlyCents ?? 0;
147 // A refused create still shows in the sum, so the tray can say by how much.
148 const add = have === undefined ? (size?.cents ?? 0) : 0;
149 const hash = new Bun.CryptoHasher("sha256").update(JSON.stringify({ want, made: have !== undefined })).digest("hex").slice(0, 16);
150 return {
151 id: `plan-db-${hash}`,
152 want,
153 steps: steps.map((s, index) => ({ ...s, index })),
154 beforeCents: before,
155 afterCents: before + add,
156 ceilingCents: (a?.ceilingDollars ?? 0) * 100,
157 deltaCents: add,
158 etaSeconds: have === undefined ? DB_ETA_SECONDS : 0,
159 refusals,
160 };
161 }
162
163 const forgeTag = (name: string): string => `forge-db:${name}`;
164 const ID = /^[A-Za-z0-9-]{1,64}$/;
165
166 /**
167 * The id of the database already tagged for `name` at the provider, or "": a repeated build finds,
168 * never doubles.
169 */
170 export async function findDatabase(call: Call, name: string): Promise<string> {
171 const all: unknown = (await call("GET", `/databases?tag_name=${encodeURIComponent(forgeTag(name))}`)).databases;
172 const hit = (Array.isArray(all) ? all : []).find((d: any) => d?.name === `forge-${name}` && typeof d.id === "string" && ID.test(d.id));
173 return hit?.id ?? "";
174 }
175
176 /** Make the cluster: one node, tagged so it is found again and counted as the forge's. */
177 export async function createDatabase(call: Call, w: DatabaseWant): Promise<string> {
178 const r = await call("POST", "/databases", {
179 name: `forge-${w.name}`,
180 engine: "pg",
181 version: PG_VERSION,
182 region: w.region,
183 size: w.size,
184 num_nodes: 1,
185 tags: [forgeTag(w.name)],
186 });
187 const id = r.database?.id;
188 if (typeof id !== "string" || !ID.test(id)) throw new Error("DigitalOcean made no database id");
189 return id;
190 }
191
192 /** A PostgreSQL connection URL, and nothing else that could be put in a secret. */
193 const POSTGRES_URL = /^postgres(?:ql)?:\/\/[^\s]{1,2000}$/;
194
195 /** The state of a database and, once online, its connection URL (never logged, never shown). */
196 export async function readDatabase(call: Call, remote: string): Promise<{ status: string; url: string }> {
197 const d = (await call("GET", `/databases/${encodeURIComponent(remote)}`)).database;
198 const uri = d?.connection?.uri;
199 return { status: String(d?.status ?? ""), url: typeof uri === "string" && POSTGRES_URL.test(uri) ? uri : "" };
200 }
src/cloud/machine.ts +1 −1
@@ -243,7 +243,7 @@ export interface Driver {
243243 /** The tag or label that names a forge on everything the forge makes for it (#16340). */
244244 export const forgeTag = (name: string) => `forge:${name}`;
245245
246 function caller(d: Driver, f: Fetch, token: string): Call {
246 export function caller(d: Driver, f: Fetch, token: string): Call {
247247 if (d.signed) return d.signed(f, token);
248248 const host = new URL(d.api).host;
249249 return async (method, path, body) => {
src/core/managed_database.ts added +55
@@ -0,0 +1,55 @@
1 /** The managed databases the forge made on a cloud account (`managed_database`), one row each. */
2
3 import type { Database } from "bun:sqlite";
4
5 export interface ManagedDatabase {
6 readonly name: string;
7 /** The cloud account, `provider/name`. */
8 readonly account: string;
9 readonly region: string;
10 readonly size: string;
11 /** The app it is bound to, `owner/name`. */
12 readonly app: string;
13 /** The provider's id for it; empty until it exists there. */
14 readonly remote: string;
15 readonly monthlyCents: number;
16 readonly createdAt: string;
17 }
18
19 interface Row {
20 name: string;
21 account: string;
22 region: string;
23 size: string;
24 app: string;
25 remote: string;
26 monthly_cents: number;
27 created_at: string;
28 }
29
30 const of = (r: Row): ManagedDatabase => ({
31 name: r.name,
32 account: r.account,
33 region: r.region,
34 size: r.size,
35 app: r.app,
36 remote: r.remote,
37 monthlyCents: r.monthly_cents,
38 createdAt: r.created_at,
39 });
40
41 export function getManagedDatabase(db: Database, name: string): ManagedDatabase | undefined {
42 const r = db.query<Row, [string]>("SELECT * FROM managed_database WHERE name = ?").get(name);
43 return r === null ? undefined : of(r);
44 }
45
46 /** What the account's databases cost a month, US cents. */
47 export const databaseCents = (db: Database, account: string): number =>
48 db.query<{ c: number | null }, [string]>("SELECT SUM(monthly_cents) AS c FROM managed_database WHERE account = ?").get(account)?.c ?? 0;
49
50 /** Record a database the moment it exists at the provider; recording it again changes nothing. */
51 export function recordManagedDatabase(db: Database, d: ManagedDatabase): void {
52 db.query(
53 "INSERT OR IGNORE INTO managed_database (name, account, region, size, app, remote, monthly_cents, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
54 ).run(d.name, d.account, d.region, d.size, d.app, d.remote, d.monthlyCents, d.createdAt);
55 }
src/core/migration-pins/20261201150000-managed-database.pin added +1
@@ -0,0 +1,1 @@
1 014e86d8eafb9d6cd896efcd5b2d4d9abf092885897a28b76c209b49bdddc5dc
src/core/migrations/20261201150000-managed-database.ts added +16
@@ -0,0 +1,16 @@
1 // Managed databases made on the owner's cloud (#17074, phase 3 of #16696): one row per database the
2 // forge made, so the spend ceiling counts it and a repeated build finds it instead of making a
3 // second. The connection URL is never a column: it is an app secret (`secret_store`), written once
4 // it is online.
5 export default `
6 CREATE TABLE IF NOT EXISTS 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 remote TEXT NOT NULL DEFAULT '',
13 monthly_cents INTEGER NOT NULL DEFAULT 0,
14 created_at TEXT NOT NULL
15 );
16 `;
src/generated/migrations.ts +2
@@ -448,6 +448,7 @@ import m443 from "../core/migrations/20261201121000-repo-check-slots.ts";
448448 import m444 from "../core/migrations/20261201130000-finding-touched.ts";
449449 import m445 from "../core/migrations/20261201130000-game-box-boot.ts";
450450 import m446 from "../core/migrations/20261201140000-scan-finding-excerpt.ts";
451 import m447 from "../core/migrations/20261201150000-managed-database.ts";
451452
452453 /** Each migration file's name and its default export, in name order. */
453454 export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
@@ -898,4 +899,5 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
898899 ["20261201130000-finding-touched.ts", m444],
899900 ["20261201130000-game-box-boot.ts", m445],
900901 ["20261201140000-scan-finding-excerpt.ts", m446],
902 ["20261201150000-managed-database.ts", m447],
901903 ];
src/http/mcp/tools/infra.ts +16 −1
@@ -1,10 +1,14 @@
11 import { buildOf, gameWant, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts";
2 import { buildManagedDatabase, planManagedDatabase, summaryOf } from "../../../actions/database.ts";
23 import { endsWords, keepPinned } from "../../../actions/pinned.ts";
34 import { EXPERIMENT_WORDS, attachMachine, beginExperiment, findExperiment, recordResult } from "../../../cloud/experiments.ts";
45 import { good, bad, type Tool, str } from "../shared.ts";
56
67 const s = (v: unknown, max: number): string => str(v).slice(0, max);
78
9 /** A managed database's ask as an agent gave it; the forge validates every part. */
10 const dbAsk = (w: Record<string, unknown>): { name: string; where: string; app: string } => ({ name: s(w["name"], 40), where: s(w["where"], 260), app: s(w["app"], 140) });
11
812 /**
913 * Infrastructure (#16696): what runs on the owner's own cloud, what it is for, what it costs and
1014 * when it ends, and building one more machine through a plan. The experiments it holds took the
@@ -14,7 +18,7 @@ const s = (v: unknown, max: number): string => str(v).slice(0, max);
1418 export const tool: Tool = {
1519 name: "infra",
1620 listedTo: "admin",
17 doc: "`{ action, id?, want?, question?, names?, result? }`: `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 dead `names`, `apply` its `id`, `keep`, `begin`, `attach`, `record_result`.",
21 doc: "`{ action, id?, want?, question?, names?, result? }`: `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 a managed Postgres on DigitalOcean `{database: true, where, name, app}` with where as digitalocean/<account>@<region>:<size> (its connection URL becomes the app's secret DATABASE_URL) or dead `names`, `apply` its `id` (a database's with the same `want`), `keep`, `begin`, `attach`, `record_result`.",
1822 description: "Cloud machines and spend.",
1923 inputSchema: {
2024 type: "object",
@@ -68,6 +72,12 @@ export const tool: Tool = {
6872 if (action === "plan") {
6973 const w = (typeof args["want"] === "object" && args["want"] !== null ? args["want"] : {}) as Record<string, unknown>;
7074 // A game box: Docker and the game agent on the owner's cloud, running a compose file.
75 if (w["database"] === true) {
76 const planned = planManagedDatabase(ctx.app, user, dbAsk(w));
77 if (!planned.ok) return bad("incomplete", planned.error);
78 const p = planned.value;
79 return good({ id: p.id, says: summaryOf(p), steps: p.steps.map((x) => x.says), refusals: p.refusals, beforeCents: p.beforeCents, afterCents: p.afterCents, ceilingCents: p.ceilingCents, deltaCents: p.deltaCents, etaSeconds: p.etaSeconds });
80 }
7181 if (w["game"] === true) {
7282 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) });
7383 if (!want.ok) return bad("incomplete", want.error);
@@ -102,6 +112,11 @@ export const tool: Tool = {
102112 etaSeconds: p.plan.etaSeconds,
103113 });
104114 }
115 if (action === "apply" && id.startsWith("plan-db-")) {
116 const w = (typeof args["want"] === "object" && args["want"] !== null ? args["want"] : {}) as Record<string, unknown>;
117 const built = await buildManagedDatabase(ctx.app, user, dbAsk(w), id);
118 return built.ok ? good({ says: built.value }) : bad("refused", built.error);
119 }
105120 if (action === "apply") {
106121 const p = planById(ctx.app, id);
107122 if (p === undefined) return bad("no_plan", "That plan is not one this forge showed lately: plan it again, then apply its id.");
test/managed-database.test.ts added +154
@@ -0,0 +1,154 @@
1 /**
2 * Managed Postgres on DigitalOcean (#17074, phase 3 of #16696): the price read, the plan step and
3 * the binding. `planDatabase` is pure; the build runs on a real forge against a recorded
4 * DigitalOcean that makes the database and answers it online, and the connection URL ends as the
5 * app's secret, in no return and no event.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts";
13 import { buildManagedDatabase, DB_WAIT, planManagedDatabase, summaryOf } from "../src/actions/database.ts";
14 import { net } from "../src/actions/pinned.ts";
15 import { accountCents } from "../src/cloud/ceiling.ts";
16 import { databaseWant, DB_SIZES, planDatabase, type DatabaseReads, type DatabaseWant } from "../src/cloud/database.ts";
17 import { NO_ACCOUNT, READ_ONLY } from "../src/core/cloud_account.ts";
18 import { NAME_TAKEN } from "../src/core/pinned.ts";
19 import { createRepo } from "../src/actions/repos.ts";
20 import { getRepo } from "../src/core/repos.ts";
21 import { resolveSecrets } from "../src/core/secret_store.ts";
22 import { createUser, getUserByName } from "../src/core/users.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24
25 quietLogs();
26
27 const want: DatabaseWant = { name: "shopdb", account: "digitalocean/main", region: "nyc3", size: "db-s-1vcpu-1gb", app: "alice/shop" };
28 const reads = (over: Partial<DatabaseReads> = {}, account = { writable: true, ceilingDollars: 50, monthlyCents: 0 }): DatabaseReads => ({
29 account: (a) => (a === "digitalocean/main" ? account : undefined),
30 appExists: (a) => a === "alice/shop",
31 have: () => undefined,
32 ...over,
33 });
34
35 describe("managed database plan", () => {
36 test("a want reads as account@region:size, and refuses what it cannot make", () => {
37 expect(databaseWant({ name: "shopdb", where: "digitalocean/main@nyc3:db-s-1vcpu-1gb", app: "alice/shop" })).toEqual({ ok: true, value: want });
38 for (const where of ["hetzner/main@nyc3:db-s-1vcpu-1gb", "digitalocean/main@NYC:db-s-1vcpu-1gb", "digitalocean/main@nyc3:huge", "digitalocean/main"])
39 expect(databaseWant({ name: "shopdb", where, app: "alice/shop" }).ok).toBe(false);
40 expect(databaseWant({ name: "Bad Name", where: "digitalocean/main@nyc3:db-s-1vcpu-1gb", app: "alice/shop" }).ok).toBe(false);
41 expect(databaseWant({ name: "shopdb", where: "digitalocean/main@nyc3:db-s-1vcpu-1gb", app: "no-slash" }).ok).toBe(false);
42 });
43
44 test("the plan prices the size, steps create, wait and bind, and fits under the ceiling", () => {
45 const p = planDatabase(want, reads());
46 expect(p.refusals).toEqual([]);
47 expect(p.steps.map((s) => s.kind)).toEqual(["create", "wait", "bind"]);
48 expect(p).toMatchObject({ beforeCents: 0, afterCents: DB_SIZES["db-s-1vcpu-1gb"]!.cents, deltaCents: 1500, ceilingCents: 5000 });
49 expect(summaryOf(p)).toContain("+$15.00 a month · $15.00 of $50 · ready in about 7 min");
50 expect(planDatabase(want, reads()).id).toBe(p.id);
51 });
52
53 test("the ceiling refuses in its own words, and the refused create still shows its price", () => {
54 const p = planDatabase({ ...want, size: "db-s-4vcpu-8gb" }, reads());
55 expect(p.refusals.join(" ")).toContain("is held to $50 a month");
56 expect(p.deltaCents).toBe(12000);
57 });
58
59 test("no account, a read-only account, an unknown app and a taken name are refused", () => {
60 expect(planDatabase({ ...want, account: "digitalocean/none" }, reads()).refusals).toEqual([NO_ACCOUNT]);
61 expect(planDatabase(want, reads({}, { writable: false, ceilingDollars: 50, monthlyCents: 0 })).refusals).toEqual([READ_ONLY]);
62 expect(planDatabase({ ...want, app: "alice/none" }, reads()).refusals[0]).toContain("is not an app");
63 const made = { ...want, size: "db-s-1vcpu-2gb", remote: "x", monthlyCents: 3000, createdAt: "" };
64 expect(planDatabase(want, reads({ have: () => made })).refusals).toEqual([NAME_TAKEN]);
65 });
66
67 test("a database that exists is only bound: no create, no new cost", () => {
68 const made = { ...want, remote: "x", monthlyCents: 1500, createdAt: "" };
69 const p = planDatabase(want, reads({ have: () => made }));
70 expect(p.steps.map((s) => s.kind)).toEqual(["bind"]);
71 expect(p.deltaCents).toBe(0);
72 });
73 });
74
75 describe("managed database build", () => {
76 let dataDir = "";
77 let app: App;
78 const admin = () => getUserByName(app.db, "alice")!;
79 const calls: string[] = [];
80 let status = "creating";
81 const DB_URL = "postgresql://doadmin:[email protected]:25060/defaultdb?sslmode=require";
82 const saved = { everyMs: DB_WAIT.everyMs, sleep: DB_WAIT.sleep };
83 const fake = async (url: string, init?: RequestInit): Promise<Response> => {
84 const u = new URL(url);
85 calls.push(`${init?.method ?? "GET"} ${u.pathname}${u.search}`);
86 const json = (b: unknown) => new Response(JSON.stringify(b), { status: 200 });
87 if (init?.method === "POST") return json({ database: { id: "db-1" } });
88 if (u.pathname === "/v2/databases") return json({ databases: [] });
89 return json({ database: { status, connection: { uri: DB_URL } } });
90 };
91 const ask = { name: "shopdb", where: "digitalocean/main@nyc3:db-s-1vcpu-1gb", app: "alice/shop" };
92
93 beforeAll(async () => {
94 dataDir = await mkdtemp(join(tmpdir(), "forge-managed-db-"));
95 app = createApp({ dataDir, port: 0 });
96 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
97 if (!made.ok) throw new Error(made.error);
98 const repo = await createRepo(app, admin(), { name: "shop", visibility: "private" });
99 if (!repo.ok) throw new Error(String(repo.error));
100 cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" } }), { status: 200 });
101 const added = await addAccount(app, admin(), "digitalocean", "main", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5");
102 if (!added.ok) throw new Error(String(added.error));
103 allowWrite(app, admin(), "digitalocean", "main", true);
104 net.fetch = fake;
105 DB_WAIT.everyMs = 1;
106 DB_WAIT.sleep = async () => {
107 status = "online";
108 };
109 }, 30_000);
110
111 afterAll(async () => {
112 DB_WAIT.everyMs = saved.everyMs;
113 DB_WAIT.sleep = saved.sleep;
114 app.close();
115 await rm(dataDir, { recursive: true, force: true });
116 });
117
118 test("only an admin plans or builds", async () => {
119 const other = { ...admin(), isAdmin: false };
120 expect(planManagedDatabase(app, other, ask)).toEqual({ ok: false, error: "not_found" });
121 expect(await buildManagedDatabase(app, other, ask, "plan-db-x")).toEqual({ ok: false, error: "not_found" });
122 });
123
124 test("a build of a plan other than the one shown is refused before the cloud is asked", async () => {
125 const r = await buildManagedDatabase(app, admin(), ask, "plan-db-0000");
126 expect(r.ok).toBe(false);
127 expect(calls).toEqual([]);
128 });
129
130 test("the build makes the database once, waits for online, and binds the URL as the app's secret", async () => {
131 const p = planManagedDatabase(app, admin(), ask);
132 if (!p.ok) throw new Error(p.error);
133 const r = await buildManagedDatabase(app, admin(), ask, p.value.id);
134 expect(r).toMatchObject({ ok: true });
135 expect(JSON.stringify(r)).not.toContain("s3cretpw");
136 expect(calls.filter((c) => c.startsWith("POST"))).toEqual(["POST /v2/databases"]);
137 const repo = getRepo(app.db, "alice", "shop")!;
138 expect(resolveSecrets(app.db, dataDir, app.bus, ["DATABASE_URL"], { repo: repo.id })["DATABASE_URL"]).toBe(DB_URL);
139 const events = app.db.query<{ payload: string }, []>("SELECT payload FROM event WHERE kind = 'infra.step' ORDER BY seq").all().map((e) => e.payload);
140 expect(events.every((e) => !e.includes("s3cretpw"))).toBe(true);
141 expect(events.map((e) => JSON.parse(e)).filter((e) => e.state === "done").map((e) => e.index)).toEqual([0, 1, 2]);
142 // The ceiling now counts it.
143 expect(accountCents(app.db, "digitalocean", "main")).toBe(1500);
144 });
145
146 test("building again makes nothing more and re-binds", async () => {
147 const again = planManagedDatabase(app, admin(), ask);
148 if (!again.ok) throw new Error(again.error);
149 expect(again.value.steps.map((s) => s.kind)).toEqual(["bind"]);
150 const before = calls.filter((c) => c.startsWith("POST")).length;
151 expect((await buildManagedDatabase(app, admin(), ask, again.value.id)).ok).toBe(true);
152 expect(calls.filter((c) => c.startsWith("POST")).length).toBe(before);
153 });
154 });
test/timers-named.test.ts +1
@@ -109,6 +109,7 @@ const ALLOWED: readonly Allowed[] = [
109109 ...allow("setInterval", "a worker VM's minute memory line: it runs in the worker, where the main process's span ring is not reachable, and reads two counters", [["src/perf/memory_watch.ts", "() => write(workerMemoryLine("]]),
110110 ...allow("setTimeout", "the loop-lag meter's own tick: it measures how late the loop runs, and a span around it would count that lateness as its own work", [["src/kernel/loop_lag.ts", "() => { // Early"]]),
111111 ...allow("setTimeout", "the next slice of a sliced flow computation: one span per slice would fill the 256-span ring in one refresh", [["src/system/flow_cache.ts", "fn"]]),
112 ...allow("setTimeout", `the managed database build's wait between looks: ${SLEEP}`, [["src/actions/database.ts", "r"]]),
112113 ...allow("setTimeout", "the release prover's scheduler seam: its caller passes a callback already inside during(\"release-prove\")", [["src/release/prove.ts", "fn"]]),
113114 ...allow("setTimeout", "track() only holds the round's promise; the round itself runs inside during(\"probes\")", [["src/contract/probes.ts", "() => { void track(during("]]),
114115 ...allow("setTimeout", "a machine's load deadline: it only resolves the race when the machine does not answer, no work of its own; the beat itself runs inside during(\"machine-beats\")", [["src/spawn/machine_load.ts", "() => resolve(undefined)"]]),

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

Keyboard shortcuts

Docs