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

Hetzner places: read stock from server_types and cities from locations, since /datacenters answers 410 #16509

Merged opened this

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

Merged

sold/hetzner-places → main 0 commits 1 thread · 1 unresolved

  • Merged. sold/hetzner-places was merged into main as 0adf720.

Review

Sign in to review this change.
9 files changed +75 −32
docs/features/cloud.md +1 −1
@@ -23,7 +23,7 @@ Not done: the route only lists. Attaching, rotating and removing stay on the pag
2323
2424 `GET /api/v1/places` lists where a forge can run: provider + datacenter + machine size, each with vCPU, memory, disk, included traffic, city and country, `costCents` (machine + the 10 GiB volume + a public address, US dollars a month), the vendor's own `price` and the rate that converted it, `readAt`, `orderable` and, when not, `why`. Filters: `plan`, `provider`, `country`. `defaults` names each plan's default place and says why; the rule is: the cheapest place in the United States that can be ordered now and meets the plan's minimum, among providers with an account that allows writes (a provider with no such place in the United States falls back to its cheapest place anywhere); `PUT /api/v1/places/pin` (admin) pins one instead.
2525
26 - Prices come from the provider's API (Hetzner `/pricing`, `/server_types`, `/datacenters`; DigitalOcean `/sizes`, `/regions`) and are kept as the provider answered, so the dollars are derived at read time. A failed read keeps the last good one. Typed in by hand, and said so: DigitalOcean's block storage price (its API has none) and its regions' countries.
26 - Prices come from the provider's API (Hetzner `/pricing`, `/server_types`, which carries each size's stock and price for every location, and `/locations` for the city and country; DigitalOcean `/sizes`, `/regions`) and are kept as the provider answered, so the dollars are derived at read time. A failed read keeps the last good one. Typed in by hand, and said so: DigitalOcean's block storage price (its API has none) and its regions' countries.
2727 - Every amount a person sees is dollars. A vendor billing in euro is converted at the European Central Bank's daily reference rate (`src/cloud/rates.ts`, no key), kept with its date; if the fetch fails the last good rate stands and the answer carries `rate.ageDays`. All conversion is `toUsd` in `src/cloud/prices.ts`; money that guards spending rounds `up`.
2828 - A refresh runs when a forge administrator reads the catalog with a write-scoped token and a read is over six hours old; a read-only token gets the kept catalog and starts no vendor call, since every vendor call is audited. One refresh runs at a time, every concurrent read waits on it, and a provider is tried again no sooner than five minutes after its last try, whether or not it answered. A vendor's answer is read to at most 2 MB. No timer yet.
2929 - `PUT /api/v1/places/pin` takes `{plan, place}` (an empty place clears the pin) and answers the validated plan and place; a place id over 200 characters is a `422`. A member is refused (`403` by the admin gate), and a pin is announced as `cloud.place_pinned`, which an admin's web session hears live.
docs/features/deploy-to-hetzner.md +2 −2
@@ -22,7 +22,7 @@ A pinned forge can run in your own Hetzner Cloud project the way it runs on Digi
2222
2323 ## When the place is not orderable
2424
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.
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 location 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.
2626
2727 ## The audit
2828
@@ -30,4 +30,4 @@ Cloud accounts → Audit lists a Hetzner volume attached to no server, and a pow
3030
3131 ## Not checked here
3232
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.
33 The Places catalog reads `/server_types` (each size's `locations[].available` stock and `prices` per location), `/locations` (city and country) and `/pricing` (volume and address). Hetzner removed `/datacenters` on 2026-06-02, so it is not called. Hetzner's server create takes `location`, which the driver sends. A shape that differs leaves the place unlisted, and a deploy to it is refused rather than ordering a guess.
src/cloud/places.ts +16 −12
@@ -60,12 +60,13 @@ const unorderable = (p: Omit<Place, "orderable" | "why">, why: string): Place =>
6060 const ARM_WHY = "an ARM size; the forge runs on x86 machines only";
6161
6262 /**
63 * Hetzner: server types, per-location stock, and the account's pricing. Hetzner bills the account
63 * Hetzner: server types (each carries its stock and price per location), the locations, and the
64 * account's pricing for the volume and address. Hetzner bills the account
6465 * in `pricing.currency`; anything but USD is converted at `rate` and kept beside the dollars. A
6566 * type with no price for a location is not a place there.
6667 */
6768 export function hetznerPlaces(
68 body: { server_types: unknown; datacenters: unknown; pricing: unknown },
69 body: { server_types: unknown; locations: unknown; pricing: unknown },
6970 rate: Rate | undefined,
7071 readAt: string,
7172 ): Place[] {
@@ -73,20 +74,17 @@ export function hetznerPlaces(
7374 const currency = str(pricing.currency, 3).toUpperCase() || "EUR";
7475 const gb = num(pricing.volume?.price_per_gb_month?.gross);
7576 const ipv4 = (loc: string) => num(arr(pricing.primary_ips).find((x) => x?.type === "ipv4")?.prices?.find((q: any) => q?.location === loc)?.price_monthly?.gross);
76 const stocked = new Map<string, Set<number>>();
77 const where = new Map<string, { city: string; country: string }>();
78 for (const d of arr(body.datacenters)) {
79 const name = str(d?.location?.name);
77 // A location is a place only when /locations names it; a deprecated one is listed, not orderable.
78 const where = new Map<string, { city: string; country: string; retired: boolean }>();
79 for (const l of arr(body.locations)) {
80 const name = str(l?.name);
8081 if (!SLUG.test(name)) continue;
81 where.set(name, { city: str(d.location.city), country: str(d.location.country, 2).toUpperCase() });
82 const set = stocked.get(name) ?? new Set<number>();
83 for (const id of arr(d?.server_types?.available)) set.add(Number(id));
84 stocked.set(name, set);
82 where.set(name, { city: str(l.city), country: str(l.country, 2).toUpperCase(), retired: l.deprecation != null });
8583 }
8684 const out: Place[] = [];
8785 for (const t of arr(body.server_types)) {
8886 const size = str(t?.name);
89 if (!SLUG.test(size) || t.deprecated) continue;
87 if (!SLUG.test(size)) continue;
9088 // The machine boots an x86 image and an x86 build of Bun: an ARM size is listed, and says why not.
9189 const arm = t.architecture !== "x86";
9290 for (const pr of arr(t.prices)) {
@@ -94,6 +92,7 @@ export function hetznerPlaces(
9492 const here = where.get(loc);
9593 const machine = num(pr?.price_monthly?.gross);
9694 if (!here || !Number.isFinite(machine)) continue;
95 const stock = arr(t.locations).find((x) => x?.name === loc);
9796 const parts = machine + (Number.isFinite(gb) ? gb * VOLUME_GIB : NaN) + ipv4(loc);
9897 const base = {
9998 id: `hetzner:${loc}:${size}`, provider: "hetzner", datacenter: loc, city: here.city, country: here.country, size,
@@ -111,7 +110,12 @@ export function hetznerPlaces(
111110 continue;
112111 }
113112 const place = { ...base, costCents: price.usdCents, price };
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"));
113 out.push(
114 arm ? unorderable(place, ARM_WHY)
115 : t.deprecation != null || stock?.deprecation != null || here.retired ? unorderable(place, "Hetzner is retiring this size or location")

Add a test for t.deprecation != null (type-level) and for stock undefined; only the per-location deprecation is exercised today.

116 : stock && stock.available !== false ? { ...place, orderable: true, why: "" }
117 : unorderable(place, "sold out at this location right now"),
118 );
115119 }
116120 }
117121 return out;
src/cloud/places_read.ts +2 −2
@@ -31,7 +31,7 @@ const table = (db: Database) => {
3131 const API: Readonly<Record<string, { base: string; paths: Readonly<Record<string, string>> }>> = {
3232 hetzner: {
3333 base: "https://api.hetzner.cloud/v1",
34 paths: { server_types: "/server_types?per_page=50", datacenters: "/datacenters?per_page=50", pricing: "/pricing" },
34 paths: { server_types: "/server_types?per_page=50", locations: "/locations?per_page=50", pricing: "/pricing" },
3535 },
3636 digitalocean: {
3737 base: "https://api.digitalocean.com/v2",
@@ -56,7 +56,7 @@ export async function readPlaces(db: Database, provider: string, f: Fetch, token
5656 body[key] = JSON.parse(new TextDecoder().decode(bytes));
5757 }
5858 const flat = provider === "hetzner"
59 ? { server_types: (body.server_types as any)?.server_types, datacenters: (body.datacenters as any)?.datacenters, pricing: body.pricing }
59 ? { server_types: (body.server_types as any)?.server_types, locations: (body.locations as any)?.locations, pricing: body.pricing }
6060 : { sizes: (body.sizes as any)?.sizes, regions: (body.regions as any)?.regions };
6161 const text = JSON.stringify(flat);
6262 if (text.length > MAX_BODY) return false;
test/helpers/places-fixture.ts +13 −9
@@ -5,14 +5,18 @@ import { refreshRate } from "../../src/cloud/rates.ts";
55 /** What Hetzner and DigitalOcean answer, as much as places read (#16203). */
66 export const hetzner = {
77 server_types: [
8 { id: 1, name: "cpx21", cores: 3, memory: 4, disk: 80, architecture: "x86", prices: [
9 { location: "ash", price_monthly: { gross: "10.00" }, included_traffic: 2 ** 40 },
10 { location: "nbg1", price_monthly: { gross: "5.00" }, included_traffic: 2 ** 43 }] },
11 { id: 2, name: "cpx11", cores: 2, memory: 2, disk: 40, architecture: "x86", prices: [{ location: "ash", price_monthly: { gross: "4.00" } }] },
8 { id: 1, name: "cpx21", cores: 3, memory: 4, disk: 80, architecture: "x86", deprecation: null,
9 locations: [{ id: 3, name: "ash", available: true, recommended: false, deprecation: null }, { id: 2, name: "nbg1", available: true, recommended: false, deprecation: null }],
10 prices: [
11 { location: "ash", price_monthly: { gross: "10.00" }, included_traffic: 2 ** 40 },
12 { location: "nbg1", price_monthly: { gross: "5.00" }, included_traffic: 2 ** 43 }] },
13 { id: 2, name: "cpx11", cores: 2, memory: 2, disk: 40, architecture: "x86", deprecation: null,
14 locations: [{ id: 3, name: "ash", available: false, recommended: false, deprecation: null }],
15 prices: [{ location: "ash", price_monthly: { gross: "4.00" } }] },
1216 ],
13 datacenters: [
14 { location: { name: "ash", city: "Ashburn, VA", country: "us" }, server_types: { available: [1] } },
15 { location: { name: "nbg1", city: "Nuremberg", country: "DE" }, server_types: { available: [1] } },
17 locations: [
18 { id: 3, name: "ash", city: "Ashburn, VA", country: "us" },
19 { id: 2, name: "nbg1", city: "Nuremberg", country: "DE" },
1620 ],
1721 pricing: { pricing: { currency: "EUR", volume: { price_per_gb_month: { gross: "0.05" } }, primary_ips: [{ type: "ipv4", prices: [{ location: "ash", price_monthly: { gross: "0.50" } }, { location: "nbg1", price_monthly: { gross: "0.50" } }] }] } },
1822 };
@@ -38,14 +42,14 @@ export async function seedHetzner(db: Database, available: number[] = [1, 2, 5,
3842 { id: 2, name: "cx23", cores: 2, memory: 4, disk: 40, architecture: "x86", prices: eur("5.99") },
3943 { id: 5, name: "cx33", cores: 4, memory: 8, disk: 80, architecture: "x86", prices: eur("8.99") },
4044 { id: 7, name: "cax21", cores: 4, memory: 8, disk: 80, architecture: "arm", prices: eur("6.49") },
41 ];
45 ].map((t) => ({ ...t, deprecation: null, locations: [{ id: 2, name: "nbg1", available: available.includes(t.id), recommended: false, deprecation: null }] }));
4246 await readPlaces(
4347 db,
4448 "hetzner",
4549 async (url) => {
4650 const u = String(url);
4751 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 } }] });
52 if (u.includes("/locations")) return json({ locations: [{ id: 2, name: "nbg1", city: "Nuremberg", country: "DE" }] });
4953 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" } }] }] } });
5054 },
5155 "t",
test/pinned-hetzner.test.ts +1 −1
@@ -133,7 +133,7 @@ describe("hetzner target", () => {
133133 await seedHetzner(app.db, [1, 5]);
134134 const r = await deployPinned(app, admin(), input({ name: "none" }));
135135 expect(r).toMatchObject({ ok: false });
136 expect(String((r as any).error)).toContain("hetzner:nbg1:cx23 cannot be ordered now: sold out at this datacenter right now");
136 expect(String((r as any).error)).toContain("hetzner:nbg1:cx23 cannot be ordered now: sold out at this location right now");
137137 expect(calls).toEqual([]);
138138 await seedHetzner(app.db);
139139 });
test/places-api.test.ts +3 −3
@@ -30,12 +30,12 @@ net.fetch = async (url) => {
3030 ecbCalls++;
3131 return new Response(ECB);
3232 }
33 if (!u.includes("api.hetzner.cloud/v1/") || u.includes("/locations")) return new Response("{}");
33 if (!u.includes("api.hetzner.cloud/v1/")) return new Response("{}");
3434 hetznerCalls++;
3535 await slow;
3636 if (hetznerDown) return new Response("down", { status: 500 });
3737 const j = (v: unknown) => new Response(JSON.stringify(v));
38 return u.includes("server_types") ? j({ server_types: hetzner.server_types }) : u.includes("datacenters") ? j({ datacenters: hetzner.datacenters }) : j(hetzner.pricing);
38 return u.includes("server_types") ? j({ server_types: hetzner.server_types }) : u.includes("/locations") ? j({ locations: hetzner.locations }) : j(hetzner.pricing);
3939 };
4040
4141 describe("places over HTTP", () => {
@@ -95,7 +95,7 @@ describe("places over HTTP", () => {
9595 await new Promise((r) => setImmediate(r));
9696 release();
9797 const bodies = await Promise.all((await Promise.all(reads)).map((r) => r.json() as Promise<any>));
98 expect(hetznerCalls).toBe(3); // one refresh: server_types, datacenters, pricing — once
98 expect(hetznerCalls).toBe(3); // one refresh: server_types, locations, pricing — once
9999 expect(ecbCalls).toBe(1);
100100 expect(bodies.every((b) => b.items.length > 0)).toBe(true);
101101 expect(isStale(app)).toBe(false);
test/places.test.ts +36 −1
@@ -80,6 +80,41 @@ describe("places from the providers' answers", () => {
8080 });
8181 });
8282
83 describe("the catalog of 2026-11 (no /datacenters)", () => {
84 const cx23 = {
85 id: 2, name: "cx23", architecture: "x86", cores: 2, memory: 4, disk: 40, category: "cost_optimized", deprecation: null,
86 locations: [{ id: 2, name: "nbg1", available: false, recommended: false, deprecation: null }],
87 prices: [{ location: "nbg1", price_monthly: { gross: "6.4900" } }],
88 };
89 const cpx22 = { ...cx23, id: 3, name: "cpx22", prices: [{ location: "nbg1", price_monthly: { gross: "7.0000" } }, { location: "ash", price_monthly: { gross: "9.0000" } }],
90 locations: [{ id: 2, name: "nbg1", available: true, recommended: false, deprecation: null }, { id: 3, name: "ash", available: true, recommended: false, deprecation: { announced: "x", unavailable_after: "y" } }] };
91 const body = { server_types: [cx23, cpx22], locations: hetzner.locations, pricing: hetzner.pricing };
92 test("stock, price and city come from server_types and locations; a deprecation is not orderable", () => {
93 const h = hetznerPlaces(body, EUR, "x");
94 expect(h.find((p) => p.id === "hetzner:nbg1:cx23")).toMatchObject({ orderable: false, city: "Nuremberg" });
95 expect(h.find((p) => p.id === "hetzner:nbg1:cx23")!.why).toContain("sold out at this location");
96 expect(h.find((p) => p.id === "hetzner:nbg1:cpx22")!.orderable).toBe(true);
97 expect(h.find((p) => p.id === "hetzner:ash:cpx22")).toMatchObject({ orderable: false, country: "US" });
98 });
99 test("an old kept body with datacenters and no locations lists nothing and does not throw", () => {
100 const old = { server_types: [cx23], datacenters: [{ location: { name: "nbg1" }, server_types: { available: [2] } }], pricing: hetzner.pricing };
101 expect(hetznerPlaces(old as any, EUR, "x")).toEqual([]);
102 });
103 test("the read needs only server_types, locations and pricing; /datacenters answering 410 changes nothing", async () => {
104 const db = new Database(":memory:");
105 const asked: string[] = [];
106 const f = async (u: string) => {
107 asked.push(u);
108 if (u.includes("/datacenters")) return new Response('{"error":{"code":"deprecated_api_endpoint"}}', { status: 410 });
109 return reply(u.includes("server_types") ? { server_types: [cx23, cpx22] } : u.includes("/locations") ? { locations: hetzner.locations } : hetzner.pricing);
110 };
111 expect(await readPlaces(db, "hetzner", f as any, "t")).toBe(true);
112 expect(asked.some((u) => u.includes("datacenters"))).toBe(false);
113 const eu = keptPlaces(db, EUR).filter((p) => p.orderable && p.country !== "US").sort((a, b) => a.costCents - b.costCents)[0];
114 expect(eu?.id).toBe("hetzner:nbg1:cpx22");
115 });
116 });
117
83118 describe("the default rule", () => {
84119 const all: Place[] = [...hetznerPlaces(hetzner, EUR, "x"), ...digitaloceanPlaces(ocean, "x")];
85120 const both = new Set(["hetzner", "digitalocean"]);
@@ -104,7 +139,7 @@ describe("the default rule", () => {
104139 describe("a stale provider keeps its last read", () => {
105140 test("a failing provider changes nothing, and a moved rate re-does the dollars", async () => {
106141 const db = new Database(":memory:");
107 const ok = async (u: string) => reply(u.includes("server_types") ? { server_types: hetzner.server_types } : u.includes("datacenters") ? { datacenters: hetzner.datacenters } : hetzner.pricing);
142 const ok = async (u: string) => reply(u.includes("server_types") ? { server_types: hetzner.server_types } : u.includes("/locations") ? { locations: hetzner.locations } : hetzner.pricing);
108143 expect(await readPlaces(db, "hetzner", ok as any, "t", new Date("2026-11-24T00:00:00Z"))).toBe(true);
109144 expect(await readPlaces(db, "hetzner", async () => new Response("no", { status: 500 }), "t")).toBe(false);
110145 const before = keptPlaces(db, EUR).find((p) => p.id === "hetzner:ash:cpx21")!;
test/tui-places.test.ts +1 −1
@@ -35,7 +35,7 @@ beforeAll(async () => {
3535 alice = await make("alice", true);
3636 bob = await make("bob", false);
3737 const j = (v: unknown) => new Response(JSON.stringify(v));
38 const ok: Fetch = async (u) => j(u.includes("server_types") ? { server_types: hetzner.server_types } : u.includes("datacenters") ? { datacenters: hetzner.datacenters } : hetzner.pricing);
38 const ok: Fetch = async (u) => j(u.includes("server_types") ? { server_types: hetzner.server_types } : u.includes("/locations") ? { locations: hetzner.locations } : hetzner.pricing);
3939 await readPlaces(forge.db, "hetzner", ok, "t");
4040 forge.db.run("CREATE TABLE IF NOT EXISTS fx_rate (currency TEXT PRIMARY KEY, usd_per REAL NOT NULL, date TEXT NOT NULL, fetched_at TEXT NOT NULL)");
4141 forge.db.run("INSERT INTO fx_rate VALUES ('EUR', 1.08, '2026-11-24', '2026-11-24T00:00:00Z')");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs