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

A deploy says where its name points before it moves it #17741

opened this

Merged 15h 39m ago, live in production

sold/deploy-record → main 0 commits

  • Merged. sold/deploy-record was merged into main as ba85a0f.

Review

Sign in to review this change.
25 files changed +271 −86
docs/features/pinned-forge.md +2
@@ -89,6 +89,8 @@ An admin names the **domain for deployed forges** (`forges.example.com`) on Infr
8989
9090 With a **Cloudflare** cloud account attached and writes allowed, the forge then writes the record itself: after the machine has an address (the deploy, and every Update, Roll back and new claim link), and again on Check, it upserts `<host> A <address>` in the zone that holds the name, through the first such account whose token can edit that zone: found by name and updated, or made, so a replaced machine's new address changes the record and never adds one; DNS only (not proxied, so the machine gets its own certificate), TTL 60. The calls go to `api.cloudflare.com` only (`upsertARecord`, `src/cloud/providers.ts`), the token in the Authorization header alone, each call audited as `pinned:dns` like the other cloud calls; the record's id and zone are kept (`pinned_dns`) with the account that wrote it. A zone the token cannot see or edit, a CNAME already at the name, or any refusal leaves the record for a person to make, and the deploy answer and Check say that instead (`dnsWrittenBy` is empty). The token needs DNS edit on the zone; the cloud account's check cannot tell that, so the first write is the proof.
9191
92 **A name that points somewhere already** is moved, and never silently. Before a deploy the forge asks DNS for the name's A records (`pointsNow`, at most 1.5 seconds): the infrastructure plan's step names each address at every door, and the Deploy to… form and the terminal's `d` ask once more with the address before anything is made. No answer from DNS is said as that, never as "points nowhere". The API and the `pinned_forge` tool deploy in one call, so their answer names the address the record held before (`dnsWas`), as the `pinned.dns` event does (`was`); the agent's confirm says only that such a record is changed. A proxied name shows its proxy's addresses, and IPv6 is not looked at.
93
9294 ## Paid forges on a cloud machine (#16205)
9395
9496 An admin chooses where **paid forges run** on Infrastructure (`/infra`, under Pinned forges; the terminal's `p`; `PATCH /api/v1/admin/settings` with `{"paidPlacement": "digitalocean/main"}`, `"hosted"` or `null` for the default; `GET` answers it as `paidPlacement`). It is a forge setting (`settings/paid_placement.ts`, `paid.placement`, every change kept with who and when). `hosted`, the default, is today's: a bought forge runs inside this one. A cloud account (one a pinned forge can be deployed to, with writes allowed) makes each paid order a pinned forge of its own (`src/spawn/cloud_placement.ts`). Free forges always stay hosted.
src/actions/infra.ts +21 −9
@@ -43,7 +43,7 @@ import { repoDir } from "../git/repos.ts";
4343 import { err, ok, type Result } from "../kernel/result.ts";
4444 import { listBoxes } from "../games/store.ts";
4545 import { getBaseDomain } from "../settings/pinned_domain.ts";
46 import { LIFETIME_DAYS, dayWords, endsWords, net } from "./pinned.ts";
46 import { LIFETIME_DAYS, dayWords, endsWords, net, pointsNow } from "./pinned.ts";
4747 import { placeWords } from "../cloud/places.ts";
4848 import { countSnapshots, listSnapshots } from "../core/snapshots.ts";
4949 import { snapshotOffer, snapshotView, type SnapshotView } from "./infra_snapshot.ts";
@@ -614,7 +614,7 @@ export function databaseWantOf(c: DatabaseCompose): Result<DatabaseWant, string>
614614 }
615615
616616 /** Plan a database compose against what exists now; nothing is made. */
617 export function planDatabase(app: App, actor: User | undefined, c: DatabaseCompose): Result<Planned, string> {
617 export async function planDatabase(app: App, actor: User | undefined, c: DatabaseCompose): Promise<Result<Planned, string>> {
618618 const who = admin(actor);
619619 if (!who.ok) return who;
620620 const want = databaseWantOf(c);
@@ -697,16 +697,28 @@ export async function planCompose(app: App, actor: User | undefined, c: Compose,
697697 const want = await wantOf(app, c, choices);
698698 // A compose that lacks something plans nothing, and reads nothing to do it.
699699 if (!want.ok) return ok({ plan: plan([], [], NOTHING), lacks: want.error, summary: "", fixes: [], needs: [] });
700 const { have, reads, databases } = readInfra(app);
701 return ok(planned(app, plan([want.value], have, reads, { databases })));
700 return planWants(app, actor, [want.value]);
701 }
702
703 /** The plan with what DNS says now of each name it points at a new machine, so a person reads what moves before it does. */
704 async function withPoints(app: App, actor: User | undefined, p: Plan): Promise<Plan> {
705 const steps = await Promise.all(
706 p.steps.map(async (s) => {
707 const w = s.kind === "dns" ? p.wants.find((x) => x.kind === "machine" && x.name === s.name) : undefined;
708 if (w?.kind !== "machine") return s;
709 const now = await pointsNow(app, actor, w.name, getPinned(app.db, w.name)?.host || (w.host ?? ""));
710 return now === "" ? s : { ...s, says: `${s.says}: ${now}` };
711 }),
712 );
713 return { ...p, steps };
702714 }
703715
704716 /** Plan wants as given (the API and MCP send them whole). */
705 export function planWants(app: App, actor: User | undefined, wants: readonly Want[], complete = false, clears: readonly string[] = []): Result<Planned, string> {
717 export async function planWants(app: App, actor: User | undefined, wants: readonly Want[], complete = false, clears: readonly string[] = []): Promise<Result<Planned, string>> {
706718 const who = admin(actor);
707719 if (!who.ok) return who;
708720 const { have, reads, databases } = readInfra(app);
709 return ok(planned(app, plan(wants, have, reads, { complete, clears, databases })));
721 return ok(planned(app, await withPoints(app, actor, plan(wants, have, reads, { complete, clears, databases }))));
710722 }
711723
712724 /** The fields a person types for a DNS record, as a form or a terminal prompt hands them over. */
@@ -728,7 +740,7 @@ export function recordAccounts(app: App): string[] {
728740 * Plan one DNS record from what a person typed. A record costs nothing, so the person's Build is
729741 * the one press: the plan comes back for the caller to start, with every refusal said.
730742 */
731 export function planRecord(app: App, actor: User | undefined, f: RecordFields): Result<Planned, string> {
743 export async function planRecord(app: App, actor: User | undefined, f: RecordFields): Promise<Result<Planned, string>> {
732744 const port = /^\d{1,5}$/.test(f.port.trim()) ? Number(f.port.trim()) : undefined;
733745 return planWants(app, actor, [dnsWantOf({ name: f.name.trim().toLowerCase().slice(0, 40), account: f.account.slice(0, 80), type: f.type.trim().toUpperCase().slice(0, 4), host: f.host.slice(0, 260), value: f.value.slice(0, 260), port })]);
734746 }
@@ -838,10 +850,10 @@ export function buildOf(app: App, actor: User | undefined, planId: string): Buil
838850 }
839851
840852 /** Build a plan again after it stopped: the same wants, planned against what exists now. */
841 export function rebuild(app: App, actor: User | undefined, planId: string): Result<string, string> {
853 export async function rebuild(app: App, actor: User | undefined, planId: string): Promise<Result<string, string>> {
842854 const b = buildOf(app, actor, planId);
843855 if (b === undefined) return err("No such build.");
844 const again = planWants(app, actor, b.wants, false, b.clears);
856 const again = await planWants(app, actor, b.wants, false, b.clears);
845857 if (!again.ok) return again;
846858 return startBuild(app, actor, again.value.plan);
847859 }
src/actions/minecraft.ts +2 −2
@@ -22,13 +22,13 @@ export interface MinecraftPlanned {
2222 }
2323
2424 /** Plan Minecraft for `i`; nothing is made. Admins only, as every infra plan is. */
25 export function planMinecraft(app: App, actor: User | undefined, i: MinecraftInput): Result<MinecraftPlanned, string> {
25 export async function planMinecraft(app: App, actor: User | undefined, i: MinecraftInput): Promise<Result<MinecraftPlanned, string>> {
2626 const placeId = i.where.split("@")[1] ?? "";
2727 const place = keptPlaces(app.db, keptRate(app.db, "EUR")).find((p) => p.id === placeId);
2828 if (place === undefined) return err("Pick where the server runs.");
2929 const design = minecraftDesign(i, place);
3030 if (!design.ok) return design;
31 const planned = planWants(app, actor, [design.value.machine, design.value.srv]);
31 const planned = await planWants(app, actor, [design.value.machine, design.value.srv]);
3232 if (!planned.ok) return planned;
3333 return ok({
3434 planned: planned.value,
src/actions/pinned.ts +53 −12
@@ -60,6 +60,7 @@ import { DOMAIN_WORDS, getBaseDomain, parseBaseDomain, setBaseDomain } from "../
6060 import { PAID_PLACEMENT_WORDS, getPaidPlacement, paidPlacementWord, parsePaidPlacement, setPaidPlacement } from "../settings/paid_placement.ts";
6161 import type { User } from "../core/users.ts";
6262 import { err, ok, type Result } from "../kernel/result.ts";
63 import { background } from "../perf/jobs.ts";
6364 import { boundedSignal } from "../kernel/fetch_timeout.ts";
6465 import { isStale, refreshIfDue } from "./places_refresh.ts";
6566 import { oneAtATime } from "../spawn/own_code.ts";
@@ -72,7 +73,12 @@ export { LIFETIME_DAYS, MAX_LIFETIME_DAYS };
7273 export const net: { fetch: Fetch; probe: Fetch; resolve: (host: string) => Promise<string[]>; bootLimit?: number | undefined } = {
7374 fetch: (u, i) => fetch(u, { ...i, signal: boundedSignal(i?.signal) }),
7475 probe: (u, i) => fetch(u, { ...i, signal: boundedSignal(i?.signal) }),
75 resolve: (host) => resolve4(host).catch(() => []),
76 // No such name is an answer; anything else is none, and is thrown.
77 resolve: (host) =>
78 resolve4(host).catch((e) => {
79 if (e?.code === "ENOTFOUND" || e?.code === "ENODATA") return [];
80 throw e;
81 }),
7682 };
7783
7884 /**
@@ -154,7 +160,11 @@ export interface IssuedClaim {
154160 readonly expiresAt: string;
155161 }
156162
157 export type Issued = PinnedView & { readonly claim: IssuedClaim };
163 export type Issued = PinnedView & {
164 readonly claim: IssuedClaim;
165 /** The address the name's record held before this deploy changed it; absent when it changed none. */
166 readonly dnsWas?: string;
167 };
158168
159169 const PLACE_HELP = "Pick one of the places the Places page lists, or leave it out for the default.";
160170
@@ -275,13 +285,14 @@ const dnsWriters = (app: App) => listCloudAccounts(app.db).filter((a) => a.provi
275285 * that arrived late is written too. Nothing is written, and nothing asked of Cloudflare, with no
276286 * such account, no name or no address; a token that cannot edit the zone leaves the record for a
277287 * person to make, which the words of the deploy and of Check then say. Each call is audited like
278 * the other cloud calls (`pinned:dns`), and the token is opened for it alone.
288 * the other cloud calls (`pinned:dns`), and the token is opened for it alone. Answers the address
289 * the record held before, when it held another.
279290 */
280 async function writeDns(app: App, who: Who, name: string): Promise<void> {
291 async function writeDns(app: App, who: Who, name: string): Promise<string | undefined> {
281292 const p = getPinned(app.db, name);
282 if (!p || p.host === "" || p.address === "") return;
293 if (!p || p.host === "" || p.address === "") return undefined;
283294 const kept = dnsOf(app.db, p.id);
284 if (kept !== undefined && kept.host === p.host && kept.address === p.address) return;
295 if (kept !== undefined && kept.host === p.host && kept.address === p.address) return undefined;
285296 for (const a of dnsWriters(app)) {
286297 const secret = secretNameOf(a.provider, a.name);
287298 const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: who.id, run: runOf(who, "dns") })[secret];
@@ -290,9 +301,39 @@ async function writeDns(app: App, who: Who, name: string): Promise<void> {
290301 const made = await upsertARecord(f, token, p.host, p.address);
291302 if (made.done === "none") continue;
292303 keepDns(app.db, p.id, { account: a.name, zone: made.zone, record: made.record, host: p.host, address: p.address });
293 app.bus.append({ kind: "pinned.dns", actorId: who.id, payload: { name, host: p.host, address: p.address, account: `cloudflare/${a.name}`, done: made.done, ...orderOf(who) } });
294 return;
304 const was = made.was === p.address ? undefined : made.was;
305 app.bus.append({ kind: "pinned.dns", actorId: who.id, payload: { name, host: p.host, address: p.address, account: `cloudflare/${a.name}`, done: made.done, ...(was === undefined ? {} : { was }), ...orderOf(who) } });
306 return was;
295307 }
308 return undefined;
309 }
310
311 /** What a deploy does to that, for a door that asks before it. */
312 export const MOVES_WORDS = "Deploying points that name at the new machine, and what answers there now is no longer reached by it.";
313
314 /** How long a page waits for DNS before it says that DNS did not answer. */
315 const LOOK_MS = 1_500;
316
317 /**
318 * What DNS says now of the name `name` would be served on, asked before a deploy points it at the
319 * new machine: a sentence's clause with each address, or that DNS did not answer. Empty when the name
320 * points nowhere or at this forge's own machine, and when no account writes the record, for then a
321 * person does. A proxied name answers with its proxy's addresses.
322 */
323 export async function pointsNow(app: App, actor: User | undefined, name: string, asked: string): Promise<string> {
324 if (!admin(actor).ok || dnsWriters(app).length === 0) return "";
325 const old = getPinned(app.db, name);
326 const host = hostFor(app, name, asked);
327 if (!host.ok) return "";
328 let timer: ReturnType<typeof setTimeout> | undefined;
329 const late = new Promise<undefined>((done) => {
330 timer = setTimeout(() => background("pinned-points-wait", () => done(undefined)), LOOK_MS);
331 });
332 const at = await Promise.race([net.resolve(host.value).catch(() => undefined), late]);
333 clearTimeout(timer);
334 if (at === undefined) return `DNS did not say where ${host.value} points now`;
335 const others = at.filter((a) => a !== old?.address).sort();
336 return others.length === 0 ? "" : `DNS sends ${host.value} to ${others.join(" and ")} now`;
296337 }
297338
298339 /** After a replace the address is unknown: with a Cloudflare account to write it, read it and write the record. */
@@ -555,9 +596,9 @@ async function deployAs(app: App, who: Who, input: DeployInput): Promise<Result<
555596 // One read for the address, so the answer can name the DNS record; a cloud that has not
556597 // assigned one yet (or refuses the read) leaves it to `check`.
557598 await readAddress(app, who, p.name);
558 await writeDns(app, who, p.name);
599 const dnsWas = await writeDns(app, who, p.name);
559600 watchPinned(app, p.name, watchStep);
560 return ok(issued(app, getPinned(app.db, p.name)!, claim.code));
601 return ok({ ...issued(app, getPinned(app.db, p.name)!, claim.code), ...(dnsWas === undefined ? {} : { dnsWas }) });
561602 }
562603
563604 const change = (
@@ -708,7 +749,7 @@ export type ClaimState = SeedState | "unknown";
708749 async function reach(app: App, p: Pinned): Promise<{ waiting: Waiting; claim: ClaimState }> {
709750 if (p.host === "") return { waiting: "name", claim: "unknown" };
710751 if (p.address === "") return { waiting: "address", claim: "unknown" };
711 if (!(await net.resolve(p.host)).includes(p.address)) return { waiting: "dns", claim: "unknown" };
752 if (!(await net.resolve(p.host).catch((): string[] => [])).includes(p.address)) return { waiting: "dns", claim: "unknown" };
712753 // Audited like every other call made for this account; the host is a validated name.
713754 const probe = gatedFetch(app.db, { provider: p.target, account: p.account }, "pinned:probe", net.probe);
714755 const ask = (path: string): Promise<Response> => probe(`${urlOf(p)}${path}`, { signal: AbortSignal.timeout(5_000), redirect: "manual" });
@@ -962,7 +1003,7 @@ export function checkWords(v: Checked): string {
9621003 */
9631004 export function claimWords(v: Issued): string {
9641005 if (v.dnsWrittenBy !== "")
965 return `The forge wrote the DNS record ${v.dns} in ${v.dnsWrittenBy} (DNS only, not proxied): there is nothing to create. It gets its own certificate once the name resolves, and is served only at ${v.url}. The claim link makes its first admin: it works once, until ${v.claim.expiresAt}, and is shown only now.`;
1006 return `The forge wrote the DNS record ${v.dns} in ${v.dnsWrittenBy} (DNS only, not proxied): there is nothing to create.${v.dnsWas === undefined ? "" : ` That record named ${v.dnsWas} before.`} It gets its own certificate once the name resolves, and is served only at ${v.url}. The claim link makes its first admin: it works once, until ${v.claim.expiresAt}, and is shown only now.`;
9661007 const dns = v.dns !== "" ? `Create the DNS record ${v.dns} (DNS only, not proxied) by hand` : v.dnsAuto ? `The forge reads its address and writes the DNS record ${v.host} A <that address> (DNS only, not proxied) as soon as the machine has one; nobody needs to press Check` : `Create the DNS record ${v.host} A <that address> (DNS only, not proxied) by hand once Check reads its address`;
9671008 return `${dns}: the forge gets its own certificate once the name resolves, and is served only at ${v.url}. The claim link makes its first admin: it works once, until ${v.claim.expiresAt}, and is shown only now.`;
9681009 }
src/cloud/providers.ts +2 −2
@@ -198,7 +198,7 @@ export const CF_ID = /^[0-9a-f]{32}$/;
198198
199199 /** What writing a forge's DNS record came to: made, changed, already right, or not written and why. */
200200 export type DnsWrite =
201 | { readonly done: "created" | "updated" | "unchanged"; readonly zone: string; readonly record: string }
201 | { readonly done: "created" | "updated" | "unchanged"; readonly zone: string; readonly record: string; /** The address an updated record held before. */ readonly was?: string }
202202 | { readonly done: "none"; readonly why: string };
203203
204204 /** One Cloudflare call: the status and the body (an empty object when it is not JSON). */
@@ -255,7 +255,7 @@ async function putARecord(f: Fetch, token: string, zone: { id: string; name: str
255255 if (mine.content === address && mine.proxied === false && mine.ttl === 60) return { done: "unchanged", zone: zone.id, record: String(mine.id) };
256256 const r = await cloudflare(f, token, "PATCH", `/zones/${zone.id}/dns_records/${mine.id}`, want);
257257 if (r.status === 401 || r.status === 403) return none(`the token cannot edit DNS records in ${zone.name}`);
258 return r.status === 200 ? { done: "updated", zone: zone.id, record: String(mine.id) } : none(`Cloudflare answered ${r.status} updating ${name}`);
258 return r.status === 200 ? { done: "updated", zone: zone.id, record: String(mine.id), was: String(mine.content).slice(0, 60) } : none(`Cloudflare answered ${r.status} updating ${name}`);
259259 }
260260 const r = await cloudflare(f, token, "POST", `/zones/${zone.id}/dns_records`, { type: "A", name, ...want, comment: "a pinned forge, written by the forge that deployed it" });
261261 if (r.status === 401 || r.status === 403) return none(`the token cannot edit DNS records in ${zone.name}`);
src/contract/openapi/routes/postApiV1AdminPinned.ts +1 −1
@@ -4,7 +4,7 @@ export const route: Route = {
44 method: "post",
55 path: "/api/v1/admin/pinned",
66 summary: "Put a pinned forge on the owner's cloud: no crew, no automatic release",
7 detail: "Put a pinned forge on the owner's cloud: no crew, no automatic release; needs an admin-scope token and a cloud account with writes allowed; `host` is the name it is served on over HTTPS; `place` (provider:datacenter:size, from Places) is where its volume and machine are made, and left out it is the catalog's default for the small plan on that provider; answers the forge with { claim: { link, expiresAt } }, the one-time link that makes its first admin, shown in this answer only, and `dns`, the record to create",
7 detail: "Put a pinned forge on the owner's cloud: no crew, no automatic release; needs an admin-scope token and a cloud account with writes allowed; `host` is the name it is served on over HTTPS; `place` (provider:datacenter:size, from Places) is where its volume and machine are made, and left out it is the catalog's default for the small plan on that provider; answers the forge with { claim: { link, expiresAt } }, the one-time link that makes its first admin, shown in this answer only, and `dns`, the record to create; `dnsWas` is the address the name's record held before, when this deploy changed it",
88 auth: true,
99 role: "admin",
1010 status: 201,
src/crew/conversation_ask.ts +1 −1
@@ -123,7 +123,7 @@ function pinnedForge(a: Args): string {
123123 return a["domain"] === "" ? "Clear the domain pinned forges are named under" : `Set the domain pinned forges are named under${clause(" to ", val(a, "domain"))}`;
124124 if (a["verb"] === "retire")
125125 return `Retire ${forge}${a["withData"] === true ? " and delete its data" : ", keeping its data"}${a["despiteClaim"] === true ? ", though its buyer has claimed it" : ""}`;
126 return `${verb(a, "verb", { deploy: "Deploy", update: "Update", rollback: "Roll back", check: "Check", claim: "Make a fresh claim link for" }, "Change")} ${forge}${clause(" on ", val(a, "target"))}`;
126 return `${verb(a, "verb", { deploy: "Deploy", update: "Update", rollback: "Roll back", check: "Check", claim: "Make a fresh claim link for" }, "Change")} ${forge}${clause(" on ", val(a, "target"))}${a["verb"] === "deploy" ? "; an A record its name has already is changed to the new machine" : ""}`;
127127 }
128128
129129 /** Infrastructure (#16696): only `apply` is held, and it builds a plan the person was shown. */
src/http/api/admin.ts +1 −1
@@ -162,7 +162,7 @@ export function adminRoutes(router: Router<Handler>): void {
162162 // A managed Postgres database (#17074): `where` is `account@region`, the URL goes to `app` as a
163163 // secret.
164164 if (i.database === true) {
165 const made = planDatabase(ctx.app, ctx.auth.user, { app, where: str(i.where).slice(0, 260), size: str(i.size).slice(0, 40), name: str(i.name).slice(0, 40), secret: str(i.secret).slice(0, 128) });
165 const made = await planDatabase(ctx.app, ctx.auth.user, { app, where: str(i.where).slice(0, 260), size: str(i.size).slice(0, 40), name: str(i.name).slice(0, 40), secret: str(i.secret).slice(0, 128) });
166166 if (!made.ok) return pinnedFail(made.error);
167167 if (made.value.lacks !== "") return apiError("refused", 422, made.value.lacks);
168168 const d = made.value;
src/http/infra_routes.ts +2 −2
@@ -224,7 +224,7 @@ async function infraRecord(ctx: Ctx): Promise<Response> {
224224 if (denied) return denied;
225225 const form = await readForm(ctx, "admin");
226226 if (form instanceof Response) return form;
227 const planned = planRecord(ctx.app, ctx.auth.user, {
227 const planned = await planRecord(ctx.app, ctx.auth.user, {
228228 name: field(form, "name"),
229229 account: field(form, "account"),
230230 type: field(form, "type"),
@@ -245,7 +245,7 @@ async function infraRebuild(ctx: Ctx): Promise<Response> {
245245 if (denied) return denied;
246246 const form = await readForm(ctx, "admin");
247247 if (form instanceof Response) return form;
248 const again = rebuild(ctx.app, ctx.auth.user, field(form, "plan"));
248 const again = await rebuild(ctx.app, ctx.auth.user, field(form, "plan"));
249249 return again.ok
250250 ? toBuild(again.value)
251251 : flashTo(ctx, "/infra/build", { tone: "danger", message: again.error });
src/http/mcp/tools/infra.ts +6 −6
@@ -183,7 +183,7 @@ export const tool: Tool = {
183183 }
184184 if (action === "plan" && args["want"] === undefined && names.length > 0) {
185185 // Dead rows to clear (failed, nothing at their provider): a plan like any other, applied by id.
186 const planned = planWants(ctx.app, user, [], false, names);
186 const planned = await planWants(ctx.app, user, [], false, names);
187187 if (!planned.ok) return bad("not_found", "no such tool here");
188188 const p = planned.value;
189189 return good({ id: p.plan.id, says: p.summary, steps: p.plan.steps.map((x) => x.says), refusals: p.fixes });
@@ -194,7 +194,7 @@ export const tool: Tool = {
194194 // address.
195195 if (w["dns"] === true) {
196196 const n = (k: string): number | undefined => (typeof w[k] === "number" ? (w[k] as number) : undefined);
197 const planned = planWants(ctx.app, user, [dnsWantOf({ name: s(w["name"], 40), account: s(w["account"], 80), type: s(w["type"], 4), host: s(w["host"], 260), value: s(w["value"], 260), port: n("port"), priority: n("priority"), weight: n("weight"), ttl: n("ttl") })]);
197 const planned = await planWants(ctx.app, user, [dnsWantOf({ name: s(w["name"], 40), account: s(w["account"], 80), type: s(w["type"], 4), host: s(w["host"], 260), value: s(w["value"], 260), port: n("port"), priority: n("priority"), weight: n("weight"), ttl: n("ttl") })]);
198198 if (!planned.ok) return bad("not_found", "no such tool here");
199199 const p = planned.value;
200200 return good({ id: p.plan.id, says: p.summary, steps: p.plan.steps.map((x) => x.says), refusals: p.fixes, etaSeconds: p.plan.etaSeconds });
@@ -203,14 +203,14 @@ export const tool: Tool = {
203203 if (typeof w["firewall"] === "string") {
204204 const want = firewallWant(ctx.app, s(w["firewall"], 40));
205205 if (!want.ok) return bad("incomplete", want.error);
206 const planned = planWants(ctx.app, user, [want.value]);
206 const planned = await planWants(ctx.app, user, [want.value]);
207207 if (!planned.ok) return bad("not_found", "no such tool here");
208208 const p = planned.value;
209209 return good({ id: p.plan.id, says: p.summary, steps: p.plan.steps.map((x) => x.says), refusals: p.fixes, deltaCents: p.plan.deltaCents });
210210 }
211211 // A managed Postgres database (#17074): its URL becomes the app's secret once it is online.
212212 if (w["database"] === true) {
213 const planned = planDatabase(ctx.app, user, { app: s(w["app"], 140), where: s(w["where"], 260), size: s(w["size"], 40), name: s(w["name"], 40), secret: s(w["secret"], 128) });
213 const planned = await planDatabase(ctx.app, user, { app: s(w["app"], 140), where: s(w["where"], 260), size: s(w["size"], 40), name: s(w["name"], 40), secret: s(w["secret"], 128) });
214214 if (!planned.ok) return bad("not_found", "no such tool here");
215215 const p = planned.value;
216216 if (p.lacks !== "") return bad("incomplete", p.lacks);
@@ -218,7 +218,7 @@ export const tool: Tool = {
218218 }
219219 // Minecraft Java as a design (#17076): a game box sized by its players, with A + SRV records.
220220 if (w["design"] === "minecraft") {
221 const made = planMinecraft(ctx.app, user, {
221 const made = await planMinecraft(ctx.app, user, {
222222 name: s(w["name"], 40) || "mc",
223223 players: String(w["players"] ?? ""),
224224 where: s(w["where"], 260),
@@ -236,7 +236,7 @@ export const tool: Tool = {
236236 if (w["game"] === true) {
237237 const want = gameWant({ name: s(w["name"], 40) || nameFor(s(w["repo"], 140)), where: s(w["where"], 260), repo: s(w["repo"], 140), host: s(w["host"], 253) });
238238 if (!want.ok) return bad("incomplete", want.error);
239 const planned = planWants(ctx.app, user, [want.value]);
239 const planned = await planWants(ctx.app, user, [want.value]);
240240 if (!planned.ok) return bad("not_found", "no such tool here");
241241 const p = planned.value;
242242 return good({ id: p.plan.id, says: p.summary, steps: p.plan.steps.map((x) => x.says), refusals: p.fixes, byAccount: p.plan.byAccount, deltaCents: p.plan.deltaCents });
src/http/pinned_routes.ts +7 −4
@@ -7,7 +7,7 @@
77 * never through a redirect or a flash: it is shown once and stored nowhere.
88 */
99
10 import { DOMAIN_WORDS, endsWords, keepPinned, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, deployPinned, fileForge, deployPlaces, pinnedForges, retirePinned, retireWords, rollbackPinned, updatePinned, type Issued } from "../actions/pinned.ts";
10 import { DOMAIN_WORDS, endsWords, keepPinned, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, deployPinned, MOVES_WORDS, pointsNow, fileForge, deployPlaces, pinnedForges, retirePinned, retireWords, rollbackPinned, updatePinned, type Issued } from "../actions/pinned.ts";
1111 import { EXPERIMENT_WORDS, attachMachine, beginExperiment, experiments, recordResult } from "../cloud/experiments.ts";
1212 import { TARGETS } from "../cloud/targets.ts";
1313 import { listCloudAccounts } from "../core/cloud_account.ts";
@@ -43,15 +43,15 @@ function shown(ctx: Ctx, title: string, v: Issued): Response {
4343 return response;
4444 }
4545
46 function render(ctx: Ctx, v: DeployForm, flash?: { tone: "danger"; message: string }): Response {
46 function render(ctx: Ctx, v: DeployForm, flash?: { tone: "danger" | "attn"; message: string }, points = ""): Response {
4747 return page(
4848 {
4949 ctx,
5050 title: "Deploy to…",
51 body: deployPage(listCloudAccounts(ctx.app.db), v, deployPlaces(ctx.app, TARGETS.map((t) => t.id)), getBaseDomain(ctx.app.db)),
51 body: deployPage(listCloudAccounts(ctx.app.db), v, deployPlaces(ctx.app, TARGETS.map((t) => t.id)), getBaseDomain(ctx.app.db), points),
5252 ...(flash ? { flash } : {}),
5353 },
54 flash ? 422 : 200,
54 points !== "" ? 409 : flash ? 422 : 200,
5555 );
5656 }
5757
@@ -72,6 +72,9 @@ async function deployToSubmit(ctx: Ctx): Promise<Response> {
7272 const bits = v.account.split("/");
7373 if (bits.length > 2) return render(ctx, v, { tone: "danger", message: "Pick a cloud account from the list." });
7474 const [target, account] = bits.length === 2 ? (bits as [string, string]) : ["digitalocean", v.account];
75 // A name that points somewhere already is moved only by a press that read where.
76 const now = await pointsNow(ctx.app, ctx.auth.user, v.name, v.host);
77 if (now !== "" && now !== field(form, "points")) return render(ctx, v, { tone: "attn", message: `${now}. ${MOVES_WORDS} Nothing was made: press Deploy again if you mean it.` }, now);
7578 const made = await deployPinned(ctx.app, ctx.auth.user, { ...v, target, account });
7679 if (!made.ok) return render(ctx, v, { tone: "danger", message: made.error });
7780 return shown(ctx, `Deployed ${made.value.name}`, made.value);
src/tui/screens/common.ts +3 −3
@@ -646,9 +646,9 @@ export function promptScreen(
646646 * `onSubmit` defers the push by one microtask — after the pop, before the
647647 * next frame — which is what lets a flow chain prompts and pickers.
648648 */
649 export function later(ctx: Ctx, next: () => Screen): Promise<void> {
650 return Promise.resolve().then(() => {
651 ctx.push(next());
649 export function later(ctx: Ctx, next: () => Screen | Promise<Screen>): Promise<void> {
650 return Promise.resolve().then(async () => {
651 ctx.push(await next());
652652 });
653653 }
654654
src/tui/screens/infra.ts +9 −11
@@ -149,9 +149,7 @@ function infraWithCompose(f: Session, ctx: Ctx): { screen: Screen; compose: (par
149149 items: c.sizes.map((z) => ({ id: z.slug, label: z.shape, hint: month(z.costCents) })),
150150 onPick: ([size = ""]) => {
151151 draft.size = size;
152 const planned = planDatabase(f.app, f.user, draft);
153 if (!planned.ok) return say(planned.error);
154 present(parent, planned.value);
152 void planDatabase(f.app, f.user, draft).then((planned) => (planned.ok ? present(parent, planned.value) : say(planned.error)));
155153 },
156154 }),
157155 );
@@ -265,10 +263,10 @@ function infraWithCompose(f: Session, ctx: Ctx): { screen: Screen; compose: (par
265263 return parent;
266264 }
267265 const d = { name: "", account: accounts[0]!, type: "A", host: "", value: "", port: "" };
268 const ask = (title: string, label: string, set: (v: string) => void, next: () => Screen): Screen =>
266 const ask = (title: string, label: string, set: (v: string) => void, next: () => Screen | Promise<Screen>): Screen =>
269267 promptScreen(ctx, parent, { title, label, onSubmit: (v) => { set(v.trim()); return later(ctx, next); } });
270 const showPlan = (): Screen => {
271 const planned = planRecord(f.app, f.user, d);
268 const showPlan = async (): Promise<Screen> => {
269 const planned = await planRecord(f.app, f.user, d);
272270 const p = planned.ok ? planned.value : undefined;
273271 const ready = p !== undefined && p.plan.refusals.length === 0 && p.plan.steps.length > 0;
274272 return confirmScreen(ctx, parent, {
@@ -285,11 +283,11 @@ function infraWithCompose(f: Session, ctx: Ctx): { screen: Screen; compose: (par
285283 },
286284 });
287285 };
288 const account = (): Screen =>
286 const account = (): Screen | Promise<Screen> =>
289287 accounts.length === 1
290288 ? showPlan()
291289 : pickerScreen(ctx, parent, { title: "Cloudflare account", items: accounts.map((a) => ({ id: a, label: a })), onPick: ([a = ""]) => { d.account = a; void later(ctx, showPlan); } });
292 const port = (): Screen => (d.type === "SRV" ? ask("Port", "the server's port", (v) => (d.port = v), account) : account());
290 const port = (): Screen | Promise<Screen> => (d.type === "SRV" ? ask("Port", "the server's port", (v) => (d.port = v), account) : account());
293291 const value = (): Screen => ask("Points to", d.type === "SRV" ? "the server's name" : "an IPv4 address", (v) => (d.value = v), port);
294292 const host = (): Screen => ask("Host", "the name in DNS, e.g. play.example.com", (v) => (d.host = v), value);
295293 return pickerScreen(ctx, parent, {
@@ -318,10 +316,10 @@ function infraWithCompose(f: Session, ctx: Ctx): { screen: Screen; compose: (par
318316 return parent;
319317 }
320318 const d = { name: "", players: "", where: "", domain: "", dns: accounts[0]!, repo: "", eula: false };
321 const ask = (title: string, label: string, set: (v: string) => void, next: () => Screen): Screen =>
319 const ask = (title: string, label: string, set: (v: string) => void, next: () => Screen | Promise<Screen>): Screen =>
322320 promptScreen(ctx, parent, { title, label, onSubmit: (v) => { set(v.trim()); return later(ctx, next); } });
323 const showPlan = (): Screen => {
324 const made = planMinecraft(f.app, f.user, d);
321 const showPlan = async (): Promise<Screen> => {
322 const made = await planMinecraft(f.app, f.user, d);
325323 if (!made.ok) return confirmScreen(ctx, parent, { title: "Not yet", body: [made.error], width: 96, actions: [{ label: "Close" }], onChoose: () => {} });
326324 return confirmScreen(ctx, parent, {
327325 title: made.value.planned.plan.refusals.length === 0 ? "The plan" : "Not yet",
src/tui/screens/pinned.ts +21 −3
@@ -12,7 +12,7 @@
1212 * nothing and does nothing.
1313 */
1414
15 import { DOMAIN_WORDS, endsWords, keepPinned, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, claimWords, deployPinned, fileForge, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, strayCloud, strayWords, updatePinned, type Issued } from "../../actions/pinned.ts";
15 import { DOMAIN_WORDS, endsWords, keepPinned, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, claimWords, deployPinned, MOVES_WORDS, pointsNow, fileForge, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, strayCloud, strayWords, updatePinned, type Issued } from "../../actions/pinned.ts";
1616 import type { Ctx, Screen } from "../app/app.ts";
1717 import { binding } from "../app/keys.ts";
1818 import { style } from "../term/style.ts";
@@ -130,6 +130,25 @@ function offerStrays(f: Session, ctx: Ctx, screen: Screen, say: (text: string) =
130130 );
131131 }
132132
133 /** Deploy at once, or, when the name points somewhere already, only after the person read where. */
134 async function deployAsked(f: Session, ctx: Ctx, say: (text: string) => void, input: Parameters<typeof deployPinned>[2], parent: Screen): Promise<void> {
135 const go = (): Promise<void> => {
136 say(`Deploying ${input.name}…`);
137 return hand(ctx, say, deployPinned(f.app, f.user, input), parent);
138 };
139 const now = await pointsNow(f.app, f.user, input.name, input.host ?? "");
140 if (now === "") return go();
141 ctx.push(
142 confirmScreen(ctx, parent, {
143 title: `Deploy ${input.name}?`,
144 body: wrap(`${now}. ${MOVES_WORDS}`, 92),
145 actions: [{ label: "Deploy" }, { label: "Cancel" }],
146 width: 100,
147 onChoose: (i) => void (i === 0 && go()),
148 }),
149 );
150 }
151
133152 export function pinnedScreen(f: Session, ctx: Ctx): Screen {
134153 const state = new ListState();
135154 let note = "";
@@ -157,8 +176,7 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen {
157176 const host = hostWord === "-" ? "" : hostWord;
158177 const [target = "", account = "", ...more] = cloud.split("/");
159178 if (rest.length > 0 || more.length > 0 || version === "" || account === "") return "Write: name hostname provider/account owner/app source version [place]; a place is provider:datacenter:size, and left out it is the default.";
160 say(`Deploying ${name}…`);
161 return hand(ctx, say, deployPinned(f.app, f.user, { name, host, target, account, app, source, version, place }), parent);
179 return deployAsked(f, ctx, say, { name, host, target, account, app, source, version, place }, parent);
162180 },
163181 });
164182
src/web/pinned.ts +2 −1
@@ -66,7 +66,7 @@ const DEPLOYABLE = new Set<string>(TARGETS.filter((t) => t.status === "first").m
6666 */
6767 const NAMES = TARGETS.filter((t) => DEPLOYABLE.has(t.id)).map((t) => t.label).join(" or ");
6868
69 export function deployPage(accounts: CloudAccount[], v: DeployForm, places: Place[], domain = ""): Html {
69 export function deployPage(accounts: CloudAccount[], v: DeployForm, places: Place[], domain = "", points = ""): Html {
7070 const usable = accounts.filter((a) => DEPLOYABLE.has(a.provider) && a.writeAllowed);
7171 const providers = new Set<string>(usable.map((a) => a.provider));
7272 const offered = places.filter((p) => providers.has(p.provider));
@@ -83,6 +83,7 @@ export function deployPage(accounts: CloudAccount[], v: DeployForm, places: Plac
8383 <a href="/settings/cloud">Cloud accounts</a>, then come back to this page: what the link carried is kept.</p>`
8484 : null}
8585 <form method="post" action="/deploy-to" class="stack">
86 ${points === "" ? null : html`<input type="hidden" name="points" value="${points}" />`}
8687 ${selectField({
8788 name: "account",
8889 label: "Cloud account",
test/boot-size.test.ts +1 −1
@@ -111,7 +111,7 @@ test("a new box over the limit makes nothing, and the plan says so before anyone
111111 expect(writes()).toHaveLength(made);
112112 const want = gameWant({ name: "third", where: `digitalocean/main@${PLACE}`, repo: "alice/third" });
113113 if (!want.ok) throw new Error(want.error);
114 const planned = planWants(app, admin, [{ ...want.value, source: "https://forge.example/alice/forge.git", version: "a".repeat(40) } as typeof want.value]);
114 const planned = await planWants(app, admin, [{ ...want.value, source: "https://forge.example/alice/forge.git", version: "a".repeat(40) } as typeof want.value]);
115115 if (!planned.ok) throw new Error(planned.error);
116116 expect(planned.value.plan.steps).toEqual([]);
117117 expect(planned.value.plan.refusals).toEqual([{ name: "third", why: expect.stringContaining("third's boot config is ") }]);
test/conversation-ask.test.ts +1 −1
@@ -537,7 +537,7 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [
537537 [
538538 "pinned_forge",
539539 { verb: "deploy", name: "shop", target: "hetzner" },
540 "Deploy the pinned forge shop on hetzner.",
540 "Deploy the pinned forge shop on hetzner; an A record its name has already is changed to the new machine.",
541541 ],
542542 ["pinned_forge", { verb: "claim", name: "shop" }, "Make a fresh claim link for the pinned forge shop."],
543543 ["pinned_forge", { verb: "domain", domain: "forges.example" }, "Set the domain pinned forges are named under to forges.example."],
test/game-box.test.ts +2 −2
@@ -145,11 +145,11 @@ describe("on a forge", () => {
145145 expect(gameBootConfig({ forgeUrl: "https://forge.example", token: next }, "/mnt/x")).toContain(next);
146146 });
147147
148 test("a game box's plan costs what the catalog says, never ends, and waits for no https answer", () => {
148 test("a game box's plan costs what the catalog says, never ends, and waits for no https answer", async () => {
149149 const want = gameWant({ name: "mc", where: "digitalocean/main@digitalocean:nyc3:s-4vcpu-8gb", repo: "alice/net", host: "mc.trevato.dev" });
150150 if (!want.ok) throw new Error(want.error);
151151 expect(want.value).toMatchObject({ boots: "game", app: "alice/net", host: "mc.trevato.dev" });
152 const planned = planWants(app, alice, [want.value]);
152 const planned = await planWants(app, alice, [want.value]);
153153 if (!planned.ok) throw new Error(planned.error);
154154 const p = planned.value.plan;
155155 expect(p.refusals).toEqual([]);
test/game-second-box.test.ts +5 −5
@@ -114,24 +114,24 @@ test("the Minecraft design refuses it, from the tool and in the terminal", async
114114 allowWrite(app, admin, "cloudflare", "main", false);
115115 });
116116
117 test("two new boxes on one file in one plan: the second is refused", () => {
117 test("two new boxes on one file in one plan: the second is refused", async () => {
118118 const want = (name: string) => {
119119 const w = gameWant({ name, where: WHERE, repo: "alice/pair" });
120120 if (!w.ok) throw new Error(w.error);
121121 return w.value;
122122 };
123 const p = planWants(app, admin, [want("one"), want("two")]);
123 const p = await planWants(app, admin, [want("one"), want("two")]);
124124 if (!p.ok) throw new Error(p.error);
125125 expect(p.value.plan.refusals).toEqual([{ name: "two", why: expect.stringContaining("one runs alice/pair's") }]);
126126 });
127127
128 test("Build again of a kept plan refuses it, and makes nothing", () => {
128 test("Build again of a kept plan refuses it, and makes nothing", async () => {
129129 const w = gameWant({ name: "second", where: WHERE, repo: "alice/mc" });
130130 if (!w.ok) throw new Error(w.error);
131131 const planId = `plan-${"1".repeat(16)}`;
132132 app.bus.append({ kind: "infra.applied", actorId: admin.id, payload: { planId, wants: [w.value], complete: false, clears: [], steps: ["x"], summary: "", etaSeconds: 0, needs: [] } });
133133 const calls = cloud.calls.length;
134 const r = rebuild(app, admin, planId);
134 const r = await rebuild(app, admin, planId);
135135 expect(r.ok ? "" : r.error).toContain(WHY);
136136 expect([cloud.calls.length, getPinned(app.db, "second")]).toEqual([calls, undefined]);
137137 });
@@ -147,7 +147,7 @@ test("the box that stands plans as built, updates and replaces as before", async
147147 const p = getPinned(app.db, "mc")!;
148148 const want = gameWant({ name: "mc", where: WHERE, repo: "alice/mc", host: p.host });
149149 if (!want.ok) throw new Error(want.error);
150 const planned = planWants(app, admin, [want.value]);
150 const planned = await planWants(app, admin, [want.value]);
151151 if (!planned.ok) throw new Error(planned.error);
152152 expect(planned.value.plan.refusals).toEqual([]);
153153 expect(planned.value.plan.steps.filter((s) => s.kind === "machine")).toEqual([]);
test/infra-dns.test.ts +6 −6
@@ -263,7 +263,7 @@ describe("a DNS record on a forge", () => {
263263 });
264264
265265 test("builds through the plan, shows as a row, and the hourly look finds what drifted", async () => {
266 const planned = planWants(app, who(), [dnsWant("mc")]);
266 const planned = await planWants(app, who(), [dnsWant("mc")]);
267267 if (!planned.ok) throw new Error(planned.error);
268268 expect(planned.value.plan.refusals).toEqual([]);
269269 const started = startBuild(app, who(), planned.value.plan);
@@ -283,7 +283,7 @@ describe("a DNS record on a forge", () => {
283283 expect(getDns(app.db, "mc")!.drift).toContain("was changed at Cloudflare");
284284 const row = infraOf(app, who());
285285 expect(row.ok && row.value.records[0]!.drift).toContain("now reads SRV → box.example.com:9");
286 const fix = planWants(app, who(), [dnsWant("mc")]);
286 const fix = await planWants(app, who(), [dnsWant("mc")]);
287287 expect(fix.ok && fix.value.plan.steps[0]!.says).toStartWith("Put back the DNS record");
288288 expect(app.db.query("SELECT 1 FROM event WHERE kind = 'dns.drift'").get()).not.toBeNull();
289289
@@ -334,12 +334,12 @@ describe("a DNS record on a forge", () => {
334334
335335 test("a person makes a record and removes it, on the page and in the terminal", async () => {
336336 const fields = { name: "web", account: "cloudflare/main", type: "a", host: "Web.Example.com", value: "203.0.113.9", port: "" };
337 expect(planRecord(app, undefined, fields)).toEqual({ ok: false, error: "not_found" });
338 const planned = planRecord(app, who(), fields);
337 expect(await planRecord(app, undefined, fields)).toEqual({ ok: false, error: "not_found" });
338 const planned = await planRecord(app, who(), fields);
339339 if (!planned.ok) throw new Error(planned.error);
340340 expect(planned.value.plan.steps.map((s) => s.says)).toEqual(["Write the DNS record A web.example.com → 203.0.113.9 in Cloudflare"]);
341341 // A bad record is refused in a sentence before anything is built.
342 const bad = planRecord(app, who(), { ...fields, value: "nope" });
342 const bad = await planRecord(app, who(), { ...fields, value: "nope" });
343343 expect(bad.ok && bad.value.plan.refusals.length).toBe(1);
344344 expect(recordAccounts(app)).toEqual(["cloudflare/main"]);
345345
@@ -383,7 +383,7 @@ describe("a DNS record on a forge", () => {
383383 tui.stop?.();
384384
385385 // The route's own removal is the same action, and says so on the outbox.
386 const built = planRecord(app, who(), fields);
386 const built = await planRecord(app, who(), fields);
387387 if (!built.ok) throw new Error(built.error);
388388 expect(startBuild(app, who(), built.value.plan).ok).toBe(true);
389389 await pollUntil(() => getDns(app.db, "web") !== undefined, "the page made its record");
test/job-slices.test.ts +1
@@ -313,6 +313,7 @@ const UNTIMED: Record<string, string> = {
313313 "allocation": "one settle pass hourly over repositories with a wallet (core/allocation.ts settleAll): indexed reads and a write only when a week turned; allocation tests drive settleAll directly",
314314 "copies-prune": "two DELETEs on indexed time columns (core/copies.ts pruneCopies), hourly on the outsider prune's own timer; copies-elsewhere.test.ts drives both fades",
315315 "places-page-wait": "a one-shot timer in the new-forge page that only resolves the race when the Places catalog refresh outlives PAGE_WAIT_MS; no work of its own; new-forge-refresh.test.ts drives the refresh",
316 "pinned-points-wait": "a one-shot timer that only resolves the race when DNS has not answered for a deploy's name in LOOK_MS; no work of its own; pinned-dns.test.ts asks with a DNS that never answers",
316317 "tell-origin-wait": "a one-shot timer that only resolves the race when an origin has not answered a copy's report in TELL_MS; no work of its own; copies-elsewhere.test.ts tells a forge that answers",
317318 "presence-ping": "a per-stream timer (one per open Talk or repository page) that only refreshes its own seat's time in an in-memory map (core/presence.ts stillHere): no query, no write; together.test.ts drives the seat it keeps",
318319 "deploy-hold": "a one-shot timer in apps/runtime_events.ts that only resolves the sleep between a production deploy's looks for a safe moment; no work of its own; the deploy-batching tests drive it with a fake sleep",
test/managed-database.test.ts +7 −7
@@ -197,22 +197,22 @@ describe("a database on a forge", () => {
197197 await rm(dataDir, { recursive: true, force: true });
198198 });
199199
200 test("every door's choices and compose read the same plan", () => {
200 test("every door's choices and compose read the same plan", async () => {
201201 const c = databaseChoices(app);
202202 expect(c.apps).toEqual(["alice/shop"]);
203203 expect(c.regions.length).toBeGreaterThan(0);
204204 expect(c.regions[0]!.value).toMatch(/^digitalocean\/main@[a-z]{3}\d$/);
205205 expect(c.sizes.map((s) => s.costCents)).toEqual([1500, 3000, 6000, 12000]);
206 const lacks = planDatabase(app, admin(), { app: "alice/shop", where: "", size: "", name: "", secret: "" });
206 const lacks = await planDatabase(app, admin(), { app: "alice/shop", where: "", size: "", name: "", secret: "" });
207207 expect(lacks.ok && lacks.value.lacks).toContain("Pick where");
208208 expect(databaseWantOf({ app: "alice/shop", where: "digitalocean/main@nyc1", size: "", name: "", secret: "" })).toMatchObject({ ok: true, value: { kind: "database", size: "db-s-1vcpu-1gb" } });
209 const ok1 = planDatabase(app, admin(), { app: "alice/shop", where: "digitalocean/main@nyc1", size: "", name: "shop-db", secret: "" });
209 const ok1 = await planDatabase(app, admin(), { app: "alice/shop", where: "digitalocean/main@nyc1", size: "", name: "shop-db", secret: "" });
210210 expect(ok1.ok && ok1.value.plan.refusals).toEqual([]);
211 expect(planDatabase(app, undefined, { app: "alice/shop", where: "digitalocean/main@nyc1", size: "", name: "", secret: "" })).toEqual({ ok: false, error: "not_found" });
211 expect(await planDatabase(app, undefined, { app: "alice/shop", where: "digitalocean/main@nyc1", size: "", name: "", secret: "" })).toEqual({ ok: false, error: "not_found" });
212212 });
213213
214214 test("a refused create leaves no cluster, and a retry makes exactly one", async () => {
215 const planned = planDatabase(app, admin(), { app: "alice/shop", where: "digitalocean/main@nyc1", size: "", name: "shop-db", secret: "" });
215 const planned = await planDatabase(app, admin(), { app: "alice/shop", where: "digitalocean/main@nyc1", size: "", name: "shop-db", secret: "" });
216216 if (!planned.ok) throw new Error(planned.error);
217217 const p = planned.value.plan;
218218 fail = 422;
@@ -318,8 +318,8 @@ describe("a database on a forge", () => {
318318 expect(planned.refusals).toEqual([]);
319319 });
320320
321 test("planning it again finds nothing to build", () => {
322 const again = planDatabase(app, admin(), { app: "alice/shop", where: "digitalocean/main@nyc1", size: "", name: "shop-db", secret: "" });
321 test("planning it again finds nothing to build", async () => {
322 const again = await planDatabase(app, admin(), { app: "alice/shop", where: "digitalocean/main@nyc1", size: "", name: "shop-db", secret: "" });
323323 expect(again.ok && again.value.plan.steps).toEqual([]);
324324 expect(again.ok && again.value.plan.deltaCents).toBe(0);
325325 });
test/minecraft-design.test.ts +6 −6
@@ -119,12 +119,12 @@ describe("the doors", () => {
119119 await rm(dir, { recursive: true, force: true });
120120 });
121121
122 test("a place the forge has not read is not planned", () => {
123 expect(planMinecraft(app, alice(), { ...input, where: "digitalocean/main@digitalocean:nyc3:nope" })).toEqual({ ok: false, error: "Pick where the server runs." });
122 test("a place the forge has not read is not planned", async () => {
123 expect(await planMinecraft(app, alice(), { ...input, where: "digitalocean/main@digitalocean:nyc3:nope" })).toEqual({ ok: false, error: "Pick where the server runs." });
124124 });
125125
126 test("a kept place plans both wants through the plan, with the compose file and what is left to do", () => {
127 const made = planMinecraft(app, alice(), { ...input, where });
126 test("a kept place plans both wants through the plan, with the compose file and what is left to do", async () => {
127 const made = await planMinecraft(app, alice(), { ...input, where });
128128 if (!made.ok) throw new Error(made.error);
129129 const p = made.value.planned.plan;
130130 expect(p.refusals).toEqual([]);
@@ -137,8 +137,8 @@ describe("the doors", () => {
137137 expect(made.value.note).toContain("play.example.com");
138138 });
139139
140 test("a person who is not an admin gets the plan's own refusal", () => {
141 expect(planMinecraft(app, getUserByName(app.db, "bob")!, { ...input, where })).toEqual({ ok: false, error: "not_found" });
140 test("a person who is not an admin gets the plan's own refusal", async () => {
141 expect(await planMinecraft(app, getUserByName(app.db, "bob")!, { ...input, where })).toEqual({ ok: false, error: "not_found" });
142142 });
143143
144144 test("the infra tool plans a full want, with the compose file and steps, and says what is missing", async () => {
test/pinned-dns.test.ts +76
@@ -22,14 +22,20 @@ import {
2222 claimWords,
2323 deployPinned,
2424 net,
25 pointsNow,
2526 readBaseDomain,
2627 updatePinned,
2728 } from "../src/actions/pinned.ts";
29 import { planWants } from "../src/actions/infra.ts";
2830 import { setCeiling } from "../src/actions/cloud_ceiling.ts";
2931 import { dnsOf, getPinned } from "../src/core/pinned.ts";
3032 import { createUser, getUserByName } from "../src/core/users.ts";
33 import { createForgeApp } from "../src/tui/forge.ts";
34 import { pinnedScreen } from "../src/tui/screens/pinned.ts";
35 import { headlessTerminal } from "../src/tui/term/terminal.ts";
3136 import { getBaseDomain } from "../src/settings/pinned_domain.ts";
3237 import { quietLogs } from "./helpers/globals.ts";
38 import { settleApp } from "./helpers/tui.ts";
3339 import { seedPlaces } from "./helpers/places-fixture.ts";
3440
3541 quietLogs();
@@ -386,6 +392,76 @@ describe("a deploy needs no DNS work from its buyer", () => {
386392 );
387393 });
388394
395 test("where the name points now is in the plan's step, and the answer names the address that was replaced", async () => {
396 const want = {
397 kind: "machine" as const,
398 name: "busy",
399 account: "digitalocean/main",
400 place: "digitalocean:nyc3:s-1vcpu-2gb",
401 app: "alice/shop",
402 source: SOURCE,
403 version: V1,
404 };
405 const step = async () => {
406 const p = await planWants(app, admin(), [want]);
407 return p.ok ? p.value.plan.steps.find((s) => s.kind === "dns")?.says : p.error;
408 };
409 const resolve = net.resolve;
410 try {
411 expect(await step()).toBe("Point busy.forges.test at it in Cloudflare");
412 net.resolve = async () => ["198.51.100.9", "198.51.100.4"];
413 expect(await step()).toBe(
414 "Point busy.forges.test at it in Cloudflare: DNS sends busy.forges.test to 198.51.100.4 and 198.51.100.9 now",
415 );
416 // No answer is not "points nowhere", whether DNS fails or keeps silent.
417 net.resolve = () => Promise.reject(new Error("SERVFAIL"));
418 const silent = "DNS did not say where busy.forges.test points now";
419 expect(await pointsNow(app, admin(), "busy", "")).toBe(silent);
420 net.resolve = () => new Promise(() => {});
421 expect(await pointsNow(app, admin(), "busy", "")).toBe(silent);
422 expect(await pointsNow(app, undefined, "busy", "")).toBe("");
423 // A forge's own machine is nothing to move.
424 net.resolve = async () => [getPinned(app.db, "acme")!.address];
425 expect(await pointsNow(app, admin(), "acme", "")).toBe("");
426 } finally {
427 net.resolve = resolve;
428 }
429 records.push({ id: (++seq).toString(16).padStart(32, "0"), type: "A", name: "busy.forges.test", content: "198.51.100.4", proxied: false, ttl: 300 });
430 const r = await deployPinned(app, admin(), input("busy"));
431 expect(r.ok && r.value.dnsWas).toBe("198.51.100.4");
432 expect(r.ok && claimWords(r.value)).toContain("That record named 198.51.100.4 before.");
433 expect(
434 app.db.query<{ was: string }, []>("SELECT json_extract(payload, '$.was') AS was FROM event WHERE kind = 'pinned.dns' ORDER BY seq DESC LIMIT 1").get()?.was,
435 ).toBe("198.51.100.4");
436 const fresh = await deployPinned(app, admin(), input("calm"));
437 expect(fresh.ok && "dnsWas" in fresh.value).toBe(false);
438 });
439
440 test("the terminal asks before it moves a name that points somewhere", async () => {
441 const { app: tui, session } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin() }, { terminal: headlessTerminal(200, 24), exitHooks: false });
442 tui.start();
443 tui.ctx.push(pinnedScreen(session, tui.ctx));
444 await settleApp(tui);
445 const press = (key: string) => tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
446 const resolve = net.resolve;
447 try {
448 net.resolve = async () => ["198.51.100.4"];
449 press("d");
450 await settleApp(tui);
451 for (const ch of `term - digitalocean/main alice/shop ${SOURCE} ${V1}`) press(ch);
452 press("enter");
453 await settleApp(tui);
454 expect(tui.screen.toText()).toContain("DNS sends term.forges.test to 198.51.100.4 now");
455 expect(getPinned(app.db, "term")).toBeUndefined();
456 press("enter");
457 await settleApp(tui);
458 expect(getPinned(app.db, "term")?.host).toBe("term.forges.test");
459 } finally {
460 net.resolve = resolve;
461 tui.stop?.();
462 }
463 });
464
389465 test("a Cloudflare account that does not allow writes is never asked to write", async () => {
390466 allowWrite(app, admin(), "cloudflare", "main", false);
391467 cf.length = 0;
test/pinned-domain-doors.test.ts +33
@@ -212,6 +212,39 @@ describe("the domain for deployed forges", () => {
212212 expect(getPinned(app.db, "acme")!.host).toBe("acme.forges.test");
213213 });
214214
215 test("a name that points somewhere already: the first press says where and makes nothing, the second deploys", async () => {
216 const added = await addAccount(app, getUserByName(app.db, "alice"), "cloudflare", "main", "cf_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9Lm2");
217 if (!added.ok) throw new Error(String(added.error));
218 allowWrite(app, getUserByName(app.db, "alice"), "cloudflare", "main", true);
219 const resolve = net.resolve;
220 const post = (over: Record<string, string>) =>
221 fetch(`${servers.url}/deploy-to`, {
222 method: "POST",
223 redirect: "manual",
224 headers: headers(adminTok, { "content-type": "application/x-www-form-urlencoded" }),
225 body: new URLSearchParams({ name: "live", host: "", account: "main", app: "alice/shop", source: SOURCE, version: V, ...over }),
226 });
227 try {
228 net.resolve = async () => ["198.51.100.4"];
229 const first = await post({});
230 expect(first.status).toBe(409);
231 const says = "DNS sends live.forges.test to 198.51.100.4 now";
232 const page = await first.text();
233 expect(page).toContain(says);
234 expect(page).toContain('name="points"');
235 expect(getPinned(app.db, "live")).toBeUndefined();
236 // The address changed since it was read: asked again.
237 net.resolve = async () => ["198.51.100.5"];
238 expect((await post({ points: says })).status).toBe(409);
239 expect(getPinned(app.db, "live")).toBeUndefined();
240 net.resolve = async () => ["198.51.100.4"];
241 expect((await post({ points: says })).status).toBe(200);
242 expect(getPinned(app.db, "live")!.host).toBe("live.forges.test");
243 } finally {
244 net.resolve = resolve;
245 }
246 });
247
215248 test("the MCP tool reads and sets it with the `domain` verb, and sets it only with an admin-scope token", async () => {
216249 const ro = createToken(
217250 app.db,

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

Keyboard shortcuts

Docs