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

Merged opened this in answer to

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

Merged

sold/sale-safe → main 0 commits

  • Merged. sold/sale-safe was merged into main as 34ce787.

Review

Sign in to review this change.
11 files changed +277 −31
src/actions/order.ts +15 −11
@@ -9,8 +9,9 @@
99 * admin retries it or refunds at the provider. Never an agent as buyer.
1010 *
1111 * 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.
1415 *
1516 * Where the forge runs is the door's one rule (`spawn/making.ts`): when paid forges run on a cloud
1617 * 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";
3435 import { FREE, getPlan, type Plan } from "../settings/plans.ts";
3536 import { reissueClaimFor } from "./spawn.ts";
3637 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";
3839
3940 export { makingWatch } from "../spawn/making.ts";
4041
@@ -246,7 +247,7 @@ export async function reconcileOrder(app: App, id: string): Promise<Order | unde
246247 }
247248
248249 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 }
250251 | { readonly kind: "shown" }
251252 | { readonly kind: "claimed" }
252253 | { readonly kind: "failed" };
@@ -254,19 +255,22 @@ export type Delivered =
254255 /** A spawned order's claim link, for the buyer who holds its ticket: made fresh, shown once, mailed when mail is on. */
255256 export async function deliverLink(app: App, o: Order): Promise<Delivered> {
256257 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 };
263265 }
266 if (open.claimed) return { kind: "claimed" };
267 if (!markShown(app.db, o.id, Date.now())) return { kind: "shown" };
264268 const made = await reissueClaimFor(app, o.name);
265269 if (!made.ok) {
266270 unmarkShown(app.db, o.id);
267271 return "reason" in made.error && made.error.reason === "claimed" ? { kind: "claimed" } : { kind: "failed" };
268272 }
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 };
270274 }
271275
272276 /** 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
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 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";
3537 import { MAX_ID, keptPlaces, pinOf } from "../cloud/places_read.ts";
3638 import { keptRate } from "../cloud/rates.ts";
3739 import { deleteARecord, upsertARecord, type Fetch } from "../cloud/providers.ts";
@@ -783,9 +785,9 @@ export function checkForOrder(app: App, orderId: string, name: string): Promise<
783785 * Retire a paid order's forge, as the order, keeping its data volume: refused for one it did not
784786 * deploy.
785787 */
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>> {
787789 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."));
789791 }
790792
791793 /**
@@ -794,7 +796,7 @@ export function retireForOrder(app: App, orderId: string, name: string): Promise
794796 * buyer pays (#16205). Reads only what the forge holds (the catalog it last read, the account,
795797 * the ceiling); nothing is asked of a provider, so a catalog never read is refused here too.
796798 */
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 {
798800 const t = targetOf(provider);
799801 if (t === undefined || t.status !== "first") return "That is not a target the forge knows.";
800802 const a = getCloudAccount(app.db, provider, account);
@@ -807,7 +809,24 @@ export function deployRoom(app: App, provider: string, account: string, plan: Pl
807809 const base = dearer || asked === "" ? undefined : pickPlace(app, provider, "", plan);
808810 if (base?.ok && at.value.costCents > base.value.costCents)
809811 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;
811830 }
812831
813832 /** 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
2727 * below none.
2828 */
2929 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[] {
177177 export function recentOrders(db: Database, limit = 20): Order[] {
178178 return db.query<Row, [number]>("SELECT * FROM forge_order WHERE state != 'pending' ORDER BY updated_at DESC LIMIT ?1").all(limit).map(fromRow);
179179 }
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(
168168 place: { readonly id: string; readonly size: string; readonly datacenter: string },
169169 counted = 0,
170170 prices: Priced = priced(app.db),
171 /** What orders in flight will cost, not yet in any row. */
172 held = 0,
171173 ): string | undefined {
172174 const who = `${provider}/${account}`;
173175 const id = place.id;
@@ -181,9 +183,9 @@ export function refusalAt(
181183 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.`;
182184 const { ceilingDollars, monthlyCents } = spendOf(app.db, provider, account, prices);
183185 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;
185187 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. ` +
187189 `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.`
188190 );
189191 }
src/spawn/cloud_placement.ts +1 −1
@@ -63,7 +63,7 @@ export function cloudPlacement(
6363 room() {
6464 const own = ownSource(app);
6565 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);
6767 return no === undefined ? undefined : { reason: "quota", message: no };
6868 },
6969 async place(plan) {
src/spawn/host.ts +2
@@ -5,6 +5,7 @@
55 * truth; BodyStore is only for placement capacity.
66 */
77
8 import { retireLapsedCloud } from "./lapse_cloud.ts";
89 import { childDirOf } from "../actions/spawn.ts";
910 import { createApp, type App } from "../app.ts";
1011 import { appsRuntime, type AppsRuntime } from "../apps/runtime.ts";
@@ -566,6 +567,7 @@ function keepSweeping(parent: App): void {
566567 const every = Math.max(1000, Math.min(60_000, Math.floor(idleAfterMs() / 4)));
567568 const timer = setInterval(() => void during("spawn-idle", async () => {
568569 await sleepLapsed(parent);
570 await retireLapsedCloud(parent);
569571 await sleepIdleChildren(parent);
570572 }, undefined, parent).catch(() => {}), every);
571573 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 {
2626 type Order,
2727 } from "../billing/orders.ts";
2828 import type { Place, PlanName } from "../cloud/places.ts";
29 import { getPinned } from "../core/pinned.ts";
2930 import { deleteSecret, resolveSecrets, setSecret } from "../core/secret_store.ts";
3031 import { err, ok, type Result } from "../kernel/result.ts";
3132 import { during } from "../perf/jobs.ts";
@@ -105,6 +106,22 @@ export const dropLink = (app: App, id: string): void => {
105106 deleteSecret(app.db, "forge", "", linkName(id));
106107 };
107108
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
108125 const mailOf = (name: string, link: string) => ({
109126 subject: `Your forge ${name} is ready`,
110127 text: [
src/web/pages/pricing.ts +33 −8
@@ -9,7 +9,13 @@
99
1010 import { setCookie } from "../../auth/cookies.ts";
1111 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";
1319 import { AFTER_PAYMENT_STEPS, planWords, priceLine } from "../../billing/plan_words.ts";
1420 import { checkoutOf } from "../../billing/checkout.ts";
1521 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
@@ -36,6 +42,7 @@ import { placeChoiceView } from "../pinned.ts";
3642 import { placeChoice } from "../../spawn/making.ts";
3743
3844 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.";
3946 const REFRESH_JS = "setTimeout(function(){location.reload()},3000);";
4047
4148 interface Values {
@@ -45,6 +52,11 @@ interface Values {
4552 readonly place: string;
4653 }
4754
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
4860 const isBuyer = (ctx: Ctx): boolean => ctx.auth.user === undefined || ctx.auth.user.kind === "user";
4961
5062 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
8597 name: "name",
8698 value: values.name,
8799 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)}.`,
89101 ...(errors["name"] ? { error: errors["name"] } : {}),
90102 })}
91103 ${selling
@@ -95,7 +107,7 @@ function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["fie
95107 type: "email",
96108 value: values.email,
97109 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.",
99111 ...(errors["email"] ? { error: errors["email"] } : {}),
100112 })
101113 : null}
@@ -104,8 +116,8 @@ function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["fie
104116 </form>
105117 <div class="muted small" data-after-pay>
106118 <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>
109121 </div>
110122 <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>
111123 </div>`;
@@ -192,7 +204,7 @@ async function doneView(ctx: Ctx): Promise<Response> {
192204 const o = await reconcileOrder(ctx.app, id);
193205 if (o === undefined) return notFoundPage(ctx);
194206 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);
196208 res.headers.set("cache-control", "no-store");
197209 return res;
198210 };
@@ -206,11 +218,17 @@ async function doneView(ctx: Ctx): Promise<Response> {
206218 <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);
207219 const given = await deliverLink(ctx.app, o);
208220 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>`);
211223 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>`);
212224 }
213225
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
214232 function resendView(ctx: Ctx, says: string | undefined, values: Values): Html {
215233 return html`<div class="narrow stack" data-resend>
216234 ${pageHead("Lost your link?")}
@@ -266,6 +284,12 @@ function receiptOrder(ctx: Ctx): Order | undefined {
266284 return o !== undefined && isReceiptable(o) ? o : undefined;
267285 }
268286
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
269293 // GET /pricing/orders/:id — the receipt: plan, amount, date and forge, from the order as stored.
270294 export function receiptPage(ctx: Ctx): Response {
271295 const o = receiptOrder(ctx);
@@ -284,6 +308,7 @@ export function receiptPage(ctx: Ctx): Response {
284308 <div><dt>Forge</dt><dd data-fact="forge">${f.forge}</dd></div>
285309 </dl>
286310 <p class="muted small">Prices are as charged when the order was made.</p>
311 ${ctx.auth.user?.isAdmin === true ? adminLink(ctx, o) : null}
287312 <p class="mt">${btn("Download printable HTML", { href: `${base}?download=1`, size: "sm" })}</p></section>
288313 </div>`,
289314 });
test/order-cloud.test.ts +97 −4
@@ -34,7 +34,12 @@ import {
3434 import { createRepo } from "../src/actions/repos.ts";
3535 import { useCheckout, type CheckoutProvider } from "../src/billing/checkout.ts";
3636 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";
3843 import { createUser, getUserByName } from "../src/core/users.ts";
3944 import { ok } from "../src/kernel/result.ts";
4045 import { usePlacement } from "../src/spawn/door.ts";
@@ -320,15 +325,24 @@ describe("a paid order on a cloud account", () => {
320325 expect(given.kind === "link" && given.claimUrl).toStartWith(
321326 "https://acme.forges.test/first-admin#",
322327 );
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");
323337 expect(await deliverLink(app, getOrder(app.db, o.id)!)).toEqual({
324 kind: "shown",
338 kind: "claimed",
325339 });
326340 expect(
327341 app.db
328342 .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",
330344 )
331 .get(),
345 .get(`ORDER_CLAIM_${o.id.toUpperCase()}`),
332346 ).toEqual({ n: 0 });
333347 expect(creates()).toBe(1);
334348 });
@@ -390,4 +404,83 @@ describe("a paid order on a cloud account", () => {
390404 );
391405 expect(r).toMatchObject({ ok: false, error: { field: "name" } });
392406 });
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("&lt;name&gt;.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 });
393486 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs