Public: anyone can read this; the crew can change it.
A paid forge can run on its own cloud machine, bought through the same New forge door #16354
Check · Review · Land · Live — No review yet.
sold/paid-forges-on-cloud → main 8 commits
18 files
changed +1031
−95
docs/features/pinned-forge.md +10
| @@ -71,6 +71,16 @@ An admin names the **domain for deployed forges** (`forges.example.com`) on Pinn | ||
| 71 | 71 | |
| 72 | 72 | With a **Cloudflare** cloud account attached and writes allowed, the forge then writes the record itself: after the machine has an address (the deploy, and every Update, Roll back and new claim link), and again on Check, it upserts `<host> A <address>` in the zone that holds the name, through the first such account whose token can edit that zone: found by name and updated, or made, so a replaced machine's new address changes the record and never adds one; DNS only (not proxied, so the machine gets its own certificate), TTL 60. The calls go to `api.cloudflare.com` only (`upsertARecord`, `src/cloud/providers.ts`), the token in the Authorization header alone, each call audited as `pinned:dns` like the other cloud calls; the record's id and zone are kept (`pinned_dns`) with the account that wrote it. A zone the token cannot see or edit, a CNAME already at the name, or any refusal leaves the record for a person to make, and the deploy answer and Check say that instead (`dnsWrittenBy` is empty). The token needs DNS edit on the zone; the cloud account's check cannot tell that, so the first write is the proof. |
| 73 | 73 | |
| 74 | ## Paid forges on a cloud machine (#16205) | |
| 75 | ||
| 76 | An admin chooses where **paid forges run** on Pinned forges (`/pinned`; the terminal's `p`; `PATCH /api/v1/admin/settings` with `{"paidPlacement": "digitalocean/main"}`, `"hosted"` or `null` for the default; `GET` answers it as `paidPlacement`). It is a forge setting (`settings/paid_placement.ts`, `paid.placement`, every change kept with who and when). `hosted`, the default, is today's: a bought forge runs inside this one. A cloud account (one a pinned forge can be deployed to, with writes allowed) makes each paid order a pinned forge of its own (`src/spawn/cloud_placement.ts`). Free forges always stay hosted. | |
| 77 | ||
| 78 | - **Told before paying.** `/pricing` (and the terminal's pricing screen) asks the cloud placement's `room` before the checkout is made: no domain for deployed forges, a catalog never read, a default place that cannot be ordered, or a deploy the account's ceiling would refuse, each is said in the deploy's own sentence, and nothing is held or charged. | |
| 79 | - **Deployed as the order.** Once paid, the forge is deployed at the catalog's default place for the plan, with no hostname (it is served on `<name>.<domain>`), running the forge's own source repository (public, cloned from this forge over https) at the commit this forge runs (`FORGE_COMMIT`; the release tag when the build names none; a forge run from source refuses). The deploy acts as the order, never a borrowed admin: the row's history says `order:<id>`, its events carry `order` and no actor, and the token reads name the order in their run. Every refusal an admin's deploy has (target, catalog, place, ceiling) applies. | |
| 80 | - **Making, then the link.** A machine takes minutes, so the order is `making` (`/pricing/done` says so and refreshes) until the forge answers on its name: the pinned check, asked as the order at most every 15 seconds by the order's row, by the page and by this process for 15 minutes after the deploy. The claim link is the pinned one, issued with the machine: kept sealed as a forge secret (`ORDER_CLAIM_<id>`, each read audited) until the order is `spawned`, then mailed (when the forge can mail) and shown once on the done page, after which it is deleted. | |
| 81 | - **Never two machines, never hosted instead.** A restart while making only asks again. A spawn lost to a restart after its machine was recorded issues a new claim instead (the machine replaced on its own volume); one lost before is deployed again on its volume. A refused deploy leaves the order `failed` with the sentence, for an admin to retry or refund; it is never made hosted. | |
| 82 | - **Not yet.** Lapse and cancel do nothing to a cloud forge; `/pricing/resend` cannot issue a new link for one (it would replace the machine); the crew credit a paid plan lends is lent over loopback to hosted forges and does not reach a cloud one (the plan rows on `/pricing` still state it); the after-payment steps, the lapse words, the key note and the `<name>--<parent>` address on `/pricing` still describe a hosted forge. | |
| 83 | ||
| 74 | 84 | ## Retiring a forge (#16219) |
| 75 | 85 | |
| 76 | 86 | A test forge, or one whose buyer left, would bill forever without a way out. **Retire** (`POST /api/v1/admin/pinned/:name/retire`, the `pinned_forge` tool's `retire` verb, Retire on `/pinned`, `x` in the terminal) deletes the forge's machine and the DNS record the forge wrote for it (job above), and keeps its data volume: the answer says what keeping it costs a month at list price. The row ends `retired`, and the account's ceiling counts it at that volume's price alone. The volume is deleted only by the second word: `withData` on the API and the tool, **Retire and delete its data** on the page (which asks for the forge's name), and a second choice and the name in the terminal. That call is the data-destroying one under the delete tier (`tier: "delete"` on the tool, `test/delete-tier.test.ts`): the forge's own agent is refused it with the page to use. A **retired forge** can be retired again with its data, and nothing else: Update, Roll back, a new claim link and Check refuse it. It is idempotent: a machine or volume already gone at the cloud (a 404) is done, so asking again finishes a retire whose volume the cloud would not delete (the machine is gone and the forge `retired` by then, its data kept). A forge its buyer has claimed, as the forge itself says when asked (or as recorded), is refused with the sentence that its data is on that volume, unless `despiteClaim` says the owner means it (the page's form for a claimed forge carries it; the terminal asks in its question). One event, `pinned.retired`, says who, whether the data went, and what became of the record. |
src/actions/order.ts +109 −2
| @@ -11,11 +11,18 @@ | ||
| 11 | 11 | * The claim link is shown once, on the return page, and mailed when the |
| 12 | 12 | * forge can send mail. It is never kept: the page makes a fresh one when the |
| 13 | 13 | * buyer arrives, and a buyer who left can ask for one by email. |
| 14 | * | |
| 15 | * When paid forges run on a cloud account (`settings/paid_placement.ts`, #16205) the forge is a | |
| 16 | * pinned forge of its own (`spawn/cloud_placement.ts`), deployed as the order, and the order is | |
| 17 | * `making` until it answers on its name. Its claim link is the pinned one, issued with the | |
| 18 | * machine: kept sealed (a forge secret, read with an audit line) until the buyer is shown it, and | |
| 19 | * shown and mailed only once the forge answers. Nothing about such an order falls back to a hosted | |
| 20 | * forge: a deploy that is refused leaves it `failed`, saying why. | |
| 14 | 21 | */ |
| 15 | 22 | |
| 16 | 23 | import type { App } from "../app.ts"; |
| 17 | 24 | import { checkoutOf } from "../billing/checkout.ts"; |
| 18 | import { getOrder, holdName, markResent, markShown, move, unmarkShown, pendingFrom, MAX_PENDING_PER_ADDRESS, CHECKOUT_MS, nameHeld, newId, newTicket, dropPending, pendingCount, setSession, spawnedFor, ticketFits, MAX_PENDING, type Order } from "../billing/orders.ts"; | |
| 25 | import { getOrder, holdName, markResent, markShown, move, takeTurn, unmarkShown, pendingFrom, MAX_PENDING_PER_ADDRESS, CHECKOUT_MS, nameHeld, newId, newTicket, dropPending, pendingCount, setSession, spawnedFor, ticketFits, MAX_PENDING, type Order } from "../billing/orders.ts"; | |
| 19 | 26 | import { putEntitlement } from "../billing/store.ts"; |
| 20 | 27 | import { heldOf } from "../perf/held.ts"; |
| 21 | 28 | import { getUserByName, type User } from "../core/users.ts"; |
| @@ -28,6 +35,12 @@ import { FREE, getPlan, type Plan } from "../settings/plans.ts"; | ||
| 28 | 35 | import { listChildrenNow, reissueClaimFor } from "./spawn.ts"; |
| 29 | 36 | import { mayMail, sendCapped } from "./mail.ts"; |
| 30 | 37 | import { mailerOf } from "./verify.ts"; |
| 38 | import { deleteSecret, resolveSecrets, setSecret } from "../core/secret_store.ts"; | |
| 39 | import { getPinned } from "../core/pinned.ts"; | |
| 40 | import { getPaidPlacement } from "../settings/paid_placement.ts"; | |
| 41 | import { catalogPlan, cloudAnswers, cloudPlacement } from "../spawn/cloud_placement.ts"; | |
| 42 | import type { Placement } from "../spawn/placement.ts"; | |
| 43 | import type { SpawnPlan } from "../spawn/plan.ts"; | |
| 31 | 44 | |
| 32 | 45 | export interface Refusal { |
| 33 | 46 | readonly field: "name" | "email" | "plan" | "form"; |
| @@ -38,6 +51,10 @@ const ADDRESS = /^[^\s<>@,;:"\\]{1,64}@[^\s<>@,;:"\\]{1,190}$/; | ||
| 38 | 51 | export const NO_PROVIDER = "Checkout is not connected on this forge: ask the operator."; |
| 39 | 52 | /** A spawn that stays `spawning` this long is taken as lost and may be retried. */ |
| 40 | 53 | const STALE_MS = 5 * 60_000; |
| 54 | /** | |
| 55 | * A `making` order's forge is asked whether it answers at most this often, however many pages wait. | |
| 56 | */ | |
| 57 | const ASK_MS = 15_000; | |
| 41 | 58 | /** A claim link is mailed again at most once a day per order: a stranger cannot make it a mail-bomb. */ |
| 42 | 59 | const RESEND_MS = 24 * 60 * 60_000; |
| 43 | 60 | |
| @@ -63,7 +80,7 @@ export const emailOf = (raw: unknown): string | undefined => { | ||
| 63 | 80 | /** Every refusal of a name, in one sentence, or undefined when it is free to buy. */ |
| 64 | 81 | export async function nameRefusal(app: App, name: string, plan: Plan, now: number): Promise<string | undefined> { |
| 65 | 82 | if (!isChildName(name) || name.length > 38) return "Use 1 to 38 lowercase letters, digits and dashes, not starting or ending with a dash"; |
| 66 | if (getUserByName(app.db, name) !== undefined || listChildrenNow(app).some((c) => c.name === name)) return "That name is taken"; | |
| 83 | if (getUserByName(app.db, name) !== undefined || listChildrenNow(app).some((c) => c.name === name) || getPinned(app.db, name) !== undefined) return "That name is taken"; | |
| 67 | 84 | if (nameHeld(app.db, name, now)) return "That name is held for someone else; try another"; |
| 68 | 85 | // The door's own plan: reserved words and the rest of the name's rules, with nothing made. |
| 69 | 86 | const dry = await spawnDoor(systemCtx(app), undefined, { name, apps: [], crew: [], plan: plan.key, dryRun: true }, { paid: true }); |
| @@ -92,6 +109,10 @@ export async function placeOrder(app: App, input: { name: unknown; plan: unknown | ||
| 92 | 109 | if (pendingFrom(app.db, input.address, now) >= MAX_PENDING_PER_ADDRESS) return err({ field: "form", message: "You have orders waiting already; finish one or try again in half an hour" }); |
| 93 | 110 | const refused = await nameRefusal(app, name, plan, now); |
| 94 | 111 | if (refused !== undefined) return err({ field: "name", message: refused }); |
| 112 | // Told before paying: what a cloud deploy would refuse now (the ceiling, the catalog), in its own | |
| 113 | // words. | |
| 114 | const full = cloudFor(app, "", plan)?.room?.(); | |
| 115 | if (full !== undefined) return err({ field: "form", message: full.message.replace(/\.$/, "") }); | |
| 95 | 116 | const id = newId(); |
| 96 | 117 | const ticket = newTicket(); |
| 97 | 118 | if (!holdName(app.db, { id, name, plan: plan.key, priceUsd: plan.priceUsd, email, ticket, address: input.address }, now)) return err({ field: "name", message: "That name is held for someone else; try another" }); |
| @@ -162,6 +183,23 @@ async function makeForge(app: App, id: string, from: "paid" | "failed" | "spawni | ||
| 162 | 183 | } |
| 163 | 184 | } |
| 164 | 185 | |
| 186 | /** | |
| 187 | * The placement a paid order on `plan` is made by when paid forges run on a cloud account; none | |
| 188 | * when they are hosted. | |
| 189 | */ | |
| 190 | function cloudFor(app: App, orderId: string, plan: Plan): Placement | undefined { | |
| 191 | const at = getPaidPlacement(app.db); | |
| 192 | return at.where === "cloud" ? cloudPlacement(app, at, { orderId, plan: catalogPlan(plan.size) }) : undefined; | |
| 193 | } | |
| 194 | ||
| 195 | /** | |
| 196 | * The sealed claim link of a cloud order, by order id: a forge secret, so it is read with an audit | |
| 197 | * line. | |
| 198 | */ | |
| 199 | const linkName = (id: string): string => `ORDER_CLAIM_${id.toUpperCase()}`; | |
| 200 | const keptLink = (app: App, id: string): string | undefined => | |
| 201 | resolveSecrets(app.db, app.config.dataDir, app.bus, [linkName(id)], { run: `order:${id}` })[linkName(id)]; | |
| 202 | ||
| 165 | 203 | async function spawnOrder(app: App, id: string): Promise<Order | undefined> { |
| 166 | 204 | const o = getOrder(app.db, id) as Order; |
| 167 | 205 | const fail = (reason: string): Order => { |
| @@ -173,6 +211,8 @@ async function spawnOrder(app: App, id: string): Promise<Order | undefined> { | ||
| 173 | 211 | try { |
| 174 | 212 | const plan = getPlan(app.db, o.plan); |
| 175 | 213 | if (plan === undefined) return fail(`the ${o.plan} plan is no longer offered`); |
| 214 | const cloud = cloudFor(app, id, plan); | |
| 215 | if (cloud !== undefined) return await placeOnCloud(app, o, plan, cloud, fail); | |
| 176 | 216 | const door = await spawnDoor(systemCtx(app), undefined, { name: o.name, apps: [], crew: [], plan: plan.key, dryRun: false }, { paid: true }); |
| 177 | 217 | if (door.status >= 400) return fail(String(door.body["message"] ?? "the forge could not be made").slice(0, 300)); |
| 178 | 218 | putEntitlement(app.db, { |
| @@ -188,6 +228,66 @@ async function spawnOrder(app: App, id: string): Promise<Order | undefined> { | ||
| 188 | 228 | } |
| 189 | 229 | } |
| 190 | 230 | |
| 231 | /** | |
| 232 | * A paid order's forge on a cloud machine: the name's rules through the same door a hosted order | |
| 233 | * takes (a plan, nothing made), then the cloud placement deploys it as the order. Its link is | |
| 234 | * kept sealed and the order is `making` until the forge answers (`askMaking`). | |
| 235 | */ | |
| 236 | async function placeOnCloud(app: App, o: Order, plan: Plan, cloud: Placement, fail: (reason: string) => Order): Promise<Order | undefined> { | |
| 237 | const dry = await spawnDoor(systemCtx(app), undefined, { name: o.name, apps: [], crew: [], plan: plan.key, dryRun: true }, { paid: true }); | |
| 238 | if (dry.status >= 400) return fail(String(dry.body["message"] ?? "the forge could not be made").slice(0, 300)); | |
| 239 | const placed = await cloud.place(dry.body["plan"] as SpawnPlan); | |
| 240 | if (!placed.ok) return fail(placed.error.message.slice(0, 300)); | |
| 241 | if (placed.value.claimUrl === undefined) return fail("the cloud deploy gave no claim link"); | |
| 242 | const kept = setSecret(app.db, app.config.dataDir, "forge", "", linkName(o.id), placed.value.claimUrl); | |
| 243 | if (!kept.ok) return fail("the claim link could not be kept"); | |
| 244 | putEntitlement(app.db, { | |
| 245 | forge: o.name, plan: plan.key, status: "active", provider: checkoutOf(app)?.name ?? "none", payer: o.email, | |
| 246 | customerId: o.customerId, subscriptionId: o.subscriptionId, source: checkoutOf(app)?.name ?? "paid", | |
| 247 | }, plan.size, ""); | |
| 248 | if (!move(app.db, o.id, "spawning", "making", Date.now())) move(app.db, o.id, "failed", "making", Date.now()); | |
| 249 | app.bus.append({ kind: "billing.order_making", payload: { id: o.id, forge: o.name, plan: plan.key, url: placed.value.url } }); | |
| 250 | void followMaking(app, o.id); | |
| 251 | return getOrder(app.db, o.id); | |
| 252 | } | |
| 253 | ||
| 254 | /** How long, and how often, this process asks after a `making` order with no page waiting on it. */ | |
| 255 | export const makingWatch = { everyMs: ASK_MS, tries: 60 }; | |
| 256 | ||
| 257 | /** | |
| 258 | * A buyer who closed the page still gets the link by mail: this process asks after the order | |
| 259 | * every `makingWatch.everyMs`, for at most `tries`, until it is no longer `making`. Holds nothing | |
| 260 | * but its own timer (unref'd); a restart drops it, and the return page asks again. | |
| 261 | */ | |
| 262 | async function followMaking(app: App, id: string): Promise<void> { | |
| 263 | try { | |
| 264 | for (let i = 0; i < makingWatch.tries; i++) { | |
| 265 | await new Promise((r) => setTimeout(r, makingWatch.everyMs).unref()); | |
| 266 | const o = getOrder(app.db, id); | |
| 267 | if (o?.state !== "making") return; | |
| 268 | await askMaking(app, o, Date.now()); | |
| 269 | } | |
| 270 | } catch (e) { | |
| 271 | app.log.warn("a making order could not be asked after", { id, says: String(e).slice(0, 200) }); | |
| 272 | } | |
| 273 | } | |
| 274 | ||
| 275 | /** | |
| 276 | * Ask a `making` order's forge whether it answers on its name (the pinned check, as the order), at | |
| 277 | * most every `ASK_MS` and one asker at a time, by the row. Once it does the order is `spawned` | |
| 278 | * and its kept link mailed, when the forge can mail. Never deploys anything: a restart while | |
| 279 | * making only asks again. | |
| 280 | */ | |
| 281 | async function askMaking(app: App, o: Order, now: number): Promise<Order | undefined> { | |
| 282 | if (now - o.updatedAt < ASK_MS || !takeTurn(app.db, o.id, "making", o.updatedAt, now)) return o; | |
| 283 | const seen = await cloudAnswers(app, o.id, o.name); | |
| 284 | if (!seen.ok || !seen.value || !move(app.db, o.id, "making", "spawned", Date.now())) return getOrder(app.db, o.id); | |
| 285 | app.bus.append({ kind: "billing.order_spawned", payload: { id: o.id, forge: o.name, plan: o.plan } }); | |
| 286 | const link = keptLink(app, o.id); | |
| 287 | if (link !== undefined && (await mailLink(app, o, link))) markResent(app.db, o.id, Date.now()); | |
| 288 | return getOrder(app.db, o.id); | |
| 289 | } | |
| 290 | ||
| 191 | 291 | /** An event from the provider says this session was paid: settle its order, if it is one of ours. */ |
| 192 | 292 | export async function settleSession(app: App, session: { id?: unknown; metadata?: { order?: unknown } | null; customer?: unknown; subscription?: unknown; payment_status?: unknown }): Promise<Order | undefined> { |
| 193 | 293 | if (session.payment_status !== "paid" && session.payment_status !== "no_payment_required") return undefined; |
| @@ -217,6 +317,7 @@ export async function reconcileOrder(app: App, id: string): Promise<Order | unde | ||
| 217 | 317 | if (o === undefined) return undefined; |
| 218 | 318 | if (o.state === "spawning" && Date.now() - o.updatedAt > STALE_MS) return makeForge(app, id, "spawning"); |
| 219 | 319 | if (o.state === "paid") return makeForge(app, id, "paid"); |
| 320 | if (o.state === "making") return askMaking(app, o, Date.now()); | |
| 220 | 321 | if (o.state !== "pending" || o.sessionId === "") return o; |
| 221 | 322 | const provider = checkoutOf(app); |
| 222 | 323 | if (provider === undefined) return o; |
| @@ -248,6 +349,12 @@ async function mailLink(app: App, o: Order, link: string): Promise<boolean> { | ||
| 248 | 349 | export async function deliverLink(app: App, o: Order): Promise<Delivered> { |
| 249 | 350 | if (o.state !== "spawned") return { kind: "failed" }; |
| 250 | 351 | if (!markShown(app.db, o.id, Date.now())) return { kind: "shown" }; |
| 352 | // A cloud order's link was issued with its machine and kept sealed: shown now, and kept no more. | |
| 353 | const kept = keptLink(app, o.id); | |
| 354 | if (kept !== undefined) { | |
| 355 | deleteSecret(app.db, "forge", "", linkName(o.id)); | |
| 356 | return { kind: "link", claimUrl: kept, mailed: o.resentAt !== null }; | |
| 357 | } | |
| 251 | 358 | const made = await reissueClaimFor(app, o.name); |
| 252 | 359 | if (!made.ok) { |
| 253 | 360 | unmarkShown(app.db, o.id); |
src/actions/pinned.ts +172 −61
| @@ -27,11 +27,11 @@ | ||
| 27 | 27 | import { resolve4 } from "node:dns/promises"; |
| 28 | 28 | import type { App } from "../app.ts"; |
| 29 | 29 | import { gatedFetch } from "../cloud/gate.ts"; |
| 30 | import { capped, CeilingRefusal, priced, rowCents } from "../cloud/ceiling.ts"; | |
| 30 | import { capped, CeilingRefusal, priced, refusalAt, rowCents } from "../cloud/ceiling.ts"; | |
| 31 | 31 | import { driverOf } from "../cloud/drivers.ts"; |
| 32 | 32 | import { orderable, provision, read, replace, retire } from "../cloud/machine.ts"; |
| 33 | 33 | import { dollars } from "../cloud/prices.ts"; |
| 34 | import { chooseDefault, meets, type Place } from "../cloud/places.ts"; | |
| 34 | import { chooseDefault, meets, type Place, type PlanName } from "../cloud/places.ts"; | |
| 35 | 35 | import { MAX_ID, keptPlaces, pinOf } from "../cloud/places_read.ts"; |
| 36 | 36 | import { keptRate } from "../cloud/rates.ts"; |
| 37 | 37 | import { deleteARecord, upsertARecord, type Fetch } from "../cloud/providers.ts"; |
| @@ -44,6 +44,7 @@ import { | ||
| 44 | 44 | } from "../core/pinned.ts"; |
| 45 | 45 | import { resolveSecrets } from "../core/secret_store.ts"; |
| 46 | 46 | import { DOMAIN_WORDS, getBaseDomain, parseBaseDomain, setBaseDomain } from "../settings/pinned_domain.ts"; |
| 47 | import { PAID_PLACEMENT_WORDS, getPaidPlacement, paidPlacementWord, parsePaidPlacement, setPaidPlacement } from "../settings/paid_placement.ts"; | |
| 47 | 48 | import type { User } from "../core/users.ts"; |
| 48 | 49 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 49 | 50 | import { boundedSignal } from "../kernel/fetch_timeout.ts"; |
| @@ -57,7 +58,28 @@ export const net: { fetch: Fetch; probe: Fetch; resolve: (host: string) => Promi | ||
| 57 | 58 | resolve: (host) => resolve4(host).catch(() => []), |
| 58 | 59 | }; |
| 59 | 60 | |
| 60 | const admin = (a: User | undefined): Result<User, string> => (a?.isAdmin ? ok(a) : err("not_found")); | |
| 61 | /** | |
| 62 | * Who a pinned call acts as: a person admin, or a paid order (#16205), which is nobody's account | |
| 63 | * and borrows none. `id` is the account an event and a secret read name (none for an order, whose | |
| 64 | * id rides the payload and the read's run instead); `by` is what the forge's history records (the | |
| 65 | * admin's id, or `order:<id>`). | |
| 66 | */ | |
| 67 | export interface Who { | |
| 68 | readonly id: string | undefined; | |
| 69 | readonly by: string; | |
| 70 | readonly order?: string; | |
| 71 | } | |
| 72 | ||
| 73 | const admin = (a: User | undefined): Result<Who, string> => (a?.isAdmin ? ok({ id: a.id, by: a.id }) : err("not_found")); | |
| 74 | ||
| 75 | /** The system actor a paid order deploys, checks and retires its own forge as. */ | |
| 76 | export const orderWho = (orderId: string): Who => ({ id: undefined, by: `order:${orderId}`, order: orderId }); | |
| 77 | ||
| 78 | /** What an event's payload says of an order that acted; nothing for an admin. */ | |
| 79 | const orderOf = (who: Who): { order?: string } => (who.order === undefined ? {} : { order: who.order }); | |
| 80 | ||
| 81 | /** The run a secret read names: the purpose, and the order when one asked. */ | |
| 82 | const runOf = (who: Who, purpose: string): string => (who.order === undefined ? `pinned:${purpose}` : `pinned:${purpose}:${who.order}`); | |
| 61 | 83 | |
| 62 | 84 | export interface PinnedView extends Omit<Pinned, "claimHash"> { |
| 63 | 85 | /** Where it is served: HTTPS on its name; empty for a forge deployed before it had one. */ |
| @@ -104,12 +126,12 @@ const PLACE_HELP = "Places are listed at Places (GET /api/v1/places); a place is | ||
| 104 | 126 | /** |
| 105 | 127 | * The place a deploy is made at, from the catalog the forge last read (no call to a provider): the |
| 106 | 128 | * one asked for, which must exist, be orderable and be on `provider`; or, when none is asked for, |
| 107 | * the catalog's default for the small plan among that provider's places. | |
| 129 | * the catalog's default for `plan` (small unless named) among that provider's places. | |
| 108 | 130 | */ |
| 109 | function pickPlace(app: App, provider: string, asked: string): Result<Place, string> { | |
| 131 | function pickPlace(app: App, provider: string, asked: string, plan: PlanName = "small"): Result<Place, string> { | |
| 110 | 132 | const all = keptPlaces(app.db, keptRate(app.db, "EUR")); |
| 111 | 133 | if (asked === "") { |
| 112 | const c = chooseDefault(all, "small", new Set([provider]), pinOf(app.db, "small")); | |
| 134 | const c = chooseDefault(all, plan, new Set([provider]), pinOf(app.db, plan)); | |
| 113 | 135 | if (c.place) return ok(c.place); |
| 114 | 136 | return err(all.length === 0 ? "The forge has not read the places list yet, so it cannot choose where to deploy; try again in a few minutes." : `${c.reason} ${PLACE_HELP}`); |
| 115 | 137 | } |
| @@ -181,7 +203,7 @@ export function changeBaseDomain(app: App, actor: User | undefined, raw: unknown | ||
| 181 | 203 | if (!who.ok) return err("not_found"); |
| 182 | 204 | const domain = parseBaseDomain(raw); |
| 183 | 205 | if (!domain.ok) return domain; |
| 184 | setBaseDomain(app.db, domain.value, who.value.id); | |
| 206 | setBaseDomain(app.db, domain.value, who.value.by); | |
| 185 | 207 | return ok(domain.value); |
| 186 | 208 | } |
| 187 | 209 | |
| @@ -200,33 +222,33 @@ const dnsWriters = (app: App) => listCloudAccounts(app.db).filter((a) => a.provi | ||
| 200 | 222 | * person to make, which the words of the deploy and of Check then say. Each call is audited like |
| 201 | 223 | * the other cloud calls (`pinned:dns`), and the token is opened for it alone. |
| 202 | 224 | */ |
| 203 | async function writeDns(app: App, who: User, name: string): Promise<void> { | |
| 225 | async function writeDns(app: App, who: Who, name: string): Promise<void> { | |
| 204 | 226 | const p = getPinned(app.db, name); |
| 205 | 227 | if (!p || p.host === "" || p.address === "") return; |
| 206 | 228 | const kept = dnsOf(app.db, p.id); |
| 207 | 229 | if (kept !== undefined && kept.host === p.host && kept.address === p.address) return; |
| 208 | 230 | for (const a of dnsWriters(app)) { |
| 209 | 231 | const secret = secretNameOf(a.provider, a.name); |
| 210 | const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: who.id, run: "pinned:dns" })[secret]; | |
| 232 | const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: who.id, run: runOf(who, "dns") })[secret]; | |
| 211 | 233 | if (token === undefined) continue; |
| 212 | 234 | const f = gatedFetch(app.db, { provider: a.provider, account: a.name }, "pinned:dns", net.fetch); |
| 213 | 235 | const made = await upsertARecord(f, token, p.host, p.address); |
| 214 | 236 | if (made.done === "none") continue; |
| 215 | 237 | keepDns(app.db, p.id, { account: a.name, zone: made.zone, record: made.record, host: p.host, address: p.address }); |
| 216 | app.bus.append({ kind: "pinned.dns", actorId: who.id, payload: { name, host: p.host, address: p.address, account: `cloudflare/${a.name}`, done: made.done } }); | |
| 238 | app.bus.append({ kind: "pinned.dns", actorId: who.id, payload: { name, host: p.host, address: p.address, account: `cloudflare/${a.name}`, done: made.done, ...orderOf(who) } }); | |
| 217 | 239 | return; |
| 218 | 240 | } |
| 219 | 241 | } |
| 220 | 242 | |
| 221 | 243 | /** After a replace the address is unknown: with a Cloudflare account to write it, read it and write the record. */ |
| 222 | async function followWithDns(app: App, who: User, name: string): Promise<void> { | |
| 244 | async function followWithDns(app: App, who: Who, name: string): Promise<void> { | |
| 223 | 245 | if (dnsWriters(app).length === 0) return; |
| 224 | 246 | await readAddress(app, who, name); |
| 225 | 247 | await writeDns(app, who, name); |
| 226 | 248 | } |
| 227 | 249 | |
| 228 | 250 | /** The record the forge wrote is removed with the forge: "none" when it wrote none, else removed, or "kept" when Cloudflare would not let it. */ |
| 229 | async function unwriteDns(app: App, who: User, name: string): Promise<"none" | "removed" | "kept"> { | |
| 251 | async function unwriteDns(app: App, who: Who, name: string): Promise<"none" | "removed" | "kept"> { | |
| 230 | 252 | const p = getPinned(app.db, name)!; |
| 231 | 253 | const kept = dnsOf(app.db, p.id); |
| 232 | 254 | if (kept === undefined) return "none"; |
| @@ -234,7 +256,7 @@ async function unwriteDns(app: App, who: User, name: string): Promise<"none" | " | ||
| 234 | 256 | const writers = dnsWriters(app).sort((a, b) => Number(b.name === kept.account) - Number(a.name === kept.account)); |
| 235 | 257 | for (const a of writers) { |
| 236 | 258 | const secret = secretNameOf(a.provider, a.name); |
| 237 | const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: who.id, run: "pinned:dns" })[secret]; | |
| 259 | const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: who.id, run: runOf(who, "dns") })[secret]; | |
| 238 | 260 | if (token === undefined) continue; |
| 239 | 261 | const f = gatedFetch(app.db, { provider: a.provider, account: a.name }, "pinned:dns", net.fetch); |
| 240 | 262 | if ((await deleteARecord(f, token, kept.zone, kept.record)) === "refused") continue; |
| @@ -245,7 +267,7 @@ async function unwriteDns(app: App, who: User, name: string): Promise<"none" | " | ||
| 245 | 267 | } |
| 246 | 268 | |
| 247 | 269 | /** Open the account's token and run `go` with a gated fetch; the token never leaves this scope. */ |
| 248 | async function withCloud<T>(app: App, who: User, p: Pinned, purpose: string, go: (f: Fetch, token: string) => Promise<T>, writes = true): Promise<Result<T, string>> { | |
| 270 | 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>> { | |
| 249 | 271 | const account = getCloudAccount(app.db, p.target, p.account); |
| 250 | 272 | if (!account) return err("No such cloud account."); |
| 251 | 273 | if (writes && !account.writeAllowed) return err("That cloud account is read-only; allow writes on it first."); |
| @@ -253,7 +275,7 @@ async function withCloud<T>(app: App, who: User, p: Pinned, purpose: string, go: | ||
| 253 | 275 | // stale or was never read, so a forge nobody has opened Places on still knows what things cost. |
| 254 | 276 | if (writes) await refreshIfDue(app, who); |
| 255 | 277 | const secret = secretNameOf(account.provider, account.name); |
| 256 | const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: who.id, run: `pinned:${purpose}` })[secret]; | |
| 278 | const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: who.id, run: runOf(who, purpose) })[secret]; | |
| 257 | 279 | if (token === undefined) return err("No such credential."); |
| 258 | 280 | try { |
| 259 | 281 | return ok(await go(gatedFetch(app.db, { provider: p.target, account: p.account }, `pinned:${purpose}`, net.fetch), token)); |
| @@ -274,7 +296,7 @@ async function withCloud<T>(app: App, who: User, p: Pinned, purpose: string, go: | ||
| 274 | 296 | * before the cloud is asked). One refused with nothing changed, here or at the cloud, leaves a |
| 275 | 297 | * running forge as it was, with the refusal as the answer. |
| 276 | 298 | */ |
| 277 | function create<T>(app: App, who: User, p: Pinned, purpose: string, go: (f: Fetch, token: string) => Promise<T>, record: (made: T) => void, moved = false): Promise<Result<T, string>> { | |
| 299 | function create<T>(app: App, who: Who, p: Pinned, purpose: string, go: (f: Fetch, token: string) => Promise<T>, record: (made: T) => void, moved = false): Promise<Result<T, string>> { | |
| 278 | 300 | return oneAtATime(app, `pinned-account:${p.target}/${p.account}`, async () => { |
| 279 | 301 | const made = await withCloud(app, who, p, purpose, go); |
| 280 | 302 | if (made.ok) record(made.value); |
| @@ -294,7 +316,7 @@ const oneChange = <T>(app: App, name: string, go: () => Promise<T>): Promise<T> | ||
| 294 | 316 | * Read the machine back and record its public IPv4 (empty while none is assigned). The cloud's |
| 295 | 317 | * refusal is returned, so "no address yet" and "the call was refused" differ. |
| 296 | 318 | */ |
| 297 | async function readAddress(app: App, who: User, name: string): Promise<Result<string, string>> { | |
| 319 | async function readAddress(app: App, who: Who, name: string): Promise<Result<string, string>> { | |
| 298 | 320 | const p = getPinned(app.db, name); |
| 299 | 321 | if (!p || p.remote === "") return ok(""); |
| 300 | 322 | const seen = await withCloud(app, who, p, "address", (f, token) => read(driverOf(p.target), f, token, p.remote), false); |
| @@ -303,13 +325,18 @@ async function readAddress(app: App, who: User, name: string): Promise<Result<st | ||
| 303 | 325 | return ok(seen.value.address); |
| 304 | 326 | } |
| 305 | 327 | |
| 306 | export async function deployPinned( | |
| 307 | app: App, | |
| 308 | actor: User | undefined, | |
| 309 | input: { name: string; host: string; target: string; account: string; app: string; source: string; version: string; place?: string | undefined; config?: unknown }, | |
| 310 | ): Promise<Result<Issued, string>> { | |
| 328 | export type DeployInput = { | |
| 329 | name: string; host: string; target: string; account: string; app: string; source: string; version: string; place?: string | undefined; config?: unknown; | |
| 330 | /** The plan whose default place is chosen when none is asked for; small when absent. */ | |
| 331 | plan?: PlanName | undefined; | |
| 332 | }; | |
| 333 | ||
| 334 | export async function deployPinned(app: App, actor: User | undefined, input: DeployInput): Promise<Result<Issued, string>> { | |
| 311 | 335 | const who = admin(actor); |
| 312 | if (!who.ok) return who; | |
| 336 | return who.ok ? deployAs(app, who.value, input) : who; | |
| 337 | } | |
| 338 | ||
| 339 | async function deployAs(app: App, who: Who, input: DeployInput): Promise<Result<Issued, string>> { | |
| 313 | 340 | const t = targetOf(input.target); |
| 314 | 341 | if (!t) return err("That is not a target the forge knows."); |
| 315 | 342 | if (t.status === "refused") return err(t.refused); |
| @@ -333,21 +360,21 @@ export async function deployPinned( | ||
| 333 | 360 | if (asked !== "" && !asked.startsWith(`${t.id}:${old.datacenter}:`)) return err(`The volume of the earlier try is in ${old.datacenter}: deploy there, or leave the place out.`); |
| 334 | 361 | if (asked === "") asked = placeIdOf(old); |
| 335 | 362 | } |
| 336 | let at = pickPlace(app, t.id, asked); | |
| 363 | let at = pickPlace(app, t.id, asked, input.plan); | |
| 337 | 364 | // A catalog never read or gone stale is read again once before this is refused. |
| 338 | 365 | if (!at.ok && isStale(app)) { |
| 339 | await refreshIfDue(app, who.value); | |
| 340 | at = pickPlace(app, t.id, asked); | |
| 366 | await refreshIfDue(app, who); | |
| 367 | at = pickPlace(app, t.id, asked, input.plan); | |
| 341 | 368 | } |
| 342 | 369 | if (!at.ok) return at; |
| 343 | 370 | if (old) dropPinned(app.db, old.name); |
| 344 | 371 | const claim = newClaim(); |
| 345 | const { place: _asked, ...rest } = input; | |
| 346 | const p = insertPinned(app.db, { ...rest, target: t.id, config: config.value, host: host.value, claimHash: claim.hash, claimExpires: claim.expires, datacenter: at.value.datacenter, size: at.value.size }, who.value.id); | |
| 347 | app.bus.append({ kind: "pinned.deployed", actorId: who.value.id, payload: { name: p.name, target: p.target, version: p.version } }); | |
| 372 | const { place: _asked, plan: _plan, ...rest } = input; | |
| 373 | const p = insertPinned(app.db, { ...rest, target: t.id, config: config.value, host: host.value, claimHash: claim.hash, claimExpires: claim.expires, datacenter: at.value.datacenter, size: at.value.size }, who.by); | |
| 374 | app.bus.append({ kind: "pinned.deployed", actorId: who.id, payload: { name: p.name, target: p.target, version: p.version, ...orderOf(who) } }); | |
| 348 | 375 | if (old?.volume) setRemote(app.db, p.name, { volume: old.volume }); |
| 349 | 376 | const made = await create( |
| 350 | app, who.value, p, "deploy", | |
| 377 | app, who, p, "deploy", | |
| 351 | 378 | (f, token) => |
| 352 | 379 | provision(capped(app, p.name, driverOf(p.target)), f, token, getPinned(app.db, p.name)!, { |
| 353 | 380 | ...(old?.volume ? { have: old.volume } : {}), |
| @@ -358,8 +385,8 @@ export async function deployPinned( | ||
| 358 | 385 | if (!made.ok) return made; |
| 359 | 386 | // One read for the address, so the answer can name the DNS record; a cloud that has not |
| 360 | 387 | // assigned one yet (or refuses the read) leaves it to `check`. |
| 361 | await readAddress(app, who.value, p.name); | |
| 362 | await writeDns(app, who.value, p.name); | |
| 388 | await readAddress(app, who, p.name); | |
| 389 | await writeDns(app, who, p.name); | |
| 363 | 390 | return ok(issued(app, getPinned(app.db, p.name)!, claim.code)); |
| 364 | 391 | } |
| 365 | 392 | |
| @@ -397,7 +424,7 @@ async function changeNow( | ||
| 397 | 424 | const fits = await withCloud(app, who.value, before, kind, () => orderable(capped(app, before.name, driverOf(before.target)), before)); |
| 398 | 425 | if (!fits.ok) return fits; |
| 399 | 426 | if (!same) { |
| 400 | const c = recordChange(app.db, before, kind, to.value, who.value.id); | |
| 427 | const c = recordChange(app.db, before, kind, to.value, who.value.by); | |
| 401 | 428 | app.bus.append({ kind: kind === "update" ? "pinned.update" : "pinned.rollback", actorId: who.value.id, payload: { name, from: c.fromVersion, to: c.toVersion } }); |
| 402 | 429 | } |
| 403 | 430 | const after = getPinned(app.db, name)!; |
| @@ -419,8 +446,8 @@ async function changeNow( | ||
| 419 | 446 | * (`CLAIMED_REFUSAL`): the buyer's forge takes its own versions, and no machine of theirs is |
| 420 | 447 | * replaced from here. |
| 421 | 448 | */ |
| 422 | function noteClaimed(app: App, who: User, name: string): void { | |
| 423 | if (markClaimed(app.db, name)) app.bus.append({ kind: "pinned.claimed", actorId: who.id, payload: { name } }); | |
| 449 | function noteClaimed(app: App, who: Who, name: string): void { | |
| 450 | if (markClaimed(app.db, name)) app.bus.append({ kind: "pinned.claimed", actorId: who.id, payload: { name, ...orderOf(who) } }); | |
| 424 | 451 | } |
| 425 | 452 | |
| 426 | 453 | /** The only door to a new version or config. Either may be left as it is. */ |
| @@ -452,12 +479,12 @@ export const rollbackPinned = (app: App, actor: User | undefined, name: string): | ||
| 452 | 479 | * now, which records it. A forge deployed before forges had names is given `host` |
| 453 | 480 | * here, once. |
| 454 | 481 | */ |
| 455 | export const claimPinned = (app: App, actor: User | undefined, name: string, input: { host?: string | undefined } = {}): Promise<Result<Issued, string>> => | |
| 456 | oneChange(app, name, () => claimNow(app, actor, name, input)); | |
| 457 | ||
| 458 | async function claimNow(app: App, actor: User | undefined, name: string, input: { host?: string | undefined }): Promise<Result<Issued, string>> { | |
| 482 | export const claimPinned = (app: App, actor: User | undefined, name: string, input: { host?: string | undefined } = {}): Promise<Result<Issued, string>> => { | |
| 459 | 483 | const who = admin(actor); |
| 460 | if (!who.ok) return who; | |
| 484 | return who.ok ? oneChange(app, name, () => claimNow(app, who.value, name, input)) : Promise.resolve(who); | |
| 485 | }; | |
| 486 | ||
| 487 | async function claimNow(app: App, who: Who, name: string, input: { host?: string | undefined }): Promise<Result<Issued, string>> { | |
| 461 | 488 | const before = getPinned(app.db, name); |
| 462 | 489 | if (!before) return err("No such pinned forge."); |
| 463 | 490 | if (before.state === "retired") return err(RETIRED_REFUSAL); |
| @@ -470,7 +497,7 @@ async function claimNow(app: App, actor: User | undefined, name: string, input: | ||
| 470 | 497 | if (before.volume === "") return err("This forge never reached a machine; deploy it again, which issues a claim."); |
| 471 | 498 | // Named in the same breath as the check above, before anything is awaited: one forge a name. |
| 472 | 499 | if (before.host === "") setHost(app.db, name, host.value); |
| 473 | const ours = await sellersStill(app, who.value, name); | |
| 500 | const ours = await sellersStill(app, who, name); | |
| 474 | 501 | if (!ours.ok) return ours; |
| 475 | 502 | const claim = newClaim(); |
| 476 | 503 | // The machine is booted from the row as it will be. The row itself takes the new hash once that |
| @@ -478,7 +505,7 @@ async function claimNow(app: App, actor: User | undefined, name: string, input: | ||
| 478 | 505 | // stands. |
| 479 | 506 | const after: Pinned = { ...getPinned(app.db, name)!, claimHash: claim.hash, claimExpires: claim.expires }; |
| 480 | 507 | const done = await create( |
| 481 | app, who.value, after, "claim", | |
| 508 | app, who, after, "claim", | |
| 482 | 509 | (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, after, { onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }) }), |
| 483 | 510 | (m) => { |
| 484 | 511 | setClaim(app.db, name, { hash: claim.hash, expires: claim.expires }); |
| @@ -486,9 +513,9 @@ async function claimNow(app: App, actor: User | undefined, name: string, input: | ||
| 486 | 513 | }, |
| 487 | 514 | ); |
| 488 | 515 | if (!done.ok) return done; |
| 489 | app.bus.append({ kind: "pinned.claim_issued", actorId: who.value.id, payload: { name, expires: claim.expires } }); | |
| 490 | await readAddress(app, who.value, name); | |
| 491 | await writeDns(app, who.value, name); | |
| 516 | app.bus.append({ kind: "pinned.claim_issued", actorId: who.id, payload: { name, expires: claim.expires, ...orderOf(who) } }); | |
| 517 | await readAddress(app, who, name); | |
| 518 | await writeDns(app, who, name); | |
| 492 | 519 | return ok(issued(app, getPinned(app.db, name)!, claim.code)); |
| 493 | 520 | } |
| 494 | 521 | |
| @@ -534,7 +561,7 @@ async function reach(app: App, p: Pinned): Promise<{ waiting: Waiting; claim: Cl | ||
| 534 | 561 | * expired) is remembered against the machine that gave it, and `claimed` is recorded once |
| 535 | 562 | * (`noteClaimed`). Check, and every change that would replace the machine, hear it through here. |
| 536 | 563 | */ |
| 537 | async function hear(app: App, who: User, p: Pinned): Promise<{ waiting: Waiting; claim: ClaimState }> { | |
| 564 | async function hear(app: App, who: Who, p: Pinned): Promise<{ waiting: Waiting; claim: ClaimState }> { | |
| 538 | 565 | const heard = await reach(app, p); |
| 539 | 566 | if (heard.claim === "unknown") return heard; |
| 540 | 567 | if (p.remote !== "") markReached(app.db, p.name, p.remote); |
| @@ -552,7 +579,7 @@ async function hear(app: App, who: User, p: Pinned): Promise<{ waiting: Waiting; | ||
| 552 | 579 | * one with no machine or whose machine is gone, and one deployed before claims, may still be replaced: there is nobody to |
| 553 | 580 | * have claimed it through this forge's link, and it could not be recovered otherwise. |
| 554 | 581 | */ |
| 555 | async function sellersStill(app: App, who: User, name: string): Promise<Result<true, string>> { | |
| 582 | async function sellersStill(app: App, who: Who, name: string): Promise<Result<true, string>> { | |
| 556 | 583 | // A read the cloud refuses is not "no address": the forge could not be asked, so the change is |
| 557 | 584 | // refused with the cloud's answer before anything is recorded. A machine that is gone (404) has |
| 558 | 585 | // nobody to ask, and replacing it is how it comes back. |
| @@ -576,12 +603,12 @@ export type Retired = PinnedView & { readonly dnsRemoved: "none" | "removed" | " | ||
| 576 | 603 | * forge says is claimed is refused unless `despiteClaim`: the buyer's data is on that volume. One |
| 577 | 604 | * change at a time per forge, like an Update. |
| 578 | 605 | */ |
| 579 | export const retirePinned = (app: App, actor: User | undefined, name: string, o: { withData?: boolean | undefined; despiteClaim?: boolean | undefined } = {}): Promise<Result<Retired, string>> => | |
| 580 | oneChange(app, name, () => retireNow(app, actor, name, o)); | |
| 581 | ||
| 582 | async function retireNow(app: App, actor: User | undefined, name: string, o: { withData?: boolean | undefined; despiteClaim?: boolean | undefined }): Promise<Result<Retired, string>> { | |
| 606 | export const retirePinned = (app: App, actor: User | undefined, name: string, o: { withData?: boolean | undefined; despiteClaim?: boolean | undefined } = {}): Promise<Result<Retired, string>> => { | |
| 583 | 607 | const who = admin(actor); |
| 584 | if (!who.ok) return who; | |
| 608 | return who.ok ? oneChange(app, name, () => retireNow(app, who.value, name, o)) : Promise.resolve(who); | |
| 609 | }; | |
| 610 | ||
| 611 | async function retireNow(app: App, who: Who, name: string, o: { withData?: boolean | undefined; despiteClaim?: boolean | undefined }): Promise<Result<Retired, string>> { | |
| 585 | 612 | const before = getPinned(app.db, name); |
| 586 | 613 | if (!before) return err("No such pinned forge."); |
| 587 | 614 | const withData = o.withData === true; |
| @@ -590,12 +617,12 @@ async function retireNow(app: App, actor: User | undefined, name: string, o: { w | ||
| 590 | 617 | if (o.despiteClaim !== true) { |
| 591 | 618 | if (before.claimedAt !== "") return err(RETIRE_CLAIMED); |
| 592 | 619 | if (before.state !== "retired") { |
| 593 | const ours = await sellersStill(app, who.value, name); | |
| 620 | const ours = await sellersStill(app, who, name); | |
| 594 | 621 | if (!ours.ok) return err(ours.error === CLAIMED_REFUSAL ? RETIRE_CLAIMED : `${ours.error} If you mean to retire it anyway, say so (despiteClaim).`); |
| 595 | 622 | } |
| 596 | 623 | } |
| 597 | 624 | const p = getPinned(app.db, name)!; |
| 598 | const gone = await withCloud(app, who.value, p, "retire", (f, token) => | |
| 625 | const gone = await withCloud(app, who, p, "retire", (f, token) => | |
| 599 | 626 | retire(driverOf(p.target), f, token, p, { withData }, { |
| 600 | 627 | onMachineGone: () => setRemote(app.db, name, { remote: "", address: "", state: "retired" }), |
| 601 | 628 | onVolumeGone: () => setRemote(app.db, name, { volume: "" }), |
| @@ -606,8 +633,8 @@ async function retireNow(app: App, actor: User | undefined, name: string, o: { w | ||
| 606 | 633 | const now = getPinned(app.db, name)!; |
| 607 | 634 | return err(now.state === "retired" && before.state !== "retired" ? `${gone.error} Its machine is deleted and it is retired; its volume is kept: retire it with its data again to delete that.` : gone.error); |
| 608 | 635 | } |
| 609 | const dnsRemoved = await unwriteDns(app, who.value, name); | |
| 610 | app.bus.append({ kind: "pinned.retired", actorId: who.value.id, payload: { name, withData, claimed: before.claimedAt !== "", dns: dnsRemoved } }); | |
| 636 | const dnsRemoved = await unwriteDns(app, who, name); | |
| 637 | app.bus.append({ kind: "pinned.retired", actorId: who.id, payload: { name, withData, claimed: before.claimedAt !== "", dns: dnsRemoved, ...orderOf(who) } }); | |
| 611 | 638 | return done(getPinned(app.db, name)!, dnsRemoved); |
| 612 | 639 | } |
| 613 | 640 | |
| @@ -659,19 +686,103 @@ export function claimWords(v: Issued): string { | ||
| 659 | 686 | */ |
| 660 | 687 | export async function checkPinned(app: App, actor: User | undefined, name: string): Promise<Result<Checked, string>> { |
| 661 | 688 | const who = admin(actor); |
| 662 | if (!who.ok) return who; | |
| 689 | return who.ok ? checkAs(app, who.value, name) : who; | |
| 690 | } | |
| 691 | ||
| 692 | async function checkAs(app: App, who: Who, name: string): Promise<Result<Checked, string>> { | |
| 663 | 693 | const p = getPinned(app.db, name); |
| 664 | 694 | if (!p) return err("No such pinned forge."); |
| 665 | 695 | if (p.state === "retired") return err(RETIRED_REFUSAL); |
| 666 | 696 | if (p.remote === "") return err("This forge has no droplet yet; deploy or update it first."); |
| 667 | const read = await readAddress(app, who.value, name); | |
| 697 | const read = await readAddress(app, who, name); | |
| 668 | 698 | if (!read.ok) return read; |
| 669 | await writeDns(app, who.value, name); | |
| 699 | await writeDns(app, who, name); | |
| 670 | 700 | const now = getPinned(app.db, name)!; |
| 671 | const reached = await hear(app, who.value, now); | |
| 701 | const reached = await hear(app, who, now); | |
| 672 | 702 | const healthy = reached.waiting === ""; |
| 673 | 703 | if (healthy && now.state !== "running") setRemote(app.db, name, { state: "running" }); |
| 674 | 704 | const after = getPinned(app.db, name)!; |
| 675 | app.bus.append({ kind: "pinned.check", actorId: who.value.id, payload: { name, address: after.address, state: after.state, healthy } }); | |
| 705 | app.bus.append({ kind: "pinned.check", actorId: who.id, payload: { name, address: after.address, state: after.state, healthy, ...orderOf(who) } }); | |
| 676 | 706 | return ok({ ...view(app, after), healthy, ...reached }); |
| 677 | 707 | } |
| 708 | ||
| 709 | /** Whether pinned forge `name` was deployed by `who`: its first recorded change says so. */ | |
| 710 | const madeBy = (app: App, name: string, who: Who): boolean => { | |
| 711 | const p = getPinned(app.db, name); | |
| 712 | return p !== undefined && changesOf(app.db, p.id).at(-1)?.by === who.by; | |
| 713 | }; | |
| 714 | ||
| 715 | const NOT_THE_ORDERS = "A pinned forge has that name already."; | |
| 716 | ||
| 717 | /** | |
| 718 | * A paid order's forge, deployed as the order (#16205): the checks, catalog, ceiling, DNS and | |
| 719 | * claim of an admin's deploy, recorded as `order:<id>`. Never a second machine for one order: a | |
| 720 | * row of that name the order made whose machine is recorded is not deployed again, its claim is | |
| 721 | * issued afresh instead (the machine replaced on its own volume, as New claim link does), which | |
| 722 | * is how an order cut off by a restart gets its link back; one cut off before its machine was | |
| 723 | * recorded is deployed again on the volume it may have made. A row the order did not make is | |
| 724 | * refused. | |
| 725 | */ | |
| 726 | export async function deployForOrder(app: App, orderId: string, input: DeployInput): Promise<Result<Issued, string>> { | |
| 727 | const who = orderWho(orderId); | |
| 728 | const old = getPinned(app.db, input.name); | |
| 729 | if (old === undefined) return deployAs(app, who, input); | |
| 730 | if (!madeBy(app, input.name, who)) return err(NOT_THE_ORDERS); | |
| 731 | if (old.state === "retired") return err(RETIRED_REFUSAL); | |
| 732 | if (old.remote !== "") return oneChange(app, input.name, () => claimNow(app, who, input.name, {})); | |
| 733 | setRemote(app.db, old.name, { state: "failed" }); | |
| 734 | return deployAs(app, who, input); | |
| 735 | } | |
| 736 | ||
| 737 | /** Check a paid order's forge, as the order: refused for one it did not deploy. */ | |
| 738 | export function checkForOrder(app: App, orderId: string, name: string): Promise<Result<Checked, string>> { | |
| 739 | const who = orderWho(orderId); | |
| 740 | return madeBy(app, name, who) ? checkAs(app, who, name) : Promise.resolve(err("No such pinned forge.")); | |
| 741 | } | |
| 742 | ||
| 743 | /** | |
| 744 | * Retire a paid order's forge, as the order, keeping its data volume: refused for one it did not | |
| 745 | * deploy. | |
| 746 | */ | |
| 747 | export function retireForOrder(app: App, orderId: string, name: string): Promise<Result<Retired, string>> { | |
| 748 | const who = orderWho(orderId); | |
| 749 | return madeBy(app, name, who) ? oneChange(app, name, () => retireNow(app, who, name, {})) : Promise.resolve(err("No such pinned forge.")); | |
| 750 | } | |
| 751 | ||
| 752 | /** | |
| 753 | * Why a deploy to `provider/account` at the catalog's default place for `plan` would be refused | |
| 754 | * now, in the sentence the deploy itself would say, or undefined when it fits: asked before a | |
| 755 | * buyer pays (#16205). Reads only what the forge holds (the catalog it last read, the account, | |
| 756 | * the ceiling); nothing is asked of a provider, so a catalog never read is refused here too. | |
| 757 | */ | |
| 758 | export function deployRoom(app: App, provider: string, account: string, plan: PlanName): string | undefined { | |
| 759 | const t = targetOf(provider); | |
| 760 | if (t === undefined || t.status !== "first") return "That is not a target the forge knows."; | |
| 761 | const a = getCloudAccount(app.db, provider, account); | |
| 762 | if (a === undefined) return "No such cloud account."; | |
| 763 | if (!a.writeAllowed) return "That cloud account is read-only; allow writes on it first."; | |
| 764 | if (getBaseDomain(app.db) === "") return HOST_NEEDED; | |
| 765 | const at = pickPlace(app, provider, "", plan); | |
| 766 | if (!at.ok) return at.error; | |
| 767 | return refusalAt(app, provider, account, at.value); | |
| 768 | } | |
| 769 | ||
| 770 | /** Where paid forges run, for an admin: `hosted` or `provider/name`. */ | |
| 771 | export function readPaidPlacement(app: App, actor: User | undefined): Result<string, "not_found"> { | |
| 772 | const who = admin(actor); | |
| 773 | return who.ok ? ok(paidPlacementWord(getPaidPlacement(app.db))) : err("not_found"); | |
| 774 | } | |
| 775 | ||
| 776 | /** | |
| 777 | * Set where paid forges run: `hosted` (or null or empty), or a cloud account that allows writes. | |
| 778 | */ | |
| 779 | export function changePaidPlacement(app: App, actor: User | undefined, raw: unknown): Result<string, "not_found" | "invalid_paid_placement"> { | |
| 780 | const who = admin(actor); | |
| 781 | if (!who.ok) return err("not_found"); | |
| 782 | const to = parsePaidPlacement(app.db, raw); | |
| 783 | if (!to.ok) return to; | |
| 784 | setPaidPlacement(app.db, to.value, who.value.by); | |
| 785 | return ok(to.value); | |
| 786 | } | |
| 787 | ||
| 788 | export { PAID_PLACEMENT_WORDS }; |
src/actions/places_refresh.ts +6 −4
| @@ -11,12 +11,14 @@ import { LISTED, RETRY_MS, STALE_MS, noteTry, readPlaces, readTimes, triedTimes | ||
| 11 | 11 | import { refreshRate } from "../cloud/rates.ts"; |
| 12 | 12 | import { listCloudAccounts, secretNameOf } from "../core/cloud_account.ts"; |
| 13 | 13 | import { resolveSecrets } from "../core/secret_store.ts"; |
| 14 | import type { User } from "../core/users.ts"; | |
| 15 | 14 | import { net } from "./cloud.ts"; |
| 16 | 15 | |
| 17 | 16 | const listed = (provider: string): boolean => (LISTED as readonly string[]).includes(provider); |
| 18 | 17 | |
| 19 | 18 | /** The refresh in flight for each forge's database, if any. */ |
| 19 | /** Whose read of a provider token the audit names: an admin, or none for a paid order (#16205). */ | |
| 20 | type Reader = { readonly id: string | undefined }; | |
| 21 | ||
| 20 | 22 | const running = new WeakMap<object, Promise<void>>(); |
| 21 | 23 | |
| 22 | 24 | /** |
| @@ -33,7 +35,7 @@ export function isStale(app: App, now = Date.now()): boolean { | ||
| 33 | 35 | }); |
| 34 | 36 | } |
| 35 | 37 | |
| 36 | async function run(app: App, who: User): Promise<void> { | |
| 38 | async function run(app: App, who: Reader): Promise<void> { | |
| 37 | 39 | await refreshRate(app.db, net.fetch); |
| 38 | 40 | const accounts = listCloudAccounts(app.db).filter((a) => listed(a.provider)); |
| 39 | 41 | const tried = triedTimes(app.db); |
| @@ -52,7 +54,7 @@ async function run(app: App, who: User): Promise<void> { | ||
| 52 | 54 | } |
| 53 | 55 | |
| 54 | 56 | /** 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> { | |
| 57 | export function refreshCatalog(app: App, who: Reader): Promise<void> { | |
| 56 | 58 | const flying = running.get(app.db); |
| 57 | 59 | if (flying) return flying; |
| 58 | 60 | const p = run(app, who).finally(() => running.delete(app.db)); |
| @@ -64,7 +66,7 @@ export function refreshCatalog(app: App, who: User): Promise<void> { | ||
| 64 | 66 | * The refresh a read waits for: the one in flight, or a new one when a refresh is due; nothing |
| 65 | 67 | * otherwise. A failure is swallowed, since the last good read stands. |
| 66 | 68 | */ |
| 67 | export async function refreshIfDue(app: App, who: User): Promise<void> { | |
| 69 | export async function refreshIfDue(app: App, who: Reader): Promise<void> { | |
| 68 | 70 | if (!running.has(app.db) && !isStale(app)) return; |
| 69 | 71 | await refreshCatalog(app, who).catch(() => undefined); |
| 70 | 72 | } |
src/actions/spawn.ts +9 −1
| @@ -446,6 +446,14 @@ async function make( | ||
| 446 | 446 | await deps.placement.retire(placed.value.bodyId); |
| 447 | 447 | return failed(app, deps, "place", "placement returned an unusable body id"); |
| 448 | 448 | } |
| 449 | // A cloud body is a forge of its own (a paid order places it, `actions/order.ts`): no ledger, | |
| 450 | // copy or credit here, which would make it a hosted child the boot, the proxy and the sleeper | |
| 451 | // all act on. | |
| 452 | const kind = placed.value.kind; | |
| 453 | if (kind === "cloud") { | |
| 454 | await deps.placement.retire(placed.value.bodyId); | |
| 455 | return failed(app, deps, "place", "a cloud body is not made into a hosted child"); | |
| 456 | } | |
| 449 | 457 | ledger = { |
| 450 | 458 | name: plan.name, |
| 451 | 459 | bodyId: placed.value.bodyId, |
| @@ -462,7 +470,7 @@ async function make( | ||
| 462 | 470 | ...(plan.domain === undefined ? {} : { domain: plan.domain }), |
| 463 | 471 | ...(plan.template === undefined ? {} : { template: plan.template }), |
| 464 | 472 | ...(plan.plan === undefined ? {} : { plan: plan.plan }), |
| 465 | placement: placed.value.kind ?? "hosted", | |
| 473 | placement: kind ?? "hosted", | |
| 466 | 474 | statusToken: secret(), |
| 467 | 475 | beatKey: secret(), |
| 468 | 476 | }; |
src/billing/orders.ts +13 −1
| @@ -15,7 +15,11 @@ | ||
| 15 | 15 | import type { Database } from "bun:sqlite"; |
| 16 | 16 | import { sha256 } from "../kernel/hash.ts"; |
| 17 | 17 | |
| 18 | export type OrderState = "pending" | "paid" | "spawning" | "spawned" | "failed"; | |
| 18 | /** | |
| 19 | * `making`: a paid order's forge is deployed on a cloud machine (#16205) and does not answer yet; | |
| 20 | * it becomes `spawned` once it does. | |
| 21 | */ | |
| 22 | export type OrderState = "pending" | "paid" | "spawning" | "making" | "spawned" | "failed"; | |
| 19 | 23 | |
| 20 | 24 | /** The hold outlives the checkout (`CHECKOUT_MS`) so a buyer who pays at the last minute still finds the name theirs. */ |
| 21 | 25 | export const HOLD_MS = 35 * 60_000; |
| @@ -133,6 +137,14 @@ export function move(db: Database, id: string, from: OrderState, to: OrderState, | ||
| 133 | 137 | ); |
| 134 | 138 | } |
| 135 | 139 | |
| 140 | /** | |
| 141 | * Take the turn to ask after an order in `state`: true only for the caller whose statement moved | |
| 142 | * its clock from `seen` to `now`, so two pages asking at once ask once. | |
| 143 | */ | |
| 144 | export function takeTurn(db: Database, id: string, state: OrderState, seen: number, now: number): boolean { | |
| 145 | return db.query("UPDATE forge_order SET updated_at = ?4 WHERE id = ?1 AND state = ?2 AND updated_at = ?3").run(id, state, seen, now).changes === 1; | |
| 146 | } | |
| 147 | ||
| 136 | 148 | /** The buyer has been shown the link: true once, for the caller that marks it. */ |
| 137 | 149 | export function markShown(db: Database, id: string, now: number): boolean { |
| 138 | 150 | return db.query("UPDATE forge_order SET shown_at = ?2 WHERE id = ?1 AND shown_at IS NULL").run(id, now).changes === 1; |
src/cloud/ceiling.ts +28 −12
| @@ -142,24 +142,40 @@ export function spendOf(db: Database, provider: string, account: string, prices: | ||
| 142 | 142 | export function admit(app: App, name: string): void { |
| 143 | 143 | const p = getPinned(app.db, name); |
| 144 | 144 | if (!p) return; |
| 145 | const who = `${p.target}/${p.account}`; | |
| 146 | const id = placeIdOf(p); | |
| 147 | 145 | const prices = priced(app.db); |
| 146 | const no = refusalAt(app, p.target, p.account, { id: placeIdOf(p), size: p.size, datacenter: p.datacenter }, rowCents(p, prices), prices); | |
| 147 | if (no !== undefined) throw new CeilingRefusal(no); | |
| 148 | } | |
| 149 | ||
| 150 | /** | |
| 151 | * Why making a machine at `place` on `provider/account` would be refused, in the sentence `admit` | |
| 152 | * throws, or undefined when it fits; `counted` is what a row is already counted at. Asked without | |
| 153 | * a row before a buyer pays (#16205), and by `admit` with one. | |
| 154 | */ | |
| 155 | export function refusalAt( | |
| 156 | app: App, | |
| 157 | provider: string, | |
| 158 | account: string, | |
| 159 | place: { readonly id: string; readonly size: string; readonly datacenter: string }, | |
| 160 | counted = 0, | |
| 161 | prices: Priced = priced(app.db), | |
| 162 | ): string | undefined { | |
| 163 | const who = `${provider}/${account}`; | |
| 164 | const id = place.id; | |
| 148 | 165 | const price = prices.forge(id); |
| 149 | 166 | if (price === undefined) |
| 150 | throw new CeilingRefusal( | |
| 151 | `The forge has no price for ${p.size} in ${p.datacenter} on ${p.target}, so it cannot hold ${who} to its ceiling; nothing was made. ` + | |
| 152 | "Prices come from the provider's own list (Places, GET /api/v1/places), which the forge reads before a create and could not read a price from; try again in a few minutes.", | |
| 167 | return ( | |
| 168 | `The forge has no price for ${place.size} in ${place.datacenter} on ${provider}, so it cannot hold ${who} to its ceiling; nothing was made. ` + | |
| 169 | "Prices come from the provider's own list (Places, GET /api/v1/places), which the forge reads before a create and could not read a price from; try again in a few minutes." | |
| 153 | 170 | ); |
| 154 | 171 | const closed = prices.closed(id); |
| 155 | if (closed !== undefined) | |
| 156 | throw new CeilingRefusal(`${id} cannot be ordered now: ${closed}; nothing was made, and a running machine was not touched. Pick another place, or try again later.`); | |
| 157 | const { ceilingDollars, monthlyCents } = spendOf(app.db, p.target, p.account, prices); | |
| 158 | const add = price - rowCents(p, prices); | |
| 159 | if (add <= 0 || monthlyCents + add <= ceilingDollars * 100) return; | |
| 160 | throw new CeilingRefusal( | |
| 172 | if (closed !== undefined) return `${id} cannot be ordered now: ${closed}; nothing was made, and a running machine was not touched. Pick another place, or try again later.`; | |
| 173 | const { ceilingDollars, monthlyCents } = spendOf(app.db, provider, account, prices); | |
| 174 | const add = price - counted; | |
| 175 | if (add <= 0 || monthlyCents + add <= ceilingDollars * 100) return undefined; | |
| 176 | return ( | |
| 161 | 177 | `${who} is held to $${ceilingDollars} a month and runs ${dollars(monthlyCents)} now; this would add ${dollars(add)}, which is over it, so nothing was made. ` + |
| 162 | `Raise the ceiling at ${CEILING_PAGE} if you mean to spend more. This is the forge's own reckoning from list prices; the provider's bill is the truth.`, | |
| 178 | `Raise the ceiling at ${CEILING_PAGE} if you mean to spend more. This is the forge's own reckoning from list prices; the provider's bill is the truth.` | |
| 163 | 179 | ); |
| 164 | 180 | } |
| 165 | 181 |
src/contract/openapi/routes/patchApiV1AdminSettings.ts +3 −2
| @@ -6,13 +6,14 @@ export const route: Route = { | ||
| 6 | 6 | summary: |
| 7 | 7 | "Change the signup mode", |
| 8 | 8 | detail: |
| 9 | "Change the signup mode (open, invite or closed), the account quotas, or the forge's own source repository (forgeRepo: owner/name, null to clear; its app is then shown as the forge itself), or the domain deployed forges are served on (pinnedDomain: such as forges.example.com, null to clear; a pinned forge deployed with no hostname is served on <name>.<domain>), one per call (a person admin's token, admin scope); answers { signup }, { quotas }, { forgeRepo } or { pinnedDomain }; a quota is a positive whole number, or null for no limit", | |
| 9 | "Change the signup mode (open, invite or closed), the account quotas, or the forge's own source repository (forgeRepo: owner/name, null to clear; its app is then shown as the forge itself), or the domain deployed forges are served on (pinnedDomain: such as forges.example.com, null to clear; a pinned forge deployed with no hostname is served on <name>.<domain>), or where paid forges run (paidPlacement: hosted, or a cloud account provider/name that allows writes; a paid order is then deployed there as a pinned forge), one per call (a person admin's token, admin scope); answers { signup }, { quotas }, { forgeRepo }, { pinnedDomain } or { paidPlacement }; a quota is a positive whole number, or null for no limit", | |
| 10 | 10 | auth: true, |
| 11 | 11 | role: "admin", |
| 12 | body: { signup: "string", quotas: "object", forgeRepo: "string", pinnedDomain: "string" }, | |
| 12 | body: { signup: "string", quotas: "object", forgeRepo: "string", pinnedDomain: "string", paidPlacement: "string" }, | |
| 13 | 13 | refusals: { |
| 14 | 14 | invalid_body: "none of signup, quotas or forgeRepo was sent, or more than one was", |
| 15 | 15 | invalid_forge_repo: "forgeRepo is not owner/name or null", |
| 16 | invalid_paid_placement: "paidPlacement is not hosted, null or a cloud account provider/name that allows writes", | |
| 16 | 17 | invalid_pinned_domain: "pinnedDomain is not a DNS name such as forges.example.com, or null", |
| 17 | 18 | invalid_signup: "signup is not open, invite or closed", |
| 18 | 19 | no_such_quota: "a quota key is unknown", |
src/http/api/admin.ts +13 −6
| @@ -23,7 +23,7 @@ import { inviteLink, list as listInviteLinks, mint as mintInviteLink, revoke as | ||
| 23 | 23 | import { changeLimit, listLimits } from "../../actions/limits.ts"; |
| 24 | 24 | import { changePlans } from "../../actions/plans.ts"; |
| 25 | 25 | import { setAccountCeilings, setAccountGrant } from "../../actions/model_grant.ts"; |
| 26 | import { DOMAIN_WORDS, changeBaseDomain, checkPinned, claimPinned, deployPinned, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned } from "../../actions/pinned.ts"; | |
| 26 | import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, claimPinned, deployPinned, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned } from "../../actions/pinned.ts"; | |
| 27 | 27 | import { TARGETS } from "../../cloud/targets.ts"; |
| 28 | 28 | import { changeQuotas, readQuotas } from "../../actions/quotas.ts"; |
| 29 | 29 | import { allowRequest, declineRequest, listRequests } from "../../actions/requests.ts"; |
| @@ -416,16 +416,17 @@ export function adminRoutes(router: Router<Handler>): void { | ||
| 416 | 416 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 417 | 417 | const denied = accountAdmin(ctx, "ro"); |
| 418 | 418 | if (denied) return denied; |
| 419 | const { read, signup, source, billing, domain } = timePhase(ctx.request, "settings", () => ({ | |
| 419 | const { read, signup, source, billing, domain, paid } = timePhase(ctx.request, "settings", () => ({ | |
| 420 | 420 | billing: readBillingLinks(ctx.app, ctx.auth.user), |
| 421 | 421 | domain: readBaseDomain(ctx.app, ctx.auth.user), |
| 422 | paid: readPaidPlacement(ctx.app, ctx.auth.user), | |
| 422 | 423 | read: readQuotas(ctx.app, ctx.auth.user), |
| 423 | 424 | signup: readSignup(ctx.app, ctx.auth.user), |
| 424 | 425 | source: readForgeSource(ctx.app, ctx.auth.user), |
| 425 | 426 | })); |
| 426 | 427 | return timePhase(ctx.request, "render", () => |
| 427 | read.ok && signup.ok && source.ok && billing.ok && domain.ok | |
| 428 | ? json({ billingLinks: billing.value, pinnedDomain: domain.value === "" ? null : domain.value, ...read.value, ...signup.value, ...source.value, signupChanges: signup.value.changes, changes: read.value.changes }) | |
| 428 | read.ok && signup.ok && source.ok && billing.ok && domain.ok && paid.ok | |
| 429 | ? json({ billingLinks: billing.value, pinnedDomain: domain.value === "" ? null : domain.value, paidPlacement: paid.value, ...read.value, ...signup.value, ...source.value, signupChanges: signup.value.changes, changes: read.value.changes }) | |
| 429 | 430 | : notFound()); |
| 430 | 431 | }); |
| 431 | 432 | |
| @@ -433,8 +434,14 @@ export function adminRoutes(router: Router<Handler>): void { | ||
| 433 | 434 | const denied = accountAdmin(ctx, "admin"); |
| 434 | 435 | if (denied) return denied; |
| 435 | 436 | const input = await body(ctx.request); |
| 436 | const sent = [input.signup, input.quotas, input.forgeRepo, input.billingLinks, input.pinnedDomain].filter((v) => v !== undefined).length; | |
| 437 | if (sent > 1) return apiError("invalid_body", 422, "send one of signup, quotas, forgeRepo, billingLinks or pinnedDomain"); | |
| 437 | const sent = [input.signup, input.quotas, input.forgeRepo, input.billingLinks, input.pinnedDomain, input.paidPlacement].filter((v) => v !== undefined).length; | |
| 438 | if (sent > 1) return apiError("invalid_body", 422, "send one of signup, quotas, forgeRepo, billingLinks, pinnedDomain or paidPlacement"); | |
| 439 | if (input.paidPlacement !== undefined) { | |
| 440 | const set = changePaidPlacement(ctx.app, ctx.auth.user, input.paidPlacement); | |
| 441 | if (set.ok) return json({ paidPlacement: set.value }); | |
| 442 | if (set.error === "not_found") return notFound(); | |
| 443 | return apiError(set.error, 422, PAID_PLACEMENT_WORDS); | |
| 444 | } | |
| 438 | 445 | if (input.pinnedDomain !== undefined) { |
| 439 | 446 | const set = changeBaseDomain(ctx.app, ctx.auth.user, input.pinnedDomain); |
| 440 | 447 | if (set.ok) return json({ pinnedDomain: set.value === "" ? null : set.value }); |
src/http/pinned_routes.ts +19 −2
| @@ -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, changeBaseDomain, 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, 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"; |
| @@ -86,7 +86,7 @@ function listPage(ctx: Ctx): Response { | ||
| 86 | 86 | const at = lastCheckOf(ctx.app.db, p.name); |
| 87 | 87 | if (at) checks.set(p.name, at); |
| 88 | 88 | } |
| 89 | return page({ ctx, title: "Pinned forges", body: pinnedListPage(forges.value, { names, checks, domain: getBaseDomain(ctx.app.db) }) }); | |
| 89 | return page({ ctx, title: "Pinned forges", body: pinnedListPage(forges.value, { names, checks, domain: getBaseDomain(ctx.app.db), paid: paidOf(ctx) }) }); | |
| 90 | 90 | } |
| 91 | 91 | |
| 92 | 92 | /** |
| @@ -133,9 +133,26 @@ async function domainSubmit(ctx: Ctx): Promise<Response> { | ||
| 133 | 133 | return flashTo(ctx, "/pinned", set.ok ? { message: set.value === "" ? "Domain for deployed forges cleared." : `Deployed forges are served on <name>.${set.value}.` } : { tone: "danger", message: `${DOMAIN_WORDS}. Nothing was saved.` }); |
| 134 | 134 | } |
| 135 | 135 | |
| 136 | const paidOf = (ctx: Ctx): string => { | |
| 137 | const now = readPaidPlacement(ctx.app, ctx.auth.user); | |
| 138 | return now.ok ? now.value : "hosted"; | |
| 139 | }; | |
| 140 | ||
| 141 | /** Save where paid forges run: the same change the API and terminal make. */ | |
| 142 | async function paidSubmit(ctx: Ctx): Promise<Response> { | |
| 143 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 144 | if (!ctx.auth.user.isAdmin) return notFoundPage(ctx); | |
| 145 | const form = await readForm(ctx, "admin"); | |
| 146 | if (form instanceof Response) return form; | |
| 147 | const set = changePaidPlacement(ctx.app, ctx.auth.user, field(form, "paid")); | |
| 148 | if (!set.ok && set.error === "not_found") return notFoundPage(ctx); | |
| 149 | return flashTo(ctx, "/pinned", set.ok ? { message: set.value === "hosted" ? "Paid forges run hosted, inside this forge." : `Paid forges are deployed on ${set.value}.` } : { tone: "danger", message: `${PAID_PLACEMENT_WORDS}. Nothing was saved.` }); | |
| 150 | } | |
| 151 | ||
| 136 | 152 | export function pinnedRoutes(router: Router<Handler>): void { |
| 137 | 153 | router.add("GET", "/pinned", listPage); |
| 138 | 154 | router.add("POST", "/pinned/domain", domainSubmit); |
| 155 | router.add("POST", "/pinned/paid", paidSubmit); | |
| 139 | 156 | router.add("POST", "/pinned/:name/:act", pinnedAct); |
| 140 | 157 | router.add("GET", "/deploy-to", deployToPage); |
| 141 | 158 | router.add("POST", "/deploy-to", deployToSubmit); |
src/settings/paid_placement.ts added +88
| @@ -0,0 +1,88 @@ | ||
| 1 | /** | |
| 2 | * Where paid forges run (#16205): `hosted`, inside this forge as today (the default), or on a | |
| 3 | * named cloud account (`digitalocean/main`), where each paid order is deployed as a pinned forge | |
| 4 | * of its own (`spawn/cloud_placement.ts`). Free forges always stay hosted. Stored in | |
| 5 | * `forge_setting` under `paid.placement` by an admin (`PATCH /api/v1/admin/settings` with | |
| 6 | * `{"paidPlacement": "digitalocean/main"}`, `"hosted"` or `null` for the default), every change | |
| 7 | * kept with who and when. Only an account a pinned forge can be deployed to, with writes allowed, | |
| 8 | * may be named; one that later loses its writes is not passed over: the order fails and says so. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { Database } from "bun:sqlite"; | |
| 12 | import { getCloudAccount } from "../core/cloud_account.ts"; | |
| 13 | import { target } from "../cloud/targets.ts"; | |
| 14 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 15 | import { writeSetting } from "./limits.ts"; | |
| 16 | ||
| 17 | export const PAID_PLACEMENT_KEY = "paid.placement"; | |
| 18 | ||
| 19 | export type PaidPlacement = | |
| 20 | | { readonly where: "hosted" } | |
| 21 | | { | |
| 22 | readonly where: "cloud"; | |
| 23 | readonly provider: string; | |
| 24 | readonly account: string; | |
| 25 | }; | |
| 26 | ||
| 27 | export const PAID_PLACEMENT_WORDS = | |
| 28 | "paid forges run on hosted (inside this forge), or on a cloud account named provider/name that a pinned forge can be deployed to, with writes allowed"; | |
| 29 | ||
| 30 | const ACCOUNT = /^([a-z]+)\/([a-z][a-z0-9_]{0,31})$/; | |
| 31 | ||
| 32 | /** | |
| 33 | * `hosted`, or the `provider/name` of an account it may be, from untrusted input (null is hosted). | |
| 34 | */ | |
| 35 | export function parsePaidPlacement( | |
| 36 | db: Database, | |
| 37 | raw: unknown, | |
| 38 | ): Result<string, "invalid_paid_placement"> { | |
| 39 | if (raw === null || raw === "" || raw === "hosted") return ok("hosted"); | |
| 40 | if (typeof raw !== "string") return err("invalid_paid_placement"); | |
| 41 | const m = ACCOUNT.exec(raw.trim()); | |
| 42 | if (m === null || target(m[1]!)?.status !== "first") | |
| 43 | return err("invalid_paid_placement"); | |
| 44 | return getCloudAccount(db, m[1]!, m[2]!)?.writeAllowed === true | |
| 45 | ? ok(`${m[1]}/${m[2]}`) | |
| 46 | : err("invalid_paid_placement"); | |
| 47 | } | |
| 48 | ||
| 49 | /** | |
| 50 | * What is stored, read as it was written: an account named stays named even if it changed since. | |
| 51 | */ | |
| 52 | export function getPaidPlacement(db: Database): PaidPlacement { | |
| 53 | const row = db | |
| 54 | .query< | |
| 55 | { value: string }, | |
| 56 | [string] | |
| 57 | >("SELECT value FROM forge_setting WHERE key = ?1") | |
| 58 | .get(PAID_PLACEMENT_KEY); | |
| 59 | const m = row === null ? null : ACCOUNT.exec(row.value); | |
| 60 | return m === null | |
| 61 | ? { where: "hosted" } | |
| 62 | : { where: "cloud", provider: m[1]!, account: m[2]! }; | |
| 63 | } | |
| 64 | ||
| 65 | /** The stored value in the setting's own words: `hosted` or `provider/name`. */ | |
| 66 | export const paidPlacementWord = (p: PaidPlacement): string => | |
| 67 | p.where === "hosted" ? "hosted" : `${p.provider}/${p.account}`; | |
| 68 | ||
| 69 | /** | |
| 70 | * Keep the choice with who made it; `hosted` clears the row, and the same value again keeps | |
| 71 | * nothing. | |
| 72 | */ | |
| 73 | export function setPaidPlacement( | |
| 74 | db: Database, | |
| 75 | value: string, | |
| 76 | actorId: string, | |
| 77 | ): void { | |
| 78 | const from = paidPlacementWord(getPaidPlacement(db)); | |
| 79 | if (from === value) return; | |
| 80 | writeSetting( | |
| 81 | db, | |
| 82 | PAID_PLACEMENT_KEY, | |
| 83 | value === "hosted" ? null : value, | |
| 84 | from, | |
| 85 | value, | |
| 86 | actorId, | |
| 87 | ); | |
| 88 | } |
src/spawn/cloud_placement.ts added +130
| @@ -0,0 +1,130 @@ | ||
| 1 | /** | |
| 2 | * The cloud placement (#16205): a paid order's forge, made as a pinned forge of its own on the | |
| 3 | * cloud account the "paid forges run on" setting names (`settings/paid_placement.ts`), never a | |
| 4 | * child of this one. `place` deploys at the catalog's default place for the plan, served on | |
| 5 | * `<name>.<base domain>` (no hostname is asked for), running the source and version this forge | |
| 6 | * itself runs; its claim link is the pinned one. `retire` retires it, keeping its data volume. | |
| 7 | * `room` refuses, in the deploy's own sentence, what a deploy would refuse now, so a buyer is told | |
| 8 | * before paying. Every call acts as the order (`orderWho`), never as a borrowed admin. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { App } from "../app.ts"; | |
| 12 | import { | |
| 13 | checkForOrder, | |
| 14 | deployForOrder, | |
| 15 | deployRoom, | |
| 16 | retireForOrder, | |
| 17 | } from "../actions/pinned.ts"; | |
| 18 | import { isPlan, type PlanName } from "../cloud/places.ts"; | |
| 19 | import { validSource } from "../core/pinned.ts"; | |
| 20 | import { publicOrigin } from "../core/public_origin.ts"; | |
| 21 | import { getRepo } from "../core/repos.ts"; | |
| 22 | import { releaseOf, running } from "../kernel/version.ts"; | |
| 23 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 24 | import { forgeSource } from "../settings/forge_source.ts"; | |
| 25 | import type { Placement, PlacementRefusal } from "./placement.ts"; | |
| 26 | ||
| 27 | /** A cloud body's id: the pinned forge's name behind a prefix no hosted or cell body has. */ | |
| 28 | const PREFIX = "cloud-"; | |
| 29 | ||
| 30 | export const cloudBodyId = (name: string): string => `${PREFIX}${name}`; | |
| 31 | ||
| 32 | /** The plan's size as a catalog plan; a size the catalog does not know is placed as small. */ | |
| 33 | export const catalogPlan = (size: string): PlanName => | |
| 34 | isPlan(size) ? size : "small"; | |
| 35 | ||
| 36 | /** | |
| 37 | * What a deployed copy of this forge runs: its own source repository (public, so the machine can | |
| 38 | * clone it over https from this forge) at the commit it runs, or the release tag when the build | |
| 39 | * names no commit. A forge run from source knows neither and cannot deploy itself. | |
| 40 | */ | |
| 41 | export function ownSource( | |
| 42 | app: App, | |
| 43 | ): Result<{ app: string; source: string; version: string }, string> { | |
| 44 | const own = forgeSource(app.db, app.config.forgeRepo); | |
| 45 | const [owner = "", name = ""] = (own ?? "").split("/"); | |
| 46 | const repo = | |
| 47 | owner === "" || name === "" ? undefined : getRepo(app.db, owner, name); | |
| 48 | if (repo === undefined || repo.visibility !== "public") | |
| 49 | return err( | |
| 50 | "This forge names no public source repository of its own (forgeRepo in its settings), so a forge deployed for an order has nothing to run.", | |
| 51 | ); | |
| 52 | const source = `${publicOrigin(app.config.url, "")}/${repo.ownerName}/${repo.name}.git`; | |
| 53 | if (!validSource(source)) | |
| 54 | return err( | |
| 55 | "This forge has no https address of its own (its url), so a deployed forge could not fetch its source.", | |
| 56 | ); | |
| 57 | const r = running(); | |
| 58 | const release = releaseOf(r); | |
| 59 | const version = | |
| 60 | r.commit !== null && r.commit.length === 40 | |
| 61 | ? r.commit | |
| 62 | : release !== null | |
| 63 | ? `v${release}` | |
| 64 | : ""; | |
| 65 | if (version === "") | |
| 66 | return err( | |
| 67 | "This forge does not know the commit it runs (it was started from source), so it cannot deploy a copy of itself.", | |
| 68 | ); | |
| 69 | return ok({ app: `${repo.ownerName}/${repo.name}`, source, version }); | |
| 70 | } | |
| 71 | ||
| 72 | const refused = (message: string): PlacementRefusal => ({ | |
| 73 | reason: "unknown", | |
| 74 | message, | |
| 75 | }); | |
| 76 | ||
| 77 | export function cloudPlacement( | |
| 78 | app: App, | |
| 79 | at: { readonly provider: string; readonly account: string }, | |
| 80 | o: { readonly orderId: string; readonly plan: PlanName }, | |
| 81 | ): Placement { | |
| 82 | return { | |
| 83 | room() { | |
| 84 | const own = ownSource(app); | |
| 85 | if (!own.ok) return refused(own.error); | |
| 86 | const no = deployRoom(app, at.provider, at.account, o.plan); | |
| 87 | return no === undefined ? undefined : { reason: "quota", message: no }; | |
| 88 | }, | |
| 89 | async place(plan) { | |
| 90 | const own = ownSource(app); | |
| 91 | if (!own.ok) return err(refused(own.error)); | |
| 92 | const made = await deployForOrder(app, o.orderId, { | |
| 93 | name: plan.name, | |
| 94 | host: "", | |
| 95 | target: at.provider, | |
| 96 | account: at.account, | |
| 97 | ...own.value, | |
| 98 | plan: o.plan, | |
| 99 | }); | |
| 100 | if (!made.ok) return err(refused(made.error)); | |
| 101 | return ok({ | |
| 102 | url: made.value.url, | |
| 103 | bodyId: cloudBodyId(plan.name), | |
| 104 | kind: "cloud", | |
| 105 | claimUrl: made.value.claim.link, | |
| 106 | }); | |
| 107 | }, | |
| 108 | async retire(bodyId) { | |
| 109 | if (!bodyId.startsWith(PREFIX)) return ok(); | |
| 110 | const gone = await retireForOrder( | |
| 111 | app, | |
| 112 | o.orderId, | |
| 113 | bodyId.slice(PREFIX.length), | |
| 114 | ); | |
| 115 | return gone.ok || gone.error === "No such pinned forge." | |
| 116 | ? ok() | |
| 117 | : err(refused(gone.error)); | |
| 118 | }, | |
| 119 | }; | |
| 120 | } | |
| 121 | ||
| 122 | /** Whether the order's forge answers on its name yet (the pinned check, as the order). */ | |
| 123 | export async function cloudAnswers( | |
| 124 | app: App, | |
| 125 | orderId: string, | |
| 126 | name: string, | |
| 127 | ): Promise<Result<boolean, string>> { | |
| 128 | const seen = await checkForOrder(app, orderId, name); | |
| 129 | return seen.ok ? ok(seen.value.healthy) : err(seen.error); | |
| 130 | } |
src/spawn/placement.ts +11 −2
| @@ -39,8 +39,17 @@ export type PlacementKind = "hosted" | "cell"; | ||
| 39 | 39 | export interface Placed { |
| 40 | 40 | readonly url: string; |
| 41 | 41 | readonly bodyId: string; |
| 42 | /** Absent reads as hosted. */ | |
| 43 | readonly kind?: PlacementKind; | |
| 42 | /** | |
| 43 | * Absent reads as hosted. `cloud` is a forge of its own on a cloud machine | |
| 44 | * (`spawn/cloud_placement.ts`, a paid order's): no child of this one, so it is never made into | |
| 45 | * a hosted child here. | |
| 46 | */ | |
| 47 | readonly kind?: PlacementKind | "cloud"; | |
| 48 | /** | |
| 49 | * A cloud body's claim link, shown once: it is claimed on its own machine, not through a copy | |
| 50 | * here. | |
| 51 | */ | |
| 52 | readonly claimUrl?: string; | |
| 44 | 53 | } |
| 45 | 54 | |
| 46 | 55 | export type PlacementRefusal = { readonly reason: "children" | "depth" | "exists" | "quota" | "unknown"; readonly message: string }; |
src/tui/screens/pinned.ts +19 −2
| @@ -11,7 +11,7 @@ | ||
| 11 | 11 | * Anyone else sees nothing and does nothing. |
| 12 | 12 | */ |
| 13 | 13 | |
| 14 | import { DOMAIN_WORDS, changeBaseDomain, 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, 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(["x"], "retire")], | |
| 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")], | |
| 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 | }, |
| @@ -180,6 +180,23 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen { | ||
| 180 | 180 | ); |
| 181 | 181 | return true; |
| 182 | 182 | } |
| 183 | if (e.key === "p") { | |
| 184 | const now = readPaidPlacement(f.app, f.user); | |
| 185 | ctx.push( | |
| 186 | promptScreen(ctx, screen, { | |
| 187 | title: "Paid forges run on", | |
| 188 | label: "hosted (inside this forge), or a cloud account such as digitalocean/main that allows writes", | |
| 189 | value: now.ok ? now.value : "hosted", | |
| 190 | onSubmit: (v) => { | |
| 191 | const set = changePaidPlacement(f.app, f.user, v.trim()); | |
| 192 | if (!set.ok) return set.error === "not_found" ? "You cannot change where paid forges run." : `${PAID_PLACEMENT_WORDS}.`; | |
| 193 | say(set.value === "hosted" ? "Paid forges run hosted, inside this forge." : `Paid forges are deployed on ${set.value}.`); | |
| 194 | return undefined; | |
| 195 | }, | |
| 196 | }), | |
| 197 | ); | |
| 198 | return true; | |
| 199 | } | |
| 183 | 200 | const p = forges()[state.index]; |
| 184 | 201 | if (p === undefined) return false; |
| 185 | 202 | if (e.key === "r") { |
src/tui/screens/pricing.ts +1
| @@ -106,6 +106,7 @@ export function pricingScreen(f: Session, ctx: Ctx): Screen { | ||
| 106 | 106 | } |
| 107 | 107 | if (o.state === "pending") s.says = "Not paid yet. Open the address, pay, then press r."; |
| 108 | 108 | else if (o.state === "paid" || o.state === "spawning") s.says = `Paid. Making ${o.name}; press r again in a moment.`; |
| 109 | else if (o.state === "making") s.says = `Paid. ${o.name} is starting on its own machine, which takes a few minutes; press r again once it answers.`; | |
| 109 | 110 | else if (o.state === "failed") stage = { kind: "done", name: o.name, says: `Paid, but the forge could not be made: ${o.reason}. The operator has been told; keep the order id ${o.id}.` }; |
| 110 | 111 | else { |
| 111 | 112 | const r = receiptFacts(o, getPlans(f.app.db).find((p) => p.key === o.plan)?.name); |
src/web/pages/pinned.ts +6
| @@ -18,6 +18,8 @@ export interface PinnedFacts { | ||
| 18 | 18 | readonly checks: Map<string, string>; |
| 19 | 19 | /** The domain deployed forges are served on; empty when none is set. */ |
| 20 | 20 | readonly domain: string; |
| 21 | /** Where paid forges run: `hosted` (when absent), or the cloud account named `provider/name`. */ | |
| 22 | readonly paid?: string; | |
| 21 | 23 | } |
| 22 | 24 | |
| 23 | 25 | const fact = (label: string, value: Html): Html => html`<div class="status-row"><dt>${label}</dt><dd>${value}</dd></div>`; |
| @@ -95,6 +97,10 @@ export function pinnedListPage(forges: PinnedView[], f: PinnedFacts): Html { | ||
| 95 | 97 | ${field({ name: "domain", label: "Domain for deployed forges", value: f.domain, placeholder: "forges.example.com", mono: true, maxlength: 253, spellcheck: false, hint: "A forge deployed with no hostname is served on <name>.<domain>, so its buyer configures no DNS. With a Cloudflare account that allows writes and a token that can edit the zone, the forge writes the record itself, after every replace too. Empty for none." })} |
| 96 | 98 | ${btn("Save", { variant: "secondary", label: "Save the domain for deployed forges" })} |
| 97 | 99 | </form> |
| 100 | <form method="post" action="/pinned/paid" class="stack"> | |
| 101 | ${field({ name: "paid", label: "Paid forges run on", value: f.paid ?? "hosted", placeholder: "hosted", mono: true, maxlength: 100, spellcheck: false, hint: "hosted runs a bought forge inside this one. A cloud account, such as digitalocean/main, deploys each paid order as a pinned forge of its own at the catalog's default place, on <name>.<domain>. Free forges stay hosted." })} | |
| 102 | ${btn("Save", { variant: "secondary", label: "Save where paid forges run" })} | |
| 103 | </form> | |
| 98 | 104 | ${forges.some((p) => p.claimedAt !== "") ? html`<p class="muted small">${HOST_CAN}</p>` : null} |
| 99 | 105 | ${forges.length === 0 ? html`<p role="status">No pinned forge yet. Deploy one to a cloud account that allows writes.</p>` : forges.map((p) => forge(p, f))}`; |
| 100 | 106 | } |
src/web/pages/pricing.ts +1
| @@ -190,6 +190,7 @@ async function doneView(ctx: Ctx): Promise<Response> { | ||
| 190 | 190 | }; |
| 191 | 191 | if (o.state === "pending") return waiting(ctx, "Waiting for the payment to arrive. This page updates by itself."); |
| 192 | 192 | if (o.state === "paid" || o.state === "spawning") return waiting(ctx, `Paid. Making ${o.name} now; the link to open it appears here.`); |
| 193 | if (o.state === "making") return waiting(ctx, `Paid. ${o.name} is starting on its own machine, which takes a few minutes; the link to open it appears here once it answers.`); | |
| 193 | 194 | if (o.state === "failed") |
| 194 | 195 | return plain(`${o.name} is paid but not made yet`, html`<p>Your payment went through, but the forge could not be made just now: ${o.reason}.</p> |
| 195 | 196 | <p>The operator has been told and will make it or pay you back. Keep this page's address: <code class="mono">${o.id}</code>.</p>`, 200); |
test/order-cloud.test.ts added +393
| @@ -0,0 +1,393 @@ | ||
| 1 | /** | |
| 2 | * Paid forges on a cloud machine (#16205): with "paid forges run on" naming a cloud account, a | |
| 3 | * paid order is deployed as a pinned forge of its own, as the order and never as a borrowed admin, | |
| 4 | * at the catalog's default place with no hostname, running the source and commit this forge runs. | |
| 5 | * The order is `making` until the forge answers, and only then shows its claim link. What a deploy | |
| 6 | * would refuse is said before checkout; a deploy refused after payment fails the order, saying | |
| 7 | * why, with no hosted forge made instead; a restart while making makes no second machine. A | |
| 8 | * recorded fetch stands in for DigitalOcean and the deployed forge. | |
| 9 | */ | |
| 10 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 11 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 12 | import { tmpdir } from "node:os"; | |
| 13 | import { join } from "node:path"; | |
| 14 | import { createApp, type App } from "../src/app.ts"; | |
| 15 | import { | |
| 16 | addAccount, | |
| 17 | allowWrite, | |
| 18 | net as cloudNet, | |
| 19 | } from "../src/actions/cloud.ts"; | |
| 20 | import { setCeiling } from "../src/actions/cloud_ceiling.ts"; | |
| 21 | import { | |
| 22 | deliverLink, | |
| 23 | makingWatch, | |
| 24 | placeOrder, | |
| 25 | reconcileOrder, | |
| 26 | settleSession, | |
| 27 | } from "../src/actions/order.ts"; | |
| 28 | import { | |
| 29 | changeBaseDomain, | |
| 30 | changePaidPlacement, | |
| 31 | net, | |
| 32 | readPaidPlacement, | |
| 33 | } from "../src/actions/pinned.ts"; | |
| 34 | import { createRepo } from "../src/actions/repos.ts"; | |
| 35 | import { useCheckout, type CheckoutProvider } from "../src/billing/checkout.ts"; | |
| 36 | import { getOrder } from "../src/billing/orders.ts"; | |
| 37 | import { changesOf, getPinned } from "../src/core/pinned.ts"; | |
| 38 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 39 | import { ok } from "../src/kernel/result.ts"; | |
| 40 | import { usePlacement } from "../src/spawn/door.ts"; | |
| 41 | import { bootHostedChild, closeHostedChildren } from "../src/spawn/host.ts"; | |
| 42 | import { getPaidPlacement } from "../src/settings/paid_placement.ts"; | |
| 43 | import { quietLogs } from "./helpers/globals.ts"; | |
| 44 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 45 | ||
| 46 | quietLogs(); | |
| 47 | ||
| 48 | const COMMIT = "c".repeat(40); | |
| 49 | // No page and no test waits on the in-process watch: each asks the order itself. | |
| 50 | makingWatch.tries = 0; | |
| 51 | ||
| 52 | describe("a paid order on a cloud account", () => { | |
| 53 | let dataDir = ""; | |
| 54 | let app: App; | |
| 55 | const calls: { method: string; path: string }[] = []; | |
| 56 | /** The names whose machines answer: resolved to their address, front page and claim. */ | |
| 57 | const up = new Set<string>(); | |
| 58 | let refuseCreate = false; | |
| 59 | let droplets = 2000; | |
| 60 | let checkouts = 0; | |
| 61 | let hostedPlaced = 0; | |
| 62 | const before = process.env["FORGE_COMMIT"]; | |
| 63 | ||
| 64 | const admin = () => getUserByName(app.db, "alice")!; | |
| 65 | const fake: CheckoutProvider = { | |
| 66 | name: "fake", | |
| 67 | create: async () => | |
| 68 | ok({ id: `cs_${++checkouts}`, url: "https://pay.fake.test/x" }), | |
| 69 | state: async () => | |
| 70 | ok({ paid: false, customer: "cus_1", subscription: "sub_1" }), | |
| 71 | }; | |
| 72 | const buy = async (name: string) => { | |
| 73 | const placed = await placeOrder( | |
| 74 | app, | |
| 75 | { | |
| 76 | name, | |
| 77 | plan: "small", | |
| 78 | email: "[email protected]", | |
| 79 | address: `198.51.100.${checkouts + 10}`, | |
| 80 | }, | |
| 81 | new URL("https://forge.test/pricing"), | |
| 82 | ); | |
| 83 | if (!placed.ok) throw new Error(placed.error.message); | |
| 84 | const o = getOrder(app.db, placed.value.id)!; | |
| 85 | await settleSession(app, { | |
| 86 | id: o.sessionId, | |
| 87 | metadata: { order: o.id }, | |
| 88 | customer: "cus_1", | |
| 89 | subscription: "sub_1", | |
| 90 | payment_status: "paid", | |
| 91 | }); | |
| 92 | return getOrder(app.db, o.id)!; | |
| 93 | }; | |
| 94 | /** Let the next ask go now: the row's clock says the last one was long ago. */ | |
| 95 | const askable = (a: App, id: string) => | |
| 96 | a.db.query("UPDATE forge_order SET updated_at = 0 WHERE id = ?1").run(id); | |
| 97 | const creates = () => | |
| 98 | calls.filter((c) => c.method === "POST" && c.path.endsWith("/droplets")) | |
| 99 | .length; | |
| 100 | ||
| 101 | const open = async (dir: string): Promise<App> => { | |
| 102 | const a = createApp({ | |
| 103 | dataDir: dir, | |
| 104 | port: 0, | |
| 105 | forgeRepo: "alice/forge", | |
| 106 | url: "https://forge.test", | |
| 107 | }); | |
| 108 | useCheckout(a, fake); | |
| 109 | usePlacement(a, { | |
| 110 | place: async (plan) => ( | |
| 111 | ++hostedPlaced, | |
| 112 | ok({ | |
| 113 | url: `https://${plan.name}.hosted.test`, | |
| 114 | bodyId: `fake-${hostedPlaced}`, | |
| 115 | }) | |
| 116 | ), | |
| 117 | retire: async () => ok(), | |
| 118 | }); | |
| 119 | return a; | |
| 120 | }; | |
| 121 | ||
| 122 | beforeAll(async () => { | |
| 123 | process.env["FORGE_COMMIT"] = COMMIT; | |
| 124 | dataDir = await mkdtemp(join(tmpdir(), "forge-order-cloud-")); | |
| 125 | app = await open(dataDir); | |
| 126 | await seedPlaces(app.db); | |
| 127 | const made = await createUser(app.db, { | |
| 128 | origin: "seed", | |
| 129 | trusted: true, | |
| 130 | username: "alice", | |
| 131 | email: "[email protected]", | |
| 132 | password: "a-good-passphrase", | |
| 133 | adminIfFirst: true, | |
| 134 | }); | |
| 135 | if (!made.ok) throw new Error(made.error); | |
| 136 | const repo = await createRepo(app, made.value, { | |
| 137 | name: "forge", | |
| 138 | visibility: "public", | |
| 139 | }); | |
| 140 | if (!repo.ok) throw new Error("repo"); | |
| 141 | cloudNet.fetch = async () => | |
| 142 | new Response( | |
| 143 | JSON.stringify({ account: { email: "[email protected]", status: "active" } }), | |
| 144 | { status: 200 }, | |
| 145 | ); | |
| 146 | const added = await addAccount( | |
| 147 | app, | |
| 148 | admin(), | |
| 149 | "digitalocean", | |
| 150 | "main", | |
| 151 | "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5", | |
| 152 | ); | |
| 153 | if (!added.ok) throw new Error(String(added.error)); | |
| 154 | allowWrite(app, admin(), "digitalocean", "main", true); | |
| 155 | expect(setCeiling(app, admin(), "digitalocean", "main", 500).ok).toBe(true); | |
| 156 | expect(changeBaseDomain(app, admin(), "forges.test").ok).toBe(true); | |
| 157 | const json = (o: unknown, status = 200) => | |
| 158 | new Response(JSON.stringify(o), { status }); | |
| 159 | const address = (id: number) => `203.0.113.${id % 250}`; | |
| 160 | net.fetch = async (url, init) => { | |
| 161 | const u = new URL(url); | |
| 162 | const method = init?.method ?? "GET"; | |
| 163 | calls.push({ method, path: u.pathname }); | |
| 164 | if (u.pathname.endsWith("/volumes")) | |
| 165 | return json({ volume: { id: "vol-1" } }, 201); | |
| 166 | if (u.pathname.endsWith("/account/keys")) | |
| 167 | return json({ ssh_key: { id: 4242 } }, 201); | |
| 168 | if (method === "DELETE") return new Response(null, { status: 204 }); | |
| 169 | if (method === "POST") | |
| 170 | return refuseCreate | |
| 171 | ? json({ message: "droplet limit reached" }, 422) | |
| 172 | : json({ droplet: { id: ++droplets } }, 202); | |
| 173 | const id = Number(u.pathname.split("/").at(-1)); | |
| 174 | return json({ | |
| 175 | droplet: { | |
| 176 | id, | |
| 177 | status: "active", | |
| 178 | networks: { v4: [{ type: "public", ip_address: address(id) }] }, | |
| 179 | }, | |
| 180 | }); | |
| 181 | }; | |
| 182 | net.resolve = async (host) => { | |
| 183 | const p = getPinned(app.db, host.split(".")[0]!); | |
| 184 | return p !== undefined && up.has(p.name) ? [p.address] : []; | |
| 185 | }; | |
| 186 | net.probe = async (url) => | |
| 187 | String(url).includes("/api/v1/first-admin/claim") | |
| 188 | ? json({ state: "waiting" }) | |
| 189 | : new Response("ok", { status: 200 }); | |
| 190 | }, 30_000); | |
| 191 | ||
| 192 | afterAll(async () => { | |
| 193 | if (before === undefined) delete process.env["FORGE_COMMIT"]; | |
| 194 | else process.env["FORGE_COMMIT"] = before; | |
| 195 | closeHostedChildren(app); | |
| 196 | app.close(); | |
| 197 | await rm(dataDir, { recursive: true, force: true }); | |
| 198 | }); | |
| 199 | ||
| 200 | test("the setting is hosted until an admin names an account that allows writes, kept with who", () => { | |
| 201 | expect(getPaidPlacement(app.db)).toEqual({ where: "hosted" }); | |
| 202 | expect(readPaidPlacement(app, undefined)).toMatchObject({ ok: false }); | |
| 203 | expect( | |
| 204 | changePaidPlacement(app, undefined, "digitalocean/main"), | |
| 205 | ).toMatchObject({ ok: false, error: "not_found" }); | |
| 206 | for (const bad of [ | |
| 207 | "digitalocean/none", | |
| 208 | "cloudflare/main", | |
| 209 | "aws/main", | |
| 210 | "main", | |
| 211 | 7, | |
| 212 | "digitalocean/Main", | |
| 213 | ]) | |
| 214 | expect(changePaidPlacement(app, admin(), bad)).toMatchObject({ | |
| 215 | ok: false, | |
| 216 | error: "invalid_paid_placement", | |
| 217 | }); | |
| 218 | expect(changePaidPlacement(app, admin(), "hosted")).toEqual({ | |
| 219 | ok: true, | |
| 220 | value: "hosted", | |
| 221 | }); | |
| 222 | expect( | |
| 223 | app.db | |
| 224 | .query( | |
| 225 | "SELECT COUNT(*) AS n FROM forge_setting_change WHERE key = 'paid.placement'", | |
| 226 | ) | |
| 227 | .get(), | |
| 228 | ).toEqual({ n: 0 }); | |
| 229 | }); | |
| 230 | ||
| 231 | test("hosted: a paid order is made as today, through the hosted placement, with no cloud call", async () => { | |
| 232 | const o = await buy("hostedone"); | |
| 233 | await bootHostedChild(app, "hostedone"); | |
| 234 | expect(o.state).toBe("spawned"); | |
| 235 | expect(hostedPlaced).toBe(1); | |
| 236 | expect(getPinned(app.db, "hostedone")).toBeUndefined(); | |
| 237 | expect(calls).toEqual([]); | |
| 238 | }); | |
| 239 | ||
| 240 | test("a deploy the ceiling would refuse is said before checkout, in the ceiling's words, and nothing is held", async () => { | |
| 241 | expect(changePaidPlacement(app, admin(), "digitalocean/main")).toEqual({ | |
| 242 | ok: true, | |
| 243 | value: "digitalocean/main", | |
| 244 | }); | |
| 245 | expect( | |
| 246 | app.db | |
| 247 | .query( | |
| 248 | "SELECT to_value, actor_id FROM forge_setting_change WHERE key = 'paid.placement'", | |
| 249 | ) | |
| 250 | .all(), | |
| 251 | ).toEqual([{ to_value: "digitalocean/main", actor_id: admin().id }]); | |
| 252 | expect(setCeiling(app, admin(), "digitalocean", "main", 5).ok).toBe(true); | |
| 253 | const n = checkouts; | |
| 254 | const r = await placeOrder( | |
| 255 | app, | |
| 256 | { | |
| 257 | name: "toodear", | |
| 258 | plan: "small", | |
| 259 | email: "[email protected]", | |
| 260 | address: "198.51.100.200", | |
| 261 | }, | |
| 262 | new URL("https://forge.test/pricing"), | |
| 263 | ); | |
| 264 | expect(r).toMatchObject({ ok: false, error: { field: "form" } }); | |
| 265 | expect(!r.ok && r.error.message).toContain( | |
| 266 | "digitalocean/main is held to $5 a month", | |
| 267 | ); | |
| 268 | expect(checkouts).toBe(n); | |
| 269 | expect( | |
| 270 | app.db | |
| 271 | .query("SELECT COUNT(*) AS n FROM forge_order WHERE name = 'toodear'") | |
| 272 | .get(), | |
| 273 | ).toEqual({ n: 0 }); | |
| 274 | expect(setCeiling(app, admin(), "digitalocean", "main", 500).ok).toBe(true); | |
| 275 | }); | |
| 276 | ||
| 277 | test("a paid order deploys one pinned forge at the default place, as the order, and is making until it answers", async () => { | |
| 278 | const o = await buy("acme"); | |
| 279 | expect(o.state).toBe("making"); | |
| 280 | expect(creates()).toBe(1); | |
| 281 | expect(hostedPlaced).toBe(1); | |
| 282 | const p = getPinned(app.db, "acme")!; | |
| 283 | expect(p).toMatchObject({ | |
| 284 | host: "acme.forges.test", | |
| 285 | target: "digitalocean", | |
| 286 | account: "main", | |
| 287 | app: "alice/forge", | |
| 288 | source: "https://forge.test/alice/forge.git", | |
| 289 | version: COMMIT, | |
| 290 | size: "s-1vcpu-2gb", | |
| 291 | datacenter: "nyc3", | |
| 292 | }); | |
| 293 | expect(changesOf(app.db, p.id).map((c) => c.by)).toEqual([`order:${o.id}`]); | |
| 294 | const ev = app.db | |
| 295 | .query< | |
| 296 | { actor_id: string | null; payload: string }, | |
| 297 | [] | |
| 298 | >("SELECT actor_id, payload FROM event WHERE kind = 'pinned.deployed'") | |
| 299 | .all(); | |
| 300 | expect(ev).toHaveLength(1); | |
| 301 | expect(ev[0]!.actor_id).toBeNull(); | |
| 302 | expect(JSON.parse(ev[0]!.payload)).toMatchObject({ | |
| 303 | name: "acme", | |
| 304 | order: o.id, | |
| 305 | }); | |
| 306 | // Not answering yet: no link, still making. | |
| 307 | expect(await deliverLink(app, o)).toEqual({ kind: "failed" }); | |
| 308 | askable(app, o.id); | |
| 309 | expect((await reconcileOrder(app, o.id))?.state).toBe("making"); | |
| 310 | // Asked again at once, the forge is not asked twice. | |
| 311 | const reads = calls.length; | |
| 312 | expect((await reconcileOrder(app, o.id))?.state).toBe("making"); | |
| 313 | expect(calls.length).toBe(reads); | |
| 314 | up.add("acme"); | |
| 315 | askable(app, o.id); | |
| 316 | const done = (await reconcileOrder(app, o.id))!; | |
| 317 | expect(done.state).toBe("spawned"); | |
| 318 | const given = await deliverLink(app, done); | |
| 319 | expect(given.kind).toBe("link"); | |
| 320 | expect(given.kind === "link" && given.claimUrl).toStartWith( | |
| 321 | "https://acme.forges.test/first-admin#", | |
| 322 | ); | |
| 323 | expect(await deliverLink(app, getOrder(app.db, o.id)!)).toEqual({ | |
| 324 | kind: "shown", | |
| 325 | }); | |
| 326 | expect( | |
| 327 | app.db | |
| 328 | .query( | |
| 329 | "SELECT COUNT(*) AS n FROM secret WHERE name LIKE 'ORDER_CLAIM_%'", | |
| 330 | ) | |
| 331 | .get(), | |
| 332 | ).toEqual({ n: 0 }); | |
| 333 | expect(creates()).toBe(1); | |
| 334 | }); | |
| 335 | ||
| 336 | test("a restart while making makes no second machine, and the link still comes once it answers", async () => { | |
| 337 | const o = await buy("beta"); | |
| 338 | expect(o.state).toBe("making"); | |
| 339 | expect(creates()).toBe(2); | |
| 340 | closeHostedChildren(app); | |
| 341 | app.close(); | |
| 342 | app = await open(dataDir); | |
| 343 | askable(app, o.id); | |
| 344 | expect((await reconcileOrder(app, o.id))?.state).toBe("making"); | |
| 345 | up.add("beta"); | |
| 346 | askable(app, o.id); | |
| 347 | expect((await reconcileOrder(app, o.id))?.state).toBe("spawned"); | |
| 348 | const given = await deliverLink(app, getOrder(app.db, o.id)!); | |
| 349 | expect(given.kind === "link" && given.claimUrl).toStartWith( | |
| 350 | "https://beta.forges.test/first-admin#", | |
| 351 | ); | |
| 352 | expect(creates()).toBe(2); | |
| 353 | }); | |
| 354 | ||
| 355 | test("a spawn lost to a restart after its machine was recorded replaces that machine for a new link, never adds one", async () => { | |
| 356 | const o = await buy("gamma"); | |
| 357 | expect(o.state).toBe("making"); | |
| 358 | const made = creates(); | |
| 359 | const deletes = () => calls.filter((c) => c.method === "DELETE" && c.path.includes("/droplets/")).length; | |
| 360 | const gone = deletes(); | |
| 361 | // As a restart mid-spawn leaves it: `spawning`, stale, its link never kept. | |
| 362 | app.db.query("UPDATE forge_order SET state = 'spawning', updated_at = 0 WHERE id = ?1").run(o.id); | |
| 363 | app.db.query("DELETE FROM secret WHERE name LIKE 'ORDER_CLAIM_%'").run(); | |
| 364 | expect((await reconcileOrder(app, o.id))?.state).toBe("making"); | |
| 365 | expect(creates()).toBe(made + 1); | |
| 366 | expect(deletes()).toBe(gone + 1); | |
| 367 | expect(app.db.query("SELECT COUNT(*) AS n FROM secret WHERE name LIKE 'ORDER_CLAIM_%'").get()).toEqual({ n: 1 }); | |
| 368 | }); | |
| 369 | ||
| 370 | test("a deploy refused after payment fails the order with the reason, and no hosted forge is made", async () => { | |
| 371 | refuseCreate = true; | |
| 372 | const o = await buy("refused"); | |
| 373 | refuseCreate = false; | |
| 374 | expect(o.state).toBe("failed"); | |
| 375 | expect(o.reason).toContain("The cloud refused: api.digitalocean.com answered 422"); | |
| 376 | expect(hostedPlaced).toBe(1); | |
| 377 | expect(getPinned(app.db, "refused")?.state).toBe("failed"); | |
| 378 | }); | |
| 379 | ||
| 380 | test("a name a pinned forge holds cannot be bought", async () => { | |
| 381 | const r = await placeOrder( | |
| 382 | app, | |
| 383 | { | |
| 384 | name: "acme", | |
| 385 | plan: "small", | |
| 386 | email: "[email protected]", | |
| 387 | address: "198.51.100.201", | |
| 388 | }, | |
| 389 | new URL("https://forge.test/pricing"), | |
| 390 | ); | |
| 391 | expect(r).toMatchObject({ ok: false, error: { field: "name" } }); | |
| 392 | }); | |
| 393 | }); |
new above
offline