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

Cloud tests share one recorded cloud, and the repository has a formatter config #16517

Merged opened this in answer to

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

Merged

mason/forge:mason/16327-cloud-tests-share-one-recorded-cloud-and → main 0 commits fork 4 threads · 4 unresolved

  • Merged. mason/16327-cloud-tests-share-one-recorded-cloud-and was merged into main as e775e2f.

Review

Sign in to review this change.
9 files changed +244 −187
.editorconfig added +8
@@ -0,0 +1,8 @@
1 root = true
2
3 [*]
4 charset = utf-8
5 end_of_line = lf
6 insert_final_newline = true
7 indent_style = space
8 indent_size = 2
.prettierignore added +6
@@ -0,0 +1,6 @@
1 # src/ is written by hand, compact: records and argument lists sit several to a line, and no
2 # printWidth reproduces that, so a formatter run over a file there would rewrap it whole. The
3 # existing tests and scripts are written the same way. test/helpers/ and new directories are formatted.
4 src/

Ignoring src/, test/ and scripts/ makes the formatter a no-op for the whole repository. Ignore only src/, or remove the config.

5 scripts/
6 test/*.test.ts
.prettierrc.json added +7
@@ -0,0 +1,7 @@
1 {
2 "printWidth": 140,
3 "semi": true,
4 "singleQuote": false,
5 "trailingComma": "all",
6 "arrowParens": "always"
7 }
CLAUDE.md +12
@@ -76,6 +76,18 @@ bun run src/main.ts # boots on :3000, data in ./data
7676 changes. Never rewrap a comment by hand. A long comment line never fails a
7777 check: the gate notes it, and the nightly `rewrap` job proposes main's
7878 touched files rewrapped as one pull (`src/nightly/propose.ts`).
79 - **A formatter config is there, and it leaves `src/`, `scripts/` and the existing tests alone.**
80 `.prettierrc.json` (width 140, double quotes, trailing commas) and `.editorconfig` say how
81 a new file is written; `.prettierignore` lists the hand-compacted files, because no
82 width reproduces how `src/` is written (records and argument lists several to a line) and a
83 format-on-save would rewrap a whole file. Only `test/helpers/` and new directories are formatted; formatting a file in the rest is a no-op: do not
84 reformat the tree, and do not change a file by script to keep a diff honest.
85 - **The cloud tests share one recorded cloud.** `test/helpers/recorded-cloud.ts` answers like
86 DigitalOcean or Hetzner by host, records the calls, and names the sequences
87 (`sequence.create`, `.replace`, `.read`); a driver that makes one more call changes it
88 there. `pinned-forge`, `pinned-claim`, `pinned-ceiling` and `pinned-hetzner` use it; a new
89 test of the pinned deploys should too. Other cloud tests still assign `net.fetch` with a
90 fake of their own and are not yet moved.
7991 - **`git push` is blocked at the shell level.** In tests and scripts that need a
8092 git _client_, drive it through `Bun.spawn(["git", ...])`, never a shell push.
8193 See `test/app.test.ts` / `test/onboarding.test.ts` for the pattern.
test/helpers/recorded-cloud.ts added +129
@@ -0,0 +1,129 @@
1 /**
2 * One recorded cloud for the pinned-forge, -claim, -ceiling and -hetzner tests: a fetch that
3 * answers like DigitalOcean or Hetzner by its host, records every call, and names the call
4 * sequences a driver makes (create, replace, read). A driver that makes one more call changes one
5 * line here, not the expected list in each test. Assign `cloud.fetch` to the pinned actions'
6 * `net.fetch`.
7 */
8
9 export type Provider = "digitalocean" | "hetzner";
10 export type Kind = "volume" | "key" | "machine";
11 export type Call = { method: string; host: string; path: string; kind: Kind | undefined; auth: string | null; body: any };
12 /** A refusal: the cloud answers `status`, or the connection is cut ("throw"). */
13 export type Fault = { method?: string; kind?: Kind; read?: boolean; status?: number | "throw"; times?: number };
14
15 const KEY = 4242;
16 const SHAPES = {
17 digitalocean: {
18 host: "api.digitalocean.com",
19 volumes: "/v2/volumes",
20 keys: "/v2/account/keys",
21 machines: "/v2/droplets",
22 volume: "vol-1",
23 },
24 hetzner: { host: "api.hetzner.cloud", volumes: "/v1/volumes", keys: "/v1/ssh_keys", machines: "/v1/servers", volume: 77 },
25 };
26
27 /** The calls a driver makes for one operation, in order, as `METHOD path`. */
28 export const sequence = {
29 /**
30 * A deploy: the volume, a throwaway key around the machine, then the machine's address read back.
31 */
32 create(p: Provider, machine: number | string): string[] {
33 const s = SHAPES[p];
34 return [`POST ${s.volumes}`, `POST ${s.keys}`, `POST ${s.machines}`, `DELETE ${s.keys}/${KEY}`, `GET ${s.machines}/${machine}`];
35 },
36 /**
37 * An Update or a new claim link: read the old machine, delete it, wait for the volume, make the
38 * new one.
39 */
40 replace(p: Provider, old: number | string, volume: number | string = SHAPES[p].volume): string[] {
41 const s = SHAPES[p];
42 return [
43 `GET ${s.machines}/${old}`,
44 `DELETE ${s.machines}/${old}`,
45 `GET ${s.volumes}/${volume}`,
46 `POST ${s.keys}`,
47 `POST ${s.machines}`,
48 `DELETE ${s.keys}/${KEY}`,
49 ];
50 },
51 /** The address check: one read of the machine. */
52 read(p: Provider, machine: number | string): string[] {
53 return [`GET ${SHAPES[p].machines}/${machine}`];
54 },
55 };
56
57 export function recordCloud(opts: { firstMachine?: number; address?: string } = {}) {
58 const calls: Call[] = [];
59 /** The body of every machine asked for, newest last. */
60 const machines: any[] = [];
61 const faults: Required<Fault>[] = [];
62 let machine = (opts.firstMachine ?? 501) - 1;
63 const address = opts.address ?? "203.0.113.9";
64 const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status });
65
66 const fetch = async (url: string, init?: RequestInit): Promise<Response> => {
67 const u = new URL(url);
68 const provider = (Object.keys(SHAPES) as Provider[]).find((p) => SHAPES[p].host === u.host);
69 if (!provider) throw new Error(`the recorded cloud was asked for ${u.host}`);
70 const s = SHAPES[provider];
71 const method = init?.method ?? "GET";
outdated

Special case for the volume id. Put the id in SHAPES per provider (77 as a number for Hetzner, "vol-1" for DigitalOcean) instead of comparing the string.

72 const kind: Kind | undefined = u.pathname.startsWith(s.volumes)
73 ? "volume"
74 : u.pathname.startsWith(s.keys)
75 ? "key"
76 : u.pathname.startsWith(s.machines)
77 ? "machine"
78 : undefined;
79 const body = init?.body ? JSON.parse(String(init.body)) : undefined;
80 calls.push({ method, host: u.host, path: u.pathname, kind, auth: new Headers(init?.headers).get("authorization"), body });
81 const fault = faults.find(
82 (f) => f.times > 0 && (!f.method || f.method === method) && (!f.kind || f.kind === kind) && (!f.read || method === "GET"),
83 );
84 if (fault) {
85 fault.times--;
86 if (fault.status === "throw") throw new Error("socket closed");
87 return json({}, fault.status);
88 }
89 const created = method === "POST";
90 if (kind === "key") return created ? json({ ssh_key: { id: KEY } }, 201) : new Response(null, { status: 204 });
91 if (kind === "volume") {
92 if (created) return json({ volume: { id: s.volume } }, 201);
93 if (method === "GET") return json({ volume: provider === "hetzner" ? { id: s.volume, server: null } : { id: s.volume } });
94 }
95 if (method === "DELETE") return provider === "hetzner" ? json({ action: {} }) : new Response(null, { status: 204 });
96 if (kind === "machine") {
97 if (created) machines.push(body);
98 const id = created ? ++machine : Number(u.pathname.split("/").at(-1));
99 if (provider === "hetzner")
100 return json(
101 created ? { server: { id } } : { server: { status: "running", public_net: { ipv4: { ip: address } } } },
102 created ? 201 : 200,
103 );
104 return json({ droplet: { id, status: "active", networks: { v4: [{ type: "public", ip_address: address }] } } }, created ? 202 : 200);
105 }
106 return json({}, 404);
107 };
108
109 return {
110 fetch,
111 calls,
112 machines,
113 /** The id of the last machine made. */
114 get machine() {
115 return machine;
116 },
117 /** Every call so far as `METHOD path`. */
118 seen: (): string[] => calls.map((c) => `${c.method} ${c.path}`),
119 /** Forget the calls (the machines asked for are kept). */
120 clear: (): void => void (calls.length = 0),
121 /** The cloud refuses the next `times` calls that match (once, by default). */
122 fail(f: Fault): void {
123 faults.push({ method: "", kind: undefined as never, read: false, status: 500, times: 1, ...f } as Required<Fault>);
124 },
125 /** Stop refusing. */
126 mend: (): void => void (faults.length = 0),
127 };
128 }
129 export type RecordedCloud = ReturnType<typeof recordCloud>;
test/pinned-ceiling.test.ts +28 −50
@@ -19,6 +19,7 @@ import { getCloudAccount } from "../src/core/cloud_account.ts";
1919 import { getPinned } from "../src/core/pinned.ts";
2020 import { createUser, getUserByName } from "../src/core/users.ts";
2121 import { quietLogs } from "./helpers/globals.ts";
22 import { recordCloud } from "./helpers/recorded-cloud.ts";
2223 import { seedPlaces } from "./helpers/places-fixture.ts";
2324
2425 quietLogs();
@@ -30,8 +31,7 @@ const SOURCE = "https://forge.example.org/trevato/forge";
3031 describe("cloud account ceiling", () => {
3132 let dataDir = "";
3233 let app: App;
33 const calls: string[] = [];
34 let seq = 1000;
34 const cloud = recordCloud();
3535
3636 const admin = () => getUserByName(app.db, "alice")!;
3737 const input = (name: string, over: Record<string, unknown> = {}) => ({
@@ -54,18 +54,7 @@ describe("cloud account ceiling", () => {
5454 if (!added.ok) throw new Error(String(added.error));
5555 allowWrite(app, admin(), provider, "main", true);
5656 }
57 net.fetch = async (url, init) => {
58 const u = new URL(url);
59 const method = init?.method ?? "GET";
60 calls.push(`${method} ${u.host}${u.pathname}`);
61 const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status });
62 if (u.pathname === "/v2/volumes" || u.pathname === "/v1/volumes") return json({ volume: { id: ++seq } }, 201);
63 // Each machine is made with a throwaway SSH key, deleted after the call (#16218).
64 if (u.pathname === "/v2/account/keys" || u.pathname === "/v1/ssh_keys") return json({ ssh_key: { id: 4242 } }, 201);
65 if (method === "DELETE") return new Response(null, { status: 204 });
66 if (u.pathname === "/v1/servers") return json({ server: { id: ++seq } }, 201);
67 return json({ droplet: { id: ++seq } }, 202);
68 };
57 net.fetch = cloud.fetch;
6958 }, 30_000);
7059
7160 afterAll(async () => {
@@ -136,14 +125,14 @@ describe("cloud account ceiling", () => {
136125 });
137126
138127 test("the deploy that would cross the ceiling is refused before any provider call", async () => {
139 calls.length = 0;
128 cloud.clear();
140129 const r = await deployPinned(app, admin(), input("four"));
141130 expect(r).toMatchObject({ ok: false });
142131 expect(error(r)).toBe(
143132 "digitalocean/main is held to $50 a month and runs $39.00 now; this would add $13.00, which is over it, so nothing was made. " +
144133 "Raise the ceiling at /settings/cloud if you mean to spend more. This is the forge's own reckoning from list prices; the provider's bill is the truth.",
145134 );
146 expect(calls).toHaveLength(0);
135 expect(cloud.calls).toHaveLength(0);
147136 });
148137
149138 test("raising the ceiling lets it through", async () => {
@@ -157,7 +146,7 @@ describe("cloud account ceiling", () => {
157146 expect(o.ok && o.value.accounts.find((a) => a.provider === "digitalocean")?.leftCents).toBe(0);
158147 const r = await updatePinned(app, admin(), "one", { version: V2 });
159148 expect(r.ok).toBe(true);
160 expect(calls.filter((c) => c.startsWith("DELETE")).length).toBeGreaterThan(0);
149 expect(cloud.seen().filter((c) => c.startsWith("DELETE")).length).toBeGreaterThan(0);
161150 });
162151
163152 test("a ceiling is whole dollars, and only an admin sets it", () => {
@@ -167,19 +156,19 @@ describe("cloud account ceiling", () => {
167156 });
168157
169158 test("a place the catalog does not hold is refused before any provider call; one it lost the price of is never counted as free", async () => {
170 calls.length = 0;
159 cloud.clear();
171160 const unknown = await deployPinned(app, admin(), input("odd", { target: "hetzner", place: "hetzner:nbg1:cx99" }));
172161 expect(error(unknown)).toContain("There is no place hetzner:nbg1:cx99 in the catalog");
173 expect(calls).toEqual([]);
162 expect(cloud.calls).toEqual([]);
174163 expect(getPinned(app.db, "odd")).toBeUndefined();
175164 // A forge whose recorded place the catalog no longer lists cannot be held to a ceiling, so a
176165 // replace is refused with the reading calls only.
177166 expect((await deployPinned(app, admin(), hetznerInput("lost"))).ok).toBe(true);
178167 setSize("lost", "cx99");
179 calls.length = 0;
168 cloud.clear();
180169 const r = await updatePinned(app, admin(), "lost", { version: V2 });
181170 expect(error(r)).toContain("The forge has no price for cx99 in nbg1 on hetzner, so it cannot hold hetzner/main to its ceiling; nothing was made.");
182 expect(calls.every((c) => c.startsWith("GET"))).toBe(true);
171 expect(cloud.calls.every((c) => c.method === "GET")).toBe(true);
183172 expect(getPinned(app.db, "lost")).toMatchObject({ state: "running", version: V1 });
184173 });
185174
@@ -197,11 +186,11 @@ describe("cloud account ceiling", () => {
197186 test("a new claim link replaces at the forge's recorded place, so it adds nothing even over a lowered ceiling", async () => {
198187 const was = getPinned(app.db, "het")!;
199188 expect(setCeiling(app, admin(), "hetzner", "main", 5).ok).toBe(true);
200 calls.length = 0;
189 cloud.clear();
201190 const r = await claimPinned(app, admin(), "het");
202191 expect(r.ok).toBe(true);
203192 // The server was made where the volume is, at the size the row recorded.
204 const made = calls.find((c) => c === "POST api.hetzner.cloud/v1/servers");
193 const made = cloud.seen().find((c) => c === "POST /v1/servers");
205194 expect(made).toBeDefined();
206195 expect(getPinned(app.db, "het")).toMatchObject({ datacenter: "nbg1", size: "cx23", volume: was.volume });
207196 expect(setCeiling(app, admin(), "hetzner", "main", 50).ok).toBe(true);
@@ -226,13 +215,13 @@ describe("cloud account ceiling", () => {
226215
227216 test("two new claim links asked together for one forge run one after the other: no machine is left behind", async () => {
228217 const before = getPinned(app.db, "three")!.remote;
229 calls.length = 0;
218 cloud.clear();
230219 const [a, b] = await Promise.all([claimPinned(app, admin(), "three"), claimPinned(app, admin(), "three")]);
231220 expect(a.ok && b.ok).toBe(true);
232 const droplets = calls.filter((c) => /^(DELETE|POST) api\.digitalocean\.com\/v2\/droplets/.test(c)).map((c) => c.split(" ")[0]);
221 const droplets = cloud.seen().filter((c) => /^(DELETE|POST) \/v2\/droplets/.test(c)).map((c) => c.split(" ")[0]);
233222 // Never two deletes or two creates in a row: each replacement finished before the next began.
234223 expect(droplets).toEqual(["DELETE", "POST", "DELETE", "POST"]);
235 const deleted = calls.filter((c) => c.startsWith("DELETE api.digitalocean.com/v2/droplets/")).map((c) => c.split("/").at(-1)!);
224 const deleted = cloud.seen().filter((c) => c.startsWith("DELETE /v2/droplets/")).map((c) => c.split("/").at(-1)!);
236225 const now = getPinned(app.db, "three")!.remote;
237226 // The first deleted the machine there was; the second deleted the first's; the row holds the
238227 // last.
@@ -244,34 +233,24 @@ describe("cloud account ceiling", () => {
244233 });
245234
246235 test("a turn is given back however a create ends: refused by the ceiling, refused by the cloud, or cut off; the next one completes", async () => {
247 const real = net.fetch;
248 let how: "" | "500" | "throw" = "";
249 net.fetch = async (url, init) => {
250 if (how !== "" && init?.method === "POST" && new URL(url).pathname === "/v2/droplets") {
251 const was = how;
252 how = "";
253 if (was === "throw") throw new Error("socket closed");
254 return new Response("{}", { status: 500 });
255 }
256 return real(url, init);
257 };
236 const how = (status: number | "throw"): void => cloud.fail({ method: "POST", kind: "machine", status });
258237 try {
259238 // The account's turn: a ceiling refusal, then the cloud's refusal, then a cut connection,
260239 // each followed by a create on the same account that is answered.
261240 expect((await deployPinned(app, admin(), input("turna"))).ok).toBe(false);
262241 expect(setCeiling(app, admin(), "digitalocean", "main", 500).ok).toBe(true);
263242 for (const end of ["500", "throw"] as const) {
264 how = end;
243 how(end === "500" ? 500 : "throw");
265244 const failed = await deployPinned(app, admin(), input(`turn${end === "500" ? "b" : "c"}`));
266245 expect(failed).toMatchObject({ ok: false });
267246 expect(error(failed)).toContain("The cloud refused");
268247 }
269248 expect((await deployPinned(app, admin(), input("turnd"))).ok).toBe(true);
270249 // The forge's turn: an Update and a new claim link that each fail, then each asked again.
271 how = "500";
250 how(500);
272251 expect((await updatePinned(app, admin(), "turnd", { version: V2 })).ok).toBe(false);
273252 expect((await updatePinned(app, admin(), "turnd", { version: V2 })).ok).toBe(true);
274 how = "throw";
253 how("throw");
275254 expect((await claimPinned(app, admin(), "turnd")).ok).toBe(false);
276255 expect((await claimPinned(app, admin(), "turnd")).ok).toBe(true);
277256 // A refusal before anything is asked gives it back too.
@@ -280,7 +259,7 @@ describe("cloud account ceiling", () => {
280259 expect((await updatePinned(app, admin(), "turnd", { version: V1 })).ok).toBe(true);
281260 expect(getPinned(app.db, "turnd")).toMatchObject({ state: "running", version: V1 });
282261 } finally {
283 net.fetch = real;
262 cloud.mend();
284263 }
285264 });
286265
@@ -290,10 +269,10 @@ describe("cloud account ceiling", () => {
290269 expect(getPinned(app.db, "het")).toMatchObject({ state: "running" });
291270 const server = getPinned(app.db, "het")!.remote;
292271 setSize("het", "cx99");
293 calls.length = 0;
272 cloud.clear();
294273 const refused = await updatePinned(app, admin(), "het", { version: V2 });
295274 expect(error(refused)).toContain("has no price for cx99");
296 expect(calls.filter((c) => !c.startsWith("GET"))).toEqual([]);
275 expect(cloud.calls.filter((c) => c.method !== "GET")).toEqual([]);
297276 // Nothing moved: not the machine, not its state, not the pin, and no change is recorded.
298277 expect(getPinned(app.db, "het")).toMatchObject({ state: "running", remote: server, version: V1 });
299278 expect(app.db.query("SELECT count(*) AS n FROM pinned_change WHERE pinned_id = (SELECT id FROM pinned_forge WHERE name = 'het')").get()).toEqual({ n: 1 });
@@ -302,12 +281,11 @@ describe("cloud account ceiling", () => {
302281 setSize("het", "cx23");
303282 expect(getPinned(app.db, "het")).toMatchObject({ state: "running", remote: server });
304283
305 const real = net.fetch;
306284 const machine = getPinned(app.db, "turnd")!.remote;
307285 expect(getPinned(app.db, "turnd")?.state).toBe("running");
308286 // The cloud refuses the delete of a new claim link's replacement: nothing was recorded for it
309287 // and the old machine still runs, so the forge is as it was.
310 net.fetch = async (url, init) => (init?.method === "DELETE" && new URL(url).pathname.startsWith("/v2/droplets/") ? new Response("{}", { status: 500 }) : real(url, init));
288 cloud.fail({ method: "DELETE", kind: "machine", times: Infinity });
311289 try {
312290 expect((await claimPinned(app, admin(), "turnd")).ok).toBe(false);
313291 expect(getPinned(app.db, "turnd")).toMatchObject({ state: "running", remote: machine });
@@ -316,16 +294,16 @@ describe("cloud account ceiling", () => {
316294 expect((await updatePinned(app, admin(), "turnd", { version: V2 })).ok).toBe(false);
317295 expect(getPinned(app.db, "turnd")).toMatchObject({ state: "failed", remote: machine, version: V2 });
318296 } finally {
319 net.fetch = real;
297 cloud.mend();
320298 }
321299 // The delete went through and the create did not: no machine, so failed, and asked again it is
322300 // made.
323 net.fetch = async (url, init) => (init?.method === "POST" && new URL(url).pathname === "/v2/droplets" ? new Response("{}", { status: 500 }) : real(url, init));
301 cloud.fail({ method: "POST", kind: "machine", times: Infinity });
324302 try {
325303 expect((await updatePinned(app, admin(), "turnd", { version: V2 })).ok).toBe(false);
326304 expect(getPinned(app.db, "turnd")).toMatchObject({ state: "failed", remote: "" });
327305 } finally {
328 net.fetch = real;
306 cloud.mend();
329307 }
330308 expect((await updatePinned(app, admin(), "turnd", { version: V2 })).ok).toBe(true);
331309 expect(getPinned(app.db, "turnd")).toMatchObject({ state: "running", version: V2 });
@@ -333,7 +311,7 @@ describe("cloud account ceiling", () => {
333311 // The cloud refuses the read of the machine, the first thing a change asks: refused with the
334312 // cloud's answer, nothing recorded, nothing changed. A machine that is gone (404) is replaced.
335313 const reads = (status: number): void =>
336 void (net.fetch = async (url, init) => ((init?.method ?? "GET") === "GET" && new URL(url).pathname.startsWith("/v2/droplets/") ? new Response("{}", { status }) : real(url, init)));
314 void (cloud.mend(), cloud.fail({ method: "GET", kind: "machine", status, times: Infinity }));
337315 const changes = () => app.db.query("SELECT count(*) AS n FROM pinned_change WHERE pinned_id = (SELECT id FROM pinned_forge WHERE name = 'turnd')").get() as { n: number };
338316 const recorded = changes().n;
339317 try {
@@ -345,7 +323,7 @@ describe("cloud account ceiling", () => {
345323 reads(404);
346324 expect((await updatePinned(app, admin(), "turnd", { version: V1 })).ok).toBe(true);
347325 } finally {
348 net.fetch = real;
326 cloud.mend();
349327 }
350328 });
351329
test/pinned-claim.test.ts +22 −78
@@ -59,6 +59,7 @@ import { pinnedScreen } from "../src/tui/screens/pinned.ts";
5959 import { pinnedListPage } from "../src/web/pages/pinned.ts";
6060 import { deployPage } from "../src/web/pinned.ts";
6161 import { Session } from "../src/tui/session.ts";
62 import { recordCloud, sequence } from "./helpers/recorded-cloud.ts";
6263 import { quietLogs } from "./helpers/globals.ts";
6364 import { seedPlaces } from "./helpers/places-fixture.ts";
6465 import { waitFor } from "./helpers/poll.ts";
@@ -120,12 +121,10 @@ describe("a deployed forge is claimed with the link its deployer was shown, and
120121 let sellerServers: Servers;
121122 let deployed: App;
122123 let servers: Servers;
123 /** Every machine the seller asked its cloud for, newest last. */
124 const machines: { user_data: string }[] = [];
125 const calls: string[] = [];
124 /** Every machine the seller asked its cloud for is in `machines`, newest last. */
125 const cloud = recordCloud({ firstMachine: 101, address: "203.0.113.7" });
126 const { machines } = cloud;
126127 let said: string | undefined;
127 /** The cloud refuses the next machine it is asked for. */
128 let refuseMachine = false;
129128 let code = "";
130129 const admin = () => getUserByName(seller.db, "alice")!;
131130 const input = (over: Record<string, unknown> = {}) => ({
@@ -172,37 +171,7 @@ describe("a deployed forge is claimed with the link its deployer was shown, and
172171 // would refuse the fourth, which is the ceiling's test to make (test/pinned-ceiling.test.ts).
173172 if (!setCeiling(seller, admin(), "digitalocean", "main", 500).ok)
174173 throw new Error("the ceiling was not set");
175 net.fetch = async (url, init) => {
176 const path = new URL(url).pathname;
177 const method = init?.method ?? "GET";
178 calls.push(`${method} ${path}`);
179 if (path === "/v2/volumes")
180 return new Response(JSON.stringify({ volume: { id: "vol-1" } }), {
181 status: 201,
182 });
183 if (method === "DELETE") return new Response(null, { status: 204 });
184 // Each machine is made with a throwaway SSH key, deleted after the call (#16218).
185 if (path === "/v2/account/keys")
186 return new Response(JSON.stringify({ ssh_key: { id: 4242 } }), {
187 status: 201,
188 });
189 if (method === "POST" && refuseMachine) {
190 refuseMachine = false;
191 return new Response("{}", { status: 500 });
192 }
193 if (method === "POST")
194 machines.push(JSON.parse(String(init?.body)) as { user_data: string });
195 return new Response(
196 JSON.stringify({
197 droplet: {
198 id: 100 + machines.length,
199 status: "active",
200 networks: { v4: [{ type: "public", ip_address: "203.0.113.7" }] },
201 },
202 }),
203 { status: 202 },
204 );
205 };
174 net.fetch = cloud.fetch;
206175 net.resolve = async () => ["203.0.113.7"];
207176 // The deployed forge, asked on its name: the claim question is answered by the real route.
208177 net.probe = async (url) => {
@@ -387,7 +356,7 @@ describe("a deployed forge is claimed with the link its deployer was shown, and
387356 .get() as { n: number };
388357 const before = events().n;
389358 said = "waiting";
390 refuseMachine = true;
359 cloud.fail({ method: "POST", kind: "machine" });
391360 const refused = await claimPinned(seller, admin(), "held");
392361 said = undefined;
393362 expect(refused).toMatchObject({ ok: false });
@@ -427,17 +396,14 @@ describe("a deployed forge is claimed with the link its deployer was shown, and
427396 ).toBe("seeded");
428397
429398 said = "waiting";
430 calls.length = 0;
399 cloud.clear();
431400 const again = await claimPinned(seller, admin(), "second");
432401 if (!again.ok) throw new Error(again.error);
433402 // The forge is asked whether it was claimed, at the address read back; then the machine is
434403 // replaced on the volume it had: nothing else carries a hash to it.
435 expect(calls.slice(0, 5)).toEqual([
436 "GET /v2/droplets/" + first.value.remote,
437 "DELETE /v2/droplets/" + first.value.remote,
438 "GET /v2/volumes/vol-1",
439 "POST /v2/account/keys",
440 "POST /v2/droplets",
404 expect(cloud.seen()).toEqual([
outdated

slice(0, 5) drops the last call of the sequence, so this checks less than the list it replaced. Compare the whole sequence.

405 ...sequence.replace("digitalocean", first.value.remote),
406 ...sequence.read("digitalocean", cloud.machine),
441407 ]);
442408 const next = LINK.exec(again.value.claim.link)![2]!;
443409 expect(next).not.toBe(old);
@@ -685,37 +651,15 @@ describe("claimed is what the deployed forge says, never what the seller says (#
685651 if (!made.ok) throw new Error(made.error);
686652 const alice = made.value;
687653 const kept = { fetch: net.fetch, probe: net.probe, resolve: net.resolve };
688 const cloud = cloudNet.fetch;
654 const ownCloud = cloudNet.fetch;
689655 let says = "waiting";
690 let machines = 0;
656 const second = recordCloud({ firstMachine: 101, address: "203.0.113.7" });
691657 cloudNet.fetch = async () =>
692658 new Response(
693659 JSON.stringify({ account: { email: "[email protected]", status: "active" } }),
694660 { status: 200 },
695661 );
696 net.fetch = async (url, init) => {
697 const path = new URL(url).pathname;
698 const method = init?.method ?? "GET";
699 if (path === "/v2/volumes")
700 return new Response(JSON.stringify({ volume: { id: "vol-1" } }), {
701 status: 201,
702 });
703 if (path === "/v2/account/keys")
704 return new Response(JSON.stringify({ ssh_key: { id: 4242 } }), {
705 status: 201,
706 });
707 if (method === "DELETE") return new Response(null, { status: 204 });
708 if (method === "POST") machines++;
709 return new Response(
710 JSON.stringify({
711 droplet: {
712 id: 100 + machines,
713 networks: { v4: [{ type: "public", ip_address: "203.0.113.7" }] },
714 },
715 }),
716 { status: 202 },
717 );
718 };
662 net.fetch = second.fetch;
719663 net.resolve = async () => ["203.0.113.7"];
720664 net.probe = async (url) =>
721665 new URL(url).pathname === "/api/v1/first-admin/claim"
@@ -769,14 +713,14 @@ describe("claimed is what the deployed forge says, never what the seller says (#
769713 expect(seen.ok && seen.value.claimedAt).not.toBe("");
770714 await checkPinned(app, alice, "one");
771715 expect(events()).toEqual([{ name: "one" }]);
772 const n = machines;
716 const n = second.machines.length;
773717 for (const refused of [
774718 await updatePinned(app, alice, "one", { version: V1 }),
775719 await rollbackPinned(app, alice, "one"),
776720 await claimPinned(app, alice, "one"),
777721 ])
778722 expect(refused).toMatchObject({ ok: false, error: CLAIMED_REFUSAL });
779 expect(machines).toBe(n);
723 expect(second.machines.length).toBe(n);
780724 expect(getPinned(app.db, "one")!.version).toBe(V2);
781725 const listed = pinnedForges(app, alice);
782726 expect(listed.ok && listed.value.find((p) => p.name === "one")!.claimedAt).not.toBe("");
@@ -785,9 +729,9 @@ describe("claimed is what the deployed forge says, never what the seller says (#
785729 says = "waiting";
786730 expect((await deploy("two")).ok).toBe(true);
787731 says = "claimed";
788 const before = machines;
732 const before = second.machines.length;
789733 expect(await claimPinned(app, alice, "two")).toMatchObject({ ok: false, error: CLAIMED_REFUSAL });
790 expect(machines).toBe(before);
734 expect(second.machines.length).toBe(before);
791735 expect(getPinned(app.db, "two")!.claimedAt).not.toBe("");
792736 expect(events()).toEqual([{ name: "one" }, { name: "two" }]);
793737
@@ -814,7 +758,7 @@ describe("claimed is what the deployed forge says, never what the seller says (#
814758 expect(getPinned(app.db, "four")!.reached).toBe(getPinned(app.db, "four")!.remote);
815759 // Then it goes silent (a broken DNS record, or an answer that is no answer): nothing replaces
816760 // its machine on a guess that nobody claimed it.
817 const stands = machines;
761 const stands = second.machines.length;
818762 for (const silent of [() => dns(false), () => void (says = "handed over")]) {
819763 dns(true);
820764 says = "waiting";
@@ -828,7 +772,7 @@ describe("claimed is what the deployed forge says, never what the seller says (#
828772 expect(refused.ok ? "" : refused.error).toContain("four.forge.test must resolve to 203.0.113.7");
829773 }
830774 }
831 expect(machines).toBe(stands);
775 expect(second.machines.length).toBe(stands);
832776 expect(getPinned(app.db, "four")).toMatchObject({ state: "running", version: V2, claimedAt: "" });
833777 // Reachable and unclaimed, the change goes through; its new machine has not answered yet, so
834778 // silence does not hold that one.
@@ -843,9 +787,9 @@ describe("claimed is what the deployed forge says, never what the seller says (#
843787 says = "waiting";
844788 expect((await deploy("five")).ok).toBe(true);
845789 says = "claimed";
846 const kept = machines;
790 const kept = second.machines.length;
847791 expect(await updatePinned(app, alice, "five", { version: V2 })).toMatchObject({ ok: false, error: CLAIMED_REFUSAL });
848 expect(machines).toBe(kept);
792 expect(second.machines.length).toBe(kept);
849793 expect(getPinned(app.db, "five")).toMatchObject({ version: V1 });
850794 expect(getPinned(app.db, "five")!.claimedAt).not.toBe("");
851795 expect(events().at(-1)).toEqual({ name: "five" });
@@ -869,7 +813,7 @@ describe("claimed is what the deployed forge says, never what the seller says (#
869813 expect(form).not.toContain("no access");
870814 } finally {
871815 Object.assign(net, kept);
872 cloudNet.fetch = cloud;
816 cloudNet.fetch = ownCloud;
873817 app.close();
874818 }
875819 });
test/pinned-forge.test.ts +14 −26
@@ -18,6 +18,7 @@ import { createToken } from "../src/core/tokens.ts";
1818 import { createUser, getUserByName } from "../src/core/users.ts";
1919 import { serve, type Servers } from "../src/http/server.ts";
2020 import { quietLogs } from "./helpers/globals.ts";
21 import { recordCloud, sequence } from "./helpers/recorded-cloud.ts";
2122 import { seedPlaces } from "./helpers/places-fixture.ts";
2223
2324 quietLogs();
@@ -31,10 +32,8 @@ describe("pinned forge", () => {
3132 let dataDir = "";
3233 let app: App;
3334 let servers: Servers;
34 const calls: { method: string; url: string; auth: string | null; body: any }[] = [];
35 let failNext = false;
36 /** The cloud refuses the next machine it is asked to make, after any delete went through. */
37 let failCreate = false;
35 const cloud = recordCloud({ firstMachine: 1001, address: "203.0.113.7" });
36 const { calls } = cloud;
3837
3938 const admin = () => getUserByName(app.db, "alice")!;
4039 // Each forge is served on a name of its own: one forge a name.
@@ -54,16 +53,7 @@ describe("pinned forge", () => {
5453 cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" } }), { status: 200 });
5554 const added = await addAccount(app, admin(), "digitalocean", "main", TOKEN);
5655 if (!added.ok) throw new Error(String(added.error));
57 net.fetch = async (url, init) => {
58 const u = new URL(url);
59 calls.push({ method: init?.method ?? "GET", url, auth: new Headers(init?.headers).get("authorization"), body: init?.body ? JSON.parse(String(init.body)) : undefined });
60 if (u.pathname === "/v2/account/keys" && init?.method === "POST") return new Response(JSON.stringify({ ssh_key: { id: 4242 } }), { status: 201 });
61 if (failNext) { failNext = false; return new Response("{}", { status: 500 }); }
62 if (failCreate && init?.method === "POST" && u.pathname === "/v2/droplets") { failCreate = false; return new Response("{}", { status: 500 }); }
63 if (u.pathname === "/v2/volumes") return new Response(JSON.stringify({ volume: { id: "vol-1" } }), { status: 201 });
64 if (init?.method === "DELETE") return new Response(null, { status: 204 });
65 return new Response(JSON.stringify({ droplet: { id: 1000 + calls.length } }), { status: 202 });
66 };
56 net.fetch = cloud.fetch;
6757 }, 30_000);
6858
6959 afterAll(async () => {
@@ -86,7 +76,7 @@ describe("pinned forge", () => {
8676 allowWrite(app, admin(), "digitalocean", "main", true);
8777 const r = await deployPinned(app, admin(), input());
8878 expect(r.ok).toBe(true);
89 expect(calls.map((c) => `${c.method} ${new URL(c.url).pathname}`)).toEqual(["POST /v2/volumes", "POST /v2/account/keys", "POST /v2/droplets", "DELETE /v2/account/keys/4242", "GET /v2/droplets/1003"]);
79 expect(cloud.seen()).toEqual(sequence.create("digitalocean", 1001));
outdated

sequence.create("digitalocean", cloud.machine) reads the machine id from the cloud itself, so it cannot fail on the wrong machine. Name the id (1001) as the Hetzner test does.

9080 expect(calls.every((c) => c.auth === `Bearer ${TOKEN}`)).toBe(true);
9181 const droplet = calls[2]!.body;
9282 expect(droplet.volumes).toEqual(["vol-1"]);
@@ -132,14 +122,12 @@ describe("pinned forge", () => {
132122 });
133123
134124 test("Update records who and when, replaces the droplet and keeps the volume", async () => {
135 calls.length = 0;
125 cloud.clear();
126 const before = getPinned(app.db, "acme")!.remote;
136127 const r = await updatePinned(app, admin(), "acme", { version: V2, config: { PUBLIC_NAME: "Acme Ltd" } });
137128 expect(r.ok).toBe(true);
138 expect(calls.map((c) => `${c.method} ${new URL(c.url).pathname}`)).toEqual([
139 // The machine's address is read first, to ask the forge there whether it was claimed.
140 expect.stringMatching(/^GET \/v2\/droplets\/\d+$/),
141 expect.stringMatching(/^DELETE \/v2\/droplets\/\d+$/), "GET /v2/volumes/vol-1", "POST /v2/account/keys", "POST /v2/droplets", "DELETE /v2/account/keys/4242",
142 ]);
129 // The machine's address is read first, to ask the forge there whether it was claimed.
130 expect(cloud.seen()).toEqual(sequence.replace("digitalocean", before));
143131 expect(calls[4]!.body.volumes).toEqual(["vol-1"]);
144132 expect(calls[4]!.body.user_data).toContain(`checkout --detach ${V2}`);
145133 const [latest] = changesOf(app.db, getPinned(app.db, "acme")!.id);
@@ -148,7 +136,7 @@ describe("pinned forge", () => {
148136 });
149137
150138 test("Update refuses an unsafe version, secret-looking config, and a no-op", async () => {
151 calls.length = 0;
139 cloud.clear();
152140 for (const version of ["main", "--upload-pack=x", `${V1}; rm -rf /`, "v1.2"])
153141 expect(await updatePinned(app, admin(), "acme", { version })).toMatchObject({ ok: false });
154142 expect(await updatePinned(app, admin(), "acme", { config: { API_TOKEN: "x" } })).toMatchObject({ ok: false });
@@ -169,17 +157,17 @@ describe("pinned forge", () => {
169157 // The first call of an Update reads the machine; the cloud refusing it is not "all is well".
170158 const before = getPinned(app.db, "acme")!;
171159 const changes = changesOf(app.db, before.id).length;
172 failNext = true;
173 calls.length = 0;
160 cloud.fail({ method: "GET" });
161 cloud.clear();
174162 const r = await updatePinned(app, admin(), "acme", { version: V2 });
175163 expect(r).toMatchObject({ ok: false, error: "The cloud refused: api.digitalocean.com answered 500" });
176 expect(calls.map((c) => c.method)).toEqual(["GET"]);
164 expect(cloud.seen()).toHaveLength(1);
177165 expect(getPinned(app.db, "acme")).toMatchObject({ version: V1, state: before.state, remote: before.remote });
178166 expect(changesOf(app.db, before.id)).toHaveLength(changes);
179167 });
180168
181169 test("a cloud failure after the old machine is deleted leaves the change recorded and the forge marked failed", async () => {
182 failCreate = true;
170 cloud.fail({ method: "POST", kind: "machine" });
183171 const r = await updatePinned(app, admin(), "acme", { version: V2 });
184172 expect(r).toMatchObject({ ok: false });
185173 expect(getPinned(app.db, "acme")).toMatchObject({ version: V2, state: "failed", remote: "" });
test/pinned-hetzner.test.ts +18 −33
@@ -15,6 +15,7 @@ import { verify } from "../src/cloud/providers.ts";
1515 import { getPinned } from "../src/core/pinned.ts";
1616 import { createUser, getUserByName } from "../src/core/users.ts";
1717 import { quietLogs } from "./helpers/globals.ts";
18 import { recordCloud, sequence } from "./helpers/recorded-cloud.ts";
1819 import { seedHetzner, seedPlaces } from "./helpers/places-fixture.ts";
1920
2021 quietLogs();
@@ -30,15 +31,14 @@ const PLACE = "hetzner:nbg1:cx23";
3031 describe("hetzner target", () => {
3132 let dataDir = "";
3233 let app: App;
33 const calls: { method: string; path: string; auth: string | null; body: any }[] = [];
34 let failServer = 0;
35 let serverSeq = 500;
34 const cloud = recordCloud();
35 const { calls } = cloud;
3636
3737 const admin = () => getUserByName(app.db, "alice")!;
3838 const input = (over: { name?: string; version?: string; place?: string } = {}) => ({
3939 name: "acme", host: `${over.name ?? "acme"}.forge.test`, target: "hetzner", account: "main", app: "alice/shop", source: SOURCE, version: V1, place: PLACE, config: { PUBLIC_NAME: "Acme" }, ...over,
4040 });
41 const seen = () => calls.map((c) => `${c.method} ${c.path}`);
41 const seen = cloud.seen;
4242
4343 beforeAll(async () => {
4444 dataDir = await mkdtemp(join(tmpdir(), "forge-hetzner-"));
@@ -52,23 +52,7 @@ describe("hetzner target", () => {
5252 allowWrite(app, admin(), "hetzner", "main", true);
5353 // The forge's name resolves nowhere here: nothing in this file asks a deployed forge.
5454 net.resolve = async () => [];
55 net.fetch = async (url, init) => {
56 const u = new URL(url);
57 expect(u.host).toBe("api.hetzner.cloud");
58 const method = init?.method ?? "GET";
59 calls.push({ method, path: u.pathname, auth: new Headers(init?.headers).get("authorization"), body: init?.body ? JSON.parse(String(init.body)) : undefined });
60 const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status });
61 if (u.pathname === "/v1/volumes") return json({ volume: { id: 77 } }, 201);
62 if (u.pathname === "/v1/volumes/77" && method === "GET") return json({ volume: { id: 77, server: null } });
63 if (u.pathname === "/v1/ssh_keys" && method === "POST") return json({ ssh_key: { id: 4242 } }, 201);
64 if (u.pathname === "/v1/servers" && method === "POST") {
65 if (failServer > 0) { failServer--; return json({}, 500); }
66 return json({ server: { id: ++serverSeq } }, 201);
67 }
68 if (method === "DELETE") return json({ action: {} });
69 if (u.pathname.startsWith("/v1/servers/")) return json({ server: { status: "running", public_net: { ipv4: { ip: "203.0.113.9" } } } });
70 return json({}, 404);
71 };
55 net.fetch = cloud.fetch;
7256 }, 30_000);
7357
7458 afterAll(async () => {
@@ -80,7 +64,7 @@ describe("hetzner target", () => {
8064 const r = await deployPinned(app, admin(), input());
8165 expect(r.ok).toBe(true);
8266 // The last call reads the new server's address, so the answer can name the DNS record.
83 expect(seen()).toEqual(["POST /v1/volumes", "POST /v1/ssh_keys", "POST /v1/servers", "DELETE /v1/ssh_keys/4242", "GET /v1/servers/501"]);
67 expect(seen()).toEqual(sequence.create("hetzner", 501));
8468 expect(calls.every((c) => c.auth === `Bearer ${TOKEN}`)).toBe(true);
8569 expect(JSON.stringify(calls.map((c) => c.body))).not.toContain(TOKEN);
8670 const [volume, server] = [calls[0]!.body, calls[2]!.body];
@@ -94,18 +78,19 @@ describe("hetzner target", () => {
9478
9579 test("the address is read back from the server", async () => {
9680 net.probe = async () => new Response("ok", { status: 200 });
81 cloud.clear();
9782 const r = await checkPinned(app, admin(), "acme");
9883 expect(r.ok && r.value.address).toBe("203.0.113.9");
99 expect(calls.at(-1)!.path).toBe("/v1/servers/501");
84 expect(seen()).toEqual(sequence.read("hetzner", 501));
10085 });
10186
10287 test("Update replaces the server and keeps the volume", async () => {
103 calls.length = 0;
88 cloud.clear();
10489 const r = await updatePinned(app, admin(), "acme", { version: V2 });
10590 expect(r.ok).toBe(true);
10691 // The address is read to ask the forge whether it was claimed; whether the recorded place may
10792 // be ordered is answered from the catalog, with no call; then the server is replaced.
108 expect(seen()).toEqual(["GET /v1/servers/501", "DELETE /v1/servers/501", "GET /v1/volumes/77", "POST /v1/ssh_keys", "POST /v1/servers", "DELETE /v1/ssh_keys/4242"]);
93 expect(seen()).toEqual(sequence.replace("hetzner", 501));
10994 const made = calls.find((c) => c.method === "POST" && c.path === "/v1/servers")!;
11095 expect(made.body).toMatchObject({ server_type: "cx23", location: "nbg1" });
11196 expect(made.body.volumes).toEqual([77]);
@@ -115,12 +100,12 @@ describe("hetzner target", () => {
115100
116101 test("a failure after the volume exists leaves it recorded, and a retry reuses it", async () => {
117102 app.db.run("DELETE FROM pinned_forge");
118 calls.length = 0;
119 failServer = 1;
103 cloud.clear();
104 cloud.fail({ method: "POST", kind: "machine" });
120105 const bad = await deployPinned(app, admin(), input({ name: "again" }));
121106 expect(bad.ok).toBe(false);
122107 expect(getPinned(app.db, "again")).toMatchObject({ state: "failed", volume: "77", remote: "" });
123 calls.length = 0;
108 cloud.clear();
124109 const good = await deployPinned(app, admin(), input({ name: "again" }));
125110 expect(good.ok).toBe(true);
126111 expect(seen()).not.toContain("POST /v1/volumes");
@@ -129,7 +114,7 @@ describe("hetzner target", () => {
129114
130115 test("a place sold out at the datacenter is refused, and nothing is called", async () => {
131116 app.db.run("DELETE FROM pinned_forge");
132 calls.length = 0;
117 cloud.clear();
133118 await seedHetzner(app.db, [1, 5]);
134119 const r = await deployPinned(app, admin(), input({ name: "none" }));
135120 expect(r).toMatchObject({ ok: false });
@@ -139,7 +124,7 @@ describe("hetzner target", () => {
139124 });
140125
141126 test("an ARM size is listed with its reason and is never ordered", async () => {
142 calls.length = 0;
127 cloud.clear();
143128 const r = await deployPinned(app, admin(), input({ name: "arm", place: "hetzner:nbg1:cax21" }));
144129 expect(r).toMatchObject({ ok: false });
145130 expect(String((r as any).error)).toContain("an ARM size; the forge runs on x86 machines only");
@@ -148,7 +133,7 @@ describe("hetzner target", () => {
148133
149134 test("with no place named and none orderable anywhere, the deploy says so and calls nothing", async () => {
150135 app.db.run("DELETE FROM pinned_forge");
151 calls.length = 0;
136 cloud.clear();
152137 await seedHetzner(app.db, []);
153138 const r = await deployPinned(app, admin(), input({ name: "nowhere", place: "" }));
154139 expect(r).toMatchObject({ ok: false });
@@ -159,7 +144,7 @@ describe("hetzner target", () => {
159144
160145 test("with no place named and none in the United States, the deploy falls back to the cheapest place anywhere", async () => {
161146 app.db.run("DELETE FROM pinned_forge");
162 calls.length = 0;
147 cloud.clear();
163148 const r = await deployPinned(app, admin(), input({ name: "europe", place: "" }));
164149 expect(r.ok).toBe(true);
165150 expect(calls.find((c) => c.method === "POST" && c.path === "/v1/servers")!.body).toMatchObject({ location: "nbg1" });
@@ -168,7 +153,7 @@ describe("hetzner target", () => {
168153 test("an Update with the recorded place sold out keeps the running server", async () => {
169154 const ok = await deployPinned(app, admin(), input({ name: "keep" }));
170155 expect(ok.ok).toBe(true);
171 calls.length = 0;
156 cloud.clear();
172157 await seedHetzner(app.db, []);
173158 const r = await updatePinned(app, admin(), "keep", { version: V2 });
174159 expect(r.ok).toBe(false);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs