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

A pinned deploy writes its DNS record as soon as the machine has an address,… #16524

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/16372-a-pinned-deploy-writes-its-dns-record-as → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/16372-a-pinned-deploy-writes-its-dns-record-as was merged into main as f70ce0d.

Review

Sign in to review this change.
11 files changed +380 −5
docs/features/pinned-forge.md +3
@@ -78,6 +78,9 @@ A deploy is made at a place from the Places catalog (`GET /api/v1/places`): `pro
7878
7979 The row records its place (`datacenter` and `size`, in `pinned_size`); the volume and the machine are made in that datacenter, and every replace (Update, Roll back, a new claim link) orders the row's own place, never today's default, because the volume lives there. The ceiling prices that place. A forge deployed before places were kept has none recorded and is read as the place the drivers once hard-coded (DigitalOcean `nyc3` `s-1vcpu-2gb`, Hetzner `nbg1`).
8080
81 ## The forge waits for its own forges (#16372)
82 After a deploy, an Update, a Roll back and a new claim link the forge itself looks every 5 seconds (`src/actions/pinned_watch.ts`): it reads the machine's address while there is none, writes the DNS record at once, and goes on until the forge answers over HTTPS, for 5 minutes at most. Nobody has to press Check. The time of each step (address, record, answer, giving up) is kept in `pinned_watch` (`src/core/pinned_watch.ts`) and each is one `pinned.watch` event. One loop a forge, held in memory, and `main.ts` starts it again at boot for every forge still waiting. At the bound it says so once: a `pinned.waiting_long` event for admins and a sentence on the forge's row on `/pinned` (and in the terminal screen, `src/tui/screens/pinned.ts`) saying what is missing and what to try. Check still works and reads the same things by hand.
83
8184 ## Pay and go: no DNS work for the buyer (#16205)
8285
8386 An admin names the **domain for deployed forges** (`forges.example.com`) on Pinned forges (`/pinned`; the terminal's `b`; `PATCH /api/v1/admin/settings` with `{"pinnedDomain": "forges.example.com"}`, `null` to clear; the MCP tool's `domain` verb). It is a forge setting (`settings/pinned_domain.ts`, `pinned.base_domain`, every change kept with who and when). With one set, a deploy needs no hostname: the forge is served on `<name>.<domain>`; a full hostname may still be given (the terminal's `-` takes the default).
src/actions/pinned.ts +52 −2
@@ -55,6 +55,8 @@ import { err, ok, type Result } from "../kernel/result.ts";
5555 import { boundedSignal } from "../kernel/fetch_timeout.ts";
5656 import { isStale, refreshIfDue } from "./places_refresh.ts";
5757 import { oneAtATime } from "../spawn/own_code.ts";
58 import { resumeWatches, stuckWords, watchPinned, type Seen } from "./pinned_watch.ts";
59 import { markStep, watchOf, type WatchTimes } from "../core/pinned_watch.ts";
5860
5961 /** Swapped in tests; the real forge always uses `fetch`, and asks DNS for a name's A records. */
6062 export const net: { fetch: Fetch; probe: Fetch; resolve: (host: string) => Promise<string[]> } = {
@@ -103,6 +105,20 @@ export interface PinnedView extends Omit<Pinned, "claimHash"> {
103105 * while the record is for a person to make.
104106 */
105107 readonly dnsWrittenBy: string;
108 /**
109 * Whether the forge writes the record itself (a Cloudflare account allows writes), so nobody need
110 * create it.
111 */
112 readonly dnsAuto: boolean;
113 /**
114 * The time of each step the forge's own watch saw (#16372), empty strings before; undefined
115 * before any watch.
116 */
117 readonly watch: WatchTimes | undefined;
118 /**
119 * What the forge says when it stopped waiting for this forge without an answer; empty otherwise.
120 */
121 readonly stuck: string;
106122 readonly crew: false;
107123 readonly autoRelease: false;
108124 readonly changes: Change[];
@@ -114,7 +130,9 @@ const view = (app: App, p: Pinned): PinnedView => {
114130 const kept = dnsOf(app.db, p.id);
115131 const written = kept !== undefined && kept.host === p.host && kept.address === p.address;
116132 const keepCents = p.state === "retired" && p.volume !== "" ? rowCents(p, priced(app.db)) : 0;
117 return { ...shown, url: urlOf(p), dns: dnsRecordOf(p), keepCents, dnsWrittenBy: written ? `cloudflare/${kept.account}` : "", crew: false, autoRelease: false, changes: changesOf(app.db, p.id) };
133 const watch = watchOf(app.db, p.id);
134 const stuck = watch !== undefined && watch.gaveUpAt !== "" && watch.answeredAt === "" ? stuckWords(p.name, watch.addressAt !== "", watch.dnsAt !== "") : "";
135 return { ...shown, url: urlOf(p), dns: dnsRecordOf(p), keepCents, dnsWrittenBy: written ? `cloudflare/${kept.account}` : "", dnsAuto: dnsWriters(app).length > 0, watch, stuck, crew: false, autoRelease: false, changes: changesOf(app.db, p.id) };
118136 };
119137
120138 /** A claim just issued: the link is in this value and nowhere else, so it is shown once. */
@@ -472,6 +490,7 @@ async function deployAs(app: App, who: Who, input: DeployInput): Promise<Result<
472490 // assigned one yet (or refuses the read) leaves it to `check`.
473491 await readAddress(app, who, p.name);
474492 await writeDns(app, who, p.name);
493 watchPinned(app, p.name, watchStep);
475494 return ok(issued(app, getPinned(app.db, p.name)!, claim.code));
476495 }
477496
@@ -521,6 +540,7 @@ async function changeNow(
521540 );
522541 if (!done.ok) return done;
523542 await followWithDns(app, who.value, name);
543 watchPinned(app, name, watchStep);
524544 return ok(view(app, getPinned(app.db, name)!));
525545 }
526546
@@ -601,6 +621,7 @@ async function claimNow(app: App, who: Who, name: string, input: { host?: string
601621 app.bus.append({ kind: "pinned.claim_issued", actorId: who.id, payload: { name, expires: claim.expires, ...orderOf(who) } });
602622 await readAddress(app, who, name);
603623 await writeDns(app, who, name);
624 watchPinned(app, name, watchStep);
604625 return ok(issued(app, getPinned(app.db, name)!, claim.code));
605626 }
606627
@@ -758,7 +779,7 @@ export function checkWords(v: Checked): string {
758779 export function claimWords(v: Issued): string {
759780 if (v.dnsWrittenBy !== "")
760781 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.`;
761 const dns = v.dns !== "" ? `Create the DNS record ${v.dns} (DNS only, not proxied) by hand` : `Check reads its address; then create the DNS record ${v.host} A <that address>`;
782 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`;
762783 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.`;
763784 }
764785
@@ -786,11 +807,40 @@ async function checkAs(app: App, who: Who, name: string): Promise<Result<Checked
786807 const reached = await hear(app, who, now);
787808 const healthy = reached.waiting === "";
788809 if (healthy && now.state !== "running") setRemote(app.db, name, { state: "running" });
810 if (healthy) markStep(app.db, now.id, "answeredAt", new Date().toISOString());
789811 const after = getPinned(app.db, name)!;
790812 app.bus.append({ kind: "pinned.check", actorId: who.id, payload: { name, address: after.address, state: after.state, healthy, ...orderOf(who) } });
791813 return ok({ ...view(app, after), healthy, ...reached });
792814 }
793815
816 /**
817 * One look of the forge's own watch (#16372): read the address while there is none, write the
818 * record, ask the forge. Taken in the forge's turn, so it never runs beside an Update, a Rollback
819 * or a claim. A refused call is no progress, never the end of the watch.
820 */
821 const WATCHER: Who = { id: undefined, by: "forge:watch" };
822 async function watchStep(app: App, name: string): Promise<Seen> {
823 return oneChange(app, name, async (): Promise<Seen> => {
824 const p = getPinned(app.db, name);
825 if (!p || p.state === "retired" || p.remote === "") return { gone: true };
826 try {
827 if (p.address === "") await readAddress(app, WATCHER, name);
828 await writeDns(app, WATCHER, name);
829 const now = getPinned(app.db, name)!;
830 const kept = dnsOf(app.db, now.id);
831 const written = kept !== undefined && kept.host === now.host && kept.address === now.address;
832 const heard = await hear(app, WATCHER, now);
833 if (heard.waiting === "" && now.state !== "running") setRemote(app.db, name, { state: "running" });
834 return { address: now.address !== "", dns: written || heard.waiting === "" || heard.waiting === "answer", answers: heard.waiting === "" };
835 } catch {
836 return { address: false, dns: false, answers: false };
837 }
838 });
839 }
840
841 /** At boot: every forge still waiting for its address or answer is watched again. */
842 export const resumePinnedWatches = (app: App): void => resumeWatches(app, watchStep);
843
794844 /** Whether pinned forge `name` was deployed by `who`: its first recorded change says so. */
795845 const madeBy = (app: App, name: string, who: Who): boolean => {
796846 const p = getPinned(app.db, name);
src/actions/pinned_watch.ts added +80
@@ -0,0 +1,80 @@
1 /**
2 * The forge waits for its own pinned forges (#16372): after a deploy, a replace or a new claim link
3 * it reads the machine's address every few seconds until there is one, writes the DNS record at
4 * once, and goes on until the forge answers over HTTPS, recording the time of each step. Bounded
5 * (`WATCH.boundMs`); at the bound it says so once, on the row and as one `pinned.waiting_long`
6 * event for admins. Held in memory one loop a forge, started by the deploy, and started again
7 * at boot for every row the table says is still waiting. Nobody has to press Check.
8 *
9 * `step` is what one look does, handed in by `actions/pinned.ts` (which this module must not
10 * import): it returns what the forge waits for now, or `gone` when there is nothing to watch.
11 */
12
13 import type { App } from "../app.ts";
14 import { during } from "../perf/jobs.ts";
15 import { getPinned } from "../core/pinned.ts";
16 import { markStep, startWatchRow, waitingNames, watchOf, type WatchStep } from "../core/pinned_watch.ts";
17
18 export type Seen = { gone: true } | { gone?: false; address: boolean; dns: boolean; answers: boolean };
19 export type Step = (app: App, name: string) => Promise<Seen>;
20
21 /** `on` is false until `main.ts` arms the watch, so a test of a deploy starts no timer. */
22 export const WATCH = { on: false, everyMs: 5_000, boundMs: 300_000, sleep: (ms: number): Promise<void> => new Promise((r) => { setTimeout(() => during("pinned-watch", r), ms).unref(); }), stop: (app: App): void => void stopped.add(app.db) };
23
24 const loops = new WeakMap<App["db"], Set<string>>();
25 const stopped = new WeakSet<App["db"]>();
26
27 /** Begin (or begin again) the wait for forge `name`; returns at once, the loop runs behind. */
28 export function watchPinned(app: App, name: string, step: Step, resume = false): void {
29 if (!WATCH.on) return;
30 const p = getPinned(app.db, name);
31 if (!p) return;
32 stopped.delete(app.db);
33 if (!resume || watchOf(app.db, p.id) === undefined) startWatchRow(app.db, p.id, new Date().toISOString());
34 const mine = loops.get(app.db) ?? new Set<string>();
35 loops.set(app.db, mine);
36 if (mine.has(name)) return; // the running loop reads the fresh start
37 mine.add(name);
38 void run(app, name, step).catch((e) => app.log.warn("pinned watch failed", { name, error: String(e) })).finally(() => mine.delete(name));
39 }
40
41 /** Arm the watch and take up every wait a restart cut off. */
42 export function resumeWatches(app: App, step: Step): void {
43 WATCH.on = true;
44 for (const name of waitingNames(app.db)) watchPinned(app, name, step, true);
45 }
46
47 async function run(app: App, name: string, step: Step): Promise<void> {
48 for (;;) {
49 const p = getPinned(app.db, name);
50 const w = p && watchOf(app.db, p.id);
51 if (!p || !w || p.state === "retired" || w.answeredAt !== "" || w.gaveUpAt !== "") return;
52 if (Date.parse(w.startedAt) + WATCH.boundMs <= Date.now()) return giveUp(app, name, p.id, w.addressAt !== "", w.dnsAt !== "");
53 const seen = await step(app, name);
54 if (seen.gone) return;
55 const at = new Date().toISOString();
56 const note = (s: WatchStep, yes: boolean): void => {
57 if (yes && markStep(app.db, p.id, s, at)) app.bus.append({ kind: "pinned.watch", actorId: undefined, payload: { name, step: s, at } });
58 };
59 note("addressAt", seen.address);
60 note("dnsAt", seen.dns);
61 if (seen.answers) {
62 note("answeredAt", true);
63 return;
64 }
65 await WATCH.sleep(WATCH.everyMs);
66 if (stopped.has(app.db)) return;
67 }
68 }
69
70 /** What the forge was still waiting for, and what an admin may try. */
71 export function stuckWords(name: string, addressSeen: boolean, dnsSeen: boolean): string {
72 if (!addressSeen) return `${name} has no address after 5 minutes: press Check to read it again.`;
73 if (!dnsSeen) return `${name} has no DNS record: create it by hand or allow a Cloudflare account to write it, then press Check.`;
74 return `${name} does not answer over HTTPS: make its record DNS only, then press Check.`;
75 }
76
77 function giveUp(app: App, name: string, id: string, addressSeen: boolean, dnsSeen: boolean): void {
78 if (!markStep(app.db, id, "gaveUpAt", new Date().toISOString())) return;
79 app.bus.append({ kind: "pinned.waiting_long", actorId: undefined, payload: { name, address: addressSeen, dns: dnsSeen, words: stuckWords(name, addressSeen, dnsSeen) } });
80 }

Once gaveUpAt is set nothing ever sets answeredAt again, so stuck stays on the row even after Check finds the forge answering. Mark the answer from checkAs (or clear stuck when it answers) and test it.

src/core/migration-pins/20261127000000-pinned-watch.pin added +1
@@ -0,0 +1,1 @@
1 61faea1d049c1b5ef4b4f5a5f06ad7dcb20de8d514b15bb8048c5535b9cd2b2f
src/core/migrations/20261127000000-pinned-watch.ts added +14
@@ -0,0 +1,14 @@
1 // The forge's own watch over a pinned forge that is not answering yet (#16372): when it started,
2 // and when each step happened (the machine's address read, the DNS record written, the forge
3 // answering over HTTPS), and when the forge stopped waiting. One row a forge, reset at every deploy
4 // and replace. Additive.
5 export default `
6 CREATE TABLE pinned_watch (
7 pinned_id TEXT PRIMARY KEY,
8 started_at TEXT NOT NULL,
9 address_at TEXT NOT NULL DEFAULT '',
10 dns_at TEXT NOT NULL DEFAULT '',
11 answered_at TEXT NOT NULL DEFAULT '',
12 gave_up_at TEXT NOT NULL DEFAULT ''
13 );
14 `;
src/core/pinned_watch.ts added +45
@@ -0,0 +1,45 @@
1 /**
2 * What the forge's watch over a pinned forge has seen (#16372): the time of each step, kept in
3 * `pinned_watch`. Plain rows in and out; the loop that fills them is `actions/pinned_watch.ts`.
4 */
5
6 import type { Database } from "bun:sqlite";
7
8 export interface WatchTimes {
9 readonly startedAt: string;
10 readonly addressAt: string;
11 readonly dnsAt: string;
12 readonly answeredAt: string;
13 readonly gaveUpAt: string;
14 }
15
16 export type WatchStep = "addressAt" | "dnsAt" | "answeredAt" | "gaveUpAt";
17 const COLUMN: Record<WatchStep, string> = { addressAt: "address_at", dnsAt: "dns_at", answeredAt: "answered_at", gaveUpAt: "gave_up_at" };
18
19 interface Row { started_at: string; address_at: string; dns_at: string; answered_at: string; gave_up_at: string }
20
21 export function watchOf(db: Database, pinnedId: string): WatchTimes | undefined {
22 const r = db.query<Row, [string]>("SELECT * FROM pinned_watch WHERE pinned_id = ?1").get(pinnedId);
23 return r ? { startedAt: r.started_at, addressAt: r.address_at, dnsAt: r.dns_at, answeredAt: r.answered_at, gaveUpAt: r.gave_up_at } : undefined;
24 }
25
26 /** A new wait begins: every step is forgotten. */
27 export function startWatchRow(db: Database, pinnedId: string, at: string): void {
28 db.query(
29 `INSERT INTO pinned_watch (pinned_id, started_at) VALUES (?1, ?2)
30 ON CONFLICT(pinned_id) DO UPDATE SET started_at = ?2, address_at = '', dns_at = '', answered_at = '', gave_up_at = ''`,
31 ).run(pinnedId, at);
32 }
33
34 /** Record a step once; true the first time. */
35 export function markStep(db: Database, pinnedId: string, step: WatchStep, at: string): boolean {
36 const c = COLUMN[step];
37 return db.query(`UPDATE pinned_watch SET ${c} = ?1 WHERE pinned_id = ?2 AND ${c} = ''`).run(at, pinnedId).changes === 1;
38 }
39
40 /** The names of the forges still waiting: started, not answered, not given up. */
41 export const waitingNames = (db: Database): string[] =>
42 db.query<{ name: string }, []>(
43 `SELECT f.name FROM pinned_watch w JOIN pinned_forge f ON f.id = w.pinned_id
44 WHERE w.answered_at = '' AND w.gave_up_at = '' AND f.state != 'retired'`,
45 ).all().map((r) => r.name);
src/main.ts +4
@@ -7,6 +7,7 @@
77 import { join } from "node:path";
88 import { sweepEntitlements } from "./billing/sync.ts";
99 import { sweepDesk } from "./actions/desk.ts";
10 import { resumePinnedWatches } from "./actions/pinned.ts";
1011 import { statusTick } from "./core/status_days.ts";
1112 import { scanNightly } from "./checks/scan.ts";
1213 import { nightlyDue } from "./checks/scan_store.ts";
@@ -959,6 +960,9 @@ const landingsWatch = watchLandings(app);
959960 // A child born before its apps were linked is offered the link, and a child offered one takes it:
960961 // at boot, then every tick.
961962 void followTick(app, true).catch((error) => app.log.error("could not link the apps", { error: String(error) }));
963 // A pinned forge still waiting for its address or answer is watched again
964 // (`actions/pinned_watch.ts`, #16372).
965 resumePinnedWatches(app);
962966 const staleTimer = setInterval(() => void during("asks", tickAsks, undefined, app), 120_000);
963967 // A desk note whose time is up goes off the home line at once, over the stream.
964968 const deskTimer = setInterval(() => void during("desk", () => sweepDesk(app), undefined, app), 30_000);
src/tui/screens/pinned.ts +2 −2
@@ -151,7 +151,7 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen {
151151 const rows: ListRow[] = forges().map((p) => ({
152152 title: p.name,
153153 ...(p.state === "failed" ? { tone: "danger" as const } : {}),
154 secondary: `${p.target} · ${short(p.version)} · ${p.state}${p.url !== "" ? ` · ${p.url}` : ""}`,
154 secondary: `${p.target} · ${short(p.version)} · ${p.state}${p.url !== "" ? ` · ${p.url}` : ""}${p.stuck === "" ? "" : ` · ${p.stuck}`}`,
155155 meta: p.changes[0] ? `${p.changes[0].kind} ${p.changes[0].at.slice(0, 16).replace("T", " ")}` : "",
156156 }));
157157 drawList(s, list!, c, state, rows);
@@ -204,7 +204,7 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen {
204204 void settle(rollbackPinned(f.app, f.user, p.name), "Rolled back");
205205 } else if (e.key === "c") {
206206 say(`Checking ${p.name}…`);
207 void checkPinned(f.app, f.user, p.name).then((r) => say(r.ok ? checkWords(r.value) : r.error));
207 void checkPinned(f.app, f.user, p.name).then((r) => say(r.ok ? `${checkWords(r.value)}${r.value.stuck === "" ? "" : ` ${r.value.stuck}`}` : r.error));

The stuck sentence reaches the terminal only after pressing c; the page shows it on the row unprompted. Show p.stuck on the row in this screen too (both doors).

208208 } else if (e.key === "f") {
209209 say(`Filing ${p.name} in its cloud project…`);
210210 void fileForge(f.app, f.user, p.name).then((r) => say(r.ok ? r.value : r.error));
src/web/pages/pinned.ts +1 −1
@@ -81,7 +81,7 @@ function forge(p: PinnedView, f: PinnedFacts): Html {
8181 ${fact("App", html`<span class="mono">${p.app}</span>`)}
8282 ${fact("Version", html`<span class="mono" title="${p.version}">${p.version.slice(0, 12)}</span>`)}
8383 ${fact("Address", p.url === "" ? none("no name yet") : html`<a class="mono" href="${p.url}" rel="noopener noreferrer">${p.url}</a>`)}
84 ${fact("DNS record", p.dns === "" ? none("Check reads the machine's address") : html`<span class="mono">${p.dns}</span> ${p.dnsWrittenBy === "" ? none("create it by hand") : none(`written by the forge in ${p.dnsWrittenBy}`)}`)}
84 ${fact("DNS record", html`${p.dns === "" ? none(p.stuck === "" ? "the forge reads the machine's address" : "no address yet") : html`<span class="mono">${p.dns}</span> ${p.dnsWrittenBy === "" ? none("create it by hand") : none(`written by the forge in ${p.dnsWrittenBy}`)}`}${p.stuck === "" ? null : html` <span role="status">${p.stuck}</span>`}`)}
8585 ${fact("Claim link", p.claimedAt !== "" ? html`used` : p.claimExpires === "" ? none("none issued") : html`shown once; works until ${time(p.claimExpires)} unless used. Check asks the forge whether it was.`)}
8686 ${p.state === "retired" ? fact("Kept data", p.volume === "" ? none("deleted") : html`its volume is kept${p.keepCents > 0 ? html`, about ${dollars(p.keepCents)} a month at list price` : null}`) : null}
8787 ${fact("Health", badge(p.state, { tone: TONE[p.state] ?? "default" }))}
test/job-slices.test.ts +1
@@ -267,6 +267,7 @@ const UNTIMED: Record<string, string> = {
267267 "deploy-permit-ceiling": "a one-shot timer armed per deploy that only aborts it and resolves the race when a deploy outlives 30 minutes; permit-ceiling.test.ts and deploy-permit-ceiling.test.ts drive it with a short ceiling",
268268 "upstream-wait": "a one-shot timer that only aborts one proxied request when its app sends no headers in 30 s; no work of its own, cleared when the headers arrive; the upstream-wait tests drive it with a short wait",
269269 "bring-wait": "a one-shot timer that only resolves a promise when a bring's mirror is still copying after 60 s, so the answer says it is copying (actions/bring.ts, bringToWork); no work of its own; talk-bring.test.ts brings a repository that settles first",
270 "pinned-watch": "a one-shot timer between the pinned watch's looks at a pinned deploy (actions/pinned_watch.ts WATCH.sleep); it only resolves the sleep, no work of its own; pinned-watch tests drive the watch with a short sleep",
270271 "runner-wait": "one-shot timers that only resolve a promise: a runner's claim held open, a check's look at its job each second (checks/runner_jobs.ts, runner_step.ts) and the runner program's own pauses; off unless FORGE_CHECKS_PLACEMENT=runner, and checks-runner-placement.test.ts drives all three",
271272 "git-pace": "a one-shot timer in git/pace.ts that only resolves the promise a paced pack write waits on: no work of its own, armed per pack chunk while a page response is in flight; git-pace.test.ts drives the pacer with a fake clock",
272273 "drill-watch": "a /proc read of the drill child's memory and a state write every WATCH_MS, only while a restore drill runs in its own process; drill-job tests drive runDrillInChild directly",
test/pinned-watch.test.ts added +177
@@ -0,0 +1,177 @@
1 /**
2 * The forge waits for its own pinned forges (#16372): the machine's address appears on the third
3 * read, the DNS record is written and the forge's answer heard with no Check call; a restart in
4 * the middle resumes the wait; a wait past its bound says so once. A recorded fetch stands in for
5 * DigitalOcean and Cloudflare.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts";
13 import { changeBaseDomain, checkPinned, claimWords, deployPinned, net, pinnedForges, resumePinnedWatches } from "../src/actions/pinned.ts";
14 import { WATCH } from "../src/actions/pinned_watch.ts";
15 import { setCeiling } from "../src/actions/cloud_ceiling.ts";
16 import { dnsOf, getPinned } from "../src/core/pinned.ts";
17 import { watchOf } from "../src/core/pinned_watch.ts";
18 import { createUser, getUserByName } from "../src/core/users.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20 import { seedPlaces } from "./helpers/places-fixture.ts";
21 import { pinnedScreen } from "../src/tui/screens/pinned.ts";
22 import { pinnedListPage } from "../src/web/pages/pinned.ts";
23 import { quietCtx, screenText, sessionFor } from "./helpers/tui-text.ts";
24
25 quietLogs();
26
27 const ZONE = "a".repeat(32);
28 const until = async (ok: () => boolean) => {
29 for (let i = 0; i < 200000 && !ok(); i++) await new Promise((r) => setImmediate(r));
30 expect(ok()).toBe(true);
31 };
32
33 describe("the forge writes the record without a Check", () => {
34 let dataDir = "";
35 let app: App;
36 let reads = 0;
37 let counting = false;
38 let hideUntil = 3;
39 let answers = true;
40 const records: { id: string; name: string; content: string }[] = [];
41 const admin = () => getUserByName(app.db, "alice")!;
42 const view0 = () => claimWords({ name: "x", host: "x.forges.test", url: "https://x.forges.test", dns: "", dnsWrittenBy: "", dnsAuto: false, claim: { expiresAt: "later" } } as unknown as Parameters<typeof claimWords>[0]);
43 const input = (name: string) => ({ name, host: "", target: "digitalocean", account: "main", app: "alice/shop", source: "https://forge.example.org/trevato/forge", version: "a".repeat(40), config: {} });
44
45 beforeAll(async () => {
46 dataDir = await mkdtemp(join(tmpdir(), "forge-watch-"));
47 app = createApp({ dataDir, port: 0 });
48 await seedPlaces(app.db);
49 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
50 if (!made.ok) throw new Error(made.error);
51 cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" }, result: [], servers: [] }), { status: 200 });
52 for (const [provider, token] of [["digitalocean", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"], ["cloudflare", "cf_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9Lm2"]] as const)
53 if (!(await addAccount(app, admin(), provider, "main", token)).ok) throw new Error("account");
54 allowWrite(app, admin(), "digitalocean", "main", true);
55 allowWrite(app, admin(), "cloudflare", "main", true);
56 setCeiling(app, admin(), "digitalocean", "main", 500);
57 changeBaseDomain(app, admin(), "forges.test");
58 net.resolve = async (h) => records.filter((r) => r.name === h).map((r) => r.content);
59 net.probe = async () => new Response("ok", { status: answers ? 200 : 502 });
60 net.fetch = async (url, init) => {
61 const u = new URL(url);
62 const method = init?.method ?? "GET";
63 const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status });
64 if (u.host === "api.cloudflare.com") {
65 const body = init?.body ? JSON.parse(String(init.body)) : undefined;
66 if (u.pathname === "/client/v4/zones") return json({ success: true, result: u.searchParams.get("name") === "forges.test" ? [{ id: ZONE, name: "forges.test" }] : [] });
67 if (method === "GET") return json({ success: true, result: records.filter((r) => r.name === u.searchParams.get("name")) });
68 if (method === "POST") {
69 const r = { id: (records.length + 1).toString(16).padStart(32, "0"), name: body.name, content: body.content };
70 records.push(r);
71 return json({ success: true, result: r });
72 }
73 const r = records.find((x) => u.pathname.endsWith(x.id))!;
74 Object.assign(r, body);
75 return json({ success: true, result: r });
76 }
77 if (u.pathname.endsWith("/volumes")) return json({ volume: { id: "vol-1" } }, 201);
78 if (u.pathname.endsWith("/account/keys")) return json({ ssh_key: { id: 4242 } }, 201);
79 if (method === "DELETE") return new Response(null, { status: 204 });
80 if (method === "POST") return json({ droplet: { id: 1001 } }, 202);
81 const hidden = !counting || ++reads < hideUntil;
82 return json({ droplet: { id: 1001, status: "active", networks: { v4: hidden ? [] : [{ type: "public", ip_address: "203.0.113.9" }] } } });
83 };
84 WATCH.everyMs = 1;
85 }, 30_000);
86
87 afterAll(async () => {
88 WATCH.stop(app);
89 WATCH.on = false;
90 app.close();
91 await rm(dataDir, { recursive: true, force: true });
92 });
93
94 test("the address appears on the third read: the record is written and the answer heard, with no Check", async () => {
95 WATCH.on = true;
96 WATCH.boundMs = 300_000;
97 counting = false;
98 hideUntil = 3;
99 const r = await deployPinned(app, admin(), input("acme"));
100 expect(r.ok).toBe(true);
101 expect(r.ok && r.value.dnsAuto).toBe(true);
102 expect(r.ok && claimWords(r.value)).toContain("nobody needs to press Check");
103 expect(r.ok && claimWords(r.value)).not.toContain("Check reads");
104 expect(getPinned(app.db, "acme")!.address).toBe("");
105 counting = true; // the deploy's own read happened with no address; the watch's reads are counted from here
106 const id = getPinned(app.db, "acme")!.id;
107 await until(() => (watchOf(app.db, id)?.answeredAt ?? "") !== "");
108 expect(reads).toBe(3);
109 expect(getPinned(app.db, "acme")!.address).toBe("203.0.113.9");
110 expect(records.find((x) => x.name === "acme.forges.test")?.content).toBe("203.0.113.9");
111 expect(dnsOf(app.db, id)).toBeDefined();
112 const w = watchOf(app.db, id)!;
113 expect(w.addressAt).not.toBe("");
114 expect(w.dnsAt).not.toBe("");
115 expect(w.gaveUpAt).toBe("");
116 expect(getPinned(app.db, "acme")!.state).toBe("running");
117 });
118
119 test("a restart in the middle of the wait resumes it", async () => {
120 WATCH.on = true;
121 counting = false;
122 hideUntil = 2;
123 reads = 0;
124 const r = await deployPinned(app, admin(), { ...input("beta") });
125 expect(r.ok).toBe(true);
126 const id = getPinned(app.db, "beta")!.id;
127 WATCH.stop(app); // the process ends here
128 expect(watchOf(app.db, id)!.answeredAt).toBe("");
129 counting = true;
130 resumePinnedWatches(app); // the next boot
131 await until(() => (watchOf(app.db, id)?.answeredAt ?? "") !== "");
132 expect(records.find((x) => x.name === "beta.forges.test")?.content).toBe("203.0.113.9");
133 });
134
135 test("a forge still not answering at the bound is said so once, on the row and to admins", async () => {
136 WATCH.on = true;
137 answers = false;
138 counting = true;
139 hideUntil = 0;
140 WATCH.boundMs = 40;
141 const r = await deployPinned(app, admin(), input("gamma"));
142 expect(r.ok).toBe(true);
143 const id = getPinned(app.db, "gamma")!.id;
144 await until(() => (watchOf(app.db, id)?.gaveUpAt ?? "") !== "");
145 const said = app.db.query("SELECT payload FROM event WHERE kind = 'pinned.waiting_long'").all() as { payload: string }[];
146 expect(said.length).toBe(1);
147 expect(said[0]!.payload).toContain("does not answer over HTTPS");
148 expect(watchOf(app.db, id)!.answeredAt).toBe("");
149 answers = true;
150 });
151
152 test("the stuck sentence shows on the page row and the terminal row, and a Check that hears the forge clears it", async () => {
153 const view = () => {
154 const r = pinnedForges(app, admin());
155 if (!r.ok) throw new Error(r.error);
156 return r.value;
157 };
158 const page = () => String(pinnedListPage(view(), { names: new Map(), checks: new Map(), domain: "forges.test" }));
159 const stuck = view().find((v) => v.name === "gamma")!.stuck;
160 expect(stuck).toContain("does not answer over HTTPS");
161 expect(stuck.split(". ").length).toBe(1);
162 expect(page()).toContain(`<span role="status">${stuck}</span>`);
163 const screen = pinnedScreen(sessionFor(app, admin()), quietCtx());
164 expect(screenText(screen, 400, 20)).toContain(stuck);
165 const checked = await checkPinned(app, admin(), "gamma");
166 expect(checked.ok && checked.value.healthy).toBe(true);
167 expect(view().find((v) => v.name === "gamma")!.stuck).toBe("");
168 expect(page()).not.toContain('role="status"');
169 expect(screenText(screen, 400, 20)).not.toContain("does not answer");
170 });
171
172 test("with no Cloudflare write account the claim says the record is made by hand once Check reads the address", () => {
173 const r = view0();
174 expect(r).toContain("by hand once Check reads its address");
175 expect(r).not.toContain("nobody needs to press Check");
176 });
177 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs