Public: anyone can read this; the crew can change it.
A deployed forge's machine and volume land in the cloud project meant for forges #16516
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/16340-a-deployed-forge-s-machine-and-volume-la → main 0 commits fork 4 threads · 4 unresolved
24 files
changed +451
−44
- docs/features/cloud.md
- docs/features/pinned-forge.md
- src/actions/cloud_ceiling.ts
- src/actions/pinned.ts
- src/cloud/droplet.ts
- src/cloud/hetzner.ts
- src/cloud/machine.ts
- src/core/cloud_account.ts
- src/core/event_audience.ts
- src/core/migration-pins/20261127100000-cloud-account-project.pin
- src/core/migrations/20261127100000-cloud-account-project.ts
- src/http/marks/settings.json
- src/http/mcp/tools/cloud_account.ts
- src/http/mcp/tools/pinned_forge.ts
- src/http/pinned_routes.ts
- src/http/settings_routes.ts
- src/tui/screens/cloud.ts
- src/tui/screens/pinned.ts
- src/web/pages/cloud.ts
- src/web/pages/pinned.ts
- test/cloud-page-shape.test.ts
- test/pinned-ceiling.test.ts
- test/pinned-project-actions.test.ts
- test/pinned-project.test.ts
docs/features/cloud.md +6 −1
| @@ -7,7 +7,7 @@ row: Cloud accounts | ||
| 7 | 7 | The forge keeps the provider tokens (a cloud vendor's API token) its repositories use, sealed. Four doors show them, all a forge admin's alone; anyone else finds no such page, screen, tool or route. No door ever returns a secret: a token is typed once, checked, sealed, and never drawn, kept in a note or sent back. |
| 8 | 8 | |
| 9 | 9 | - **Page**: Settings → Cloud accounts, `/settings/cloud`. Each account with what it is used for, when it was verified and last used, and today's vendor calls. Attach, verify, allow writes, rename, rotate, audit and remove are forms on the page. |
| 10 | - **Terminal**: the "Cloud accounts" screen (`src/tui/screens/cloud.ts`), opened from the palette. `a` attaches (token typed masked), `v` re-verifies, `r` rotates, `n` renames, `x` removes. The checks are the page's (`src/actions/cloud.ts`). | |
| 10 | - **Terminal**: the "Cloud accounts" screen (`src/tui/screens/cloud.ts`), opened from the palette. `a` attaches (token typed masked), `v` re-verifies, `r` rotates, `n` renames, `x` removes, `P` sets the project its forges are filed in. The checks are the page's (`src/actions/cloud.ts`). | |
| 11 | 11 | - **MCP**: `cloud_accounts` takes no arguments and returns the accounts with each token's use, verification, write permission and today's calls. It counts as a write, so a `ro` token never lists them. |
| 12 | 12 | - **HTTP**: `GET /api/v1/cloud/accounts` returns the same body as `cloud_accounts` (both build it with `cloudOverview`). |
| 13 | 13 | |
| @@ -19,6 +19,11 @@ Answers: `401` with no signed-in user, `403` for a read-only token (every vendor | ||
| 19 | 19 | |
| 20 | 20 | 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 | 21 | |
| 22 | ## The project a forge is filed in (#16340) | |
| 23 | ||
| 24 | - A DigitalOcean account can name the cloud **project** its forges go in: a text field on its row at `/settings/cloud`, `P` on the terminal screen, `set_project` on the MCP `cloud_account` tool. Empty is the provider's default project. An admin only; the name is checked, and the project must exist when a forge is deployed, or the deploy is refused before anything is made. | |
| 25 | - A deploy files the droplet and volume in it and tags both with the forge's name. A forge made earlier is filed with `file` (see `docs/features/pinned-forge.md`). Hetzner shows no field: a Hetzner token already belongs to one project, so setting one is refused. | |
| 26 | ||
| 22 | 27 | ## Places and prices in US dollars (#16203) |
| 23 | 28 | |
| 24 | 29 | `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. |
docs/features/pinned-forge.md +2 −1
| @@ -9,7 +9,8 @@ A pinned forge is a forge the owner put on their own cloud. The forge that deplo | ||
| 9 | 9 | ## Doors (forge admin, admin-scope token) |
| 10 | 10 | |
| 11 | 11 | - HTTP: `GET /api/v1/admin/pinned` (forges, their changes, the targets), `POST /api/v1/admin/pinned` (deploy; the answer holds `claim.link`), `POST /api/v1/admin/pinned/:name/update`, `POST /api/v1/admin/pinned/:name/rollback`, `POST /api/v1/admin/pinned/:name/claim` (a new claim link). |
| 12 | - Terminal: palette → **Pinned forges** (forge admin): `d` deploy, `u` update, `r` roll back, `n` a new claim link (asked first); a deploy and `n` show the link in a dialog to copy; it follows the bus, so a change made at any door shows at once (`src/tui/screens/pinned.ts`). | |
| 12 | - Terminal: palette → **Pinned forges** (forge admin): `d` deploy, `u` update, `r` roll back, `f` files the forge's machine and volume in its account's cloud project, `n` a new claim link (asked first); a deploy and `n` show the link in a dialog to copy; it follows the bus, so a change made at any door shows at once (`src/tui/screens/pinned.ts`). | |
| 13 | - File in a project (#16340): an account's project (set on Settings → Cloud accounts, `P` in the terminal, `set_project` over MCP; DigitalOcean only, since a Hetzner token already belongs to one project) is where a deploy files the machine and volume it makes, both tagged with the forge. A forge made before the project was set is filed by `file`: the **File in project** button on `/pinned`, `f` on the terminal screen, or the MCP `pinned_forge` verb `file`, all through `fileForge` in `src/actions/pinned.ts`; it is safe to repeat. A deploy into a project that does not exist is refused before anything is made. If the cloud refuses the filing after the machine exists, the machine is kept and a `pinned.unfiled` event says the forge stayed in the default project; run `file` to file it. | |
| 13 | 14 | - Web: `/deploy-to` (forge admin; linked from Cloud accounts) is a server-rendered form for cloud account, app, source, version, name and hostname. Its answer is a page with the claim link, sent `no-store`, not a redirect. The link `/deploy-to?app=owner/name&source=https://…&version=v1.2.3` (`deployToHref` in `src/web/pinned.ts`) lands on it with those filled in after one sign-in; nothing deploys until the button is pressed. The POST is same-origin checked and calls the same `deployPinned` (`src/http/pinned_routes.ts`). |
| 14 | 15 | - Web list: `/pinned` (forge admin; 404 otherwise) is server-rendered, with actions; one block of plain rows per forge: name, app, version, address (a link), health (the state), when the last check ran (the newest `pinned.check` event; `never checked` before the first), and the last change with who and when, from the same `pinnedForges` read as the API (`src/web/pages/pinned.ts`). The intro links `/deploy-to`; an empty list says so. A person can update, roll back and check a forge from `/pinned`, as the terminal's `u`, `r` and `c` do: each row has four buttons (Update, Roll back, Check, New claim link), and each goes through the confirm page before it runs (Update also asks for the version). The row also shows the DNS record and when the claim link runs out. They post to `POST /pinned/:name/:act` (`act` is `update`, `rollback`, `check` or `claim`; admin only, same-origin, 404 for non-admins and unknown acts); the result, or the sentence that refuses it, is shown as a flash on `/pinned` (`src/http/pinned_routes.ts`). |
| 15 | 16 | - MCP: `pinned_forge` with `verb` `list`, `deploy`, `claim`, `update`, `rollback` (and `check`) — the same words and the same checks (`src/actions/pinned.ts`). |
src/actions/cloud_ceiling.ts +21 −1
| @@ -5,7 +5,7 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import type { App } from "../app.ts"; |
| 8 | import { getCloudAccount, setCeilingDollars } from "../core/cloud_account.ts"; | |
| 8 | import { getCloudAccount, setCeilingDollars, setProjectName } from "../core/cloud_account.ts"; | |
| 9 | 9 | import type { User } from "../core/users.ts"; |
| 10 | 10 | import { MAX_WARM, setWarmTarget, warmTargets } from "../cloud/warm_pool.ts"; |
| 11 | 11 | import { err, ok, type Result } from "../kernel/result.ts"; |
| @@ -34,3 +34,23 @@ export function setWarm(app: App, actor: User | undefined, provider: string, nam | ||
| 34 | 34 | app.bus.append({ kind: "cloud.warm_target", actorId: actor.id, payload: { provider, name, place, from, to: count } }); |
| 35 | 35 | return ok(count === 0 ? `no machine is kept warm at ${place}` : `up to ${count} machine${count === 1 ? "" : "s"} kept warm at ${place}, as purchases and the ceiling allow`); |
| 36 | 36 | } |
| 37 | ||
| 38 | const PROJECT = /^[A-Za-z0-9][A-Za-z0-9 ._:-]{0,99}$/; | |
| 39 | ||
| 40 | /** The words where a Hetzner account would name its project: its token already belongs to one. */ | |
| 41 | export const HETZNER_PROJECT_WORDS = "A Hetzner token already belongs to one project, so there is nothing to name: its forges land there."; | |
| 42 | ||
| 43 | /** | |
| 44 | * The cloud project an account's forges are filed in (DigitalOcean); empty goes back to the | |
| 45 | * provider's default. | |
| 46 | */ | |
| 47 | export function setProject(app: App, actor: User | undefined, provider: string, name: string, project: unknown): Result<string, string> { | |
| 48 | if (actor?.isAdmin !== true) return err("not_found"); | |
| 49 | if (typeof project !== "string" || (project !== "" && !PROJECT.test(project))) return err("A project is the name it has at the provider: letters, digits, spaces and . _ : -, up to 100; empty for the default project."); | |
| 50 | const before = getCloudAccount(app.db, provider, name); | |
| 51 | if (!before) return err("No such credential."); | |
| 52 | if (provider === "hetzner") return err(HETZNER_PROJECT_WORDS); | |
| 53 | if (!setProjectName(app.db, provider, name, project)) return err("No such credential."); | |
| 54 | app.bus.append({ kind: "cloud.project", actorId: actor.id, payload: { provider, name, from: before.project, to: project } }); | |
| 55 | return ok(project === "" ? "forges go in the provider's default project" : `forges are filed in the project "${project}"; a missing one refuses a deploy before anything is made`); | |
| 56 | } |
src/actions/pinned.ts +32 −3
| @@ -29,7 +29,7 @@ import type { App } from "../app.ts"; | ||
| 29 | 29 | import { gatedFetch } from "../cloud/gate.ts"; |
| 30 | 30 | import { capped, CeilingRefusal, priced, refusalAt, rowCents } from "../cloud/ceiling.ts"; |
| 31 | 31 | import { driverOf } from "../cloud/drivers.ts"; |
| 32 | import { orderable, provision, read, replace, retire } from "../cloud/machine.ts"; | |
| 32 | import { fileIn, orderable, provision, read, replace, retire } from "../cloud/machine.ts"; | |
| 33 | 33 | import { dollars } from "../cloud/prices.ts"; |
| 34 | 34 | import { chooseDefault, isPlan, meets, type Chosen, type Place, type PlanName } from "../cloud/places.ts"; |
| 35 | 35 | import { inFlight } from "../billing/orders.ts"; |
| @@ -292,6 +292,33 @@ async function unwriteDns(app: App, who: Who, name: string): Promise<"none" | "r | ||
| 292 | 292 | return "kept"; |
| 293 | 293 | } |
| 294 | 294 | |
| 295 | /** The cloud project the row's account files its forges in; empty is the provider's default. */ | |
| 296 | const projectOf = (app: App, p: Pinned): string => getCloudAccount(app.db, p.target, p.account)?.project ?? ""; | |
| 297 | ||
| 298 | /** | |
| 299 | * A machine made but not filed in its project stays in the provider's default one: the event says | |
| 300 | * so, and that `file` files it, for the admin who reads the forge's changes. | |
| 301 | */ | |
| 302 | const unfiled = (app: App, who: Who, name: string) => (why: string): void => { | |
| 303 | app.bus.append({ kind: "pinned.unfiled", actorId: who.id, payload: { name, why, say: `${name} stayed in the provider's default project (${why}); \`file\` files it.`, ...orderOf(who) } }); | |
| 304 | }; | |
| 305 | ||
| 306 | /** | |
| 307 | * File a forge's machine and volume in its account's project (#16340): the one action for a row | |
| 308 | * made before the project was set, and the same call a deploy makes. Idempotent at the cloud. | |
| 309 | */ | |
| 310 | export function fileForge(app: App, actor: User | undefined, name: string): Promise<Result<string, string>> { | |
| 311 | const who = admin(actor); | |
| 312 | if (!who.ok) return Promise.resolve(who); | |
| 313 | const p = getPinned(app.db, name); | |
| 314 | if (!p) return Promise.resolve(err("No such pinned forge.")); | |
| 315 | if (p.state === "retired") return Promise.resolve(err(RETIRED_REFUSAL)); | |
| 316 | const project = projectOf(app, p); | |
| 317 | if (project === "") return Promise.resolve(err("Its cloud account names no project: set one on Settings → Cloud first.")); | |
| 318 | if (p.remote === "" || p.volume === "") return Promise.resolve(err("This forge has no machine and volume to file yet.")); | |
| 319 | return withCloud(app, who.value, p, "file", (f, token) => fileIn(capped(app, p.name, driverOf(p.target)), f, token, p, project)).then((r) => (r.ok ? ok(`${name} is filed in the project "${project}".`) : r)); | |
| 320 | } | |
| 321 | ||
| 295 | 322 | /** Open the account's token and run `go` with a gated fetch; the token never leaves this scope. */ |
| 296 | 323 | async function withCloud<T>(app: App, who: Who, p: Pinned, purpose: string, go: (f: Fetch, token: string) => Promise<T>, writes = true): Promise<Result<T, string>> { |
| 297 | 324 | const account = getCloudAccount(app.db, p.target, p.account); |
| @@ -434,7 +461,9 @@ async function deployAs(app: App, who: Who, input: DeployInput): Promise<Result< | ||
| 434 | 461 | (f, token) => |
| 435 | 462 | provision(capped(app, p.name, driverOf(p.target)), f, token, getPinned(app.db, p.name)!, { |
| 436 | 463 | ...(old?.volume ? { have: old.volume } : {}), |
| 464 | project: projectOf(app, p), | |
| 437 | 465 | onVolume: (volume) => setRemote(app.db, p.name, { volume }), |
| 466 | onUnfiled: unfiled(app, who, p.name), | |
| 438 | 467 | }), |
| 439 | 468 | (m) => setRemote(app.db, p.name, { ...m, state: "running" }), |
| 440 | 469 | ); |
| @@ -486,7 +515,7 @@ async function changeNow( | ||
| 486 | 515 | const after = getPinned(app.db, name)!; |
| 487 | 516 | const done = await create( |
| 488 | 517 | app, who.value, after, kind, |
| 489 | (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, after, { onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }) }), | |
| 518 | (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, after, { project: projectOf(app, after), onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }), onUnfiled: unfiled(app, who.value, name) }), | |
| 490 | 519 | (m) => setRemote(app.db, name, { ...m, address: "", state: "running" }), |
| 491 | 520 | true, |
| 492 | 521 | ); |
| @@ -562,7 +591,7 @@ async function claimNow(app: App, who: Who, name: string, input: { host?: string | ||
| 562 | 591 | const after: Pinned = { ...getPinned(app.db, name)!, claimHash: claim.hash, claimExpires: claim.expires }; |
| 563 | 592 | const done = await create( |
| 564 | 593 | app, who, after, "claim", |
| 565 | (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, after, { onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }) }), | |
| 594 | (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, after, { project: projectOf(app, after), onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }), onUnfiled: unfiled(app, who, name) }), | |
| 566 | 595 | (m) => { |
| 567 | 596 | setClaim(app.db, name, { hash: claim.hash, expires: claim.expires }); |
| 568 | 597 | setRemote(app.db, name, { ...m, address: "", state: "running" }); |
src/cloud/droplet.ts +14 −4
| @@ -4,11 +4,12 @@ | ||
| 4 | 4 | * |
| 5 | 5 | * Calls (DigitalOcean API v2): POST /volumes, POST /account/keys and DELETE /account/keys/{id} (a |
| 6 | 6 | * throwaway key, so no root password is mailed), POST /droplets, DELETE /droplets/{id}, GET |
| 7 | * /droplets/{id} (the public IPv4 the droplet was given, read back after it boots). | |
| 7 | * /droplets/{id} (the public IPv4 the droplet was given, read back after it boots), GET /projects | |
| 8 | * and POST /projects/{id}/resources (file the droplet and volume in the account's project, #16340). | |
| 8 | 9 | */ |
| 9 | 10 | |
| 10 | 11 | import { dropThrowawayKey, makeThrowawayKey } from "./throwaway_key.ts"; |
| 11 | import { bootConfig as boot, ipv4, volumeName, type Booted, type Driver } from "./machine.ts"; | |
| 12 | import { bootConfig as boot, forgeTag, ipv4, volumeName, type Booted, type Driver } from "./machine.ts"; | |
| 12 | 13 | |
| 13 | 14 | export { BUN_VERSION } from "./machine.ts"; |
| 14 | 15 | |
| @@ -24,7 +25,7 @@ const KEYS = "/account/keys"; | ||
| 24 | 25 | export const digitalocean: Driver = { |
| 25 | 26 | api: "https://api.digitalocean.com/v2", |
| 26 | 27 | async createVolume(call, p) { |
| 27 | const v = await call("POST", "/volumes", { name: volumeName(p.name), region: p.datacenter, size_gigabytes: 10, filesystem_type: "ext4" }); | |
| 28 | const v = await call("POST", "/volumes", { name: volumeName(p.name), region: p.datacenter, size_gigabytes: 10, filesystem_type: "ext4", tags: [forgeTag(p.name)] }); | |
| 28 | 29 | return String(v.volume?.id ?? ""); |
| 29 | 30 | }, |
| 30 | 31 | async createMachine(call, p, volume) { |
| @@ -33,13 +34,22 @@ export const digitalocean: Driver = { | ||
| 33 | 34 | try { |
| 34 | 35 | const d = await call("POST", "/droplets", { |
| 35 | 36 | name: `forge-${p.name}`, region: p.datacenter, size: p.size, image: "ubuntu-24-04-x64", |
| 36 | volumes: [volume], user_data: bootConfig(p), tags: ["forge-pinned"], ssh_keys: [Number(key)], | |
| 37 | volumes: [volume], user_data: bootConfig(p), tags: ["forge-pinned", forgeTag(p.name)], ssh_keys: [Number(key)], | |
| 37 | 38 | }); |
| 38 | 39 | return String(d.droplet?.id ?? ""); |
| 39 | 40 | } finally { |
| 40 | 41 | await dropThrowawayKey(call, KEYS, key); |
| 41 | 42 | } |
| 42 | 43 | }, |
| 44 | async projectId(call, name) { | |
| 45 | const all: any[] = (await call("GET", "/projects?per_page=200")).projects ?? []; | |
| 46 | const found = all.find((x) => x?.name === name && typeof x.id === "string"); | |
| 47 | if (!found) throw new Error(`DigitalOcean has no project called "${name}": make it there, or change the account's project. Nothing was made.`); | |
| 48 | return found.id; | |
| 49 | }, | |
| 50 | async assign(call, project, t) { | |
| 51 | await call("POST", `/projects/${encodeURIComponent(project)}/resources`, { resources: [`do:droplet:${t.machine}`, `do:volume:${t.volume}`] }); | |
| 52 | }, | |
| 43 | 53 | async deleteMachine(call, remote) { |
| 44 | 54 | await call("DELETE", `/droplets/${remote}`); |
| 45 | 55 | }, |
src/cloud/hetzner.ts +4 −3
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * Hetzner Cloud (#16200): its calls only; the sequence they run in is |
| 3 | 3 | * machine.ts. A Hetzner token is scoped to one project and is read or |
| 4 | * read-write, nothing narrower. | |
| 4 | * read-write, nothing narrower: it already belongs to one project, so a Hetzner account has no | |
| 5 | * project to name (#16340) and every volume and server carries the label forge=<name> instead. | |
| 5 | 6 | * |
| 6 | 7 | * Calls (Hetzner Cloud API v1): POST /volumes, POST /ssh_keys and DELETE |
| 7 | 8 | * /ssh_keys/{id} (a throwaway key, so no root password is mailed), POST /servers (the volume |
| @@ -26,7 +27,7 @@ const KEYS = "/ssh_keys"; | ||
| 26 | 27 | export const hetzner: Driver = { |
| 27 | 28 | api: "https://api.hetzner.cloud/v1", |
| 28 | 29 | async createVolume(call, p) { |
| 29 | const v = await call("POST", "/volumes", { name: volumeName(p.name), location: p.datacenter, size: 10, format: "ext4", automount: false }); | |
| 30 | const v = await call("POST", "/volumes", { name: volumeName(p.name), location: p.datacenter, size: 10, format: "ext4", automount: false, labels: { "forge-pinned": "true", forge: p.name } }); | |
| 30 | 31 | return String(v.volume?.id ?? ""); |
| 31 | 32 | }, |
| 32 | 33 | async createMachine(call, p, volume) { |
| @@ -36,7 +37,7 @@ export const hetzner: Driver = { | ||
| 36 | 37 | const s = await call("POST", "/servers", { |
| 37 | 38 | name: `forge-${p.name}`, server_type: p.size, location: p.datacenter, image: IMAGE, |
| 38 | 39 | volumes: [Number(volume)], automount: true, user_data: bootConfig(p, volume), ssh_keys: [Number(key)], |
| 39 | public_net: { enable_ipv4: true, enable_ipv6: true }, start_after_create: true, labels: { "forge-pinned": "true" }, | |
| 40 | public_net: { enable_ipv4: true, enable_ipv6: true }, start_after_create: true, labels: { "forge-pinned": "true", forge: p.name }, | |
| 40 | 41 | }); |
| 41 | 42 | return String(s.server?.id ?? ""); |
| 42 | 43 | } finally { |
src/cloud/machine.ts +50 −4
| @@ -173,8 +173,19 @@ export interface Driver { | ||
| 173 | 173 | /** Whether the volume is attached to no machine: a cloud detaches it after a delete answers, and refuses a new machine with it until then. */ |
| 174 | 174 | volumeFree(call: Call, volume: string): Promise<boolean>; |
| 175 | 175 | readMachine(call: Call, remote: string): Promise<{ status: string; address: string }>; |
| 176 | /** | |
| 177 | * The id of the cloud project called `name`, refused in plain words when there is none. Only a | |
| 178 | * cloud whose resources land in a default project has it (DigitalOcean); a Hetzner token already | |
| 179 | * belongs to one project. | |
| 180 | */ | |
| 181 | projectId?(call: Call, name: string): Promise<string>; | |
| 182 | /** File the machine and the volume in the project `projectId` named. */ | |
| 183 | assign?(call: Call, project: string, things: { machine: string; volume: string }): Promise<void>; | |
| 176 | 184 | } |
| 177 | 185 | |
| 186 | /** The tag or label that names a forge on everything the forge makes for it (#16340). */ | |
| 187 | export const forgeTag = (name: string) => `forge:${name}`; | |
| 188 | ||
| 178 | 189 | function caller(d: Driver, f: Fetch, token: string): Call { |
| 179 | 190 | const host = new URL(d.api).host; |
| 180 | 191 | return async (method, path, body) => { |
| @@ -197,17 +208,49 @@ const ID = /^\d+$/; | ||
| 197 | 208 | * machine is asked for. Returns the ids to keep. |
| 198 | 209 | */ |
| 199 | 210 | export async function provision( |
| 200 | d: Driver, f: Fetch, token: string, p: Pinned, hooks: { have?: string; onVolume(id: string): void }, | |
| 211 | d: Driver, f: Fetch, token: string, p: Pinned, hooks: { have?: string; project?: string; onVolume(id: string): void; onUnfiled?(why: string): void }, | |
| 201 | 212 | ): Promise<{ remote: string; volume: string }> { |
| 202 | 213 | const call = caller(d, f, token); |
| 203 | 214 | d.admit?.(p); |
| 215 | // A project that does not exist refuses before anything is made. | |
| 216 | const project = await projectOf(d, call, hooks.project); | |
| 204 | 217 | let volume = hooks.have ?? ""; |
| 205 | 218 | if (volume === "") { |
| 206 | 219 | volume = await d.createVolume(call, p); |
| 207 | 220 | if (volume === "") throw new Error(`${new URL(d.api).host} made no volume`); |
| 208 | 221 | hooks.onVolume(volume); |
| 209 | 222 | } |
| 210 | return { remote: await d.createMachine(call, p, volume), volume }; | |
| 223 | const remote = await d.createMachine(call, p, volume); | |
| 224 | await file(d, call, project, remote, volume, hooks.onUnfiled); | |
| 225 | return { remote, volume }; | |
| 226 | } | |
| 227 | ||
| 228 | async function projectOf(d: Driver, call: Call, name: string | undefined): Promise<string> { | |
| 229 | return name && d.projectId ? d.projectId(call, name) : ""; | |
| 230 | } | |
| 231 | ||
| 232 | /** | |
| 233 | * File what exists in the project. A refusal here never undoes or hides the machine, which is | |
| 234 | * made and must be recorded: the forge stays in the default project until `fileIn` is asked again, | |
| 235 | * and `onUnfiled` is told why so the caller can say so. | |
| 236 | */ | |
| 237 | async function file(d: Driver, call: Call, project: string, machine: string, volume: string, onUnfiled?: (why: string) => void): Promise<void> { | |
| 238 | if (project === "" || !d.assign) return; | |
| 239 | try { | |
| 240 | await d.assign(call, project, { machine, volume }); | |
| 241 | } catch (e) { | |
| 242 | onUnfiled?.(e instanceof Error ? e.message.slice(0, 200) : "failed"); | |
| 243 | } | |
| 244 | } | |
| 245 | ||
| 246 | /** | |
| 247 | * File a forge's machine and volume in the project `name` (a row made before the project was set). | |
| 248 | */ | |
| 249 | export async function fileIn(d: Driver, f: Fetch, token: string, p: Pinned, name: string): Promise<void> { | |
| 250 | if (!d.projectId || !d.assign) throw new Error("this cloud has no projects to file a forge in"); | |
| 251 | if (p.remote === "" || p.volume === "") throw new Error("this forge has no machine and volume to file"); | |
| 252 | const call = caller(d, f, token); | |
| 253 | await d.assign(call, await d.projectId(call, name), { machine: p.remote, volume: p.volume }); | |
| 211 | 254 | } |
| 212 | 255 | |
| 213 | 256 | /** |
| @@ -219,12 +262,13 @@ export async function provision( | ||
| 219 | 262 | * does not delete twice. |
| 220 | 263 | */ |
| 221 | 264 | export async function replace( |
| 222 | d: Driver, f: Fetch, token: string, p: Pinned, hooks: { onDeleted(): void }, | |
| 265 | d: Driver, f: Fetch, token: string, p: Pinned, hooks: { project?: string; onDeleted(): void; onUnfiled?(why: string): void }, | |
| 223 | 266 | ): Promise<{ remote: string }> { |
| 224 | 267 | if (p.volume === "") throw new Error("this forge has no volume to keep"); |
| 225 | 268 | if (p.remote !== "" && !ID.test(p.remote)) throw new Error("this forge has no machine to replace"); |
| 226 | 269 | const call = caller(d, f, token); |
| 227 | 270 | d.admit?.(p); |
| 271 | const project = await projectOf(d, call, hooks.project); | |
| 228 | 272 | if (p.remote !== "") { |
| 229 | 273 | try { |
| 230 | 274 | await d.deleteMachine(call, p.remote); |
| @@ -234,7 +278,9 @@ export async function replace( | ||
| 234 | 278 | hooks.onDeleted(); |
| 235 | 279 | await untilFree(d, call, p.volume); |
| 236 | 280 | } |
| 237 | return { remote: await d.createMachine(call, p, p.volume) }; | |
| 281 | const remote = await d.createMachine(call, p, p.volume); | |
| 282 | await file(d, call, project, remote, p.volume, hooks.onUnfiled); | |
| 283 | return { remote }; | |
| 238 | 284 | } |
| 239 | 285 | |
| 240 | 286 | /** How long a replace waits for the old machine to let go of the volume, and how often it asks. */ |
src/core/cloud_account.ts +12
| @@ -52,6 +52,11 @@ export interface CloudAccount { | ||
| 52 | 52 | readonly writeAllowed: boolean; |
| 53 | 53 | /** The most the forge will let this account cost a month, whole US dollars (ceiling.ts). */ |
| 54 | 54 | readonly ceilingDollars: number; |
| 55 | /** | |
| 56 | * The cloud project its machines and volumes are filed in (DigitalOcean); empty is the provider's | |
| 57 | * default. | |
| 58 | */ | |
| 59 | readonly project: string; | |
| 55 | 60 | } |
| 56 | 61 | |
| 57 | 62 | interface Row { |
| @@ -61,6 +66,7 @@ interface Row { | ||
| 61 | 66 | verified_at: string | null; |
| 62 | 67 | write_allowed: number; |
| 63 | 68 | ceiling_dollars: number; |
| 69 | project: string; | |
| 64 | 70 | } |
| 65 | 71 | |
| 66 | 72 | const toAccount = (r: Row): CloudAccount => ({ |
| @@ -70,6 +76,7 @@ const toAccount = (r: Row): CloudAccount => ({ | ||
| 70 | 76 | verifiedAt: r.verified_at, |
| 71 | 77 | writeAllowed: r.write_allowed === 1, |
| 72 | 78 | ceilingDollars: r.ceiling_dollars, |
| 79 | project: r.project ?? "", | |
| 73 | 80 | }); |
| 74 | 81 | |
| 75 | 82 | export function listCloudAccounts(db: Database): CloudAccount[] { |
| @@ -130,6 +137,11 @@ export function setCeilingDollars(db: Database, provider: string, name: string, | ||
| 130 | 137 | return db.query("UPDATE cloud_account SET ceiling_dollars = ?3 WHERE provider = ?1 AND name = ?2").run(provider, name, dollars).changes > 0; |
| 131 | 138 | } |
| 132 | 139 | |
| 140 | export function setProjectName(db: Database, provider: string, name: string, project: string): boolean { | |
| 141 | table(db); | |
| 142 | return db.query("UPDATE cloud_account SET project = ?3 WHERE provider = ?1 AND name = ?2").run(provider, name, project).changes > 0; | |
| 143 | } | |
| 144 | ||
| 133 | 145 | export function renameCloudAccount( |
| 134 | 146 | db: Database, |
| 135 | 147 | provider: string, |
src/core/event_audience.ts +1
| @@ -307,6 +307,7 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 307 | 307 | kind === "forge.updates_taken" || |
| 308 | 308 | kind === "cloud.write_allowed" || |
| 309 | 309 | kind === "cloud.ceiling" || |
| 310 | kind === "cloud.project" || | |
| 310 | 311 | // How many prepared machines a plan keeps waiting is a spend choice (`cloud/warm_pool.ts`, |
| 311 | 312 | // #16362). |
| 312 | 313 | kind === "cloud.warm_target" || |
src/core/migration-pins/20261127100000-cloud-account-project.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | e12b67a55c1d59558e90a98fee8bf24077db280c9420107dec62777a6b81b97b |
src/core/migrations/20261127100000-cloud-account-project.ts added +5
src/http/marks/settings.json +1
src/http/mcp/tools/cloud_account.ts +12 −9
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | import { addAccount, allowWrite, auditAccount, removeAccount, renameAccount, reverify, rotateAccount } from "../../../actions/cloud.ts"; |
| 2 | import { setCeiling, setWarm } from "../../../actions/cloud_ceiling.ts"; | |
| 2 | import { setCeiling, setProject, setWarm } from "../../../actions/cloud_ceiling.ts"; | |
| 3 | 3 | import { PROVIDERS } from "../../../cloud/providers.ts"; |
| 4 | 4 | import { scopeAllows } from "../../../core/tokens.ts"; |
| 5 | 5 | import { good, bad, type Tool, str } from "../shared.ts"; |
| @@ -7,13 +7,13 @@ import { good, bad, type Tool, str } from "../shared.ts"; | ||
| 7 | 7 | export const tool: Tool = { |
| 8 | 8 | name: "cloud_account", |
| 9 | 9 | listedTo: "admin", |
| 10 | doc: "`{ verb, provider, name, value?, to?, allowed?, repo?, dollars?, place?, count? }`: change a cloud account: `attach` or `rotate` a token (`value`), `verify` it, `rename` it (`to`), `remove` it, `allow_writes` (`allowed` true or false), `set_ceiling` (`dollars`: the most the forge lets it cost a month, whole US dollars, 50 until changed) `set_warm` (`place`, `count`: how many prepared machines to keep booted and waiting at a place, 0 until set, counted against the ceiling and shown beside it), or `audit` (`repo` owner/name); a forge admin with an admin-scope token; answers a one-line `says`", | |
| 10 | doc: "`{ verb, provider, name, value?, to?, allowed?, repo?, dollars?, place?, count?, project? }`: change a cloud account: `attach` or `rotate` a token (`value`), `verify` it, `rename` it (`to`), `remove` it, `allow_writes` (`allowed` true or false), `set_ceiling` (`dollars`: the most the forge lets it cost a month, whole US dollars, 50 until changed) `set_project` (`project`: the DigitalOcean project its forges are filed in, empty for the default; a Hetzner token already has one), `set_warm` (`place`, `count`: how many prepared machines to keep booted and waiting at a place, 0 until set, counted against the ceiling and shown beside it), or `audit` (`repo` owner/name); a forge admin with an admin-scope token; answers a one-line `says`", | |
| 11 | 11 | description: |
| 12 | 12 | "Change a cloud account by `verb` (admin).", |
| 13 | 13 | inputSchema: { |
| 14 | 14 | type: "object", |
| 15 | 15 | properties: { |
| 16 | verb: { type: "string", enum: ["attach", "verify", "rotate", "rename", "remove", "allow_writes", "set_ceiling", "set_warm", "audit"] }, | |
| 16 | verb: { type: "string", enum: ["attach", "verify", "rotate", "rename", "remove", "allow_writes", "set_ceiling", "set_project", "set_warm", "audit"] }, | |
| 17 | 17 | provider: { type: "string", enum: [...PROVIDERS] }, |
| 18 | 18 | name: { type: "string", maxLength: 32 }, |
| 19 | 19 | value: { type: "string", maxLength: 4096, description: "For attach, rotate." }, |
| @@ -22,6 +22,7 @@ export const tool: Tool = { | ||
| 22 | 22 | repo: { type: "string", maxLength: 200 }, |
| 23 | 23 | place: { type: "string", maxLength: 100, description: "For set_warm: provider:datacenter:size." }, |
| 24 | 24 | count: { type: "integer", minimum: 0, maximum: 10, description: "For set_warm." }, |
| 25 | project: { type: "string", maxLength: 100, description: "For set_project." }, | |
| 25 | 26 | dollars: { type: "integer", minimum: 0, maximum: 100000, description: "For set_ceiling." }, |
| 26 | 27 | }, |
| 27 | 28 | required: ["verb", "provider", "name"], |
| @@ -54,12 +55,14 @@ export const tool: Tool = { | ||
| 54 | 55 | ? allowWrite(ctx.app, user, provider, name, args["allowed"] === true) |
| 55 | 56 | : verb === "set_ceiling" |
| 56 | 57 | ? setCeiling(ctx.app, user, provider, name, args["dollars"]) |
| 57 | : verb === "set_warm" | |
| 58 | ? setWarm(ctx.app, user, provider, name, args["place"], args["count"]) | |
| 59 | : verb === "audit" | |
| 60 | ? await auditAccount(ctx.app, user, provider, name, str(args["repo"])) | |
| 61 | : undefined; | |
| 62 | if (done === undefined) return bad("bad_verb", "verb is attach, verify, rotate, rename, remove, allow_writes, set_ceiling, set_warm or audit"); | |
| 58 | : verb === "set_project" | |
| 59 | ? setProject(ctx.app, user, provider, name, args["project"]) | |
| 60 | : verb === "set_warm" | |
| 61 | ? setWarm(ctx.app, user, provider, name, args["place"], args["count"]) | |
| 62 | : verb === "audit" | |
| 63 | ? await auditAccount(ctx.app, user, provider, name, str(args["repo"])) | |
| 64 | : undefined; | |
| 65 | if (done === undefined) return bad("bad_verb", "verb is attach, verify, rotate, rename, remove, allow_writes, set_ceiling, set_project, set_warm or audit"); | |
| 63 | 66 | if (!done.ok) return bad("refused", done.error); |
| 64 | 67 | const v = done.value as unknown; |
| 65 | 68 | const said = |
src/http/mcp/tools/pinned_forge.ts +8 −4
| @@ -1,4 +1,4 @@ | ||
| 1 | import { DOMAIN_WORDS, changeBaseDomain, checkPinned, checkWords, claimPinned, claimWords, deployPinned, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned } from "../../../actions/pinned.ts"; | |
| 1 | import { DOMAIN_WORDS, changeBaseDomain, checkPinned, checkWords, claimPinned, claimWords, deployPinned, fileForge, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned } from "../../../actions/pinned.ts"; | |
| 2 | 2 | import { TARGETS } from "../../../cloud/targets.ts"; |
| 3 | 3 | import { scopeAllows } from "../../../core/tokens.ts"; |
| 4 | 4 | import { good, bad, type Tool, str } from "../shared.ts"; |
| @@ -6,7 +6,7 @@ import { good, bad, type Tool, str } from "../shared.ts"; | ||
| 6 | 6 | export const tool: Tool = { |
| 7 | 7 | name: "pinned_forge", |
| 8 | 8 | listedTo: "admin", |
| 9 | doc: "`{ verb, name?, host?, domain?, withData?, despiteClaim?, target?, account?, app?, source?, version?, place?, config? }`: a forge on the owner's cloud. `deploy`: `app` from `source` at `version` on a writable `account`, at `place` (default: the small plan's), on `host` (default `<name>.<domain>`; Cloudflare writes the record); answers once with `claim.link` and `dns`. `claim`: a fresh link while unclaimed. `update`: change `version` or `config`. `rollback`: back one. `domain`: read or set the domain. `check`: `waiting` or `url`, `healthy`, `claim`. `retire`: delete the machine, keep the data (`withData` deletes it). `list`: all, with changes. A forge admin with an admin-scope token", | |
| 9 | doc: "`{ verb, name?, host?, domain?, withData?, despiteClaim?, target?, account?, app?, source?, version?, place?, config? }`: a forge on the owner's cloud. `deploy`: `app` from `source` at `version` on a writable `account`, at `place` (default: the small plan's), on `host` (default `<name>.<domain>`; Cloudflare writes the record); answers once with `claim.link` and `dns`. `claim`: a fresh link while unclaimed. `update`: change `version` or `config`. `rollback`: back one. `domain`: read or set the domain. `check`: `waiting` or `url`, `healthy`, `claim`. `retire`: delete the machine, keep the data (`withData` deletes it). `file`: put its machine and volume in its cloud account's project (a forge made before the project was set). `list`: all, with changes. A forge admin with an admin-scope token", | |
| 10 | 10 | description: "Pinned forges on your cloud: list, deploy, claim, update, rollback, check, retire (admin).", |
| 11 | 11 | tier: "delete", |
| 12 | 12 | deletes: (args) => args["verb"] === "retire" && args["withData"] === true, |
| @@ -14,7 +14,7 @@ export const tool: Tool = { | ||
| 14 | 14 | inputSchema: { |
| 15 | 15 | type: "object", |
| 16 | 16 | properties: { |
| 17 | verb: { type: "string", enum: ["list", "deploy", "claim", "update", "rollback", "check", "domain", "retire"] }, | |
| 17 | verb: { type: "string", enum: ["list", "deploy", "claim", "update", "rollback", "check", "domain", "retire", "file"] }, | |
| 18 | 18 | withData: { type: "boolean", description: "Retire: delete the data too; no undo." }, |
| 19 | 19 | despiteClaim: { type: "boolean", description: "Retire a forge its buyer claimed." }, |
| 20 | 20 | domain: { type: "string", maxLength: 253, description: "Domain for deployed forges; empty clears." }, |
| @@ -70,6 +70,10 @@ export const tool: Tool = { | ||
| 70 | 70 | const done = await retirePinned(ctx.app, user, name, { withData: args["withData"] === true, despiteClaim: args["despiteClaim"] === true }); |
| 71 | 71 | return done.ok ? good({ says: retireWords(done.value), forge: done.value }) : bad("refused", done.error); |
| 72 | 72 | } |
| 73 | if (verb === "file") { | |
| 74 | const filed = await fileForge(ctx.app, user, name); | |
| 75 | return filed.ok ? good({ says: filed.value }) : bad("refused", filed.error); | |
| 76 | } | |
| 73 | 77 | if (verb === "check") { |
| 74 | 78 | const seen = await checkPinned(ctx.app, user, name); |
| 75 | 79 | return seen.ok ? good({ says: `check ${name}: now ${seen.value.version}. ${checkWords(seen.value)}`, forge: seen.value }) : bad("refused", seen.error); |
| @@ -83,7 +87,7 @@ export const tool: Tool = { | ||
| 83 | 87 | : verb === "rollback" |
| 84 | 88 | ? await rollbackPinned(ctx.app, user, name) |
| 85 | 89 | : undefined; |
| 86 | if (done === undefined) return bad("bad_verb", "verb is list, deploy, claim, update, rollback, check, retire or domain"); | |
| 90 | if (done === undefined) return bad("bad_verb", "verb is list, deploy, claim, update, rollback, check, retire, file or domain"); | |
| 87 | 91 | if (!done.ok) return bad("refused", done.error); |
| 88 | 92 | return good({ says: `${verb} ${name}: now ${done.value.version}, ${done.value.state}${done.value.url ? ` at ${done.value.url}` : ""}.`, forge: done.value }); |
| 89 | 93 | }, |
src/http/pinned_routes.ts +4 −1
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | * never through a redirect or a flash: it is shown once and stored nowhere. |
| 8 | 8 | */ |
| 9 | 9 | |
| 10 | import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, deployPinned, deployPlaces, pinnedForges, retirePinned, retireWords, rollbackPinned, updatePinned, type Issued } from "../actions/pinned.ts"; | |
| 10 | import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, deployPinned, fileForge, deployPlaces, pinnedForges, retirePinned, retireWords, rollbackPinned, updatePinned, type Issued } from "../actions/pinned.ts"; | |
| 11 | 11 | import { TARGETS } from "../cloud/targets.ts"; |
| 12 | 12 | import { listCloudAccounts } from "../core/cloud_account.ts"; |
| 13 | 13 | import { lastCheckOf } from "../core/pinned.ts"; |
| @@ -112,6 +112,9 @@ async function pinnedAct(ctx: Ctx): Promise<Response> { | ||
| 112 | 112 | // the confirm page. A claimed forge is retired only when the form says the owner means it. |
| 113 | 113 | const gone = await retirePinned(ctx.app, user, name, { withData: act === "retire-data", despiteClaim: field(form, "despite_claim") === "1" }); |
| 114 | 114 | return flashTo(ctx, "/pinned", gone.ok ? { tone: "success", message: retireWords(gone.value) } : { tone: "danger", message: gone.error }); |
| 115 | } else if (act === "file") { | |
| 116 | const filed = await fileForge(ctx.app, user, name); | |
| 117 | return flashTo(ctx, "/pinned", filed.ok ? { tone: "success", message: filed.value } : { tone: "danger", message: filed.error }); | |
| 115 | 118 | } else if (act === "claim") { |
| 116 | 119 | const made = await claimPinned(ctx.app, user, name, { host: field(form, "host") }); |
| 117 | 120 | return made.ok ? shown(ctx, `A new claim link for ${name}`, made.value) : flashTo(ctx, "/pinned", { tone: "danger", message: made.error }); |
src/http/settings_routes.ts +2
| @@ -69,6 +69,7 @@ import { | ||
| 69 | 69 | cloudAudit, |
| 70 | 70 | cloudAuditPage, |
| 71 | 71 | cloudCeiling, |
| 72 | cloudProject, | |
| 72 | 73 | cloudRename, |
| 73 | 74 | cloudRotate, |
| 74 | 75 | cloudPage, |
| @@ -237,6 +238,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 237 | 238 | router.add("POST", "/settings/cloud/verify", cloudVerify); |
| 238 | 239 | router.add("POST", "/settings/cloud/write", cloudWrite); |
| 239 | 240 | router.add("POST", "/settings/cloud/ceiling", cloudCeiling); |
| 241 | router.add("POST", "/settings/cloud/project", cloudProject); | |
| 240 | 242 | router.add("POST", "/settings/cloud/audit", cloudAudit); |
| 241 | 243 | router.add("GET", "/settings/cloud/audit", cloudAuditPage); |
| 242 | 244 | router.add("POST", "/settings/cloud/rotate", cloudRotate); |
src/tui/screens/cloud.ts +15
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | */ |
| 9 | 9 | |
| 10 | 10 | import { addAccount, allowWrite, auditAccount, removeAccount, renameAccount, reverify, rotateAccount } from "../../actions/cloud.ts"; |
| 11 | import { setProject } from "../../actions/cloud_ceiling.ts"; | |
| 11 | 12 | import { usesByVendor, type VendorUse } from "../../cloud/declared.ts"; |
| 12 | 13 | import { cloudOverview } from "../../cloud/overview.ts"; |
| 13 | 14 | import { dollars } from "../../cloud/prices.ts"; |
| @@ -120,6 +121,7 @@ export function cloudScreen(f: Session, ctx: Ctx): Screen { | ||
| 120 | 121 | binding(["n"], "rename"), |
| 121 | 122 | binding(["x"], "remove"), |
| 122 | 123 | binding(["w"], "writes on/off"), |
| 124 | binding(["P"], "project for its forges"), | |
| 123 | 125 | binding(["A"], "audit"), |
| 124 | 126 | binding(["c"], "calls today"), |
| 125 | 127 | ], |
| @@ -178,6 +180,19 @@ export function cloudScreen(f: Session, ctx: Ctx): Screen { | ||
| 178 | 180 | }, |
| 179 | 181 | }), |
| 180 | 182 | ); |
| 183 | else if (e.key === "P") | |
| 184 | ctx.push( | |
| 185 | promptScreen(ctx, screen, { | |
| 186 | title: `Project for the forges of ${provider}/${name}`, | |
| 187 | label: "the cloud project its machines and volumes are filed in; empty for the default", | |
| 188 | onSubmit: (project) => { | |
| 189 | const r = setProject(f.app, f.user, provider, name, project.trim()); | |
| 190 | if (!r.ok) return r.error; | |
| 191 | say(`Saved: ${r.value}.`); | |
| 192 | return undefined; | |
| 193 | }, | |
| 194 | }), | |
| 195 | ); | |
| 181 | 196 | else if (e.key === "w") { |
| 182 | 197 | const r = allowWrite(f.app, f.user, provider, name, !a.writeAllowed); |
| 183 | 198 | say(r.ok ? `${provider}/${name}: ${a.writeAllowed ? "read-only" : "writes allowed"}.` : r.error); |
src/tui/screens/pinned.ts +12 −9
| @@ -2,16 +2,16 @@ | ||
| 2 | 2 | * Pinned forges in the terminal, a forge admin's (#8697): each forge with its |
| 3 | 3 | * version, state and last changes, as the API lists them. `d` deploys, `u` |
| 4 | 4 | * updates (the only way its version or config move), `r` rolls back to the |
| 5 | * previous version, `c` reads the address back and probes it, `n` issues a | |
| 6 | * new claim link (shown once, as a deploy's is), `b` sets the domain deployed forges are served on | |
| 7 | * (a deploy then needs no hostname: `-` in its place), `x` retires a forge (its machine goes, its data | |
| 8 | * is kept unless the name is typed to delete it too; a claimed forge is asked about twice), each through | |
| 9 | * `actions/pinned.ts`, so the checks, the record of who and when and the events | |
| 10 | * the web screens follow are the API's. | |
| 11 | * Anyone else sees nothing and does nothing. | |
| 5 | * previous version, `f` files its machine and volume in its account's cloud project, `c` reads the | |
| 6 | * address back and probes it, `n` issues a new claim link (shown once, as a deploy's is), `b` sets | |
| 7 | * the domain deployed forges are served on (a deploy then needs no hostname: `-` in its place), `x` | |
| 8 | * retires a forge (its machine goes, its data is kept unless the name is typed to delete it too; a | |
| 9 | * claimed forge is asked about twice), each through `actions/pinned.ts`, so the checks, the record | |
| 10 | * of who and when and the events the web screens follow are the API's. Anyone else sees nothing and | |
| 11 | * does nothing. | |
| 12 | 12 | */ |
| 13 | 13 | |
| 14 | import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, claimWords, deployPinned, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned, type Issued } from "../../actions/pinned.ts"; | |
| 14 | import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, claimWords, deployPinned, fileForge, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned, type Issued } from "../../actions/pinned.ts"; | |
| 15 | 15 | import type { Ctx, Screen } from "../app/app.ts"; |
| 16 | 16 | import { binding } from "../app/keys.ts"; |
| 17 | 17 | import { style } from "../term/style.ts"; |
| @@ -137,7 +137,7 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen { | ||
| 137 | 137 | |
| 138 | 138 | const screen: Screen = { |
| 139 | 139 | title: "Pinned forges", |
| 140 | keys: [binding(["j", "k"], "move cursor"), binding(["d"], "deploy"), binding(["u"], "update"), binding(["r"], "roll back"), binding(["c"], "check"), binding(["n"], "new claim link"), binding(["b"], "domain for forges"), binding(["p"], "paid forges run on"), binding(["x"], "retire")], | |
| 140 | keys: [binding(["j", "k"], "move cursor"), binding(["d"], "deploy"), binding(["u"], "update"), binding(["r"], "roll back"), binding(["c"], "check"), binding(["f"], "file in its cloud project"), binding(["n"], "new claim link"), binding(["b"], "domain for forges"), binding(["p"], "paid forges run on"), binding(["x"], "retire")], | |
| 141 | 141 | async load(signal) { |
| 142 | 142 | live(f, signal, { kinds: ["pinned.deployed", "pinned.update", "pinned.rollback", "pinned.check", "pinned.claim_issued", "pinned.claimed"] }, () => ctx.invalidate()); |
| 143 | 143 | }, |
| @@ -205,6 +205,9 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen { | ||
| 205 | 205 | } else if (e.key === "c") { |
| 206 | 206 | say(`Checking ${p.name}…`); |
| 207 | 207 | void checkPinned(f.app, f.user, p.name).then((r) => say(r.ok ? checkWords(r.value) : r.error)); |
| 208 | } else if (e.key === "f") { | |
| 209 | say(`Filing ${p.name} in its cloud project…`); | |
| 210 | void fileForge(f.app, f.user, p.name).then((r) => say(r.ok ? r.value : r.error)); | |
| 208 | 211 | } else if (e.key === "n") offerClaim(f, ctx, screen, say, p); |
| 209 | 212 | else if (e.key === "x") offerRetire(f, ctx, screen, say, p); |
| 210 | 213 | else if (e.key === "u") |
src/web/pages/cloud.ts +19 −1
| @@ -33,7 +33,7 @@ import { nameFrame, notePhase, takeSessionTime, timePhase, timePhaseAsync } from | ||
| 33 | 33 | import type { Ctx } from "../../http/context.ts"; |
| 34 | 34 | import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts"; |
| 35 | 35 | import { field, readForm } from "../form.ts"; |
| 36 | import { setCeiling } from "../../actions/cloud_ceiling.ts"; | |
| 36 | import { setCeiling, setProject } from "../../actions/cloud_ceiling.ts"; | |
| 37 | 37 | import { html, type Html } from "../html.ts"; |
| 38 | 38 | import { flashTo, page } from "../layout.ts"; |
| 39 | 39 | import { btn, confirmAction, icon, row, time } from "../ui.ts"; |
| @@ -96,6 +96,14 @@ function accountsCard(db: Database, accounts: CloudAccount[], reads: CloudRead[] | ||
| 96 | 96 | aria-label="Monthly ceiling in US dollars for ${a.name}" required /> |
| 97 | 97 | ${btn("Set ceiling", { size: "sm", label: `Set the ceiling of ${a.name}` })} |
| 98 | 98 | </form> |
| 99 | ${a.provider === "digitalocean" | |
| 100 | ? html`<form method="post" action="/settings/cloud/project" class="row-fields"> | |
| 101 | ${hidden(a.provider, a.name)} | |
| 102 | <input class="input" type="text" name="project" value="${a.project}" placeholder="project for its forges" | |
| 103 | aria-label="Cloud project for the forges of ${a.name}" maxlength="100" /> | |
| 104 | ${btn("Set project", { size: "sm", label: `Set the project of ${a.name}` })} | |
| 105 | </form>` | |
| 106 | : ""} | |
| 99 | 107 | <form method="post" action="/settings/cloud/audit" class="row-fields"> |
| 100 | 108 | ${hidden(a.provider, a.name)} |
| 101 | 109 | <input class="input" type="text" name="repo" placeholder="owner/repo for findings" |
| @@ -236,6 +244,16 @@ export async function cloudCeiling(ctx: Ctx): Promise<Response> { | ||
| 236 | 244 | return flashTo(ctx, "/settings/cloud", r.ok ? { message: `Saved: ${r.value}.` } : { tone: "danger", message: r.error }); |
| 237 | 245 | } |
| 238 | 246 | |
| 247 | // POST /settings/cloud/project: the cloud project an account's forges are filed in. | |
| 248 | export async function cloudProject(ctx: Ctx): Promise<Response> { | |
| 249 | const denied = requireAdmin(ctx); | |
| 250 | if (denied) return denied; | |
| 251 | const form = await readForm(ctx, "admin"); | |
| 252 | if (form instanceof Response) return form; | |
| 253 | const r = setProject(ctx.app, ctx.auth.user, field(form, "provider"), field(form, "name"), field(form, "project").trim()); | |
| 254 | return flashTo(ctx, "/settings/cloud", r.ok ? { message: `Saved: ${r.value}.` } : { tone: "danger", message: r.error }); | |
| 255 | } | |
| 256 | ||
| 239 | 257 | // POST /settings/cloud/audit |
| 240 | 258 | export async function cloudAudit(ctx: Ctx): Promise<Response> { |
| 241 | 259 | const denied = requireAdmin(ctx); |
src/web/pages/pinned.ts +5
| @@ -36,6 +36,10 @@ function actions(p: PinnedView): Html { | ||
| 36 | 36 | <input type="hidden" name="to" value="${to("check")}" /> |
| 37 | 37 | ${btn("Check", { variant: "ghost", label: `Check ${p.name}` })} |
| 38 | 38 | </form>`; |
| 39 | const file = html`<form method="get" action="/-/confirm"> | |
| 40 | <input type="hidden" name="to" value="${to("file")}" /> | |
| 41 | ${btn("File in project", { variant: "ghost", label: `File ${p.name} in its cloud project` })} | |
| 42 | </form>`; | |
| 39 | 43 | // Retire asks the confirm page; a claimed forge's form says the owner means it (`despite_claim`). |
| 40 | 44 | const retire = (act: string, label: string, claimed: boolean): Html => html`<form method="get" action="/-/confirm"> |
| 41 | 45 | <input type="hidden" name="to" value="${to(act)}" /> |
| @@ -57,6 +61,7 @@ function actions(p: PinnedView): Html { | ||
| 57 | 61 | ${btn("Roll back", { variant: "secondary", label: `Roll back ${p.name}` })} |
| 58 | 62 | </form> |
| 59 | 63 | ${check} |
| 64 | ${p.volume === "" ? null : file} | |
| 60 | 65 | <form method="get" action="/-/confirm"> |
| 61 | 66 | <input type="hidden" name="to" value="${to("claim")}" /> |
| 62 | 67 | ${p.host === "" ? html`<input class="mono" name="host" placeholder="forge.example.com" maxlength="253" required spellcheck="false" autocomplete="off" aria-label="Hostname for ${p.name}" />` : null} |
test/cloud-page-shape.test.ts +13 −1
| @@ -4,7 +4,8 @@ import { mkdtemp, rm } from "node:fs/promises"; | ||
| 4 | 4 | import { tmpdir } from "node:os"; |
| 5 | 5 | import { join } from "node:path"; |
| 6 | 6 | import { createApp, type App } from "../src/app.ts"; |
| 7 | import { createUser } from "../src/core/users.ts"; | |
| 7 | import { addAccount, net as cloudNet } from "../src/actions/cloud.ts"; | |
| 8 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 8 | 9 | import { serve, type Servers } from "../src/http/server.ts"; |
| 9 | 10 | import { quietLogs } from "./helpers/globals.ts"; |
| 10 | 11 | |
| @@ -71,3 +72,14 @@ test("a signed-in non-admin gets the gate's 403 for the vendor calls", async () | ||
| 71 | 72 | expect(res.status).toBe(403); |
| 72 | 73 | expect(await res.text()).not.toContain("vendor call"); |
| 73 | 74 | }); |
| 75 | ||
| 76 | test("a Hetzner row has no project field and no explanation; a DigitalOcean row has the field", async () => { | |
| 77 | cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" }, servers: [] }), { status: 200 }); | |
| 78 | const alice = getUserByName(app.db, "alice")!; | |
| 79 | await addAccount(app, alice, "hetzner", "main", "hcloud_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9"); | |
| 80 | await addAccount(app, alice, "digitalocean", "main", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"); | |
| 81 | const page = await (await fetch(`${servers.url}/settings/cloud`, { headers: { cookie } })).text(); | |
| 82 | expect(page).toContain("Cloud project for the forges of main"); | |
| 83 | expect(page.match(/Cloud project for the forges of/g)).toHaveLength(1); | |
| 84 | expect(page).not.toContain("already belongs to one project"); | |
| 85 | }); |
test/pinned-ceiling.test.ts +2 −2
| @@ -369,8 +369,8 @@ describe("cloud account ceiling", () => { | ||
| 369 | 369 | } |
| 370 | 370 | expect(bare).toEqual([]); |
| 371 | 371 | // Deploy, update or rollback (asked, then made), a new claim link, the read and the retire: the |
| 372 | // six there are. | |
| 373 | expect(uses).toBe(6); | |
| 372 | // and filing in a project (#16340): the seven there are. | |
| 373 | expect(uses).toBe(7); | |
| 374 | 374 | }); |
| 375 | 375 | }); |
| 376 | 376 |
test/pinned-project-actions.test.ts added +111
| @@ -0,0 +1,111 @@ | ||
| 1 | /** | |
| 2 | * #16340 end to end through the actions: the account's project, a deploy that files, one that | |
| 3 | * refuses, and `file`. | |
| 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 { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts"; | |
| 11 | import { setProject } from "../src/actions/cloud_ceiling.ts"; | |
| 12 | import { deployPinned, fileForge, net } from "../src/actions/pinned.ts"; | |
| 13 | import { getCloudAccount } from "../src/core/cloud_account.ts"; | |
| 14 | import { getPinned } from "../src/core/pinned.ts"; | |
| 15 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 16 | import { quietLogs } from "./helpers/globals.ts"; | |
| 17 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 18 | ||
| 19 | quietLogs(); | |
| 20 | ||
| 21 | let dataDir = ""; | |
| 22 | let app: App; | |
| 23 | let projects: unknown[] = [{ id: "p1", name: "forges" }]; | |
| 24 | const calls: { method: string; path: string; body: any }[] = []; | |
| 25 | const admin = () => getUserByName(app.db, "alice")!; | |
| 26 | const input = (name: string) => ({ name, host: `${name}.forge.test`, target: "digitalocean", account: "main", app: "alice/shop", source: "https://forge.example.org/trevato/forge", version: "a".repeat(40), config: {} }); | |
| 27 | ||
| 28 | beforeAll(async () => { | |
| 29 | dataDir = await mkdtemp(join(tmpdir(), "forge-project-")); | |
| 30 | app = createApp({ dataDir, port: 0 }); | |
| 31 | await seedPlaces(app.db); | |
| 32 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 33 | if (!made.ok) throw new Error(made.error); | |
| 34 | cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" } }), { status: 200 }); | |
| 35 | const added = await addAccount(app, admin(), "digitalocean", "main", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"); | |
| 36 | if (!added.ok) throw new Error(String(added.error)); | |
| 37 | allowWrite(app, admin(), "digitalocean", "main", true); | |
| 38 | await addAccount(app, admin(), "hetzner", "main", "hcloud_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9"); | |
| 39 | let seq = 100; | |
| 40 | net.fetch = async (url, init) => { | |
| 41 | const u = new URL(url); | |
| 42 | const method = init?.method ?? "GET"; | |
| 43 | calls.push({ method, path: u.pathname, body: init?.body ? JSON.parse(String(init.body)) : undefined }); | |
| 44 | const json = (o: unknown) => new Response(JSON.stringify(o), { status: 200 }); | |
| 45 | if (u.pathname === "/v2/projects") return json({ projects }); | |
| 46 | if (u.pathname === "/v2/volumes") return json({ volume: { id: `vol-${++seq}` } }); | |
| 47 | if (u.pathname === "/v2/account/keys" && method === "POST") return json({ ssh_key: { id: 4242 } }); | |
| 48 | if (method === "DELETE") return new Response(null, { status: 204 }); | |
| 49 | if (u.pathname === "/v2/droplets") return json({ droplet: { id: ++seq } }); | |
| 50 | return json({}); | |
| 51 | }; | |
| 52 | }, 30_000); | |
| 53 | ||
| 54 | afterAll(async () => { | |
| 55 | app.close(); | |
| 56 | await rm(dataDir, { recursive: true, force: true }); | |
| 57 | }); | |
| 58 | ||
| 59 | const creates = () => calls.filter((c) => c.method === "POST" && /\/(volumes|droplets)$/.test(c.path)); | |
| 60 | ||
| 61 | test("the project is a field of the account, set by an admin only, and Hetzner has none to name", () => { | |
| 62 | expect(setProject(app, undefined, "digitalocean", "main", "forges")).toEqual({ ok: false, error: "not_found" }); | |
| 63 | expect(setProject(app, admin(), "digitalocean", "main", "bad<name>").ok).toBe(false); | |
| 64 | expect(setProject(app, admin(), "digitalocean", "nope", "forges").ok).toBe(false); | |
| 65 | const h = setProject(app, admin(), "hetzner", "main", "forges"); | |
| 66 | expect(h.ok === false && h.error).toContain("already belongs to one project"); | |
| 67 | expect(setProject(app, admin(), "digitalocean", "main", "forges").ok).toBe(true); | |
| 68 | expect(getCloudAccount(app.db, "digitalocean", "main")!.project).toBe("forges"); | |
| 69 | }); | |
| 70 | ||
| 71 | test("a deploy into a project that does not exist is refused with zero creates", async () => { | |
| 72 | projects = [{ id: "p0", name: "first-project" }]; | |
| 73 | calls.length = 0; | |
| 74 | const r = await deployPinned(app, admin(), input("lost")); | |
| 75 | expect(r.ok).toBe(false); | |
| 76 | expect(String((r as { error: string }).error)).toContain('no project called "forges"'); | |
| 77 | expect(creates()).toEqual([]); | |
| 78 | }); | |
| 79 | ||
| 80 | test("a deploy files its droplet and volume, and a forge made before can be filed by one call", async () => { | |
| 81 | projects = [{ id: "p1", name: "forges" }]; | |
| 82 | calls.length = 0; | |
| 83 | expect((await deployPinned(app, admin(), input("test1"))).ok).toBe(true); | |
| 84 | const filed = calls.filter((c) => c.path === "/v2/projects/p1/resources"); | |
| 85 | expect(filed).toHaveLength(1); | |
| 86 | const p = getPinned(app.db, "test1")!; | |
| 87 | expect(filed[0]!.body.resources).toEqual([`do:droplet:${p.remote}`, `do:volume:${p.volume}`]); | |
| 88 | calls.length = 0; | |
| 89 | const again = await fileForge(app, admin(), "test1"); | |
| 90 | expect(again.ok).toBe(true); | |
| 91 | expect(calls.filter((c) => c.path === "/v2/projects/p1/resources")).toHaveLength(1); | |
| 92 | expect((await fileForge(app, undefined, "test1")).ok).toBe(false); | |
| 93 | setProject(app, admin(), "digitalocean", "main", ""); | |
| 94 | expect((await fileForge(app, admin(), "test1")).ok).toBe(false); | |
| 95 | }); | |
| 96 | ||
| 97 | test("a filing the cloud refuses leaves the forge made and says on the bus that it stayed unfiled", async () => { | |
| 98 | setProject(app, admin(), "digitalocean", "main", "forges"); | |
| 99 | projects = [{ id: "p1", name: "forges" }]; | |
| 100 | const was = net.fetch; | |
| 101 | net.fetch = (url, init) => (new URL(url).pathname.endsWith("/resources") ? Promise.resolve(new Response("{}", { status: 500 })) : was(url, init)); | |
| 102 | try { | |
| 103 | expect((await deployPinned(app, admin(), input("test2"))).ok).toBe(true); | |
| 104 | } finally { | |
| 105 | net.fetch = was; | |
| 106 | } | |
| 107 | expect(getPinned(app.db, "test2")!.remote).not.toBe(""); | |
| 108 | const seen = app.db.query("SELECT payload FROM event WHERE kind = 'pinned.unfiled'").get() as { payload: string } | null; | |
| 109 | expect(JSON.parse(seen!.payload)).toMatchObject({ name: "test2" }); | |
| 110 | expect(seen!.payload).toContain("`file`"); | |
| 111 | }); |
test/pinned-project.test.ts added +99
| @@ -0,0 +1,99 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { digitalocean } from "../src/cloud/droplet.ts"; | |
| 3 | import { hetzner } from "../src/cloud/hetzner.ts"; | |
| 4 | import { DETACH, fileIn, provision, replace } from "../src/cloud/machine.ts"; | |
| 5 | ||
| 6 | // #16340: a forge's droplet and volume are filed in the account's cloud project, and carry a tag | |
| 7 | // naming the forge; a project that is not there refuses before anything is made. | |
| 8 | const p = { name: "test1", datacenter: "fra1", size: "s-1vcpu-1gb", remote: "11", volume: "vol-a", source: "https://x.test/r.git", version: "v1.0.0", config: {}, host: "t.example.test", claimHash: "", claimExpires: "" } as any; | |
| 9 | ||
| 10 | function recorded(projects: unknown[]) { | |
| 11 | const log: { method: string; path: string; body: any }[] = []; | |
| 12 | const f = (async (url: string, init: any) => { | |
| 13 | const path = String(url).replace("https://api.digitalocean.com/v2", ""); | |
| 14 | const body = init.body ? JSON.parse(init.body) : undefined; | |
| 15 | log.push({ method: init.method, path, body }); | |
| 16 | const json = (o: unknown) => new Response(JSON.stringify(o), { status: 200 }); | |
| 17 | if (path.startsWith("/projects?")) return json({ projects }); | |
| 18 | if (path === "/volumes" && init.method === "POST") return json({ volume: { id: "vol-a" } }); | |
| 19 | if (path === "/account/keys" && init.method === "POST") return json({ ssh_key: { id: 5 } }); | |
| 20 | if (path === "/droplets" && init.method === "POST") return json({ droplet: { id: 22 } }); | |
| 21 | if (path.startsWith("/volumes/")) return json({ volume: { droplet_ids: [] } }); | |
| 22 | return json({}); | |
| 23 | }) as any; | |
| 24 | return { f, log }; | |
| 25 | } | |
| 26 | const FORGES = [{ id: "proj-1", name: "forges" }, { id: "proj-0", name: "first-project" }]; | |
| 27 | const assigns = (log: { method: string; path: string; body: any }[]) => log.filter((c) => c.path.endsWith("/resources")); | |
| 28 | ||
| 29 | test("a deploy files the droplet and the volume in the named project and tags both", async () => { | |
| 30 | const { f, log } = recorded(FORGES); | |
| 31 | const made = await provision(digitalocean, f, "t", p, { project: "forges", onVolume() {} }); | |
| 32 | expect(made).toEqual({ remote: "22", volume: "vol-a" }); | |
| 33 | expect(assigns(log)).toEqual([{ method: "POST", path: "/projects/proj-1/resources", body: { resources: ["do:droplet:22", "do:volume:vol-a"] } }]); | |
| 34 | expect(log.find((c) => c.path === "/volumes")!.body.tags).toEqual(["forge:test1"]); | |
| 35 | expect(log.find((c) => c.path === "/droplets")!.body.tags).toContain("forge:test1"); | |
| 36 | expect(log.indexOf(assigns(log)[0]!)).toBeGreaterThan(log.findIndex((c) => c.path === "/droplets")); | |
| 37 | }); | |
| 38 | ||
| 39 | test("a project that is not there refuses with nothing made", async () => { | |
| 40 | const { f, log } = recorded([{ id: "proj-0", name: "first-project" }]); | |
| 41 | await expect(provision(digitalocean, f, "t", p, { project: "forges", onVolume() {} })).rejects.toThrow('no project called "forges"'); | |
| 42 | expect(log.filter((c) => c.method === "POST")).toEqual([]); | |
| 43 | }); | |
| 44 | ||
| 45 | test("a replace files the new droplet the same way, and refuses before deleting when the project is gone", async () => { | |
| 46 | const keep = { ...DETACH }; | |
| 47 | DETACH.everyMs = 1; | |
| 48 | try { | |
| 49 | const { f, log } = recorded(FORGES); | |
| 50 | expect((await replace(digitalocean, f, "t", p, { project: "forges", onDeleted() {} })).remote).toBe("22"); | |
| 51 | expect(assigns(log)[0]!.body).toEqual({ resources: ["do:droplet:22", "do:volume:vol-a"] }); | |
| 52 | const none = recorded([]); | |
| 53 | await expect(replace(digitalocean, none.f, "t", p, { project: "forges", onDeleted() {} })).rejects.toThrow("no project"); | |
| 54 | expect(none.log.some((c) => c.method === "DELETE" || c.method === "POST")).toBe(false); | |
| 55 | } finally { Object.assign(DETACH, keep); } | |
| 56 | }); | |
| 57 | ||
| 58 | test("a refused filing keeps the machine that was made", async () => { | |
| 59 | const { f, log } = recorded(FORGES); | |
| 60 | const bad = ((url: string, init: any) => String(url).endsWith("/resources") ? Promise.resolve(new Response("{}", { status: 500 })) : f(url, init)) as any; | |
| 61 | expect((await provision(digitalocean, bad, "t", p, { project: "forges", onVolume() {} })).remote).toBe("22"); | |
| 62 | expect(log.some((c) => c.path === "/droplets")).toBe(true); | |
| 63 | }); | |
| 64 | ||
| 65 | test("a refused filing is told to onUnfiled, with the reason", async () => { | |
| 66 | const { f } = recorded(FORGES); | |
| 67 | const bad = ((url: string, init: any) => String(url).endsWith("/resources") ? Promise.resolve(new Response("{}", { status: 500 })) : f(url, init)) as any; | |
| 68 | const told: string[] = []; | |
| 69 | await provision(digitalocean, bad, "t", p, { project: "forges", onVolume() {}, onUnfiled: (why) => told.push(why) }); | |
| 70 | expect(told).toEqual(["api.digitalocean.com answered 500"]); | |
| 71 | const ok = recorded(FORGES); | |
| 72 | await provision(digitalocean, ok.f, "t", p, { project: "forges", onVolume() {}, onUnfiled: (why) => told.push(why) }); | |
| 73 | expect(told.length).toBe(1); | |
| 74 | }); | |
| 75 | ||
| 76 | test("a row made before the project was set is filed by one call", async () => { | |
| 77 | const { f, log } = recorded(FORGES); | |
| 78 | await fileIn(digitalocean, f, "t", p, "forges"); | |
| 79 | expect(assigns(log)).toHaveLength(1); | |
| 80 | expect(assigns(log)[0]!.body.resources).toEqual(["do:droplet:11", "do:volume:vol-a"]); | |
| 81 | }); | |
| 82 | ||
| 83 | test("Hetzner has no project to name, and labels the server and the volume with the forge", async () => { | |
| 84 | const log: { path: string; body: any }[] = []; | |
| 85 | const f = (async (url: string, init: any) => { | |
| 86 | const path = String(url).replace("https://api.hetzner.cloud/v1", ""); | |
| 87 | log.push({ path, body: init.body ? JSON.parse(init.body) : undefined }); | |
| 88 | const json = (o: unknown) => new Response(JSON.stringify(o), { status: 200 }); | |
| 89 | if (path === "/volumes") return json({ volume: { id: 7 } }); | |
| 90 | if (path === "/ssh_keys" && init.method === "POST") return json({ ssh_key: { id: 5 } }); | |
| 91 | if (path === "/servers") return json({ server: { id: 8 } }); | |
| 92 | return json({}); | |
| 93 | }) as any; | |
| 94 | await provision(hetzner, f, "t", p, { project: "forges", onVolume() {} }); | |
| 95 | expect(log.some((c) => c.path.includes("project"))).toBe(false); | |
| 96 | expect(log.find((c) => c.path === "/volumes")!.body.labels.forge).toBe("test1"); | |
| 97 | expect(log.find((c) => c.path === "/servers")!.body.labels.forge).toBe("test1"); | |
| 98 | await expect(fileIn(hetzner, f, "t", p, "forges")).rejects.toThrow("no projects"); | |
| 99 | }); |
new above
offline
Both doors:
fileForgeis reachable only through MCP. Add a terminal entry in src/tui/ and a page action, and document it in docs/features/pinned-forge.md.