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

A pinned forge is deployed at a place from the catalog, not at a hard-coded datacenter and size #16333

Merged opened this

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

Merged

sold/deploy-at-a-place → main 0 commits

  • Merged. sold/deploy-at-a-place was merged into main as a553468.

Review

Sign in to review this change.
25 files changed +772 −278
docs/features/deploy-to-hetzner.md +4 −5
@@ -14,16 +14,15 @@ A pinned forge can run in your own Hetzner Cloud project the way it runs on Digi
1414
1515 ## What it makes
1616
17 - Location **Nuremberg** (`nbg1`), an EU location: the US ones cost about three times as much for a tenth of the traffic.
18 - The server **type is chosen from Hetzner's own lists at order time**: the cheapest cost-optimized (CX), x86 type with at least 2 GiB that Hetzner says can be ordered in Nuremberg now. No type is named in the code.
17 - The **place is the deploy's**: `hetzner:<location>:<type>` from the Places catalog (`pinned-forge.md`, "Where it is made"), named by the `place` field or, left out, the catalog's default for the small plan, which is the cheapest orderable place in the United States. A Nuremberg place, such as `hetzner:nbg1:cx23`, costs about a third of a US one for ten times the traffic, and is named on purpose. The server and its volume are made in that location; no location or type is named in the code. ARM types are never offered: the boot is x86.
1918 - A 10 GiB volume, attached and automounted at `/mnt/HC_Volume_<id>`. Update deletes the server and makes a new one on the same volume; the data is not touched.
2019 - The server is made with a throwaway SSH key (made and deleted per create), so Hetzner never emails a root password; the machine accepts no password, no root login and nothing on port 22, and opens only 80 and 443. See "What the booted machine is" in `pinned-forge.md`.
2120 - The address is read back from the server, for the DNS record; the forge itself is served only on its name over HTTPS, by Caddy from Ubuntu's own packages, as on DigitalOcean.
2221 - A replaced server (Update, Roll back, a new claim link) has a new address: change the record to the one Check names.
2322
24 ## When nothing is in stock
23 ## When the place is not orderable
2524
26 When no CX type with 2 GiB can be ordered in Nuremberg, the deploy stops **before it makes anything** and says so ("Hetzner has no CX server with 2 GiB or more that can be ordered in nbg1 right now; nothing was made. Try again later."). Nothing is billed; try again later.
25 A place the catalog says is sold out, unknown, or another provider's stops the deploy **before it makes anything** and says so ("hetzner:nbg1:cx23 cannot be ordered now: sold out at this datacenter right now"). A replace of a running forge whose recorded place has since sold out is refused the same way, with the running server untouched. Nothing is billed; pick another place or try again later.
2726
2827 ## The audit
2928
@@ -31,4 +30,4 @@ Cloud accounts → Audit lists a Hetzner volume attached to no server, and a pow
3130
3231 ## Not checked here
3332
34 The `/server_types` price shape and `/datacenters` `server_types.available` were written from the Hetzner API reference as recalled; this sandbox cannot reach docs.hetzner.cloud, so a first real deploy is the check. A shape that differs stops with the "nothing can be ordered" message rather than ordering a guess.
33 The `/server_types` price shape and `/datacenters` `server_types.available` that the Places catalog reads were written from the Hetzner API reference as recalled; this sandbox cannot reach docs.hetzner.cloud, so a first real deploy is the check. A shape that differs leaves the place unlisted, and a deploy to it is refused rather than ordering a guess.
docs/features/pinned-forge.md +9 −3
@@ -59,6 +59,12 @@ A pinned forge runs on a public address, so its machine is set up for that (`src
5959
6060 On a new machine (reach it through the provider's console, since SSH is closed): `ufw status verbose` lists only 80 and 443; `systemctl show forge -p User` says `forge` and `ps -o user= -C bun` too; `sshd -T | grep -Ei 'passwordauthentication|permitrootlogin'` says `no`; `apt-config dump | grep Unattended-Upgrade::` and `systemctl status apt-daily-upgrade.timer`; `journalctl -t forge-boot` says `sandbox ready`; `systemd-run --wait --pty -p User=forge -p NoNewPrivileges=yes -p ProtectSystem=strict -p PrivateTmp=yes bwrap --unshare-user --ro-bind / / -- /bin/true` exits 0 (the one that proves `NoNewPrivileges` and bubblewrap agree); the same with every directive of the unit and a sandbox that mounts its own /proc, `systemd-run --wait --pty -p User=forge -p NoNewPrivileges=yes -p ProtectSystem=strict -p ProtectHome=yes -p PrivateTmp=yes -p ProtectKernelModules=yes -p ProtectClock=yes -p RestrictSUIDSGID=yes bwrap --unshare-user --unshare-pid --ro-bind / / --proc /proc --dev /dev -- /bin/true`, exits 0 (the unit hides no part of /proc, which is why it has no `ProtectKernelLogs`); `stat -c %A /usr/bin/bwrap` is not setuid; `journalctl -u forge` shows no read-only-file-system error from the checkout; `systemctl is-active caddy` says `active` and `ss -ltnp` shows Caddy on 80 and 443 and Bun on `127.0.0.1` alone; `cat /etc/caddy/Caddyfile` is the forge's own and `curl -s http://<address>/` never showed Caddy's welcome page (the claim that dpkg kept the file); `stat -c %U <mount>/caddy` says `caddy` after a forge restart; once the DNS record exists, `journalctl -u caddy` shows the certificate obtained, and after an Update it shows none requested. HTTP/3 is not offered a way in (ufw opens 443/tcp only; browsers fall back). The forge's start walks the whole volume to set ownership, which is slow on a large one. No email from the provider with a root password arrives.
6161
62 ## Where it is made: the place (#16205)
63
64 A deploy is made at a place from the Places catalog (`GET /api/v1/places`): `provider:datacenter:size`, such as `digitalocean:sfo2:s-1vcpu-2gb`. Every door takes it as `place` (the API body and MCP tool field, the Place select on `/deploy-to`, an optional last word of the terminal's `d` line). Left out, it is the catalog's default for the small plan among the chosen account's provider (the cheapest orderable place in the United States, or the one pinned on Places). The place must exist in the catalog, be orderable and be on the account's provider; otherwise the deploy is refused in a sentence, before any call to a provider. ARM sizes are listed with their reason and are never offered: the machine boots x86 only.
65
66 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`).
67
6268 ## After the claim: what the host can still do (#16204)
6369
6470 Nobody marks a forge claimed by hand: the deployed forge says so. Check, and every Update, Roll back and request for a new claim link, asks it first; when one hears `claimed` (The claim, above), the selling forge records it once (`pinned_forge.claimed_at`, event `pinned.claimed`). From then it refuses `update`, `rollback` and a new claim link for that forge, each with the same sentence (`CLAIMED_REFUSAL`): updates are the buyer's to take, and no machine of theirs is replaced from here. A forge that cannot be asked is never recorded as claimed, and is not taken as unclaimed either: once its current machine has answered about its claim (`pinned_forge.reached`), silence from it (a broken DNS record, a forge that is down) refuses Update, Roll back and a new claim link, with a sentence saying the forge could not be reached to confirm nobody claimed it and to run Check until it answers. A forge whose current machine has never answered (still booting, DNS not pointed yet, a first boot that failed) may still be replaced, or it could never be recovered. The question starts with a read of the machine at its cloud: when the cloud refuses that read the change is refused with the cloud's answer, before anything is recorded; a machine that is gone (404) has nobody to ask and is replaced. `/pinned` (once, when any forge is claimed) and `/deploy-to` say what the host still can while the machine is in the host's cloud account (`HOST_CAN` in `src/core/pinned.ts`): open its console, boot it into rescue, snapshot its disk, read its boot data. It never says "no access". The path that gives the host none is the buyer's own cloud account: deploy there (the account picker on `/deploy-to`; choosing it at purchase is #16203).
@@ -69,8 +75,8 @@ Prices are list prices as last read (USD a month); the owner's own bill is the t
6975
7076 | Target | Status | What runs | Cost | Refused / caveat |
7177 |---|---|---|---|---|
72 | DigitalOcean | **deploys today** | One droplet (`s-1vcpu-2gb`, Ubuntu 24.04) with a 10 GiB block volume as `FORGE_APP_DATA`. An Update deletes the droplet and starts a new one on the same volume, so data is untouched. | ~$12 + ~$1.20 | A token cannot be narrowed below "create droplets and volumes". |
73 | Hetzner Cloud | **deploys today** | One server (Ubuntu 24.04) with a 10 GiB volume as `FORGE_APP_DATA`, in Nuremberg; the type is the cheapest in-stock CX with 2 GiB, read from the API. See `deploy-to-hetzner.md`. | the API's list price + the volume | The token must be read-write; Hetzner offers nothing narrower. |
78 | DigitalOcean | **deploys today** | One droplet (Ubuntu 24.04) at the forge's place, with a 10 GiB block volume in the same datacenter as `FORGE_APP_DATA`. An Update deletes the droplet and starts a new one on the same volume, so data is untouched. | ~$12 + ~$1.20 | A token cannot be narrowed below "create droplets and volumes". |
79 | Hetzner Cloud | **deploys today** | One server (Ubuntu 24.04) with a 10 GiB volume as `FORGE_APP_DATA`, at the forge's place. See `deploy-to-hetzner.md`. | the API's list price + the volume | The token must be read-write; Hetzner offers nothing narrower. |
7480 | AWS | not written | EC2 `t4g.small` + EBS gp3, same boot script; SigV4 already exists for reads. | ~$12 + ~$0.80 + public IPv4 ~$3.65 | Wants a role scoped to a tag rather than a long-lived key. |
7581 | Azure | not written | B1ms VM + managed disk through a service principal on one resource group. | ~$15 + ~$1 + public IP ~$3.65 | Needs a resource group, network and public IP first: three calls more. |
7682 | Cloudflare | **refused** | Workers/Durable Objects keep state, but not as files a Bun process opens. Containers run, with a disk wiped on sleep or replace. | Workers Paid from $5 | No volume that survives; the forge refuses rather than lose repositories quietly. |
@@ -88,7 +94,7 @@ Open-source "Deploy to" buttons (Heroku's `app.json`, Render's `render.yaml`, Di
8894
8995 ## One at a time
9096
91 Every create (a deploy, and the machine an Update, Roll back or new claim link makes) is held to its cloud account's ceiling (`src/cloud/ceiling.ts`, set on `/settings/cloud`). A forge is priced from the one catalog of places (`src/cloud/places.ts`, `GET /api/v1/places`): what the provider's own API last said its size costs where the drivers order it, with its volume and address, converted at the day's rate and rounded up. The forge reads the catalog again before a create when it is stale or was never read; a size it still has no price for is refused, never counted as free. Creates on one account run one after the other from the ceiling check until the machine is recorded, so two asked together cannot both fit where one does. Changes to one forge run one after the other too: two new claim links asked together make two replacements in turn, never two machines at once, and the second link is the one that works.
97 Every create (a deploy, and the machine an Update, Roll back or new claim link makes) is held to its cloud account's ceiling (`src/cloud/ceiling.ts`, set on `/settings/cloud`). A forge is priced from the one catalog of places (`src/cloud/places.ts`, `GET /api/v1/places`): what the provider's own API last said its size costs at the place its row records, with its volume and address, converted at the day's rate and rounded up. The forge reads the catalog again before a create when it is stale or was never read; a size it still has no price for is refused, never counted as free. Creates on one account run one after the other from the ceiling check until the machine is recorded, so two asked together cannot both fit where one does. Changes to one forge run one after the other too: two new claim links asked together make two replacements in turn, never two machines at once, and the second link is the one that works.
9298
9399 ## Failing half-way
94100
src/actions/pinned.ts +57 −5
@@ -30,19 +30,22 @@ import { gatedFetch } from "../cloud/gate.ts";
3030 import { capped, CeilingRefusal } from "../cloud/ceiling.ts";
3131 import { driverOf } from "../cloud/drivers.ts";
3232 import { orderable, provision, read, replace } from "../cloud/machine.ts";
33 import { chooseDefault, meets, type Place } from "../cloud/places.ts";
34 import { MAX_ID, keptPlaces, pinOf } from "../cloud/places_read.ts";
35 import { keptRate } from "../cloud/rates.ts";
3336 import type { Fetch } from "../cloud/providers.ts";
3437 import { target as targetOf } from "../cloud/targets.ts";
3538 import { getCloudAccount, secretNameOf } from "../core/cloud_account.ts";
3639 import { FIRST_ADMIN_SEED_TTL_MS, firstAdminLink, newFirstAdminCode, type SeedState } from "../core/first_admin.ts";
3740 import {
38 APP, CLAIMED_REFUSAL, NAME, changesOf, checkConfig, dnsRecordOf, getPinned, insertPinned, listPinned, previousOf,
41 APP, CLAIMED_REFUSAL, NAME, changesOf, checkConfig, dnsRecordOf, getPinned, insertPinned, listPinned, placeIdOf, previousOf,
3942 dropPinned, markClaimed, markReached, recordChange, setClaim, setHost, setRemote, urlOf, validHost, validSource, validVersion, unconfirmedRefusal, type Change, type Pinned,
4043 } from "../core/pinned.ts";
4144 import { resolveSecrets } from "../core/secret_store.ts";
4245 import type { User } from "../core/users.ts";
4346 import { err, ok, type Result } from "../kernel/result.ts";
4447 import { boundedSignal } from "../kernel/fetch_timeout.ts";
45 import { refreshIfDue } from "./places_refresh.ts";
48 import { isStale, refreshIfDue } from "./places_refresh.ts";
4649 import { oneAtATime } from "../spawn/own_code.ts";
4750
4851 /** Swapped in tests; the real forge always uses `fetch`, and asks DNS for a name's A records. */
@@ -81,6 +84,40 @@ export interface IssuedClaim {
8184
8285 export type Issued = PinnedView & { readonly claim: IssuedClaim };
8386
87 const PLACE_HELP = "Places are listed at Places (GET /api/v1/places); a place is provider:datacenter:size.";
88
89 /**
90 * The place a deploy is made at, from the catalog the forge last read (no call to a provider): the
91 * one asked for, which must exist, be orderable and be on `provider`; or, when none is asked for,
92 * the catalog's default for the small plan among that provider's places.
93 */
94 function pickPlace(app: App, provider: string, asked: string): Result<Place, string> {
95 const all = keptPlaces(app.db, keptRate(app.db, "EUR"));
96 if (asked === "") {
97 const c = chooseDefault(all, "small", new Set([provider]), pinOf(app.db, "small"));
98 if (c.place) return ok(c.place);
99 return err(all.length === 0 ? "The forge has not read the places list yet, so it cannot choose where to deploy; try again in a few minutes." : `${c.reason} ${PLACE_HELP}`);
100 }
101 const place = asked.length > MAX_ID ? undefined : all.find((x) => x.id === asked);
102 if (!place) return err(`There is no place ${asked.slice(0, 80)} in the catalog. ${PLACE_HELP}`);
103 if (place.provider !== provider) return err(`${place.id} is on ${place.provider}, and this deploy is to ${provider}: name one of ${provider}'s places.`);
104 if (!place.orderable) return err(`${place.id} cannot be ordered now: ${place.why}. Pick another place, or leave it out for the default.`);
105 return ok(place);
106 }
107
108 const MAX_OFFERED = 60;
109
110 /**
111 * The places a deploy form offers for `providers`: orderable, meeting the small plan, cheapest
112 * first, at most `MAX_OFFERED`.
113 */
114 export function deployPlaces(app: App, providers: readonly string[]): Place[] {
115 return keptPlaces(app.db, keptRate(app.db, "EUR"))
116 .filter((p) => p.orderable && meets(p, "small") && providers.includes(p.provider))
117 .sort((a, b) => a.costCents - b.costCents || a.id.localeCompare(b.id))
118 .slice(0, MAX_OFFERED);
119 }
120
84121 const HOST_WORDS = "A hostname is a full DNS name you control, such as forge.example.com: lowercase letters, digits, dashes and dots.";
85122 const NAMELESS = "This forge was deployed before forges had names: issue a claim for it with a hostname first.";
86123
@@ -168,7 +205,7 @@ async function readAddress(app: App, who: User, name: string): Promise<Result<st
168205 export async function deployPinned(
169206 app: App,
170207 actor: User | undefined,
171 input: { name: string; host: string; target: string; account: string; app: string; source: string; version: string; config?: unknown },
208 input: { name: string; host: string; target: string; account: string; app: string; source: string; version: string; place?: string | undefined; config?: unknown },
172209 ): Promise<Result<Issued, string>> {
173210 const who = admin(actor);
174211 if (!who.ok) return who;
@@ -188,9 +225,24 @@ export async function deployPinned(
188225 // its volume (if one was made) is kept for the retry, and the new deploy is recorded afresh.
189226 const old = getPinned(app.db, input.name);
190227 if (old && !(old.state === "failed" && old.remote === "" && old.target === t.id)) return err("A pinned forge has that name already.");
228 // Where it is made: the place asked for, else the catalog's default. A volume the earlier try made
229 // lives in one datacenter, so the retry stays there.
230 let asked = (input.place ?? "").trim();
231 if (old?.volume) {
232 if (asked !== "" && !asked.startsWith(`${t.id}:${old.datacenter}:`)) return err(`The volume of the earlier try is in ${old.datacenter}: deploy there, or leave the place out.`);
233 if (asked === "") asked = placeIdOf(old);
234 }
235 let at = pickPlace(app, t.id, asked);
236 // A catalog never read or gone stale is read again once before this is refused.
237 if (!at.ok && isStale(app)) {
238 await refreshIfDue(app, who.value);
239 at = pickPlace(app, t.id, asked);
240 }
241 if (!at.ok) return at;
191242 if (old) dropPinned(app.db, old.name);
192243 const claim = newClaim();
193 const p = insertPinned(app.db, { ...input, target: t.id, config: config.value, host: host.value, claimHash: claim.hash, claimExpires: claim.expires }, who.value.id);
244 const { place: _asked, ...rest } = input;
245 const p = insertPinned(app.db, { ...rest, target: t.id, config: config.value, host: host.value, claimHash: claim.hash, claimExpires: claim.expires, datacenter: at.value.datacenter, size: at.value.size }, who.value.id);
194246 app.bus.append({ kind: "pinned.deployed", actorId: who.value.id, payload: { name: p.name, target: p.target, version: p.version } });
195247 if (old?.volume) setRemote(app.db, p.name, { volume: old.volume });
196248 const made = await create(
@@ -239,7 +291,7 @@ async function changeNow(
239291 if (!ours.ok) return ours;
240292 // Asked of the cloud before the pin moves: what cannot be ordered, or would pass the account's
241293 // ceiling, is refused while the row and the running machine still agree, and nothing is recorded.
242 const fits = await withCloud(app, who.value, before, kind, (f, token) => orderable(capped(app, before.name, driverOf(before.target)), f, token));
294 const fits = await withCloud(app, who.value, before, kind, () => orderable(capped(app, before.name, driverOf(before.target)), before));
243295 if (!fits.ok) return fits;
244296 if (!same) {
245297 const c = recordChange(app.db, before, kind, to.value, who.value.id);
src/cloud/ceiling.ts +49 −70
@@ -2,8 +2,8 @@
22 * The spend ceiling of a cloud account: what the forge reckons the account costs a month from the
33 * forges it made on it and has not retired, and the refusal to make one more thing that would take
44 * it over (cloud providers send alerts, not caps, so the forge is the cap). Whole US dollars for
5 * the ceiling, whole US cents for money. The check runs in `capped`, the driver's own `plan` step:
6 * after what to order is read, before anything is made.
5 * the ceiling, whole US cents for money. The check runs in `capped`, the driver's own `admit` step:
6 * before anything is made or deleted.
77 *
88 * There is one source of prices, the Places catalog (#16203, `places.ts`, `places_read.ts`): what
99 * each provider's own API last said a place costs, a place being a datacenter and a machine size
@@ -18,9 +18,7 @@
1818 import type { Database } from "bun:sqlite";
1919 import type { App } from "../app.ts";
2020 import { getCloudAccount } from "../core/cloud_account.ts";
21 import { getPinned, listPinned, type Pinned } from "../core/pinned.ts";
22 import { REGION, SIZE as DROPLET_SIZE } from "./droplet.ts";
23 import { LOCATION } from "./hetzner.ts";
21 import { getPinned, listPinned, placeIdOf, type Pinned } from "../core/pinned.ts";
2422 import type { Driver } from "./machine.ts";
2523 import { keptPlaces } from "./places_read.ts";
2624 import { dollars, toUsd } from "./prices.ts";
@@ -34,73 +32,66 @@ export const CEILING_PAGE = "/settings/cloud";
3432 /** A refusal in words meant to be shown as they are; withCloud passes it on whole. */
3533 export class CeilingRefusal extends Error {}
3634
37 /** The datacenter each driver orders in: with a size, the place a forge is. */
38 const WHERE: Readonly<Record<string, string>> = { digitalocean: REGION, hetzner: LOCATION };
39
40 /** The size each driver orders when it decides nothing at plan time. */
41 const FIXED_SIZE: Readonly<Record<string, string>> = { digitalocean: DROPLET_SIZE };
42
43 /** The size a machine was recorded with at creation; none for a machine made before sizes were kept. */
44 function recordedSize(db: Database, pinnedId: string): string | undefined {
45 return db.query<{ size: string }, [string]>("SELECT size FROM pinned_size WHERE pinned_id = ?1").get(pinnedId)?.size;
46 }
47
48 function noteSize(db: Database, pinnedId: string, size: string): void {
49 db.query("INSERT INTO pinned_size (pinned_id, size) VALUES (?1, ?2) ON CONFLICT(pinned_id) DO UPDATE SET size = excluded.size").run(pinnedId, size);
50 }
51
5235 /**
53 * The catalog as the ceiling reads it, taken once for a reckoning: what a forge of a size costs a
54 * month on a cloud, in US cents rounded up (its machine, its volume and its address, as the
55 * catalog's place has them), and the dearest the cloud has where the driver orders. Undefined for
56 * a place the catalog does not hold, or holds with no price or no rate.
36 * The catalog as the ceiling reads it, taken once for a reckoning: what a place costs a month on
37 * a cloud, in US cents rounded up (its machine, its volume and its address, as the catalog's
38 * place has them), and the dearest the cloud has in a datacenter. Undefined for a place the
39 * catalog does not hold, or holds with no price or no rate.
5740 */
5841 export interface Priced {
59 forge(cloud: string, size: string): number | undefined;
60 dearest(cloud: string): number | undefined;
42 /** The price of a Places id (`provider:datacenter:size`). */
43 forge(id: string): number | undefined;
44 dearest(cloud: string, datacenter?: string): number | undefined;
45 /** Why a listed place cannot be ordered now; undefined when it can, or is not listed. */
46 closed(id: string): string | undefined;
6147 }
6248
6349 export function priced(db: Database): Priced {
6450 const rate = keptRate(db, "EUR");
65 const cents = new Map<string, number>();
51 const cents = new Map<string, { cloud: string; datacenter: string; cents: number }>();
52 const closed = new Map<string, string>();
6653 for (const p of keptPlaces(db, rate)) {
6754 // A place the catalog could not price says so with no cost; it is not a place that costs nothing.
68 if (p.costCents <= 0 || p.datacenter !== WHERE[p.provider]) continue;
55 if (p.costCents <= 0) continue;
6956 try {
70 cents.set(`${p.provider}:${p.size}`, toUsd(p.price.vendorAmount, p.price.vendorCurrency, rate, "up").usdCents);
57 cents.set(p.id, { cloud: p.provider, datacenter: p.datacenter, cents: toUsd(p.price.vendorAmount, p.price.vendorCurrency, rate, "up").usdCents });
58 if (!p.orderable) closed.set(p.id, p.why);
7159 } catch {
7260 // no rate for its currency: no price
7361 }
7462 }
7563 return {
76 forge: (cloud, size) => cents.get(`${cloud}:${size}`),
77 dearest: (cloud) => {
78 const all = [...cents].filter(([k]) => k.startsWith(`${cloud}:`)).map(([, c]) => c);
64 forge: (id) => cents.get(id)?.cents,
65 dearest: (cloud, datacenter) => {
66 const mine = [...cents.values()].filter((c) => c.cloud === cloud);
67 const here = mine.filter((c) => c.datacenter === datacenter);
68 const all = (here.length > 0 ? here : mine).map((c) => c.cents);
7969 return all.length === 0 ? undefined : Math.max(...all);
8070 },
71 closed: (id) => closed.get(id),
8172 };
8273 }
8374
84 type Row = Pick<Pinned, "id" | "target" | "remote" | "volume">;
75 type Row = Pick<Pinned, "target" | "remote" | "volume" | "datacenter" | "size">;
8576
8677 /**
8778 * What one pinned row costs a month, cents. A row with a machine or a volume is counted as the
88 * whole forge of its recorded size: the catalog prices a place whole, and a volume waiting for its
89 * machine is about to be one. A machine of no recorded size, or of one the catalog no longer
90 * lists, is counted at the dearest the cloud has there: the reckoning errs high. Zero only for a
91 * row with nothing made, or when the catalog holds nothing for the cloud at all (then nothing new
92 * is admitted either).
79 * whole forge of its recorded place: the catalog prices a place whole, and a volume waiting for
80 * its machine is about to be one. A place the catalog no longer lists is counted at the dearest
81 * the cloud has in that datacenter: the reckoning errs high. Zero only for a row with nothing
82 * made, or when the catalog holds nothing for the cloud at all (then nothing new is admitted
83 * either).
9384 */
94 export function rowCents(db: Database, p: Row, prices: Priced = priced(db)): number {
85 export function rowCents(p: Row, prices: Priced): number {
9586 if (p.remote === "" && p.volume === "") return 0;
96 return prices.forge(p.target, recordedSize(db, p.id) ?? "") ?? prices.dearest(p.target) ?? 0;
87 return prices.forge(placeIdOf(p)) ?? prices.dearest(p.target, p.datacenter) ?? 0;
9788 }
9889
9990 /** What the forge reckons an account costs a month, in cents: the sum over its own pinned rows. */
10091 export function accountCents(db: Database, provider: string, account: string, prices: Priced = priced(db)): number {
10192 return listPinned(db)
10293 .filter((p) => p.target === provider && p.account === account)
103 .reduce((sum, p) => sum + rowCents(db, p, prices), 0);
94 .reduce((sum, p) => sum + rowCents(p, prices), 0);
10495 }
10596
10697 export interface Spend {
@@ -117,25 +108,29 @@ export function spendOf(db: Database, provider: string, account: string, prices:
117108 }
118109
119110 /**
120 * Refuse, in a plain sentence, when making the machine named by `plan` for pinned forge `name`
121 * would put its account over the ceiling. What the row is already counted at comes off, so a
122 * replace of a same-size machine, and the machine of a volume that was waiting for one, add
123 * nothing; a forge already over a lowered ceiling may still be replaced by what costs no more.
111 * Refuse, in a plain sentence, when making the place recorded on pinned forge `name` would put
112 * its account over the ceiling, or when that place cannot be ordered now. What the row is already
113 * counted at comes off, so a replace of a machine at its own place, and the machine of a volume
114 * that was waiting for one, add nothing; a forge already over a lowered ceiling may still be
115 * replaced by what costs no more.
124116 */
125 export function admit(app: App, name: string, plan: unknown): void {
117 export function admit(app: App, name: string): void {
126118 const p = getPinned(app.db, name);
127119 if (!p) return;
128120 const who = `${p.target}/${p.account}`;
129 const size = typeof plan === "string" ? plan : FIXED_SIZE[p.target];
121 const id = placeIdOf(p);
130122 const prices = priced(app.db);
131 const price = size === undefined ? undefined : prices.forge(p.target, size);
132 if (size === undefined || price === undefined)
123 const price = prices.forge(id);
124 if (price === undefined)
133125 throw new CeilingRefusal(
134 `The forge has no price for ${size ?? "the machine"} in ${WHERE[p.target] ?? "its datacenter"} on ${p.target}, so it cannot hold ${who} to its ceiling; nothing was made. ` +
126 `The forge has no price for ${p.size} in ${p.datacenter} on ${p.target}, so it cannot hold ${who} to its ceiling; nothing was made. ` +
135127 "Prices come from the provider's own list (Places, GET /api/v1/places), which the forge reads before a create and could not read a price from; try again in a few minutes.",
136128 );
129 const closed = prices.closed(id);
130 if (closed !== undefined)
131 throw new CeilingRefusal(`${id} cannot be ordered now: ${closed}; nothing was made, and a running machine was not touched. Pick another place, or try again later.`);
137132 const { ceilingDollars, monthlyCents } = spendOf(app.db, p.target, p.account, prices);
138 const add = price - rowCents(app.db, p, prices);
133 const add = price - rowCents(p, prices);
139134 if (add <= 0 || monthlyCents + add <= ceilingDollars * 100) return;
140135 throw new CeilingRefusal(
141136 `${who} is held to $${ceilingDollars} a month and runs ${dollars(monthlyCents)} now; this would add ${dollars(add)}, which is over it, so nothing was made. ` +
@@ -143,23 +138,7 @@ export function admit(app: App, name: string, plan: unknown): void {
143138 );
144139 }
145140
146 /**
147 * The driver, held to the account's ceiling: its `plan` checks before the first thing is made, and
148 * the size of each machine it makes is kept so a replace can be counted against it.
149 */
150 export function capped<P>(app: App, name: string, d: Driver<P>): Driver<P> {
151 return {
152 ...d,
153 async plan(call) {
154 const plan = await d.plan(call);
155 admit(app, name, plan);
156 return plan;
157 },
158 async createMachine(call, p, volume, plan) {
159 const remote = await d.createMachine(call, p, volume, plan);
160 const size = typeof plan === "string" ? plan : FIXED_SIZE[p.target];
161 if (size !== undefined) noteSize(app.db, p.id, size);
162 return remote;
163 },
164 };
141 /** The driver, held to the account's ceiling: its `admit` checks before the first thing is made. */
142 export function capped(app: App, name: string, d: Driver): Driver {
143 return { ...d, admit: () => admit(app, name) };
165144 }
src/cloud/drivers.ts +2 −2
@@ -7,10 +7,10 @@ import { digitalocean } from "./droplet.ts";
77 import { hetzner } from "./hetzner.ts";
88 import type { Driver } from "./machine.ts";
99
10 const DRIVERS: Readonly<Record<string, Driver<any>>> = { digitalocean, hetzner };
10 const DRIVERS: Readonly<Record<string, Driver>> = { digitalocean, hetzner };
1111
1212 /** The driver of a target, or a plain error when none deploys there. */
13 export function driverOf(id: string): Driver<any> {
13 export function driverOf(id: string): Driver {
1414 const d = DRIVERS[id];
1515 if (!d) throw new Error(`No driver deploys to ${id}.`);
1616 return d;
src/cloud/droplet.ts +3 −5
@@ -11,8 +11,6 @@ import { dropThrowawayKey, makeThrowawayKey } from "./throwaway_key.ts";
1111 import { bootConfig as boot, ipv4, volumeName, type Booted, type Driver } from "./machine.ts";
1212
1313 export { BUN_VERSION } from "./machine.ts";
14 export const REGION = "nyc3";
15 export const SIZE = "s-1vcpu-2gb";
1614
1715 /** DigitalOcean mounts a volume at /mnt/<its name, dashes as underscores>. */
1816 const dataDir = (name: string) => `/mnt/${volumeName(name).replace(/-/g, "_")}`;
@@ -22,11 +20,11 @@ export const bootConfig = (p: Booted): string => boot(p, dataDir(p.name));
2220 /** DigitalOcean's collection of account SSH keys. */
2321 const KEYS = "/account/keys";
2422
23 /** Both the volume and the droplet are made in the row's datacenter, at its size (`machine.ts`). */
2524 export const digitalocean: Driver = {
2625 api: "https://api.digitalocean.com/v2",
27 plan: async () => undefined,
2826 async createVolume(call, p) {
29 const v = await call("POST", "/volumes", { name: volumeName(p.name), region: REGION, size_gigabytes: 10, filesystem_type: "ext4" });
27 const v = await call("POST", "/volumes", { name: volumeName(p.name), region: p.datacenter, size_gigabytes: 10, filesystem_type: "ext4" });
3028 return String(v.volume?.id ?? "");
3129 },
3230 async createMachine(call, p, volume) {
@@ -34,7 +32,7 @@ export const digitalocean: Driver = {
3432 const key = await makeThrowawayKey(call, KEYS, p.name);
3533 try {
3634 const d = await call("POST", "/droplets", {
37 name: `forge-${p.name}`, region: REGION, size: SIZE, image: "ubuntu-24-04-x64",
35 name: `forge-${p.name}`, region: p.datacenter, size: p.size, image: "ubuntu-24-04-x64",
3836 volumes: [volume], user_data: bootConfig(p), tags: ["forge-pinned"], ssh_keys: [Number(key)],
3937 });
4038 return String(d.droplet?.id ?? "");
src/cloud/hetzner.ts +7 −41
@@ -3,28 +3,15 @@
33 * machine.ts. A Hetzner token is scoped to one project and is read or
44 * read-write, nothing narrower.
55 *
6 * Calls (Hetzner Cloud API v1): GET /server_types and /datacenters (what can be
7 * ordered where, read before anything is made), POST /volumes, POST /ssh_keys and DELETE
6 * Calls (Hetzner Cloud API v1): POST /volumes, POST /ssh_keys and DELETE
87 * /ssh_keys/{id} (a throwaway key, so no root password is mailed), POST /servers (the volume
98 * attached and automounted at /mnt/HC_Volume_<id>), DELETE /servers/{id}, GET /servers/{id} (the
109 * public IPv4 read back after it boots).
1110 */
1211
1312 import { dropThrowawayKey, makeThrowawayKey } from "./throwaway_key.ts";
14 import { bootConfig as boot, ipv4, volumeName, type Booted, type Call, type Driver } from "./machine.ts";
13 import { bootConfig as boot, ipv4, volumeName, type Booted, type Driver } from "./machine.ts";
1514
16 /**
17 * Nuremberg: an EU location, because the US ones cost about three times as much for a tenth of the
18 * traffic. One constant a setting can later replace.
19 */
20 export const LOCATION = "nbg1";
21 /**
22 * The cost-optimized shared line (CX); the type is chosen from the API at order time, never named
23 * here.
24 */
25 export const TYPE_LINE = /^cx\d+$/;
26 /** The least memory a forge runs in, GiB. */
27 export const MIN_MEMORY_GIB = 2;
2815 const IMAGE = "ubuntu-24.04";
2916
3017 /** Hetzner mounts an attached volume, when automount is asked for, under /mnt/HC_Volume_<id>. */
@@ -32,43 +19,22 @@ const dataDir = (volume: string) => `/mnt/HC_Volume_${volume}`;
3219
3320 export const bootConfig = (p: Booted, volume: string): string => boot(p, dataDir(volume));
3421
35 /**
36 * The cheapest x86 server type of the CX line with at least MIN_MEMORY_GIB that
37 * can be ordered at `location` now, read from the API; throws, in words the
38 * pinned page can show as they are, when there is none.
39 */
40 export async function pickType(call: Call, location = LOCATION): Promise<string> {
41 const types: any[] = (await call("GET", "/server_types?per_page=50")).server_types ?? [];
42 const dcs: any[] = (await call("GET", "/datacenters?per_page=50")).datacenters ?? [];
43 const here = dcs.filter((d) => d?.location?.name === location);
44 const stocked = new Set<number>(here.flatMap((d) => (Array.isArray(d?.server_types?.available) ? d.server_types.available : [])));
45 const price = (t: any) => Number(t.prices?.find((x: any) => x?.location === location)?.price_monthly?.gross);
46 const options = types
47 .filter((t) => TYPE_LINE.test(String(t?.name)) && t.architecture === "x86" && Number(t.memory) >= MIN_MEMORY_GIB && !t.deprecated)
48 .filter((t) => stocked.has(t.id))
49 .filter((t) => Number.isFinite(price(t)))
50 .sort((a, b) => price(a) - price(b) || String(a.name).localeCompare(String(b.name)));
51 const best = options[0];
52 if (!best) throw new Error(`Hetzner has no CX server with ${MIN_MEMORY_GIB} GiB or more that can be ordered in ${location} right now; nothing was made. Try again later.`);
53 return String(best.name);
54 }
55
5622 /** Hetzner's collection of project SSH keys. */
5723 const KEYS = "/ssh_keys";
5824
59 export const hetzner: Driver<string> = {
25 /** The volume and the server are made at the row's location, the server of its type (`machine.ts`). */
26 export const hetzner: Driver = {
6027 api: "https://api.hetzner.cloud/v1",
61 plan: (call) => pickType(call),
6228 async createVolume(call, p) {
63 const v = await call("POST", "/volumes", { name: volumeName(p.name), location: LOCATION, size: 10, format: "ext4", automount: false });
29 const v = await call("POST", "/volumes", { name: volumeName(p.name), location: p.datacenter, size: 10, format: "ext4", automount: false });
6430 return String(v.volume?.id ?? "");
6531 },
66 async createMachine(call, p, volume, type) {
32 async createMachine(call, p, volume) {
6733 // A server made with no SSH key is sent a root password by email; see throwaway_key.ts.
6834 const key = await makeThrowawayKey(call, KEYS, p.name);
6935 try {
7036 const s = await call("POST", "/servers", {
71 name: `forge-${p.name}`, server_type: type, location: LOCATION, image: IMAGE,
37 name: `forge-${p.name}`, server_type: p.size, location: p.datacenter, image: IMAGE,
7238 volumes: [Number(volume)], automount: true, user_data: bootConfig(p, volume), ssh_keys: [Number(key)],
7339 public_net: { enable_ipv4: true, enable_ipv6: true }, start_after_create: true, labels: { "forge-pinned": "true" },
7440 });
src/cloud/machine.ts +27 −23
@@ -138,23 +138,27 @@ ${proxyCommands(dataDir)}
138138 /** One request to the cloud's fixed host; the driver's calls are made through it. */
139139 export type Call = (method: string, path: string, body?: unknown) => Promise<any>;
140140
141 /** What a cloud supplies; `Plan` is what it decides before anything is made (a size, a type). */
142 export interface Driver<Plan = undefined> {
141 /**
142 * What a cloud supplies. Where and what to order is the row's recorded place (`p.datacenter`,
143 * `p.size`), never a constant of the driver: the volume and the machine are made in the same
144 * datacenter, and a replace orders the place its volume is in.
145 */
146 export interface Driver {
143147 /** The fixed API base, https, no trailing slash. */
144148 readonly api: string;
145149 /**
146 * Decide what to order, or throw plainly when it cannot be ordered: called before the first thing
147 * is made.
150 * Refuse a place that may not be ordered, by throwing in words shown as they are: called before
151 * the first thing is made or deleted (`ceiling.ts` sets it).
148152 */
149 plan(call: Call): Promise<Plan>;
150 createVolume(call: Call, p: Pinned, plan: Plan): Promise<string>;
153 admit?(p: Pinned): void;
154 createVolume(call: Call, p: Pinned): Promise<string>;
151155 /** Make the machine with the volume attached; returns its id. */
152 createMachine(call: Call, p: Pinned, volume: string, plan: Plan): Promise<string>;
156 createMachine(call: Call, p: Pinned, volume: string): Promise<string>;
153157 deleteMachine(call: Call, remote: string): Promise<void>;
154158 readMachine(call: Call, remote: string): Promise<{ status: string; address: string }>;
155159 }
156160
157 function caller(d: Driver<any>, f: Fetch, token: string): Call {
161 function caller(d: Driver, f: Fetch, token: string): Call {
158162 const host = new URL(d.api).host;
159163 return async (method, path, body) => {
160164 const res = await f(`${d.api}${path}`, {
@@ -175,18 +179,18 @@ const ID = /^\d+$/;
175179 * made (`have`) is reused; a new one is recorded through `onVolume` before the
176180 * machine is asked for. Returns the ids to keep.
177181 */
178 export async function provision<P>(
179 d: Driver<P>, f: Fetch, token: string, p: Pinned, hooks: { have?: string; onVolume(id: string): void },
182 export async function provision(
183 d: Driver, f: Fetch, token: string, p: Pinned, hooks: { have?: string; onVolume(id: string): void },
180184 ): Promise<{ remote: string; volume: string }> {
181185 const call = caller(d, f, token);
182 const plan = await d.plan(call);
186 d.admit?.(p);
183187 let volume = hooks.have ?? "";
184188 if (volume === "") {
185 volume = await d.createVolume(call, p, plan);
189 volume = await d.createVolume(call, p);
186190 if (volume === "") throw new Error(`${new URL(d.api).host} made no volume`);
187191 hooks.onVolume(volume);
188192 }
189 return { remote: await d.createMachine(call, p, volume, plan), volume };
193 return { remote: await d.createMachine(call, p, volume), volume };
190194 }
191195
192196 /**
@@ -197,13 +201,13 @@ export async function provision<P>(
197201 * `onDeleted` clears the recorded id at once, so a retry after a failed create
198202 * does not delete twice.
199203 */
200 export async function replace<P>(
201 d: Driver<P>, f: Fetch, token: string, p: Pinned, hooks: { onDeleted(): void },
204 export async function replace(
205 d: Driver, f: Fetch, token: string, p: Pinned, hooks: { onDeleted(): void },
202206 ): Promise<{ remote: string }> {
203207 if (p.volume === "") throw new Error("this forge has no volume to keep");
204208 if (p.remote !== "" && !ID.test(p.remote)) throw new Error("this forge has no machine to replace");
205209 const call = caller(d, f, token);
206 const plan = await d.plan(call);
210 d.admit?.(p);
207211 if (p.remote !== "") {
208212 try {
209213 await d.deleteMachine(call, p.remote);
@@ -212,16 +216,16 @@ export async function replace<P>(
212216 }
213217 hooks.onDeleted();
214218 }
215 return { remote: await d.createMachine(call, p, p.volume, plan) };
219 return { remote: await d.createMachine(call, p, p.volume) };
216220 }
217221
218222 /**
219 * Decide what would be ordered, and make nothing: the driver's `plan` alone, which is where a
220 * cloud that cannot deliver, or a ceiling (`ceiling.ts`), refuses. Asked before a change is
221 * recorded, so a refusal leaves the row and the machine agreeing.
223 * Ask whether the row's place may be ordered, and make nothing: the driver's `admit` alone, which
224 * is where a place that cannot be ordered, or a ceiling (`ceiling.ts`), refuses. Asked before a
225 * change is recorded, so a refusal leaves the row and the machine agreeing.
222226 */
223 export async function orderable<P>(d: Driver<P>, f: Fetch, token: string): Promise<void> {
224 await d.plan(caller(d, f, token));
227 export async function orderable(d: Driver, p: Pinned): Promise<void> {
228 d.admit?.(p);
225229 }
226230
227231 const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$/;
@@ -229,7 +233,7 @@ const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)
229233 export const ipv4 = (v: unknown): string => (typeof v === "string" && IPV4.test(v) ? v : "");
230234
231235 /** Read the machine back: its status and public IPv4 (empty while none is assigned). */
232 export async function read(d: Driver<any>, f: Fetch, token: string, remote: string): Promise<{ status: string; address: string }> {
236 export async function read(d: Driver, f: Fetch, token: string, remote: string): Promise<{ status: string; address: string }> {
233237 if (!ID.test(remote)) throw new Error("this forge has no machine to read");
234238 return d.readMachine(caller(d, f, token), remote);
235239 }
src/cloud/places.ts +8 −3
@@ -56,6 +56,9 @@ const SLUG = /^[a-z0-9][a-z0-9._-]{0,40}$/;
5656
5757 const unorderable = (p: Omit<Place, "orderable" | "why">, why: string): Place => ({ ...p, orderable: false, why });
5858
59 /** The reason an ARM size is not a place: the forge's machine is an x86 image running an x86 Bun. */
60 const ARM_WHY = "an ARM size; the forge runs on x86 machines only";
61
5962 /**
6063 * Hetzner: server types, per-location stock, and the account's pricing. Hetzner bills the account
6164 * in `pricing.currency`; anything but USD is converted at `rate` and kept beside the dollars. A
@@ -83,7 +86,9 @@ export function hetznerPlaces(
8386 const out: Place[] = [];
8487 for (const t of arr(body.server_types)) {
8588 const size = str(t?.name);
86 if (!SLUG.test(size) || t.architecture !== "x86" || t.deprecated) continue;
89 if (!SLUG.test(size) || t.deprecated) continue;
90 // The machine boots an x86 image and an x86 build of Bun: an ARM size is listed, and says why not.
91 const arm = t.architecture !== "x86";
8792 for (const pr of arr(t.prices)) {
8893 const loc = str(pr?.location);
8994 const here = where.get(loc);
@@ -106,7 +111,7 @@ export function hetznerPlaces(
106111 continue;
107112 }
108113 const place = { ...base, costCents: price.usdCents, price };
109 out.push(stocked.get(loc)?.has(Number(t.id)) ? { ...place, orderable: true, why: "" } : unorderable(place, "sold out at this datacenter right now"));
114 out.push(arm ? unorderable(place, ARM_WHY) : stocked.get(loc)?.has(Number(t.id)) ? { ...place, orderable: true, why: "" } : unorderable(place, "sold out at this datacenter right now"));
110115 }
111116 }
112117 return out;
@@ -145,7 +150,7 @@ export function digitaloceanPlaces(body: { sizes: unknown; regions: unknown }, r
145150 size, vcpu: num(s.vcpus), memoryMiB: num(s.memory), diskGiB: num(s.disk), trafficGiB: Math.round(num(s.transfer) * 1024) || 0,
146151 costCents: price.usdCents, price, assumed: ["volume"] as string[], readAt,
147152 };
148 out.push(s.available === true && open.has(slug) ? { ...base, orderable: true, why: "" } : unorderable(base, open.has(slug) ? "this size is not offered now" : "this region is not taking new machines"));
153 out.push(/arm/.test(size) ? unorderable(base, ARM_WHY) : s.available === true && open.has(slug) ? { ...base, orderable: true, why: "" } : unorderable(base, open.has(slug) ? "this size is not offered now" : "this region is not taking new machines"));
149154 }
150155 }
151156 return out;
src/contract/openapi/routes/postApiV1AdminPinned.ts +2 −2
@@ -4,11 +4,11 @@ export const route: Route = {
44 method: "post",
55 path: "/api/v1/admin/pinned",
66 summary: "Put a pinned forge on the owner's cloud: no crew, no automatic release",
7 detail: "Put a pinned forge on the owner's cloud: no crew, no automatic release; needs an admin-scope token and a cloud account with writes allowed; `host` is the name it is served on over HTTPS; answers the forge with { claim: { link, expiresAt } }, the one-time link that makes its first admin, shown in this answer only, and `dns`, the record to create",
7 detail: "Put a pinned forge on the owner's cloud: no crew, no automatic release; needs an admin-scope token and a cloud account with writes allowed; `host` is the name it is served on over HTTPS; `place` (provider:datacenter:size, from Places) is where its volume and machine are made, and left out it is the catalog's default for the small plan on that provider; answers the forge with { claim: { link, expiresAt } }, the one-time link that makes its first admin, shown in this answer only, and `dns`, the record to create",
88 auth: true,
99 role: "admin",
1010 status: 201,
11 body: { name: "string", host: "string", target: "string", account: "string", app: "string", source: "string", version: "string", config: "object" },
11 body: { name: "string", host: "string", target: "string", account: "string", app: "string", source: "string", version: "string", place: "string", config: "object" },
1212 refusals: {
1313 not_found: "only a forge administrator sees this route",
1414 refused: "the request was understood and refused; the message says why (422)",
src/core/migration-pins/20261124185948-pinned-place.pin added +1
@@ -0,0 +1,1 @@
1 390fc8eded5d8a26d2c91841240818c46da1ee62325682ef0d25ea1cf70a8ebb
src/core/migrations/20261124185948-pinned-place.ts added +7
@@ -0,0 +1,7 @@
1 // A pinned forge's place is one fact: the datacenter its volume and machine are made in, beside
2 // the size already kept in `pinned_size` (#16205). Recorded when the forge is deployed, before
3 // anything is made, so a replace always orders where the volume is. Empty on a row from before:
4 // the code reads that as the place the drivers once hard-coded. Additive.
5 export default `
6 ALTER TABLE pinned_size ADD COLUMN datacenter TEXT NOT NULL DEFAULT '';
7 `;
src/core/pinned.ts +31 −4
@@ -36,8 +36,29 @@ export interface Pinned {
3636 * `remote`, the forge has been reached since its current machine was made.
3737 */
3838 readonly reached: string;
39 /**
40 * Where its volume and machine are: the cloud's datacenter, and the machine size ordered there.
41 * Recorded with the row at deploy and never changed, so every replace orders the same place
42 * (the volume lives there). Together with `target` it is a Places id (`placeIdOf`).
43 */
44 readonly datacenter: string;
45 readonly size: string;
3946 }
4047
48 /**
49 * The place a forge deployed before places were kept is read as: where the drivers once ordered
50 * every forge (DigitalOcean nyc3 `s-1vcpu-2gb`, Hetzner nbg1, a `cx23` when its row kept no
51 * size). Only a row with nothing recorded gets it, so an old forge's replace still orders where
52 * its volume is.
53 */
54 const LEGACY_PLACE: Readonly<Record<string, { datacenter: string; size: string }>> = {
55 digitalocean: { datacenter: "nyc3", size: "s-1vcpu-2gb" },
56 hetzner: { datacenter: "nbg1", size: "cx23" },
57 };
58
59 /** The Places id of where a forge is: `provider:datacenter:size`. */
60 export const placeIdOf = (p: Pick<Pinned, "target" | "datacenter" | "size">): string => `${p.target}:${p.datacenter}:${p.size}`;
61
4162 export interface Change {
4263 readonly id: number;
4364 readonly kind: "deploy" | "update" | "rollback";
@@ -108,7 +129,7 @@ export function checkConfig(raw: unknown): Result<Record<string, string>, string
108129 interface Row {
109130 id: string; name: string; target: string; account: string; app: string; source: string;
110131 version: string; config: string; remote: string; volume: string; address: string; state: string; claimed_at: string; created_at: string;
111 host: string; claim_hash: string; claim_expires: string; reached: string;
132 host: string; claim_hash: string; claim_expires: string; reached: string; datacenter: string | null; size: string | null;
112133 }
113134
114135 const toPinned = (r: Row): Pinned => ({
@@ -116,13 +137,17 @@ const toPinned = (r: Row): Pinned => ({
116137 version: r.version, config: JSON.parse(r.config) as Record<string, string>,
117138 remote: r.remote, volume: r.volume, address: r.address, state: r.state, claimedAt: r.claimed_at, createdAt: r.created_at,
118139 host: r.host, claimHash: r.claim_hash, claimExpires: r.claim_expires, reached: r.reached,
140 datacenter: r.datacenter || LEGACY_PLACE[r.target]?.datacenter || "", size: r.size || LEGACY_PLACE[r.target]?.size || "",
119141 });
120142
143 /** A forge row with its place beside it. */
144 const SELECT = "SELECT f.*, s.datacenter AS datacenter, s.size AS size FROM pinned_forge f LEFT JOIN pinned_size s ON s.pinned_id = f.id";
145
121146 export const listPinned = (db: Database): Pinned[] =>
122 db.query<Row, []>("SELECT * FROM pinned_forge ORDER BY created_at, id").all().map(toPinned);
147 db.query<Row, []>(`${SELECT} ORDER BY f.created_at, f.id`).all().map(toPinned);
123148
124149 export function getPinned(db: Database, name: string): Pinned | undefined {
125 const r = db.query<Row, [string]>("SELECT * FROM pinned_forge WHERE name = ?1").get(name);
150 const r = db.query<Row, [string]>(`${SELECT} WHERE f.name = ?1`).get(name);
126151 return r ? toPinned(r) : undefined;
127152 }
128153
@@ -137,7 +162,7 @@ export function changesOf(db: Database, pinnedId: string): Change[] {
137162
138163 export function insertPinned(
139164 db: Database,
140 p: { name: string; target: string; account: string; app: string; source: string; version: string; config: Record<string, string>; host: string; claimHash: string; claimExpires: string },
165 p: { name: string; target: string; account: string; app: string; source: string; version: string; config: Record<string, string>; host: string; claimHash: string; claimExpires: string; datacenter: string; size: string },
141166 by: string,
142167 ): Pinned {
143168 const at = new Date().toISOString();
@@ -150,6 +175,7 @@ export function insertPinned(
150175 db.query(
151176 "INSERT INTO pinned_forge (id, name, target, account, app, source, version, config, change_id, created_at, host, claim_hash, claim_expires) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)",
152177 ).run(pid, p.name, p.target, p.account, p.app, p.source, p.version, config, Number(c.lastInsertRowid), at, p.host, p.claimHash, p.claimExpires);
178 db.query("INSERT INTO pinned_size (pinned_id, size, datacenter) VALUES (?1, ?2, ?3)").run(pid, p.size, p.datacenter);
153179 })();
154180 return getPinned(db, p.name)!;
155181 }
@@ -244,6 +270,7 @@ export const CLAIMED_REFUSAL = "This forge was handed to its buyer: its updates
244270
245271 /** The row of a deploy that never reached a droplet, so its name can be tried again; its recorded change stays as history. */
246272 export function dropPinned(db: Database, name: string): void {
273 db.query("DELETE FROM pinned_size WHERE pinned_id IN (SELECT id FROM pinned_forge WHERE name = ?1 AND remote = '' AND state = 'failed')").run(name);
247274 db.query("DELETE FROM pinned_forge WHERE name = ?1 AND remote = '' AND state = 'failed'").run(name);
248275 }
249276
src/http/api/admin.ts +1 −1
@@ -90,7 +90,7 @@ export function adminRoutes(router: Router<Handler>): void {
9090 const i = await body(ctx.request);
9191 const made = await deployPinned(ctx.app, ctx.auth.user, {
9292 name: str(i.name), host: str(i.host), target: str(i.target), account: str(i.account), app: str(i.app),
93 source: str(i.source), version: str(i.version), config: i.config,
93 source: str(i.source), version: str(i.version), place: str(i.place), config: i.config,
9494 });
9595 // The answer holds the claim link, shown once: nothing between here and the caller keeps it.
9696 return made.ok ? once(json(made.value, 201)) : pinnedFail(made.error);
src/http/mcp/tools/pinned_forge.ts +3 −2
@@ -6,7 +6,7 @@ import { good, bad, type Tool, str } from "../shared.ts";
66 export const tool: Tool = {
77 name: "pinned_forge",
88 listedTo: "admin",
9 doc: "`{ verb, name?, host?, target?, account?, app?, source?, version?, config? }`: a pinned forge on the owner's cloud has no crew and no automatic release. `list` shows them with every recorded change and the targets (what runs, what it costs, what is refused); `deploy` puts one on `target` with a cloud `account` (writes allowed) serving `app` owner/name from `source` at `version` on `host`, its own name over HTTPS, and answers once with `claim.link`, the only way to become its first admin, and `dns`, the record to create; `claim` issues a fresh link for a forge nobody has claimed (the machine is replaced, the old link stops); `update` is the only way its `version` or `config` change; `rollback` goes back one; `check` reads the machine's address back and says what the forge waits for (`waiting`: address, dns, answer) or that it answers and what became of its claim (`url`, `healthy`, `claim`). A forge admin with an admin-scope token",
9 doc: "`{ verb, name?, host?, target?, account?, app?, source?, version?, place?, config? }`: a pinned forge on the owner's cloud has no crew and no automatic release. `list` shows them with every recorded change and the targets (what runs, what it costs, what is refused); `deploy` puts one on `target` with a cloud `account` (writes allowed) serving `app` owner/name from `source` at `version` on `host`, its own name over HTTPS, at `place` (provider:datacenter:size, from Places; the catalog's default for the small plan on that provider when left out; recorded on the forge, and every replace orders there), and answers once with `claim.link`, the only way to become its first admin, and `dns`, the record to create; `claim` issues a fresh link for a forge nobody has claimed (the machine is replaced, the old link stops); `update` is the only way its `version` or `config` change; `rollback` goes back one; `check` reads the machine's address back and says what the forge waits for (`waiting`: address, dns, answer) or that it answers and what became of its claim (`url`, `healthy`, `claim`). A forge admin with an admin-scope token",
1010 description: "Pinned forges on your cloud: list, deploy, claim, update, rollback, check (admin).",
1111 inputSchema: {
1212 type: "object",
@@ -19,6 +19,7 @@ export const tool: Tool = {
1919 app: { type: "string", maxLength: 140 },
2020 source: { type: "string", maxLength: 300 },
2121 version: { type: "string", maxLength: 40, description: "Commit id or tag." },
22 place: { type: "string", maxLength: 200, description: "provider:datacenter:size, an orderable place of the account's provider; omit for the default." },
2223 config: { type: "object", description: "NAME: value; no secrets." },
2324 },
2425 required: ["verb"],
@@ -45,7 +46,7 @@ export const tool: Tool = {
4546 verb === "deploy"
4647 ? await deployPinned(ctx.app, user, {
4748 name, host: str(args["host"]), target: str(args["target"]), account: str(args["account"]), app: str(args["app"]),
48 source: str(args["source"]), version: str(args["version"]), config: args["config"],
49 source: str(args["source"]), version: str(args["version"]), place: str(args["place"]), config: args["config"],
4950 })
5051 : await claimPinned(ctx.app, user, name, { host: args["host"] === undefined ? undefined : str(args["host"]) });
5152 if (!made.ok) return bad("refused", made.error);
src/http/pinned_routes.ts +4 −2
@@ -7,7 +7,8 @@
77 * never through a redirect or a flash: it is shown once and stored nowhere.
88 */
99
10 import { checkPinned, checkWords, claimPinned, deployPinned, pinnedForges, rollbackPinned, updatePinned, type Issued } from "../actions/pinned.ts";
10 import { checkPinned, checkWords, claimPinned, deployPinned, deployPlaces, pinnedForges, rollbackPinned, updatePinned, type Issued } from "../actions/pinned.ts";
11 import { TARGETS } from "../cloud/targets.ts";
1112 import { listCloudAccounts } from "../core/cloud_account.ts";
1213 import { lastCheckOf } from "../core/pinned.ts";
1314 import { getUsersByIds } from "../core/users.ts";
@@ -28,6 +29,7 @@ const seen = (get: (k: string) => string): DeployForm => {
2829 account: get("account").trim().slice(0, 60),
2930 name: get("name").trim().slice(0, 40) || nameFor(app),
3031 host: get("host").trim().toLowerCase().slice(0, 253),
32 place: get("place").trim().slice(0, 200),
3133 };
3234 };
3335
@@ -43,7 +45,7 @@ function render(ctx: Ctx, v: DeployForm, flash?: { tone: "danger"; message: stri
4345 {
4446 ctx,
4547 title: "Deploy to…",
46 body: deployPage(listCloudAccounts(ctx.app.db), v),
48 body: deployPage(listCloudAccounts(ctx.app.db), v, deployPlaces(ctx.app, TARGETS.map((t) => t.id))),
4749 ...(flash ? { flash } : {}),
4850 },
4951 flash ? 422 : 200,
src/tui/screens/pinned.ts +5 −5
@@ -79,14 +79,14 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen {
7979 const deploy = (parent: Screen): Screen =>
8080 promptScreen(ctx, parent, {
8181 title: "Deploy a pinned forge",
82 label: "name hostname provider/account owner/app https-source version",
83 placeholder: "acme forge.acme.com digitalocean/main alice/shop https://host/alice/shop v1.0.0",
82 label: "name hostname provider/account owner/app https-source version [place]",
83 placeholder: "acme forge.acme.com digitalocean/main alice/shop https://host/alice/shop v1.0.0 digitalocean:sfo2:s-1vcpu-2gb",
8484 onSubmit: (raw) => {
85 const [name = "", host = "", cloud = "", app = "", source = "", version = "", ...rest] = raw.trim().split(/\s+/);
85 const [name = "", host = "", cloud = "", app = "", source = "", version = "", place = "", ...rest] = raw.trim().split(/\s+/);
8686 const [target = "", account = "", ...more] = cloud.split("/");
87 if (rest.length > 0 || more.length > 0 || version === "" || account === "") return "Write: name hostname provider/account owner/app source version.";
87 if (rest.length > 0 || more.length > 0 || version === "" || account === "") return "Write: name hostname provider/account owner/app source version [place]; a place is provider:datacenter:size, and left out it is the default.";
8888 say(`Deploying ${name}…`);
89 return hand(ctx, say, deployPinned(f.app, f.user, { name, host, target, account, app, source, version }), parent);
89 return hand(ctx, say, deployPinned(f.app, f.user, { name, host, target, account, app, source, version, place }), parent);
9090 },
9191 });
9292
src/web/pinned.ts +17 −1
@@ -9,6 +9,8 @@
99 import { claimWords, type Issued } from "../actions/pinned.ts";
1010 import type { CloudAccount } from "../core/cloud_account.ts";
1111 import { HOST_CAN } from "../core/pinned.ts";
12 import type { Place } from "../cloud/places.ts";
13 import { dollars } from "../cloud/prices.ts";
1214 import { LABEL } from "../cloud/providers.ts";
1315 import { TARGETS } from "../cloud/targets.ts";
1416 import { pageHead } from "./chrome.ts";
@@ -22,6 +24,8 @@ export interface DeployForm {
2224 source: string;
2325 version: string;
2426 host: string;
27 /** A Places id, or empty for the catalog's default. */
28 place: string;
2529 }
2630
2731 /** Name a new forge after the app it runs, when the link does not say. */
@@ -61,8 +65,11 @@ const DEPLOYABLE = new Set<string>(TARGETS.filter((t) => t.status === "first").m
6165 */
6266 const NAMES = TARGETS.filter((t) => DEPLOYABLE.has(t.id)).map((t) => t.label).join(" or ");
6367
64 export function deployPage(accounts: CloudAccount[], v: DeployForm): Html {
68 export function deployPage(accounts: CloudAccount[], v: DeployForm, places: Place[]): Html {
6569 const usable = accounts.filter((a) => DEPLOYABLE.has(a.provider) && a.writeAllowed);
70 const providers = new Set<string>(usable.map((a) => a.provider));
71 const offered = places.filter((p) => providers.has(p.provider));
72 const named = (provider: string): string => (LABEL as Record<string, string>)[provider] ?? provider;
6673 return html`<div class="page-head"><h1>Deploy to…</h1></div>
6774 ${card(
6875 html`<p class="muted small">
@@ -81,6 +88,15 @@ export function deployPage(accounts: CloudAccount[], v: DeployForm): Html {
8188 required: true,
8289 options: usable.map((a) => ({ value: `${a.provider}/${a.name}`, label: `${LABEL[a.provider]} / ${a.name}`, selected: v.account === a.name || v.account === `${a.provider}/${a.name}` })),
8390 })}
91 ${selectField({
92 name: "place",
93 label: "Place",
94 hint: "Where its volume and machine are made, and where every Update replaces it. The default is the cheapest place in the United States on the account's cloud. A place must be on the account's own cloud.",
95 options: [
96 { value: "", label: "Default: the cheapest place in the United States", selected: v.place === "" },
97 ...offered.map((p) => ({ value: p.id, label: `${named(p.provider)} · ${p.city} (${p.datacenter}) · ${p.size} · ${dollars(p.costCents)} a month`, selected: v.place === p.id })),
98 ],
99 })}
84100 ${field({ name: "app", label: "App", value: v.app, placeholder: "owner/name", mono: true, required: true, maxlength: 140, spellcheck: false })}
85101 ${field({ name: "source", label: "Source", value: v.source, placeholder: "https://…", mono: true, required: true, maxlength: 400, spellcheck: false, hint: "An https git address." })}
86102 ${field({ name: "version", label: "Version", value: v.version, mono: true, required: true, maxlength: 40, spellcheck: false, hint: "A full 40-character commit id or a tag like v1.2.3 — never a branch." })}
test/helpers/places-fixture.ts +28 −17
@@ -25,6 +25,33 @@ export const ocean = {
2525 };
2626
2727
28 /**
29 * Hetzner's places as the pinned-forge tests have them: the CX line in nbg1, in euros, and one ARM
30 * size (id 7, which the forge never orders). `available` is the ids in stock there, so a test can
31 * sell a size out and read the catalog again.
32 */
33 export async function seedHetzner(db: Database, available: number[] = [1, 2, 5, 7]): Promise<void> {
34 const json = (o: unknown): Response => new Response(JSON.stringify(o), { status: 200 });
35 const eur = (gross: string) => [{ location: "nbg1", price_monthly: { gross } }];
36 const types = [
37 { id: 1, name: "cx22", cores: 2, memory: 4, disk: 40, architecture: "x86", prices: eur("4.50") },
38 { id: 2, name: "cx23", cores: 2, memory: 4, disk: 40, architecture: "x86", prices: eur("5.99") },
39 { id: 5, name: "cx33", cores: 4, memory: 8, disk: 80, architecture: "x86", prices: eur("8.99") },
40 { id: 7, name: "cax21", cores: 4, memory: 8, disk: 80, architecture: "arm", prices: eur("6.49") },
41 ];
42 await readPlaces(
43 db,
44 "hetzner",
45 async (url) => {
46 const u = String(url);
47 if (u.includes("/server_types")) return json({ server_types: types });
48 if (u.includes("/datacenters")) return json({ datacenters: [{ location: { name: "nbg1", city: "Nuremberg", country: "DE" }, server_types: { available } }] });
49 return json({ pricing: { currency: "EUR", volume: { price_per_gb_month: { gross: "0.0572" } }, primary_ips: [{ type: "ipv4", prices: [{ location: "nbg1", price_monthly: { gross: "0.50" } }] }] } });
50 },
51 "t",
52 );
53 }
54
2855 /**
2956 * The catalog the pinned-forge tests deploy against, kept as a real read keeps it: DigitalOcean's
3057 * `s-1vcpu-2gb` in nyc3 ($12 + the $1 volume = $13.00 a month) and Hetzner's CX line in nbg1 in
@@ -33,23 +60,7 @@ export const ocean = {
3360 */
3461 export async function seedPlaces(db: Database): Promise<void> {
3562 const json = (o: unknown): Response => new Response(JSON.stringify(o), { status: 200 });
36 const eur = (gross: string) => [{ location: "nbg1", price_monthly: { gross } }];
37 const types = [
38 { id: 1, name: "cx22", cores: 2, memory: 4, disk: 40, architecture: "x86", prices: eur("4.50") },
39 { id: 2, name: "cx23", cores: 2, memory: 4, disk: 40, architecture: "x86", prices: eur("5.99") },
40 { id: 5, name: "cx33", cores: 4, memory: 8, disk: 80, architecture: "x86", prices: eur("8.99") },
41 ];
4263 await readPlaces(db, "digitalocean", async (url) => json(String(url).includes("/sizes") ? { sizes: ocean.sizes } : { regions: ocean.regions }), "t");
43 await readPlaces(
44 db,
45 "hetzner",
46 async (url) => {
47 const u = String(url);
48 if (u.includes("/server_types")) return json({ server_types: types });
49 if (u.includes("/datacenters")) return json({ datacenters: [{ location: { name: "nbg1", city: "Nuremberg", country: "DE" }, server_types: { available: [1, 2, 5] } }] });
50 return json({ pricing: { currency: "EUR", volume: { price_per_gb_month: { gross: "0.0572" } }, primary_ips: [{ type: "ipv4", prices: [{ location: "nbg1", price_monthly: { gross: "0.50" } }] }] } });
51 },
52 "t",
53 );
64 await seedHetzner(db);
5465 await refreshRate(db, async () => new Response("<Cube time='2026-11-23'><Cube currency='USD' rate='1.2'/></Cube>", { status: 200 }));
5566 }
test/pinned-ceiling.test.ts +44 −40
@@ -31,13 +31,15 @@ describe("cloud account ceiling", () => {
3131 let dataDir = "";
3232 let app: App;
3333 const calls: string[] = [];
34 let hetznerType = "cx23";
3534 let seq = 1000;
3635
3736 const admin = () => getUserByName(app.db, "alice")!;
3837 const input = (name: string, over: Record<string, unknown> = {}) => ({
3938 name, host: `${name}.forge.test`, target: "digitalocean", account: "main", app: "alice/shop", source: SOURCE, version: V1, config: {}, ...over,
4039 });
40 // Hetzner has no United States place in the fixture's catalog, so a Hetzner forge names one.
41 const hetznerInput = (name: string) => input(name, { target: "hetzner", place: "hetzner:nbg1:cx23" });
42 const setSize = (name: string, size: string) => app.db.run("UPDATE pinned_size SET size = ?1 WHERE pinned_id = (SELECT id FROM pinned_forge WHERE name = ?2)", [size, name]);
4143 const error = (r: unknown) => String((r as { error: unknown }).error);
4244
4345 beforeAll(async () => {
@@ -57,8 +59,6 @@ describe("cloud account ceiling", () => {
5759 const method = init?.method ?? "GET";
5860 calls.push(`${method} ${u.host}${u.pathname}`);
5961 const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status });
60 if (u.pathname === "/v1/server_types") return json({ server_types: [{ id: 9, name: hetznerType, architecture: "x86", memory: 4, prices: [{ location: "nbg1", price_monthly: { gross: "5.0" } }] }] });
61 if (u.pathname === "/v1/datacenters") return json({ datacenters: [{ location: { name: "nbg1" }, server_types: { available: [9] } }] });
6262 if (u.pathname === "/v2/volumes" || u.pathname === "/v1/volumes") return json({ volume: { id: ++seq } }, 201);
6363 // Each machine is made with a throwaway SSH key, deleted after the call (#16218).
6464 if (u.pathname === "/v2/account/keys" || u.pathname === "/v1/ssh_keys") return json({ ssh_key: { id: 4242 } }, 201);
@@ -82,16 +82,18 @@ describe("cloud account ceiling", () => {
8282 test("a forge is priced from the Places catalog, where the drivers order it: euros at the day's rate, rounded up; what it does not list has no price", () => {
8383 const p = priced(app.db);
8484 // DigitalOcean: $12 machine + $1 volume, in dollars as the provider says.
85 expect(p.forge("digitalocean", "s-1vcpu-2gb")).toBe(1300);
85 expect(p.forge("digitalocean:nyc3:s-1vcpu-2gb")).toBe(1300);
8686 // Hetzner cx23 in nbg1: 5.99 + 0.572 (10 GiB) + 0.50 (address) = 7.062 EUR, at 1.2 = 8.4744, up.
87 expect(p.forge("hetzner", "cx23")).toBe(848);
88 expect(p.forge("hetzner", "cx33")).toBe(1208);
87 expect(p.forge("hetzner:nbg1:cx23")).toBe(848);
88 expect(p.forge("hetzner:nbg1:cx33")).toBe(1208);
8989 expect(p.dearest("hetzner")).toBe(1208);
90 expect(p.dearest("hetzner", "nbg1")).toBe(1208);
91 // The place is the whole fact: the same size in another datacenter is not this price.
92 expect(p.forge("hetzner:ash:cx23")).toBeUndefined();
9093 // The catalog's own figure for the same place rounds to the nearest cent; the ceiling's never
9194 // rounds in favour of spending.
9295 expect(keptPlaces(app.db, keptRate(app.db, "EUR")).find((x) => x.id === "hetzner:nbg1:cx23")?.costCents).toBe(847);
93 for (const [cloud, size] of [["digitalocean", "s-9vcpu"], ["hetzner", "cx99"], ["aws", "t4g.small"], ["hetzner", ""]] as const)
94 expect(p.forge(cloud, size)).toBeUndefined();
96 for (const id of ["digitalocean:nyc3:s-9vcpu", "hetzner:nbg1:cx99", "aws:eu:t4g.small", "hetzner:nbg1:"]) expect(p.forge(id)).toBeUndefined();
9597 expect(p.dearest("aws")).toBeUndefined();
9698 });
9799
@@ -100,14 +102,14 @@ describe("cloud account ceiling", () => {
100102 const bare = createApp({ dataDir: dir, port: 0 });
101103 try {
102104 // Never read: nothing has a price.
103 expect(priced(bare.db).forge("digitalocean", "s-1vcpu-2gb")).toBeUndefined();
105 expect(priced(bare.db).forge("digitalocean:nyc3:s-1vcpu-2gb")).toBeUndefined();
104106 await seedPlaces(bare.db);
105 expect(priced(bare.db).forge("hetzner", "cx23")).toBe(848);
107 expect(priced(bare.db).forge("hetzner:nbg1:cx23")).toBe(848);
106108 // The rate gone: a euro place has no dollars, and so no price; a dollar place keeps its own.
107109 bare.db.run("DELETE FROM fx_rate");
108 expect(priced(bare.db).forge("hetzner", "cx23")).toBeUndefined();
110 expect(priced(bare.db).forge("hetzner:nbg1:cx23")).toBeUndefined();
109111 expect(priced(bare.db).dearest("hetzner")).toBeUndefined();
110 expect(priced(bare.db).forge("digitalocean", "s-1vcpu-2gb")).toBe(1300);
112 expect(priced(bare.db).forge("digitalocean:nyc3:s-1vcpu-2gb")).toBe(1300);
111113 } finally {
112114 bare.close();
113115 await rm(dir, { recursive: true, force: true });
@@ -151,41 +153,45 @@ describe("cloud account ceiling", () => {
151153 expect(setCeiling(app, admin(), "digitalocean", "nope", 10)).toMatchObject({ ok: false });
152154 });
153155
154 test("a size with no price is refused, never counted as free", async () => {
155 hetznerType = "cx99";
156 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 () => {
156157 calls.length = 0;
157 const r = await deployPinned(app, admin(), input("odd", { target: "hetzner" }));
158 expect(r).toMatchObject({ ok: false });
158 const unknown = await deployPinned(app, admin(), input("odd", { target: "hetzner", place: "hetzner:nbg1:cx99" }));
159 expect(error(unknown)).toContain("There is no place hetzner:nbg1:cx99 in the catalog");
160 expect(calls).toEqual([]);
161 expect(getPinned(app.db, "odd")).toBeUndefined();
162 // A forge whose recorded place the catalog no longer lists cannot be held to a ceiling, so a
163 // replace is refused with the reading calls only.
164 expect((await deployPinned(app, admin(), hetznerInput("lost"))).ok).toBe(true);
165 setSize("lost", "cx99");
166 calls.length = 0;
167 const r = await updatePinned(app, admin(), "lost", { version: V2 });
159168 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.");
160169 expect(calls.every((c) => c.startsWith("GET"))).toBe(true);
161 hetznerType = "cx23";
170 expect(getPinned(app.db, "lost")).toMatchObject({ state: "running", version: V1 });
162171 });
163172
164173 test("Hetzner is reckoned in dollars at the day's rate, rounded up: a cx23 forge is $8.48", async () => {
165 expect((await deployPinned(app, admin(), input("het", { target: "hetzner" }))).ok).toBe(true);
174 expect((await deployPinned(app, admin(), hetznerInput("het"))).ok).toBe(true);
166175 const o = cloudOverview(app, admin());
167 expect(o.ok && o.value.accounts.find((a) => a.provider === "hetzner")).toMatchObject({ monthlyCents: 848, ceilingDollars: 50 });
176 // "lost" is counted too: its place is no longer listed, so it is reckoned at the dearest the
177 // datacenter has (cx33, $12.08), erring high.
178 expect(o.ok && o.value.accounts.find((a) => a.provider === "hetzner")).toMatchObject({ monthlyCents: 848 + 1208, ceilingDollars: 50 });
179 setSize("lost", "cx23");
180 const o2 = cloudOverview(app, admin());
181 expect(o2.ok && o2.value.accounts.find((a) => a.provider === "hetzner")).toMatchObject({ monthlyCents: 848 * 2 });
168182 });
169183
170 test("a new claim link is a create like any other: over the ceiling it is refused before anything is made", async () => {
171 // "het" runs a cx23 ($8.48). Hetzner now offers only the cx33 ($12.08), so its replacement
172 // would add $3.60, and the account is held to $10.
173 expect(setCeiling(app, admin(), "hetzner", "main", 10).ok).toBe(true);
184 test("a new claim link replaces at the forge's recorded place, so it adds nothing even over a lowered ceiling", async () => {
174185 const was = getPinned(app.db, "het")!;
175 hetznerType = "cx33";
186 expect(setCeiling(app, admin(), "hetzner", "main", 5).ok).toBe(true);
176187 calls.length = 0;
177188 const r = await claimPinned(app, admin(), "het");
178 expect(r).toMatchObject({ ok: false });
179 expect(error(r)).toContain("hetzner/main is held to $10 a month and runs $8.48 now; this would add $3.60, which is over it, so nothing was made.");
180 expect(calls.filter((c) => !c.startsWith("GET"))).toEqual([]);
181 expect(JSON.stringify(r)).not.toContain("first-admin#");
182 expect(getPinned(app.db, "het")).toMatchObject({ claimHash: was.claimHash, remote: was.remote, state: "running" });
183 // With room for it, the same request makes the machine, and the forge is counted at its new size.
189 expect(r.ok).toBe(true);
190 // The server was made where the volume is, at the size the row recorded.
191 const made = calls.find((c) => c === "POST api.hetzner.cloud/v1/servers");
192 expect(made).toBeDefined();
193 expect(getPinned(app.db, "het")).toMatchObject({ datacenter: "nbg1", size: "cx23", volume: was.volume });
184194 expect(setCeiling(app, admin(), "hetzner", "main", 50).ok).toBe(true);
185 expect((await claimPinned(app, admin(), "het")).ok).toBe(true);
186 hetznerType = "cx23";
187 const o = cloudOverview(app, admin());
188 expect(o.ok && o.value.accounts.find((x) => x.provider === "hetzner")).toMatchObject({ monthlyCents: 1208 });
189195 // A forge whose machine is gone and whose volume waits is still counted whole, so finishing
190196 // it adds nothing: it passes a ceiling it already fills.
191197 app.db.run("UPDATE pinned_forge SET remote = '', address = '', state = 'failed' WHERE name = 'two'");
@@ -266,23 +272,21 @@ describe("cloud account ceiling", () => {
266272 });
267273
268274 test("a create refused before anything was changed leaves a running forge running; one that lost its machine is failed", async () => {
269 // Refused at the plan (a size the forge has no price for): nothing was asked of the cloud but
270 // reads.
275 // Refused at the ceiling's check (a place the catalog does not hold): nothing was asked of the
276 // cloud but reads.
271277 expect(getPinned(app.db, "het")).toMatchObject({ state: "running" });
272278 const server = getPinned(app.db, "het")!.remote;
273 hetznerType = "cx99";
279 setSize("het", "cx99");
274280 calls.length = 0;
275281 const refused = await updatePinned(app, admin(), "het", { version: V2 });
276 hetznerType = "cx23";
277282 expect(error(refused)).toContain("has no price for cx99");
278283 expect(calls.filter((c) => !c.startsWith("GET"))).toEqual([]);
279284 // Nothing moved: not the machine, not its state, not the pin, and no change is recorded.
280285 expect(getPinned(app.db, "het")).toMatchObject({ state: "running", remote: server, version: V1 });
281286 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 });
282287 // A new claim link refused the same way leaves it running too.
283 hetznerType = "cx99";
284288 expect((await claimPinned(app, admin(), "het")).ok).toBe(false);
285 hetznerType = "cx23";
289 setSize("het", "cx23");
286290 expect(getPinned(app.db, "het")).toMatchObject({ state: "running", remote: server });
287291
288292 const real = net.fetch;
test/pinned-claim.test.ts +1 −1
@@ -864,7 +864,7 @@ describe("claimed is what the deployed forge says, never what the seller says (#
864864 expect(page()).not.toContain("no access");
865865 // The deploy page says it before anything is sold, once, and points at the buyer's own
866866 // account.
867 const form = String(deployPage([], { name: "", account: "", app: "", source: "", version: "", host: "" }));
867 const form = String(deployPage([], { name: "", account: "", app: "", source: "", version: "", host: "", place: "" }, []));
868868 for (const words of ["boot it into rescue", "snapshot its disk", "gives the host none of that"]) expect(form.split(words).length - 1).toBe(1);
869869 expect(form).not.toContain("no access");
870870 } finally {
test/pinned-harden.test.ts +7 −5
@@ -298,6 +298,8 @@ const row = {
298298 address: "",
299299 state: "",
300300 createdAt: "",
301 datacenter: "nbg1",
302 size: "cx23",
301303 ...forge,
302304 } as Pinned;
303305
@@ -317,7 +319,7 @@ describe("no root password is ever made", () => {
317319
318320 test("DigitalOcean: the droplet is created with a key, and the key is deleted after", async () => {
319321 const { asked, call } = recorder();
320 await digitalocean.createMachine(call, row, "vol-1", undefined);
322 await digitalocean.createMachine(call, row, "vol-1");
321323 expect(asked.map((a) => `${a.method} ${a.path}`)).toEqual([
322324 "POST /account/keys",
323325 "POST /droplets",
@@ -330,7 +332,7 @@ describe("no root password is ever made", () => {
330332
331333 test("Hetzner: the server is created with a key, and the key is deleted after", async () => {
332334 const { asked, call } = recorder();
333 await hetzner.createMachine(call, row, "77", "cx23");
335 await hetzner.createMachine(call, row, "77");
334336 expect(asked.map((a) => `${a.method} ${a.path}`)).toEqual([
335337 "POST /ssh_keys",
336338 "POST /servers",
@@ -343,7 +345,7 @@ describe("no root password is ever made", () => {
343345
344346 test("the private half is never in anything sent", async () => {
345347 const { asked, call } = recorder();
346 await hetzner.createMachine(call, row, "77", "cx23");
348 await hetzner.createMachine(call, row, "77");
347349 expect(JSON.stringify(asked)).not.toMatch(/PRIVATE KEY|BEGIN OPENSSH/);
348350 });
349351
@@ -354,7 +356,7 @@ describe("no root password is ever made", () => {
354356 return call(m, p, b);
355357 };
356358 await expect(
357 hetzner.createMachine(failing, row, "77", "cx23"),
359 hetzner.createMachine(failing, row, "77"),
358360 ).rejects.toThrow("answered 500");
359361 expect(asked.at(-1)).toMatchObject({
360362 method: "DELETE",
@@ -362,7 +364,7 @@ describe("no root password is ever made", () => {
362364 });
363365 const none: Call = async () => ({});
364366 await expect(
365 hetzner.createMachine(none, row, "77", "cx23"),
367 hetzner.createMachine(none, row, "77"),
366368 ).rejects.toThrow("no SSH key");
367369 });
368370 });
test/pinned-hetzner-doors.test.ts +2 −4
@@ -66,8 +66,6 @@ describe("Hetzner at the existing doors", () => {
6666 paths.push(`${u.host} ${method} ${u.pathname}`);
6767 const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status });
6868 if (u.host === "api.hetzner.cloud") {
69 if (u.pathname === "/v1/server_types") return json({ server_types: [{ id: 2, name: "cx23", architecture: "x86", memory: 4, prices: [price("nbg1", "5.99")] }] });
70 if (u.pathname === "/v1/datacenters") return json({ datacenters: [{ location: { name: "nbg1" }, server_types: { available: [2] } }] });
7169 if (u.pathname === "/v1/volumes") return json({ volume: { id: 77 } }, 201);
7270 if (u.pathname === "/v1/ssh_keys" && method === "POST") return json({ ssh_key: { id: 4242 } }, 201);
7371 return json({ server: { id: 501 } }, 201);
@@ -99,7 +97,7 @@ describe("Hetzner at the existing doors", () => {
9997 });
10098
10199 test("a posted hetzner/main deploys to Hetzner", async () => {
102 const r = await post({ ...named("eu"), account: "hetzner/main" });
100 const r = await post({ ...named("eu"), account: "hetzner/main", place: "hetzner:nbg1:cx23" });
103101 // The answer is the page that shows the claim link once, not a redirect.
104102 expect(r.status).toBe(200);
105103 expect(getPinned(app.db, "eu")).toMatchObject({ target: "hetzner", state: "running" });
@@ -126,7 +124,7 @@ describe("Hetzner at the existing doors", () => {
126124 const key = (s: Screen, k: string) => s.key?.({ type: "key", key: k, ctrl: false, alt: false, shift: false });
127125 key(pinnedScreen(f, ctx), "d");
128126 const prompt = pushed[0]!;
129 prompt.paste?.(`tty tty.forge.test hetzner/main alice/shop ${SOURCE} ${V}`);
127 prompt.paste?.(`tty tty.forge.test hetzner/main alice/shop ${SOURCE} ${V} hetzner:nbg1:cx23`);
130128 key(prompt, "enter");
131129 await waitFor(() => getPinned(app.db, "tty")?.state === "running");
132130 expect(getPinned(app.db, "tty")).toMatchObject({ target: "hetzner", state: "running" });
test/pinned-hetzner.test.ts +40 −37
@@ -1,8 +1,8 @@
11 /**
22 * Hetzner Cloud as a pinned-forge target (#16200): a recorded fetch stands in
33 * for api.hetzner.cloud. The shared sequence is proved on DigitalOcean in
4 * pinned-forge.test.ts; here are Hetzner's own calls, the type it picks from
5 * the API, and the same half-way recovery through the same shared code.
4 * pinned-forge.test.ts; here are Hetzner's own calls, made at the place the row records, and the
5 * same half-way recovery through the same shared code.
66 */
77 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
88 import { mkdtemp, rm } from "node:fs/promises";
@@ -11,12 +11,11 @@ import { join } from "node:path";
1111 import { createApp, type App } from "../src/app.ts";
1212 import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts";
1313 import { checkPinned, deployPinned, net, updatePinned } from "../src/actions/pinned.ts";
14 import { LOCATION } from "../src/cloud/hetzner.ts";
1514 import { verify } from "../src/cloud/providers.ts";
1615 import { getPinned } from "../src/core/pinned.ts";
1716 import { createUser, getUserByName } from "../src/core/users.ts";
1817 import { quietLogs } from "./helpers/globals.ts";
19 import { seedPlaces } from "./helpers/places-fixture.ts";
18 import { seedHetzner, seedPlaces } from "./helpers/places-fixture.ts";
2019
2120 quietLogs();
2221
@@ -25,26 +24,19 @@ const V1 = "a".repeat(40);
2524 const V2 = "b".repeat(40);
2625 const SOURCE = "https://forge.example.org/trevato/forge";
2726
28 const price = (gross: string) => [{ location: LOCATION, price_monthly: { gross } }, { location: "ash", price_monthly: { gross: "30.0" } }];
29 const TYPES = [
30 { id: 1, name: "cx22", architecture: "x86", memory: 4, prices: price("4.5") },
31 { id: 2, name: "cx23", architecture: "x86", memory: 4, prices: price("5.99") },
32 { id: 3, name: "cx12", architecture: "x86", memory: 1, prices: price("3.0") },
33 { id: 4, name: "cax11", architecture: "arm", memory: 4, prices: price("3.5") },
34 { id: 5, name: "cx33", architecture: "x86", memory: 8, prices: price("8.99") },
35 ];
27 /** The place a Hetzner forge is deployed at here: the catalog has no United States place to default to. */
28 const PLACE = "hetzner:nbg1:cx23";
3629
3730 describe("hetzner target", () => {
3831 let dataDir = "";
3932 let app: App;
4033 const calls: { method: string; path: string; auth: string | null; body: any }[] = [];
41 let stocked: number[] = [2, 5];
4234 let failServer = 0;
4335 let serverSeq = 500;
4436
4537 const admin = () => getUserByName(app.db, "alice")!;
46 const input = (over: { name?: string; version?: string } = {}) => ({
47 name: "acme", host: `${over.name ?? "acme"}.forge.test`, target: "hetzner", account: "main", app: "alice/shop", source: SOURCE, version: V1, config: { PUBLIC_NAME: "Acme" }, ...over,
38 const input = (over: { name?: string; version?: string; place?: string } = {}) => ({
39 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,
4840 });
4941 const seen = () => calls.map((c) => `${c.method} ${c.path}`);
5042
@@ -66,8 +58,6 @@ describe("hetzner target", () => {
6658 const method = init?.method ?? "GET";
6759 calls.push({ method, path: u.pathname, auth: new Headers(init?.headers).get("authorization"), body: init?.body ? JSON.parse(String(init.body)) : undefined });
6860 const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status });
69 if (u.pathname === "/v1/server_types") return json({ server_types: TYPES });
70 if (u.pathname === "/v1/datacenters") return json({ datacenters: [{ location: { name: LOCATION }, server_types: { available: stocked } }, { location: { name: "ash" }, server_types: { available: [1, 2, 3, 4, 5] } }] });
7161 if (u.pathname === "/v1/volumes") return json({ volume: { id: 77 } }, 201);
7262 if (u.pathname === "/v1/ssh_keys" && method === "POST") return json({ ssh_key: { id: 4242 } }, 201);
7363 if (u.pathname === "/v1/servers" && method === "POST") {
@@ -85,20 +75,20 @@ describe("hetzner target", () => {
8575 await rm(dataDir, { recursive: true, force: true });
8676 });
8777
88 test("deploy reads the types, picks the cheapest CX in stock with 2 GiB in an EU location, and mounts the volume by its id", async () => {
78 test("deploy makes the volume and the server at the recorded place, and mounts the volume by its id", async () => {
8979 const r = await deployPinned(app, admin(), input());
9080 expect(r.ok).toBe(true);
9181 // The last call reads the new server's address, so the answer can name the DNS record.
92 expect(seen()).toEqual(["GET /v1/server_types", "GET /v1/datacenters", "POST /v1/volumes", "POST /v1/ssh_keys", "POST /v1/servers", "DELETE /v1/ssh_keys/4242", "GET /v1/servers/501"]);
82 expect(seen()).toEqual(["POST /v1/volumes", "POST /v1/ssh_keys", "POST /v1/servers", "DELETE /v1/ssh_keys/4242", "GET /v1/servers/501"]);
9383 expect(calls.every((c) => c.auth === `Bearer ${TOKEN}`)).toBe(true);
9484 expect(JSON.stringify(calls.map((c) => c.body))).not.toContain(TOKEN);
95 const [volume, server] = [calls[2]!.body, calls[4]!.body];
96 expect(["nbg1", "fsn1", "hel1"]).toContain(volume.location);
85 const [volume, server] = [calls[0]!.body, calls[2]!.body];
86 expect(volume.location).toBe("nbg1");
9787 expect(server).toMatchObject({ server_type: "cx23", location: volume.location, volumes: [77], automount: true });
9888 expect(server.user_data).toContain("FORGE_APP_DATA=/mnt/HC_Volume_77");
9989 expect(server.user_data).toContain(`checkout --detach ${V1}`);
10090 expect(server.user_data).not.toContain(TOKEN);
101 expect(getPinned(app.db, "acme")).toMatchObject({ target: "hetzner", state: "running", volume: "77", remote: "501" });
91 expect(getPinned(app.db, "acme")).toMatchObject({ target: "hetzner", state: "running", volume: "77", remote: "501", datacenter: "nbg1", size: "cx23" });
10292 });
10393
10494 test("the address is read back from the server", async () => {
@@ -112,14 +102,11 @@ describe("hetzner target", () => {
112102 calls.length = 0;
113103 const r = await updatePinned(app, admin(), "acme", { version: V2 });
114104 expect(r.ok).toBe(true);
115 // The address is read to ask the forge whether it was claimed; what would be ordered is asked
116 // before the pin moves; then the server is replaced.
117 expect(seen()).toEqual([
118 "GET /v1/servers/501",
119 "GET /v1/server_types", "GET /v1/datacenters",
120 "GET /v1/server_types", "GET /v1/datacenters", "DELETE /v1/servers/501", "POST /v1/ssh_keys", "POST /v1/servers", "DELETE /v1/ssh_keys/4242",
121 ]);
105 // The address is read to ask the forge whether it was claimed; whether the recorded place may
106 // be ordered is answered from the catalog, with no call; then the server is replaced.
107 expect(seen()).toEqual(["GET /v1/servers/501", "DELETE /v1/servers/501", "POST /v1/ssh_keys", "POST /v1/servers", "DELETE /v1/ssh_keys/4242"]);
122108 const made = calls.find((c) => c.method === "POST" && c.path === "/v1/servers")!;
109 expect(made.body).toMatchObject({ server_type: "cx23", location: "nbg1" });
123110 expect(made.body.volumes).toEqual([77]);
124111 expect(made.body.user_data).toContain(`checkout --detach ${V2}`);
125112 expect(getPinned(app.db, "acme")).toMatchObject({ volume: "77", remote: "502", version: V2 });
@@ -139,27 +126,43 @@ describe("hetzner target", () => {
139126 expect(getPinned(app.db, "again")).toMatchObject({ state: "running", volume: "77" });
140127 });
141128
142 test("when no type can be ordered, nothing is made and the page is told so", async () => {
129 test("a place sold out at the datacenter is refused, and nothing is called", async () => {
143130 app.db.run("DELETE FROM pinned_forge");
144131 calls.length = 0;
145 stocked = [3, 4];
132 await seedHetzner(app.db, [1, 5]);
146133 const r = await deployPinned(app, admin(), input({ name: "none" }));
147134 expect(r).toMatchObject({ ok: false });
148 expect(String((r as any).error)).toContain("can be ordered in nbg1 right now");
149 expect(seen().every((s) => s.startsWith("GET"))).toBe(true);
150 stocked = [2, 5];
135 expect(String((r as any).error)).toContain("hetzner:nbg1:cx23 cannot be ordered now: sold out at this datacenter right now");
136 expect(calls).toEqual([]);
137 await seedHetzner(app.db);
151138 });
152139
153 test("an Update with no type in stock keeps the running server", async () => {
140 test("an ARM size is listed with its reason and is never ordered", async () => {
141 calls.length = 0;
142 const r = await deployPinned(app, admin(), input({ name: "arm", place: "hetzner:nbg1:cax21" }));
143 expect(r).toMatchObject({ ok: false });
144 expect(String((r as any).error)).toContain("an ARM size; the forge runs on x86 machines only");
145 expect(calls).toEqual([]);
146 });
147
148 test("with no place named and none in the United States, the deploy says so and calls nothing", async () => {
149 calls.length = 0;
150 const r = await deployPinned(app, admin(), input({ name: "nowhere", place: "" }));
151 expect(r).toMatchObject({ ok: false });
152 expect(String((r as any).error)).toContain("no place in the United States");
153 expect(calls).toEqual([]);
154 });
155
156 test("an Update with the recorded place sold out keeps the running server", async () => {
154157 const ok = await deployPinned(app, admin(), input({ name: "keep" }));
155158 expect(ok.ok).toBe(true);
156159 calls.length = 0;
157 stocked = [];
160 await seedHetzner(app.db, []);
158161 const r = await updatePinned(app, admin(), "keep", { version: V2 });
159162 expect(r.ok).toBe(false);
160163 expect(seen().some((s) => s.startsWith("DELETE"))).toBe(false);
161164 expect(getPinned(app.db, "keep")!.remote).not.toBe("");
162 stocked = [2, 5];
165 await seedHetzner(app.db);
163166 });
164167
165168 test("verify is a read of the fixed host with the bearer token, and refuses a bad one", async () => {
test/pinned-place.test.ts added +413
@@ -0,0 +1,413 @@
1 /**
2 * A pinned forge is deployed at a place (#16205): provider, datacenter and size, from the Places
3 * catalog. It is the catalog's default when none is asked for, refused before any provider call
4 * when it is unknown, unorderable or another provider's, recorded on the row, the datacenter of the
5 * volume and the machine alike, and the one every replace orders, whatever the default has become.
6 * The ceiling prices that place and no other.
7 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import {
14 addAccount,
15 allowWrite,
16 net as cloudNet,
17 } from "../src/actions/cloud.ts";
18 import { setCeiling } from "../src/actions/cloud_ceiling.ts";
19 import {
20 claimPinned,
21 deployPinned,
22 deployPlaces,
23 net,
24 updatePinned,
25 } from "../src/actions/pinned.ts";
26 import { spendOf } from "../src/cloud/ceiling.ts";
27 import { readPlaces } from "../src/cloud/places_read.ts";
28 import { getPinned, placeIdOf } from "../src/core/pinned.ts";
29 import { createUser, getUserByName } from "../src/core/users.ts";
30 import { quietLogs } from "./helpers/globals.ts";
31 import { seedPlaces } from "./helpers/places-fixture.ts";
32
33 quietLogs();
34
35 const V1 = "a".repeat(40);
36 const V2 = "b".repeat(40);
37 const SOURCE = "https://forge.example.org/trevato/forge";
38
39 /** DigitalOcean as it answers in production: the plain size is in sfo2, nyc3 has the intel variant. */
40 const ocean = (plainPrice: number) => ({
41 regions: [
42 { slug: "nyc3", available: true },
43 { slug: "sfo2", available: true },
44 { slug: "ams3", available: true },
45 ],
46 sizes: [
47 {
48 slug: "s-1vcpu-2gb",
49 memory: 2048,
50 vcpus: 1,
51 disk: 50,
52 transfer: 2,
53 price_monthly: plainPrice,
54 available: true,
55 regions: ["sfo2", "ams3"],
56 },
57 {
58 slug: "s-1vcpu-2gb-intel",
59 memory: 2048,
60 vcpus: 1,
61 disk: 50,
62 transfer: 2,
63 price_monthly: 14,
64 available: true,
65 regions: ["nyc3"],
66 },
67 {
68 slug: "s-2vcpu-4gb",
69 memory: 4096,
70 vcpus: 2,
71 disk: 80,
72 transfer: 4,
73 price_monthly: 24,
74 available: false,
75 regions: ["sfo2"],
76 },
77 ],
78 });
79
80 describe("a deploy is made at a place", () => {
81 let dataDir = "";
82 let app: App;
83 const calls: { method: string; host: string; path: string; body: any }[] = [];
84 let seq = 1000;
85
86 const admin = () => getUserByName(app.db, "alice")!;
87 const input = (name: string, over: Record<string, unknown> = {}) => ({
88 name,
89 host: `${name}.forge.test`,
90 target: "digitalocean",
91 account: "main",
92 app: "alice/shop",
93 source: SOURCE,
94 version: V1,
95 config: {},
96 ...over,
97 });
98 const error = (r: unknown) => String((r as { error: unknown }).error);
99 const readOcean = (plainPrice: number) =>
100 readPlaces(
101 app.db,
102 "digitalocean",
103 async (url) =>
104 new Response(
105 JSON.stringify(
106 String(url).includes("/sizes")
107 ? { sizes: ocean(plainPrice).sizes }
108 : { regions: ocean(plainPrice).regions },
109 ),
110 { status: 200 },
111 ),
112 "t",
113 );
114 /** The body of the newest call that made `what` (a volume, a droplet, a server). */
115 const made = (what: string) =>
116 calls
117 .filter((c) => c.method === "POST" && c.path.endsWith(`/${what}`))
118 .at(-1)!.body;
119
120 beforeAll(async () => {
121 dataDir = await mkdtemp(join(tmpdir(), "forge-place-"));
122 app = createApp({ dataDir, port: 0 });
123 await seedPlaces(app.db);
124 const user = await createUser(app.db, {
125 origin: "seed",
126 trusted: true,
127 username: "alice",
128 email: "[email protected]",
129 password: "a-good-passphrase",
130 adminIfFirst: true,
131 });
132 if (!user.ok) throw new Error(user.error);
133 cloudNet.fetch = async () =>
134 new Response(
135 JSON.stringify({
136 account: { email: "[email protected]", status: "active" },
137 servers: [],
138 meta: { pagination: { total_entries: 0 } },
139 }),
140 { status: 200 },
141 );
142 for (const [provider, token] of [
143 ["digitalocean", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"],
144 ["hetzner", "hcloud_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9"],
145 ] as const) {
146 const added = await addAccount(app, admin(), provider, "main", token);
147 if (!added.ok) throw new Error(String(added.error));
148 allowWrite(app, admin(), provider, "main", true);
149 }
150 expect(setCeiling(app, admin(), "digitalocean", "main", 500).ok).toBe(true);
151 net.resolve = async () => [];
152 net.fetch = async (url, init) => {
153 const u = new URL(url);
154 const method = init?.method ?? "GET";
155 calls.push({
156 method,
157 host: u.host,
158 path: u.pathname,
159 body: init?.body ? JSON.parse(String(init.body)) : undefined,
160 });
161 const json = (o: unknown, status = 200) =>
162 new Response(JSON.stringify(o), { status });
163 if (u.pathname.endsWith("/volumes"))
164 return json({ volume: { id: ++seq } }, 201);
165 if (
166 u.pathname.endsWith("/account/keys") ||
167 u.pathname.endsWith("/ssh_keys")
168 )
169 return json({ ssh_key: { id: 4242 } }, 201);
170 if (method === "DELETE") return new Response(null, { status: 204 });
171 if (u.pathname.endsWith("/servers"))
172 return json({ server: { id: ++seq } }, 201);
173 return json({ droplet: { id: ++seq } }, 202);
174 };
175 }, 30_000);
176
177 afterAll(async () => {
178 app.close();
179 await rm(dataDir, { recursive: true, force: true });
180 });
181
182 test("a forge from before places were kept is read as the place the drivers once hard-coded, and replaced there", async () => {
183 // The fixture's catalog lists DigitalOcean's s-1vcpu-2gb in nyc3, which is where that forge is.
184 expect((await deployPinned(app, admin(), input("old"))).ok).toBe(true);
185 app.db.run(
186 "DELETE FROM pinned_size WHERE pinned_id = (SELECT id FROM pinned_forge WHERE name = 'old')",
187 );
188 expect(getPinned(app.db, "old")).toMatchObject({
189 datacenter: "nyc3",
190 size: "s-1vcpu-2gb",
191 });
192 calls.length = 0;
193 expect((await updatePinned(app, admin(), "old", { version: V2 })).ok).toBe(
194 true,
195 );
196 expect(made("droplets")).toMatchObject({
197 region: "nyc3",
198 size: "s-1vcpu-2gb",
199 });
200 });
201
202 test("with no place given, the deploy is at the catalog's default for the plan on the account's provider", async () => {
203 await readOcean(12);
204 const r = await deployPinned(app, admin(), input("plain"));
205 expect(r.ok).toBe(true);
206 // The plain size is only in sfo2, which the catalog says: the old constant, nyc3, has no such size.
207 expect(made("droplets")).toMatchObject({
208 region: "sfo2",
209 size: "s-1vcpu-2gb",
210 });
211 expect(getPinned(app.db, "plain")).toMatchObject({
212 datacenter: "sfo2",
213 size: "s-1vcpu-2gb",
214 });
215 // The answer carries it, in the one place a person reads it.
216 expect(r.ok && r.value).toMatchObject({
217 datacenter: "sfo2",
218 size: "s-1vcpu-2gb",
219 });
220 });
221
222 test("the volume and the machine are made in the same datacenter", async () => {
223 calls.length = 0;
224 expect(
225 (
226 await deployPinned(
227 app,
228 admin(),
229 input("pair", { place: "digitalocean:ams3:s-1vcpu-2gb" }),
230 )
231 ).ok,
232 ).toBe(true);
233 expect(made("volumes").region).toBe("ams3");
234 expect(made("droplets")).toMatchObject({
235 region: "ams3",
236 size: "s-1vcpu-2gb",
237 });
238 expect(made("droplets").volumes).toEqual([
239 getPinned(app.db, "pair")!.volume,
240 ]);
241 // Hetzner too: its volume and server take the one location.
242 calls.length = 0;
243 expect(
244 (
245 await deployPinned(
246 app,
247 admin(),
248 input("pairh", { target: "hetzner", place: "hetzner:nbg1:cx23" }),
249 )
250 ).ok,
251 ).toBe(true);
252 expect(made("volumes").location).toBe("nbg1");
253 expect(made("servers")).toMatchObject({
254 location: "nbg1",
255 server_type: "cx23",
256 });
257 });
258
259 test("an unknown, unorderable or other provider's place is refused with no provider call, and leaves no row", async () => {
260 const refusals: [string, string][] = [
261 [
262 "digitalocean:nyc3:s-1vcpu-2gb",
263 "There is no place digitalocean:nyc3:s-1vcpu-2gb in the catalog",
264 ],
265 ["nonsense", "There is no place nonsense in the catalog"],
266 [`digitalocean:sfo2:${"x".repeat(300)}`, "in the catalog"],
267 [
268 "digitalocean:sfo2:s-2vcpu-4gb",
269 "digitalocean:sfo2:s-2vcpu-4gb cannot be ordered now: this size is not offered now",
270 ],
271 [
272 "hetzner:nbg1:cx23",
273 "hetzner:nbg1:cx23 is on hetzner, and this deploy is to digitalocean",
274 ],
275 [
276 "hetzner:nbg1:cax21",
277 "is on hetzner, and this deploy is to digitalocean",
278 ],
279 ];
280 for (const [place, said] of refusals) {
281 calls.length = 0;
282 const r = await deployPinned(app, admin(), input("nope", { place }));
283 expect(r).toMatchObject({ ok: false });
284 expect(error(r)).toContain(said);
285 expect(calls).toEqual([]);
286 expect(getPinned(app.db, "nope")).toBeUndefined();
287 }
288 // The same on a Hetzner account: a DigitalOcean place is not its place.
289 calls.length = 0;
290 const r = await deployPinned(
291 app,
292 admin(),
293 input("nope", {
294 target: "hetzner",
295 place: "digitalocean:sfo2:s-1vcpu-2gb",
296 }),
297 );
298 expect(error(r)).toContain(
299 "is on digitalocean, and this deploy is to hetzner",
300 );
301 expect(calls).toEqual([]);
302 });
303
304 test("the form offers orderable places of the accounts' providers, cheapest first, with the ARM and sold-out ones left out", () => {
305 const offered = deployPlaces(app, ["digitalocean"]).map((p) => p.id);
306 expect(offered).toEqual([
307 "digitalocean:ams3:s-1vcpu-2gb",
308 "digitalocean:sfo2:s-1vcpu-2gb",
309 "digitalocean:nyc3:s-1vcpu-2gb-intel",
310 ]);
311 const hetzner = deployPlaces(app, ["hetzner"]).map((p) => p.id);
312 expect(hetzner).toContain("hetzner:nbg1:cx23");
313 expect(hetzner).not.toContain("hetzner:nbg1:cax21");
314 });
315
316 test("a replace orders the row's recorded place, though the default has since moved", async () => {
317 const was = getPinned(app.db, "plain")!;
318 // sfo2's plain size now costs more than nyc3's intel one: a new deploy would default there.
319 await readOcean(20);
320 calls.length = 0;
321 expect((await deployPinned(app, admin(), input("later"))).ok).toBe(true);
322 expect(made("droplets")).toMatchObject({
323 region: "nyc3",
324 size: "s-1vcpu-2gb-intel",
325 });
326 // The forge deployed before still replaces where its volume is, by Update and by a new link.
327 calls.length = 0;
328 expect(
329 (await updatePinned(app, admin(), "plain", { version: V2 })).ok,
330 ).toBe(true);
331 expect(made("droplets")).toMatchObject({
332 region: "sfo2",
333 size: "s-1vcpu-2gb",
334 volumes: [was.volume],
335 });
336 calls.length = 0;
337 expect((await claimPinned(app, admin(), "plain")).ok).toBe(true);
338 expect(made("droplets")).toMatchObject({
339 region: "sfo2",
340 size: "s-1vcpu-2gb",
341 volumes: [was.volume],
342 });
343 expect(
344 calls.some((c) => c.method === "POST" && c.path.endsWith("/volumes")),
345 ).toBe(false);
346 expect(placeIdOf(getPinned(app.db, "plain")!)).toBe(
347 "digitalocean:sfo2:s-1vcpu-2gb",
348 );
349 await readOcean(12);
350 });
351
352 test("a retry of a failed deploy stays in the datacenter its volume was made in", async () => {
353 const real = net.fetch;
354 net.fetch = async (url, init) =>
355 init?.method === "POST" && new URL(url).pathname === "/v2/droplets"
356 ? new Response("{}", { status: 500 })
357 : real(url, init);
358 try {
359 expect(
360 (
361 await deployPinned(
362 app,
363 admin(),
364 input("retry", { place: "digitalocean:ams3:s-1vcpu-2gb" }),
365 )
366 ).ok,
367 ).toBe(false);
368 } finally {
369 net.fetch = real;
370 }
371 const volume = getPinned(app.db, "retry")!.volume;
372 expect(volume).not.toBe("");
373 // Asked for another datacenter, it says why not; with none asked for it is the same place.
374 expect(
375 error(
376 await deployPinned(
377 app,
378 admin(),
379 input("retry", { place: "digitalocean:sfo2:s-1vcpu-2gb" }),
380 ),
381 ),
382 ).toContain("The volume of the earlier try is in ams3");
383 calls.length = 0;
384 expect((await deployPinned(app, admin(), input("retry"))).ok).toBe(true);
385 expect(calls.some((c) => c.path.endsWith("/volumes"))).toBe(false);
386 expect(made("droplets")).toMatchObject({
387 region: "ams3",
388 volumes: [volume],
389 });
390 });
391
392 test("the ceiling prices the place being made: the dearer place is refused where the default fits", async () => {
393 const spent = spendOf(app.db, "digitalocean", "main").monthlyCents;
394 // Room for one default forge ($13.00) and not for the intel place ($15.00).
395 expect(
396 setCeiling(app, admin(), "digitalocean", "main", spent / 100 + 14).ok,
397 ).toBe(true);
398 calls.length = 0;
399 const dear = await deployPinned(
400 app,
401 admin(),
402 input("dear", { place: "digitalocean:nyc3:s-1vcpu-2gb-intel" }),
403 );
404 expect(error(dear)).toContain(
405 "this would add $15.00, which is over it, so nothing was made",
406 );
407 expect(calls).toEqual([]);
408 expect((await deployPinned(app, admin(), input("cheap"))).ok).toBe(true);
409 expect(spendOf(app.db, "digitalocean", "main").monthlyCents).toBe(
410 spent + 1300,
411 );
412 });
413 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs