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

Deploys never move a live name by surprise: DNS is asked before Build, a restore asks once more #18030

opened this

Merged 12h 13m ago, live in production

sold/deploy-points → main 0 commits

  • Merged. sold/deploy-points was merged into main as 49e77a8.

Review

Sign in to review this change.
29 files changed +325 −79
docs/features/pinned-forge.md +1 −1
@@ -89,7 +89,7 @@ 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.
92 **A name that points somewhere already** is moved only by a call that repeats where. Before a deploy the forge asks DNS for the name's A records (`pointsNow`, at most 1.5 seconds). When the name points elsewhere, or DNS gives no answer, `deployPinned` makes nothing and answers that sentence; it goes on when the call carries the same sentence in `points`, and an address that changed in between is asked again. The Deploy to… form and the terminal's `d` show it and ask once more. The API answers 409 `points_elsewhere` with `points`, the `pinned_forge` tool the same refusal, and the agent's held confirm shows the sentence the call repeats. The infrastructure plan's DNS step names it at every door and carries it, and Build and Build again stop when it differs. Build asks about all its names at once before it makes anything; when a name changes after that, the run stops at that machine, what earlier steps made stays and is billed, and planning it again goes on from there. A name whose addresses rotate may be asked about again at each press. A restore of a snapshot asks once more in the same way, on the web and in the terminal. The deploy's answer names the address the record held before (`dnsWas`), as the `pinned.dns` event does (`was`). A paid order's own name is not asked about. A proxied name shows its proxy's addresses, and IPv6 is not looked at.
9393
9494 ## Paid forges on a cloud machine (#16205)
9595
src/actions/infra.ts +12 −3
@@ -700,6 +700,9 @@ export async function planCompose(app: App, actor: User | undefined, c: Compose,
700700 return planWants(app, actor, [want.value]);
701701 }
702702
703 /** What a plan says of where its names point: kept with its build, and sent back by the page's Build. */
704 export const pointsOf = (p: Plan): string[] => p.steps.flatMap((s) => (s.points === undefined ? [] : [s.points]));
705
703706 /** 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. */
704707 async function withPoints(app: App, actor: User | undefined, p: Plan): Promise<Plan> {
705708 const steps = await Promise.all(
@@ -707,7 +710,7 @@ async function withPoints(app: App, actor: User | undefined, p: Plan): Promise<P
707710 const w = s.kind === "dns" ? p.wants.find((x) => x.kind === "machine" && x.name === s.name) : undefined;
708711 if (w?.kind !== "machine") return s;
709712 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}` };
713 return now === "" ? s : { ...s, says: `${s.says}: ${now}`, points: now };
711714 }),
712715 );
713716 return { ...p, steps };
@@ -766,7 +769,7 @@ export function startBuild(app: App, actor: User | undefined, p: Plan): Result<s
766769 app.bus.append({
767770 kind: "infra.applied",
768771 actorId: who.value.id,
769 payload: { planId: p.id, wants: p.wants, complete: p.complete, clears: p.clears, steps: p.steps.map((s) => s.says), summary: summaryOf(p), etaSeconds: p.etaSeconds, needs: p.needs },
772 payload: { planId: p.id, wants: p.wants, complete: p.complete, clears: p.clears, steps: p.steps.map((s) => s.says), summary: summaryOf(p), etaSeconds: p.etaSeconds, needs: p.needs, points: pointsOf(p) },
770773 });
771774 void apply(app, who.value, p)
772775 .then((r) => {
@@ -802,6 +805,8 @@ export interface Build {
802805 readonly wants: readonly Want[];
803806 /** The dead rows the plan clears. */
804807 readonly clears: readonly string[];
808 /** Where its names pointed when it was shown (`pointsOf`). */
809 readonly points: readonly string[];
805810 }
806811
807812 /** The latest build of plan `planId`, from the outbox; undefined when none was started. */
@@ -815,7 +820,7 @@ export function buildOf(app: App, actor: User | undefined, planId: string): Buil
815820 .all(planId);
816821 const start = rows.map((r) => r.kind).lastIndexOf("infra.applied");
817822 if (start < 0) return undefined;
818 const head = JSON.parse(rows[start]!.payload) as { steps: string[]; wants: Want[]; clears?: string[]; summary?: string; etaSeconds?: number; needs?: string[] };
823 const head = JSON.parse(rows[start]!.payload) as { steps: string[]; wants: Want[]; clears?: string[]; summary?: string; etaSeconds?: number; needs?: string[]; points?: string[] };
819824 const steps = head.steps.map((says, index) => ({ index, says, state: "waiting" as StepState, why: "" }));
820825 let refused = "";
821826 for (const r of rows.slice(start + 1)) {
@@ -844,6 +849,7 @@ export function buildOf(app: App, actor: User | undefined, planId: string): Buil
844849 // A build kept from before `boots` says `game: true`: built again, it is still a game box.
845850 wants: head.wants.map((w) => (w.kind === "machine" && (w as { game?: boolean }).game === true ? { ...w, boots: "game" as const } : w)),
846851 clears: head.clears ?? [],
852 points: head.points ?? [],
847853 state: failed ? "failed" : done ? "done" : "running",
848854 urls: done ? head.wants.map((w) => hosts.get(w.name) ?? "").filter((u) => u !== "") : [],
849855 };
@@ -855,6 +861,9 @@ export async function rebuild(app: App, actor: User | undefined, planId: string)
855861 if (b === undefined) return err("No such build.");
856862 const again = await planWants(app, actor, b.wants, false, b.clears);
857863 if (!again.ok) return again;
864 // Build again is pressed beside the old plan: a name that points elsewhere by now was not in it.
865 const unread = pointsOf(again.value.plan).filter((x) => !b.points.includes(x));
866 if (unread.length > 0) return err(`Since the plan was shown: ${unread.join(". ")}. Nothing was built; plan it again.`);
858867 return startBuild(app, actor, again.value.plan);
859868 }
860869
src/actions/infra_snapshot.ts +9 −6
@@ -28,7 +28,7 @@ import { getPinned, placeIdOf, type Pinned } from "../core/pinned.ts";
2828 import type { User } from "../core/users.ts";
2929 import { besideBox, boxNamed, type GameBox } from "../games/store.ts";
3030 import { err, ok, type Result } from "../kernel/result.ts";
31 import { admin, dayWords, deployPinned, oneChange, retirePinned, withCloud, type Issued, type Retired } from "./pinned.ts";
31 import { admin, dayWords, deployPinned, oneChange, retirePinned, withCloud, type Issued, type Moves, type Retired } from "./pinned.ts";
3232
3333 /**
3434 * How long an End that snapshots first waits for the snapshot to complete, and how often it asks.
@@ -172,30 +172,33 @@ function boxRefused(app: App, s: Snapshot, of: GameBox, name: string): string |
172172 * Bring a snapshot back as what it was taken of, under a new `name` at the place it was taken: the
173173 * same deploy as any other, so its ceiling, its claim link and its refusals are the deploy's. A game
174174 * box comes back as a box of its own, with its own row and token; the old one's row is not touched.
175 * One at a time for what it was taken of, so two restores never start beside each other.
175 * One at a time for what it was taken of, so two restores never start beside each other. A name that
176 * points elsewhere is moved only when `points` repeats where, as in any deploy.
176177 */
177 export async function restoreSnapshot(app: App, actor: User | undefined, id: string, name: string): Promise<Result<Issued, string>> {
178 export async function restoreSnapshot(app: App, actor: User | undefined, id: string, name: string, points = ""): Promise<Result<Issued, string | Moves>> {
178179 const who = admin(actor);
179180 if (!who.ok) return who;
180181 const s = getSnapshot(app.db, id);
181182 if (!s) return err("No such snapshot.");
182 return oneChange(app, s.name, () => restoreNow(app, actor, who, s, name));
183 return oneChange(app, s.name, () => restoreNow(app, actor, who, s, name, points));
183184 }
184185
185 async function restoreNow(app: App, actor: User | undefined, who: ReturnType<typeof admin> & { ok: true }, s: Snapshot, name: string): Promise<Result<Issued, string>> {
186 async function restoreNow(app: App, actor: User | undefined, who: ReturnType<typeof admin> & { ok: true }, s: Snapshot, name: string, points: string): Promise<Result<Issued, string | Moves>> {
186187 if (s.state !== "ready") return err(snapshotView(s).restoreRefused);
187188 const of = getPinned(app.db, s.name);
188189 const box = boxNamed(app.db, s.name);
189190 const no = box === undefined ? undefined : boxRefused(app, s, box, name);
190191 if (no !== undefined) return err(no);
191192 const made = await deployPinned(app, actor, {
193 points,
192194 boots: box === undefined ? of?.boots : "game",
193195 client: of?.client,
194196 ...(box === undefined ? {} : { box: { branch: box.branch, path: box.path, restoredFrom: box.id } }),
195197 name, host: "", target: s.target, account: s.account, app: box?.repo ?? s.app, source: s.source, version: s.version, config: s.config,
196198 place: placeIdOf(s), restore: { id: s.remote, what: s.what },
197199 });
198 if (made.ok) app.bus.append({ kind: "infra.restored", actorId: who.value.id, payload: { name, from: s.name, id: s.id } });
200 if (!made.ok) return made;
201 app.bus.append({ kind: "infra.restored", actorId: who.value.id, payload: { name, from: s.name, id: s.id } });
199202 return made;
200203 }
201204
src/actions/pinned.ts +22 −4
@@ -308,8 +308,17 @@ async function writeDns(app: App, who: Who, name: string): Promise<string | unde
308308 return undefined;
309309 }
310310
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.";
311 /** A deploy that would move a name nobody read about: it made nothing, and goes on when the call repeats `points`. */
312 export interface Moves {
313 readonly points: string;
314 }
315
316 /** A refused deploy in words, at every door. */
317 export const deployWords = (e: string | Moves): string =>
318 typeof e === "string" ? e : `${e.points}. Deploying points that name at the new machine, and what answers there now is no longer reached by it. Nothing was made.`;
319
320 /** The same for a caller with no form to press twice: what it sends to go on. */
321 export const repeatWords = (e: Moves): string => `${deployWords(e)} If the name is meant to move, make the same call with points: "${e.points}"`;
313322
314323 /** How long a page waits for DNS before it says that DNS did not answer. */
315324 const LOOK_MS = 1_500;
@@ -496,6 +505,8 @@ export type DeployInput = {
496505 * restored, not made new.
497506 */
498507 restore?: Restore | undefined;
508 /** What the person read of where the name points now (`pointsNow`); empty when it pointed nowhere. */
509 points?: string | undefined;
499510 };
500511
501512 /**
@@ -511,9 +522,16 @@ function bootOf(app: App, p: Pinned): () => Pinned & { game?: GameBoot } {
511522 return () => ({ ...p, game: { forgeUrl: (app.config.url ?? "").replace(/\/+$/, ""), token: rotateGameBoxToken(app.db, box.id) } });
512523 }
513524
514 export async function deployPinned(app: App, actor: User | undefined, input: DeployInput): Promise<Result<Issued, string>> {
525 /**
526 * Deploy a forge, a game box or a services machine as an admin. A name that points elsewhere, or that
527 * DNS gave no answer for, is moved only when `points` repeats that sentence: every door, and Build,
528 * goes through this one check.
529 */
530 export async function deployPinned(app: App, actor: User | undefined, { points = "", ...input }: DeployInput): Promise<Result<Issued, string | Moves>> {
515531 const who = admin(actor);
516 return who.ok ? deployAs(app, who.value, input) : who;
532 if (!who.ok) return who;
533 const now = await pointsNow(app, actor, input.name, input.host);
534 return now === "" || now === points ? deployAs(app, who.value, input) : err({ points: now });
517535 }
518536
519537 /**
src/cloud/plan.ts +21 −5
@@ -30,7 +30,7 @@
3030
3131 import type { App } from "../app.ts";
3232 import { dropRecord, putRecord } from "../actions/dns_record.ts";
33 import { besideNew, clearPinned, deployPinned, firewallPinned, net, newClaim, ownCode, LIFETIME_DAYS, LIFETIME_WORDS, MAX_LIFETIME_DAYS, retirePinned } from "../actions/pinned.ts";
33 import { besideNew, clearPinned, deployPinned, pointsNow, deployWords, firewallPinned, net, newClaim, ownCode, LIFETIME_DAYS, LIFETIME_WORDS, MAX_LIFETIME_DAYS, retirePinned } from "../actions/pinned.ts";
3434 import { stuckWords, WATCH } from "../actions/pinned_watch.ts";
3535 import { bindDatabase, createDatabase, ONLY_DIGITALOCEAN, pollDatabase } from "../actions/database.ts";
3636 import { getRepo } from "../core/repos.ts";
@@ -257,6 +257,8 @@ export interface Step {
257257 readonly says: string;
258258 /** What it changes a month, US cents: a machine's whole price (disk and address in it), a retire's saving negative. */
259259 readonly cents: number;
260 /** A `dns` step's: where its name pointed when the plan was shown (`pointsNow`). Build stops when that differs. */
261 readonly points?: string;
260262 }
261263
262264 export interface AccountVerdict {
@@ -771,7 +773,10 @@ export interface StepEvent {
771773 export interface Hands {
772774 /** The same wants planned again against what stands now. */
773775 replan(p: Plan): Plan;
774 deploy(w: MachineWant): Promise<Result<unknown, string>>;
776 /** What DNS says now of where its name points; empty when a deploy moves nothing. */
777 points(w: MachineWant): Promise<string>;
778 /** `points` is what the plan said of where its name points. */
779 deploy(w: MachineWant, points: string): Promise<Result<unknown, string>>;
775780 /** Write a DNS record, or change the one its name has; and take one away. */
776781 record(w: DnsWant): Promise<Result<unknown, string>>;
777782 unrecord(name: string): Promise<Result<unknown, string>>;
@@ -904,6 +909,13 @@ export async function apply(
904909 return ok({ planId: p.id, done, skipped, failed: { index: s.index, why } });
905910 };
906911
912 // Every name once, before anything is made: one that moved, or that DNS is silent about, must not stop
913 // a run that has made and billed things already. `deployPinned` asks again at its own step.
914 const read = (name: string): string => p.steps.find((x) => x.kind === "dns" && x.name === name)?.points ?? "";
915 const asked = await Promise.all(p.steps.filter((s) => s.kind === "machine" && !finished(s)).map(async (s) => ({ name: s.name, now: await hands.points(machineOf(s.name)!) })));
916 const moved = asked.filter((x) => x.now !== "" && x.now !== read(x.name));
917 if (moved.length > 0) return err(`Since the plan was shown: ${moved.map((x) => `${x.now}.`).join(" ")} Nothing was built; look at the plan again.`);
918
907919 for (let i = 0; i < p.steps.length; i++) {
908920 const s = p.steps[i]!;
909921 const waits = s.kind === "dns" || s.kind === "ready" || s.kind === "address";
@@ -917,7 +929,7 @@ export async function apply(
917929 const next = p.steps[i + 1];
918930 if (s.kind === "disk" && next?.kind === "machine" && next.name === s.name && !finished(next)) group.push(next);
919931 for (const g of group) say(g, "started");
920 const r = await hands.deploy(machineOf(s.name)!);
932 const r = await hands.deploy(machineOf(s.name)!, read(s.name));
921933 for (const g of group) {
922934 if (!finished(g)) return failed(g, r.ok ? `The deploy answered, and ${s.name} has no ${g.kind} yet.` : r.error);
923935 say(g, "done");
@@ -1149,9 +1161,11 @@ function handsOf(app: App, actor: User | undefined): Hands {
11491161 return d === undefined ? undefined : { made: d.remote !== "", online: d.state === "online", bound: d.boundAt !== "" };
11501162 },
11511163 },
1152 deploy: (w) => {
1164 points: (w) => pointsNow(app, actor, w.name, w.host ?? ""),
1165 deploy: async (w, points) => {
11531166 const provider = providerOf(w.account);
1154 return deployPinned(app, actor, {
1167 const made = await deployPinned(app, actor, {
1168 points,
11551169 name: w.name,
11561170 host: w.host ?? "",
11571171 target: provider,
@@ -1164,6 +1178,8 @@ function handsOf(app: App, actor: User | undefined): Hands {
11641178 boots: w.boots,
11651179 client: w.client,
11661180 });
1181 if (made.ok || typeof made.error === "string") return made.ok ? made : err(deployWords(made.error));
1182 return err(`The plan did not say so: ${deployWords(made.error)} What earlier steps made stays, and is billed: plan it again, and Build goes on from there.`);
11671183 },
11681184 retire: (name) => retirePinned(app, actor, name),
11691185 record: (w) => putRecord(app, actor, w.name, w.account, w),
src/contract/openapi/routes/postApiV1AdminPinned.ts +4 −2
@@ -4,12 +4,14 @@ 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; `dnsWas` is the address the name's record held before, when this deploy changed it",
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; a name that points elsewhere, or that DNS gave no answer for, answers 409 with `points`, the sentence that says so, and makes nothing: the same call with that `points` goes on",
88 auth: true,
99 role: "admin",
1010 status: 201,
11 body: { name: "string", host: "string", target: "string", account: "string", app: "string", source: "string", version: "string", place: "string", config: "object" },
11 body: { name: "string", host: "string", target: "string", account: "string", app: "string", source: "string", version: "string", place: "string", config: "object", points: "string" },
12 errorStatus: { 409: "`points_elsewhere`: the name points elsewhere, or DNS gave no answer; nothing was made, and `points` is the sentence to repeat" },
1213 refusals: {
14 points_elsewhere: "the name points elsewhere, or DNS gave no answer; nothing was made (409)",
1315 not_found: "only a forge administrator sees this route",
1416 refused: "the request was understood and refused; the message says why (422)",
1517 },
src/crew/conversation_ask.ts +4 −1
@@ -123,9 +123,12 @@ 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"))}${a["verb"] === "deploy" ? "; an A record its name has already is changed to the new machine" : ""}`;
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" && POINTS.test(String(a["points"])) ? `. ${String(a["points"])}, and that name moves to the new machine` : ""}`;
127127 }
128128
129 /** The sentence a deploy that moves a name repeats (`pointsNow`), shown whole: cut, it would lose its addresses. */
130 const POINTS = /^DNS (sends [a-z0-9.-]{1,253} to [0-9.]{7,15}( and [0-9.]{7,15})* now|did not say where [a-z0-9.-]{1,253} points now)$/;
131
129132 /** Infrastructure (#16696): only `apply` is held, and it builds a plan the person was shown. */
130133 function infra(a: Args): string {
131134 // A plan that clears dead rows names them in `names` (the tool refuses one that does not), so the
src/http/api/admin.ts +4 −3
@@ -23,7 +23,7 @@ import { inviteLink, list as listInviteLinks, mint as mintInviteLink, revoke as
2323 import { changeLimit, listLimits } from "../../actions/limits.ts";
2424 import { changePlans, measuredPlans } from "../../actions/plans.ts";
2525 import { setAccountCeilings, setAccountGrant } from "../../actions/model_grant.ts";
26 import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, keepPinned, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, claimPinned, deployPinned, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned } from "../../actions/pinned.ts";
26 import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, keepPinned, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, claimPinned, deployPinned, deployWords, repeatWords, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned } from "../../actions/pinned.ts";
2727 import { TARGETS } from "../../cloud/targets.ts";
2828 import { infraCode } from "../../cloud/infra_read.ts";
2929 import { buildOf, infraOf, nameFor, planById, planCompose, planDatabase, startBuild } from "../../actions/infra.ts";
@@ -92,10 +92,11 @@ export function adminRoutes(router: Router<Handler>): void {
9292 const i = await body(ctx.request);
9393 const made = await deployPinned(ctx.app, ctx.auth.user, {
9494 name: str(i.name), host: str(i.host), target: str(i.target), account: str(i.account), app: str(i.app),
95 source: str(i.source), version: str(i.version), place: str(i.place), config: i.config,
95 source: str(i.source), version: str(i.version), place: str(i.place), config: i.config, points: str(i.points),
9696 });
97 if (!made.ok && typeof made.error !== "string") return json({ error: "points_elsewhere", message: repeatWords(made.error), points: made.error.points }, 409);
9798 // The answer holds the claim link, shown once: nothing between here and the caller keeps it.
98 return made.ok ? once(json(made.value, 201)) : pinnedFail(made.error);
99 return made.ok ? once(json(made.value, 201)) : pinnedFail(deployWords(made.error));
99100 });
100101
101102 // A fresh claim link for a forge nobody has claimed; the one before it stops working.
src/http/infra_routes.ts +9 −6
@@ -7,10 +7,10 @@
77
88 import { cloudFactsAll } from "../actions/cloud_says.ts";
99 import { infraCode } from "../cloud/infra_read.ts";
10 import { buildOf, cloudResources, machineOf, providerConsole, readProjectsNow, type ComposeChoices, composeChoices, domainOf, infraOf, nameFor, planCompose, planRecord, rebuild, recordAccounts, startBuild } from "../actions/infra.ts";
10 import { buildOf, cloudResources, machineOf, providerConsole, readProjectsNow, type ComposeChoices, composeChoices, domainOf, infraOf, nameFor, planCompose, planRecord, pointsOf, rebuild, recordAccounts, startBuild } from "../actions/infra.ts";
1111 import { dropRecord } from "../actions/dns_record.ts";
1212 import { deleteSnapshot, endWithSnapshot, restoreSnapshot } from "../actions/infra_snapshot.ts";
13 import { clearPinned, endsWords, keepPinned, retirePinned, retireWords } from "../actions/pinned.ts";
13 import { deployWords, clearPinned, endsWords, keepPinned, retirePinned, retireWords } from "../actions/pinned.ts";
1414 import { timePhase, timePhaseAsync } from "../core/route_timing.ts";
1515 import { behaviorsJs } from "../web/behaviors.ts";
1616 import { notFoundPage, signInFirst } from "../web/chrome.ts";
@@ -19,7 +19,7 @@ import { field, readForm } from "../web/form.ts";
1919 import { html, type Html } from "../web/html.ts";
2020 import { flashTo, fragment, page } from "../web/layout.ts";
2121 import { machineView } from "../actions/machine_view.ts";
22 import { INFRA_CSS, cloudPage, consolePage, endingPage, buildTray, placesRegion, composeForm, infraJs, buildPage, planTray, recordForm, resourcesPage, runningRegion, type ComposeState } from "../web/pages/infra.ts";
22 import { INFRA_CSS, cloudPage, consolePage, endingPage, restoringPage, buildTray, placesRegion, composeForm, infraJs, buildPage, planTray, recordForm, resourcesPage, runningRegion, type ComposeState } from "../web/pages/infra.ts";
2323 import { cloudBranch, cloudList, cloudOverview, cloudPane, cloudTotal, cloudTreeJs } from "../web/pages/cloud_tree.ts";
2424 import { filesByNode } from "../cloud/declared_read.ts";
2525 import { logsOfContainer } from "../cloud/containers.ts";
@@ -216,7 +216,7 @@ async function infraApply(ctx: Ctx): Promise<Response> {
216216 if (!planned.ok) return notFoundPage(ctx);
217217 const p = planned.value;
218218 if (p.lacks !== "") return render(ctx, s, { flash: { tone: "attn", message: p.lacks } }, 422);
219 if (p.plan.id !== field(form, "plan"))
219 if (p.plan.id !== field(form, "plan") || pointsOf(p.plan).join("; ") !== field(form, "points"))
220220 return render(
221221 ctx,
222222 s,
@@ -365,8 +365,11 @@ async function infraSnapshot(ctx: Ctx): Promise<Response> {
365365 return flashTo(ctx, "/infra", gone.ok ? { tone: "success", message: gone.value } : { tone: "danger", message: gone.error });
366366 }
367367 if (ctx.params.act !== "restore") return notFoundPage(ctx);
368 const made = await restoreSnapshot(ctx.app, ctx.auth.user, id, field(form, "name").trim().toLowerCase().slice(0, 40));
369 return flashTo(ctx, "/infra", made.ok ? { tone: "success", message: `Bringing ${made.value.name} back from its snapshot: it appears under what runs.` } : { tone: "danger", message: made.error });
368 const name = field(form, "name").trim().toLowerCase().slice(0, 40);
369 const made = await restoreSnapshot(ctx.app, ctx.auth.user, id, name, field(form, "points"));
370 if (made.ok) return flashTo(ctx, "/infra", { tone: "success", message: `Bringing ${made.value.name} back from its snapshot: it appears under what runs.` });
371 if (typeof made.error === "string") return flashTo(ctx, "/infra", { tone: "danger", message: made.error });
372 return page({ ctx, title: `Bring back ${name}? · forge`, body: restoringPage(id, name, deployWords(made.error), made.error.points) }, 409);
370373 }
371374
372375 export function infraRoutes(router: Router<Handler>): void {
src/http/mcp/tools/pinned_forge.ts +5 −4
@@ -1,4 +1,4 @@
1 import { DOMAIN_WORDS, endsWords, keepPinned, changeBaseDomain, checkPinned, checkWords, claimPinned, claimWords, deployPinned, fileForge, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, strayCloud, strayWords, updatePinned } from "../../../actions/pinned.ts";
1 import { DOMAIN_WORDS, endsWords, keepPinned, changeBaseDomain, checkPinned, checkWords, claimPinned, claimWords, deployPinned, repeatWords, fileForge, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, strayCloud, strayWords, updatePinned } from "../../../actions/pinned.ts";
22 import { TARGETS } from "../../../cloud/targets.ts";
33 import { scopeAllows } from "../../../core/tokens.ts";
44 import { good, bad, type Tool, str } from "../shared.ts";
@@ -6,7 +6,7 @@ import { good, bad, type Tool, str } from "../shared.ts";
66 export const tool: Tool = {
77 name: "pinned_forge",
88 listedTo: "admin",
9 doc: "`{ verb, name?, host?, domain?, withData?, despiteClaim?, target?, account?, app?, source?, version?, place?, config?, lifetimeDays? }`: a forge on the owner's cloud. `deploy`: `app` from `source` at `version` on a writable `account`, at `place` (default: the small plan's), on `host` (default `<name>.<domain>`; Cloudflare writes the record); answers once with `claim.link` and `dns`. `claim`: a fresh link. `update`: change `version` or `config`. `rollback`: back one. `domain`: read or set. `check`: `waiting` or `url`, `healthy`, `claim`. `retire`: delete the machine, keep the data (`withData` deletes it). `strays` (`target`, `account`): labelled machines and volumes no row owns. `file`: into its account's project. `keep`: 7 more days to `endsAt` (`deploy` sets `lifetimeDays`). `list`: all, with changes. A forge admin with an admin-scope token",
9 doc: "`{ verb, name?, host?, domain?, withData?, despiteClaim?, target?, account?, app?, source?, version?, place?, config?, points?, lifetimeDays? }`: a forge on the owner's cloud. `deploy`: `app` from `source` at `version` on a writable `account`, at `place` (default: the small plan's), on `host` (default `<name>.<domain>`; Cloudflare writes the record); answers once with `claim.link` and `dns`. `claim`: a fresh link. `update`: change `version` or `config`. `rollback`: back one. `domain`: read or set. `check`: `waiting` or `url`, `healthy`, `claim`. `retire`: delete the machine, keep the data (`withData` deletes it). `strays` (`target`, `account`): labelled machines and volumes no row owns. `file`: into its account's project. `keep`: 7 more days to `endsAt` (`deploy` sets `lifetimeDays`). `list`: all, with changes. A forge admin with an admin-scope token",
1010 description: "Pinned forges on your cloud: list, deploy, claim, update, rollback, check, retire (admin).",
1111 tier: "delete",
1212 deletes: (args) => args["verb"] === "retire" && args["withData"] === true,
@@ -28,6 +28,7 @@ export const tool: Tool = {
2828 version: { type: "string", maxLength: 40, description: "Commit id or tag." },
2929 place: { type: "string", maxLength: 200, description: "provider:datacenter:size; omit for the default." },
3030 config: { type: "object", description: "NAME: value; no secrets." },
31 points: { type: "string", maxLength: 2000 },
3132 },
3233 required: ["verb"],
3334 },
@@ -61,11 +62,11 @@ export const tool: Tool = {
6162 verb === "deploy"
6263 ? await deployPinned(ctx.app, user, {
6364 name, host: str(args["host"]), target: str(args["target"]), account: str(args["account"]), app: str(args["app"]),
64 source: str(args["source"]), version: str(args["version"]), place: str(args["place"]), config: args["config"],
65 source: str(args["source"]), version: str(args["version"]), place: str(args["place"]), config: args["config"], points: str(args["points"]),
6566 ...(typeof args["lifetimeDays"] === "number" ? { lifetimeDays: args["lifetimeDays"] } : {}),
6667 })
6768 : await claimPinned(ctx.app, user, name, { host: args["host"] === undefined ? undefined : str(args["host"]) });
68 if (!made.ok) return bad("refused", made.error);
69 if (!made.ok) return typeof made.error === "string" ? bad("refused", made.error) : bad("points_elsewhere", repeatWords(made.error));
6970 return good({ says: `${verb} ${name}: now ${made.value.version}, ${made.value.state} at ${made.value.url}. ${claimWords(made.value)}`, claim: made.value.claim, forge: made.value });
7071 }
7172 if (verb === "retire") {
src/http/pinned_routes.ts +4 −5
@@ -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, MOVES_WORDS, pointsNow, 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, deployWords, 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";
@@ -72,11 +72,10 @@ 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 const made = await deployPinned(ctx.app, ctx.auth.user, { ...v, target, account, points: field(form, "points") });
7576 // 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);
78 const made = await deployPinned(ctx.app, ctx.auth.user, { ...v, target, account });
79 if (!made.ok) return render(ctx, v, { tone: "danger", message: made.error });
77 if (!made.ok && typeof made.error !== "string") return render(ctx, v, { tone: "attn", message: `${deployWords(made.error)} Press Deploy again if you mean it.` }, made.error.points);
78 if (!made.ok) return render(ctx, v, { tone: "danger", message: deployWords(made.error) });
8079 return shown(ctx, `Deployed ${made.value.name}`, made.value);
8180 }
8281
src/tui/screens/infra.ts +18 −5
@@ -17,7 +17,7 @@ import { infraCode, type CodeFile } from "../../cloud/infra_read.ts";
1717 import { buildOf, composeChoices, providerConsole, databaseChoices, infraOf, cloudResources, nameFor, planCompose, planDatabase, planRecord, recordAccounts, startBuild, type Compose, type Planned, type Running } from "../../actions/infra.ts";
1818 import { deleteSnapshot, endWithSnapshot, restoredName, restoreSnapshot } from "../../actions/infra_snapshot.ts";
1919 import { planMinecraft } from "../../actions/minecraft.ts";
20 import { LIFETIME_DAYS, clearPinned, endsWords, keepPinned, retirePinned, retireWords } from "../../actions/pinned.ts";
20 import { LIFETIME_DAYS, clearPinned, deployWords, endsWords, keepPinned, retirePinned, retireWords } from "../../actions/pinned.ts";
2121 import type { SnapshotView } from "../../actions/infra_snapshot.ts";
2222 import { machineView } from "../../actions/machine_view.ts";
2323 import { actionLine, viewRows } from "../../cloud/provider_detail.ts";
@@ -27,7 +27,7 @@ import { getPinned } from "../../core/pinned.ts";
2727 import type { Ctx, Screen } from "../app/app.ts";
2828 import { binding } from "../app/keys.ts";
2929 import { style } from "../term/style.ts";
30 import { truncate } from "../term/width.ts";
30 import { truncate, wrap } from "../term/width.ts";
3131 import type { Session } from "../session.ts";
3232 import { fill, len, split } from "../ui/layout.ts";
3333 import { ListState, confirmScreen, drawList, later, live, pickerScreen, promptScreen, type ListRow } from "./common.ts";
@@ -563,9 +563,22 @@ function infraWithCompose(f: Session, ctx: Ctx): { screen: Screen; compose: (par
563563 value: restoredName(snap.name),
564564 onSubmit: (name) =>
565565 later(ctx, () => {
566 void restoreSnapshot(f.app, f.user, snap.id, name.trim().toLowerCase()).then((r) =>
567 say(r.ok ? `Bringing ${r.value.name} back from its snapshot.` : r.error),
568 );
566 const restore = async (points: string): Promise<void> => {
567 const r = await restoreSnapshot(f.app, f.user, snap.id, name.trim().toLowerCase(), points);
568 if (r.ok) return say(`Bringing ${r.value.name} back from its snapshot.`);
569 const { error } = r;
570 if (typeof error === "string") return say(error);
571 ctx.push(
572 confirmScreen(ctx, screen, {
573 title: `Bring back ${snap.name}?`,
574 body: wrap(deployWords(error), 92),
575 actions: [{ label: "Restore" }, { label: "Cancel" }],
576 width: 100,
577 onChoose: (i) => void (i === 0 && restore(error.points)),
578 }),
579 );
580 };
581 void restore("");
569582 return screen;
570583 }),
571584 }),
src/tui/screens/pinned.ts +11 −11
@@ -12,10 +12,11 @@
1212 * nothing and does nothing.
1313 */
1414
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";
15 import { DOMAIN_WORDS, endsWords, keepPinned, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, claimWords, deployPinned, deployWords, 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";
19 import { err, type Result } from "../../kernel/result.ts";
1920 import { truncate, wrap } from "../term/width.ts";
2021 import type { Session } from "../session.ts";
2122 import { fill, len, split } from "../ui/layout.ts";
@@ -28,7 +29,7 @@ const short = (v: string): string => (v.length === 40 ? v.slice(0, 10) : v);
2829 * A claim just issued: what to do with it on the screen's line, and the link itself in the one
2930 * dialog that shows it, held nowhere once that closes.
3031 */
31 async function hand(ctx: Ctx, say: (text: string) => void, r: Promise<{ ok: true; value: Issued } | { ok: false; error: string }>, parent: Screen): Promise<void> {
32 async function hand(ctx: Ctx, say: (text: string) => void, r: Result<Issued, string> | Promise<Result<Issued, string>>, parent: Screen): Promise<void> {
3233 const made = await r;
3334 if (!made.ok) return say(made.error);
3435 say(claimWords(made.value));
@@ -130,21 +131,20 @@ function offerStrays(f: Session, ctx: Ctx, screen: Screen, say: (text: string) =
130131 );
131132 }
132133
133 /** Deploy at once, or, when the name points somewhere already, only after the person read where. */
134 /** Deploy, and when the name points somewhere already, only after the person read where (`points`). */
134135 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();
136 say(`Deploying ${input.name}…`);
137 const made = await deployPinned(f.app, f.user, input);
138 if (made.ok || typeof made.error === "string") return hand(ctx, say, made.ok ? made : err(deployWords(made.error)), parent);
139 const { error } = made;
140 say(`${input.name} is not deployed yet.`);
141141 ctx.push(
142142 confirmScreen(ctx, parent, {
143143 title: `Deploy ${input.name}?`,
144 body: wrap(`${now}. ${MOVES_WORDS}`, 92),
144 body: wrap(deployWords(error), 92),
145145 actions: [{ label: "Deploy" }, { label: "Cancel" }],
146146 width: 100,
147 onChoose: (i) => void (i === 0 && go()),
147 onChoose: (i) => void (i === 0 && deployAsked(f, ctx, say, { ...input, points: error.points }, parent)),
148148 }),
149149 );
150150 }
src/web/pages/infra.ts +18 −1
@@ -14,7 +14,7 @@
1414 import { LIFETIME_DAYS } from "../../actions/pinned.ts";
1515 import type { CodeFile } from "../../cloud/infra_read.ts";
1616 import { restoredName, type SnapshotView } from "../../actions/infra_snapshot.ts";
17 import { ENDED_DAYS, type RecordFields, type Build, type ComposeChoices, type InfraView, type Planned, type Running } from "../../actions/infra.ts";
17 import { ENDED_DAYS, pointsOf, type RecordFields, type Build, type ComposeChoices, type InfraView, type Planned, type Running } from "../../actions/infra.ts";
1818 import type { MachineView } from "../../actions/machine_view.ts";
1919 import { actionLine, viewRows } from "../../cloud/provider_detail.ts";
2020 import { dollars } from "../../cloud/prices.ts";
@@ -315,6 +315,22 @@ export function endingPage(r: Running): Html {
315315 </div>`;
316316 }
317317
318 /** A restore whose name points elsewhere: where, read before the press that moves it. */
319 export function restoringPage(id: string, name: string, words: string, points: string): Html {
320 return html`<div class="narrow-wide">
321 ${pageHead(`Bring back ${name}?`)}
322 <p>${words}</p>
323 <div class="form-actions">
324 <form method="post" action="/infra/snapshot/${id}/restore">
325 <input type="hidden" name="name" value="${name}" />
326 <input type="hidden" name="points" value="${points}" />
327 ${btn("Restore", { variant: "primary" })}
328 </form>
329 ${btn("Cancel", { href: "/infra", variant: "ghost" })}
330 </div>
331 </div>`;
332 }
333
318334 const radio = (name: string, value: string, checked: boolean, o: { disabled?: boolean; label?: string } = {}): Html =>
319335 html`<input
320336 type="radio"
@@ -472,6 +488,7 @@ export function planTray(p: Planned): Html {
472488 const ready = p.lacks === "" && !refused && p.plan.steps.length > 0;
473489 return html`<div id="plan-tray" class="plan-tray" aria-live="polite" data-state="${ready ? "ready" : "lacking"}">
474490 <input type="hidden" name="plan" value="${p.lacks === "" ? p.plan.id : ""}" />
491 <input type="hidden" name="points" value="${pointsOf(p.plan).join("; ")}" />
475492 <div data-line>
476493 <p>${p.lacks !== "" ? html`<span class="muted">${p.lacks}</span>` : phrases(p.summary)}</p>
477494 ${btn("Build", { variant: "primary", disabled: !ready, label: ready ? `Build: ${p.summary}` : "Build" })}
test/boot-size.test.ts +2 −2
@@ -74,7 +74,7 @@ beforeAll(async () => {
7474 net.fetch = cloud.fetch;
7575 net.resolve = async () => [];
7676 const box = await deploy("mc");
77 if (!box.ok) throw new Error(box.error);
77 if (!box.ok) throw new Error(String(box.error));
7878 const up = await updatePinned(app, admin, "mc", { version: "b".repeat(40) });
7979 if (!up.ok) throw new Error(up.error);
8080 }, 30_000);
@@ -122,7 +122,7 @@ test("a new box over the limit makes nothing, and the plan says so before anyone
122122 test("an update is measured as the row it makes, and priced as the one that runs", async () => {
123123 const big = { NOTE: "x".repeat(500) };
124124 const f = await deployPinned(app, admin, { name: "site", host: "", target: "digitalocean", account: "main", app: "alice/site", source: "https://forge.example/alice/forge.git", version: "a".repeat(40), place: PLACE, config: big });
125 if (!f.ok) throw new Error(f.error);
125 if (!f.ok) throw new Error(String(f.error));
126126 const now = getPinned(app.db, "site")!;
127127 limit(Buffer.byteLength(digitalocean.boot.of(now, now.volume)) - 1);
128128 // What runs is over the limit: the update that makes it smaller is let in.
test/claim-order.test.ts +1 −1
@@ -50,7 +50,7 @@ beforeAll(async () => {
5050 net.fetch = cloud.fetch;
5151 net.resolve = async () => [];
5252 const box = await deployPinned(app, admin, { name: "mc", host: "", target: "digitalocean", account: "main", app: "alice/mc", boots: "game", source: "https://forge.example/alice/forge.git", version: "a".repeat(40), place: PLACE });
53 if (!box.ok) throw new Error(box.error);
53 if (!box.ok) throw new Error(String(box.error));
5454 const up = await update("b");
5555 if (!up.ok) throw new Error(up.error);
5656 }, 30_000);
test/conversation-ask.test.ts +8 −1
@@ -543,8 +543,15 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [
543543 [
544544 "pinned_forge",
545545 { verb: "deploy", name: "shop", target: "hetzner" },
546 "Deploy the pinned forge shop on hetzner; an A record its name has already is changed to the new machine.",
546 "Deploy the pinned forge shop on hetzner.",
547547 ],
548 // A name that points elsewhere is moved only by a call that repeats where, so the person reads the address; other text is no part of the ask.
549 [
550 "pinned_forge",
551 { verb: "deploy", name: "shop", target: "hetzner", points: "DNS sends a-quite-long-name.customer.example.com to 198.51.100.4 and 198.51.100.9 now" },
552 "Deploy the pinned forge shop on hetzner. DNS sends a-quite-long-name.customer.example.com to 198.51.100.4 and 198.51.100.9 now, and that name moves to the new machine.",
553 ],
554 ["pinned_forge", { verb: "deploy", name: "shop", target: "hetzner", points: "nothing is served there" }, "Deploy the pinned forge shop on hetzner."],
548555 ["pinned_forge", { verb: "claim", name: "shop" }, "Make a fresh claim link for the pinned forge shop."],
549556 ["pinned_forge", { verb: "domain", domain: "forges.example" }, "Set the domain pinned forges are named under to forges.example."],
550557 ["pinned_forge", { verb: "retire", name: "shop" }, "Retire the pinned forge shop, keeping its data."],
test/game-restore.test.ts +3 −3
@@ -11,7 +11,7 @@ import { join } from "node:path";
1111 import { createApp, type App } from "../src/app.ts";
1212 import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts";
1313 import { restoreSnapshot } from "../src/actions/infra_snapshot.ts";
14 import { deployPinned, net, retirePinned } from "../src/actions/pinned.ts";
14 import { deployPinned, deployWords, net, retirePinned } from "../src/actions/pinned.ts";
1515 import { getPinned } from "../src/core/pinned.ts";
1616 import { insertSnapshot } from "../src/core/snapshots.ts";
1717 import { createUser, type User } from "../src/core/users.ts";
@@ -42,7 +42,7 @@ describe("a game box's snapshot", () => {
4242 };
4343 const restore = async (id: string, name: string): Promise<string> => {
4444 const r = await restoreSnapshot(app, admin, id, name);
45 return r.ok ? "" : r.error;
45 return r.ok ? "" : deployWords(r.error);
4646 };
4747 const rowOf = (name: string) => app.db.query("SELECT * FROM game_box WHERE name = ?1").get(name);
4848 /** Refused, and nothing asked of the cloud or kept here. */
@@ -72,7 +72,7 @@ describe("a game box's snapshot", () => {
7272 name: "mc", host: "play.example.com", target: "digitalocean", account: "main", app: "alice/mc-network", boots: "game",
7373 source: "https://forge.example/alice/forge.git", version: "a".repeat(40), place: "digitalocean:nyc3:s-1vcpu-2gb",
7474 });
75 if (!box.ok) throw new Error(box.error);
75 if (!box.ok) throw new Error(String(box.error));
7676 app.db.run("UPDATE game_box SET branch = 'live', path = 'net/compose.yml' WHERE name = 'mc'");
7777 first = token(booted());
7878 snap = ready("mc");
test/game-second-box.test.ts +1 −1
@@ -69,7 +69,7 @@ beforeAll(async () => {
6969 net.fetch = cloud.fetch;
7070 net.resolve = async () => [];
7171 const box = await direct("mc", "alice/mc");
72 if (!box.ok) throw new Error(box.error);
72 if (!box.ok) throw new Error(String(box.error));
7373 }, 30_000);
7474 afterAll(async () => {
7575 cloudNet.fetch = saved.cloud;
test/infra-dns.test.ts +1
@@ -112,6 +112,7 @@ describe("the plan of a DNS record", () => {
112112 function hands(rows: Map<string, string>, calls: string[], fail = ""): Hands {
113113 return {
114114 replan: (p) => p,
115 points: async () => "",
115116 deploy: async () => ok({}),
116117 clear: () => ok({}),
117118 retire: async () => ok({}),
test/infra-page.test.ts +29 −4
@@ -248,7 +248,7 @@ describe("infrastructure", () => {
248248 version: "a".repeat(40),
249249 place: "digitalocean:nyc3:s-1vcpu-2gb",
250250 });
251 if (!d.ok) throw new Error(d.error);
251 if (!d.ok) throw new Error(String(d.error));
252252 app.db
253253 .query(
254254 "INSERT INTO cloud_watch (provider, account, at, error, resources, actual_cents, forge_cents, ceiling_cents, since, problem_key) VALUES ('digitalocean','main',?1,'',?2,0,0,5000,?1,'x')",
@@ -415,7 +415,7 @@ describe("infrastructure", () => {
415415
416416 test("a machine with nothing at its provider offers no End, here or on /infra", async () => {
417417 const d = await deployPinned(app, admin, { name: "canary", host: "", target: "digitalocean", account: "main", app: "ada/shop", source: "https://forge.example.net/ada/shop.git", version: "a".repeat(40), place: "digitalocean:nyc3:s-1vcpu-2gb" });
418 if (!d.ok) throw new Error(d.error);
418 if (!d.ok) throw new Error(String(d.error));
419419 setRemote(app.db, "canary", { remote: "", volume: "", address: "", state: "failed" });
420420 const running = await (await get("/infra/live?part=running")).text();
421421 expect(running).toContain('id="machine-canary"');
@@ -514,7 +514,7 @@ describe("infrastructure", () => {
514514
515515 test("what ended a month ago and bills nothing is counted in one line, not listed", async () => {
516516 const d = await deployPinned(app, admin, { name: "ancient", host: "", target: "digitalocean", account: "main", app: "ada/shop", source: "https://forge.example.net/ada/shop.git", version: "a".repeat(40), place: "digitalocean:nyc3:s-1vcpu-2gb" });
517 if (!d.ok) throw new Error(d.error);
517 if (!d.ok) throw new Error(String(d.error));
518518 setRemote(app.db, "ancient", { remote: "", volume: "", address: "", state: "retired" });
519519 app.db.query("INSERT INTO event (id, kind, repo_id, actor_id, payload, created_at) VALUES ('old-retire-1', 'pinned.retired', NULL, NULL, ?1, ?2)").run(JSON.stringify({ name: "ancient" }), new Date(Date.now() - 40 * 86_400_000).toISOString());
520520 const v = infraOf(app, admin);
@@ -526,7 +526,7 @@ describe("infrastructure", () => {
526526
527527 test("the terminal clears a dead row with c after a confirm, and x refuses it: there is nothing to end", async () => {
528528 const d = await deployPinned(app, admin, { name: "deadrow", host: "", target: "digitalocean", account: "main", app: "ada/shop", source: "https://forge.example.net/ada/shop.git", version: "a".repeat(40), place: "digitalocean:nyc3:s-1vcpu-2gb" });
529 if (!d.ok) throw new Error(d.error);
529 if (!d.ok) throw new Error(String(d.error));
530530 setRemote(app.db, "deadrow", { remote: "", volume: "", address: "", state: "failed" });
531531 const v = infraOf(app, admin);
532532 if (!v.ok) throw new Error(v.error);
@@ -548,4 +548,29 @@ describe("infrastructure", () => {
548548 expect(getPinned(app.db, "deadrow")).toBeUndefined();
549549 tui.stop?.();
550550 });
551
552 test("Build shows the plan again when the name points elsewhere than the page said", async () => {
553 const a = await addAccount(app, admin, "cloudflare", "main", "cf_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9Lm2");
554 if (!a.ok) throw new Error(String(a.error));
555 allowWrite(app, admin, "cloudflare", "main", true);
556 const resolve = net.resolve;
557 try {
558 net.resolve = async () => ["198.51.100.4"];
559 const form = compose({ name: "moving" });
560 const tray = await (await post("/infra/plan?fragment=1", { ...form })).text();
561 const hidden = (n: string) => new RegExp(`name="${n}" value="([^"]*)"`).exec(tray)?.[1] ?? "";
562 expect(tray).toContain("DNS sends moving.forges.example.net to 198.51.100.4 now");
563 net.resolve = async () => ["198.51.100.9"];
564 const no = await post("/infra/apply", { ...form, plan: hidden("plan"), points: hidden("points") });
565 expect(no.status).toBe(409);
566 expect(await no.text()).toContain("DNS sends moving.forges.example.net to 198.51.100.9 now");
567 expect(buildOf(app, admin, hidden("plan"))).toBeUndefined();
568 net.resolve = async () => ["198.51.100.4"];
569 const yes = await post("/infra/apply", { ...form, plan: hidden("plan"), points: hidden("points") });
570 expect(yes.status).toBe(303);
571 await settled(hidden("plan"));
572 } finally {
573 net.resolve = resolve;
574 }
575 }, 30_000);
551576 });
test/infra-plan.test.ts +1
@@ -342,6 +342,7 @@ describe("apply", () => {
342342 });
343343 const hands: Hands = {
344344 replan: (p) => p,
345 points: async () => "",
345346 deploy: async (w) => {
346347 calls.push(`deploy ${w.name}`);
347348 const no = o.deploy?.(w, rows);
test/infra-snapshot.test.ts +51 −2
@@ -87,7 +87,7 @@ describe("snapshots", () => {
8787
8888 test("End with a snapshot: the snapshot is made and complete before the machine is deleted, and the row says what it bills", async () => {
8989 const d = await deployPinned(app, admin, say("snap1"));
90 if (!d.ok) throw new Error(d.error);
90 if (!d.ok) throw new Error(String(d.error));
9191 const p = getPinned(app.db, "snap1")!;
9292 expect(snapshotOffer(app, p)).toContain("Snapshot its data volume first: 10 GiB kept for $0.60 a month");
9393 snaps.readsUntilReady = 2;
@@ -107,7 +107,7 @@ describe("snapshots", () => {
107107
108108 test("a snapshot the cloud refuses ends nothing: the machine stays and the row says why", async () => {
109109 const d = await deployPinned(app, admin, say("snap2"));
110 if (!d.ok) throw new Error(d.error);
110 if (!d.ok) throw new Error(String(d.error));
111111 snaps.refuse = true;
112112 cloud.calls.length = 0;
113113 const r = await endWithSnapshot(app, admin, "snap2");
@@ -221,6 +221,55 @@ describe("snapshots", () => {
221221 tui.stop?.();
222222 });
223223
224 test("a restore whose name points elsewhere, or that DNS is silent about, asks once more and goes on", async () => {
225 cloudNet.fetch = async (url) => Response.json({ success: true, result: String(url).includes("/zones") ? [] : { id: "t", status: "active" } });
226 const added = await addAccount(app, admin, "cloudflare", "dns", "cfut_9Zq4TxLm7Kp2Vb8nWcR5yHs3Jd6Fg1");
227 if (!added.ok) throw new Error(String(added.error));
228 allowWrite(app, admin, "cloudflare", "dns", true);
229 const s = listSnapshots(app.db).find((x) => x.state === "ready")!;
230 const post = (body: Record<string, string>) =>
231 fetch(`${servers.url}/infra/snapshot/${s.id}/restore`, {
232 method: "POST",
233 headers: { cookie, "content-type": "application/x-www-form-urlencoded" },
234 body: new URLSearchParams(body),
235 redirect: "manual",
236 });
237 const points = "DNS sends moved1.forges.example.net to 198.51.100.4 now";
238 const resolve = net.resolve;
239 try {
240 net.resolve = async () => ["198.51.100.4"];
241 const first = await post({ name: "moved1" });
242 expect(first.status).toBe(409);
243 const text = await first.text();
244 expect(text).toContain(points);
245 expect(text).toContain(`name="points"`);
246 expect(getPinned(app.db, "moved1")).toBeUndefined();
247 expect((await post({ name: "moved1", points })).status).toBe(303);
248 expect(getPinned(app.db, "moved1")).toBeDefined();
249 net.resolve = () => Promise.reject(new Error("SERVFAIL"));
250 const silent = await restoreSnapshot(app, admin, s.id, "moved2");
251 expect(silent).toEqual({ ok: false, error: { points: "DNS did not say where moved2.forges.example.net points now" } });
252 expect(getPinned(app.db, "moved2")).toBeUndefined();
253 // The terminal: the same sentence, and Restore goes on.
254 const { app: tui, session } = createForgeApp(app, { sshUsername: "ada", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin }, { terminal: headlessTerminal(160, 40), exitHooks: false });
255 tui.start();
256 tui.ctx.push(infraScreen(session, tui.ctx));
257 await settleApp(tui);
258 const press = (key: string) => tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
259 for (let i = 0; i < 40; i++) press("j");
260 press("r");
261 await settleApp(tui);
262 press("enter");
263 await settleApp(tui);
264 expect(tui.screen.toText()).toContain("DNS did not say where");
265 expect(tui.screen.toText()).toContain("Restore");
266 tui.stop?.();
267 } finally {
268 net.resolve = resolve;
269 allowWrite(app, admin, "cloudflare", "dns", false);
270 }
271 });
272
224273 test("delete: the cloud's snapshot and the row go; a failed row has nothing at the cloud", async () => {
225274 const ready = listSnapshots(app.db).find((x) => x.state === "ready")!;
226275 snaps.calls.length = 0;
test/machine-boots.test.ts +2 −2
@@ -13,7 +13,7 @@ import { createApp, type App } from "../src/app.ts";
1313 import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts";
1414 import { buildOf } from "../src/actions/infra.ts";
1515 import { restoreSnapshot } from "../src/actions/infra_snapshot.ts";
16 import { net, updatePinned } from "../src/actions/pinned.ts";
16 import { deployWords, net, updatePinned } from "../src/actions/pinned.ts";
1717 import { WATCH } from "../src/actions/pinned_watch.ts";
1818 import { asciiBoot } from "../src/cloud/boot_ascii.ts";
1919 import { bootConfig as digitalocean } from "../src/cloud/droplet.ts";
@@ -165,7 +165,7 @@ describe("made and replaced", () => {
165165 const s = insertSnapshot(app.db, getPinned(app.db, "web")!, "volume");
166166 app.db.run("UPDATE infra_snapshot SET state = 'ready', remote = 'snap-1' WHERE id = ?1", [s.id]);
167167 const back = await restoreSnapshot(app, admin, s.id, "web-restored");
168 if (!back.ok) throw new Error(back.error);
168 if (!back.ok) throw new Error(deployWords(back.error));
169169 expect(getPinned(app.db, "web-restored")).toMatchObject({ boots: "services", client: "acme" });
170170 expect(booted()).toContain(ANSWER);
171171 });
test/machine-view.test.ts +1 −1
@@ -106,7 +106,7 @@ describe("opened at every door", () => {
106106 net.fetch = fetchView;
107107 net.resolve = async () => [];
108108 const d = await deployPinned(app, admin, { name: "mc", host: "", target: "digitalocean", account: "main", app: "ada/shop", source: "https://forge.example.net/ada/shop.git", version: "a".repeat(40), place: "digitalocean:nyc3:s-1vcpu-2gb" });
109 if (!d.ok) throw new Error(d.error);
109 if (!d.ok) throw new Error(String(d.error));
110110 servers = await serve(app);
111111 cookie = `forge_session=${createSession(app.db, admin.id).token}`;
112112 }, 30_000);
test/pinned-claim.test.ts +3 −3
@@ -193,7 +193,7 @@ describe("a deployed forge is claimed with the link its deployer was shown, and
193193
194194 test("the deploy answers once with a link on the forge's own name; the machine is given its hash and never the link", async () => {
195195 const r = await deployPinned(seller, admin(), input());
196 if (!r.ok) throw new Error(r.error);
196 if (!r.ok) throw new Error(String(r.error));
197197 const link = LINK.exec(r.value.claim.link);
198198 expect(link?.[1]).toBe(HOST);
199199 code = link![2]!;
@@ -348,7 +348,7 @@ describe("a deployed forge is claimed with the link its deployer was shown, and
348348 admin(),
349349 input({ name: "held", host: "held.forge.test" }),
350350 );
351 if (!made.ok) throw new Error(made.error);
351 if (!made.ok) throw new Error(String(made.error));
352352 const was = getPinned(seller.db, "held")!;
353353 const events = () =>
354354 seller.db
@@ -386,7 +386,7 @@ describe("a deployed forge is claimed with the link its deployer was shown, and
386386 admin(),
387387 input({ name: "second", host: "second.forge.test" }),
388388 );
389 if (!first.ok) throw new Error(first.error);
389 if (!first.ok) throw new Error(String(first.error));
390390 const old = LINK.exec(first.value.claim.link)![2]!;
391391 expect(
392392 seedFirstAdmin(
test/pinned-dns.test.ts +43 −1
@@ -26,7 +26,8 @@ import {
2626 readBaseDomain,
2727 updatePinned,
2828 } from "../src/actions/pinned.ts";
29 import { planWants } from "../src/actions/infra.ts";
29 import { buildOf, planWants, rebuild, startBuild } from "../src/actions/infra.ts";
30 import { pollUntil } from "./helpers/poll.ts";
3031 import { setCeiling } from "../src/actions/cloud_ceiling.ts";
3132 import { dnsOf, getPinned } from "../src/core/pinned.ts";
3233 import { createUser, getUserByName } from "../src/core/users.ts";
@@ -437,6 +438,47 @@ describe("a deploy needs no DNS work from its buyer", () => {
437438 expect(fresh.ok && "dnsWas" in fresh.value).toBe(false);
438439 });
439440
441 test("Build stops, with nothing made, when the name points elsewhere than the plan said; so does Build again", async () => {
442 const want = { kind: "machine" as const, name: "swing", account: "digitalocean/main", place: "digitalocean:nyc3:s-1vcpu-2gb", app: "alice/shop", source: SOURCE, version: V1 };
443 const resolve = net.resolve;
444 const now = "DNS sends swing.forges.test to 198.51.100.9 now";
445 try {
446 for (const before of [[], ["198.51.100.4"]]) {
447 net.resolve = async () => before;
448 const p = await planWants(app, admin(), [want]);
449 if (!p.ok) throw new Error(p.error);
450 net.resolve = async () => ["198.51.100.9"];
451 expect(startBuild(app, admin(), p.value.plan).ok).toBe(true);
452 await pollUntil(() => buildOf(app, admin(), p.value.plan.id)?.state === "failed", "the build stopped");
453 expect(JSON.stringify(buildOf(app, admin(), p.value.plan.id))).toContain(now);
454 expect(getPinned(app.db, "swing")).toBeUndefined();
455 const again = await rebuild(app, admin(), p.value.plan.id);
456 expect(error(again)).toContain(now);
457 expect(getPinned(app.db, "swing")).toBeUndefined();
458 }
459 } finally {
460 net.resolve = resolve;
461 }
462 });
463
464 test("Build asks about every name before it makes anything: a silent DNS for the second machine makes no first one", async () => {
465 const want = (name: string) => ({ kind: "machine" as const, name, account: "digitalocean/main", place: "digitalocean:nyc3:s-1vcpu-2gb", app: "alice/shop", source: SOURCE, version: V1 });
466 const resolve = net.resolve;
467 try {
468 net.resolve = async () => [];
469 const p = await planWants(app, admin(), [want("first"), want("second")]);
470 if (!p.ok) throw new Error(p.error);
471 expect(p.value.plan.refusals).toEqual([]);
472 net.resolve = (h) => (h.startsWith("second.") ? Promise.reject(new Error("SERVFAIL")) : Promise.resolve([]));
473 expect(startBuild(app, admin(), p.value.plan).ok).toBe(true);
474 await pollUntil(() => buildOf(app, admin(), p.value.plan.id)?.state === "failed", "the build stopped");
475 expect(JSON.stringify(buildOf(app, admin(), p.value.plan.id))).toContain("DNS did not say where second.forges.test points now. Nothing was built; look at the plan again.");
476 expect([getPinned(app.db, "first"), getPinned(app.db, "second")]).toEqual([undefined, undefined]);
477 } finally {
478 net.resolve = resolve;
479 }
480 });
481
440482 test("the terminal asks before it moves a name that points somewhere", async () => {
441483 const { app: tui, session } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin() }, { terminal: headlessTerminal(200, 24), exitHooks: false });
442484 tui.start();
test/pinned-domain-doors.test.ts +36
@@ -12,6 +12,7 @@ import {
1212 allowWrite,
1313 net as cloudNet,
1414 } from "../src/actions/cloud.ts";
15 import { setCeiling } from "../src/actions/cloud_ceiling.ts";
1516 import { net } from "../src/actions/pinned.ts";
1617 import { getPinned } from "../src/core/pinned.ts";
1718 import { createToken } from "../src/core/tokens.ts";
@@ -245,6 +246,41 @@ describe("the domain for deployed forges", () => {
245246 }
246247 });
247248
249 test("the API and the MCP tool move a live name only when the call repeats where it points", async () => {
250 expect(setCeiling(app, getUserByName(app.db, "alice"), "digitalocean", "main", 500).ok).toBe(true);
251 const resolve = net.resolve;
252 const body = (name: string, over: Record<string, string> = {}) => ({ name, target: "digitalocean", account: "main", app: "alice/shop", source: SOURCE, version: V, ...over });
253 const api = (b: unknown) =>
254 fetch(`${servers.url}/api/v1/admin/pinned`, { method: "POST", headers: headers(adminTok, { "content-type": "application/json" }), body: JSON.stringify(b) });
255 try {
256 net.resolve = async () => ["198.51.100.4"];
257 const says = (name: string) => `DNS sends ${name}.forges.test to 198.51.100.4 now`;
258 const no = await api(body("viaapi"));
259 expect(no.status).toBe(409);
260 expect(await no.json()).toMatchObject({ error: "points_elsewhere", points: says("viaapi") });
261 expect((await api(body("viaapi", { points: "DNS sends viaapi.forges.test to 198.51.100.5 now" }))).status).toBe(409);
262 expect(getPinned(app.db, "viaapi")).toBeUndefined();
263 expect((await api(body("viaapi", { points: says("viaapi") }))).status).toBe(201);
264
265 const refused = await mcp(adminTok, { verb: "deploy", ...body("viamcp") });
266 expect(refused.result?.isError).toBe(true);
267 expect(JSON.stringify(refused)).toContain(says("viamcp"));
268 expect(getPinned(app.db, "viamcp")).toBeUndefined();
269 const done = await mcp(adminTok, { verb: "deploy", ...body("viamcp", { points: says("viamcp") }) });
270 expect(done.result?.content[0]?.text).toContain("deploy viamcp: now");
271 expect(getPinned(app.db, "viamcp")?.host).toBe("viamcp.forges.test");
272
273 // No answer from DNS is asked about as well.
274 net.resolve = () => Promise.reject(new Error("SERVFAIL"));
275 const silent = await api(body("mute"));
276 expect(silent.status).toBe(409);
277 expect(await silent.json()).toMatchObject({ points: "DNS did not say where mute.forges.test points now" });
278 expect(getPinned(app.db, "mute")).toBeUndefined();
279 } finally {
280 net.resolve = resolve;
281 }
282 });
283
248284 test("the MCP tool reads and sets it with the `domain` verb, and sets it only with an admin-scope token", async () => {
249285 const ro = createToken(
250286 app.db,
test/pinned-retire-doors.test.ts +1 −1
@@ -48,7 +48,7 @@ describe("retire at its doors", () => {
4848 source: SOURCE,
4949 version: V,
5050 });
51 if (!r.ok) throw new Error(r.error);
51 if (!r.ok) throw new Error(String(r.error));
5252 // The deploy deletes its throwaway SSH key; only what a retire deletes is counted.
5353 deletes.length = 0;
5454 };

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

Keyboard shortcuts

Docs