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

Places: one catalog of where a forge can live, with its datacenter and its re… #16241

Merged opened this in answer to

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

Merged

scout/forge:scout/16203-places-one-catalog-of-where-a-forge-can → main 0 commits fork

  • Merged. scout/16203-places-one-catalog-of-where-a-forge-can was merged into main as d9bac79.

Review

Sign in to review this change.
26 files changed +1205 −5
AGENTS.md +2
@@ -92,3 +92,5 @@ A pull that changes code under `src/` adds or edits a `test/*.test.ts` too, or s
9292
9393 A pull that adds a page (`src/web/pages/*.ts`), an MCP tool (`src/http/mcp/tools/*.ts`) or a settings module (`src/settings/*.ts`) has a commit line `Replaces: <what it takes the place of>` or `Replaces: nothing, <why>` (#14249, `src/kernel/replaces.ts`); `bun scripts/gate.ts` says it as a note, never a refusal, and the reviewer holds the pull to that line.
9494 `src/release/shipped_held.ts`: `heldShipped`, per forge, the public changelog answer (`shippedHeld`, which `GET /api/v1/changelog` answers from; the page, feeds and MCP walk fresh) held 60 s per `?repo=` value (20 at most) so the first call and the second share one git walk (#15631); `recordRelease`, `recordAppRelease` and `setReleaseTests` drop it (`forgetShipped`) so a release is never served stale; a walk that fails is not held; the route names the phase `shipped` in `server-timing` (`desc="hit"` when held); gone on restart.
95
96 `src/actions/places_refresh.ts`: `running`, the one catalog refresh in flight per forge database (#16203), so concurrent admin reads wait on it; at most one per forge, gone on restart. Its terminal door is `src/tui/screens/places.ts` (`p` pins; `pinPlace` gives the API and the terminal the same gate and the `cloud.place_pinned` event).
docs/features/cloud.md +14
@@ -18,3 +18,17 @@ curl -H "authorization: Bearer $FORGE_TOKEN" "$FORGE_URL/api/v1/cloud/accounts"
1818 Answers: `401` with no signed-in user, `403` for a read-only token (every vendor call is audited, so listing is a write-scoped act), `404` for anyone who is not a forge admin.
1919
2020 Not done: the route only lists. Attaching, rotating and removing stay on the page and in the terminal, where the token can be typed masked.
21
22 ## Places and prices in US dollars (#16203)
23
24 `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; `PUT /api/v1/places/pin` (admin) pins one instead.
25
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.
27 - 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`.
28 - 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.
29 - `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.
30 - Each item carries `priceNote`, the curious path's sentence, such as `€5.99 at 1.08 on 24 Nov`; empty when nothing was converted.
31
32 **In the terminal:** the palette's *Places* (`src/tui/screens/places.ts`) shows the rule, each plan's default and why, and every place by price in dollars. Anyone signed in reads it; a forge admin who is a person also presses `p` to pin a plan (plan, then place id; empty clears) through `pinPlace`, the same act as the API. Opening it as an admin refreshes a stale catalog first.
33
34 Not done: deploying by place id, the buyer's "Choose where it runs" disclosure and the owner's margin page; they build on this catalog.
forge.json +1
@@ -8,6 +8,7 @@
88 "api.cloudflare.com",
99 "api.digitalocean.com",
1010 "api.hetzner.cloud",
11 "www.ecb.europa.eu",
1112 "api.fly.io",
1213 "api.backblazeb2.com",
1314 "api.vercel.com",
src/actions/places.ts added +74
@@ -0,0 +1,74 @@
1 /**
2 * Places (#16203): the catalog a buyer reads, shaped from the last good provider reads and the last
3 * good dollar rate, and the admin's pin. Reading the providers again is `places_refresh.ts`.
4 */
5
6 import type { App } from "../app.ts";
7 import { DEFAULT_RULE, PLAN_MINIMUMS, chooseDefault, isPlan, type PlanName, type Place } from "../cloud/places.ts";
8 import { keptPlaces, pinOf, setPin } from "../cloud/places_read.ts";
9 import { conversionNote } from "../cloud/prices.ts";
10 import { keptRate, rateAgeDays } from "../cloud/rates.ts";
11 import { listCloudAccounts } from "../core/cloud_account.ts";
12 import type { User } from "../core/users.ts";
13 import { err, ok, type Result } from "../kernel/result.ts";
14
15 const PLANS = Object.keys(PLAN_MINIMUMS) as PlanName[];
16 const COUNTRY = /^[A-Za-z]{2}$/;
17 const WORD = /^[a-z0-9_-]{1,32}$/;
18
19 export interface PlacesQuery {
20 readonly plan?: string | undefined;
21 readonly provider?: string | undefined;
22 readonly country?: string | undefined;
23 }
24
25 export interface Catalog {
26 readonly items: readonly (Place & { defaultFor: PlanName[]; priceNote: string })[];
27 readonly defaults: Record<PlanName, { placeId: string | null; reason: string }>;
28 readonly rule: string;
29 readonly currency: "USD";
30 readonly rate: { currency: string; usdPer: number; date: string; ageDays: number } | null;
31 readonly next_cursor: null;
32 }
33
34 export function placesCatalog(app: App, q: PlacesQuery, now = new Date()): Result<Catalog, string> {
35 if (q.plan !== undefined && !isPlan(q.plan)) return err("plan must be small, medium or large");
36 if (q.provider !== undefined && !WORD.test(q.provider)) return err("provider is not a provider id");
37 if (q.country !== undefined && !COUNTRY.test(q.country)) return err("country is a two-letter code, like US");
38 const rate = keptRate(app.db, "EUR");
39 const all = keptPlaces(app.db, rate);
40 const writers = new Set(listCloudAccounts(app.db).filter((a) => a.writeAllowed).map((a) => a.provider as string));
41 const defaults = Object.fromEntries(PLANS.map((p) => {
42 const c = chooseDefault(all, p, writers, pinOf(app.db, p));
43 return [p, { placeId: c.place?.id ?? null, reason: c.reason }];
44 })) as Record<PlanName, { placeId: string | null; reason: string }>;
45 const plan = q.plan as PlanName | undefined;
46 const shown = all.filter((p) =>
47 (!q.provider || p.provider === q.provider) && (!q.country || p.country === q.country.toUpperCase()) &&
48 (!plan || (p.memoryMiB >= PLAN_MINIMUMS[plan].memoryMiB && p.vcpu >= PLAN_MINIMUMS[plan].vcpu && p.diskGiB >= PLAN_MINIMUMS[plan].diskGiB)));
49 const isDefault = (p: Place): PlanName[] => PLANS.filter((n) => defaults[n].placeId === p.id);
50 return ok({
51 items: shown.map((p) => ({ ...p, defaultFor: isDefault(p), priceNote: conversionNote(p.price) })),
52 defaults,
53 rule: DEFAULT_RULE,
54 currency: "USD",
55 rate: rate ? { currency: rate.currency, usdPer: rate.usdPer, date: rate.date, ageDays: rateAgeDays(rate, now) } : null,
56 next_cursor: null,
57 });
58 }
59
60 /** An admin who is a person may pin a default; an agent's token may not. */
61 export const mayPin = (user: Pick<User, "isAdmin" | "kind"> | null | undefined): boolean => user?.isAdmin === true && user.kind !== "agent";
62
63 /**
64 * Pin a plan's default place, or clear the pin with an empty id. The page, the API and the
65 * terminal all pin here; the event is what a viewer's page follows. An error is `not_found` for
66 * who may not, or a sentence.
67 */
68 export function pinPlace(app: App, who: User | null | undefined, plan: unknown, id: string): Result<{ plan: PlanName; place: string }, string> {
69 if (!who || !mayPin(who)) return err("not_found");
70 const bad = setPin(app.db, plan, id, keptRate(app.db, "EUR"));
71 if (bad !== undefined) return err(bad);
72 app.bus.append({ kind: "cloud.place_pinned", actorId: who.id, payload: { plan: plan as string, place: id } });
73 return ok({ plan: plan as PlanName, place: id });
74 }
src/actions/places_refresh.ts added +70
@@ -0,0 +1,70 @@
1 /**
2 * Places (#16203), the refresh: read the providers and the dollar rate again. Nothing else here
3 * calls a provider, and a failed call changes nothing. One refresh runs at a time per forge and
4 * every caller that arrives meanwhile waits on that one; a provider is asked again no sooner than
5 * `RETRY_MS` after its last try, whether or not it answered.
6 */
7
8 import type { App } from "../app.ts";
9 import { gatedFetch } from "../cloud/gate.ts";
10 import { LISTED, RETRY_MS, STALE_MS, noteTry, readPlaces, readTimes, triedTimes } from "../cloud/places_read.ts";
11 import { refreshRate } from "../cloud/rates.ts";
12 import { listCloudAccounts, secretNameOf } from "../core/cloud_account.ts";
13 import { resolveSecrets } from "../core/secret_store.ts";
14 import type { User } from "../core/users.ts";
15 import { net } from "./cloud.ts";
16
17 const listed = (provider: string): boolean => (LISTED as readonly string[]).includes(provider);
18
19 /** The refresh in flight for each forge's database, if any. */
20 const running = new WeakMap<object, Promise<void>>();
21
22 /**
23 * True when a refresh is due: a listed provider's last read is stale and it was not tried within
24 * `RETRY_MS`.
25 */
26 export function isStale(app: App, now = Date.now()): boolean {
27 const read = readTimes(app.db);
28 const tried = triedTimes(app.db);
29 return listCloudAccounts(app.db).some((a) => {
30 if (!listed(a.provider)) return false;
31 if (now - Date.parse(read[a.provider] ?? "") < STALE_MS) return false;
32 return !(now - Date.parse(tried[a.provider] ?? "") < RETRY_MS);
33 });
34 }
35
36 async function run(app: App, who: User): Promise<void> {
37 await refreshRate(app.db, net.fetch);
38 const accounts = listCloudAccounts(app.db).filter((a) => listed(a.provider));
39 const tried = triedTimes(app.db);
40 const seen = new Set<string>();
41 for (const a of accounts) {
42 // Each provider is read once a round, through its first account.
43 if (seen.has(a.provider)) continue;
44 if (Date.now() - Date.parse(tried[a.provider] ?? "") < RETRY_MS) continue;
45 seen.add(a.provider);
46 noteTry(app.db, a.provider);
47 const secret = secretNameOf(a.provider, a.name);
48 const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: who.id, run: "places:read" })[secret];
49 if (token === undefined) continue;
50 await readPlaces(app.db, a.provider, gatedFetch(app.db, { provider: a.provider, account: a.name }, "places:read", net.fetch), token);
51 }
52 }
53
54 /** Read the providers and the rate again; each failure leaves its last good read standing. */
55 export function refreshCatalog(app: App, who: User): Promise<void> {
56 const flying = running.get(app.db);
57 if (flying) return flying;
58 const p = run(app, who).finally(() => running.delete(app.db));
59 running.set(app.db, p);
60 return p;
61 }
62
63 /**
64 * The refresh a read waits for: the one in flight, or a new one when a refresh is due; nothing
65 * otherwise. A failure is swallowed, since the last good read stands.
66 */
67 export async function refreshIfDue(app: App, who: User): Promise<void> {
68 if (!running.has(app.db) && !isStale(app)) return;
69 await refreshCatalog(app, who).catch(() => undefined);
70 }
src/cloud/places.ts added +186
@@ -0,0 +1,186 @@
1 /**
2 * Places (#16203): where a forge can live. A place is provider + datacenter + machine size, with
3 * what it holds, what it costs a month in US dollars and whether it can be ordered now. The
4 * functions here take what a provider's API answered and return plain places; reading the API and
5 * keeping the last good read is places_read.ts. The default for a plan is one rule, written in
6 * `DEFAULT_RULE` so the page can print it as it is.
7 */
8
9 import { toUsd, type Price, type Rate } from "./prices.ts";
10
11 export type PlanName = "small" | "medium" | "large";
12
13 /** The least machine each plan needs: memory in MiB, vCPUs, disk in GiB. */
14 export const PLAN_MINIMUMS: Readonly<Record<PlanName, { readonly memoryMiB: number; readonly vcpu: number; readonly diskGiB: number }>> = {
15 small: { memoryMiB: 2048, vcpu: 1, diskGiB: 20 },
16 medium: { memoryMiB: 4096, vcpu: 2, diskGiB: 40 },
17 large: { memoryMiB: 8192, vcpu: 4, diskGiB: 80 },
18 };
19 export const isPlan = (v: unknown): v is PlanName => v === "small" || v === "medium" || v === "large";
20
21 export const DEFAULT_RULE =
22 "The cheapest place in the United States that can be ordered now and meets the plan's minimum, among cloud accounts that allow writes.";
23
24 /** The data volume every forge gets, GiB. */
25 export const VOLUME_GIB = 10;
26
27 export interface Place {
28 /** Stable: provider:datacenter:size. */
29 readonly id: string;
30 readonly provider: string;
31 readonly datacenter: string;
32 readonly city: string;
33 /** ISO 3166 alpha-2, upper case; empty when the provider's API does not say and none is known. */
34 readonly country: string;
35 readonly size: string;
36 readonly vcpu: number;
37 readonly memoryMiB: number;
38 readonly diskGiB: number;
39 readonly trafficGiB: number;
40 /** Machine + the forge's volume + a public address, US dollar cents a month. */
41 readonly costCents: number;
42 /** The vendor's own figure and the rate that made the dollars, for the curious path. */
43 readonly price: Price;
44 /** Components the provider's API does not price, so a person is not told they are included. */
45 readonly assumed: readonly string[];
46 readonly readAt: string;
47 readonly orderable: boolean;
48 /** Why not, in words a person can read; empty when orderable. */
49 readonly why: string;
50 }
51
52 const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : typeof v === "string" && v !== "" && Number.isFinite(Number(v)) ? Number(v) : NaN);
53 const str = (v: unknown, max = 64): string => (typeof v === "string" ? v.slice(0, max) : "");
54 const arr = (v: unknown): any[] => (Array.isArray(v) ? v : []);
55 const SLUG = /^[a-z0-9][a-z0-9._-]{0,40}$/;
56
57 const unorderable = (p: Omit<Place, "orderable" | "why">, why: string): Place => ({ ...p, orderable: false, why });
58
59 /**
60 * Hetzner: server types, per-location stock, and the account's pricing. Hetzner bills the account
61 * in `pricing.currency`; anything but USD is converted at `rate` and kept beside the dollars. A
62 * type with no price for a location is not a place there.
63 */
64 export function hetznerPlaces(
65 body: { server_types: unknown; datacenters: unknown; pricing: unknown },
66 rate: Rate | undefined,
67 readAt: string,
68 ): Place[] {
69 const pricing: any = (body.pricing as any)?.pricing ?? body.pricing ?? {};
70 const currency = str(pricing.currency, 3).toUpperCase() || "EUR";
71 const gb = num(pricing.volume?.price_per_gb_month?.gross);
72 const ipv4 = (loc: string) => num(arr(pricing.primary_ips).find((x) => x?.type === "ipv4")?.prices?.find((q: any) => q?.location === loc)?.price_monthly?.gross);
73 const stocked = new Map<string, Set<number>>();
74 const where = new Map<string, { city: string; country: string }>();
75 for (const d of arr(body.datacenters)) {
76 const name = str(d?.location?.name);
77 if (!SLUG.test(name)) continue;
78 where.set(name, { city: str(d.location.city), country: str(d.location.country, 2).toUpperCase() });
79 const set = stocked.get(name) ?? new Set<number>();
80 for (const id of arr(d?.server_types?.available)) set.add(Number(id));
81 stocked.set(name, set);
82 }
83 const out: Place[] = [];
84 for (const t of arr(body.server_types)) {
85 const size = str(t?.name);
86 if (!SLUG.test(size) || t.architecture !== "x86" || t.deprecated) continue;
87 for (const pr of arr(t.prices)) {
88 const loc = str(pr?.location);
89 const here = where.get(loc);
90 const machine = num(pr?.price_monthly?.gross);
91 if (!here || !Number.isFinite(machine)) continue;
92 const parts = machine + (Number.isFinite(gb) ? gb * VOLUME_GIB : NaN) + ipv4(loc);
93 const base = {
94 id: `hetzner:${loc}:${size}`, provider: "hetzner", datacenter: loc, city: here.city, country: here.country, size,
95 vcpu: num(t.cores), memoryMiB: Math.round(num(t.memory) * 1024), diskGiB: num(t.disk),
96 trafficGiB: Math.round(num(pr.included_traffic ?? t.included_traffic) / 2 ** 30) || 0, readAt, assumed: [] as string[],
97 };
98 let price: Price;
99 try {
100 price = toUsd(parts, currency, rate);
101 } catch {
102 // No price for a part, or no rate for the currency: the place is listed, not orderable, and
103 // says why.
104 const fallback: Price = { usdCents: 0, vendorAmount: Number.isFinite(machine) ? machine : 0, vendorCurrency: currency };
105 out.push(unorderable({ ...base, costCents: 0, price: fallback }, Number.isFinite(parts) ? `no ${currency} to dollars rate has been read yet` : "the provider gave no price for every part"));
106 continue;
107 }
108 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"));
110 }
111 }
112 return out;
113 }
114
115 /** DigitalOcean's API names a region but not its country; this is the only typed-in part. */
116 const DO_WHERE: Readonly<Record<string, { city: string; country: string }>> = {
117 nyc1: { city: "New York", country: "US" }, nyc2: { city: "New York", country: "US" }, nyc3: { city: "New York", country: "US" },
118 sfo1: { city: "San Francisco", country: "US" }, sfo2: { city: "San Francisco", country: "US" }, sfo3: { city: "San Francisco", country: "US" },
119 atl1: { city: "Atlanta", country: "US" }, tor1: { city: "Toronto", country: "CA" }, ams3: { city: "Amsterdam", country: "NL" },
120 fra1: { city: "Frankfurt", country: "DE" }, lon1: { city: "London", country: "GB" }, sgp1: { city: "Singapore", country: "SG" },
121 blr1: { city: "Bangalore", country: "IN" }, syd1: { city: "Sydney", country: "AU" },
122 };
123 /**
124 * DigitalOcean's block storage list price, USD per GiB a month; its API has no price for volumes.
125 */
126 export const DO_VOLUME_USD_PER_GIB = 0.1;
127
128 /**
129 * DigitalOcean: sizes carry their own USD price, regions and availability; the shared `s-` line
130 * only.
131 */
132 export function digitaloceanPlaces(body: { sizes: unknown; regions: unknown }, readAt: string): Place[] {
133 const open = new Set<string>(arr(body.regions).filter((r) => r?.available === true).map((r) => str(r.slug)));
134 const out: Place[] = [];
135 for (const s of arr(body.sizes)) {
136 const size = str(s?.slug);
137 const machine = num(s?.price_monthly);
138 if (!/^s-/.test(size) || !SLUG.test(size) || !Number.isFinite(machine)) continue;
139 for (const slug of arr(s.regions).map((r) => str(r))) {
140 const here = DO_WHERE[slug];
141 if (!SLUG.test(slug)) continue;
142 const price = toUsd(machine + DO_VOLUME_USD_PER_GIB * VOLUME_GIB, "USD", undefined);
143 const base = {
144 id: `digitalocean:${slug}:${size}`, provider: "digitalocean", datacenter: slug, city: here?.city ?? slug, country: here?.country ?? "",
145 size, vcpu: num(s.vcpus), memoryMiB: num(s.memory), diskGiB: num(s.disk), trafficGiB: Math.round(num(s.transfer) * 1024) || 0,
146 costCents: price.usdCents, price, assumed: ["volume"] as string[], readAt,
147 };
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"));
149 }
150 }
151 return out;
152 }
153
154 export const meets = (p: Place, plan: PlanName): boolean => {
155 const m = PLAN_MINIMUMS[plan];
156 return p.memoryMiB >= m.memoryMiB && p.vcpu >= m.vcpu && p.diskGiB >= m.diskGiB;
157 };
158
159 export interface Chosen {
160 readonly place: Place | undefined;
161 /** One sentence, in words a buyer reads: where it will run and why. */
162 readonly reason: string;
163 }
164
165 /**
166 * The default place for a plan. A pin wins when it names an orderable place that meets the plan;
167 * otherwise the cheapest orderable US place meeting the minimum among `writers` (providers with an
168 * attached account that allows writes); ties go to the lower id so the answer never flickers.
169 */
170 export function chooseDefault(places: readonly Place[], plan: PlanName, writers: ReadonlySet<string>, pin?: string): Chosen {
171 const live = places.filter((p) => p.orderable && meets(p, plan) && writers.has(p.provider));
172 const pinned = pin ? live.find((p) => p.id === pin) : undefined;
173 if (pinned) return { place: pinned, reason: `Runs in ${where(pinned)}: the owner chose this place.` };
174 const best = live
175 .filter((p) => p.country === "US")
176 .sort((a, b) => a.costCents - b.costCents || a.id.localeCompare(b.id))[0];
177 if (best) return { place: best, reason: `Runs in ${where(best)}: the cheapest place in the United States that can be ordered now.` };
178 return {
179 place: undefined,
180 reason: writers.size === 0
181 ? "Nowhere can be ordered: no cloud account that allows writes is attached."
182 : "Nowhere can be ordered: no place in the United States that can be ordered now meets this plan.",
183 };
184 }
185
186 const where = (p: Place) => `${p.city}, ${p.country || p.datacenter}`;
src/cloud/places_read.ts added +123
@@ -0,0 +1,123 @@
1 /**
2 * Reading places from a provider and keeping the last good read (#16203). What is stored is the
3 * provider's own answer, not the dollars: the catalog is derived from it at read time with the rate
4 * that stands, so a moved rate re-does every conversion without another call to the provider. A
5 * read that fails leaves the previous one in place.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { digitaloceanPlaces, hetznerPlaces, isPlan, type PlanName, type Place } from "./places.ts";
10 import type { Rate } from "./prices.ts";
11 import { readCapped } from "../spawn/bounded_read.ts";
12 import type { Fetch } from "./providers.ts";
13
14 /** A read older than this is refreshed the next time an admin looks. */
15 export const STALE_MS = 6 * 3_600_000;
16 /** Providers whose API lists places. */
17 export const LISTED = ["digitalocean", "hetzner"] as const;
18 const MAX_BODY = 2_000_000;
19
20 /** A failing provider is asked again no sooner than this. */
21 export const RETRY_MS = 5 * 60_000;
22 /** The longest a place id can be; a longer one is no place. */
23 export const MAX_ID = 200;
24
25 const table = (db: Database) => {
26 db.run("CREATE TABLE IF NOT EXISTS place_try (provider TEXT PRIMARY KEY, tried_at TEXT NOT NULL)");
27 db.run("CREATE TABLE IF NOT EXISTS place_read (provider TEXT PRIMARY KEY, read_at TEXT NOT NULL, body TEXT NOT NULL)");
28 db.run("CREATE TABLE IF NOT EXISTS place_pin (plan TEXT PRIMARY KEY, place_id TEXT NOT NULL)");
29 };
30
31 const API: Readonly<Record<string, { base: string; paths: Readonly<Record<string, string>> }>> = {
32 hetzner: {
33 base: "https://api.hetzner.cloud/v1",
34 paths: { server_types: "/server_types?per_page=50", datacenters: "/datacenters?per_page=50", pricing: "/pricing" },
35 },
36 digitalocean: {
37 base: "https://api.digitalocean.com/v2",
38 paths: { sizes: "/sizes?per_page=200", regions: "/regions?per_page=200" },
39 },
40 };
41
42 /**
43 * Ask the provider for its places and keep the answer; the previous read stands when this one
44 * fails.
45 */
46 export async function readPlaces(db: Database, provider: string, f: Fetch, token: string, now = new Date()): Promise<boolean> {
47 const api = API[provider];
48 if (!api) return false;
49 try {
50 const body: Record<string, unknown> = {};
51 for (const [key, path] of Object.entries(api.paths)) {
52 const res = await f(`${api.base}${path}`, { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(20_000) });
53 if (!res.ok) return false;
54 const bytes = await readCapped(res, MAX_BODY);
55 if (bytes === undefined) return false;
56 body[key] = JSON.parse(new TextDecoder().decode(bytes));
57 }
58 const flat = provider === "hetzner"
59 ? { server_types: (body.server_types as any)?.server_types, datacenters: (body.datacenters as any)?.datacenters, pricing: body.pricing }
60 : { sizes: (body.sizes as any)?.sizes, regions: (body.regions as any)?.regions };
61 const text = JSON.stringify(flat);
62 if (text.length > MAX_BODY) return false;
63 table(db);
64 db.query(
65 `INSERT INTO place_read (provider, read_at, body) VALUES (?1, ?2, ?3)
66 ON CONFLICT (provider) DO UPDATE SET read_at = excluded.read_at, body = excluded.body`,
67 ).run(provider, now.toISOString(), text);
68 return true;
69 } catch {
70 return false;
71 }
72 }
73
74 /** Note that a provider was asked now, whether or not the read worked. */
75 export function noteTry(db: Database, provider: string, now = new Date()): void {
76 table(db);
77 db.query("INSERT INTO place_try (provider, tried_at) VALUES (?1, ?2) ON CONFLICT (provider) DO UPDATE SET tried_at = excluded.tried_at").run(provider, now.toISOString());
78 }
79
80 const timesOf = (db: Database, tableName: "place_try" | "place_read", column: "tried_at" | "read_at"): Record<string, string> => {
81 table(db);
82 return Object.fromEntries(db.query<{ provider: string; at: string }, []>(`SELECT provider, ${column} AS at FROM ${tableName}`).all().map((r) => [r.provider, r.at]));
83 };
84
85 /** When each provider was last asked. */
86 export const triedTimes = (db: Database): Record<string, string> => timesOf(db, "place_try", "tried_at");
87
88 /** When each provider was last read successfully. */
89 export const readTimes = (db: Database): Record<string, string> => timesOf(db, "place_read", "read_at");
90
91 /** Every kept place, priced in dollars at `rate`. */
92 export function keptPlaces(db: Database, rate: Rate | undefined): Place[] {
93 table(db);
94 const out: Place[] = [];
95 for (const r of db.query<{ provider: string; read_at: string; body: string }, []>("SELECT * FROM place_read ORDER BY provider").all()) {
96 try {
97 const body = JSON.parse(r.body);
98 out.push(...(r.provider === "hetzner" ? hetznerPlaces(body, rate, r.read_at) : digitaloceanPlaces(body, r.read_at)));
99 } catch {
100 // an unreadable keep is skipped, not a failure of the catalog
101 }
102 }
103 return out;
104 }
105
106 export const pinOf = (db: Database, plan: PlanName): string | undefined => {
107 table(db);
108 return db.query<{ place_id: string }, [string]>("SELECT place_id FROM place_pin WHERE plan = ?1").get(plan)?.place_id;
109 };
110
111 /** Pin a plan's default, or clear the pin with an empty id. The id must be a place that is kept. */
112 export function setPin(db: Database, plan: unknown, id: string, rate: Rate | undefined): string | undefined {
113 if (!isPlan(plan)) return "plan must be small, medium or large";
114 table(db);
115 if (id.length > MAX_ID) return "no such place";
116 if (id === "") {
117 db.query("DELETE FROM place_pin WHERE plan = ?1").run(plan);
118 return undefined;
119 }
120 if (!keptPlaces(db, rate).some((p) => p.id === id)) return "no such place";
121 db.query("INSERT INTO place_pin (plan, place_id) VALUES (?1, ?2) ON CONFLICT (plan) DO UPDATE SET place_id = excluded.place_id").run(plan, id);
122 return undefined;
123 }
src/cloud/prices.ts added +65
@@ -0,0 +1,65 @@
1 /**
2 * The one place money changes currency (#16203). Every amount a person sees is US dollars; a vendor
3 * that bills in another currency is converted here, at a dated reference rate, and the vendor's own
4 * amount stays beside the result so the conversion can be shown and re-done. Cents, never floats,
5 * leave this module.
6 */
7
8 /** `usdPer` US dollars buy one unit of `currency` on `date` (ECB reference rates are quoted so). */
9 export interface Rate {
10 readonly currency: string;
11 readonly usdPer: number;
12 /** The day the rate is for, YYYY-MM-DD. */
13 readonly date: string;
14 }
15
16 /** `up` is for a figure that guards spending: never round in the owner's favour of the vendor. */
17 export type Rounding = "nearest" | "up";
18
19 /** A price as the vendor states it, and as the person reads it. */
20 export interface Price {
21 readonly usdCents: number;
22 /** The vendor's amount in major units (5.99) and its currency. */
23 readonly vendorAmount: number;
24 readonly vendorCurrency: string;
25 /** The rate used; absent when the vendor bills in dollars and nothing was converted. */
26 readonly rate?: { readonly usdPer: number; readonly date: string };
27 }
28
29 const cents = (usd: number, round: Rounding): number => {
30 const c = usd * 100;
31 // Float noise (5.99 * 100 = 599.0000000000001) must not push an exact figure up a cent.
32 return round === "up" ? Math.ceil(Math.round(c * 1e6) / 1e6) : Math.round(c);
33 };
34
35 /**
36 * Convert `amount` (major units of `currency`) to US dollar cents. USD is never converted. Any
37 * other currency needs a rate for exactly that currency, or this throws: no guessing.
38 */
39 export function toUsd(amount: number, currency: string, rate: Rate | undefined, round: Rounding = "nearest"): Price {
40 const cur = currency.toUpperCase();
41 if (!Number.isFinite(amount) || amount < 0) throw new Error("not an amount");
42 if (cur === "USD") return { usdCents: cents(amount, round), vendorAmount: amount, vendorCurrency: "USD" };
43 if (!rate || rate.currency !== cur) throw new Error(`no ${cur} rate`);
44 return {
45 usdCents: cents(amount * rate.usdPer, round),
46 vendorAmount: amount,
47 vendorCurrency: cur,
48 rate: { usdPer: rate.usdPer, date: rate.date },
49 };
50 }
51
52 /** "$12.34" for cents; the only formatter for dollars. */
53 export const dollars = (usdCents: number): string => `$${(usdCents / 100).toFixed(2)}`;
54
55 const SYMBOL: Readonly<Record<string, string>> = { EUR: "€", GBP: "£" };
56 const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
57
58 /** The curious path's sentence: "€5.99 at 1.08 on 24 Nov", or "" when nothing was converted. */
59 export function conversionNote(p: Price): string {
60 if (!p.rate) return "";
61 const [, m, d] = p.rate.date.split("-").map(Number);
62 const sym = SYMBOL[p.vendorCurrency];
63 const amount = sym ? `${sym}${p.vendorAmount.toFixed(2)}` : `${p.vendorAmount.toFixed(2)} ${p.vendorCurrency}`;
64 return `${amount} at ${p.rate.usdPer} on ${d} ${MONTHS[(m ?? 1) - 1]}`;
65 }
src/cloud/rates.ts added +65
@@ -0,0 +1,65 @@
1 /**
2 * The daily reference rate (#16203): the European Central Bank publishes euro rates with no key.
3 * Fetched here, kept with its date; a failed fetch leaves the last good rate in place and the page
4 * says how old it is.
5 */
6
7 import type { Database } from "bun:sqlite";
8 import type { Fetch } from "./providers.ts";
9 import type { Rate } from "./prices.ts";
10
11 export const ECB_URL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
12 /** A rate outside this band is a broken feed, not a market. */
13 const SANE = { min: 0.2, max: 5 };
14
15 /**
16 * USD per EUR and its day from the ECB's daily XML, or undefined when it is not what it should be.
17 */
18 export function parseEcb(xml: string): Rate | undefined {
19 const date = /<Cube\s+time=['"](\d{4}-\d{2}-\d{2})['"]/.exec(xml)?.[1];
20 const usd = /<Cube\s+currency=['"]USD['"]\s+rate=['"]([0-9.]+)['"]/.exec(xml)?.[1];
21 const v = Number(usd);
22 if (!date || !usd || !Number.isFinite(v) || v < SANE.min || v > SANE.max) return undefined;
23 return { currency: "EUR", usdPer: v, date };
24 }
25
26 const table = (db: Database) =>
27 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)");
28
29 export interface KeptRate extends Rate {
30 readonly fetchedAt: string;
31 }
32
33 /** The last good rate for a currency, or undefined when none was ever read. */
34 export function keptRate(db: Database, currency: string): KeptRate | undefined {
35 table(db);
36 const r = db.query<{ usd_per: number; date: string; fetched_at: string }, [string]>("SELECT * FROM fx_rate WHERE currency = ?1").get(currency);
37 return r ? { currency, usdPer: r.usd_per, date: r.date, fetchedAt: r.fetched_at } : undefined;
38 }
39
40 /**
41 * Fetch today's rate and keep it. Returns the rate that stands afterwards: the new one, or the last
42 * good one when the fetch fails or answers rubbish.
43 */
44 export async function refreshRate(db: Database, f: Fetch, now = new Date()): Promise<KeptRate | undefined> {
45 try {
46 const res = await f(ECB_URL, { signal: AbortSignal.timeout(10_000) });
47 if (res.ok) {
48 const rate = parseEcb((await res.text()).slice(0, 20_000));
49 if (rate) {
50 table(db);
51 db.query(
52 `INSERT INTO fx_rate (currency, usd_per, date, fetched_at) VALUES (?1, ?2, ?3, ?4)
53 ON CONFLICT (currency) DO UPDATE SET usd_per = excluded.usd_per, date = excluded.date, fetched_at = excluded.fetched_at`,
54 ).run(rate.currency, rate.usdPer, rate.date, now.toISOString());
55 }
56 }
57 } catch {
58 // the last good rate stands
59 }
60 return keptRate(db, "EUR");
61 }
62
63 /** Whole days between the rate's day and `now`: what the page says when the fetch keeps failing. */
64 export const rateAgeDays = (r: Rate, now = new Date()): number =>
65 Math.max(0, Math.floor((now.getTime() - Date.parse(`${r.date}T00:00:00Z`)) / 86_400_000));
src/cloud/targets.ts +2 −2
@@ -24,7 +24,7 @@ export const TARGETS: readonly Target[] = [
2424 label: "DigitalOcean",
2525 status: "first",
2626 runs: "One droplet (Ubuntu, Bun from the pinned source) with one block volume mounted as FORGE_APP_DATA. Replacing the droplet keeps the volume, so a version change never touches the data.",
27 cost: "about $12 (s-1vcpu-2gb) + $1.20 (10 GiB volume)",
27 cost: "read from DigitalOcean's own sizes, in US dollars: GET /api/v1/places?provider=digitalocean",
2828 refused: "Nothing the forge needs is refused; the token must be able to create droplets and volumes, which DigitalOcean cannot narrow further.",
2929 },
3030 {
@@ -32,7 +32,7 @@ export const TARGETS: readonly Target[] = [
3232 label: "Hetzner Cloud",
3333 status: "first",
3434 runs: "One server (Ubuntu, Bun from the pinned source) with one volume mounted as FORGE_APP_DATA, in Nuremberg. The forge reads Hetzner's own list and orders the cheapest cost-optimized (CX) type with at least 2 GiB that is in stock there; when none can be ordered it says so before it makes anything. Replacing the server keeps the volume.",
35 cost: "the cheapest in-stock CX type with at least 2 GiB, at its list price in Nuremberg, + the 10 GiB volume; the API's price is the truth",
35 cost: "read from Hetzner's own pricing and converted to US dollars at the day's reference rate: GET /api/v1/places?provider=hetzner",
3636 refused: "Nothing the forge needs is refused; the token must be read-write, and Hetzner scopes it to one project and offers nothing narrower.",
3737 },
3838 {
src/contract/openapi/routes/getApiV1Places.ts added +13
@@ -0,0 +1,13 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: "/api/v1/places",
6 summary: "Where a forge can run, with its monthly cost in US dollars",
7 detail: "The catalog of places (provider + datacenter + machine size): vCPU, memory, disk, included traffic, city and country, the monthly cost in US dollar cents (machine + the forge's volume + public address) beside the vendor's own amount and the rate that converted it, the day it was read, whether it can be ordered now and why not, and which plans it is the default for. Also `defaults` per plan with the reason in words, the `rule` that chooses them, and the dollar `rate` with its date and age. A forge administrator's look refreshes a stale catalog first; a failed read keeps the last good one",
8 auth: true,
9 role: "member",
10 query: { plan: "string", provider: "string", country: "string" },
11 refusals: { invalid: "plan is not small, medium or large, provider is not an id, or country is not two letters (422)" },
12 refuses: [401],
13 };
src/contract/openapi/routes/index.ts +2
@@ -129,6 +129,7 @@ export { route as getApiV1OrgsOrgTeamsTeamMembers } from "./getApiV1OrgsOrgTeams
129129 export { route as getApiV1Packs } from "./getApiV1Packs.ts";
130130 export { route as getApiV1PacksName } from "./getApiV1PacksName.ts";
131131 export { route as getApiV1PassportHealth } from "./getApiV1PassportHealth.ts";
132 export { route as getApiV1Places } from "./getApiV1Places.ts";
132133 export { route as getApiV1Plans } from "./getApiV1Plans.ts";
133134 export { route as getApiV1ProofDaily } from "./getApiV1ProofDaily.ts";
134135 export { route as getApiV1ReachAsks } from "./getApiV1ReachAsks.ts";
@@ -470,6 +471,7 @@ export { route as putApiV1ForgesNamePlan } from "./putApiV1ForgesNamePlan.ts";
470471 export { route as putApiV1ForgesRecipesName } from "./putApiV1ForgesRecipesName.ts";
471472 export { route as putApiV1Front } from "./putApiV1Front.ts";
472473 export { route as putApiV1PacksName } from "./putApiV1PacksName.ts";
474 export { route as putApiV1PlacesPin } from "./putApiV1PlacesPin.ts";
473475 export { route as putApiV1ReposOwnerNameAppDomainsHostOldRecords } from "./putApiV1ReposOwnerNameAppDomainsHostOldRecords.ts";
474476 export { route as putApiV1ReposOwnerNameAppEnvVar } from "./putApiV1ReposOwnerNameAppEnvVar.ts";
475477 export { route as putApiV1ReposOwnerNameAppMembers } from "./putApiV1ReposOwnerNameAppMembers.ts";
src/contract/openapi/routes/putApiV1PlacesPin.ts added +13
@@ -0,0 +1,13 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "put",
5 path: "/api/v1/places/pin",
6 summary: "Pin the default place of a plan",
7 detail: "Pin the place a plan runs in by default, overriding the cheapest-orderable-US rule, or clear the pin with an empty `place` (a forge administrator's token, admin scope); answers { plan, place }",
8 auth: true,
9 role: "admin",
10 body: { plan: "small, medium or large", place: "a place id from GET /api/v1/places, or empty to clear" },
11 refusals: { invalid: "the plan is unknown or the place is not in the catalog (422)" },
12 refuses: [404, 422],
13 };
src/contract/tags.ts +1
@@ -78,6 +78,7 @@ const ALIAS: Readonly<Record<string, string>> = {
7878 plans: "forges",
7979 start: "forges",
8080 cloud: "forges",
81 places: "forges",
8182 migrate: "forges",
8283 returns: "billing",
8384 credit: "billing",
src/core/event_audience.ts +2
@@ -299,6 +299,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
299299 kind === "forge.upstream" ||
300300 kind === "forge.updates_taken" ||
301301 kind === "cloud.write_allowed" ||
302 // A plan's pinned default place is an admin's act (`actions/places.ts`, #16203).
303 kind === "cloud.place_pinned" ||
302304 // A bet's name, share and what is left are the owner's plan (#8713).
303305 kind.startsWith("bet.") ||
304306 // A pinned forge's deploy, update and rollback name the owner's cloud (#8697).
src/http/api/cloud.ts +30 −1
@@ -11,7 +11,11 @@ import { scopeAllows } from "../../core/tokens.ts";
1111 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1212 import type { Handler } from "../context.ts";
1313 import { holds, weakEtag } from "../etag.ts";
14 import { apiError, notFound, unauthorized } from "../respond.ts";
14 import { pinPlace, placesCatalog } from "../../actions/places.ts";
15 import { refreshIfDue } from "../../actions/places_refresh.ts";
16 import { MAX_ID } from "../../cloud/places_read.ts";
17 import { accountAdmin } from "./admin.ts";
18 import { apiError, body, json, notFound, str, unauthorized } from "../respond.ts";
1519 import type { Router } from "../router.ts";
1620
1721 export function cloudRoutes(router: Router<Handler>): void {
@@ -35,4 +39,29 @@ export function cloudRoutes(router: Router<Handler>): void {
3539 if (holds(ctx.request, etag)) return new Response(null, { status: 304, headers });
3640 return new Response(text, { headers: { "content-type": "application/json", ...headers } });
3741 });
42
43 // ---- places (#16203): the catalog, with its dollar prices and the default for each plan ----
44 router.add("GET", "/api/v1/places", async (ctx) => {
45 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
46 const user = ctx.auth.user;
47 if (!user || ctx.auth.scope === undefined) return unauthorized();
48 // An admin's look refreshes a stale catalog first; a failed read leaves the last good one
49 // standing. Every vendor call is audited, so only a write-scoped token starts one.
50 if (user.isAdmin && scopeAllows(ctx.auth.scope, "rw")) await refreshIfDue(ctx.app, user);
51 const url = new URL(ctx.request.url);
52 const q = (k: string) => url.searchParams.get(k) ?? undefined;
53 const seen = placesCatalog(ctx.app, { plan: q("plan"), provider: q("provider"), country: q("country") });
54 return seen.ok ? json(seen.value) : apiError("invalid", 422, seen.error);
55 });
56
57 router.add("PUT", "/api/v1/places/pin", async (ctx) => {
58 const denied = accountAdmin(ctx, "admin");
59 if (denied) return denied;
60 const i = await body(ctx.request);
61 const place = str(i.place);
62 if (place.length > MAX_ID) return apiError("invalid", 422, "no such place");
63 const pinned = pinPlace(ctx.app, ctx.auth.user, i.plan, place);
64 if (!pinned.ok) return pinned.error === "not_found" ? notFound() : apiError("invalid", 422, pinned.error);
65 return json(pinned.value);
66 });
3867 }
src/http/marks/api-v1-places.json added +4
@@ -0,0 +1,4 @@
1 {
2 "head": "/api/v1/places",
3 "mark": "open"
4 }
src/http/sse.ts +1 −1
@@ -264,7 +264,7 @@ export function viewerStream(
264264 emit("run.log", { run: runId, ...frameOf(lines) });
265265 }, gone.signal);
266266 const unsubscribe = app.bus.subscribe((event: ForgeEvent) => {
267 if (event.repoId === null ? !(event.kind.startsWith("backup.") || (viewer !== undefined && event.kind.startsWith("desk."))) : !visible(event.repoId)) return;
267 if (event.repoId === null ? !(event.kind.startsWith("backup.") || event.kind === "cloud.place_pinned" || (viewer !== undefined && event.kind.startsWith("desk."))) : !visible(event.repoId)) return;
268268 if (!meant(event)) return;
269269 send(event);
270270 }, "ordered");
src/spawn/bounded_read.ts +1 −1
@@ -5,7 +5,7 @@
55 * is ever held. Undefined past the limit or when the client goes away.
66 */
77
8 export async function readCapped(req: Request, max: number): Promise<Uint8Array | undefined> {
8 export async function readCapped(req: Pick<Request, "body">, max: number): Promise<Uint8Array | undefined> {
99 if (req.body === null) return new Uint8Array();
1010 const reader = req.body.getReader();
1111 const chunks: Uint8Array[] = [];
src/tui/forge.ts +2
@@ -20,6 +20,7 @@ import { sourceFor } from "../view/source.ts";
2020 import { fleetCommand } from "./screens/fleet.ts";
2121 import { dataCommand } from "./screens/data.ts";
2222 import { packsCommand } from "./screens/packs.ts";
23 import { placesCommand } from "./screens/places.ts";
2324 import { crewNowCommand } from "./screens/crew_now.ts";
2425 import { publicFeedCommand } from "./screens/publicfeed.ts";
2526 import { statusCommand } from "./screens/status.ts";
@@ -279,6 +280,7 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
279280 ...needsCommands(session, ctx),
280281 ...asksAdminCommands(session, ctx),
281282 packsCommand(session, ctx),
283 ...(session.user ? [placesCommand(session, ctx)] : []),
282284 crewNowCommand(session, ctx),
283285 publicFeedCommand(session, ctx),
284286 statusCommand(session, ctx),
src/tui/screens/places.ts added +98
@@ -0,0 +1,98 @@
1 /**
2 * Places, in the terminal (#16203): where a forge can run, from the same catalog the API gives
3 * (`actions/places.ts`): each plan's default and why, then every place with its dollars a month.
4 * Anyone signed in reads it. A forge admin who is a person also pins a plan's default with `p`
5 * (a plan, then a place id; an empty id clears the pin) through `pinPlace`, the API's own act,
6 * which announces `cloud.place_pinned` so a viewer on the web hears it. Opening it as an admin
7 * first refreshes a stale catalog, as the API's admin read does.
8 */
9
10 import { mayPin, pinPlace, placesCatalog } from "../../actions/places.ts";
11 import { refreshIfDue } from "../../actions/places_refresh.ts";
12 import { dollars } from "../../cloud/prices.ts";
13 import type { Ctx, Screen } from "../app/app.ts";
14 import { binding } from "../app/keys.ts";
15 import type { Session } from "../session.ts";
16 import { style } from "../term/style.ts";
17 import { Scroll, drawLines, hitScroll, later, promptScreen, runAsync } from "./common.ts";
18
19 /** The screen's lines: the rule, each plan's default, then the places by price. */
20 export function placeLines(session: Pick<Session, "app">): string[] {
21 const seen = placesCatalog(session.app, {});
22 if (!seen.ok) return [seen.error];
23 const c = seen.value;
24 const rate = c.rate === null ? "No dollar rate kept yet." : `Euro at ${String(c.rate.usdPer)} on ${c.rate.date}${c.rate.ageDays > 0 ? ` (${String(c.rate.ageDays)} days old)` : ""}.`;
25 const lines = [c.rule, rate, ""];
26 for (const plan of ["small", "medium", "large"] as const) {
27 const d = c.defaults[plan];
28 lines.push(`${plan}: ${d.placeId ?? "none"}`, ` ${d.reason}`);
29 }
30 lines.push("");
31 if (c.items.length === 0) lines.push("No place is kept yet: a forge admin's read of the catalog fetches them.");
32 for (const p of [...c.items].sort((a, b) => a.costCents - b.costCents || a.id.localeCompare(b.id))) {
33 const how = p.orderable ? "" : ` (${p.why})`;
34 const note = p.priceNote === "" ? "" : ` ${p.priceNote}`;
35 lines.push(`${dollars(p.costCents)}/mo ${p.id} ${p.city}${p.country === "" ? "" : `, ${p.country}`} ${String(p.vcpu)} vCPU ${String(Math.round(p.memoryMiB / 1024))} GiB ${String(p.diskGiB)} GiB disk${how}${note}`);
36 }
37 return lines;
38 }
39
40 export function placesScreen(session: Session, ctx: Ctx): Screen {
41 const scroll = new Scroll();
42 const may = (): boolean => mayPin(session.user);
43 if (may() && session.user) {
44 const who = session.user;
45 runAsync(ctx, async () => {
46 await refreshIfDue(session.app, who);
47 ctx.invalidate();
48 });
49 }
50 const screen: Screen = {
51 title: "Places",
52 get keys() {
53 return [binding(["j", "k"], "scroll"), ...(may() ? [binding(["p"], "pin a plan's default")] : []), binding(["esc", "q"], "back")];
54 },
55 render(area, s) {
56 const c = ctx.theme.c;
57 const lines = placeLines(session);
58 drawLines(s, area, c, scroll, lines.map((text) => [{ text, style: style(text.startsWith(" ") || /^\$/.test(text) ? c.mutedFg : c.fg, c.bg) }]));
59 hitScroll(ctx, area, scroll, lines.length);
60 },
61 key(e) {
62 if (scroll.key(e, placeLines(session).length)) return true;
63 if (e.key === "esc" || e.key === "q") ctx.pop();
64 else if (e.key === "p" && may())
65 ctx.push(
66 promptScreen(ctx, screen, {
67 title: "Pin 1/2",
68 label: "Plan (small, medium or large)",
69 onSubmit: (plan) =>
70 later(ctx, () =>
71 promptScreen(ctx, screen, {
72 title: "Pin 2/2",
73 label: "Place id (empty clears the pin)",
74 onSubmit: (id) => {
75 const pinned = pinPlace(session.app, session.user, plan.trim(), id.trim());
76 if (pinned.ok) {
77 ctx.toast(id.trim() === "" ? `${plan.trim()} is unpinned` : `${plan.trim()} is pinned to ${id.trim()}`, "success");
78 return undefined;
79 }
80 return pinned.error === "not_found" ? "Pinning is a forge admin's." : pinned.error;
81 },
82 }),
83 ),
84 }),
85 );
86 return true;
87 },
88 };
89 return screen;
90 }
91
92 /** Offered to everyone signed in: the pin is the admin's, the list is anyone's. */
93 export const placesCommand = (session: Session, ctx: Ctx) => ({
94 id: "places",
95 title: "Places",
96 hint: "where a forge can run, in dollars a month, and each plan's default",
97 run: () => ctx.push(placesScreen(session, ctx)),
98 });
test/helpers/places-fixture.ts added +22
@@ -0,0 +1,22 @@
1 /** What Hetzner and DigitalOcean answer, as much as places read (#16203). */
2 export const hetzner = {
3 server_types: [
4 { id: 1, name: "cpx21", cores: 3, memory: 4, disk: 80, architecture: "x86", prices: [
5 { location: "ash", price_monthly: { gross: "10.00" }, included_traffic: 2 ** 40 },
6 { location: "nbg1", price_monthly: { gross: "5.00" }, included_traffic: 2 ** 43 }] },
7 { id: 2, name: "cpx11", cores: 2, memory: 2, disk: 40, architecture: "x86", prices: [{ location: "ash", price_monthly: { gross: "4.00" } }] },
8 ],
9 datacenters: [
10 { location: { name: "ash", city: "Ashburn, VA", country: "us" }, server_types: { available: [1] } },
11 { location: { name: "nbg1", city: "Nuremberg", country: "DE" }, server_types: { available: [1] } },
12 ],
13 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" } }] }] } },
14 };
15 export const ocean = {
16 regions: [{ slug: "nyc3", available: true }, { slug: "ams3", available: true }],
17 sizes: [
18 { slug: "s-1vcpu-2gb", memory: 2048, vcpus: 1, disk: 50, transfer: 2, price_monthly: 12, available: true, regions: ["nyc3", "ams3"] },
19 { slug: "gpu-h100", memory: 9, vcpus: 1, disk: 1, transfer: 1, price_monthly: 1, available: true, regions: ["nyc3"] },
20 ],
21 };
22
test/palette-roster.test.ts +3
@@ -55,6 +55,7 @@ test("a site-admin person is offered the whole roster", () => {
5555 ["packs", "Forge packs", "premade forges to deploy, and how to help build their apps"],
5656 ["mirror-packs", "Mirror the packs' upstreams", "bring each pack's upstream projects in as read-only repositories"],
5757 ["pack-repos", "Pack repositories", "which repositories /packs lists"],
58 ["places", "Places", "where a forge can run, in dollars a month, and each plan's default"],
5859 ["crew-now", "Your crew's latest work", "the three runs a forge link's page shows"],
5960 ["public-feed", "Shipped on public apps", "what merged on public apps, newest first"],
6061 ["status", "Status", "is the forge working, in one sentence"],
@@ -250,6 +251,7 @@ test("a site-admin agent is offered the roster without the person-only entries",
250251 ["needs", "How is my forge?", "what needs you, with a recommendation each; a takes a safe one"],
251252 ["asks-admin", "What stands in the way", "what waits on you and what stands in your way; a asks whoever can, o opens the control"],
252253 ["packs", "Forge packs", "premade forges to deploy, and how to help build their apps"],
254 ["places", "Places", "where a forge can run, in dollars a month, and each plan's default"],
253255 ["crew-now", "Your crew's latest work", "the three runs a forge link's page shows"],
254256 ["public-feed", "Shipped on public apps", "what merged on public apps, newest first"],
255257 ["status", "Status", "is the forge working, in one sentence"],
@@ -356,6 +358,7 @@ test("a member person is offered the signed-in roster without the admin entries"
356358 ["needs", "How is my forge?", "what needs you, with a recommendation each; a takes a safe one"],
357359 ["asks-admin", "What stands in the way", "what waits on you and what stands in your way; a asks whoever can, o opens the control"],
358360 ["packs", "Forge packs", "premade forges to deploy, and how to help build their apps"],
361 ["places", "Places", "where a forge can run, in dollars a month, and each plan's default"],
359362 ["crew-now", "Your crew's latest work", "the three runs a forge link's page shows"],
360363 ["public-feed", "Shipped on public apps", "what merged on public apps, newest first"],
361364 ["status", "Status", "is the forge working, in one sentence"],
test/places-api.test.ts added +168
@@ -0,0 +1,168 @@
1 /**
2 * Places (#16203) over HTTP: the refresh, who may start one, the filters, the pin, and the
3 * terminal's twin.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { addAccount, allowWrite, net } from "../src/actions/cloud.ts";
11 import { pinPlace } from "../src/actions/places.ts";
12 import { isStale, refreshCatalog } from "../src/actions/places_refresh.ts";
13 import { RETRY_MS, noteTry } from "../src/cloud/places_read.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { createUser, getUserByName } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { hetzner } from "./helpers/places-fixture.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21
22 const ECB = `<gesmes:Envelope><Cube><Cube time='2026-11-24'><Cube currency='USD' rate='1.08'/></Cube></Cube></gesmes:Envelope>`;
23 let hetznerCalls = 0;
24 let ecbCalls = 0;
25 let hetznerDown = false;
26 let slow: Promise<void> | undefined;
27 net.fetch = async (url) => {
28 const u = String(url);
29 if (u.includes("ecb.europa.eu")) {
30 ecbCalls++;
31 return new Response(ECB);
32 }
33 if (!u.includes("api.hetzner.cloud/v1/") || u.includes("/locations")) return new Response("{}");
34 hetznerCalls++;
35 await slow;
36 if (hetznerDown) return new Response("down", { status: 500 });
37 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);
39 };
40
41 describe("places over HTTP", () => {
42 let dir = "";
43 let app: App;
44 let servers: Servers;
45 let admin = "";
46 let roAdmin = "";
47 let bob = "";
48 const get = (q = "", t = admin) => fetch(`${servers.url}/api/v1/places${q}`, { headers: { authorization: `Bearer ${t}` } });
49 const pin = (b: unknown, t = admin) =>
50 fetch(`${servers.url}/api/v1/places/pin`, { method: "PUT", headers: { authorization: `Bearer ${t}`, "content-type": "application/json" }, body: JSON.stringify(b) });
51 const aliceUser = () => getUserByName(app.db, "alice")!;
52
53 beforeAll(async () => {
54 dir = await mkdtemp(join(tmpdir(), "forge-places-api-"));
55 app = createApp({ dataDir: dir, port: 0 });
56 servers = await serve(app);
57 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
58 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst });
59 if (!made.ok) throw new Error(made.error);
60 }
61 admin = createToken(app.db, aliceUser().id, "admin", "admin").token;
62 roAdmin = createToken(app.db, aliceUser().id, "ro", "ro").token;
63 bob = createToken(app.db, getUserByName(app.db, "bob")!.id, "t", "rw").token;
64 const added = await addAccount(app, aliceUser(), "hetzner", "main", "hz-token-0123456789abcdef");
65 if (!added.ok) throw new Error(String(added.error));
66 allowWrite(app, aliceUser(), "hetzner", "main", true);
67 }, 30_000);
68 afterAll(async () => {
69 servers.stop();
70 app.close();
71 await rm(dir, { recursive: true, force: true });
72 });
73
74 test("a read-only token, even an admin's, gets the kept catalog and starts no vendor call", async () => {
75 hetznerCalls = 0;
76 ecbCalls = 0;
77 expect(isStale(app)).toBe(true);
78 const res = await get("", roAdmin);
79 expect(res.status).toBe(200);
80 expect(((await res.json()) as any).items).toEqual([]);
81 expect(hetznerCalls + ecbCalls).toBe(0);
82 });
83
84 test("a member's read never refreshes", async () => {
85 expect(((await (await get("", bob)).json()) as any).items).toEqual([]);
86 expect(hetznerCalls).toBe(0);
87 });
88
89 test("concurrent admin reads share one refresh; then the catalog is populated and not stale", async () => {
90 let release!: () => void;
91 slow = new Promise((r) => (release = r));
92 const reads = [get()];
93 while (hetznerCalls === 0) await new Promise((r) => setImmediate(r));
94 reads.push(get(), get());
95 await new Promise((r) => setImmediate(r));
96 release();
97 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
99 expect(ecbCalls).toBe(1);
100 expect(bodies.every((b) => b.items.length > 0)).toBe(true);
101 expect(isStale(app)).toBe(false);
102 slow = undefined;
103 });
104
105 test("filters narrow the items, and defaultFor names the plan a place is the default of", async () => {
106 const all: any = await (await get()).json();
107 const ids = all.items.map((p: any) => p.id);
108 expect(ids).toContain("hetzner:ash:cpx21");
109 expect(all.defaults.small.placeId).toBe("hetzner:ash:cpx21");
110 expect(all.items.find((p: any) => p.id === "hetzner:ash:cpx21").defaultFor).toEqual(["small", "medium"]);
111 expect(all.items.find((p: any) => p.id === "hetzner:nbg1:cpx21").defaultFor).toEqual([]);
112 expect(all.items.find((p: any) => p.id === "hetzner:ash:cpx21").priceNote).toContain("at 1.08");
113 const de: any = await (await get("?country=de")).json();
114 expect(de.items.every((p: any) => p.country === "DE")).toBe(true);
115 expect(de.items.length).toBeGreaterThan(0);
116 const large: any = await (await get("?plan=large")).json();
117 expect(large.items).toEqual([]);
118 expect(((await (await get("?provider=digitalocean")).json()) as any).items).toEqual([]);
119 expect(((await (await get("?provider=hetzner")).json()) as any).items.length).toBe(all.items.length);
120 });
121
122 test("a failing provider is tried at most every few minutes", async () => {
123 hetznerDown = true;
124 const old = new Date(Date.now() - 7 * 3_600_000).toISOString();
125 app.db.run("UPDATE place_read SET read_at = ?1", [old]);
126 app.db.run("DELETE FROM place_try");
127 expect(isStale(app)).toBe(true);
128 hetznerCalls = 0;
129 await get();
130 expect(hetznerCalls).toBe(1); // the first request fails
131 expect(isStale(app)).toBe(false);
132 await get();
133 expect(hetznerCalls).toBe(1);
134 expect(isStale(app, Date.now() + RETRY_MS + 1000)).toBe(true);
135 hetznerDown = false;
136 noteTry(app.db, "hetzner", new Date(0));
137 await refreshCatalog(app, aliceUser());
138 expect(isStale(app)).toBe(false);
139 });
140
141 test("PUT /pin: a member is refused, an unknown place or plan 422, a long id 422", async () => {
142 expect((await pin({ plan: "small", place: "hetzner:ash:cpx21" }, bob)).status).toBe(403);
143 expect((await pin({ plan: "small", place: "nope" })).status).toBe(422);
144 expect((await pin({ plan: "huge", place: "" })).status).toBe(422);
145 expect((await pin({ plan: "small", place: "x".repeat(5000) })).status).toBe(422);
146 expect((await pin({ plan: "small", place: "hetzner:ash:cpx21" }, roAdmin)).status).toBe(403);
147 });
148
149 test("a pin sticks, is echoed validated, is announced, and clears", async () => {
150 const heard: string[] = [];
151 app.bus.subscribe((e) => void (e.kind === "cloud.place_pinned" && heard.push(e.kind)));
152 const res = await pin({ plan: "small", place: "hetzner:nbg1:cpx21" });
153 expect(res.status).toBe(200);
154 expect(await res.json()).toEqual({ plan: "small", place: "hetzner:nbg1:cpx21" });
155 expect(((await (await get()).json()) as any).defaults.small).toMatchObject({ placeId: "hetzner:nbg1:cpx21" });
156 expect(heard).toEqual(["cloud.place_pinned"]);
157 expect((await pin({ plan: "small", place: "" })).status).toBe(200);
158 expect(((await (await get()).json()) as any).defaults.small.placeId).toBe("hetzner:ash:cpx21");
159 });
160
161 test("the terminal's door is the same act: a member is refused, an admin's pin is announced", () => {
162 const bobUser = getUserByName(app.db, "bob")!;
163 const refused = pinPlace(app, bobUser, "small", "hetzner:ash:cpx21");
164 expect(refused).toEqual({ ok: false, error: "not_found" });
165 expect(pinPlace(app, aliceUser(), "small", "hetzner:ash:cpx21").ok).toBe(true);
166 expect(pinPlace(app, aliceUser(), "small", "").ok).toBe(true);
167 });
168 });
test/places.test.ts added +154
@@ -0,0 +1,154 @@
1 /** Places (#16203): dollars, the default rule, a stale provider's last read, the route's shape. */
2 import { Database } from "bun:sqlite";
3 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { chooseDefault, digitaloceanPlaces, hetznerPlaces, type Place } from "../src/cloud/places.ts";
9 import { keptPlaces, readPlaces, setPin } from "../src/cloud/places_read.ts";
10 import { conversionNote, toUsd } from "../src/cloud/prices.ts";
11 import { keptRate, parseEcb, rateAgeDays, refreshRate } from "../src/cloud/rates.ts";
12 import { createToken } from "../src/core/tokens.ts";
13 import { createUser, getUserByName } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { hetzner, ocean } from "./helpers/places-fixture.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 const ECB = `<gesmes:Envelope><Cube><Cube time='2026-11-24'><Cube currency='USD' rate='1.08'/><Cube currency='JPY' rate='160'/></Cube></Cube></gesmes:Envelope>`;
21 const EUR = { currency: "EUR", usdPer: 1.08, date: "2026-11-24" };
22 const reply = (v: unknown) => new Response(JSON.stringify(v));
23
24 describe("one conversion", () => {
25 test("dollars are not converted; euros are, with the vendor's amount kept and a note", () => {
26 expect(toUsd(12, "USD", undefined)).toEqual({ usdCents: 1200, vendorAmount: 12, vendorCurrency: "USD" });
27 const p = toUsd(5.99, "EUR", EUR);
28 expect(p.usdCents).toBe(647);
29 expect(p.vendorAmount).toBe(5.99);
30 expect(conversionNote(p)).toBe("€5.99 at 1.08 on 24 Nov");
31 });
32 test("a spending figure rounds up, and float noise does not add a cent", () => {
33 expect(toUsd(5.99, "EUR", { ...EUR, usdPer: 1.0 }, "up").usdCents).toBe(599);
34 expect(toUsd(5.99, "EUR", { ...EUR, usdPer: 1.001 }).usdCents).toBe(600);
35 expect(toUsd(5.99, "USD", undefined, "up").usdCents).toBe(599);
36 });
37 test("no rate means no guess", () => {
38 expect(() => toUsd(1, "EUR", undefined)).toThrow();
39 expect(() => toUsd(1, "GBP", EUR)).toThrow();
40 });
41 });
42
43 describe("the rate", () => {
44 test("parses the ECB feed and refuses rubbish", () => {
45 expect(parseEcb(ECB)).toEqual(EUR);
46 expect(parseEcb("<Cube currency='USD' rate='99'/>")).toBeUndefined();
47 });
48 test("a failed fetch keeps the last good rate and its age shows", async () => {
49 const db = new Database(":memory:");
50 expect((await refreshRate(db, async () => reply(ECB) as any))?.usdPer).toBe(1.08);
51 const kept = await refreshRate(db, async () => { throw new Error("down"); });
52 expect(kept?.usdPer).toBe(1.08);
53 expect(await refreshRate(db, async () => new Response("<x/>"))).toEqual(keptRate(db, "EUR")!);
54 expect(rateAgeDays(kept!, new Date("2026-11-27T10:00:00Z"))).toBe(3);
55 });
56 });
57
58 describe("places from the providers' answers", () => {
59 const h = hetznerPlaces(hetzner, EUR, "2026-11-24T00:00:00Z");
60 test("Hetzner costs are machine + volume + address in dollars, with the euro kept", () => {
61 const ash = h.find((p) => p.id === "hetzner:ash:cpx21")!;
62 expect(ash.price).toMatchObject({ vendorAmount: 11, vendorCurrency: "EUR" });
63 expect(ash.costCents).toBe(Math.round(11 * 1.08 * 100));
64 expect(ash.country).toBe("US");
65 expect(ash.memoryMiB).toBe(4096);
66 expect(ash.orderable).toBe(true);
67 });
68 test("a type sold out, or a place with no rate, says why instead of failing", () => {
69 const sold = h.find((p) => p.id === "hetzner:ash:cpx11")!;
70 expect(sold.orderable).toBe(false);
71 expect(sold.why).toContain("sold out");
72 const noRate = hetznerPlaces(hetzner, undefined, "x");
73 expect(noRate.every((p) => !p.orderable && p.why.includes("rate"))).toBe(true);
74 });
75 test("DigitalOcean keeps only shared sizes, priced in dollars as given", () => {
76 const d = digitaloceanPlaces(ocean, "2026-11-24T00:00:00Z");
77 expect(d.map((p) => p.id)).toEqual(["digitalocean:nyc3:s-1vcpu-2gb", "digitalocean:ams3:s-1vcpu-2gb"]);
78 expect(d[0]!.costCents).toBe(1300);
79 expect(d[0]!.price.rate).toBeUndefined();
80 });
81 });
82
83 describe("the default rule", () => {
84 const all: Place[] = [...hetznerPlaces(hetzner, EUR, "x"), ...digitaloceanPlaces(ocean, "x")];
85 const both = new Set(["hetzner", "digitalocean"]);
86 test("the cheapest orderable US place that meets the plan", () => {
87 const c = chooseDefault(all, "small", both);
88 expect(c.place?.id).toBe("hetzner:ash:cpx21"); // $11.88 beats DO's $13.00; nbg1 is not US; cpx11 is sold out
89 expect(c.reason).toContain("cheapest place in the United States");
90 });
91 test("only providers with a writing account count", () => {
92 expect(chooseDefault(all, "small", new Set(["digitalocean"])).place?.id).toBe("digitalocean:nyc3:s-1vcpu-2gb");
93 });
94 test("a pin wins; a pin that cannot be ordered does not", () => {
95 expect(chooseDefault(all, "small", both, "digitalocean:nyc3:s-1vcpu-2gb").place?.id).toBe("digitalocean:nyc3:s-1vcpu-2gb");
96 expect(chooseDefault(all, "small", both, "hetzner:ash:cpx11").place?.id).toBe("hetzner:ash:cpx21");
97 });
98 test("nothing orderable says so, and says why", () => {
99 expect(chooseDefault(all, "small", new Set()).reason).toContain("no cloud account");
100 expect(chooseDefault(all, "large", both).reason).toContain("no place in the United States");
101 });
102 });
103
104 describe("a stale provider keeps its last read", () => {
105 test("a failing provider changes nothing, and a moved rate re-does the dollars", async () => {
106 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);
108 expect(await readPlaces(db, "hetzner", ok as any, "t", new Date("2026-11-24T00:00:00Z"))).toBe(true);
109 expect(await readPlaces(db, "hetzner", async () => new Response("no", { status: 500 }), "t")).toBe(false);
110 const before = keptPlaces(db, EUR).find((p) => p.id === "hetzner:ash:cpx21")!;
111 expect(before.readAt).toBe("2026-11-24T00:00:00.000Z");
112 const moved = keptPlaces(db, { ...EUR, usdPer: 1.2 }).find((p) => p.id === "hetzner:ash:cpx21")!;
113 expect(moved.costCents).toBeGreaterThan(before.costCents);
114 expect(setPin(db, "small", "hetzner:ash:cpx21", EUR)).toBeUndefined();
115 expect(setPin(db, "small", "nope", EUR)).toBe("no such place");
116 expect(setPin(db, "huge", "", EUR)).toContain("plan");
117 });
118 });
119
120 describe("GET /api/v1/places", () => {
121 let dir = "";
122 let app: App;
123 let servers: Servers;
124 let token = "";
125 beforeAll(async () => {
126 dir = await mkdtemp(join(tmpdir(), "forge-places-"));
127 app = createApp({ dataDir: dir, port: 0 });
128 servers = await serve(app);
129 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: false });
130 if (!made.ok) throw new Error(made.error);
131 token = createToken(app.db, getUserByName(app.db, "alice")!.id, "t", "ro").token;
132 }, 30_000);
133 afterAll(async () => {
134 servers.stop();
135 app.close();
136 await rm(dir, { recursive: true, force: true });
137 });
138 const get = (q = "", t: string | undefined = token) => fetch(`${servers.url}/api/v1/places${q}`, t ? { headers: { authorization: `Bearer ${t}` } } : {});
139
140 test("needs a signed-in person", async () => {
141 expect((await get("", "")).status).toBe(401);
142 });
143 test("an empty catalog is typed and says why there is no default", async () => {
144 const body: any = await (await get()).json();
145 expect(body).toMatchObject({ items: [], currency: "USD", rate: null, next_cursor: null });
146 expect(body.defaults.small.placeId).toBeNull();
147 expect(body.defaults.small.reason).toContain("Nowhere can be ordered");
148 expect(body.rule).toContain("cheapest place in the United States");
149 });
150 test("a bad filter is a 422, not a guess", async () => {
151 expect((await get("?plan=huge")).status).toBe(422);
152 expect((await get("?country=USA")).status).toBe(422);
153 });
154 });
test/tui-places.test.ts added +89
@@ -0,0 +1,89 @@
1 /**
2 * Places (#16203) in the terminal: anyone reads the catalog, only an admin pins, and a pin is
3 * announced.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import type { Fetch } from "../src/cloud/providers.ts";
11 import { readPlaces } from "../src/cloud/places_read.ts";
12 import { pinOf } from "../src/cloud/places_read.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import { createForgeApp } from "../src/tui/forge.ts";
15 import { headlessTerminal } from "../src/tui/term/terminal.ts";
16 import { hetzner } from "./helpers/places-fixture.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18 import { settleApp } from "./helpers/tui.ts";
19
20 quietLogs();
21
22 let dir: string;
23 let forge: App;
24 let alice: User;
25 let bob: User;
26
27 beforeAll(async () => {
28 dir = await mkdtemp(join(tmpdir(), "forge-tui-places-"));
29 forge = createApp({ dataDir: dir, port: 0 });
30 const make = async (username: string, adminIfFirst: boolean): Promise<User> => {
31 const made = await createUser(forge.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst });
32 if (!made.ok) throw new Error(made.error);
33 return made.value;
34 };
35 alice = await make("alice", true);
36 bob = await make("bob", false);
37 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);
39 await readPlaces(forge.db, "hetzner", ok, "t");
40 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)");
41 forge.db.run("INSERT INTO fx_rate VALUES ('EUR', 1.08, '2026-11-24', '2026-11-24T00:00:00Z')");
42 });
43
44 afterAll(async () => {
45 forge?.close();
46 await rm(dir, { recursive: true, force: true });
47 });
48
49 const open = async (user: User) => {
50 const terminal = headlessTerminal(160, 40);
51 const { app } = createForgeApp(forge, { sshUsername: "t", remoteAddress: "127.0.0.1", user }, { terminal, exitHooks: false });
52 app.start();
53 const key = (k: string) => app.dispatch({ type: "key", key: k, ctrl: k.startsWith("ctrl+"), alt: false, shift: false });
54 await settleApp(app);
55 app.dispatch({ type: "key", key: "k", ctrl: true, alt: false, shift: false });
56 for (const ch of "Places") key(ch);
57 key("enter");
58 await settleApp(app);
59 return { app, key, text: () => app.screen.toText().replace(/\s+/g, " ") };
60 };
61
62 test("a member reads the places in dollars and cannot pin", async () => {
63 const { app, key, text } = await open(bob);
64 expect(text()).toContain("hetzner:ash:cpx21");
65 expect(text()).toContain("$11.88/mo");
66 expect(text()).not.toContain("pin a plan's default");
67 key("p");
68 await settleApp(app);
69 expect(text()).not.toContain("Pin 1/2");
70 app.stop();
71 });
72
73 test("an admin pins a plan from the terminal, and the forge announces it", async () => {
74 const heard: string[] = [];
75 forge.bus.subscribe((e) => void (e.kind === "cloud.place_pinned" && heard.push(e.kind)));
76 const { app, key, text } = await open(alice);
77 expect(text()).toContain("pin a plan's default");
78 key("p");
79 await settleApp(app);
80 for (const ch of "small") key(ch);
81 key("enter");
82 await settleApp(app);
83 for (const ch of "hetzner:nbg1:cpx21") key(ch);
84 key("enter");
85 await settleApp(app);
86 expect(pinOf(forge.db, "small")).toBe("hetzner:nbg1:cpx21");
87 expect(heard).toEqual(["cloud.place_pinned"]);
88 app.stop();
89 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs