Public: anyone can read this; the crew can change it.
A paid forge sale is safe: the claim link survives without mail, a lapsed cloud forge stops billing, orders in flight count #16484
Check · Review · Land · Live done — Landed and live in production.
sold/sale-safe → main 0 commits
11 files
changed +277
−31
src/actions/order.ts +15 −11
| @@ -9,8 +9,9 @@ | ||
| 9 | 9 | * admin retries it or refunds at the provider. Never an agent as buyer. |
| 10 | 10 | * |
| 11 | 11 | * The claim link is shown once, on the return page, and mailed when the |
| 12 | * forge can send mail. It is never kept: the page makes a fresh one when the | |
| 13 | * buyer arrives, and a buyer who left can ask for one by email. | |
| 12 | * forge can send mail. A hosted forge's is never kept: the page makes a fresh one when the | |
| 13 | * buyer arrives, and a buyer who left can ask for one by email. A cloud forge's stays sealed and | |
| 14 | * is shown on every visit until the forge is claimed or the claim expires. | |
| 14 | 15 | * |
| 15 | 16 | * Where the forge runs is the door's one rule (`spawn/making.ts`): when paid forges run on a cloud |
| 16 | 17 | * account (#16205) the door deploys it as the order, at the place the buyer chose (#16385) or the |
| @@ -34,7 +35,7 @@ import { nameTaken, spawnDoor } from "../spawn/door.ts"; | ||
| 34 | 35 | import { FREE, getPlan, type Plan } from "../settings/plans.ts"; |
| 35 | 36 | import { reissueClaimFor } from "./spawn.ts"; |
| 36 | 37 | import { mailerOf } from "./verify.ts"; |
| 37 | import { askMaking, dropLink, failOrder, keptLink, mailLink } from "../spawn/making.ts"; | |
| 38 | import { askMaking, failOrder, mailLink, openLink } from "../spawn/making.ts"; | |
| 38 | 39 | |
| 39 | 40 | export { makingWatch } from "../spawn/making.ts"; |
| 40 | 41 | |
| @@ -246,7 +247,7 @@ export async function reconcileOrder(app: App, id: string): Promise<Order | unde | ||
| 246 | 247 | } |
| 247 | 248 | |
| 248 | 249 | export type Delivered = |
| 249 | | { readonly kind: "link"; readonly claimUrl: string; readonly mailed: boolean } | |
| 250 | | { readonly kind: "link"; readonly claimUrl: string; readonly mailed: boolean; readonly mail: boolean; readonly kept: boolean } | |
| 250 | 251 | | { readonly kind: "shown" } |
| 251 | 252 | | { readonly kind: "claimed" } |
| 252 | 253 | | { readonly kind: "failed" }; |
| @@ -254,19 +255,22 @@ export type Delivered = | ||
| 254 | 255 | /** A spawned order's claim link, for the buyer who holds its ticket: made fresh, shown once, mailed when mail is on. */ |
| 255 | 256 | export async function deliverLink(app: App, o: Order): Promise<Delivered> { |
| 256 | 257 | if (o.state !== "spawned") return { kind: "failed" }; |
| 257 | if (!markShown(app.db, o.id, Date.now())) return { kind: "shown" }; | |
| 258 | // A cloud order's link was issued with its machine and kept sealed: shown now, and kept no more. | |
| 259 | const kept = keptLink(app, o.id); | |
| 260 | if (kept !== undefined) { | |
| 261 | dropLink(app, o.id); | |
| 262 | return { kind: "link", claimUrl: kept, mailed: o.resentAt !== null }; | |
| 258 | const mail = mailerOf(app, { id: "order" }) !== undefined; | |
| 259 | // A cloud order's link was issued with its machine and kept sealed: shown every time until its | |
| 260 | // forge is claimed or the claim expires, whether or not mail is on. | |
| 261 | const open = openLink(app, o); | |
| 262 | if (open.link !== undefined) { | |
| 263 | markShown(app.db, o.id, Date.now()); | |
| 264 | return { kind: "link", claimUrl: open.link, mailed: o.resentAt !== null, mail, kept: true }; | |
| 263 | 265 | } |
| 266 | if (open.claimed) return { kind: "claimed" }; | |
| 267 | if (!markShown(app.db, o.id, Date.now())) return { kind: "shown" }; | |
| 264 | 268 | const made = await reissueClaimFor(app, o.name); |
| 265 | 269 | if (!made.ok) { |
| 266 | 270 | unmarkShown(app.db, o.id); |
| 267 | 271 | return "reason" in made.error && made.error.reason === "claimed" ? { kind: "claimed" } : { kind: "failed" }; |
| 268 | 272 | } |
| 269 | return { kind: "link", claimUrl: made.value.claimUrl, mailed: await mailLink(app, o, made.value.claimUrl) }; | |
| 273 | return { kind: "link", claimUrl: made.value.claimUrl, mailed: await mailLink(app, o, made.value.claimUrl), mail, kept: false }; | |
| 270 | 274 | } |
| 271 | 275 | |
| 272 | 276 | /** A buyer who left asks for the link again: it goes to the order's own email and nowhere else. Always the same answer. */ |
src/actions/pinned.ts +24 −5
| @@ -31,7 +31,9 @@ import { capped, CeilingRefusal, priced, refusalAt, rowCents } from "../cloud/ce | ||
| 31 | 31 | import { driverOf } from "../cloud/drivers.ts"; |
| 32 | 32 | import { orderable, provision, read, replace, retire } from "../cloud/machine.ts"; |
| 33 | 33 | import { dollars } from "../cloud/prices.ts"; |
| 34 | import { chooseDefault, meets, type Chosen, type Place, type PlanName } from "../cloud/places.ts"; | |
| 34 | import { chooseDefault, isPlan, meets, type Chosen, type Place, type PlanName } from "../cloud/places.ts"; | |
| 35 | import { inFlight } from "../billing/orders.ts"; | |
| 36 | import { getPlan } from "../settings/plans.ts"; | |
| 35 | 37 | import { MAX_ID, keptPlaces, pinOf } from "../cloud/places_read.ts"; |
| 36 | 38 | import { keptRate } from "../cloud/rates.ts"; |
| 37 | 39 | import { deleteARecord, upsertARecord, type Fetch } from "../cloud/providers.ts"; |
| @@ -783,9 +785,9 @@ export function checkForOrder(app: App, orderId: string, name: string): Promise< | ||
| 783 | 785 | * Retire a paid order's forge, as the order, keeping its data volume: refused for one it did not |
| 784 | 786 | * deploy. |
| 785 | 787 | */ |
| 786 | export function retireForOrder(app: App, orderId: string, name: string): Promise<Result<Retired, string>> { | |
| 788 | export function retireForOrder(app: App, orderId: string, name: string, o: { withData?: boolean; despiteClaim?: boolean } = {}): Promise<Result<Retired, string>> { | |
| 787 | 789 | const who = orderWho(orderId); |
| 788 | return madeBy(app, name, who) ? oneChange(app, name, () => retireNow(app, who, name, {})) : Promise.resolve(err("No such pinned forge.")); | |
| 790 | return madeBy(app, name, who) ? oneChange(app, name, () => retireNow(app, who, name, o)) : Promise.resolve(err("No such pinned forge.")); | |
| 789 | 791 | } |
| 790 | 792 | |
| 791 | 793 | /** |
| @@ -794,7 +796,7 @@ export function retireForOrder(app: App, orderId: string, name: string): Promise | ||
| 794 | 796 | * buyer pays (#16205). Reads only what the forge holds (the catalog it last read, the account, |
| 795 | 797 | * the ceiling); nothing is asked of a provider, so a catalog never read is refused here too. |
| 796 | 798 | */ |
| 797 | export function deployRoom(app: App, provider: string, account: string, plan: PlanName, asked = "", dearer = true): string | undefined { | |
| 799 | export function deployRoom(app: App, provider: string, account: string, plan: PlanName, asked = "", dearer = true, except = ""): string | undefined { | |
| 798 | 800 | const t = targetOf(provider); |
| 799 | 801 | if (t === undefined || t.status !== "first") return "That is not a target the forge knows."; |
| 800 | 802 | const a = getCloudAccount(app.db, provider, account); |
| @@ -807,7 +809,24 @@ export function deployRoom(app: App, provider: string, account: string, plan: Pl | ||
| 807 | 809 | const base = dearer || asked === "" ? undefined : pickPlace(app, provider, "", plan); |
| 808 | 810 | if (base?.ok && at.value.costCents > base.value.costCents) |
| 809 | 811 | 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.`; |
| 810 | return refusalAt(app, provider, account, at.value); | |
| 812 | const prices = priced(app.db); | |
| 813 | return refusalAt(app, provider, account, at.value, 0, prices, heldCents(app, provider, prices, except)); | |
| 814 | } | |
| 815 | ||
| 816 | /** | |
| 817 | * What orders in flight will cost a month at their own places, by the ceiling's prices: the ones | |
| 818 | * with no costed row yet, other than `except` (the order being made, which `admit` counts by its row). | |
| 819 | */ | |
| 820 | function heldCents(app: App, provider: string, prices: ReturnType<typeof priced>, except: string): number { | |
| 821 | let sum = 0; | |
| 822 | for (const o of inFlight(app.db, Date.now())) { | |
| 823 | const row = getPinned(app.db, o.name); | |
| 824 | if (o.id === except || (row !== undefined && rowCents(row, prices) > 0)) continue; | |
| 825 | const size = getPlan(app.db, o.plan)?.size ?? "small"; | |
| 826 | const at = pickPlace(app, provider, o.place, isPlan(size) ? size : "small"); | |
| 827 | if (at.ok) sum += prices.forge(at.value.id) ?? 0; | |
| 828 | } | |
| 829 | return sum; | |
| 811 | 830 | } |
| 812 | 831 | |
| 813 | 832 | /** Where paid forges run, for an admin: `hosted` or `provider/name`. */ |
src/billing/lapse_rule.ts +4
| @@ -27,3 +27,7 @@ export const graceEnds = (r: LapseRule, since: number): number => since + r.grac | ||
| 27 | 27 | * below none. |
| 28 | 28 | */ |
| 29 | 29 | export const graceDaysLeft = (r: LapseRule, since: number, now: number): number => Math.max(0, Math.ceil((graceEnds(r, since) - now) / DAY)); |
| 30 | ||
| 31 | /** The rule for a forge on its own cloud machine: the machine is deleted, its data kept, then deleted. */ | |
| 32 | export const cloudLapseWords = (r: LapseRule, keepDays: number): string => | |
| 33 | `If a payment lapses, you have ${r.graceDays} ${r.graceDays === 1 ? "day" : "days"} of grace. After that its machine is deleted and its data kept ${keepDays} ${keepDays === 1 ? "day" : "days"}, then deleted.`; |
src/billing/orders.ts +23
| @@ -177,3 +177,26 @@ export function failedOrders(db: Database): Order[] { | ||
| 177 | 177 | export function recentOrders(db: Database, limit = 20): Order[] { |
| 178 | 178 | return db.query<Row, [number]>("SELECT * FROM forge_order WHERE state != 'pending' ORDER BY updated_at DESC LIMIT ?1").all(limit).map(fromRow); |
| 179 | 179 | } |
| 180 | ||
| 181 | /** | |
| 182 | * Orders whose forge is not up yet or is about to be made: paid, spawning or making, and pending | |
| 183 | * ones still within the checkout's validity. What the ceiling counts beside its pinned rows. | |
| 184 | */ | |
| 185 | export function inFlight(db: Database, now: number): Order[] { | |
| 186 | return db | |
| 187 | .query<Row, [number, number]>( | |
| 188 | "SELECT * FROM forge_order WHERE state IN ('paid', 'spawning', 'making') OR (state = 'pending' AND hold_until > ?1 AND created_at + ?2 > ?1)", | |
| 189 | ) | |
| 190 | .all(now, CHECKOUT_MS) | |
| 191 | .map(fromRow); | |
| 192 | } | |
| 193 | ||
| 194 | /** Bought orders whose forge was made: what a lapse may end. */ | |
| 195 | export function soldOrders(db: Database): Order[] { | |
| 196 | return db.query<Row, []>("SELECT * FROM forge_order WHERE state = 'spawned' AND session_id != ''").all().map(fromRow); | |
| 197 | } | |
| 198 | ||
| 199 | /** Say on a made order what became of its forge (a lapse); its state does not change. */ | |
| 200 | export function noteOrder(db: Database, id: string, reason: string): void { | |
| 201 | db.query("UPDATE forge_order SET reason = ?2 WHERE id = ?1 AND state = 'spawned'").run(id, reason); | |
| 202 | } |
src/cloud/ceiling.ts +4 −2
| @@ -168,6 +168,8 @@ export function refusalAt( | ||
| 168 | 168 | place: { readonly id: string; readonly size: string; readonly datacenter: string }, |
| 169 | 169 | counted = 0, |
| 170 | 170 | prices: Priced = priced(app.db), |
| 171 | /** What orders in flight will cost, not yet in any row. */ | |
| 172 | held = 0, | |
| 171 | 173 | ): string | undefined { |
| 172 | 174 | const who = `${provider}/${account}`; |
| 173 | 175 | const id = place.id; |
| @@ -181,9 +183,9 @@ export function refusalAt( | ||
| 181 | 183 | if (closed !== undefined) return `${id} cannot be ordered now: ${closed}; nothing was made, and a running machine was not touched. Pick another place, or try again later.`; |
| 182 | 184 | const { ceilingDollars, monthlyCents } = spendOf(app.db, provider, account, prices); |
| 183 | 185 | const add = price - counted; |
| 184 | if (add <= 0 || monthlyCents + add <= ceilingDollars * 100) return undefined; | |
| 186 | if (add <= 0 || monthlyCents + held + add <= ceilingDollars * 100) return undefined; | |
| 185 | 187 | return ( |
| 186 | `${who} is held to $${ceilingDollars} a month and runs ${dollars(monthlyCents)} now; this would add ${dollars(add)}, which is over it, so nothing was made. ` + | |
| 188 | `${who} is held to $${ceilingDollars} a month and runs ${dollars(monthlyCents + held)} now; this would add ${dollars(add)}, which is over it, so nothing was made. ` + | |
| 187 | 189 | `Raise the ceiling at ${CEILING_PAGE} if you mean to spend more. This is the forge's own reckoning from list prices; the provider's bill is the truth.` |
| 188 | 190 | ); |
| 189 | 191 | } |
src/spawn/cloud_placement.ts +1 −1
| @@ -63,7 +63,7 @@ export function cloudPlacement( | ||
| 63 | 63 | room() { |
| 64 | 64 | const own = ownSource(app); |
| 65 | 65 | if (!own.ok) return refused(own.error); |
| 66 | const no = deployRoom(app, at.provider, at.account, o.plan, o.place ?? "", o.dearer === true); | |
| 66 | const no = deployRoom(app, at.provider, at.account, o.plan, o.place ?? "", o.dearer === true, o.orderId); | |
| 67 | 67 | return no === undefined ? undefined : { reason: "quota", message: no }; |
| 68 | 68 | }, |
| 69 | 69 | async place(plan) { |
src/spawn/host.ts +2
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | * truth; BodyStore is only for placement capacity. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { retireLapsedCloud } from "./lapse_cloud.ts"; | |
| 8 | 9 | import { childDirOf } from "../actions/spawn.ts"; |
| 9 | 10 | import { createApp, type App } from "../app.ts"; |
| 10 | 11 | import { appsRuntime, type AppsRuntime } from "../apps/runtime.ts"; |
| @@ -566,6 +567,7 @@ function keepSweeping(parent: App): void { | ||
| 566 | 567 | const every = Math.max(1000, Math.min(60_000, Math.floor(idleAfterMs() / 4))); |
| 567 | 568 | const timer = setInterval(() => void during("spawn-idle", async () => { |
| 568 | 569 | await sleepLapsed(parent); |
| 570 | await retireLapsedCloud(parent); | |
| 569 | 571 | await sleepIdleChildren(parent); |
| 570 | 572 | }, undefined, parent).catch(() => {}), every); |
| 571 | 573 | timer.unref?.(); |
src/spawn/lapse_cloud.ts added +57
| @@ -0,0 +1,57 @@ | ||
| 1 | /** | |
| 2 | * A lapsed or refunded cloud forge stops billing (#16478). A forge made by an order on its own | |
| 3 | * cloud machine is retired once its billing is `none` (`billing/lapse.ts`: grace over, or | |
| 4 | * cancelled), or once its subscription's latest payment was refunded in full: the machine is | |
| 5 | * deleted, its data volume kept, and the order says so. After the retention period the volume is | |
| 6 | * deleted too. Each call asks the cloud only for a forge still to be changed; a refusal is tried | |
| 7 | * again later, not at every sweep. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { App } from "../app.ts"; | |
| 11 | import { retireForOrder } from "../actions/pinned.ts"; | |
| 12 | import { lapseFor } from "../billing/lapse.ts"; | |
| 13 | import { noteOrder, soldOrders, type Order } from "../billing/orders.ts"; | |
| 14 | import { getPinned } from "../core/pinned.ts"; | |
| 15 | import { limitValue } from "../settings/limits.ts"; | |
| 16 | ||
| 17 | const DAY = 86_400_000; | |
| 18 | const RETRY_MS = 10 * 60_000; | |
| 19 | const tried = new WeakMap<App, Map<string, number>>(); | |
| 20 | ||
| 21 | /** When this order's forge stopped being paid for, and when its data may go; undefined while it is. */ | |
| 22 | export function lapsedSince(app: App, o: Order, now: number): { since: number; keepUntil: number } | undefined { | |
| 23 | const lapse = lapseFor(app.db, o.name, now); | |
| 24 | if (lapse.state === "none") return lapse; | |
| 25 | if (o.subscriptionId === "") return undefined; | |
| 26 | const last = app.db | |
| 27 | .query<{ status: string; at: string }, [string]>("SELECT status, at FROM payment WHERE subscription_id = ?1 ORDER BY at DESC LIMIT 1") | |
| 28 | .get(o.subscriptionId); | |
| 29 | if (last?.status !== "refunded") return undefined; | |
| 30 | const since = Date.parse(last.at); | |
| 31 | return { since, keepUntil: since + limitValue(app.db, "billing.retention_days") * DAY }; | |
| 32 | } | |
| 33 | ||
| 34 | /** Retire the machines of lapsed cloud orders, keeping their volumes until retention ends. Answers the names changed. */ | |
| 35 | export async function retireLapsedCloud(app: App, now = Date.now()): Promise<string[]> { | |
| 36 | const asked = tried.get(app) ?? new Map<string, number>(); | |
| 37 | tried.set(app, asked); | |
| 38 | const done: string[] = []; | |
| 39 | for (const o of soldOrders(app.db)) { | |
| 40 | const p = getPinned(app.db, o.name); | |
| 41 | const lapsed = p === undefined ? undefined : lapsedSince(app, o, now); | |
| 42 | if (p === undefined || lapsed === undefined) continue; | |
| 43 | const withData = now >= lapsed.keepUntil; | |
| 44 | if (p.state === "retired" && (p.volume === "" || !withData)) continue; | |
| 45 | if (now - (asked.get(o.id) ?? 0) < RETRY_MS) continue; | |
| 46 | asked.set(o.id, now); | |
| 47 | const gone = await retireForOrder(app, o.id, o.name, { withData, despiteClaim: true }); | |
| 48 | if (!gone.ok) { | |
| 49 | app.log.warn("a lapsed cloud forge could not be retired", { forge: o.name, says: gone.error.slice(0, 200) }); | |
| 50 | continue; | |
| 51 | } | |
| 52 | const until = new Date(lapsed.keepUntil).toISOString().slice(0, 10); | |
| 53 | noteOrder(app.db, o.id, withData ? "lapsed: its machine and its data are deleted" : `lapsed: its machine is deleted and its data is kept until ${until}`); | |
| 54 | done.push(o.name); | |
| 55 | } | |
| 56 | return done; | |
| 57 | } |
src/spawn/making.ts +17
| @@ -26,6 +26,7 @@ import { | ||
| 26 | 26 | type Order, |
| 27 | 27 | } from "../billing/orders.ts"; |
| 28 | 28 | import type { Place, PlanName } from "../cloud/places.ts"; |
| 29 | import { getPinned } from "../core/pinned.ts"; | |
| 29 | 30 | import { deleteSecret, resolveSecrets, setSecret } from "../core/secret_store.ts"; |
| 30 | 31 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 31 | 32 | import { during } from "../perf/jobs.ts"; |
| @@ -105,6 +106,22 @@ export const dropLink = (app: App, id: string): void => { | ||
| 105 | 106 | deleteSecret(app.db, "forge", "", linkName(id)); |
| 106 | 107 | }; |
| 107 | 108 | |
| 109 | /** | |
| 110 | * A cloud order's sealed link while its forge is unclaimed and the link still works; once the | |
| 111 | * forge reports claimed, or the claim expires, the sealed copy is deleted. | |
| 112 | */ | |
| 113 | export function openLink(app: App, o: Order): { readonly link?: string; readonly claimed: boolean } { | |
| 114 | const kept = keptLink(app, o.id); | |
| 115 | if (kept === undefined) return { claimed: false }; | |
| 116 | const p = getPinned(app.db, o.name); | |
| 117 | const claimed = p !== undefined && p.claimedAt !== ""; | |
| 118 | if (claimed || (p !== undefined && p.claimExpires !== "" && Date.parse(p.claimExpires) <= Date.now())) { | |
| 119 | dropLink(app, o.id); | |
| 120 | return { claimed }; | |
| 121 | } | |
| 122 | return { link: kept, claimed: false }; | |
| 123 | } | |
| 124 | ||
| 108 | 125 | const mailOf = (name: string, link: string) => ({ |
| 109 | 126 | subject: `Your forge ${name} is ready`, |
| 110 | 127 | text: [ |
src/web/pages/pricing.ts +33 −8
| @@ -9,7 +9,13 @@ | ||
| 9 | 9 | |
| 10 | 10 | import { setCookie } from "../../auth/cookies.ts"; |
| 11 | 11 | import { deliverLink, mayView, NO_PROVIDER, placeOrder, reconcileOrder, resendLink, type Refusal } from "../../actions/order.ts"; |
| 12 | import { lapseRule, lapseRuleWords } from "../../billing/lapse_rule.ts"; | |
| 12 | import { cloudLapseWords, lapseRule, lapseRuleWords } from "../../billing/lapse_rule.ts"; | |
| 13 | import { mailerOf } from "../../actions/verify.ts"; | |
| 14 | import { getBaseDomain } from "../../settings/pinned_domain.ts"; | |
| 15 | import { getPaidPlacement } from "../../settings/paid_placement.ts"; | |
| 16 | import { limitValue } from "../../settings/limits.ts"; | |
| 17 | import { getPinned, urlOf } from "../../core/pinned.ts"; | |
| 18 | import { openLink } from "../../spawn/making.ts"; | |
| 13 | 19 | import { AFTER_PAYMENT_STEPS, planWords, priceLine } from "../../billing/plan_words.ts"; |
| 14 | 20 | import { checkoutOf } from "../../billing/checkout.ts"; |
| 15 | 21 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; |
| @@ -36,6 +42,7 @@ import { placeChoiceView } from "../pinned.ts"; | ||
| 36 | 42 | import { placeChoice } from "../../spawn/making.ts"; |
| 37 | 43 | |
| 38 | 44 | const COOKIE = "forge_order"; |
| 45 | const NO_MAIL_STEP = "A link to open it is shown on the page after payment: keep that page or its address."; | |
| 39 | 46 | const REFRESH_JS = "setTimeout(function(){location.reload()},3000);"; |
| 40 | 47 | |
| 41 | 48 | interface Values { |
| @@ -45,6 +52,11 @@ interface Values { | ||
| 45 | 52 | readonly place: string; |
| 46 | 53 | } |
| 47 | 54 | |
| 55 | /** The lapse words: for a forge on its own machine (a paid placement on a cloud, or this order's own row), else the hosted ones. */ | |
| 56 | const lapseSays = (ctx: Ctx, cloud: boolean): string => (cloud ? cloudLapseWords(lapseRule(ctx.app.db), limitValue(ctx.app.db, "billing.retention_days")) : lapseRuleWords(lapseRule(ctx.app.db))); | |
| 57 | const paidOnCloud = (ctx: Ctx): boolean => getPaidPlacement(ctx.app.db).where === "cloud"; | |
| 58 | const mailOn = (ctx: Ctx): boolean => mailerOf(ctx.app, { id: "order" }) !== undefined; | |
| 59 | ||
| 48 | 60 | const isBuyer = (ctx: Ctx): boolean => ctx.auth.user === undefined || ctx.auth.user.kind === "user"; |
| 49 | 61 | |
| 50 | 62 | function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["field"], string>>): Html { |
| @@ -85,7 +97,7 @@ function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["fie | ||
| 85 | 97 | name: "name", |
| 86 | 98 | value: values.name, |
| 87 | 99 | required: true, |
| 88 | hint: `Its address: <name>--${childHost(ctx.app)}.`, | |
| 100 | hint: paidOnCloud(ctx) ? `Its address: <name>.${getBaseDomain(ctx.app.db)} on its own machine (free: <name>--${childHost(ctx.app)}).` : `Its address: <name>--${childHost(ctx.app)}.`, | |
| 89 | 101 | ...(errors["name"] ? { error: errors["name"] } : {}), |
| 90 | 102 | })} |
| 91 | 103 | ${selling |
| @@ -95,7 +107,7 @@ function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["fie | ||
| 95 | 107 | type: "email", |
| 96 | 108 | value: values.email, |
| 97 | 109 | autocomplete: "email", |
| 98 | hint: "The link to open your forge is shown after payment and sent here.", | |
| 110 | hint: mailOn(ctx) || !paidOnCloud(ctx) ? "The link to open your forge is shown after payment and sent here." : "The link to open your forge is shown after payment.", | |
| 99 | 111 | ...(errors["email"] ? { error: errors["email"] } : {}), |
| 100 | 112 | }) |
| 101 | 113 | : null} |
| @@ -104,8 +116,8 @@ function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["fie | ||
| 104 | 116 | </form> |
| 105 | 117 | <div class="muted small" data-after-pay> |
| 106 | 118 | <p>${buyable ? "After you pay:" : "How a paid plan is set up:"}</p> |
| 107 | <ol>${AFTER_PAYMENT_STEPS.map((l) => html`<li>${l}</li>`)}</ol> | |
| 108 | <p data-lapse="sleep" data-grace-days="${rule.graceDays}">${lapseRuleWords(rule)} <span data-legal><a href="/terms">Terms</a> · <a href="/privacy">Privacy</a></span></p> | |
| 119 | <ol>${AFTER_PAYMENT_STEPS.map((l, i) => html`<li>${i === 2 && paidOnCloud(ctx) && !mailOn(ctx) ? NO_MAIL_STEP : l}</li>`)}</ol> | |
| 120 | <p data-lapse="sleep" data-grace-days="${rule.graceDays}">${lapseSays(ctx, paidOnCloud(ctx))} <span data-legal><a href="/terms">Terms</a> · <a href="/privacy">Privacy</a></span></p> | |
| 109 | 121 | </div> |
| 110 | 122 | <p class="muted small">Paid already? ${ordered === undefined ? null : html`<a href="/pricing/done?order=${ordered}">Open your order</a> · `}<a href="/pricing/resend">Lost your link?</a></p> |
| 111 | 123 | </div>`; |
| @@ -192,7 +204,7 @@ async function doneView(ctx: Ctx): Promise<Response> { | ||
| 192 | 204 | const o = await reconcileOrder(ctx.app, id); |
| 193 | 205 | if (o === undefined) return notFoundPage(ctx); |
| 194 | 206 | const plain = (title: string, body: Html, status = 200): Response => { |
| 195 | const res = page({ ctx, title, body: html`<div class="narrow-wide" data-order="${o.state}">${pageHead(title)}<section class="settings-block">${body}${o.state === "failed" ? null : html`<p class="mt small" data-receipt-link><a href="/pricing/orders/${o.id}">Receipt</a></p>`}</section>${o.state === "failed" ? null : html`<p class="muted small" data-lapse="sleep">${lapseRuleWords(lapseRule(ctx.app.db))}</p>`}</div>` }, status); | |
| 207 | const res = page({ ctx, title, body: html`<div class="narrow-wide" data-order="${o.state}">${pageHead(title)}<section class="settings-block">${body}${o.state === "failed" ? null : html`<p class="mt small" data-receipt-link><a href="/pricing/orders/${o.id}">Receipt</a></p>`}</section>${o.state === "failed" ? null : html`<p class="muted small" data-lapse="sleep">${lapseSays(ctx, getPinned(ctx.app.db, o.name) !== undefined)}</p>`}${o.reason.startsWith("lapsed") ? html`<p role="status" data-lapsed>Payment lapsed: ${o.reason.slice(8)}. Ask the operator.</p>` : null}</div>` }, status); | |
| 196 | 208 | res.headers.set("cache-control", "no-store"); |
| 197 | 209 | return res; |
| 198 | 210 | }; |
| @@ -206,11 +218,17 @@ async function doneView(ctx: Ctx): Promise<Response> { | ||
| 206 | 218 | <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); |
| 207 | 219 | const given = await deliverLink(ctx.app, o); |
| 208 | 220 | if (given.kind === "link") |
| 209 | return plain(`${o.name} is ready`, html`${claimLinkBody(given.claimUrl, false)}${given.mailed ? html`<p class="small mt">It was also sent to ${o.email}.</p>` : null}`); | |
| 210 | if (given.kind === "claimed") return plain(`${o.name} is taken over`, html`<p>The link was used; sign in at <a href="${`https://${o.name}--${childHost(ctx.app)}`}">your forge</a>.</p>`); | |
| 221 | return plain(`${o.name} is ready`, html`${claimLinkBody(given.claimUrl, false)}${given.mailed ? html`<p class="small mt">It was also sent to ${o.email}.</p>` : given.kept && !given.mail ? html`<p class="small mt">Keep this page or its address: it shows the link until the forge is claimed.</p>` : null}`); | |
| 222 | if (given.kind === "claimed") return plain(`${o.name} is taken over`, html`<p>The link was used; sign in at <a href="${forgeUrl(ctx, o)}">your forge</a>.</p>`); | |
| 211 | 223 | return plain(`${o.name} is ready`, html`<p>The link was shown already, once.</p><p class="mt">${btn("Send it again by email", { href: "/pricing/resend", size: "sm" })}</p>`); |
| 212 | 224 | } |
| 213 | 225 | |
| 226 | /** Where a taken-over forge answers: its own machine's name, or the hosted address. */ | |
| 227 | const forgeUrl = (ctx: Ctx, o: Order): string => { | |
| 228 | const p = getPinned(ctx.app.db, o.name); | |
| 229 | return p !== undefined && p.host !== "" ? urlOf(p) : `https://${o.name}--${childHost(ctx.app)}`; | |
| 230 | }; | |
| 231 | ||
| 214 | 232 | function resendView(ctx: Ctx, says: string | undefined, values: Values): Html { |
| 215 | 233 | return html`<div class="narrow stack" data-resend> |
| 216 | 234 | ${pageHead("Lost your link?")} |
| @@ -266,6 +284,12 @@ function receiptOrder(ctx: Ctx): Order | undefined { | ||
| 266 | 284 | return o !== undefined && isReceiptable(o) ? o : undefined; |
| 267 | 285 | } |
| 268 | 286 | |
| 287 | /** For an admin: the order's claim link while its forge is unclaimed. */ | |
| 288 | const adminLink = (ctx: Ctx, o: Order): Html | null => { | |
| 289 | const open = o.state === "spawned" ? openLink(ctx.app, o) : undefined; | |
| 290 | return open?.link === undefined ? null : html`<p class="small" data-admin-link>Claim link: <code class="mono">${open.link}</code></p>`; | |
| 291 | }; | |
| 292 | ||
| 269 | 293 | // GET /pricing/orders/:id — the receipt: plan, amount, date and forge, from the order as stored. |
| 270 | 294 | export function receiptPage(ctx: Ctx): Response { |
| 271 | 295 | const o = receiptOrder(ctx); |
| @@ -284,6 +308,7 @@ export function receiptPage(ctx: Ctx): Response { | ||
| 284 | 308 | <div><dt>Forge</dt><dd data-fact="forge">${f.forge}</dd></div> |
| 285 | 309 | </dl> |
| 286 | 310 | <p class="muted small">Prices are as charged when the order was made.</p> |
| 311 | ${ctx.auth.user?.isAdmin === true ? adminLink(ctx, o) : null} | |
| 287 | 312 | <p class="mt">${btn("Download printable HTML", { href: `${base}?download=1`, size: "sm" })}</p></section> |
| 288 | 313 | </div>`, |
| 289 | 314 | }); |
test/order-cloud.test.ts +97 −4
| @@ -34,7 +34,12 @@ import { | ||
| 34 | 34 | import { createRepo } from "../src/actions/repos.ts"; |
| 35 | 35 | import { useCheckout, type CheckoutProvider } from "../src/billing/checkout.ts"; |
| 36 | 36 | import { getOrder } from "../src/billing/orders.ts"; |
| 37 | import { changesOf, getPinned } from "../src/core/pinned.ts"; | |
| 37 | import { changesOf, getPinned, markClaimed } from "../src/core/pinned.ts"; | |
| 38 | import { retireLapsedCloud } from "../src/spawn/lapse_cloud.ts"; | |
| 39 | import { priced, spendOf } from "../src/cloud/ceiling.ts"; | |
| 40 | import { defaultPlace } from "../src/actions/pinned.ts"; | |
| 41 | import { pricingDone, pricingPage } from "../src/web/pages/pricing.ts"; | |
| 42 | import type { Ctx } from "../src/http/context.ts"; | |
| 38 | 43 | import { createUser, getUserByName } from "../src/core/users.ts"; |
| 39 | 44 | import { ok } from "../src/kernel/result.ts"; |
| 40 | 45 | import { usePlacement } from "../src/spawn/door.ts"; |
| @@ -320,15 +325,24 @@ describe("a paid order on a cloud account", () => { | ||
| 320 | 325 | expect(given.kind === "link" && given.claimUrl).toStartWith( |
| 321 | 326 | "https://acme.forges.test/first-admin#", |
| 322 | 327 | ); |
| 328 | // Shown again every visit while unclaimed, mail or no mail. | |
| 329 | expect(await deliverLink(app, getOrder(app.db, o.id)!)).toMatchObject({ | |
| 330 | kind: "link", | |
| 331 | claimUrl: given.kind === "link" ? given.claimUrl : "", | |
| 332 | kept: true, | |
| 333 | mail: false, | |
| 334 | }); | |
| 335 | // Once the forge reports claimed, the sealed copy is deleted. | |
| 336 | markClaimed(app.db, "acme"); | |
| 323 | 337 | expect(await deliverLink(app, getOrder(app.db, o.id)!)).toEqual({ |
| 324 | kind: "shown", | |
| 338 | kind: "claimed", | |
| 325 | 339 | }); |
| 326 | 340 | expect( |
| 327 | 341 | app.db |
| 328 | 342 | .query( |
| 329 | "SELECT COUNT(*) AS n FROM secret WHERE name LIKE 'ORDER_CLAIM_%'", | |
| 343 | "SELECT COUNT(*) AS n FROM secret WHERE name LIKE 'ORDER_CLAIM_%' AND name = ?1", | |
| 330 | 344 | ) |
| 331 | .get(), | |
| 345 | .get(`ORDER_CLAIM_${o.id.toUpperCase()}`), | |
| 332 | 346 | ).toEqual({ n: 0 }); |
| 333 | 347 | expect(creates()).toBe(1); |
| 334 | 348 | }); |
| @@ -390,4 +404,83 @@ describe("a paid order on a cloud account", () => { | ||
| 390 | 404 | ); |
| 391 | 405 | expect(r).toMatchObject({ ok: false, error: { field: "name" } }); |
| 392 | 406 | }); |
| 407 | ||
| 408 | const ctxOf = (path: string, cookie = ""): Ctx => { | |
| 409 | const url = new URL(`https://forge.test${path}`); | |
| 410 | return { app, request: new Request(url.href, { headers: new Headers(cookie === "" ? {} : { cookie }) }), url, params: {}, auth: { user: undefined, scope: undefined, via: "none" }, theme: undefined } as Ctx; | |
| 411 | }; | |
| 412 | ||
| 413 | test("without mail, /pricing/done shows the link every visit until the forge is claimed, and says so", async () => { | |
| 414 | const placed = await placeOrder(app, { name: "keepme", plan: "small", email: "[email protected]", address: "198.51.100.150" }, new URL("https://forge.test/pricing")); | |
| 415 | if (!placed.ok) throw new Error(placed.error.message); | |
| 416 | const o = getOrder(app.db, placed.value.id)!; | |
| 417 | await settleSession(app, { id: o.sessionId, metadata: { order: o.id }, customer: "cus_k", subscription: "sub_k", payment_status: "paid" }); | |
| 418 | up.add("keepme"); | |
| 419 | askable(app, o.id); | |
| 420 | await reconcileOrder(app, o.id); | |
| 421 | const cookie = `forge_order=${o.id}.${placed.value.ticket}`; | |
| 422 | const visit = async () => (await pricingDone(ctxOf(`/pricing/done?order=${o.id}`, cookie))).text(); | |
| 423 | for (let i = 0; i < 2; i++) { | |
| 424 | const body = await visit(); | |
| 425 | expect(body).toContain("keepme.forges.test/first-admin#"); | |
| 426 | expect(body).toContain("it shows the link until the forge is claimed"); | |
| 427 | expect(body).not.toContain("also sent to"); | |
| 428 | } | |
| 429 | markClaimed(app.db, "keepme"); | |
| 430 | const after = await visit(); | |
| 431 | expect(after).not.toContain("first-admin#"); | |
| 432 | expect(after).toContain("The link was used"); | |
| 433 | }); | |
| 434 | ||
| 435 | test("a refunded cloud forge's machine is retired keeping its volume, then its volume is deleted after retention", async () => { | |
| 436 | const placed = await placeOrder(app, { name: "lapsing", plan: "small", email: "[email protected]", address: "198.51.100.151" }, new URL("https://forge.test/pricing")); | |
| 437 | if (!placed.ok) throw new Error(placed.error.message); | |
| 438 | const o = getOrder(app.db, placed.value.id)!; | |
| 439 | await settleSession(app, { id: o.sessionId, metadata: { order: o.id }, customer: "cus_l", subscription: "sub_l", payment_status: "paid" }); | |
| 440 | up.add("lapsing"); | |
| 441 | askable(app, o.id); | |
| 442 | await reconcileOrder(app, o.id); | |
| 443 | const now = Date.now(); | |
| 444 | expect(await retireLapsedCloud(app, now)).toEqual([]); | |
| 445 | app.db.query("INSERT INTO payment (id, subscription_id, customer_id, amount_minor, currency, status, at) VALUES ('in_l', 'sub_l', 'cus_l', 1000, 'usd', 'refunded', ?1)").run(new Date(now).toISOString()); | |
| 446 | const deletes = (what: string) => calls.filter((c) => c.method === "DELETE" && c.path.includes(what)).length; | |
| 447 | const volumes = deletes("/volumes"); | |
| 448 | expect(await retireLapsedCloud(app, now)).toEqual(["lapsing"]); | |
| 449 | expect(getPinned(app.db, "lapsing")).toMatchObject({ state: "retired" }); | |
| 450 | expect(getPinned(app.db, "lapsing")?.volume).not.toBe(""); | |
| 451 | expect(deletes("/volumes")).toBe(volumes); | |
| 452 | expect(getOrder(app.db, o.id)?.reason).toContain("its data is kept until"); | |
| 453 | const later = now + 3650 * 86_400_000; | |
| 454 | expect(await retireLapsedCloud(app, later)).toEqual(["lapsing"]); | |
| 455 | expect(getPinned(app.db, "lapsing")?.volume).toBe(""); | |
| 456 | expect(deletes("/volumes")).toBe(volumes + 1); | |
| 457 | expect(getOrder(app.db, o.id)?.reason).toContain("its machine and its data are deleted"); | |
| 458 | }); | |
| 459 | ||
| 460 | test("orders in flight count against the ceiling: of two buyers where one fits, the second is refused before payment", async () => { | |
| 461 | const place = defaultPlace(app, "digitalocean", "small").place!; | |
| 462 | const one = priced(app.db).forge(place.id)!; | |
| 463 | const spent = spendOf(app.db, "digitalocean", "main").monthlyCents; | |
| 464 | expect(setCeiling(app, admin(), "digitalocean", "main", Math.ceil((spent + one) / 100)).ok).toBe(true); | |
| 465 | const n = checkouts; | |
| 466 | const first = await placeOrder(app, { name: "fitsone", plan: "small", email: "[email protected]", address: "198.51.100.160" }, new URL("https://forge.test/pricing")); | |
| 467 | expect(first.ok).toBe(true); | |
| 468 | const second = await placeOrder(app, { name: "fitstwo", plan: "small", email: "[email protected]", address: "198.51.100.161" }, new URL("https://forge.test/pricing")); | |
| 469 | expect(second).toMatchObject({ ok: false }); | |
| 470 | expect(!second.ok && second.error.message).toContain("held to $"); | |
| 471 | expect(checkouts).toBe(n + 1); | |
| 472 | expect(setCeiling(app, admin(), "digitalocean", "main", 500).ok).toBe(true); | |
| 473 | }); | |
| 474 | ||
| 475 | test("/pricing describes a paid forge's address on its own machine for a cloud account, the hosted way otherwise", async () => { | |
| 476 | const text = async () => (await pricingPage(ctxOf("/pricing"))).text(); | |
| 477 | const cloud = await text(); | |
| 478 | expect(cloud).toContain("<name>.forges.test on its own machine"); | |
| 479 | expect(cloud).toContain("its machine is deleted and its data kept"); | |
| 480 | expect(changePaidPlacement(app, admin(), "hosted").ok).toBe(true); | |
| 481 | const hosted = await text(); | |
| 482 | expect(hosted).not.toContain("on its own machine"); | |
| 483 | expect(hosted).toContain("After that your forge sleeps and keeps its data"); | |
| 484 | expect(changePaidPlacement(app, admin(), "digitalocean/main").ok).toBe(true); | |
| 485 | }); | |
| 393 | 486 | }); |
new above
offline