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

A game box's token changes only when its new machine is asked for (#17532) #17718

opened this

Merged 19h 32m ago, live in production

sold/claim-order → main 0 commits 1 thread · 1 unresolved

  • Merged. sold/claim-order was merged into main as 4054eea.

Review

Sign in to review this change.
6 files changed +161 −29
src/actions/pinned.ts +12 −13
@@ -31,7 +31,7 @@ import { besideBox, boxNamed, createGameBox, rotateGameBoxToken, setGameBoxMachi
3131 import type { GameBoot } from "../games/boot.ts";
3232 import type { App } from "../app.ts";
3333 import { gatedFetch } from "../cloud/gate.ts";
34 import { bootFits, capped, CeilingRefusal, priced, refusalAt, rowCents } from "../cloud/ceiling.ts";
34 import { capped, CeilingRefusal, priced, refusalAt, rowCents } from "../cloud/ceiling.ts";
3535 import { driverOf, firewallCloud } from "../cloud/drivers.ts";
3636 import { ensureFirewall, NO_FIREWALL, removeFirewall } from "../cloud/firewall.ts";
3737 import { clearFirewall, firewallOf, setFirewall } from "../core/pinned_firewall.ts";
@@ -457,18 +457,16 @@ export type DeployInput = {
457457 };
458458
459459 /**
460 * The row a machine is made from: a game box's carries its boot (`games/boot.ts`) with a token made
461 * now, so each machine made for it (a create or a replace) has its own and ends the one before.
460 * The row as its new machine boots it, for `provision` and `replace` to ask when they make one: a game
461 * box's carries its boot (`games/boot.ts`) with a token made then, which ends the one before. Made any
462 * earlier, a refusal would cut off the box that runs. A row and a games store that disagree boot
463 * nothing, and are refused here, before anything is asked of the cloud.
462464 */
463 function bootRow(app: App, p: Pinned): Pinned & { game?: GameBoot } {
465 function bootOf(app: App, p: Pinned): () => Pinned & { game?: GameBoot } {
464466 const box = boxNamed(app.db, p.name);
465 // The row says what it boots; a row and a games store that disagree boot nothing.
466467 if ((box !== undefined) !== (p.boots === "game")) throw new Error(`${p.name} is ${box === undefined ? "a game box with no row in the games store" : "a game box's name, and its machine is not one"}`);
467 if (box === undefined) return p;
468 // Before the token: refused after it, the box that runs would be cut off.
469 bootFits(app, driverOf(p.target), p, net.bootLimit);
470 const token = rotateGameBoxToken(app.db, box.id);
471 return { ...p, game: { forgeUrl: (app.config.url ?? "").replace(/\/+$/, ""), token } };
468 if (box === undefined) return () => p;
469 return () => ({ ...p, game: { forgeUrl: (app.config.url ?? "").replace(/\/+$/, ""), token: rotateGameBoxToken(app.db, box.id) } });
472470 }
473471
474472 export async function deployPinned(app: App, actor: User | undefined, input: DeployInput): Promise<Result<Issued, string>> {
@@ -542,7 +540,8 @@ async function deployAs(app: App, who: Who, input: DeployInput): Promise<Result<
542540 const made = await create(
543541 app, who, p, "deploy",
544542 (f, token) =>
545 provision(capped(app, p.name, driverOf(p.target), net.bootLimit), f, token, bootRow(app, getPinned(app.db, p.name)!), {
543 provision(capped(app, p.name, driverOf(p.target), net.bootLimit), f, token, getPinned(app.db, p.name)!, {
544 boot: bootOf(app, getPinned(app.db, p.name)!),
546545 ...(old?.volume ? { have: old.volume } : {}),
547546 ...(restore === undefined ? {} : { from: restore }),
548547 project: projectOf(app, p),
@@ -600,7 +599,7 @@ async function changeNow(
600599 const after = getPinned(app.db, name)!;
601600 const done = await create(
602601 app, who.value, after, kind,
603 (f, token) => replace(capped(app, after.name, driverOf(after.target), net.bootLimit), f, token, bootRow(app, after), { project: projectOf(app, after), onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }), onUnfiled: unfiled(app, who.value, name) }),
602 (f, token) => replace(capped(app, after.name, driverOf(after.target), net.bootLimit), f, token, after, { boot: bootOf(app, after), project: projectOf(app, after), onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }), onUnfiled: unfiled(app, who.value, name) }),
604603 (m) => setRemote(app.db, name, { ...m, address: "", state: "running" }),
605604 true,
606605 );
@@ -677,7 +676,7 @@ async function claimNow(app: App, who: Who, name: string, input: { host?: string
677676 const after: Pinned = { ...getPinned(app.db, name)!, claimHash: claim.hash, claimExpires: claim.expires };
678677 const done = await create(
679678 app, who, after, "claim",
680 (f, token) => replace(capped(app, after.name, driverOf(after.target), net.bootLimit), f, token, bootRow(app, after), { project: projectOf(app, after), onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }), onUnfiled: unfiled(app, who, name) }),
679 (f, token) => replace(capped(app, after.name, driverOf(after.target), net.bootLimit), f, token, after, { boot: bootOf(app, after), project: projectOf(app, after), onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }), onUnfiled: unfiled(app, who, name) }),
681680 (m) => {
682681 setClaim(app.db, name, { hash: claim.hash, expires: claim.expires });
683682 setRemote(app.db, name, { ...m, address: "", state: "running" });
src/cloud/boot_size.ts +2 −2
@@ -16,8 +16,8 @@ const asBooted = (app: App, p: Booted): Booted =>
1616
1717 /** Why `p`'s boot config is refused: its size, the limit, and that nothing was touched; undefined when it fits or the cloud names no limit. */
1818 export function bootRefusal(app: App, d: Driver, p: Booted & { readonly volume?: string; readonly remote?: string }, limit: number | undefined = d.boot.limit): string | undefined {
19 if (limit === undefined) return undefined;
19 // Built also where no limit is known: a config that cannot be built is refused while the old machine runs.
2020 const bytes = Buffer.byteLength(d.boot.of(asBooted(app, p), p.volume || "1"), "utf8");
21 if (bytes <= limit) return undefined;
21 if (limit === undefined || bytes <= limit) return undefined;
2222 return `${p.name}'s boot config is ${bytes} bytes, and ${new URL(d.api).host} takes at most ${limit}. Nothing was made or deleted${p.remote ? `, and ${p.name} keeps running` : ""}.`;
2323 }
src/cloud/ceiling.ts +7 −2
@@ -239,7 +239,7 @@ export function refusalOf(s: Standing): string | undefined {
239239 }
240240
241241 /** Refuse a boot config over its cloud's limit (`bootRefusal`), in those words, before anything is made or deleted. */
242 export function bootFits(app: App, d: Driver, p: Parameters<typeof bootRefusal>[2], limit?: number): void {
242 function bootFits(app: App, d: Driver, p: Parameters<typeof bootRefusal>[2], limit?: number): void {
243243 const no = bootRefusal(app, d, p, limit);
244244 if (no !== undefined) throw new CeilingRefusal(no);
245245 }
@@ -248,8 +248,13 @@ export function bootFits(app: App, d: Driver, p: Parameters<typeof bootRefusal>[
248248 export function capped(app: App, name: string, d: Driver, limit?: number): Driver {
249249 return {
250250 ...d,
251 // The place and the price are the row's as recorded; the size is of what would boot.
251 // The cloud's own refusal first, in its words. The place and the price are the row's as recorded; the size is of what would boot.
252252 admit: (p, next = p) => {
253 try {
254 d.admit?.(p, next);
255 } catch (e) {
256 throw new CeilingRefusal(e instanceof Error ? e.message : String(e));
257 }
253258 admit(app, name);
254259 bootFits(app, d, next, limit);
255260 },
src/cloud/machine.ts +9 −8
@@ -307,11 +307,11 @@ const ID = /^[A-Za-z0-9-]{1,64}$/;
307307
308308 /**
309309 * Volume first, then the machine that mounts it. A volume a failed earlier try
310 * made (`have`) is reused; a new one is recorded through `onVolume` before the
310 * made (`have`) is reused; `boot` is as `machineOf` has it; a new one is recorded through `onVolume` before the

The boot clause is spliced into the volume sentence. Give it its own sentence, e.g. 'boot gives the row as the new machine boots it (see machineOf).'

311311 * machine is asked for. Returns the ids to keep.
312312 */
313313 export async function provision(
314 d: Driver, f: Fetch, token: string, p: Pinned, hooks: { have?: string; project?: string; from?: Restore; onVolume(id: string): void; onUnfiled?(why: string): void },
314 d: Driver, f: Fetch, token: string, p: Pinned, hooks: { have?: string; project?: string; from?: Restore; boot?(): Pinned; onVolume(id: string): void; onUnfiled?(why: string): void },
315315 ): Promise<{ remote: string; volume: string }> {
316316 const call = caller(d, f, token);
317317 d.admit?.(p);
@@ -325,7 +325,7 @@ export async function provision(
325325 if (!VOLUME.test(volume)) throw new Error(`${new URL(d.api).host} made no volume`);
326326 hooks.onVolume(volume);
327327 }
328 const remote = await machineOf(d, call, p, volume, hooks.from?.what === "machine" ? hooks.from.id : undefined);
328 const remote = await machineOf(d, call, p, volume, hooks.boot, hooks.from?.what === "machine" ? hooks.from.id : undefined);
329329 await file(d, call, project, remote, volume, hooks.onUnfiled);
330330 return { remote, volume };
331331 }
@@ -342,11 +342,12 @@ const found = async (ask: Promise<string>): Promise<string> => {
342342 /**
343343 * One forge, one machine: the machine already made for it is adopted, and one is created only when
344344 * the provider has none. An answer with no usable id is an error, and the machine it made is found
345 * by name on the next try.
345 * by name on the next try. `boot` gives the row as the new machine boots it, and is asked only when
346 * one is really made: a token made there is never made for a machine that runs already.
346347 */
347 async function machineOf(d: Driver, call: Call, p: Pinned, volume: string, image?: string): Promise<string> {
348 async function machineOf(d: Driver, call: Call, p: Pinned, volume: string, boot?: () => Pinned, image?: string): Promise<string> {
348349 const have = await found(d.findMachine(call, p));
349 const remote = have !== "" ? have : await d.createMachine(call, p, volume, image);
350 const remote = have !== "" ? have : await d.createMachine(call, boot?.() ?? p, volume, image);
350351 if (!ID.test(remote)) throw new Error(`${new URL(d.api).host} made no machine the forge can name`);
351352 return remote;
352353 }
@@ -388,7 +389,7 @@ export async function fileIn(d: Driver, f: Fetch, token: string, p: Pinned, name
388389 * does not delete twice.
389390 */
390391 export async function replace(
391 d: Driver, f: Fetch, token: string, p: Pinned, hooks: { project?: string; onDeleted(): void; onUnfiled?(why: string): void },
392 d: Driver, f: Fetch, token: string, p: Pinned, hooks: { project?: string; boot?(): Pinned; onDeleted(): void; onUnfiled?(why: string): void },
392393 ): Promise<{ remote: string }> {
393394 if (p.volume === "") throw new Error("this forge has no volume to keep");
394395 if (p.remote !== "" && !ID.test(p.remote)) throw new Error("this forge has no machine to replace");
@@ -404,7 +405,7 @@ export async function replace(
404405 hooks.onDeleted();
405406 await untilFree(d, call, p.volume);
406407 }
407 const remote = await machineOf(d, call, p, p.volume);
408 const remote = await machineOf(d, call, p, p.volume, hooks.boot);
408409 await file(d, call, project, remote, p.volume, hooks.onUnfiled);
409410 return { remote };
410411 }
test/claim-order.test.ts added +128
@@ -0,0 +1,128 @@
1 /**
2 * A game box's token changes only when a new machine is really asked for (#17532). Whatever refuses a new
3 * claim link, an Update or a Rollback before that leaves the running box its token, and a machine whose
4 * create's answer was lost keeps the one it booted with when the next try adopts it. A recorded cloud.
5 */
6 import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts";
12 import { claimPinned, deployPinned, net, rollbackPinned, updatePinned } from "../src/actions/pinned.ts";
13 import { capped } from "../src/cloud/ceiling.ts";
14 import { ovh } from "../src/cloud/ovh.ts";
15 import { getPinned } from "../src/core/pinned.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { boxByToken } from "../src/games/store.ts";
18 import { setBaseDomain } from "../src/settings/pinned_domain.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20 import { seedPlaces } from "./helpers/places-fixture.ts";
21 import { recordCloud } from "./helpers/recorded-cloud.ts";
22
23 quietLogs();
24
25 let dir = "";
26 let app: App;
27 let admin: User;
28 const cloud = recordCloud();
29 const saved = { cloud: cloudNet.fetch, fetch: net.fetch, resolve: net.resolve };
30 const PLACE = "digitalocean:nyc3:s-1vcpu-2gb";
31 /** The token in the newest machine's boot config. */
32 const token = (): string => /fgb_[A-Za-z0-9_-]{43}/.exec(String(cloud.holds.machines.at(-1)!.body.user_data))![0];
33 const machines = (): string => JSON.stringify(cloud.holds.machines.map((m) => m.id));
34 const deletes = (): number => cloud.calls.filter((c) => c.method === "DELETE" && c.kind === "machine").length;
35 const claim = () => claimPinned(app, admin, "mc");
36 const update = (c: string) => updatePinned(app, admin, "mc", { version: c.repeat(40) });
37
38 beforeAll(async () => {
39 dir = await mkdtemp(join(tmpdir(), "forge-claim-order-"));
40 app = createApp({ dataDir: dir, port: 0, url: "https://forge.example" });
41 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
42 if (!made.ok) throw new Error(made.error);
43 admin = made.value;
44 await seedPlaces(app.db);
45 cloudNet.fetch = async () => Response.json({ account: { email: "[email protected]", status: "active" } });
46 const added = await addAccount(app, admin, "digitalocean", "main", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5");
47 if (!added.ok) throw new Error(String(added.error));
48 allowWrite(app, admin, "digitalocean", "main", true);
49 setBaseDomain(app.db, "forges.example.net", admin.id);
50 net.fetch = cloud.fetch;
51 net.resolve = async () => [];
52 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);
54 const up = await update("b");
55 if (!up.ok) throw new Error(up.error);
56 }, 30_000);
57 afterEach(() => {
58 cloud.mend();
59 net.bootLimit = undefined;
60 app.db.run("UPDATE pinned_size SET size = 's-1vcpu-2gb'");
61 });
62 afterAll(async () => {
63 cloudNet.fetch = saved.cloud;
64 net.fetch = saved.fetch;
65 net.resolve = saved.resolve;
66 app.close();
67 await rm(dir, { recursive: true, force: true });
68 });
69
70 /** The catalog's body with the box's size no longer sold. */
71 const closePlace = (): (() => void) => {
72 const was = app.db.query<{ body: string }, []>("SELECT body FROM place_read WHERE provider = 'digitalocean'").get()!.body;
73 const next = was.replace(/("slug":"s-1vcpu-2gb"[^{}]*?"available":)true/, "$1false");
74 expect(next).not.toBe(was);
75 app.db.run("UPDATE place_read SET body = ?1 WHERE provider = 'digitalocean'", [next]);
76 return () => void app.db.run("UPDATE place_read SET body = ?1 WHERE provider = 'digitalocean'", [was]);
77 };
78
79 const REFUSALS: readonly (readonly [string, () => void | (() => void), RegExp])[] = [
80 ["a boot config over the limit", () => void (net.bootLimit = 10), /takes at most 10\./],
81 ["a place with no price", () => void app.db.run("UPDATE pinned_size SET size = 's-none'"), /has no price for s-none/],
82 ["a place that is closed", closePlace, /cannot be ordered now/],
83 ["a cloud that refuses the delete", () => cloud.fail({ method: "DELETE", kind: "machine", status: 500 }), /The cloud refused/],
84 ["a cloud that does not answer", () => cloud.fail({ method: "DELETE", kind: "machine", status: "throw" }), /The cloud refused/],
85 ];
86
87 test.each(REFUSALS)("%s: a new claim link, an Update and a Rollback leave the running box its token and its machine", async (_why, refuse, words) => {
88 const old = token();
89 const before = machines();
90 for (const go of [claim, () => update("c"), () => rollbackPinned(app, admin, "mc")]) {
91 const undo = refuse();
92 const r = await go();
93 if (typeof undo === "function") undo();
94 expect(r.ok ? "" : r.error).toMatch(words);
95 expect(boxByToken(app.db, old)?.name).toBe("mc");
96 expect(machines()).toBe(before);
97 expect(getPinned(app.db, "mc")!.remote).toBe(String(cloud.holds.machines.at(-1)!.id));
98 }
99 });
100
101 test("a new claim link that is let in: the new machine's token is the box's, and the old one is nobody's", async () => {
102 const old = token();
103 const n = deletes();
104 const r = await claim();
105 expect(r.ok ? "" : r.error).toBe("");
106 expect(deletes()).toBe(n + 1);
107 expect(token()).not.toBe(old);
108 expect(boxByToken(app.db, token())?.name).toBe("mc");
109 expect(boxByToken(app.db, old)).toBeUndefined();
110 });
111
112 test("a machine whose create's answer was lost is adopted by the next try with the token it booted with", async () => {
113 cloud.fail({ method: "POST", kind: "machine", lost: true });
114 expect((await claim()).ok).toBe(false);
115 const its = token();
116 expect(boxByToken(app.db, its)?.name).toBe("mc");
117 const again = await claim();
118 expect(again.ok ? "" : again.error).toBe("");
119 expect(cloud.holds.machines).toHaveLength(1);
120 expect(token()).toBe(its);
121 expect(boxByToken(app.db, its)?.name).toBe("mc");
122 });
123
124 test("the ceiling keeps the cloud's own refusal: OVHcloud US has two regions", () => {
125 const p = { ...getPinned(app.db, "mc")!, target: "ovh", boots: "forge" as const };
126 expect(() => capped(app, "none", ovh).admit!({ ...p, datacenter: "nyc3" })).toThrow("OVHcloud US has no region nyc3");
127 expect(() => capped(app, "none", ovh).admit!({ ...p, datacenter: "US-EAST-VA-1" })).not.toThrow();
128 });
test/pinned-ceiling.test.ts +3 −4
@@ -351,7 +351,7 @@ describe("cloud account ceiling", () => {
351351 if (/^import\b[^\n]*$/.test(text.slice(text.lastIndexOf("\n", m.index) + 1, m.index))) continue;
352352 uses++;
353353 const before = text.slice(Math.max(0, m.index - 80), m.index);
354 if (!/\bcapped\(app, [\w.]+, $/.test(before) && !/\b(?:read|retire|strays|ensureFirewall|removeFirewall|snapshotKind|takeSnapshot|readSnapshot|dropSnapshot|viewOf|bootFits|bootRefusal)\((?:app, )?$/.test(before)) bare.push(`${file.slice(src.length + 1)}: …${before.slice(-40)}driverOf(`);
354 if (!/\bcapped\(app, [\w.]+, $/.test(before) && !/\b(?:read|retire|strays|ensureFirewall|removeFirewall|snapshotKind|takeSnapshot|readSnapshot|dropSnapshot|viewOf|bootRefusal)\((?:app, )?$/.test(before)) bare.push(`${file.slice(src.length + 1)}: …${before.slice(-40)}driverOf(`);
355355 }
356356 }
357357 expect(bare).toEqual([]);
@@ -363,9 +363,8 @@ describe("cloud account ceiling", () => {
363363 // finds, makes or deletes that one firewall, never a machine or a volume; and the read-only
364364 // view of a machine (#17151), handed to `viewOf`. A bare driverOf still fails the pattern
365365 // above; only those call names are let through.
366 // And the size of a boot config, measured and sent nowhere: before a game box's token is made, and in
367 // the plan.
368 expect(uses).toBe(18);
366 // And the size of a boot config, measured in the plan and sent nowhere.
367 expect(uses).toBe(17);
369368 });
370369 });
371370

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

Keyboard shortcuts

Docs