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

One door makes every forge: a paid plan runs where paid.placement says, however it was granted #16394

Merged opened this

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

Merged

sold/one-door → main 0 commits

  • Merged. sold/one-door was merged into main as 07da35b.

Review

Sign in to review this change.
13 files changed +1110 −212
src/actions/order.ts +47 −143
@@ -12,39 +12,34 @@
1212 * forge can send mail. It is never kept: the page makes a fresh one when the
1313 * buyer arrives, and a buyer who left can ask for one by email.
1414 *
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.
15 * Where the forge runs is the door's one rule (`spawn/making.ts`): when paid forges run on a cloud
16 * account (#16205) the door deploys it as the order, at the place the buyer chose (#16385) or the
17 * plan's default, and the order is `making` until it answers on its name. Its claim link is the
18 * pinned one, issued with the machine: kept sealed until the buyer is shown it, and shown and
19 * mailed only once the forge answers. Nothing about such an order falls back to a hosted forge: a
20 * deploy that is refused leaves it `failed`, saying why.
2121 */
2222
23 import { during } from "../perf/jobs.ts";
2423 import type { App } from "../app.ts";
2524 import { checkoutOf } from "../billing/checkout.ts";
26 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";
25 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";
2726 import { putEntitlement } from "../billing/store.ts";
2827 import { heldOf } from "../perf/held.ts";
29 import { getUserByName, type User } from "../core/users.ts";
28 import type { User } from "../core/users.ts";
3029 import { publicOrigin } from "../core/public_origin.ts";
3130 import { err, ok, type Result } from "../kernel/result.ts";
3231 import { isChildName } from "../core/proposal_token.ts";
3332 import type { Ctx } from "../http/context.ts";
34 import { spawnDoor } from "../spawn/door.ts";
33 import { nameTaken, spawnDoor } from "../spawn/door.ts";
3534 import { FREE, getPlan, type Plan } from "../settings/plans.ts";
36 import { listChildrenNow, reissueClaimFor } from "./spawn.ts";
37 import { mayMail, sendCapped } from "./mail.ts";
35 import { reissueClaimFor } from "./spawn.ts";
3836 import { mailerOf } from "./verify.ts";
39 import { deleteSecret, resolveSecrets, setSecret } from "../core/secret_store.ts";
40 import { getPinned } from "../core/pinned.ts";
41 import { getPaidPlacement } from "../settings/paid_placement.ts";
42 import { catalogPlan, cloudAnswers, cloudPlacement } from "../spawn/cloud_placement.ts";
43 import type { Placement } from "../spawn/placement.ts";
44 import type { SpawnPlan } from "../spawn/plan.ts";
37 import { askMaking, dropLink, failOrder, keptLink, mailLink } from "../spawn/making.ts";
38
39 export { makingWatch } from "../spawn/making.ts";
4540
4641 export interface Refusal {
47 readonly field: "name" | "email" | "plan" | "form";
42 readonly field: "name" | "email" | "plan" | "place" | "form";
4843 readonly message: string;
4944 }
5045
@@ -52,10 +47,6 @@ const ADDRESS = /^[^\s<>@,;:"\\]{1,64}@[^\s<>@,;:"\\]{1,190}$/;
5247 export const NO_PROVIDER = "Checkout is not connected on this forge: ask the operator.";
5348 /** A spawn that stays `spawning` this long is taken as lost and may be retried. */
5449 const STALE_MS = 5 * 60_000;
55 /**
56 * A `making` order's forge is asked whether it answers at most this often, however many pages wait.
57 */
58 const ASK_MS = 15_000;
5950 /** A claim link is mailed again at most once a day per order: a stranger cannot make it a mail-bomb. */
6051 const RESEND_MS = 24 * 60 * 60_000;
6152
@@ -78,15 +69,21 @@ export const emailOf = (raw: unknown): string | undefined => {
7869 return s.length <= 254 && ADDRESS.test(s) ? s.toLowerCase() : undefined;
7970 };
8071
81 /** Every refusal of a name, in one sentence, or undefined when it is free to buy. */
82 export async function nameRefusal(app: App, name: string, plan: Plan, now: number): Promise<string | undefined> {
83 if (!isChildName(name) || name.length > 38) return "Use 1 to 38 lowercase letters, digits and dashes, not starting or ending with a dash";
84 if (getUserByName(app.db, name) !== undefined || listChildrenNow(app).some((c) => c.name === name) || getPinned(app.db, name) !== undefined) return "That name is taken";
85 if (nameHeld(app.db, name, now)) return "That name is held for someone else; try another";
86 // The door's own plan: reserved words and the rest of the name's rules, with nothing made.
87 const dry = await spawnDoor(systemCtx(app), undefined, { name, apps: [], crew: [], plan: plan.key, dryRun: true }, { paid: true });
88 if (dry.status >= 400) return String(dry.body["message"] ?? "That name cannot be used").replace(/^name: /, "");
89 return undefined;
72 /**
73 * Every refusal of a name, or of where it runs, in one sentence and the field it is about, or
74 * undefined when it is free to buy. Where it runs is the door's: its plan, with nothing made,
75 * refuses an unorderable or dearer place, or a deploy the ceiling would refuse, before payment.
76 */
77 export async function nameRefusal(app: App, name: string, plan: Plan, now: number, place = ""): Promise<Refusal | undefined> {
78 const named = (message: string): Refusal => ({ field: "name", message });
79 if (!isChildName(name) || name.length > 38) return named("Use 1 to 38 lowercase letters, digits and dashes, not starting or ending with a dash");
80 if (await nameTaken(app, name)) return named("That name is taken");
81 if (nameHeld(app.db, name, now)) return named("That name is held for someone else; try another");
82 const dry = await spawnDoor(systemCtx(app), undefined, { name, apps: [], crew: [], plan: plan.key, ...(place === "" ? {} : { place }), dryRun: true }, { paid: true });
83 if (dry.status < 400) return undefined;
84 const said = String(dry.body["message"] ?? "That name cannot be used");
85 if (said.startsWith("place: ")) return { field: "place", message: said.slice(7).replace(/\.$/, "") };
86 return dry.body["error"] === "refused" ? { field: "form", message: said.replace(/\.$/, "") } : named(said.replace(/^name: /, ""));
9087 }
9188
9289 export interface Placed {
@@ -98,25 +95,22 @@ export interface Placed {
9895 }
9996
10097 /** Validate, hold the name, make the checkout. Nothing is held if the checkout cannot be made. */
101 export async function placeOrder(app: App, input: { name: unknown; plan: unknown; email: unknown; address: string }, url: URL, now = Date.now()): Promise<Result<Placed, Refusal>> {
98 export async function placeOrder(app: App, input: { name: unknown; plan: unknown; email: unknown; address: string; place?: unknown }, url: URL, now = Date.now()): Promise<Result<Placed, Refusal>> {
10299 const plan = typeof input.plan === "string" ? getPlan(app.db, input.plan) : undefined;
103100 if (plan === undefined || plan.key === FREE || plan.priceUsd <= 0) return err({ field: "plan", message: "Pick one of the paid plans" });
104101 const email = emailOf(input.email);
105102 if (email === undefined) return err({ field: "email", message: "Enter the email the link should go to" });
106103 const name = typeof input.name === "string" ? input.name.trim() : "";
104 const place = typeof input.place === "string" ? input.place.trim().slice(0, 200) : "";
107105 const provider = checkoutOf(app);
108106 if (provider === undefined) return err({ field: "form", message: NO_PROVIDER });
109107 if (pendingCount(app.db, now) >= MAX_PENDING) return err({ field: "form", message: "Many orders are waiting right now; try again in a few minutes" });
110108 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" });
111 const refused = await nameRefusal(app, name, plan, now);
112 if (refused !== undefined) return err({ field: "name", message: refused });
113 // Told before paying: what a cloud deploy would refuse now (the ceiling, the catalog), in its own
114 // words.
115 const full = cloudFor(app, "", plan)?.room?.();
116 if (full !== undefined) return err({ field: "form", message: full.message.replace(/\.$/, "") });
109 const refused = await nameRefusal(app, name, plan, now, place);
110 if (refused !== undefined) return err(refused);
117111 const id = newId();
118112 const ticket = newTicket();
119 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" });
113 if (!holdName(app.db, { id, name, plan: plan.key, priceUsd: plan.priceUsd, email, ticket, address: input.address, place }, now)) return err({ field: "name", message: "That name is held for someone else; try another" });
120114 const origin = publicOrigin(app.config.url, url.origin);
121115 const made = await provider.create({
122116 orderId: id, forge: name, plan: plan.key, planName: plan.name, priceUsd: plan.priceUsd, email,
@@ -185,41 +179,25 @@ async function makeForge(app: App, id: string, from: "paid" | "failed" | "spawni
185179 }
186180
187181 /**
188 * The placement a paid order on `plan` is made by when paid forges run on a cloud account; none
189 * when they are hosted.
182 * Make the order's forge through the one door, as the order: hosted, or on a cloud machine with the
183 * order `making` (`spawn/making.ts`), whichever the door's rule says. A paid order's entitlement
184 * is written once the door has made or deployed it.
190185 */
191 function cloudFor(app: App, orderId: string, plan: Plan): Placement | undefined {
192 const at = getPaidPlacement(app.db);
193 return at.where === "cloud" ? cloudPlacement(app, at, { orderId, plan: catalogPlan(plan.size) }) : undefined;
194 }
195
196 /**
197 * The sealed claim link of a cloud order, by order id: a forge secret, so it is read with an audit
198 * line.
199 */
200 const linkName = (id: string): string => `ORDER_CLAIM_${id.toUpperCase()}`;
201 const keptLink = (app: App, id: string): string | undefined =>
202 resolveSecrets(app.db, app.config.dataDir, app.bus, [linkName(id)], { run: `order:${id}` })[linkName(id)];
203
204186 async function spawnOrder(app: App, id: string): Promise<Order | undefined> {
205187 const o = getOrder(app.db, id) as Order;
206 const fail = (reason: string): Order => {
207 move(app.db, id, "spawning", "failed", Date.now(), { reason });
208 app.bus.append({ kind: "billing.order_failed", payload: { id, forge: o.name, plan: o.plan, reason } });
209 app.log.error("a paid order could not be made into a forge", { id, forge: o.name, reason });
210 return getOrder(app.db, id) as Order;
211 };
188 const fail = (reason: string): Order => failOrder(app, id, reason);
212189 try {
213190 const plan = getPlan(app.db, o.plan);
214191 if (plan === undefined) return fail(`the ${o.plan} plan is no longer offered`);
215 const cloud = cloudFor(app, id, plan);
216 if (cloud !== undefined) return await placeOnCloud(app, o, plan, cloud, fail);
217 const door = await spawnDoor(systemCtx(app), undefined, { name: o.name, apps: [], crew: [], plan: plan.key, dryRun: false }, { paid: true });
192 const door = await spawnDoor(systemCtx(app), undefined, { name: o.name, apps: [], crew: [], plan: plan.key, ...(o.place === "" ? {} : { place: o.place }), dryRun: false }, { paid: true, order: o });
218193 if (door.status >= 400) return fail(String(door.body["message"] ?? "the forge could not be made").slice(0, 300));
219 putEntitlement(app.db, {
220 forge: o.name, plan: plan.key, status: "active", provider: checkoutOf(app)?.name ?? "none", payer: o.email,
221 customerId: o.customerId, subscriptionId: o.subscriptionId, source: checkoutOf(app)?.name ?? "paid",
222 }, plan.size, "");
194 // A forge an admin or a gift code gave has no checkout behind it: its plan is not a sale.
195 if (o.sessionId !== "")
196 putEntitlement(app.db, {
197 forge: o.name, plan: plan.key, status: "active", provider: checkoutOf(app)?.name ?? "none", payer: o.email,
198 customerId: o.customerId, subscriptionId: o.subscriptionId, source: checkoutOf(app)?.name ?? "paid",
199 }, plan.size, "");
200 if (door.body["making"] === true) return getOrder(app.db, id);
223201 // The forge exists and is paid for: spawned, even if a lost try marked it failed meanwhile.
224202 if (!move(app.db, id, "spawning", "spawned", Date.now())) move(app.db, id, "failed", "spawned", Date.now());
225203 app.bus.append({ kind: "billing.order_spawned", payload: { id, forge: o.name, plan: plan.key } });
@@ -229,67 +207,6 @@ async function spawnOrder(app: App, id: string): Promise<Order | undefined> {
229207 }
230208 }
231209
232 /**
233 * A paid order's forge on a cloud machine: the name's rules through the same door a hosted order
234 * takes (a plan, nothing made), then the cloud placement deploys it as the order. Its link is
235 * kept sealed and the order is `making` until the forge answers (`askMaking`).
236 */
237 async function placeOnCloud(app: App, o: Order, plan: Plan, cloud: Placement, fail: (reason: string) => Order): Promise<Order | undefined> {
238 const dry = await spawnDoor(systemCtx(app), undefined, { name: o.name, apps: [], crew: [], plan: plan.key, dryRun: true }, { paid: true });
239 if (dry.status >= 400) return fail(String(dry.body["message"] ?? "the forge could not be made").slice(0, 300));
240 const placed = await cloud.place(dry.body["plan"] as SpawnPlan);
241 if (!placed.ok) return fail(placed.error.message.slice(0, 300));
242 if (placed.value.claimUrl === undefined) return fail("the cloud deploy gave no claim link");
243 const kept = setSecret(app.db, app.config.dataDir, "forge", "", linkName(o.id), placed.value.claimUrl);
244 if (!kept.ok) return fail("the claim link could not be kept");
245 putEntitlement(app.db, {
246 forge: o.name, plan: plan.key, status: "active", provider: checkoutOf(app)?.name ?? "none", payer: o.email,
247 customerId: o.customerId, subscriptionId: o.subscriptionId, source: checkoutOf(app)?.name ?? "paid",
248 }, plan.size, "");
249 if (!move(app.db, o.id, "spawning", "making", Date.now())) move(app.db, o.id, "failed", "making", Date.now());
250 app.bus.append({ kind: "billing.order_making", payload: { id: o.id, forge: o.name, plan: plan.key, url: placed.value.url } });
251 void followMaking(app, o.id);
252 return getOrder(app.db, o.id);
253 }
254
255 /** How long, and how often, this process asks after a `making` order with no page waiting on it. */
256 export const makingWatch = { everyMs: ASK_MS, tries: 60 };
257
258 /**
259 * A buyer who closed the page still gets the link by mail: this process asks after the order
260 * every `makingWatch.everyMs`, for at most `tries`, until it is no longer `making`. Holds nothing
261 * but its own timer (unref'd); a restart drops it, and the return page asks again.
262 */
263 async function followMaking(app: App, id: string): Promise<void> {
264 try {
265 for (let i = 0; i < makingWatch.tries; i++) {
266 await new Promise((r) => setTimeout(r, makingWatch.everyMs).unref());
267 // The ask is the work: it runs as a named job, the sleep before it only waits.
268 const o = getOrder(app.db, id);
269 if (o?.state !== "making") return;
270 await during("order.making", () => askMaking(app, o, Date.now()), undefined, app);
271 }
272 } catch (e) {
273 app.log.warn("a making order could not be asked after", { id, says: String(e).slice(0, 200) });
274 }
275 }
276
277 /**
278 * Ask a `making` order's forge whether it answers on its name (the pinned check, as the order), at
279 * most every `ASK_MS` and one asker at a time, by the row. Once it does the order is `spawned`
280 * and its kept link mailed, when the forge can mail. Never deploys anything: a restart while
281 * making only asks again.
282 */
283 async function askMaking(app: App, o: Order, now: number): Promise<Order | undefined> {
284 if (now - o.updatedAt < ASK_MS || !takeTurn(app.db, o.id, "making", o.updatedAt, now)) return o;
285 const seen = await cloudAnswers(app, o.id, o.name);
286 if (!seen.ok || !seen.value || !move(app.db, o.id, "making", "spawned", Date.now())) return getOrder(app.db, o.id);
287 app.bus.append({ kind: "billing.order_spawned", payload: { id: o.id, forge: o.name, plan: o.plan } });
288 const link = keptLink(app, o.id);
289 if (link !== undefined && (await mailLink(app, o, link))) markResent(app.db, o.id, Date.now());
290 return getOrder(app.db, o.id);
291 }
292
293210 /** An event from the provider says this session was paid: settle its order, if it is one of ours. */
294211 export async function settleSession(app: App, session: { id?: unknown; metadata?: { order?: unknown } | null; customer?: unknown; subscription?: unknown; payment_status?: unknown }): Promise<Order | undefined> {
295212 if (session.payment_status !== "paid" && session.payment_status !== "no_payment_required") return undefined;
@@ -334,19 +251,6 @@ export type Delivered =
334251 | { readonly kind: "claimed" }
335252 | { readonly kind: "failed" };
336253
337 const mailOf = (name: string, link: string) => ({
338 subject: `Your forge ${name} is ready`,
339 text: ["Your forge is ready.", "", "Open this link to take it over. It works once, for a day:", "", link, "", "If you did not buy a forge, ignore this message."].join("\n"),
340 });
341
342 /** Send the link to the order's email when the forge can mail; true when it went. */
343 async function mailLink(app: App, o: Order, link: string): Promise<boolean> {
344 const mailer = mailerOf(app, { id: "order" });
345 if (mailer === undefined || !mayMail(app, o.email)) return false;
346 const m = mailOf(o.name, link);
347 return (await sendCapped(app, mailer, { to: o.email, ...m })) === "sent";
348 }
349
350254 /** A spawned order's claim link, for the buyer who holds its ticket: made fresh, shown once, mailed when mail is on. */
351255 export async function deliverLink(app: App, o: Order): Promise<Delivered> {
352256 if (o.state !== "spawned") return { kind: "failed" };
@@ -354,7 +258,7 @@ export async function deliverLink(app: App, o: Order): Promise<Delivered> {
354258 // A cloud order's link was issued with its machine and kept sealed: shown now, and kept no more.
355259 const kept = keptLink(app, o.id);
356260 if (kept !== undefined) {
357 deleteSecret(app.db, "forge", "", linkName(o.id));
261 dropLink(app, o.id);
358262 return { kind: "link", claimUrl: kept, mailed: o.resentAt !== null };
359263 }
360264 const made = await reissueClaimFor(app, o.name);
src/actions/pinned.ts +26 −13
@@ -31,7 +31,7 @@ import { capped, CeilingRefusal, priced, refusalAt, rowCents } from "../cloud/ce
3131 import { driverOf } from "../cloud/drivers.ts";
3232 import { orderable, provision, read, replace, retire } from "../cloud/machine.ts";
3333 import { dollars } from "../cloud/prices.ts";
34 import { chooseDefault, meets, type Place, type PlanName } from "../cloud/places.ts";
34 import { chooseDefault, meets, type Chosen, type Place, type PlanName } from "../cloud/places.ts";
3535 import { MAX_ID, keptPlaces, pinOf } from "../cloud/places_read.ts";
3636 import { keptRate } from "../cloud/rates.ts";
3737 import { deleteARecord, upsertARecord, type Fetch } from "../cloud/providers.ts";
@@ -44,7 +44,7 @@ import {
4444 } from "../core/pinned.ts";
4545 import { resolveSecrets } from "../core/secret_store.ts";
4646 import { getRepo } from "../core/repos.ts";
47 import { running } from "../kernel/version.ts";
47 import { releaseOf, running } from "../kernel/version.ts";
4848 import { forgeSource } from "../settings/forge_source.ts";
4949 import { DOMAIN_WORDS, getBaseDomain, parseBaseDomain, setBaseDomain } from "../settings/pinned_domain.ts";
5050 import { PAID_PLACEMENT_WORDS, getPaidPlacement, paidPlacementWord, parsePaidPlacement, setPaidPlacement } from "../settings/paid_placement.ts";
@@ -131,10 +131,10 @@ const PLACE_HELP = "Places are listed at Places (GET /api/v1/places); a place is
131131 * one asked for, which must exist, be orderable and be on `provider`; or, when none is asked for,
132132 * the catalog's default for `plan` (small unless named) among that provider's places.
133133 */
134 function pickPlace(app: App, provider: string, asked: string, plan: PlanName = "small"): Result<Place, string> {
134 function pickPlace(app: App, provider: string, asked: string, plan?: PlanName): Result<Place, string> {
135135 const all = keptPlaces(app.db, keptRate(app.db, "EUR"));
136136 if (asked === "") {
137 const c = chooseDefault(all, plan, new Set([provider]), pinOf(app.db, plan));
137 const c = defaultPlace(app, provider, plan ?? "small", all);
138138 if (c.place) return ok(c.place);
139139 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}`);
140140 }
@@ -142,18 +142,24 @@ function pickPlace(app: App, provider: string, asked: string, plan: PlanName = "
142142 if (!place) return err(`There is no place ${asked.slice(0, 80)} in the catalog. ${PLACE_HELP}`);
143143 if (place.provider !== provider) return err(`${place.id} is on ${place.provider}, and this deploy is to ${provider}: name one of ${provider}'s places.`);
144144 if (!place.orderable) return err(`${place.id} cannot be ordered now: ${place.why}. Pick another place, or leave it out for the default.`);
145 // A forge deployed on a plan needs the plan's room; an admin's own deploy names no plan.
146 if (plan !== undefined && !meets(place, plan)) return err(`${place.id} is too small for a ${plan} forge. Pick a bigger place, or leave it out for the default.`);
145147 return ok(place);
146148 }
147149
150 /** The catalog's default place on `provider` for `plan`, and the sentence that says why. */
151 export const defaultPlace = (app: App, provider: string, plan: PlanName, all = keptPlaces(app.db, keptRate(app.db, "EUR"))): Chosen =>
152 chooseDefault(all, plan, new Set([provider]), pinOf(app.db, plan));
153
148154 const MAX_OFFERED = 60;
149155
150156 /**
151 * The places a deploy form offers for `providers`: orderable, meeting the small plan, cheapest
152 * first, at most `MAX_OFFERED`.
157 * The places a deploy form offers for `providers`: orderable, meeting `plan` (small unless named),
158 * cheapest first, at most `MAX_OFFERED`.
153159 */
154 export function deployPlaces(app: App, providers: readonly string[]): Place[] {
160 export function deployPlaces(app: App, providers: readonly string[], plan: PlanName = "small"): Place[] {
155161 return keptPlaces(app.db, keptRate(app.db, "EUR"))
156 .filter((p) => p.orderable && meets(p, "small") && providers.includes(p.provider))
162 .filter((p) => p.orderable && meets(p, plan) && providers.includes(p.provider))
157163 .sort((a, b) => a.costCents - b.costCents || a.id.localeCompare(b.id))
158164 .slice(0, MAX_OFFERED);
159165 }
@@ -346,9 +352,12 @@ export function ownCode(app: App, asked: { source?: string; version?: string }):
346352 source = `${base}/${repo.ownerName}/${repo.name}.git`;
347353 }
348354 if (version === "") {
349 const commit = running().commit;
350 if (commit === null || !/^[0-9a-f]{40}$/.test(commit)) return err("Name a version: this forge does not know the full commit it runs (FORGE_COMMIT).");
351 version = commit;
355 // The commit this process runs, else its release tag.
356 const r = running();
357 const release = releaseOf(r);
358 if (r.commit !== null && /^[0-9a-f]{40}$/.test(r.commit)) version = r.commit;
359 else if (release !== null) version = `v${release}`;
360 else return err("Name a version: this forge does not know the full commit it runs (FORGE_COMMIT).");
352361 }
353362 return ok({ source, version });
354363 }
@@ -785,15 +794,19 @@ export function retireForOrder(app: App, orderId: string, name: string): Promise
785794 * buyer pays (#16205). Reads only what the forge holds (the catalog it last read, the account,
786795 * the ceiling); nothing is asked of a provider, so a catalog never read is refused here too.
787796 */
788 export function deployRoom(app: App, provider: string, account: string, plan: PlanName): string | undefined {
797 export function deployRoom(app: App, provider: string, account: string, plan: PlanName, asked = "", dearer = true): string | undefined {
789798 const t = targetOf(provider);
790799 if (t === undefined || t.status !== "first") return "That is not a target the forge knows.";
791800 const a = getCloudAccount(app.db, provider, account);
792801 if (a === undefined) return "No such cloud account.";
793802 if (!a.writeAllowed) return "That cloud account is read-only; allow writes on it first.";
794803 if (getBaseDomain(app.db) === "") return HOST_NEEDED;
795 const at = pickPlace(app, provider, "", plan);
804 const at = pickPlace(app, provider, asked, plan);
796805 if (!at.ok) return at.error;
806 // A place dearer than the plan's own is not priced into a checkout yet: refused unless `dearer`.
807 const base = dearer || asked === "" ? undefined : pickPlace(app, provider, "", plan);
808 if (base?.ok && at.value.costCents > base.value.costCents)
809 return `${at.value.city} costs ${dollars(at.value.costCents - base.value.costCents)} a month more than this plan's place, and a dearer place cannot be bought yet: pick one at ${dollars(base.value.costCents)} a month or less, or leave it out.`;
797810 return refusalAt(app, provider, account, at.value);
798811 }
799812
src/billing/orders.ts +8 −6
@@ -49,18 +49,20 @@ export interface Order {
4949 readonly updatedAt: number;
5050 readonly shownAt: number | null;
5151 readonly resentAt: number | null;
52 /** The place chosen for a forge on a cloud account; empty for the plan's default. */
53 readonly place: string;
5254 }
5355
5456 interface Row {
5557 id: string; name: string; plan: string; price_usd: number; paid_at: number; email: string; state: OrderState; ticket_hash: string; session_id: string;
5658 customer_id: string; subscription_id: string; reason: string; created_at: number; hold_until: number; updated_at: number;
57 shown_at: number | null; resent_at: number | null;
59 shown_at: number | null; resent_at: number | null; place: string;
5860 }
5961
6062 const fromRow = (r: Row): Order => ({
6163 id: r.id, name: r.name, plan: r.plan, priceUsd: r.price_usd, paidAt: r.paid_at, email: r.email, state: r.state, sessionId: r.session_id, customerId: r.customer_id,
6264 subscriptionId: r.subscription_id, reason: r.reason, createdAt: r.created_at, holdUntil: r.hold_until, updatedAt: r.updated_at,
63 shownAt: r.shown_at, resentAt: r.resent_at,
65 shownAt: r.shown_at, resentAt: r.resent_at, place: r.place,
6466 });
6567
6668 export const newId = (): string => `ord_${crypto.randomUUID().replace(/-/g, "")}`;
@@ -102,13 +104,13 @@ export const pendingCount = (db: Database, now: number): number =>
102104 db.query<{ n: number }, [number]>("SELECT COUNT(*) AS n FROM forge_order WHERE state = 'pending' AND hold_until > ?1").get(now)?.n ?? 0;
103105
104106 /** Write a new pending order. The hold is checked and the row written in one transaction. False when the name is held. */
105 export function holdName(db: Database, o: { id: string; name: string; plan: string; priceUsd: number; email: string; ticket: string; address: string }, now: number): boolean {
107 export function holdName(db: Database, o: { id: string; name: string; plan: string; priceUsd: number; email: string; ticket: string; address: string; place?: string }, now: number): boolean {
106108 return db.transaction(() => {
107109 if (nameHeld(db, o.name, now)) return false;
108110 db.query(
109 `INSERT INTO forge_order (id, name, plan, email, state, ticket_hash, created_at, hold_until, updated_at, address, price_usd)
110 VALUES (?1, ?2, ?3, ?4, 'pending', ?5, ?6, ?7, ?6, ?8, ?9)`,
111 ).run(o.id, o.name, o.plan, o.email, sha256(o.ticket), now, now + HOLD_MS, o.address, o.priceUsd);
111 `INSERT INTO forge_order (id, name, plan, email, state, ticket_hash, created_at, hold_until, updated_at, address, price_usd, place)
112 VALUES (?1, ?2, ?3, ?4, 'pending', ?5, ?6, ?7, ?6, ?8, ?9, ?10)`,
113 ).run(o.id, o.name, o.plan, o.email, sha256(o.ticket), now, now + HOLD_MS, o.address, o.priceUsd, o.place ?? "");
112114 return true;
113115 })();
114116 }
src/core/migration-pins/20261125020000-forge-order-place.pin added +1
@@ -0,0 +1,1 @@
1 0adefef17f36f562d7442e1456924aeba3981a199b360bbb2ecf86af7bb01911
src/core/migrations/20261125020000-forge-order-place.ts added +5
@@ -0,0 +1,5 @@
1 // Orders (#16385): the place a buyer chose for a forge on a cloud account (provider:datacenter:size),
2 // read again when the order is made. Additive; older rows keep the empty place, the default.
3 export default `
4 ALTER TABLE forge_order ADD COLUMN place TEXT NOT NULL DEFAULT '';
5 `;
src/spawn/cloud_placement.ts +15 −34
@@ -13,13 +13,11 @@ import {
1313 checkForOrder,
1414 deployForOrder,
1515 deployRoom,
16 ownCode,
1617 retireForOrder,
1718 } from "../actions/pinned.ts";
1819 import { isPlan, type PlanName } from "../cloud/places.ts";
19 import { validSource } from "../core/pinned.ts";
20 import { publicOrigin } from "../core/public_origin.ts";
2120 import { getRepo } from "../core/repos.ts";
22 import { releaseOf, running } from "../kernel/version.ts";
2321 import { err, ok, type Result } from "../kernel/result.ts";
2422 import { forgeSource } from "../settings/forge_source.ts";
2523 import type { Placement, PlacementRefusal } from "./placement.ts";
@@ -34,39 +32,17 @@ export const catalogPlan = (size: string): PlanName =>
3432 isPlan(size) ? size : "small";
3533
3634 /**
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.
35 * What a deployed copy of this forge runs: what an admin's deploy runs when it names none
36 * (`ownCode`, one rule and one wording), and the repository it comes from as the app.
4037 */
4138 export function ownSource(
4239 app: App,
4340 ): 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 });
41 const code = ownCode(app, {});
42 if (!code.ok) return code;
43 const [owner = "", name = ""] = (forgeSource(app.db, app.config.forgeRepo) ?? "").split("/");
44 const repo = getRepo(app.db, owner, name);
45 return repo === undefined ? err("This forge names no repository of its own code.") : ok({ app: `${repo.ownerName}/${repo.name}`, ...code.value });
7046 }
7147
7248 const refused = (message: string): PlacementRefusal => ({
@@ -77,13 +53,17 @@ const refused = (message: string): PlacementRefusal => ({
7753 export function cloudPlacement(
7854 app: App,
7955 at: { readonly provider: string; readonly account: string },
80 o: { readonly orderId: string; readonly plan: PlanName },
56 /**
57 * `place`: a Places id, or empty for the plan's default. `dearer`: a place dearer than that
58 * default may be asked for (an admin's); otherwise it is refused, as a checkout cannot price it.
59 */
60 o: { readonly orderId: string; readonly plan: PlanName; readonly place?: string; readonly dearer?: boolean },
8161 ): Placement {
8262 return {
8363 room() {
8464 const own = ownSource(app);
8565 if (!own.ok) return refused(own.error);
86 const no = deployRoom(app, at.provider, at.account, o.plan);
66 const no = deployRoom(app, at.provider, at.account, o.plan, o.place ?? "", o.dearer === true);
8767 return no === undefined ? undefined : { reason: "quota", message: no };
8868 },
8969 async place(plan) {
@@ -96,6 +76,7 @@ export function cloudPlacement(
9676 account: at.account,
9777 ...own.value,
9878 plan: o.plan,
79 place: o.place,
9980 });
10081 if (!made.ok) return err(refused(made.error));
10182 return ok({
src/spawn/door.ts +124 −1
@@ -60,6 +60,13 @@ import { FREE, getPlan, getPlans, PAID_PLAN_ADMIN_ONLY } from "../settings/plans
6060 import { giftOf, REDEEM_WORDS, settleGift, unclaimGift } from "../actions/codes.ts";
6161 import { parseTemplate, TEMPLATES } from "./templates.ts";
6262 import { claimCode, CODE_WORDS, type Code } from "../billing/codes.ts";
63 import { MAX_ID } from "../cloud/places_read.ts";
64 import { getPinned } from "../core/pinned.ts";
65 import { getUserByName } from "../core/users.ts";
66 import { parsePaidPlacement } from "../settings/paid_placement.ts";
67 import type { Plan } from "../settings/plans.ts";
68 import { catalogPlan, cloudPlacement } from "./cloud_placement.ts";
69 import { givenOrder, makeOnCloud, placeChoice, whereFor, type Where } from "./making.ts";
6370
6471 export interface Door {
6572 readonly status: number;
@@ -252,7 +259,12 @@ export async function spawnDoor(
252259 * so it does not wait on the first reach proof: the page shows the forge starting
253260 * (`web/forge_made.ts`) and the proof goes on behind it, an alarm if it never comes.
254261 */
255 opts: { readonly paid?: boolean; readonly page?: boolean } = {},
262 opts: {
263 readonly paid?: boolean;
264 readonly page?: boolean;
265 /** The paid order this forge is made for, `spawning`: a cloud forge is deployed as it. */
266 readonly order?: { readonly id: string };
267 } = {},
256268 ): Promise<Door> {
257269 // The forge's own release prober (`release/prober.ts`) is no stranger: its walk spends no
258270 // stranger's allowance.
@@ -386,6 +398,7 @@ export async function spawnDoor(
386398 const source: SpawnSource = { catalog, briefs, subscriptions: [] };
387399 // A plan (`settings/plans.ts`) gives the child its size; read now, so an edit governs this spawn.
388400 let planKey: string | undefined;
401 let planOf: Plan | undefined;
389402 let size = raw["size"];
390403 // A gift code (`actions/codes.ts`) names the plan itself: no admin, no payment, whatever the
391404 // provider.
@@ -409,6 +422,7 @@ export async function spawnDoor(
409422 if (size !== undefined && size !== null && size !== "" && size !== chosen.size)
410423 return invalid("size", `the ${chosen.name} plan is a ${chosen.size} forge; leave size out or send ${chosen.size}`);
411424 planKey = chosen.key;
425 planOf = chosen;
412426 size = chosen.size;
413427 }
414428 // The same word the name field asks about, so a name it calls free is one the door takes.
@@ -422,6 +436,25 @@ export async function spawnDoor(
422436 }
423437 const unknown = unknownTemplate(raw["template"]);
424438 if (unknown !== undefined) return unknown;
439 // Where it runs: the one rule (`spawn/making.ts`), and the place asked for checked now, against
440 // the catalog this forge holds, before anything is paid or made.
441 const named = accountNamed(ctx.app, user, raw);
442 if (named !== undefined && "status" in named) return named;
443 const where = whereFor(ctx.app, planOf, named);
444 const placeIn = raw["place"] ?? "";
445 if (typeof placeIn !== "string" || placeIn.length > MAX_ID) return invalid("place", "must be a place id, provider:datacenter:size (GET /api/v1/places)");
446 const asked = placeIn.trim();
447 if (asked !== "" && where.where === "hosted") return invalid("place", "a forge on this plan runs inside this forge; a place is for a paid plan on a cloud account");
448 const cloud = { plan: catalogPlan(typeof size === "string" ? size : "small"), place: asked, dearer: user?.isAdmin === true };
449 if (where.where === "cloud") {
450 const room = (at: string) => cloudPlacement(ctx.app, where, { orderId: "", ...cloud, place: at }).room?.();
451 const full = room(asked);
452 // A deploy that cannot be made anywhere is refused as such; one only the place stops is the place's.
453 const anywhere = full === undefined || asked === "" ? full : room("");
454 if (anywhere !== undefined) return spawnWords({ kind: "refused", reason: anywhere.reason, message: anywhere.message });
455 if (full !== undefined) return invalid("place", full.message);
456 if (dry && opts.order === undefined && typeof raw["name"] === "string" && (await nameTaken(ctx.app, raw["name"]))) return invalid("name", "That name is taken");
457 }
425458 const input = {
426459 name: raw["name"],
427460 org: raw["name"],
@@ -462,6 +495,7 @@ export async function spawnDoor(
462495 ...dryRun(planned.value, source),
463496 ...(budgetWaits === undefined ? {} : { budgetNote: `the $${budgetWaits} budget applies when a model key is given with it; none is, so this forge gets no key` }),
464497 ...(planned.value.budgetUsd === null ? {} : { keyNote: KEY_BUDGET_NOTE }),
498 ...(where.where === "cloud" ? { runsOn: runsOn(ctx.app, where, planOf, cloud) } : {}),
465499 },
466500 };
467501 }
@@ -479,6 +513,11 @@ export async function spawnDoor(
479513 },
480514 };
481515 }
516 if (where.where === "cloud") {
517 const door = await cloudDoor(ctx, user, { where, ...cloud, input, source, gift: hasGift ? giftIn : undefined, order: opts.order });
518 if (door.status >= 400) slot?.release();
519 return door;
520 }
482521 // One rule for births (`spawn/births.ts`): the machine's own figures decide how many are made at
483522 // once, and a spawn that does not fit waits its turn, then is told its place and how long.
484523 const place = await takePlace(ctx.app, { anon }).catch((error: unknown) => {
@@ -590,6 +629,90 @@ export async function spawnDoor(
590629 };
591630 }
592631
632 /** A name a person, a child or a pinned forge holds. */
633 export async function nameTaken(app: App, name: string): Promise<boolean> {
634 return getUserByName(app.db, name) !== undefined || getPinned(app.db, name) !== undefined || (await forgeNameVerdict(app, name)).verdict === "taken";
635 }
636
637 /** The cloud account an admin named with `target` and `account`, none, or the refusal. */
638 function accountNamed(app: App, user: User | undefined, raw: Record<string, unknown>): { provider: string; account: string } | Door | undefined {
639 const t = raw["target"];
640 const a = raw["account"];
641 if ((t === undefined || t === null || t === "") && (a === undefined || a === null || a === "")) return undefined;
642 if (user?.isAdmin !== true) return invalid("target", "only a site admin names the cloud account a forge runs on");
643 const at = typeof t === "string" && typeof a === "string" ? parsePaidPlacement(app.db, `${t}/${a}`) : undefined;
644 if (at === undefined || !at.ok || at.value === "hosted") return invalid("account", "name a cloud account a pinned forge can be deployed to, with writes allowed, as target and account");
645 return { provider: t as string, account: a as string };
646 }
647
648 /** Where a cloud forge will run, for the plan: the account, the place, and why that place. */
649 function runsOn(app: App, at: Where & { where: "cloud" }, plan: Plan | undefined, c: { place: string; dearer: boolean }): Record<string, string> {
650 const choice = placeChoice(app, plan, c.dearer);
651 return { account: `${at.provider}/${at.account}`, place: c.place || (choice?.defaultId ?? ""), says: c.place === "" ? (choice?.says ?? "") : "The place you chose." };
652 }
653
654 /**
655 * A forge on a cloud machine (`spawn/making.ts`): the plan's rules as a hosted forge's, then an
656 * order (the paid one, or one written now for an admin's or a gift code's forge) deployed by the
657 * cloud placement and `making` until it answers. The answer names the page its claim link
658 * appears on, and, for an order written now, the ticket that opens that page.
659 */
660 async function cloudDoor(
661 ctx: Ctx,
662 user: User | undefined,
663 c: {
664 where: Where & { where: "cloud" };
665 plan: ReturnType<typeof catalogPlan>;
666 place: string;
667 dearer: boolean;
668 input: Parameters<typeof planSpawn>[0];
669 source: SpawnSource;
670 gift: unknown;
671 order: { readonly id: string } | undefined;
672 },
673 ): Promise<Door> {
674 const planned = planSpawn(c.input, c.source);
675 if (!planned.ok) return spawnWords({ kind: "invalid", ...planned.error });
676 const clash = founderClash(planned.value, user);
677 if (clash !== undefined) return spawnWords({ kind: "invalid", ...clash });
678 const name = planned.value.name;
679 if (c.order === undefined && (await nameTaken(ctx.app, name))) return invalid("name", "That name is taken");
680 let gift: Code | undefined;
681 if (c.gift !== undefined) {
682 const claimed = claimCode(ctx.app.db, c.gift);
683 if (!claimed.ok) return invalid("code", CODE_WORDS[claimed.error]);
684 gift = claimed.value;
685 }
686 let settled = false;
687 try {
688 const given = c.order === undefined ? givenOrder(ctx.app, { name, plan: planned.value.plan ?? FREE, email: user?.email ?? "", place: c.place }) : undefined;
689 const id = c.order?.id ?? given?.id;
690 if (id === undefined) return invalid("name", "That name is held for someone else; try another");
691 const made = await makeOnCloud(ctx.app, id, c.where, { plan: c.plan, place: c.place, dearer: c.dearer }, planned.value);
692 if (!made.ok) return spawnWords({ kind: "failed", message: made.error });
693 if (gift !== undefined) {
694 settleGift(ctx.app, gift, name);
695 settled = true;
696 }
697 const done = `/pricing/done?order=${id}`;
698 return {
699 status: 202,
700 body: {
701 dryRun: false,
702 making: true,
703 name,
704 url: made.value.url,
705 order: id,
706 done,
707 ...(given === undefined ? {} : { ticket: given.ticket }),
708 says: `${name} is starting on its own machine, which takes a few minutes. Its claim link appears at ${done} once it answers, and is mailed when this forge can mail.`,
709 },
710 };
711 } finally {
712 if (gift !== undefined && !settled) unclaimGift(ctx.app, gift);
713 }
714 }
715
593716 /**
594717 * What a spawn says of the new forge: ready, still starting (never "not reachable"), or what is
595718 * wrong.
src/spawn/making.ts added +281
@@ -0,0 +1,281 @@
1 /**
2 * Where a forge is made, and making one on a cloud machine (#16205, #16385). `whereFor` is the one
3 * rule every way of making a forge asks, through `spawnDoor`: an admin's named account, else a
4 * paid plan (bought, given by an admin or by a gift code) on the account "paid forges run on"
5 * names (`settings/paid_placement.ts`), else hosted inside this forge.
6 *
7 * A forge on a cloud machine is always an order (`billing/orders.ts`), whoever it is for: a bought
8 * one arrives `spawning`, one nobody pays for here is written `spawning` by `givenOrder`. The
9 * cloud placement deploys it as the order (`deployForOrder`, which never makes a second machine
10 * for one order), its claim link is kept sealed, and the order is `making` until the forge answers
11 * on its name; then `/pricing/done` shows the link once, and it is mailed when the forge can mail.
12 */
13
14 import type { App } from "../app.ts";
15 import { mayMail, sendCapped } from "../actions/mail.ts";
16 import { defaultPlace, deployPlaces } from "../actions/pinned.ts";
17 import { mailerOf } from "../actions/verify.ts";
18 import {
19 getOrder,
20 holdName,
21 markResent,
22 move,
23 newId,
24 newTicket,
25 takeTurn,
26 type Order,
27 } from "../billing/orders.ts";
28 import type { Place, PlanName } from "../cloud/places.ts";
29 import { deleteSecret, resolveSecrets, setSecret } from "../core/secret_store.ts";
30 import { err, ok, type Result } from "../kernel/result.ts";
31 import { during } from "../perf/jobs.ts";
32 import { getPaidPlacement } from "../settings/paid_placement.ts";
33 import { FREE, type Plan } from "../settings/plans.ts";
34 import {
35 catalogPlan,
36 cloudAnswers,
37 cloudPlacement,
38 } from "./cloud_placement.ts";
39 import type { SpawnPlan } from "./plan.ts";
40
41 export type Where =
42 | { readonly where: "hosted" }
43 | {
44 readonly where: "cloud";
45 readonly provider: string;
46 readonly account: string;
47 };
48
49 /**
50 * The one rule: an account an admin named; else, for a paid plan, the account paid forges run on
51 * when one is set; else hosted. Who may name an account or hold a paid plan is the door's check.
52 */
53 export function whereFor(
54 app: App,
55 plan: Plan | undefined,
56 named?: { readonly provider: string; readonly account: string },
57 ): Where {
58 if (named !== undefined) return { where: "cloud", ...named };
59 if (plan === undefined || plan.key === FREE) return { where: "hosted" };
60 return getPaidPlacement(app.db);
61 }
62
63 /** What a "Choose where it runs" list offers: the default and why, and every orderable place. */
64 export interface PlaceChoice {
65 readonly says: string;
66 readonly defaultId: string;
67 readonly defaultCents: number;
68 readonly places: readonly Place[];
69 /** A place dearer than the default may be chosen (an admin's); otherwise it is shown, not offered. */
70 readonly dearer: boolean;
71 }
72
73 /** The list for a forge on `plan`, or none when it runs hosted (a free plan, or paid forges hosted). */
74 export function placeChoice(
75 app: App,
76 plan: Plan | undefined,
77 dearer: boolean,
78 ): PlaceChoice | undefined {
79 const at = whereFor(app, plan);
80 if (at.where === "hosted" || plan === undefined) return undefined;
81 const size: PlanName = catalogPlan(plan.size);
82 const chosen = defaultPlace(app, at.provider, size);
83 return {
84 says: chosen.reason,
85 defaultId: chosen.place?.id ?? "",
86 defaultCents: chosen.place?.costCents ?? 0,
87 places: deployPlaces(app, [at.provider], size),
88 dearer,
89 };
90 }
91
92 /** A `making` order's forge is asked whether it answers at most this often, however many pages wait. */
93 const ASK_MS = 15_000;
94
95 /** How long, and how often, this process asks after a `making` order with no page waiting on it. */
96 export const makingWatch = { everyMs: ASK_MS, tries: 60 };
97
98 /** The sealed claim link of a cloud order, by order id: a forge secret, read with an audit line. */
99 const linkName = (id: string): string => `ORDER_CLAIM_${id.toUpperCase()}`;
100 export const keptLink = (app: App, id: string): string | undefined =>
101 resolveSecrets(app.db, app.config.dataDir, app.bus, [linkName(id)], {
102 run: `order:${id}`,
103 })[linkName(id)];
104 export const dropLink = (app: App, id: string): void => {
105 deleteSecret(app.db, "forge", "", linkName(id));
106 };
107
108 const mailOf = (name: string, link: string) => ({
109 subject: `Your forge ${name} is ready`,
110 text: [
111 "Your forge is ready.",
112 "",
113 "Open this link to take it over. It works once, for a day:",
114 "",
115 link,
116 "",
117 "If you did not buy a forge, ignore this message.",
118 ].join("\n"),
119 });
120
121 /** Send the link to the order's email when the forge can mail; true when it went. */
122 export async function mailLink(
123 app: App,
124 o: Order,
125 link: string,
126 ): Promise<boolean> {
127 const mailer = mailerOf(app, { id: "order" });
128 if (mailer === undefined || o.email === "" || !mayMail(app, o.email))
129 return false;
130 return (
131 (await sendCapped(app, mailer, {
132 to: o.email,
133 ...mailOf(o.name, link),
134 })) === "sent"
135 );
136 }
137
138 /**
139 * Move a `spawning` order to `failed`, saying why: the event and the log line only for the move
140 * that took effect, so a refusal said twice is recorded once.
141 */
142 export function failOrder(app: App, id: string, reason: string): Order {
143 if (move(app.db, id, "spawning", "failed", Date.now(), { reason })) {
144 const o = getOrder(app.db, id) as Order;
145 app.bus.append({
146 kind: "billing.order_failed",
147 payload: { id, forge: o.name, plan: o.plan, reason },
148 });
149 app.log.error("an order could not be made into a forge", {
150 id,
151 forge: o.name,
152 reason,
153 });
154 }
155 return getOrder(app.db, id) as Order;
156 }
157
158 /**
159 * The order of a cloud forge nobody pays for here (an admin's paid plan, a gift code's), written
160 * `spawning`: the name is held, and the making page and claim link are an order's. None when the
161 * name is held already.
162 */
163 export function givenOrder(
164 app: App,
165 o: { name: string; plan: string; email: string; place: string },
166 ): { id: string; ticket: string } | undefined {
167 const id = newId();
168 const ticket = newTicket();
169 const now = Date.now();
170 if (!holdName(app.db, { id, ...o, priceUsd: 0, ticket, address: "" }, now))
171 return undefined;
172 move(app.db, id, "pending", "spawning", now);
173 return { id, ticket };
174 }
175
176 /**
177 * Deploy the `spawning` order's forge on `at`, as the order: its link kept sealed and the order
178 * `making`. A refusal fails the order, saying why, and nothing hosted is made instead.
179 */
180 export async function makeOnCloud(
181 app: App,
182 orderId: string,
183 at: { readonly provider: string; readonly account: string },
184 o: {
185 readonly plan: PlanName;
186 readonly place: string;
187 readonly dearer: boolean;
188 },
189 plan: SpawnPlan,
190 ): Promise<Result<{ url: string }, string>> {
191 const fail = (reason: string) =>
192 err(failOrder(app, orderId, reason.slice(0, 300)).reason || reason);
193 const placed = await cloudPlacement(app, at, { orderId, ...o }).place(plan);
194 if (!placed.ok) return fail(placed.error.message);
195 if (placed.value.claimUrl === undefined)
196 return fail("the cloud deploy gave no claim link");
197 if (
198 !setSecret(
199 app.db,
200 app.config.dataDir,
201 "forge",
202 "",
203 linkName(orderId),
204 placed.value.claimUrl,
205 ).ok
206 )
207 return fail("the claim link could not be kept");
208 if (!move(app.db, orderId, "spawning", "making", Date.now()))
209 move(app.db, orderId, "failed", "making", Date.now());
210 app.bus.append({
211 kind: "billing.order_making",
212 payload: {
213 id: orderId,
214 forge: plan.name,
215 plan: plan.plan ?? FREE,
216 url: placed.value.url,
217 },
218 });
219 void followMaking(app, orderId);
220 return ok({ url: placed.value.url });
221 }
222
223 /**
224 * A buyer who closed the page still gets the link by mail: this process asks after the order
225 * every `makingWatch.everyMs`, for at most `tries`, until it is no longer `making`. Holds nothing
226 * but its own timer (unref'd); a restart drops it, and the return page asks again.
227 */
228 async function followMaking(app: App, id: string): Promise<void> {
229 try {
230 for (let i = 0; i < makingWatch.tries; i++) {
231 await new Promise((r) => setTimeout(r, makingWatch.everyMs).unref());
232 // The ask is the work: it runs as a named job, the sleep before it only waits.
233 const o = getOrder(app.db, id);
234 if (o?.state !== "making") return;
235 await during(
236 "order.making",
237 () => askMaking(app, o, Date.now()),
238 undefined,
239 app,
240 );
241 }
242 } catch (e) {
243 app.log.warn("a making order could not be asked after", {
244 id,
245 says: String(e).slice(0, 200),
246 });
247 }
248 }
249
250 /**
251 * Ask a `making` order's forge whether it answers on its name (the pinned check, as the order), at
252 * most every `ASK_MS` and one asker at a time, by the row. Once it does the order is `spawned`
253 * and its kept link mailed, when the forge can mail. Never deploys anything: a restart while
254 * making only asks again.
255 */
256 export async function askMaking(
257 app: App,
258 o: Order,
259 now: number,
260 ): Promise<Order | undefined> {
261 if (
262 now - o.updatedAt < ASK_MS ||
263 !takeTurn(app.db, o.id, "making", o.updatedAt, now)
264 )
265 return o;
266 const seen = await cloudAnswers(app, o.id, o.name);
267 if (
268 !seen.ok ||
269 !seen.value ||
270 !move(app.db, o.id, "making", "spawned", Date.now())
271 )
272 return getOrder(app.db, o.id);
273 app.bus.append({
274 kind: "billing.order_spawned",
275 payload: { id: o.id, forge: o.name, plan: o.plan },
276 });
277 const link = keptLink(app, o.id);
278 if (link !== undefined && (await mailLink(app, o, link)))
279 markResent(app.db, o.id, Date.now());
280 return getOrder(app.db, o.id);
281 }
src/tui/screens/newforge.ts +28 −3
@@ -17,6 +17,8 @@ import { isFollowMode } from "../../spawn/chain.ts";
1717 import { starterBudgetField } from "../../settings/starter_budget.ts";
1818 import { MAX_BUDGET_USD, MIN_BUDGET_USD } from "../../spawn/plan.ts";
1919 import { listRecipes, saveRecipe } from "../../spawn/recipes.ts";
20 import { placeChoice } from "../../spawn/making.ts";
21 import { FREE, getPlan, getPlans } from "../../settings/plans.ts";
2022 import type { Ctx, Screen } from "../app/app.ts";
2123 import { binding } from "../app/keys.ts";
2224 import { style } from "../term/style.ts";
@@ -56,6 +58,10 @@ const SPECS: readonly Spec[] = [
5658 { key: "saveAs", label: "Save as recipe", hint: "A name to keep the apps and budget under, saved with the plan. Optional." },
5759 ];
5860
61 /** An admin's: a paid plan runs where paid forges run, at the place chosen (`spawn/making.ts`). */
62 const PLAN_SPEC: Spec = { key: "plan", label: "Plan", hint: "Free (default) or a paid plan, which runs where paid forges run. Left and right choose.", choices: [""] };
63 const PLACE_SPEC: Spec = { key: "place", label: "Where it runs", hint: "", choices: [""] };
64
5965 const RECIPE_SPEC: Spec = { key: "recipe", label: "Spawn from recipe", hint: "Left and right choose one of yours; its apps and budget replace the fields above.", choices: [""] };
6066
6167 /** The chosen template's own sentence; a typed id that is no template keeps the general hint. */
@@ -82,7 +88,16 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
8288 const specs = [
8389 ...SPECS.map((s) => (s.key === "template" ? { ...s, choices: [...TEMPLATE_CHOICES, ...repoTemplates] } : s)),
8490 ...(recipes.length === 0 ? [] : [{ ...RECIPE_SPEC, choices: ["", ...recipes] }]),
91 ...(f.user?.isAdmin === true && getPlans(f.app.db).some((p) => p.key !== FREE)
92 ? [{ ...PLAN_SPEC, choices: ["", ...getPlans(f.app.db).filter((p) => p.key !== FREE).map((p) => p.key)] }, PLACE_SPEC]
93 : []),
8594 ];
95 /** Where a paid plan's forge may run: the default first, then the catalog's places for its size. */
96 const where = () => placeChoice(f.app, getPlan(f.app.db, values["plan"] ?? ""), true);
97 const choicesOf = (spec: Spec): readonly string[] | undefined =>
98 spec.key === "place" ? ["", ...(where()?.places.map((p) => p.id) ?? [])] : spec.choices;
99 const hintOf = (spec: Spec): string =>
100 spec.key === "template" ? templateHint(values["template"] || DEFAULT_TEMPLATE) : spec.key === "place" ? (where()?.says ?? "A free forge runs inside this forge.") : spec.hint;
86101 const starter = starterBudgetField(f.app.db);
87102 const values: Record<string, string> = { budgetUsd: starter, ...initial };
88103 // The prefilled budget is replaced by the first thing typed, never appended to ('20' is not
@@ -127,6 +142,8 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
127142 ...(val("size") === "" || val("size") === DEFAULT_SIZE ? {} : { size: val("size") }),
128143 // Blank is the default: it is not recorded, as on the page.
129144 ...(val("template") === "" || val("template") === DEFAULT_TEMPLATE ? {} : { template: val("template") }),
145 ...(val("plan") === "" ? {} : { plan: val("plan") }),
146 ...(val("place") === "" ? {} : { place: val("place") }),
130147 dryRun,
131148 };
132149 };
@@ -190,6 +207,7 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
190207 const size = (body["plan"] as { size?: string } | undefined)?.size;
191208 const template = (body["plan"] as { template?: string } | undefined)?.template;
192209 const says = (body["preview"] as { says?: string } | undefined)?.says;
210 const runsOn = body["runsOn"] as { account: string; place: string; says: string } | undefined;
193211 const mode = val("followMode") === "" ? "take-updates" : val("followMode");
194212 plan = [
195213 `A forge at ${childUrlOf(f.app, val("name"))}.`,
@@ -200,6 +218,7 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
200218 "Copied into it:",
201219 ...copied.map((c) => ` ${c}`),
202220 ...(size === undefined ? [] : [`Size: ${size}.`]),
221 ...(runsOn === undefined ? [] : [`Runs on ${runsOn.account} at ${runsOn.place}. ${runsOn.says}`]),
203222 ...(template === undefined ? [] : [`Template: ${templateOf(template).title}.`]),
204223 `About ${Math.max(1, Math.round(bytes / 1024))} KB. Nothing is made until you press enter.`,
205224 ...(typeof body["keyNote"] === "string" ? [body["keyNote"]] : []),
@@ -207,6 +226,11 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
207226 return;
208227 }
209228 values["modelKey"] = "";
229 if (body["making"] === true) {
230 ctx.toast(String(body["says"]), "success");
231 ctx.pop();
232 return;
233 }
210234 const link = body["claimUrl"];
211235 const name = String(body["name"] ?? val("name"));
212236 if (typeof link === "string") {
@@ -253,7 +277,8 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
253277 let cursor: { x: number; y: number } | null = null;
254278 specs.slice(first, first + rows).forEach((spec, n) => {
255279 const i = first + n;
256 const raw = spec.choices === undefined ? (values[spec.key] ?? "") : (values[spec.key] || spec.choices[0]!);
280 const choices = choicesOf(spec);
281 const raw = choices === undefined ? (values[spec.key] ?? "") : (values[spec.key] || choices[0]!);
257282 const shown = spec.secret === true ? "•".repeat([...raw].length) : raw;
258283 const at = field(s, { x: area.x, y: area.y + n * 3, w: Math.min(70, area.w), h: 3 }, c, {
259284 label: spec.label,
@@ -262,7 +287,7 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
262287 ...(focus === i ? { cursor: [...shown].length } : {}),
263288 ...(error !== undefined && (errorKey === spec.key || (errorKey === undefined && focus === i))
264289 ? { error }
265 : { hint: spec.key === "template" ? templateHint(values["template"] || DEFAULT_TEMPLATE) : spec.hint }),
290 : { hint: hintOf(spec) }),
266291 });
267292 if (focus === i) cursor = at;
268293 });
@@ -288,7 +313,7 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
288313 focus = (focus + 1) % specs.length;
289314 return true;
290315 }
291 const choices = specs[focus]!.choices;
316 const choices = choicesOf(specs[focus]!);
292317 const step = e.key === "left" ? -1 : e.key === "right" || e.key === " " || e.key === "space" ? 1 : 0;
293318 if (choices !== undefined && step !== 0) {
294319 // A choice can be cycled or typed; both end in a value the door checks.
src/web/pages/new-forge.ts +46 −3
@@ -45,7 +45,11 @@ import { headWords, templateHeads } from "../../spawn/template_head.ts";
4545 import { html, type Html } from "../html.ts";
4646 import { timeAgo } from "../time_element.ts";
4747 import { noteForgeMade } from "../funnel_door.ts";
48 import { page } from "../layout.ts";
48 import { page, redirect } from "../layout.ts";
49 import { placeChoiceView } from "../pinned.ts";
50 import { orderCookie } from "./pricing.ts";
51 import { placeChoice } from "../../spawn/making.ts";
52 import { FREE, getPlan, getPlans } from "../../settings/plans.ts";
4953 import { linkToSend, madeBody, madeJs } from "../forge_made.ts";
5054 import { pickList } from "../pick.ts";
5155 import { btn, field as formField, selectField } from "../ui.ts";
@@ -70,6 +74,11 @@ interface Values {
7074 readonly template: string;
7175 /** A gift code (`actions/codes.ts`): it names the plan, so no checkout and no card. */
7276 readonly code: string;
77 /** An admin's plan (empty: free), and the plan a gift code gives, for where it runs. */
78 readonly plan: string;
79 readonly giftPlan: string;
80 /** A Places id (`spawn/making.ts`); empty for the plan's default. */
81 readonly place: string;
7382 /** The last post carried a key: it is never sent back, so it is asked for again. */
7483 readonly hadKey: boolean;
7584 }
@@ -91,6 +100,9 @@ const EMPTY: Values = {
91100 size: DEFAULT_SIZE,
92101 template: DEFAULT_TEMPLATE,
93102 code: "",
103 plan: "",
104 giftPlan: "",
105 place: "",
94106 hadKey: false,
95107 };
96108
@@ -428,6 +440,8 @@ function formView(
428440 </p>
429441 </details>
430442 ${codeField(values.code, errors["code"])}
443 ${planField(ctx, user, values.plan, errors["plan"])}
444 ${placeChoiceView(placeChoice(ctx.app, getPlan(ctx.app.db, values.plan || values.giftPlan), user?.isAdmin === true), values.place, errors["place"])}
431445 ${anon
432446 ? null
433447 : html`<details class="field"${values.saveAs !== "" || errors["recipe"] ? html` open` : null}>
@@ -542,6 +556,9 @@ function planView(ctx: Ctx, user: User | undefined, values: Values, body: Record
542556 <ul class="mb">
543557 <li>A forge at <b>${address}</b>.</li>
544558 ${giftLine(body["gift"])}
559 ${typeof (body["runsOn"] as { account?: unknown } | undefined)?.account === "string"
560 ? html`<li data-runs-on>It runs on its own machine, on ${(body["runsOn"] as { account: string }).account}, at ${(body["runsOn"] as { place: string }).place}. Its link appears once it answers.</li>`
561 : null}
545562 ${user === undefined
546563 ? null
547564 : html`<li>
@@ -670,11 +687,12 @@ export async function newForgePage(ctx: Ctx): Promise<Response> {
670687 const seen = code === "" ? undefined : giftOf(ctx.app, ctx.request, code);
671688 const errors: Errors = seen !== undefined && !seen.ok ? { code: `${REDEEM_WORDS[seen.error]}.` } : {};
672689 const gift = seen?.ok ? html`<p class="small" id="gift" role="status"><b>${giftWords(seen.value)}</b></p>` : null;
690 const plan = user?.isAdmin === true ? (ctx.url.searchParams.get("plan") ?? "").slice(0, 40) : "";
673691 const response = page({
674692 ctx,
675693 title: "New forge",
676694 keyboardResizes: true,
677 body: formView(ctx, user, { ...EMPTY, code, name: (ctx.url.searchParams.get("name") ?? "").slice(0, 38), template: askedTemplate(ctx), budgetUsd: starterBudgetField(ctx.app.db), ...fromPack(ctx, user) }, errors, gift, reads),
695 body: formView(ctx, user, { ...EMPTY, code, plan, giftPlan: seen?.ok ? seen.value.plan : "", name: (ctx.url.searchParams.get("name") ?? "").slice(0, 38), template: askedTemplate(ctx), budgetUsd: starterBudgetField(ctx.app.db), ...fromPack(ctx, user) }, errors, gift, reads),
678696 });
679697 notePhase(ctx.request, "render", performance.now() - rendering);
680698 return response;
@@ -706,6 +724,9 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
706724 size: field(form, "size").trim() || DEFAULT_SIZE,
707725 template: field(form, "template").trim() || DEFAULT_TEMPLATE,
708726 code: field(form, "code").trim().slice(0, 64),
727 plan: field(form, "plan").trim().slice(0, 40),
728 giftPlan: "",
729 place: field(form, "place").trim().slice(0, 200),
709730 hadKey: field(form, "modelKey").trim() !== "",
710731 };
711732 const key = field(form, "modelKey").trim();
@@ -747,6 +768,8 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
747768 ...(values.size === DEFAULT_SIZE ? {} : { size: values.size }),
748769 ...(values.template === DEFAULT_TEMPLATE ? {} : { template: values.template }),
749770 ...(values.code === "" ? {} : { code: values.code }),
771 ...(values.plan === "" ? {} : { plan: values.plan }),
772 ...(values.place === "" ? {} : { place: values.place }),
750773 dryRun: planOnly,
751774 }, { page: true });
752775 if (door.status === 404 && door.body["error"] === "unknown_template")
@@ -776,13 +799,20 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
776799 body: formView(
777800 ctx,
778801 user,
779 values,
802 { ...values, giftPlan: String((door.body["gift"] as { plan?: unknown } | undefined)?.plan ?? "") },
780803 {},
781804 html`${saved === undefined ? null : html`<p class="small" role="status" id="saved">Saved as <b>${saved}</b>.</p>`}${planView(ctx, user, values, door.body)}`,
782805 await readsFor(ctx, user),
783806 ),
784807 });
785808 noteForgeMade(ctx);
809 // On a cloud machine: the order's making page, which shows the claim link once it answers.
810 if (door.body["making"] === true && typeof door.body["ticket"] === "string") {
811 const res = redirect(String(door.body["done"]), { cookie: orderCookie(ctx, String(door.body["order"]), door.body["ticket"]) });
812 res.headers.set("cache-control", "no-store");
813 if (values.code !== "") res.headers.append("set-cookie", dropGift(ctx.url, ctx.app.config.url));
814 return res;
815 }
786816 const link = door.body["claimUrl"];
787817 const note = door.body["keyNote"];
788818 const name = String(door.body["name"] ?? values.name);
@@ -805,6 +835,19 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
805835 return response;
806836 }
807837
838 /** An admin's plan for the new forge: a paid one runs where paid forges run. Only with paid plans. */
839 function planField(ctx: Ctx, user: User | undefined, chosen: string, error: string | undefined): Html | null {
840 const plans = getPlans(ctx.app.db);
841 if (user?.isAdmin !== true || plans.every((p) => p.key === FREE)) return null;
842 return selectField({
843 label: "Plan",
844 name: "plan",
845 hint: "A paid plan runs where paid forges run; See the plan shows where.",
846 options: plans.map((p) => ({ value: p.key === FREE ? "" : p.key, label: p.name, selected: (p.key === FREE ? "" : p.key) === chosen })),
847 ...(error ? { error } : {}),
848 });
849 }
850
808851 /**
809852 * The code is asked for only when one is in play: filled in from a link, or behind a quiet
810853 * disclosure that needs no script.
src/web/pages/pricing.ts +19 −9
@@ -32,6 +32,8 @@ import { offerData, sharedProperties } from "../offer.ts";
3232 import { safeJson } from "../structured_data.ts";
3333 import { btn, field as formField } from "../ui.ts";
3434 import { claimLinkBody } from "./new-forge.ts";
35 import { placeChoiceView } from "../pinned.ts";
36 import { placeChoice } from "../../spawn/making.ts";
3537
3638 const COOKIE = "forge_order";
3739 const REFRESH_JS = "setTimeout(function(){location.reload()},3000);";
@@ -39,6 +41,8 @@ const REFRESH_JS = "setTimeout(function(){location.reload()},3000);";
3941 interface Values {
4042 readonly name: string;
4143 readonly email: string;
44 /** A Places id for a forge on a cloud account; empty for the plan's default. */
45 readonly place: string;
4246 }
4347
4448 const isBuyer = (ctx: Ctx): boolean => ctx.auth.user === undefined || ctx.auth.user.kind === "user";
@@ -95,6 +99,7 @@ function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["fie
9599 ...(errors["email"] ? { error: errors["email"] } : {}),
96100 })
97101 : null}
102 ${selling ? placeChoiceView(placeChoice(ctx.app, plans.find((p) => p.key !== FREE), false), values.place, errors["place"]) : null}
98103 <dl class="status-rows">${rows}</dl>
99104 </form>
100105 <div class="muted small" data-after-pay>
@@ -118,7 +123,7 @@ export function pricingPage(ctx: Ctx): Response {
118123 description: "What each forge plan costs and the CPU, memory, disk and crew credit it includes.",
119124 tight: true,
120125 jsonLd: safeJson({ "@context": "https://schema.org", "@type": "Product", name: "Open Platform Forge", url: `${ctx.url.origin}/`, additionalProperty: sharedProperties(lapseRule(ctx.app.db)), offers: offerData(plans, ctx.url.origin, lapseRule(ctx.app.db), true, startUsd) }),
121 body: plansView(ctx, { name: (ctx.url.searchParams.get("name") ?? "").slice(0, 38), email: "" }, {}),
126 body: plansView(ctx, { name: (ctx.url.searchParams.get("name") ?? "").slice(0, 38), email: "", place: "" }, {}),
122127 });
123128 notePhase(ctx.request, "render", performance.now() - rendering);
124129 return response;
@@ -127,23 +132,26 @@ export function pricingPage(ctx: Ctx): Response {
127132 const cookieFor = (ctx: Ctx, value: string, maxAge: number): string =>
128133 setCookie(COOKIE, value, { path: "/pricing", maxAge, secure: secureFor(ctx.url, ctx.app.config.url) });
129134
135 /** The cookie that opens an order's `/pricing/done`, for two days: a paid order's, or a cloud forge's an admin or a code gave. */
136 export const orderCookie = (ctx: Ctx, id: string, ticket: string): string => cookieFor(ctx, `${id}.${ticket}`, 2 * 86_400);
137
130138 // POST /pricing/order — free goes on to the free path; a paid plan holds the name and goes to
131139 // checkout.
132140 export async function pricingOrder(ctx: Ctx): Promise<Response> {
133141 if (!isBuyer(ctx)) return notFoundPage(ctx);
134142 const form = await readForm(ctx, ctx.auth.user === undefined ? undefined : "admin");
135143 if (form instanceof Response) return form;
136 const values: Values = { name: field(form, "name").trim().slice(0, 60), email: field(form, "email").trim().slice(0, 254) };
144 const values: Values = { name: field(form, "name").trim().slice(0, 60), email: field(form, "email").trim().slice(0, 254), place: field(form, "place").trim().slice(0, 200) };
137145 const plan = field(form, "plan");
138146 if (plan === FREE) return redirect(`/forges/new?name=${encodeURIComponent(values.name.slice(0, 38))}`);
139147 const verdict = takeDoor(ctx.app, "plan", ctx.request);
140148 if (!verdict.allowed) return page({ ctx, title: "Get your own forge", body: plansView(ctx, values, { form: `Too many tries from here; try again in ${verdict.retryAfter}s` }) }, 429);
141 const placed = await placeOrder(ctx.app, { name: values.name, plan, email: values.email, address: clientBucket(ctx.request) }, ctx.url);
149 const placed = await placeOrder(ctx.app, { name: values.name, plan, email: values.email, address: clientBucket(ctx.request), place: values.place }, ctx.url);
142150 if (!placed.ok) {
143151 const status = placed.error.message === NO_PROVIDER ? 409 : 422;
144152 return page({ ctx, title: "Get your own forge", body: plansView(ctx, values, { [placed.error.field]: `${placed.error.message}.` }) }, status);
145153 }
146 const res = redirect(placed.value.redirect, { cookie: cookieFor(ctx, `${placed.value.id}.${placed.value.ticket}`, 2 * 86_400) });
154 const res = redirect(placed.value.redirect, { cookie: orderCookie(ctx, placed.value.id, placed.value.ticket) });
147155 res.headers.set("cache-control", "no-store");
148156 return res;
149157 }
@@ -189,8 +197,10 @@ async function doneView(ctx: Ctx): Promise<Response> {
189197 return res;
190198 };
191199 if (o.state === "pending") return waiting(ctx, "Waiting for the payment to arrive. This page updates by itself.");
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.`);
200 // A forge an admin or a code gave was not bought here: no "Paid".
201 const paid = o.sessionId === "" ? "" : "Paid. ";
202 if (o.state === "paid" || o.state === "spawning") return waiting(ctx, `${paid}Making ${o.name} now; the link to open it appears here.`);
203 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.`);
194204 if (o.state === "failed")
195205 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>
196206 <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);
@@ -218,7 +228,7 @@ export function resendPage(ctx: Ctx): Response {
218228 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
219229 if (!isBuyer(ctx)) return notFoundPage(ctx);
220230 const rendering = performance.now();
221 const response = page({ ctx, title: "Lost your link?", body: resendView(ctx, undefined, { name: "", email: "" }) });
231 const response = page({ ctx, title: "Lost your link?", body: resendView(ctx, undefined, { name: "", email: "", place: "" }) });
222232 notePhase(ctx.request, "render", performance.now() - rendering);
223233 return response;
224234 }
@@ -229,12 +239,12 @@ export async function resendSubmit(ctx: Ctx): Promise<Response> {
229239 if (!isBuyer(ctx)) return notFoundPage(ctx);
230240 const form = await readForm(ctx, ctx.auth.user === undefined ? undefined : "admin");
231241 if (form instanceof Response) return form;
232 const values: Values = { name: field(form, "name").trim().slice(0, 60), email: field(form, "email").trim().slice(0, 254) };
242 const values: Values = { name: field(form, "name").trim().slice(0, 60), email: field(form, "email").trim().slice(0, 254), place: field(form, "place").trim().slice(0, 200) };
233243 const verdict = takeDoor(ctx.app, "plan", ctx.request);
234244 if (!verdict.allowed) return page({ ctx, title: "Lost your link?", body: resendView(ctx, `Too many tries from here; try again in ${verdict.retryAfter}s.`, values) }, 429);
235245 const out = await resendLink(ctx.app, values.name, values.email);
236246 const says = out === "no_mail" ? "This forge cannot send email. Ask the operator for a new link." : "If that order exists, the link is on its way to the email it was bought with.";
237 const res = page({ ctx, title: "Lost your link?", body: resendView(ctx, says, { name: "", email: "" }) });
247 const res = page({ ctx, title: "Lost your link?", body: resendView(ctx, says, { name: "", email: "", place: "" }) });
238248 res.headers.set("cache-control", "no-store");
239249 return res;
240250 }
src/web/pinned.ts +27
@@ -10,6 +10,7 @@ import { claimWords, type Issued } from "../actions/pinned.ts";
1010 import type { CloudAccount } from "../core/cloud_account.ts";
1111 import { HOST_CAN } from "../core/pinned.ts";
1212 import type { Place } from "../cloud/places.ts";
13 import type { PlaceChoice } from "../spawn/making.ts";
1314 import { dollars } from "../cloud/prices.ts";
1415 import { LABEL } from "../cloud/providers.ts";
1516 import { TARGETS } from "../cloud/targets.ts";
@@ -106,3 +107,29 @@ export function deployPage(accounts: CloudAccount[], v: DeployForm, places: Plac
106107 </form>`,
107108 )}`;
108109 }
110
111 /**
112 * Where a forge on a cloud account runs (#16385): one sentence with the default and why, and a
113 * closed "Choose where it runs" list of the orderable places, by country, each with its city,
114 * machine and monthly cost, and what it costs over the default. A dearer place is shown and not
115 * offered unless `choice.dearer`. The New forge page's and the order form's one fragment; nothing
116 * for a forge that runs hosted.
117 */
118 export function placeChoiceView(choice: PlaceChoice | undefined, chosen: string, error?: string): Html | null {
119 if (choice === undefined) return null;
120 const countries = new Map<string, Place[]>();
121 for (const p of [...choice.places].sort((a, b) => a.country.localeCompare(b.country) || a.city.localeCompare(b.city) || a.costCents - b.costCents))
122 countries.set(p.country || "Elsewhere", [...(countries.get(p.country || "Elsewhere") ?? []), p]);
123 const over = (p: Place) => p.costCents - choice.defaultCents;
124 const row = (p: Place) => html`<label class="small"><input type="radio" name="place" value="${p.id}"${chosen === p.id ? html` checked` : null}${over(p) > 0 && !choice.dearer ? html` disabled` : null}> ${p.city} · ${p.vcpu} vCPU, ${Math.round(p.memoryMiB / 1024)} GB · ${dollars(p.costCents)} a month${over(p) > 0 ? ` (${dollars(over(p))} more)` : ""}${p.id === choice.defaultId ? " · the default" : ""}</label>`;
125 return html`<p class="small" data-place-default>${choice.says}</p>
126 <details class="field" data-place-choice${chosen !== "" || error ? html` open` : null}>
127 <summary>Choose where it runs</summary>
128 ${error ? html`<p class="error" role="alert">${error}</p>` : null}
129 <fieldset class="stack">
130 <label class="small"><input type="radio" name="place" value=""${chosen === "" ? html` checked` : null}> The default</label>
131 ${[...countries].map(([country, ps]) => html`<p class="muted small mt">${country}</p>${ps.map(row)}`)}
132 ${choice.dearer || !choice.places.some((p) => over(p) > 0) ? null : html`<p class="muted small">A dearer place cannot be bought yet.</p>`}
133 </fieldset>
134 </details>`;
135 }
test/one-door.test.ts added +483
@@ -0,0 +1,483 @@
1 /**
2 * One door for making a forge (#16385): `spawnDoor` decides where it runs by one rule
3 * (`whereFor`), and every way in reaches the cloud placement through it: a paid order, an admin's
4 * paid plan, a gift code, an admin's named account. A `place` is checked against the catalog
5 * before anything is paid or made, with no call to a provider; a dearer place than the plan's own
6 * is refused for anyone but an admin. The New forge page shows the default and a closed list for a
7 * paid plan, and nothing for a free one. A recorded fetch stands in for DigitalOcean.
8 */
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import {
15 addAccount,
16 allowWrite,
17 net as cloudNet,
18 } from "../src/actions/cloud.ts";
19 import { setCeiling } from "../src/actions/cloud_ceiling.ts";
20 import { makeCode } from "../src/actions/codes.ts";
21 import {
22 makingWatch,
23 placeOrder,
24 settleSession,
25 } from "../src/actions/order.ts";
26 import {
27 changeBaseDomain,
28 changePaidPlacement,
29 net,
30 } from "../src/actions/pinned.ts";
31 import { createRepo } from "../src/actions/repos.ts";
32 import { useCheckout, type CheckoutProvider } from "../src/billing/checkout.ts";
33 import { getOrder } from "../src/billing/orders.ts";
34 import { readPlaces } from "../src/cloud/places_read.ts";
35 import { refreshRate } from "../src/cloud/rates.ts";
36 import { changesOf, getPinned } from "../src/core/pinned.ts";
37 import { createUser, getUserByName, type User } from "../src/core/users.ts";
38 import type { Ctx } from "../src/http/context.ts";
39 import { ok } from "../src/kernel/result.ts";
40 import { getPlan } from "../src/settings/plans.ts";
41 import { spawnDoor, usePlacement } from "../src/spawn/door.ts";
42 import { placeChoice, whereFor } from "../src/spawn/making.ts";
43 import { closeHostedChildren } from "../src/spawn/host.ts";
44 import { newForgePage } from "../src/web/pages/new-forge.ts";
45 import { quietLogs } from "./helpers/globals.ts";
46
47 quietLogs();
48 makingWatch.tries = 0;
49
50 const COMMIT = "d".repeat(40);
51 /** nyc3 is the default ($13), sfo3 is dearer ($25), ams3 cannot be ordered now. */
52 const ocean = {
53 regions: [
54 { slug: "nyc3", available: true },
55 { slug: "sfo3", available: true },
56 { slug: "ams3", available: false },
57 ],
58 sizes: [
59 {
60 slug: "s-1vcpu-2gb",
61 memory: 2048,
62 vcpus: 1,
63 disk: 50,
64 transfer: 2,
65 price_monthly: 12,
66 available: true,
67 regions: ["nyc3", "ams3"],
68 },
69 {
70 slug: "s-2vcpu-4gb",
71 memory: 4096,
72 vcpus: 2,
73 disk: 80,
74 transfer: 4,
75 price_monthly: 24,
76 available: true,
77 regions: ["sfo3"],
78 },
79 ],
80 };
81
82 describe("one door for making a forge", () => {
83 let dataDir = "";
84 let app: App;
85 const calls: string[] = [];
86 let hosted = 0;
87 const before = process.env["FORGE_COMMIT"];
88 const admin = () => getUserByName(app.db, "alice")!;
89 const ctxOf = (user: User | undefined, path = "/forges/new"): Ctx => ({
90 app,
91 request: new Request(`https://forge.test${path}`, { method: "POST" }),
92 url: new URL(`https://forge.test${path}`),
93 params: {},
94 auth: { user, scope: undefined, via: "none" },
95 theme: undefined,
96 });
97 const door = (user: User | undefined, raw: Record<string, unknown>) =>
98 spawnDoor(ctxOf(user), user, { apps: [], crew: [], ...raw });
99 const creates = () => calls.filter((c) => c === "POST /v2/droplets").length;
100 const fake: CheckoutProvider = {
101 name: "fake",
102 create: async () =>
103 ok({
104 id: `cs_${calls.length}_${Date.now()}`,
105 url: "https://pay.fake.test/x",
106 }),
107 state: async () =>
108 ok({ paid: false, customer: "cus_1", subscription: "sub_1" }),
109 };
110
111 beforeAll(async () => {
112 process.env["FORGE_COMMIT"] = COMMIT;
113 dataDir = await mkdtemp(join(tmpdir(), "forge-one-door-"));
114 app = createApp({
115 dataDir,
116 port: 0,
117 forgeRepo: "alice/forge",
118 url: "https://forge.test",
119 });
120 useCheckout(app, fake);
121 usePlacement(app, {
122 place: async (plan) => (
123 ++hosted,
124 ok({
125 url: `https://${plan.name}.hosted.test`,
126 bodyId: `fake-${hosted}`,
127 })
128 ),
129 retire: async () => ok(),
130 });
131 const json = (o: unknown, status = 200) =>
132 new Response(JSON.stringify(o), { status });
133 await readPlaces(
134 app.db,
135 "digitalocean",
136 async (url) =>
137 json(
138 String(url).includes("/sizes")
139 ? { sizes: ocean.sizes }
140 : { regions: ocean.regions },
141 ),
142 "t",
143 );
144 await refreshRate(
145 app.db,
146 async () =>
147 new Response(
148 "<Cube time='2026-11-23'><Cube currency='USD' rate='1.2'/></Cube>",
149 { status: 200 },
150 ),
151 );
152 const made = await createUser(app.db, {
153 origin: "seed",
154 trusted: true,
155 username: "alice",
156 email: "[email protected]",
157 password: "a-good-passphrase",
158 adminIfFirst: true,
159 });
160 if (!made.ok) throw new Error(made.error);
161 if (
162 !(
163 await createRepo(app, made.value, {
164 name: "forge",
165 visibility: "public",
166 })
167 ).ok
168 )
169 throw new Error("repo");
170 cloudNet.fetch = async () =>
171 json({ account: { email: "[email protected]", status: "active" } });
172 if (
173 !(
174 await addAccount(
175 app,
176 admin(),
177 "digitalocean",
178 "main",
179 "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5",
180 )
181 ).ok
182 )
183 throw new Error("account");
184 allowWrite(app, admin(), "digitalocean", "main", true);
185 expect(setCeiling(app, admin(), "digitalocean", "main", 500).ok).toBe(true);
186 expect(changeBaseDomain(app, admin(), "forges.test").ok).toBe(true);
187 let droplets = 3000;
188 net.fetch = async (url, init) => {
189 const u = new URL(url);
190 const method = init?.method ?? "GET";
191 calls.push(`${method} ${u.pathname}`);
192 if (u.pathname.endsWith("/volumes"))
193 return json({ volume: { id: "vol-1" } }, 201);
194 if (u.pathname.endsWith("/account/keys"))
195 return json({ ssh_key: { id: 4242 } }, 201);
196 if (method === "DELETE") return new Response(null, { status: 204 });
197 if (method === "POST") return json({ droplet: { id: ++droplets } }, 202);
198 const id = Number(u.pathname.split("/").at(-1));
199 return json({
200 droplet: {
201 id,
202 status: "active",
203 networks: {
204 v4: [{ type: "public", ip_address: `203.0.113.${id % 250}` }],
205 },
206 },
207 });
208 };
209 net.resolve = async () => [];
210 net.probe = async () => new Response("ok", { status: 200 });
211 }, 30_000);
212
213 afterAll(async () => {
214 if (before === undefined) delete process.env["FORGE_COMMIT"];
215 else process.env["FORGE_COMMIT"] = before;
216 closeHostedChildren(app);
217 app.close();
218 await rm(dataDir, { recursive: true, force: true });
219 });
220
221 test("the rule: free is hosted, a paid plan follows the setting, an admin's named account wins", () => {
222 const small = getPlan(app.db, "small");
223 expect(whereFor(app, getPlan(app.db, "free"))).toEqual({ where: "hosted" });
224 expect(whereFor(app, small)).toEqual({ where: "hosted" });
225 expect(
226 whereFor(app, undefined, { provider: "digitalocean", account: "main" }),
227 ).toEqual({ where: "cloud", provider: "digitalocean", account: "main" });
228 expect(changePaidPlacement(app, admin(), "digitalocean/main").ok).toBe(
229 true,
230 );
231 expect(whereFor(app, small)).toEqual({
232 where: "cloud",
233 provider: "digitalocean",
234 account: "main",
235 });
236 expect(whereFor(app, getPlan(app.db, "free"))).toEqual({ where: "hosted" });
237 expect(changePaidPlacement(app, admin(), "hosted").ok).toBe(true);
238 expect(whereFor(app, small)).toEqual({ where: "hosted" });
239 });
240
241 test("a free forge stays hosted and takes no place", async () => {
242 expect(changePaidPlacement(app, admin(), "digitalocean/main").ok).toBe(
243 true,
244 );
245 const made = await door(admin(), { name: "freeone", dryRun: false });
246 expect(made.status).toBe(201);
247 expect(hosted).toBe(1);
248 expect(getPinned(app.db, "freeone")).toBeUndefined();
249 const placed = await door(admin(), {
250 name: "freetwo",
251 place: "digitalocean:nyc3:s-1vcpu-2gb",
252 });
253 expect(placed).toMatchObject({
254 status: 422,
255 body: { message: expect.stringMatching(/^place: /) },
256 });
257 expect(calls).toEqual([]);
258 });
259
260 test("an unorderable or too-small place is refused in the catalog's words, with no provider call", async () => {
261 const shut = await door(admin(), {
262 name: "shut",
263 plan: "small",
264 place: "digitalocean:ams3:s-1vcpu-2gb",
265 });
266 expect(shut.status).toBe(422);
267 expect(String(shut.body["message"])).toStartWith(
268 "place: digitalocean:ams3:s-1vcpu-2gb cannot be ordered now",
269 );
270 const none = await door(admin(), {
271 name: "shut",
272 plan: "small",
273 place: "digitalocean:lon1:s-1vcpu-2gb",
274 });
275 expect(String(none.body["message"])).toContain("There is no place");
276 expect(
277 await door(admin(), {
278 name: "shut",
279 plan: "medium",
280 place: "digitalocean:nyc3:s-1vcpu-2gb",
281 }),
282 ).toMatchObject({
283 status: 422,
284 body: {
285 message: expect.stringContaining("too small for a medium forge"),
286 },
287 });
288 expect(calls).toEqual([]);
289 });
290
291 test("an admin's paid plan is deployed as an order, making, with the order's page and ticket", async () => {
292 const plan = await door(admin(), { name: "client", plan: "small" });
293 expect(plan.body["runsOn"]).toMatchObject({
294 account: "digitalocean/main",
295 place: "digitalocean:nyc3:s-1vcpu-2gb",
296 });
297 const made = await door(admin(), {
298 name: "client",
299 plan: "small",
300 dryRun: false,
301 });
302 expect(made.status).toBe(202);
303 expect(made.body).toMatchObject({
304 making: true,
305 name: "client",
306 done: expect.stringMatching(/^\/pricing\/done\?order=ord_/),
307 });
308 expect(typeof made.body["ticket"]).toBe("string");
309 const o = getOrder(app.db, String(made.body["order"]))!;
310 expect(o).toMatchObject({
311 state: "making",
312 priceUsd: 0,
313 email: "[email protected]",
314 sessionId: "",
315 });
316 expect(
317 changesOf(app.db, getPinned(app.db, "client")!.id).map((c) => c.by),
318 ).toEqual([`order:${o.id}`]);
319 expect(creates()).toBe(1);
320 expect(hosted).toBe(1);
321 // The name is held: a second door for it is refused, and nothing more is made.
322 expect(
323 (await door(admin(), { name: "client", plan: "small", dryRun: false }))
324 .status,
325 ).toBe(422);
326 expect(creates()).toBe(1);
327 });
328
329 test("an admin may name the account, and a dearer place, for any plan", async () => {
330 expect(changePaidPlacement(app, admin(), "hosted").ok).toBe(true);
331 const made = await door(admin(), {
332 name: "named",
333 target: "digitalocean",
334 account: "main",
335 place: "digitalocean:sfo3:s-2vcpu-4gb",
336 dryRun: false,
337 });
338 expect(made).toMatchObject({ status: 202, body: { making: true } });
339 expect(getPinned(app.db, "named")).toMatchObject({
340 datacenter: "sfo3",
341 size: "s-2vcpu-4gb",
342 });
343 const stranger = await door(undefined, {
344 name: "named2",
345 target: "digitalocean",
346 account: "main",
347 });
348 expect(String(stranger.body["message"])).toStartWith(
349 "target: only a site admin",
350 );
351 expect(changePaidPlacement(app, admin(), "digitalocean/main").ok).toBe(
352 true,
353 );
354 });
355
356 test("a gift code's forge is deployed through the same door, and spends the code once", async () => {
357 const code = makeCode(
358 app,
359 admin(),
360 { plan: "small", uses: 1 },
361 "https://forge.test",
362 );
363 if (!code.ok) throw new Error(code.error);
364 const dear = await door(undefined, {
365 name: "gifted",
366 code: code.value.code,
367 place: "digitalocean:sfo3:s-2vcpu-4gb",
368 dryRun: false,
369 });
370 expect(dear.status).toBe(422);
371 expect(String(dear.body["message"])).toContain(
372 "a dearer place cannot be bought yet",
373 );
374 const made = await door(undefined, {
375 name: "gifted",
376 code: code.value.code,
377 dryRun: false,
378 });
379 expect(made).toMatchObject({
380 status: 202,
381 body: { making: true, name: "gifted" },
382 });
383 expect(getPinned(app.db, "gifted")).toMatchObject({ datacenter: "nyc3" });
384 expect(
385 (
386 await door(undefined, {
387 name: "gifted2",
388 code: code.value.code,
389 dryRun: false,
390 })
391 ).status,
392 ).toBe(422);
393 });
394
395 test("a paid order reaches the cloud through the door, at the place chosen before payment", async () => {
396 const dear = await placeOrder(
397 app,
398 {
399 name: "bought",
400 plan: "small",
401 email: "[email protected]",
402 address: "198.51.100.9",
403 place: "digitalocean:sfo3:s-2vcpu-4gb",
404 },
405 new URL("https://forge.test/pricing"),
406 );
407 expect(dear).toMatchObject({ ok: false, error: { field: "place" } });
408 const shut = await placeOrder(
409 app,
410 {
411 name: "bought",
412 plan: "small",
413 email: "[email protected]",
414 address: "198.51.100.9",
415 place: "digitalocean:ams3:s-1vcpu-2gb",
416 },
417 new URL("https://forge.test/pricing"),
418 );
419 expect(shut).toMatchObject({ ok: false, error: { field: "place" } });
420 const n = creates();
421 const placed = await placeOrder(
422 app,
423 {
424 name: "bought",
425 plan: "small",
426 email: "[email protected]",
427 address: "198.51.100.9",
428 place: "digitalocean:nyc3:s-1vcpu-2gb",
429 },
430 new URL("https://forge.test/pricing"),
431 );
432 if (!placed.ok) throw new Error(placed.error.message);
433 const o = getOrder(app.db, placed.value.id)!;
434 expect(o.place).toBe("digitalocean:nyc3:s-1vcpu-2gb");
435 await settleSession(app, {
436 id: o.sessionId,
437 metadata: { order: o.id },
438 customer: "cus_1",
439 subscription: "sub_1",
440 payment_status: "paid",
441 });
442 expect(getOrder(app.db, o.id)?.state).toBe("making");
443 expect(creates()).toBe(n + 1);
444 expect(
445 changesOf(app.db, getPinned(app.db, "bought")!.id).map((c) => c.by),
446 ).toEqual([`order:${o.id}`]);
447 });
448
449 test("the New forge page shows the default and a closed list for a paid plan, nothing for a free one", async () => {
450 const free = await (
451 await newForgePage({
452 ...ctxOf(admin()),
453 request: new Request("https://forge.test/forges/new"),
454 })
455 ).text();
456 expect(free).not.toContain("data-place-choice");
457 const paid = await (
458 await newForgePage({
459 ...ctxOf(admin(), "/forges/new?plan=small"),
460 request: new Request("https://forge.test/forges/new?plan=small"),
461 })
462 ).text();
463 expect(paid).toContain(
464 "the cheapest place in the United States that can be ordered now",
465 );
466 expect(paid).toMatch(
467 /<details class="field" data-place-choice>\s*<summary>Choose where it runs<\/summary>/,
468 );
469 expect(paid).toContain('value="digitalocean:nyc3:s-1vcpu-2gb"');
470 // A dearer place is shown with what it costs over the default; an admin may pick it.
471 expect(
472 placeChoice(app, getPlan(app.db, "small"), false)?.places.map(
473 (p) => p.id,
474 ),
475 ).toEqual([
476 "digitalocean:nyc3:s-1vcpu-2gb",
477 "digitalocean:sfo3:s-2vcpu-4gb",
478 ]);
479 expect(paid).toMatch(
480 /value="digitalocean:sfo3:s-2vcpu-4gb"> San Francisco[^<]*more\)/,
481 );
482 });
483 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs