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

An infrastructure plan: steps, cost against each ceiling, time to ready, refusals, and a resumable apply #16701

Closed opened this
Closed without merging

sold/infra-plan → main 2 commits

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +1301 −16
src/actions/pinned.ts +8 −11
@@ -38,10 +38,10 @@ import { MAX_ID, keptPlaces, pinOf } from "../cloud/places_read.ts";
3838 import { keptRate } from "../cloud/rates.ts";
3939 import { deleteARecord, upsertARecord, type Fetch } from "../cloud/providers.ts";
4040 import { target as targetOf } from "../cloud/targets.ts";
41 import { getCloudAccount, listCloudAccounts, secretNameOf } from "../core/cloud_account.ts";
41 import { getCloudAccount, listCloudAccounts, NO_ACCOUNT, READ_ONLY, secretNameOf } from "../core/cloud_account.ts";
4242 import { FIRST_ADMIN_SEED_TTL_MS, firstAdminLink, newFirstAdminCode, type SeedState } from "../core/first_admin.ts";
4343 import {
44 APP, CLAIMED_REFUSAL, NAME, changesOf, checkConfig, dnsRecordOf, getPinned, insertPinned, listPinned, placeIdOf, previousOf,
44 APP, CLAIMED_REFUSAL, HOST_NEEDED, NAME, NAME_TAKEN, changesOf, checkConfig, dnsRecordOf, getPinned, insertPinned, listPinned, placeIdOf, previousOf,
4545 dnsOf, dropDns, dropPinned, keepDns, markClaimed, markReached, recordChange, setClaim, setHost, setRemote, urlOf, validHost, validSource, validVersion, unconfirmedRefusal, type Change, type Pinned,
4646 } from "../core/pinned.ts";
4747 import { resolveSecrets } from "../core/secret_store.ts";
@@ -203,7 +203,6 @@ const HOST_WORDS = "A hostname is a full DNS name you control, such as forge.exa
203203 const RETIRED_REFUSAL = "This forge was retired: its machine is gone. Deploy it again, under a new name, to run it.";
204204 const RETIRE_CLAIMED =
205205 "This forge was handed to its buyer: its data is on that volume, and retiring it deletes their forge. If you mean to, retire it again and say so (despiteClaim); this forge will not retire it otherwise.";
206 const HOST_NEEDED = "Name the host the forge is served on, such as forge.example.com; or set a domain for deployed forges on Pinned forges, and each is served on <name>.<domain> with no hostname given.";
207206 const NAMELESS = "This forge was deployed before forges had names: issue a claim for it with a hostname first.";
208207
209208 /**
@@ -340,8 +339,8 @@ export function fileForge(app: App, actor: User | undefined, name: string): Prom
340339 /** Open the account's token and run `go` with a gated fetch; the token never leaves this scope. */
341340 async function withCloud<T>(app: App, who: Who, p: Pinned, purpose: string, go: (f: Fetch, token: string) => Promise<T>, writes = true): Promise<Result<T, string>> {
342341 const account = getCloudAccount(app.db, p.target, p.account);
343 if (!account) return err("No such cloud account.");
344 if (writes && !account.writeAllowed) return err("That cloud account is read-only; allow writes on it first.");
342 if (!account) return err(NO_ACCOUNT);
343 if (writes && !account.writeAllowed) return err(READ_ONLY);
345344 // A create is priced from the Places catalog (`cloud/ceiling.ts`): read again here when it is
346345 // stale or was never read, so a forge nobody has opened Places on still knows what things cost.
347346 if (writes) await refreshIfDue(app, who);
@@ -453,7 +452,7 @@ async function deployAs(app: App, who: Who, input: DeployInput): Promise<Result<
453452 // A first deploy that failed before any droplet exists may be tried again: its row goes,
454453 // its volume (if one was made) is kept for the retry, and the new deploy is recorded afresh.
455454 const old = getPinned(app.db, input.name);
456 if (old && !(old.state === "failed" && old.remote === "" && old.target === t.id)) return err("A pinned forge has that name already.");
455 if (old && !(old.state === "failed" && old.remote === "" && old.target === t.id)) return err(NAME_TAKEN);
457456 // Where it is made: the place asked for, else the catalog's default. A volume the earlier try made
458457 // lives in one datacenter, so the retry stays there.
459458 let asked = (input.place ?? "").trim();
@@ -847,8 +846,6 @@ const madeBy = (app: App, name: string, who: Who): boolean => {
847846 return p !== undefined && changesOf(app.db, p.id).at(-1)?.by === who.by;
848847 };
849848
850 const NOT_THE_ORDERS = "A pinned forge has that name already.";
851
852849 /**
853850 * A paid order's forge, deployed as the order (#16205): the checks, catalog, ceiling, DNS and
854851 * claim of an admin's deploy, recorded as `order:<id>`. Never a second machine for one order: a
@@ -862,7 +859,7 @@ export async function deployForOrder(app: App, orderId: string, input: DeployInp
862859 const who = orderWho(orderId);
863860 const old = getPinned(app.db, input.name);
864861 if (old === undefined) return deployAs(app, who, input);
865 if (!madeBy(app, input.name, who)) return err(NOT_THE_ORDERS);
862 if (!madeBy(app, input.name, who)) return err(NAME_TAKEN);
866863 if (old.state === "retired") return err(RETIRED_REFUSAL);
867864 if (old.remote !== "") return oneChange(app, input.name, () => claimNow(app, who, input.name, {}));
868865 setRemote(app.db, old.name, { state: "failed" });
@@ -894,8 +891,8 @@ export function deployRoom(app: App, provider: string, account: string, plan: Pl
894891 const t = targetOf(provider);
895892 if (t === undefined || t.status !== "first") return "That is not a target the forge knows.";
896893 const a = getCloudAccount(app.db, provider, account);
897 if (a === undefined) return "No such cloud account.";
898 if (!a.writeAllowed) return "That cloud account is read-only; allow writes on it first.";
894 if (a === undefined) return NO_ACCOUNT;
895 if (!a.writeAllowed) return READ_ONLY;
899896 if (getBaseDomain(app.db) === "") return HOST_NEEDED;
900897 const at = pickPlace(app, provider, asked, plan);
901898 if (!at.ok) return at.error;
src/cloud/ceiling.ts +36 −5
@@ -173,21 +173,52 @@ export function refusalAt(
173173 /** What orders in flight will cost, not yet in any row. */
174174 held = 0,
175175 ): string | undefined {
176 const { ceilingDollars, monthlyCents } = spendOf(app.db, provider, account, prices);
177 return refusalOf({
178 provider, account, place, counted, held, ceilingDollars, monthlyCents,
179 orphan: orphanRefusal(app.db, provider, account),
180 price: prices.forge(place.id),
181 closed: prices.closed(place.id),
182 });
183 }
184
185 /** What `refusalOf` judges: the account's standing and the place's price, already read. */
186 export interface Standing {
187 readonly provider: string;
188 readonly account: string;
189 readonly place: { readonly id: string; readonly size: string; readonly datacenter: string };
190 /** The orphan refusal standing on the account (`orphanRefusal`), if any. */
191 readonly orphan: string | undefined;
192 /** The place's price, US cents a month rounded up (`Priced.forge`); undefined when the catalog has none. */
193 readonly price: number | undefined;
194 /** Why the place cannot be ordered now (`Priced.closed`). */
195 readonly closed: string | undefined;
196 readonly ceilingDollars: number;
197 readonly monthlyCents: number;
198 /** What a row is already counted at. */
199 readonly counted: number;
200 /** What creates ahead of this one, in no row yet, will cost. */
201 readonly held: number;
202 }
203
204 /**
205 * The ceiling's judgement on facts already read, in the sentences every door shows: an orphan on
206 * the account, no price, a place that cannot be ordered, then the ceiling. `refusalAt` reads the
207 * facts for one create; the infrastructure plan (`plan.ts`) reads them once for many.
208 */
209 export function refusalOf(s: Standing): string | undefined {
176210 // The hourly watch saw something at the provider the forge cannot account for: nothing more is
177211 // made.
178 const orphan = orphanRefusal(app.db, provider, account);
179 if (orphan !== undefined) return orphan;
212 if (s.orphan !== undefined) return s.orphan;
213 const { provider, account, place, price, closed, ceilingDollars, monthlyCents, counted, held } = s;
180214 const who = `${provider}/${account}`;
181215 const id = place.id;
182 const price = prices.forge(id);
183216 if (price === undefined)
184217 return (
185218 `The forge has no price for ${place.size} in ${place.datacenter} on ${provider}, so it cannot hold ${who} to its ceiling; nothing was made. ` +
186219 "Prices come from the provider's own list (Places, GET /api/v1/places), which the forge reads before a create and could not read a price from; try again in a few minutes."
187220 );
188 const closed = prices.closed(id);
189221 if (closed !== undefined) return `${id} cannot be ordered now: ${closed}; nothing was made, and a running machine was not touched. Pick another place, or try again later.`;
190 const { ceilingDollars, monthlyCents } = spendOf(app.db, provider, account, prices);
191222 const add = price - counted;
192223 if (add <= 0 || monthlyCents + held + add <= ceilingDollars * 100) return undefined;
193224 return (
src/cloud/plan.ts added +645
@@ -0,0 +1,645 @@
1 /**
2 * The infrastructure plan (#16696, phase 1b): what a person wants built on their own cloud
3 * accounts, compared with what the forge already made there, gives the steps that would run, what
4 * each account costs a month before and after against its ceiling, the time to ready, and every
5 * refusal, before anything is made. Plan before money: nothing is built from a plan with a
6 * refusal, and `apply` checks again against what stands now before the first step.
7 *
8 * `plan` is pure: what exists (`Have`) and what the forge holds (`Reads`) are handed in, so every
9 * sum and refusal is testable without a database or a cloud. Its refusals are the ceiling's own
10 * sentences (`refusalOf`) and the deploy's, never a second wording. `readInfra` reads both from the
11 * forge.
12 *
13 * `apply` runs the steps through the pinned deploy and retire (`actions/pinned.ts`); it makes no
14 * provider call of its own. Each step is one `infra.step` event (started, done or failed) on the
15 * outbox, which is durable, so a page, the terminal and Talk can all follow the same ones. Whether
16 * a step is done is read from what exists (the row's volume and machine, the watch's DNS and answer
17 * times, the experiment link, a retired row), never from a log of what ran: a run that stopped on
18 * a failure, or with the process, is finished by applying the same plan again, which skips what
19 * exists. The forge has no generic job queue (timers call apps over HTTP), so this is the job: the
20 * plan is the intent, reality is the progress, the outbox is the record.
21 *
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.
24 */
25
26 import type { App } from "../app.ts";
27 import { deployPinned, retirePinned } from "../actions/pinned.ts";
28 import { stuckWords, WATCH } from "../actions/pinned_watch.ts";
29 import { getCloudAccount, listCloudAccounts, NO_ACCOUNT, READ_ONLY } from "../core/cloud_account.ts";
30 import { dnsOf, getPinned, HOST_NEEDED, listPinned, NAME_TAKEN, placeIdOf, type Pinned } from "../core/pinned.ts";
31 import { watchOf } from "../core/pinned_watch.ts";
32 import type { User } from "../core/users.ts";
33 import { err, ok, type Result } from "../kernel/result.ts";
34 import { getBaseDomain } from "../settings/pinned_domain.ts";
35 import { accountCents, priced, refusalOf, rowCents } from "./ceiling.ts";
36 import { attachMachine, EXPERIMENT_WORDS, experiments } from "./experiments.ts";
37 import { VOLUME_GIB } from "./places.ts";
38 import { dollars } from "./prices.ts";
39 import { orphanRefusal } from "./watch_read.ts";
40
41 /** A machine with its data disk and public address at a place, running an app from a source. */
42 export interface MachineWant {
43 readonly kind: "machine";
44 /** The pinned forge's name, which is its identity: one resource a name. */
45 readonly name: string;
46 /** The cloud account it is made on, `provider/name`. */
47 readonly account: string;
48 /** A Places id, `provider:datacenter:size`. */
49 readonly place: string;
50 /** What it is for: the app it runs, `owner/name`. */
51 readonly app: string;
52 /** The https git address it boots from; empty runs this forge's own code. */
53 readonly source: string;
54 /** A full commit or a release tag; absent runs the commit this forge runs. */
55 readonly version?: string | undefined;
56 /** The name it is served on; absent is `<name>.<domain for deployed forges>`. */
57 readonly host?: string | undefined;
58 /** When it ends, ISO. Carried for lifetimes (phase 1a); this pull records no end. */
59 readonly endsAt?: string | undefined;
60 /** The experiment whose question it runs. */
61 readonly experimentId?: string | undefined;
62 }
63
64 export type Want = MachineWant;
65
66 /** A machine the forge made (a pinned row), as the plan needs it. */
67 export interface MachineHave {
68 readonly kind: "machine";
69 readonly name: string;
70 readonly account: string;
71 readonly place: string;
72 readonly app: string;
73 readonly source: string;
74 readonly version: string;
75 readonly host: string;
76 /** The row's state: running, failed, retired… */
77 readonly state: string;
78 /** What exists of it: the volume, the machine, its DNS record, an answer over HTTPS. */
79 readonly volume: boolean;
80 readonly machine: boolean;
81 readonly dns: boolean;
82 readonly answered: boolean;
83 /** The experiment it is on now; empty for none. */
84 readonly experiment: string;
85 /** What it costs a month now, and once retired with its data kept, US cents (`rowCents`). */
86 readonly cents: number;
87 readonly keptCents: number;
88 }
89
90 export type Have = MachineHave;
91
92 /** One cloud account as the plan reads it. */
93 export interface AccountRead {
94 readonly writable: boolean;
95 readonly ceilingDollars: number;
96 /** What the forge reckons it costs a month now, US cents (`accountCents`). */
97 readonly monthlyCents: number;
98 /** The orphan refusal standing on it (`orphanRefusal`), if any. */
99 readonly orphan?: string | undefined;
100 }
101
102 /** What the forge holds, handed to `plan` so it reads nothing itself. */
103 export interface Reads {
104 /** Undefined for an account the forge does not hold. */
105 account(account: string): AccountRead | undefined;
106 /** A place's price a month, US cents rounded up (`Priced.forge`); undefined when it has none. */
107 price(place: string): number | undefined;
108 /** Why a place cannot be ordered now (`Priced.closed`). */
109 closed(place: string): string | undefined;
110 /** The name a forge called `name` would be served on, `asked` winning; empty when there is none. */
111 host(name: string, asked: string): string;
112 /** Whether an attached Cloudflare account that allows writes can write the DNS record. */
113 readonly dnsAuto: boolean;
114 /** Undefined for no such experiment. */
115 experiment(id: string): { readonly state: "running" | "done"; readonly question: string } | undefined;
116 }
117
118 export type StepKind = "disk" | "machine" | "attach" | "dns" | "ready" | "retire";
119
120 export interface Step {
121 readonly index: number;
122 readonly kind: StepKind;
123 /** The resource the step is for. */
124 readonly name: string;
125 readonly account: string;
126 /** The step in a sentence, as every door shows it. */
127 readonly says: string;
128 /** What it changes a month, US cents: a machine's whole price (disk and address in it), a retire's saving negative. */
129 readonly cents: number;
130 }
131
132 export interface AccountVerdict {
133 readonly account: string;
134 readonly beforeCents: number;
135 /** After every step the plan asks of the account, refused creates included, so the tray says by how much. */
136 readonly afterCents: number;
137 readonly ceilingCents: number;
138 /** Nothing the plan asks of this account is refused. */
139 readonly fits: boolean;
140 }
141
142 export interface Refusal {
143 /** The resource refused. */
144 readonly name: string;
145 readonly why: string;
146 }
147
148 export interface Plan {
149 /** Stable for the same wants: a rerun of a plan is the same plan. */
150 readonly id: string;
151 readonly wants: readonly Want[];
152 /** The wants are the whole of it: what exists and is not wanted is retired. */
153 readonly complete: boolean;
154 readonly steps: readonly Step[];
155 readonly byAccount: readonly AccountVerdict[];
156 readonly deltaCents: number;
157 readonly etaSeconds: number;
158 readonly refusals: readonly Refusal[];
159 }
160
161 /**
162 * Seconds from the create to an answer over HTTPS, by provider. No deploy times are measured yet
163 * (the watch keeps each step's time in `pinned_watch`, but no log or test holds real ones), so
164 * these are conservative: cloud-init installs Bun, fetches the source, installs the crew's CLI,
165 * and the proxy gets a certificate once the name resolves, all inside the watch's own bound of
166 * 300 s (`WATCH.boundMs`), OVHcloud at that bound for its slower instance creates. Replace with
167 * the medians of `pinned_watch.answered_at - started_at` once there are some.
168 */
169 const BOOT_SECONDS: Readonly<Record<string, number>> = { digitalocean: 240, hetzner: 240, ovh: 300 };
170 const BOOT_DEFAULT = 300;
171 /** The provider calls of one create (volume, machine, address, record) or one retire. */
172 const CALL_SECONDS = 20;
173 const RETIRE_SECONDS = 30;
174
175 const providerOf = (account: string): string => account.slice(0, Math.max(0, account.indexOf("/")));
176 const partsOf = (place: string): { provider: string; datacenter: string; size: string } => {
177 const [provider = "", datacenter = "", size = ""] = place.split(":");
178 return { provider, datacenter, size };
179 };
180 const versionWords = (v: string | undefined): string =>
181 v === undefined || v === "" ? "this forge's own commit" : /^[0-9a-f]{40}$/.test(v) ? v.slice(0, 7) : v;
182
183 /** Whether an existing row is the machine this want describes, so nothing new is made for it. */
184 const same = (w: MachineWant, h: MachineHave): boolean =>
185 h.account === w.account &&
186 h.place === w.place &&
187 h.app === w.app &&
188 (w.source === "" || h.source === w.source) &&
189 (w.version === undefined || h.version === w.version);
190
191 /**
192 * What would run for `wants` given what exists, and what it costs. Without `complete`, what exists
193 * and is not wanted is left alone; with it, each such machine is retired, its data kept (deleting
194 * data stays the typed-name confirm on its own page). Creates come before retires, and the
195 * ceiling is checked on the creates without the retires' savings, as the deploy itself will.
196 */
197 export function plan(wants: readonly Want[], have: readonly Have[], reads: Reads, o: { complete?: boolean } = {}): Plan {
198 const complete = o.complete === true;
199 const byName = new Map(have.map((h) => [h.name, h]));
200 const creates: Step[] = [];
201 const waits: Step[] = [];
202 const retires: Step[] = [];
203 const refusals: Refusal[] = [];
204 const accounts = new Map<string, { before: number; after: number; ceiling: number; held: number; refused: boolean }>();
205 const boots: number[] = [];
206 const seen = new Set<string>();
207 let calls = 0;
208
209 const ledger = (account: string, a: AccountRead) => {
210 let l = accounts.get(account);
211 if (!l)
212 accounts.set(
213 account,
214 (l = { before: a.monthlyCents, after: a.monthlyCents, ceiling: a.ceilingDollars * 100, held: 0, refused: false }),
215 );
216 return l;
217 };
218 const refuse = (name: string, why: string, account?: string): void => {
219 refusals.push({ name, why });
220 const l = account === undefined ? undefined : accounts.get(account);
221 if (l) l.refused = true;
222 };
223 const step = (list: Step[], s: Omit<Step, "index">) => list.push({ ...s, index: 0 });
224
225 for (const w of wants) {
226 if (seen.has(w.name)) {
227 refuse(w.name, NAME_TAKEN);
228 continue;
229 }
230 seen.add(w.name);
231 const h = byName.get(w.name);
232 const a = reads.account(w.account);
233 if (a === undefined) {
234 refuse(w.name, NO_ACCOUNT);
235 continue;
236 }
237 const l = ledger(w.account, a);
238 // A row of this name that is not this machine, or is retired, holds the name; one whose first
239 // deploy failed before its machine existed is finished on the volume it may have made.
240 const retry = h !== undefined && h.state === "failed" && !h.machine && h.account === w.account && h.place === w.place;
241 if (h !== undefined && !retry && (h.state === "retired" || !same(w, h))) {
242 refuse(w.name, NAME_TAKEN, w.account);
243 continue;
244 }
245 if (!a.writable) {
246 refuse(w.name, READ_ONLY, w.account);
247 continue;
248 }
249 const at = partsOf(w.place);
250 if (at.provider !== providerOf(w.account)) {
251 refuse(
252 w.name,
253 `${w.place} is on ${at.provider}, and ${w.account} is on ${providerOf(w.account)}: name one of ${providerOf(w.account)}'s places.`,
254 w.account,
255 );
256 continue;
257 }
258 const host = h !== undefined && h.host !== "" ? h.host : reads.host(w.name, w.host ?? "");
259 if (host === "") {
260 refuse(w.name, HOST_NEEDED, w.account);
261 continue;
262 }
263 const exp = w.experimentId === undefined ? undefined : reads.experiment(w.experimentId);
264 if (w.experimentId !== undefined && exp?.state !== "running") {
265 refuse(w.name, exp === undefined ? EXPERIMENT_WORDS.no_experiment : EXPERIMENT_WORDS.done, w.account);
266 continue;
267 }
268 const make = h === undefined || retry;
269 if (make) {
270 const price = reads.price(w.place);
271 const counted = h?.cents ?? 0;
272 const no = refusalOf({
273 provider: at.provider,
274 account: w.account.slice(at.provider.length + 1),
275 place: { id: w.place, size: at.size, datacenter: at.datacenter },
276 orphan: a.orphan,
277 price,
278 closed: reads.closed(w.place),
279 ceilingDollars: a.ceilingDollars,
280 monthlyCents: a.monthlyCents,
281 counted,
282 held: l.held,
283 });
284 const add = price === undefined ? 0 : Math.max(0, price - counted);
285 // A create refused for its price still shows in the sum, so the tray can say by how much.
286 l.after += add;
287 if (no !== undefined) {
288 refuse(w.name, no, w.account);
289 continue;
290 }
291 l.held += add;
292 if (h?.volume !== true)
293 step(creates, {
294 kind: "disk",
295 name: w.name,
296 account: w.account,
297 says: `Create a ${VOLUME_GIB} GiB disk in ${at.datacenter} on ${w.account}`,
298 cents: 0,
299 });
300 step(creates, {
301 kind: "machine",
302 name: w.name,
303 account: w.account,
304 cents: add,
305 says: `Start the ${at.size} machine in ${at.datacenter} with ${w.app} at ${versionWords(w.version)}, ${dollars(add)} a month with its disk and address`,
306 });
307 calls += 1;
308 }
309 if (exp !== undefined && w.experimentId !== undefined && h?.experiment !== w.experimentId)
310 step(creates, {
311 kind: "attach",
312 name: w.name,
313 account: w.account,
314 says: `Put ${w.name} on the experiment "${exp.question}"`,
315 cents: 0,
316 });
317 if (make || h?.dns !== true)
318 step(waits, {
319 kind: "dns",
320 name: w.name,
321 account: w.account,
322 cents: 0,
323 says: reads.dnsAuto
324 ? `Write ${host} → its address in Cloudflare`
325 : `Point ${host} at its address by hand: no Cloudflare account that allows writes can`,
326 });
327 if (make || h?.answered !== true) {
328 step(waits, { kind: "ready", name: w.name, account: w.account, says: `Wait until ${host} answers over HTTPS`, cents: 0 });
329 boots.push(BOOT_SECONDS[at.provider] ?? BOOT_DEFAULT);
330 }
331 }
332
333 if (complete)
334 for (const h of have) {
335 if (seen.has(h.name) || h.state === "retired") continue;
336 const a = reads.account(h.account);
337 if (a === undefined) {
338 refuse(h.name, NO_ACCOUNT);
339 continue;
340 }
341 const l = ledger(h.account, a);
342 if (!a.writable) {
343 refuse(h.name, READ_ONLY, h.account);
344 continue;
345 }
346 const saves = h.keptCents - h.cents;
347 l.after += saves;
348 step(retires, {
349 kind: "retire",
350 name: h.name,
351 account: h.account,
352 cents: saves,
353 says: `Retire ${h.name}: delete its machine and keep its disk, ${dollars(-saves)} a month less`,
354 });
355 }
356
357 const steps = [...creates, ...waits, ...retires].map((s, index) => ({ ...s, index }));
358 const byAccount = [...accounts].map(([account, l]) => ({
359 account,
360 beforeCents: l.before,
361 afterCents: l.after,
362 ceilingCents: l.ceiling,
363 fits: !l.refused,
364 }));
365 const hash = new Bun.CryptoHasher("sha256").update(JSON.stringify({ wants, complete })).digest("hex").slice(0, 16);
366 return {
367 id: `plan-${hash}`,
368 wants,
369 complete,
370 steps,
371 byAccount,
372 deltaCents: byAccount.reduce((s, a) => s + a.afterCents - a.beforeCents, 0),
373 etaSeconds: calls * CALL_SECONDS + (boots.length === 0 ? 0 : Math.max(...boots)) + retires.length * RETIRE_SECONDS,
374 refusals,
375 };
376 }
377
378 /** What exists of a resource now, read for `apply`; undefined when there is no row. */
379 export interface Facts {
380 readonly state: string;
381 readonly volume: boolean;
382 readonly machine: boolean;
383 readonly address: boolean;
384 readonly dns: boolean;
385 readonly answered: boolean;
386 /** The watch gave up (`stuckWords`); empty while it still waits. */
387 readonly stuck: string;
388 /** The experiment it is on now; empty for none. */
389 readonly experiment: string;
390 }
391
392 /** One `infra.step` event's payload. */
393 export interface StepEvent {
394 readonly planId: string;
395 readonly index: number;
396 readonly state: "started" | "done" | "failed";
397 readonly says: string;
398 readonly why?: string;
399 }
400
401 /** What `apply` does to the world; the forge's own (`handsOf`) unless a test hands in others. */
402 export interface Hands {
403 /** The same wants planned again against what stands now. */
404 replan(p: Plan): Plan;
405 deploy(w: MachineWant): Promise<Result<unknown, string>>;
406 retire(name: string): Promise<Result<unknown, string>>;
407 attach(experimentId: string, name: string): Result<void, string>;
408 facts(name: string): Facts | undefined;
409 emit(e: StepEvent): void;
410 sleep(): Promise<void>;
411 now(): number;
412 }
413
414 export interface Applied {
415 readonly planId: string;
416 /** Steps this run did, and those it found done already. */
417 readonly done: readonly number[];
418 readonly skipped: readonly number[];
419 /** The step it stopped on; absent when every step is done. */
420 readonly failed?: { readonly index: number; readonly why: string };
421 }
422
423 /** How long `apply` waits on the watch for DNS and an answer before it fails the step. */
424 const waitBoundMs = (): number => WATCH.boundMs + 2 * WATCH.everyMs;
425
426 const doneBy = (s: Step, w: Want | undefined, f: Facts | undefined): boolean => {
427 if (s.kind === "retire") return f === undefined || f.state === "retired";
428 if (f === undefined) return false;
429 switch (s.kind) {
430 case "disk":
431 return f.volume;
432 case "machine":
433 return f.machine;
434 case "attach":
435 return w?.experimentId !== undefined && f.experiment === w.experimentId;
436 case "dns":
437 return f.dns || f.answered;
438 case "ready":
439 return f.answered;
440 }
441 };
442
443 /**
444 * Build what `p` plans, step by step, each one an `infra.step` event. Refused outright when the
445 * plan has refusals, or when planned again now it has some or costs any account more than it said:
446 * the person builds only what they saw. A step already done (`Facts`) is skipped; the first that
447 * fails stops the run with the cloud's or the deploy's own words, and applying the same plan again
448 * takes up from there. Disk and machine are made by one deploy, so both start together; DNS and
449 * the answer are read from the forge's own watch (`actions/pinned_watch.ts`) at its pace.
450 */
451 export async function apply(
452 app: App,
453 actor: User | undefined,
454 p: Plan,
455 hands: Hands = handsOf(app, actor),
456 ): Promise<Result<Applied, string>> {
457 if (actor?.isAdmin !== true) return err("not_found");
458 if (p.refusals.length > 0) return err(`This plan has refusals, so nothing was built: ${p.refusals.map((r) => r.why).join(" ")}`);
459 const now = hands.replan(p);
460 if (now.refusals.length > 0)
461 return err(`Since the plan was shown: ${now.refusals.map((r) => r.why).join(" ")} Nothing was built; look at the plan again.`);
462 const shown = new Map(p.byAccount.map((a) => [a.account, a.afterCents]));
463 const dearer = now.byAccount.find((a) => a.afterCents > (shown.get(a.account) ?? a.beforeCents));
464 if (dearer !== undefined)
465 return err(
466 `${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.`,
467 );
468
469 const wants = new Map(p.wants.map((w) => [w.name, w]));
470 const done: number[] = [];
471 const skipped: number[] = [];
472 const say = (s: Step, state: StepEvent["state"], why?: string) =>
473 hands.emit({ planId: p.id, index: s.index, state, says: s.says, ...(why === undefined ? {} : { why }) });
474 const finished = (s: Step) => doneBy(s, wants.get(s.name), hands.facts(s.name));
475 const failed = (s: Step, why: string): Result<Applied, string> => {
476 say(s, "failed", why);
477 return ok({ planId: p.id, done, skipped, failed: { index: s.index, why } });
478 };
479
480 for (let i = 0; i < p.steps.length; i++) {
481 const s = p.steps[i]!;
482 if (finished(s)) {
483 skipped.push(s.index);
484 continue;
485 }
486 if (s.kind === "disk" || s.kind === "machine") {
487 // One deploy makes both: the disk (unless a failed try left one) and the machine.
488 const group = [s];
489 const next = p.steps[i + 1];
490 if (s.kind === "disk" && next?.kind === "machine" && next.name === s.name && !finished(next)) group.push(next);
491 for (const g of group) say(g, "started");
492 const r = await hands.deploy(wants.get(s.name)!);
493 for (const g of group) {
494 if (!finished(g)) return failed(g, r.ok ? `The deploy answered, and ${s.name} has no ${g.kind} yet.` : r.error);
495 say(g, "done");
496 done.push(g.index);
497 }
498 i += group.length - 1;
499 } else if (s.kind === "attach") {
500 say(s, "started");
501 const r = hands.attach(wants.get(s.name)!.experimentId!, s.name);
502 if (!r.ok) return failed(s, r.error);
503 say(s, "done");
504 done.push(s.index);
505 } else if (s.kind === "retire") {
506 say(s, "started");
507 const r = await hands.retire(s.name);
508 if (!finished(s)) return failed(s, r.ok ? `${s.name} is not retired yet.` : r.error);
509 say(s, "done");
510 done.push(s.index);
511 } else {
512 // The DNS and answer steps that follow are waited on together, as the watch looks at each.
513 const group: Step[] = [];
514 for (let j = i; j < p.steps.length && (p.steps[j]!.kind === "dns" || p.steps[j]!.kind === "ready"); j++) group.push(p.steps[j]!);
515 const pending = group.filter((g) => !finished(g));
516 for (const g of group) if (!pending.includes(g)) skipped.push(g.index);
517 for (const g of pending) say(g, "started");
518 const since = hands.now();
519 while (pending.length > 0) {
520 for (const g of [...pending]) {
521 const f = hands.facts(g.name);
522 if (doneBy(g, undefined, f)) {
523 say(g, "done");
524 done.push(g.index);
525 pending.splice(pending.indexOf(g), 1);
526 } else if (f === undefined || f.state === "retired") return failed(g, `${g.name} is gone.`);
527 else if (f.stuck !== "") return failed(g, f.stuck);
528 }
529 if (pending.length === 0) break;
530 if (hands.now() - since >= waitBoundMs()) {
531 const g = pending[0]!;
532 const f = hands.facts(g.name);
533 return failed(g, stuckWords(g.name, f?.address === true, f?.dns === true));
534 }
535 await hands.sleep();
536 }
537 i += group.length - 1;
538 }
539 }
540 return ok({ planId: p.id, done, skipped });
541 }
542
543 /** What exists and what the forge holds, from its database, for `plan`. */
544 export function readInfra(app: App): { have: Have[]; reads: Reads } {
545 const db = app.db;
546 const prices = priced(db);
547 const exps = experiments(db).items;
548 const have = listPinned(db).map((p): Have => {
549 const f = factsOf(app, p, exps);
550 return {
551 kind: "machine",
552 name: p.name,
553 account: `${p.target}/${p.account}`,
554 place: placeIdOf(p),
555 app: p.app,
556 source: p.source,
557 version: p.version,
558 host: p.host,
559 state: p.state,
560 volume: f.volume,
561 machine: f.machine,
562 dns: f.dns,
563 answered: f.answered,
564 experiment: f.experiment,
565 cents: rowCents(p, prices),
566 keptCents: rowCents({ ...p, state: "retired" }, prices),
567 };
568 });
569 const base = getBaseDomain(db);
570 const reads: Reads = {
571 account: (account) => {
572 const i = account.indexOf("/");
573 const provider = account.slice(0, Math.max(0, i));
574 const name = account.slice(i + 1);
575 const a = i > 0 ? getCloudAccount(db, provider, name) : undefined;
576 if (a === undefined) return undefined;
577 return {
578 writable: a.writeAllowed,
579 ceilingDollars: a.ceilingDollars,
580 monthlyCents: accountCents(db, provider, name, prices),
581 orphan: orphanRefusal(db, provider, name),
582 };
583 },
584 price: (place) => prices.forge(place),
585 closed: (place) => prices.closed(place),
586 host: (name, asked) => asked.trim().toLowerCase() || (base === "" ? "" : `${name}.${base}`),
587 dnsAuto: listCloudAccounts(db).some((a) => a.provider === "cloudflare" && a.writeAllowed),
588 experiment: (id) => {
589 const e = exps.find((x) => x.id === id);
590 return e === undefined ? undefined : { state: e.state, question: e.question };
591 },
592 };
593 return { have, reads };
594 }
595
596 function factsOf(app: App, p: Pinned, exps = experiments(app.db).items): Facts {
597 const w = watchOf(app.db, p.id);
598 const kept = dnsOf(app.db, p.id);
599 const on = exps.find((e) => e.machines.some((m) => m.name === p.name && m.until === ""));
600 return {
601 state: p.state,
602 volume: p.volume !== "",
603 machine: p.remote !== "",
604 address: p.address !== "",
605 dns: (w?.dnsAt ?? "") !== "" || (kept !== undefined && kept.host === p.host && kept.address === p.address && p.address !== ""),
606 answered: (w?.answeredAt ?? "") !== "",
607 stuck: w === undefined || w.gaveUpAt === "" ? "" : stuckWords(p.name, w.addressAt !== "", w.dnsAt !== ""),
608 experiment: on?.id ?? "",
609 };
610 }
611
612 /** The forge's own hands: the pinned deploy and retire as `actor`, the watch's facts, the outbox. */
613 function handsOf(app: App, actor: User | undefined): Hands {
614 return {
615 replan: (p) => {
616 const { have, reads } = readInfra(app);
617 return plan(p.wants, have, reads, { complete: p.complete });
618 },
619 deploy: (w) => {
620 const provider = providerOf(w.account);
621 return deployPinned(app, actor, {
622 name: w.name,
623 host: w.host ?? "",
624 target: provider,
625 account: w.account.slice(provider.length + 1),
626 app: w.app,
627 place: w.place,
628 ...(w.source === "" ? {} : { source: w.source }),
629 ...(w.version === undefined ? {} : { version: w.version }),
630 });
631 },
632 retire: (name) => retirePinned(app, actor, name),
633 attach: (id, name) => {
634 const r = attachMachine(app, actor!.id, id, name);
635 return r.ok ? ok(undefined) : err(EXPERIMENT_WORDS[r.error]);
636 },
637 facts: (name) => {
638 const p = getPinned(app.db, name);
639 return p === undefined ? undefined : factsOf(app, p);
640 },
641 emit: (e) => void app.bus.append({ kind: "infra.step", actorId: actor?.id, payload: { ...e } }),
642 sleep: () => WATCH.sleep(WATCH.everyMs),
643 now: () => Date.now(),
644 };
645 }
src/core/cloud_account.ts +5
@@ -44,6 +44,11 @@ export function accountOfSecret(
4444 : undefined;
4545 }
4646
47 /** A cloud call for an account the forge does not hold. */
48 export const NO_ACCOUNT = "No such cloud account.";
49 /** A create, retire or other write asked of an account attached read-only. */
50 export const READ_ONLY = "That cloud account is read-only; allow writes on it first.";
51
4752 export interface CloudAccount {
4853 readonly provider: Provider;
4954 readonly name: string;
src/core/pinned.ts +6
@@ -270,6 +270,12 @@ export const unconfirmedRefusal = (p: Pick<Pinned, "name" | "host" | "address">)
270270 `${p.name} has answered from this machine before and cannot be reached now, so this forge cannot confirm that nobody has claimed it; nothing was changed. ` +
271271 `Run Check until it says the forge answers (its name ${p.host} must resolve to ${p.address === "" ? "its machine" : p.address}), then ask again.`;
272272
273 /** A deploy under a name a pinned forge already holds: one forge a name, retired ones too. */
274 export const NAME_TAKEN = "A pinned forge has that name already.";
275
276 /** A deploy with no host asked for and no domain for deployed forges to make one from. */
277 export const HOST_NEEDED = "Name the host the forge is served on, such as forge.example.com; or set a domain for deployed forges on Pinned forges, and each is served on <name>.<domain> with no hostname given.";
278
273279 /** The sentence a refused Update, Rollback or new claim link gives after the claim. */
274280 export const CLAIMED_REFUSAL = "This forge was handed to its buyer: its updates are theirs to take, and this forge no longer changes it.";
275281
test/infra-plan-apply.test.ts added +149
@@ -0,0 +1,149 @@
1 /**
2 * The infrastructure plan on a real forge (#16696, phase 1b): `readInfra` reads the pinned rows,
3 * the catalog and the ceiling; `apply` builds through the pinned deploy and retire against a
4 * recorded cloud (no network), reads DNS and the answer from the watch's own rows, appends one
5 * `infra.step` event per step, and a second apply of the same plan asks nothing of the cloud.
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 { net } from "../src/actions/pinned.ts";
14 import { WATCH } from "../src/actions/pinned_watch.ts";
15 import { beginExperiment } from "../src/cloud/experiments.ts";
16 import { apply, plan, readInfra, type MachineWant } from "../src/cloud/plan.ts";
17 import { getPinned } from "../src/core/pinned.ts";
18 import { markStep, startWatchRow } from "../src/core/pinned_watch.ts";
19 import { createUser, getUserByName } from "../src/core/users.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21 import { recordCloud } from "./helpers/recorded-cloud.ts";
22 import { seedPlaces } from "./helpers/places-fixture.ts";
23
24 quietLogs();
25
26 describe("infrastructure plan on a forge", () => {
27 let dataDir = "";
28 let app: App;
29 const cloud = recordCloud();
30 const saved = { sleep: WATCH.sleep, everyMs: WATCH.everyMs };
31 const admin = () => getUserByName(app.db, "alice")!;
32 const want = (name: string, over: Partial<MachineWant> = {}): MachineWant => ({
33 kind: "machine",
34 name,
35 account: "digitalocean/main",
36 place: "digitalocean:nyc3:s-1vcpu-2gb",
37 app: "alice/shop",
38 source: "https://forge.example.org/alice/shop",
39 version: "a".repeat(40),
40 host: `${name}.forge.test`,
41 ...over,
42 });
43 const steps = () =>
44 app.db
45 .query<{ payload: string }, []>("SELECT payload FROM event WHERE kind = 'infra.step' ORDER BY seq")
46 .all()
47 .map((r) => JSON.parse(r.payload) as { index: number; state: string });
48
49 beforeAll(async () => {
50 dataDir = await mkdtemp(join(tmpdir(), "forge-infra-plan-"));
51 app = createApp({ dataDir, port: 0 });
52 await seedPlaces(app.db);
53 const made = await createUser(app.db, {
54 origin: "seed",
55 trusted: true,
56 username: "alice",
57 email: "[email protected]",
58 password: "a-good-passphrase",
59 adminIfFirst: true,
60 });
61 if (!made.ok) throw new Error(made.error);
62 cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" } }), { status: 200 });
63 const added = await addAccount(app, admin(), "digitalocean", "main", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5");
64 if (!added.ok) throw new Error(String(added.error));
65 allowWrite(app, admin(), "digitalocean", "main", true);
66 net.fetch = cloud.fetch;
67 // Nothing leaves the process: the name never resolves, so a retire asks the forge nothing.
68 net.resolve = async () => [];
69 // The watch is not armed in tests: each of its looks here records the record and the answer.
70 WATCH.everyMs = 1;
71 WATCH.sleep = async () => {
72 for (const p of readInfra(app).have) {
73 const row = getPinned(app.db, p.name)!;
74 if (row.remote === "" || p.answered) continue;
75 startWatchRow(app.db, row.id, new Date().toISOString());
76 markStep(app.db, row.id, "dnsAt", new Date().toISOString());
77 markStep(app.db, row.id, "answeredAt", new Date().toISOString());
78 }
79 };
80 }, 30_000);
81
82 afterAll(async () => {
83 WATCH.sleep = saved.sleep;
84 WATCH.everyMs = saved.everyMs;
85 app.close();
86 await rm(dataDir, { recursive: true, force: true });
87 });
88
89 test("the plan reads the catalog and the ceiling: one machine at $13 of $50", () => {
90 const { have, reads } = readInfra(app);
91 const p = plan([want("shop")], have, reads);
92 expect(p.refusals).toEqual([]);
93 expect(p.byAccount).toEqual([{ account: "digitalocean/main", beforeCents: 0, afterCents: 1300, ceilingCents: 5000, fits: true }]);
94 expect(p.steps.map((s) => s.kind)).toEqual(["disk", "machine", "dns", "ready"]);
95 // No Cloudflare account that allows writes: the record is by hand.
96 expect(p.steps[2]!.says).toBe("Point shop.forge.test at its address by hand: no Cloudflare account that allows writes can");
97 });
98
99 test("apply builds through the pinned deploy, puts it on its experiment, and says each step", async () => {
100 const exp = beginExperiment(app, admin().id, "Does a small droplet serve the shop?", []);
101 if (!exp.ok) throw new Error(exp.error);
102 const { have, reads } = readInfra(app);
103 const p = plan([want("shop", { experimentId: exp.value })], have, reads);
104 const before = cloud.calls.length;
105 const r = await apply(app, admin(), p);
106 expect(r).toEqual({ ok: true, value: { planId: p.id, done: [0, 1, 2, 3, 4], skipped: [] } });
107 expect(cloud.calls.length).toBeGreaterThan(before);
108 expect(getPinned(app.db, "shop")).toMatchObject({ state: "running", datacenter: "nyc3", size: "s-1vcpu-2gb", host: "shop.forge.test" });
109 expect(steps().map((e) => `${e.index}:${e.state}`)).toEqual([
110 "0:started",
111 "1:started",
112 "0:done",
113 "1:done",
114 "2:started",
115 "2:done",
116 "3:started",
117 "4:started",
118 "3:done",
119 "4:done",
120 ]);
121 const after = readInfra(app);
122 expect(after.have.find((h) => h.name === "shop")).toMatchObject({
123 machine: true,
124 dns: true,
125 answered: true,
126 experiment: exp.value,
127 cents: 1300,
128 });
129
130 // The same plan again: everything exists, nothing is asked of the cloud, nothing new is said.
131 const calls = cloud.calls.length;
132 const again = await apply(app, admin(), p);
133 expect(again).toEqual({ ok: true, value: { planId: p.id, done: [], skipped: [0, 1, 2, 3, 4] } });
134 expect(cloud.calls.length).toBe(calls);
135 expect(steps()).toHaveLength(10);
136 // And planned afresh, there is nothing left to do and nothing more to pay.
137 expect(plan(p.wants, after.have, after.reads).steps).toEqual([]);
138 });
139
140 test("a complete set retires what is not in it through the pinned retire, keeping its data", async () => {
141 const { have, reads } = readInfra(app);
142 const p = plan([], have, reads, { complete: true });
143 expect(p.steps.map((s) => `${s.kind}:${s.name}`)).toEqual(["retire:shop"]);
144 const r = await apply(app, admin(), p);
145 expect(r.ok && r.value.done).toEqual([0]);
146 expect(getPinned(app.db, "shop")).toMatchObject({ state: "retired", remote: "" });
147 expect(getPinned(app.db, "shop")!.volume).not.toBe("");
148 });
149 });
test/infra-plan.test.ts added +452
@@ -0,0 +1,452 @@
1 /**
2 * The infrastructure plan (#16696, phase 1b), pure: what would run for a set of wants against what
3 * exists, what each account costs before and after against its ceiling, the time to ready and
4 * every refusal in the forge's own words; then `apply` with fake hands: events in order, a failed
5 * step that stops the run, and a rerun that skips what exists. No database, no network.
6 */
7 import { describe, expect, test } from "bun:test";
8 import { refusalOf } from "../src/cloud/ceiling.ts";
9 import { EXPERIMENT_WORDS } from "../src/cloud/experiments.ts";
10 import {
11 apply,
12 plan,
13 type Facts,
14 type Hands,
15 type Have,
16 type MachineWant,
17 type Plan,
18 type Reads,
19 type StepEvent,
20 } from "../src/cloud/plan.ts";
21 import type { App } from "../src/app.ts";
22 import { NO_ACCOUNT, READ_ONLY } from "../src/core/cloud_account.ts";
23 import { HOST_NEEDED, NAME_TAKEN } from "../src/core/pinned.ts";
24 import type { User } from "../src/core/users.ts";
25 import { err, ok } from "../src/kernel/result.ts";
26
27 const NYC = "digitalocean:nyc3:s-1vcpu-2gb";
28 const FSN = "hetzner:fsn1:cx23";
29 const PRICES: Record<string, number> = { [NYC]: 1300, [FSN]: 520, "digitalocean:nyc3:s-2vcpu-4gb": 2500 };
30
31 type Acct = { writable?: boolean; ceilingDollars?: number; monthlyCents?: number; orphan?: string };
32 function reads(accounts: Record<string, Acct> = { "digitalocean/main": {}, "hetzner/main": {} }, over: Partial<Reads> = {}): Reads {
33 return {
34 account: (a) => {
35 const x = accounts[a];
36 return x === undefined
37 ? undefined
38 : { writable: x.writable ?? true, ceilingDollars: x.ceilingDollars ?? 50, monthlyCents: x.monthlyCents ?? 0, orphan: x.orphan };
39 },
40 price: (p) => PRICES[p],
41 closed: () => undefined,
42 host: (name, asked) => asked || `${name}.forges.test`,
43 dnsAuto: true,
44 experiment: (id) =>
45 id === "e1"
46 ? { state: "running", question: "Is Hetzner fast enough?" }
47 : id === "e2"
48 ? { state: "done", question: "Old" }
49 : undefined,
50 ...over,
51 };
52 }
53
54 const want = (name: string, over: Partial<MachineWant> = {}): MachineWant => ({
55 kind: "machine",
56 name,
57 account: "digitalocean/main",
58 place: NYC,
59 app: "alice/shop",
60 source: "https://forge.example.org/alice/shop",
61 version: "a".repeat(40),
62 ...over,
63 });
64 const have = (name: string, over: Partial<Have> = {}): Have => ({
65 kind: "machine",
66 name,
67 account: "digitalocean/main",
68 place: NYC,
69 app: "alice/shop",
70 source: "https://forge.example.org/alice/shop",
71 version: "a".repeat(40),
72 host: `${name}.forges.test`,
73 state: "running",
74 volume: true,
75 machine: true,
76 dns: true,
77 answered: true,
78 experiment: "",
79 cents: 1300,
80 keptCents: 100,
81 ...over,
82 });
83 const kinds = (p: Plan) => p.steps.map((s) => `${s.kind}:${s.name}`);
84
85 describe("plan", () => {
86 test("one machine: disk, machine, DNS, ready, in that order, with sentences and the month's price", () => {
87 const p = plan([want("shop")], [], reads());
88 expect(kinds(p)).toEqual(["disk:shop", "machine:shop", "dns:shop", "ready:shop"]);
89 expect(p.steps.map((s) => s.index)).toEqual([0, 1, 2, 3]);
90 expect(p.steps.map((s) => s.says)).toEqual([
91 "Create a 10 GiB disk in nyc3 on digitalocean/main",
92 "Start the s-1vcpu-2gb machine in nyc3 with alice/shop at aaaaaaa, $13.00 a month with its disk and address",
93 "Write shop.forges.test → its address in Cloudflare",
94 "Wait until shop.forges.test answers over HTTPS",
95 ]);
96 expect(p.steps[1]!.cents).toBe(1300);
97 expect(p.byAccount).toEqual([{ account: "digitalocean/main", beforeCents: 0, afterCents: 1300, ceilingCents: 5000, fits: true }]);
98 expect(p.deltaCents).toBe(1300);
99 expect(p.refusals).toEqual([]);
100 });
101
102 test("without a Cloudflare writer the DNS step says it is by hand; a tag version and own code read plainly", () => {
103 const p = plan(
104 [want("a", { version: "v1.2.3" }), want("b", { source: "", version: undefined })],
105 [],
106 reads(undefined, { dnsAuto: false }),
107 );
108 expect(p.steps.find((s) => s.kind === "dns")!.says).toBe(
109 "Point a.forges.test at its address by hand: no Cloudflare account that allows writes can",
110 );
111 expect(p.steps.filter((s) => s.kind === "machine").map((s) => s.says.split(" with ")[1])).toEqual([
112 "alice/shop at v1.2.3, $13.00 a month",
113 "alice/shop at this forge's own commit, $13.00 a month",
114 ]);
115 });
116
117 test("creates come first, then the waits, so every machine boots at once", () => {
118 const p = plan([want("a"), want("b")], [], reads());
119 expect(kinds(p)).toEqual(["disk:a", "machine:a", "disk:b", "machine:b", "dns:a", "ready:a", "dns:b", "ready:b"]);
120 });
121
122 test("the plan's id is the same for the same wants, and differs for others", () => {
123 expect(plan([want("a")], [], reads()).id).toBe(plan([want("a")], [have("x")], reads()).id);
124 expect(plan([want("a")], [], reads()).id).not.toBe(plan([want("b")], [], reads()).id);
125 expect(plan([want("a")], [], reads()).id).not.toBe(plan([want("a")], [], reads(), { complete: true }).id);
126 });
127
128 test("fits: two machines under the ceiling are counted together", () => {
129 const p = plan([want("a"), want("b")], [], reads({ "digitalocean/main": { monthlyCents: 1000 } }));
130 expect(p.byAccount).toEqual([{ account: "digitalocean/main", beforeCents: 1000, afterCents: 3600, ceilingCents: 5000, fits: true }]);
131 expect(p.deltaCents).toBe(2600);
132 });
133
134 test("exceeds: the create that passes the ceiling is refused in the ceiling's words, counting the ones before it", () => {
135 const r = reads({ "digitalocean/main": { ceilingDollars: 30, monthlyCents: 1000 } });
136 const p = plan([want("a"), want("b")], [], r);
137 // a fits ($10 + $13 = $23 of $30); b would make it $36.
138 expect(kinds(p)).toEqual(["disk:a", "machine:a", "dns:a", "ready:a"]);
139 const words = refusalOf({
140 provider: "digitalocean",
141 account: "main",
142 place: { id: NYC, size: "s-1vcpu-2gb", datacenter: "nyc3" },
143 orphan: undefined,
144 price: 1300,
145 closed: undefined,
146 ceilingDollars: 30,
147 monthlyCents: 1000,
148 counted: 0,
149 held: 1300,
150 });
151 expect(words).toContain("is held to $30 a month and runs $23.00 now; this would add $13.00");
152 expect(p.refusals).toEqual([{ name: "b", why: words! }]);
153 expect(p.byAccount).toEqual([{ account: "digitalocean/main", beforeCents: 1000, afterCents: 3600, ceilingCents: 3000, fits: false }]);
154 });
155
156 test("mixed accounts: each is held to its own ceiling; one over does not hold the other", () => {
157 const r = reads({ "digitalocean/main": { ceilingDollars: 10 }, "hetzner/main": { ceilingDollars: 50, monthlyCents: 400 } });
158 const p = plan([want("d"), want("h", { account: "hetzner/main", place: FSN })], [], r);
159 expect(p.byAccount).toEqual([
160 { account: "digitalocean/main", beforeCents: 0, afterCents: 1300, ceilingCents: 1000, fits: false },
161 { account: "hetzner/main", beforeCents: 400, afterCents: 920, ceilingCents: 5000, fits: true },
162 ]);
163 expect(p.refusals.map((x) => x.name)).toEqual(["d"]);
164 expect(kinds(p)).toEqual(["disk:h", "machine:h", "dns:h", "ready:h"]);
165 expect(p.deltaCents).toBe(1820);
166 });
167
168 describe("refusals, each in the words the forge already says", () => {
169 const why = (p: Plan) => p.refusals.map((r) => r.why);
170
171 test("an unorderable place", () => {
172 const p = plan([want("a")], [], reads(undefined, { closed: (id) => (id === NYC ? "this size is not offered now" : undefined) }));
173 expect(why(p)).toEqual([
174 `${NYC} cannot be ordered now: this size is not offered now; nothing was made, and a running machine was not touched. Pick another place, or try again later.`,
175 ]);
176 expect(p.steps).toEqual([]);
177 });
178
179 test("no price", () => {
180 const p = plan([want("a", { place: "digitalocean:sfo3:s-8vcpu-16gb" })], [], reads());
181 expect(why(p)[0]).toStartWith(
182 "The forge has no price for s-8vcpu-16gb in sfo3 on digitalocean, so it cannot hold digitalocean/main to its ceiling",
183 );
184 expect(p.byAccount[0]!.afterCents).toBe(0);
185 });
186
187 test("the ceiling exceeded", () => {
188 const p = plan([want("a")], [], reads({ "digitalocean/main": { ceilingDollars: 12 } }));
189 expect(why(p)[0]).toStartWith(
190 "digitalocean/main is held to $12 a month and runs $0.00 now; this would add $13.00, which is over it, so nothing was made.",
191 );
192 });
193
194 test("a read-only account, and one the forge does not hold", () => {
195 expect(why(plan([want("a")], [], reads({ "digitalocean/main": { writable: false } })))).toEqual([READ_ONLY]);
196 expect(why(plan([want("a", { account: "digitalocean/other" })], [], reads()))).toEqual([NO_ACCOUNT]);
197 });
198
199 test("an orphan standing on the account", () => {
200 const orphan = "digitalocean/main shows an orphan the forge did not account for: droplet x; nothing was made.";
201 expect(why(plan([want("a")], [], reads({ "digitalocean/main": { orphan } })))).toEqual([orphan]);
202 });
203
204 test("a name taken: by another machine, by a retired one, or twice in the wants", () => {
205 expect(why(plan([want("a", { app: "alice/other" })], [have("a")], reads()))).toEqual([NAME_TAKEN]);
206 expect(why(plan([want("a")], [have("a", { state: "retired", machine: false })], reads()))).toEqual([NAME_TAKEN]);
207 expect(why(plan([want("a"), want("a")], [], reads()))).toEqual([NAME_TAKEN]);
208 });
209
210 test("a place on another provider, no host, and an experiment that is gone or done", () => {
211 expect(why(plan([want("a", { place: FSN })], [], reads()))).toEqual([
212 `${FSN} is on hetzner, and digitalocean/main is on digitalocean: name one of digitalocean's places.`,
213 ]);
214 expect(why(plan([want("a")], [], reads(undefined, { host: () => "" })))).toEqual([HOST_NEEDED]);
215 expect(why(plan([want("a", { experimentId: "nope" })], [], reads()))).toEqual([EXPERIMENT_WORDS.no_experiment]);
216 expect(why(plan([want("a", { experimentId: "e2" })], [], reads()))).toEqual([EXPERIMENT_WORDS.done]);
217 });
218 });
219
220 test("what exists already is not made again: only what is missing of it is a step", () => {
221 expect(plan([want("a")], [have("a")], reads()).steps).toEqual([]);
222 expect(kinds(plan([want("a")], [have("a", { answered: false })], reads()))).toEqual(["ready:a"]);
223 expect(kinds(plan([want("a")], [have("a", { dns: false, answered: false })], reads()))).toEqual(["dns:a", "ready:a"]);
224 // A source or version left out of the want matches whatever the row runs.
225 expect(plan([want("a", { source: "", version: undefined })], [have("a")], reads()).steps).toEqual([]);
226 expect(plan([want("a")], [have("a")], reads()).deltaCents).toBe(0);
227 });
228
229 test("a first deploy that failed before its machine is finished on the disk it made, counted once", () => {
230 const failed = have("a", { state: "failed", machine: false, dns: false, answered: false, cents: 1300 });
231 const p = plan([want("a")], [failed], reads({ "digitalocean/main": { monthlyCents: 1300 } }));
232 expect(kinds(p)).toEqual(["machine:a", "dns:a", "ready:a"]);
233 expect(p.steps[0]!.cents).toBe(0);
234 expect(p.deltaCents).toBe(0);
235 });
236
237 test("an experiment's machine is put on it after it is made, unless it is on it already", () => {
238 expect(kinds(plan([want("a", { experimentId: "e1" })], [], reads()))).toEqual(["disk:a", "machine:a", "attach:a", "dns:a", "ready:a"]);
239 expect(plan([want("a", { experimentId: "e1" })], [], reads()).steps[2]!.says).toBe('Put a on the experiment "Is Hetzner fast enough?"');
240 expect(plan([want("a", { experimentId: "e1" })], [have("a", { experiment: "e1" })], reads()).steps).toEqual([]);
241 });
242
243 test("retire steps come only with a complete set, after the creates, keeping the data", () => {
244 const haves = [have("old"), have("gone", { state: "retired", machine: false, cents: 100 })];
245 expect(kinds(plan([want("a")], haves, reads()))).toEqual(["disk:a", "machine:a", "dns:a", "ready:a"]);
246 const p = plan([want("a")], haves, reads({ "digitalocean/main": { monthlyCents: 1400 } }), { complete: true });
247 expect(kinds(p)).toEqual(["disk:a", "machine:a", "dns:a", "ready:a", "retire:old"]);
248 expect(p.steps.at(-1)).toMatchObject({ cents: -1200, says: "Retire old: delete its machine and keep its disk, $12.00 a month less" });
249 expect(p.byAccount[0]).toMatchObject({ beforeCents: 1400, afterCents: 1500 });
250 expect(p.deltaCents).toBe(100);
251 expect(plan([], [have("old")], reads({ "digitalocean/main": { writable: false } }), { complete: true }).refusals).toEqual([
252 { name: "old", why: READ_ONLY },
253 ]);
254 });
255
256 test("the ceiling counts creates without the retires' savings, as the deploy will", () => {
257 const p = plan([want("a")], [have("old")], reads({ "digitalocean/main": { ceilingDollars: 20, monthlyCents: 1300 } }), {
258 complete: true,
259 });
260 expect(p.refusals.map((r) => r.name)).toEqual(["a"]);
261 });
262
263 test("eta: one create's calls plus the slowest boot; retires add theirs; nothing to wait for is zero", () => {
264 expect(plan([want("a")], [], reads()).etaSeconds).toBe(20 + 240);
265 expect(plan([want("a"), want("h", { account: "hetzner/main", place: FSN })], [], reads()).etaSeconds).toBe(40 + 240);
266 expect(
267 plan([want("o", { account: "ovh/main", place: "ovh:US-EAST-VA-1:d2-2" })], [], reads({ "ovh/main": {} }, { price: () => 800 }))
268 .etaSeconds,
269 ).toBe(20 + 300);
270 expect(plan([want("a")], [have("a")], reads(), { complete: true }).etaSeconds).toBe(0);
271 expect(plan([], [have("old")], reads(), { complete: true }).etaSeconds).toBe(30);
272 });
273 });
274
275 describe("apply", () => {
276 const ADMIN = { id: "u1", isAdmin: true } as User;
277 const APP = {} as App;
278
279 /** A tiny world: rows by name, a clock, and the calls the hands were asked to make. */
280 function world(o: { deploy?: (w: MachineWant, rows: Map<string, Facts>) => string | undefined; boot?: number } = {}) {
281 const rows = new Map<string, Facts>();
282 const events: StepEvent[] = [];
283 const calls: string[] = [];
284 let clock = 0;
285 const boot = o.boot ?? 2;
286 const ticks = new Map<string, number>();
287 const fact = (over: Partial<Facts> = {}): Facts => ({
288 state: "running",
289 volume: true,
290 machine: true,
291 address: false,
292 dns: false,
293 answered: false,
294 stuck: "",
295 experiment: "",
296 ...over,
297 });
298 const hands: Hands = {
299 replan: (p) => p,
300 deploy: async (w) => {
301 calls.push(`deploy ${w.name}`);
302 const no = o.deploy?.(w, rows);
303 if (no !== undefined) return err(no);
304 rows.set(w.name, fact({ ...rows.get(w.name), state: "running", volume: true, machine: true }));
305 ticks.set(w.name, 0);
306 return ok({});
307 },
308 retire: async (name) => {
309 calls.push(`retire ${name}`);
310 rows.set(name, fact({ ...rows.get(name), state: "retired", machine: false }));
311 return ok({});
312 },
313 attach: (id, name) => {
314 calls.push(`attach ${name} ${id}`);
315 rows.set(name, { ...rows.get(name)!, experiment: id });
316 return ok(undefined);
317 },
318 facts: (name) => rows.get(name),
319 emit: (e) => events.push(e),
320 // Each look of the watch moves every booting machine on: address and DNS, then an answer.
321 sleep: async () => {
322 clock += 5000;
323 for (const [name, t] of ticks) {
324 const r = rows.get(name)!;
325 ticks.set(name, t + 1);
326 if (t + 1 >= 1) rows.set(name, { ...r, address: true, dns: true });
327 if (t + 1 >= boot) rows.set(name, { ...rows.get(name)!, answered: true });
328 }
329 },
330 now: () => clock,
331 };
332 return { rows, events, calls, hands, fact };
333 }
334 const trail = (es: StepEvent[]) => es.map((e) => `${e.index}:${e.state}`);
335
336 test("each step emits started then done, in order, and the run says what it did", async () => {
337 const w = world();
338 const p = plan([want("a", { experimentId: "e1" })], [], reads());
339 const r = await apply(APP, ADMIN, p, w.hands);
340 expect(r).toEqual(ok({ planId: p.id, done: [0, 1, 2, 3, 4], skipped: [] }));
341 // disk and machine are one deploy, so both start before either is done.
342 expect(trail(w.events)).toEqual([
343 "0:started",
344 "1:started",
345 "0:done",
346 "1:done",
347 "2:started",
348 "2:done",
349 "3:started",
350 "4:started",
351 "3:done",
352 "4:done",
353 ]);
354 expect(w.events.every((e) => e.planId === p.id && e.says === p.steps[e.index]!.says)).toBe(true);
355 expect(w.calls).toEqual(["deploy a", "attach a e1"]);
356 });
357
358 test("two machines boot together: both deploys, then one wait for both", async () => {
359 const w = world();
360 const p = plan([want("a"), want("b")], [], reads());
361 await apply(APP, ADMIN, p, w.hands);
362 expect(w.calls).toEqual(["deploy a", "deploy b"]);
363 expect(trail(w.events).slice(8)).toEqual(["4:started", "5:started", "6:started", "7:started", "4:done", "6:done", "5:done", "7:done"]);
364 });
365
366 test("a failed step stops the run with the deploy's words; the rerun skips what exists and finishes", async () => {
367 let refuse = true;
368 // The first try makes the disk and is refused at the machine, as a cloud can.
369 const w = world({
370 deploy: (x, rows) => {
371 if (!refuse) return undefined;
372 rows.set(x.name, {
373 state: "failed",
374 volume: true,
375 machine: false,
376 address: false,
377 dns: false,
378 answered: false,
379 stuck: "",
380 experiment: "",
381 });
382 return "The cloud refused: api.digitalocean.com answered 422";
383 },
384 });
385 const p = plan([want("a"), want("b")], [], reads());
386 const first = await apply(APP, ADMIN, p, w.hands);
387 expect(first).toEqual(
388 ok({ planId: p.id, done: [0], skipped: [], failed: { index: 1, why: "The cloud refused: api.digitalocean.com answered 422" } }),
389 );
390 expect(trail(w.events)).toEqual(["0:started", "1:started", "0:done", "1:failed"]);
391 expect(w.events.at(-1)!.why).toBe("The cloud refused: api.digitalocean.com answered 422");
392 expect(w.calls).toEqual(["deploy a"]);
393
394 refuse = false;
395 w.events.length = 0;
396 const again = await apply(APP, ADMIN, p, w.hands);
397 expect(again).toEqual(ok({ planId: p.id, done: [1, 2, 3, 4, 6, 5, 7], skipped: [0] }));
398 expect(trail(w.events).slice(0, 2)).toEqual(["1:started", "1:done"]);
399 expect(w.calls).toEqual(["deploy a", "deploy a", "deploy b"]);
400
401 // A third run finds everything done and asks nothing of the cloud.
402 w.events.length = 0;
403 const third = await apply(APP, ADMIN, p, w.hands);
404 expect(third).toEqual(ok({ planId: p.id, done: [], skipped: [0, 1, 2, 3, 4, 5, 6, 7] }));
405 expect(w.events).toEqual([]);
406 expect(w.calls).toHaveLength(3);
407 });
408
409 test("the watch giving up fails the wait in its words; so does the bound when the watch says nothing", async () => {
410 const stuck = "a does not answer over HTTPS: make its record DNS only, then press Check.";
411 const w = world({ boot: 1_000 });
412 w.hands.sleep = async () => void w.rows.set("a", { ...w.rows.get("a")!, address: true, dns: true, stuck });
413 const p = plan([want("a")], [], reads());
414 const r = await apply(APP, ADMIN, p, w.hands);
415 expect(r.ok && r.value.failed).toEqual({ index: 3, why: stuck });
416 expect(trail(w.events)).toEqual(["0:started", "1:started", "0:done", "1:done", "2:started", "3:started", "2:done", "3:failed"]);
417
418 const quiet = world({ boot: 1_000_000 });
419 const q = await apply(APP, ADMIN, p, quiet.hands);
420 expect(q.ok && q.value.failed).toEqual({ index: 3, why: "a does not answer over HTTPS: make its record DNS only, then press Check." });
421 });
422
423 test("retires run after the creates and are done once the row says retired", async () => {
424 const w = world();
425 w.rows.set("old", w.fact({ dns: true, answered: true }));
426 const p = plan([want("a")], [have("old")], reads(), { complete: true });
427 const r = await apply(APP, ADMIN, p, w.hands);
428 expect(r.ok && r.value.done).toEqual([0, 1, 2, 3, 4]);
429 expect(w.calls).toEqual(["deploy a", "retire old"]);
430 expect(trail(w.events).slice(-2)).toEqual(["4:started", "4:done"]);
431 });
432
433 test("refused: a non-admin, a plan with refusals, and one that would refuse or cost more now", async () => {
434 const w = world();
435 const p = plan([want("a")], [], reads());
436 expect(await apply(APP, { id: "u2", isAdmin: false } as User, p, w.hands)).toEqual(err("not_found"));
437 const refused = plan([want("a")], [], reads({ "digitalocean/main": { writable: false } }));
438 expect(await apply(APP, ADMIN, refused, w.hands)).toEqual(err(`This plan has refusals, so nothing was built: ${READ_ONLY}`));
439 w.hands.replan = () => refused;
440 expect(await apply(APP, ADMIN, p, w.hands)).toEqual(
441 err(`Since the plan was shown: ${READ_ONLY} Nothing was built; look at the plan again.`),
442 );
443 w.hands.replan = () => plan([want("a", { place: "digitalocean:nyc3:s-2vcpu-4gb" })], [], reads());
444 expect(await apply(APP, ADMIN, p, w.hands)).toEqual(
445 err(
446 "digitalocean/main would cost $25.00 a month after this, more than the plan showed ($13.00); nothing was built. Look at the plan again.",
447 ),
448 );
449 expect(w.calls).toEqual([]);
450 expect(w.events).toEqual([]);
451 });
452 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs