Public: anyone can read this; the crew can change it.
A forge whose payment lapses sleeps after a grace period, and no webhook ever deletes one #11372
mason/forge:mason/11140-a-forge-whose-payment-lapses-sleeps-afte → main 13 commits fork
17 files
changed +568
−10
docs/MCP.md +1 −1
| @@ -133,7 +133,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`; | ||
| 133 | 133 | | `land_past_gate` | — | Land one pull past a broken gate, with a recorded reason; an owner's only | 321 | |
| 134 | 134 | | `lift` | — | Lift an issue out from behind the Later gate | 214 | |
| 135 | 135 | | `limb` | `defer`, `resume`, `close`, `raise`, `lower`, `replan`, `takeback`, `undo` | Act on a limb by `action` | 532 | |
| 136 | | `limits` | — | Every limit the owner can hit, value and bounds | 977 | | |
| 136 | | `limits` | — | Every limit the owner can hit, value and bounds | 1018 | | |
| 137 | 137 | | `maintenance` | `status`, `prepare`, `resume`, `pause-duty`, `resume-duty` | Prepare the forge for a power-off, check the drain, or end maintenance (admin) | 308 | |
| 138 | 138 | | `make_it_yours` | — | Fork an app you can see: code and history, following the original | 337 | |
| 139 | 139 | | `map` | — | An app's plan: ready or waiting, critical path, crew, parkedTwice; `done` adds closed; `first: N` ranks N first | 375 | |
docs/features/billing-lapse.md added +13
| @@ -0,0 +1,13 @@ | ||
| 1 | # A lapsed payment sleeps a forge (#11140) | |
| 2 | ||
| 3 | Stopping service is how payment is enforced; losing someone's work is never the penalty. Code: `src/billing/lapse.ts` (reads only), the gate in `src/spawn/host.ts` (`wakeGate`, `resolveHostedChildApp`, `sleepLapsed`), the page in `src/web/pages/lapsed.ts`. | |
| 4 | ||
| 5 | - **Grace (`past_due`):** the forge keeps running. `/forges` and the terminal's "Forges you sent" (the operator) show "Payment late" with the date it runs to, and one pay action. Length: the limit `billing.grace_days`, default 7 (`/admin/limits`). | |
| 6 | - **After grace, or on cancellation (`none`):** the forge is put to sleep (at its next request, at the webhook, and by the sweep) and cannot wake. A browser gets a plain page (that it sleeps and why, *Pay again* when a buy link is set, how to export); no date is shown to a visitor; the operator sees "data kept to" on `/forges` and in the terminal. A git client or API call gets the same words, status 402. Its apps answer 503. | |
| 7 | - **Paying again:** the webhook writes `active`; the next request wakes the forge as it was. | |
| 8 | - **Data:** kept at least `billing.keep_days` (default 30, never below 30) after the lapse. Nothing removes it automatically; removal is an admin's own action (`/forges/<name>/remove`). A test reads the webhook path's sources for any delete. | |
| 9 | - **Untouched:** a forge with no row, on the free plan, or whose entitlement is `granted` or a gift code. Only `source: stripe` rows can lapse. | |
| 10 | - **Pay link:** the buy link for the forge's size (Settings → Billing). With none set the page says to ask the operator, and the operator's row says no link is set. | |
| 11 | - **Cost:** the request path reads a forge's lapse at most once every 2 seconds (`src/billing/lapse_seen.ts`); writing an entitlement drops the reads at once. The two limits are read in one query. | |
| 12 | - **Terminal:** sleeping stops the forge, so its own terminal stops with it. | |
| 13 | - **Not yet:** the banner inside the lapsed forge itself for its own admins (the entitlement lives in this forge's database, not the child's). |
src/actions/limits.ts +3 −2
| @@ -13,7 +13,7 @@ import { | ||
| 13 | 13 | LIMIT_KEYS, |
| 14 | 14 | isLimitKey, |
| 15 | 15 | limitChanges, |
| 16 | limitState, | |
| 16 | limitStates, | |
| 17 | 17 | setLimit, |
| 18 | 18 | type LimitChange, |
| 19 | 19 | type LimitDef, |
| @@ -39,11 +39,12 @@ export function listLimits( | ||
| 39 | 39 | ): Result<{ limits: LimitRow[]; changes: LimitChange[] }, "not_found"> { |
| 40 | 40 | const who = admin(actor); |
| 41 | 41 | if (!who.ok) return who; |
| 42 | const states = limitStates(app.db); | |
| 42 | 43 | return ok({ |
| 43 | 44 | limits: LIMIT_KEYS.map((key) => ({ |
| 44 | 45 | ...LIMITS[key], |
| 45 | 46 | key, |
| 46 | ...limitState(app.db, key), | |
| 47 | ...states[key], | |
| 47 | 48 | })), |
| 48 | 49 | changes: limitChanges(app.db), |
| 49 | 50 | }); |
src/billing/lapse.ts added +80
| @@ -0,0 +1,80 @@ | ||
| 1 | /** | |
| 2 | * A lapsed payment as plain data (#11140): stopping service is how payment is | |
| 3 | * enforced, and losing someone's work is never the penalty. This module only | |
| 4 | * reads: it answers whether a forge runs, is in its grace period, or sleeps, | |
| 5 | * and until when its data is kept. It removes nothing, and nothing here or in | |
| 6 | * the webhook that calls it can: removal is an admin's own action (`spawn/manage.ts`). | |
| 7 | * | |
| 8 | * Only a forge a payment provider manages (`source: stripe`) can lapse. A forge | |
| 9 | * with no row, on the free plan, or granted by hand or by a code reads `running`. | |
| 10 | */ | |
| 11 | ||
| 12 | import type { Database } from "bun:sqlite"; | |
| 13 | import { getBillingLinks } from "../settings/billing.ts"; | |
| 14 | import { limitValues } from "../settings/limits.ts"; | |
| 15 | import { FRESH_MS, seenFor } from "./lapse_seen.ts"; | |
| 16 | import { getStored } from "./store.ts"; | |
| 17 | ||
| 18 | const DAY_MS = 86_400_000; | |
| 19 | ||
| 20 | export type Lapse = | |
| 21 | | { state: "running" } | |
| 22 | | { state: "grace"; since: number; graceEnds: number } | |
| 23 | /** `since` is when service stopped; its data is kept at least until `keptUntil`. */ | |
| 24 | | { state: "asleep"; since: number; keptUntil: number }; | |
| 25 | ||
| 26 | /** When the forge's current status began: the first change of the unbroken run of changes ending in it. */ | |
| 27 | function statusSince(db: Database, forge: string, status: string): number | undefined { | |
| 28 | const at = db | |
| 29 | .query<{ at: string | null }, [string, string]>( | |
| 30 | `SELECT MIN(at) AS at FROM entitlement_change WHERE forge = ?1 | |
| 31 | AND id > COALESCE((SELECT MAX(id) FROM entitlement_change WHERE forge = ?1 AND to_status != ?2), 0)`, | |
| 32 | ) | |
| 33 | .get(forge, status)?.at; | |
| 34 | const t = at === null || at === undefined ? NaN : Date.parse(at); | |
| 35 | return Number.isFinite(t) ? t : undefined; | |
| 36 | } | |
| 37 | ||
| 38 | export function lapseOf(db: Database, forge: string, now = Date.now()): Lapse { | |
| 39 | const stored = getStored(db, forge); | |
| 40 | if (stored === undefined || stored.source !== "stripe" || stored.status === "active") return { state: "running" }; | |
| 41 | const since = statusSince(db, forge, stored.status) ?? Date.parse(stored.updatedAt); | |
| 42 | const days = limitValues(db, ["billing.keep_days", "billing.grace_days"]); | |
| 43 | const keep = days["billing.keep_days"] * DAY_MS; | |
| 44 | if (stored.status === "none") return { state: "asleep", since, keptUntil: since + keep }; | |
| 45 | const graceEnds = since + days["billing.grace_days"] * DAY_MS; | |
| 46 | return now >= graceEnds ? { state: "asleep", since: graceEnds, keptUntil: graceEnds + keep } : { state: "grace", since, graceEnds }; | |
| 47 | } | |
| 48 | ||
| 49 | /** `lapseOf` for the request path: reused for 2 seconds (`lapse_seen.ts`), and dropped at once when an entitlement is written. */ | |
| 50 | export function lapseNow(db: Database, forge: string, now = Date.now()): Lapse { | |
| 51 | const mine = seenFor(db); | |
| 52 | const hit = mine.get(forge); | |
| 53 | if (hit !== undefined && now >= hit.at && now - hit.at < FRESH_MS) return hit.lapse; | |
| 54 | const lapse = lapseOf(db, forge, now); | |
| 55 | mine.set(forge, { at: now, lapse }); | |
| 56 | return lapse; | |
| 57 | } | |
| 58 | ||
| 59 | /** Where this forge's owner pays: the buy link for its size, when the operator set one; else nowhere. */ | |
| 60 | export function payAgainHref(db: Database, size: string | undefined): string | undefined { | |
| 61 | return getBillingLinks(db)[(size ?? "small") as "small"]; | |
| 62 | } | |
| 63 | ||
| 64 | /** The ask when no buy link is set: this forge cannot say where to pay, its operator can. */ | |
| 65 | export const ASK_OPERATOR = "No payment link is set here: ask the operator of this forge to pay."; | |
| 66 | ||
| 67 | const day = (ms: number): string => new Date(ms).toISOString().slice(0, 10); | |
| 68 | ||
| 69 | /** A lapse in plain words for the operator's row: a short state, and the date that matters. */ | |
| 70 | export function lapseBadge(l: Exclude<Lapse, { state: "running" }>): { state: string; until: string } { | |
| 71 | return l.state === "grace" ? { state: "Payment late", until: `runs to ${day(l.graceEnds)}` } : { state: "Asleep, unpaid", until: `data kept to ${day(l.keptUntil)}` }; | |
| 72 | } | |
| 73 | ||
| 74 | /** What a visitor to an asleep forge is told: that it sleeps and why, and how to take the data. No dates: those are the operator's. */ | |
| 75 | export function lapseWords(name: string): { what: string; export: string } { | |
| 76 | return { | |
| 77 | what: `${name} is asleep because its payment lapsed. Nothing was deleted, and paying again wakes it as it was.`, | |
| 78 | export: "To take your work with you instead, ask the operator of this forge for an export of its data.", | |
| 79 | }; | |
| 80 | } |
src/billing/lapse_seen.ts added +24
| @@ -0,0 +1,24 @@ | ||
| 1 | /** | |
| 2 | * The reads of each forge's lapse that a request may reuse (#11140): a child's | |
| 3 | * every request asks, and the answer changes only when its entitlement is | |
| 4 | * written (which drops them all, `store.ts`) or a grace period runs out. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { Database } from "bun:sqlite"; | |
| 8 | import type { Lapse } from "./lapse.ts"; | |
| 9 | ||
| 10 | /** How long a read is reused. */ | |
| 11 | export const FRESH_MS = 2000; | |
| 12 | ||
| 13 | const seen = new WeakMap<Database, Map<string, { at: number; lapse: Lapse }>>(); | |
| 14 | ||
| 15 | export function seenFor(db: Database): Map<string, { at: number; lapse: Lapse }> { | |
| 16 | let mine = seen.get(db); | |
| 17 | if (mine === undefined) seen.set(db, (mine = new Map())); | |
| 18 | return mine; | |
| 19 | } | |
| 20 | ||
| 21 | /** Drop every reused read: an entitlement changed, or a test moved time. */ | |
| 22 | export function forgetLapses(db: Database): void { | |
| 23 | seen.get(db)?.clear(); | |
| 24 | } |
src/billing/store.ts +2
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | */ |
| 9 | 9 | |
| 10 | 10 | import type { Database } from "bun:sqlite"; |
| 11 | import { forgetLapses } from "./lapse_seen.ts"; | |
| 11 | 12 | import type { Entitlement, EntitlementStatus } from "./types.ts"; |
| 12 | 13 | |
| 13 | 14 | export interface Stored extends Entitlement { |
| @@ -90,6 +91,7 @@ export function putEntitlement(db: Database, p: Put, size: string, actorId: stri | ||
| 90 | 91 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)`, |
| 91 | 92 | ).run(p.forge, before?.plan ?? size, p.plan, before?.status ?? "active", p.status, p.source, actorId, at); |
| 92 | 93 | })(); |
| 94 | forgetLapses(db); | |
| 93 | 95 | return entitlementOf(db, p.forge, size); |
| 94 | 96 | } |
| 95 | 97 |
src/billing/sync.ts +4
| @@ -10,6 +10,8 @@ | ||
| 10 | 10 | |
| 11 | 11 | import type { App } from "../app.ts"; |
| 12 | 12 | import { listChildrenNow } from "../actions/spawn.ts"; |
| 13 | import { sleepChild } from "../spawn/host.ts"; | |
| 14 | import { lapseOf } from "./lapse.ts"; | |
| 13 | 15 | import { tellPlan } from "./notice.ts"; |
| 14 | 16 | import { openKey } from "./connection.ts"; |
| 15 | 17 | import { getStored, putEntitlement } from "./store.ts"; |
| @@ -51,6 +53,8 @@ export async function syncSubscription(app: App, id: string | undefined): Promis | ||
| 51 | 53 | if (put === undefined) return; |
| 52 | 54 | const size = listChildrenNow(app).find((c) => c.name === put.forge)?.size ?? getStored(app.db, put.forge)?.plan ?? "small"; |
| 53 | 55 | putEntitlement(app.db, put, size, "stripe"); |
| 56 | // A lapse stops service now, not at the next request; it only stops it (#11140). | |
| 57 | if (lapseOf(app.db, put.forge).state === "asleep") await sleepChild(app, put.forge).catch(() => false); | |
| 54 | 58 | tellPlan(app, put.forge); |
| 55 | 59 | }); |
| 56 | 60 | return failed; |
src/http/stripe_hook.ts +1
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | * A `customer.subscription.*` or `invoice.*` event only names a subscription: the |
| 11 | 11 | * hook re-reads it from Stripe and writes the entitlement from that, one |
| 12 | 12 | * subscription at a time, so events out of order end on the current state. |
| 13 | * A lapse puts the forge to sleep (`billing/lapse.ts`); no event removes anything. | |
| 13 | 14 | */ |
| 14 | 15 | |
| 15 | 16 | import type { App } from "../app.ts"; |
src/settings/limits.ts +53
| @@ -52,6 +52,8 @@ export type LimitKey = | ||
| 52 | 52 | | "model_review.auto" |
| 53 | 53 | | "model_review.min_landed" |
| 54 | 54 | | "model_review.slack_pct" |
| 55 | | "billing.grace_days" | |
| 56 | | "billing.keep_days" | |
| 55 | 57 | | "shell_idle_minutes"; |
| 56 | 58 | |
| 57 | 59 | export interface LimitDef { |
| @@ -304,6 +306,22 @@ export const LIMITS: Record<LimitKey, LimitDef> = { | ||
| 304 | 306 | max: 100, |
| 305 | 307 | reason: "Past this the weekly review undoes its own change, so quality is the bar the saving is held to.", |
| 306 | 308 | }, |
| 309 | "billing.grace_days": { | |
| 310 | label: "Days a forge keeps running after its payment is past due", | |
| 311 | unit: "days", | |
| 312 | default: 7, | |
| 313 | min: 0, | |
| 314 | max: 90, | |
| 315 | reason: "A late card is usually a mistake, so service continues for a while; after it the forge sleeps, which is how payment is enforced.", | |
| 316 | }, | |
| 317 | "billing.keep_days": { | |
| 318 | label: "Days at least that a lapsed forge keeps its data", | |
| 319 | unit: "days", | |
| 320 | default: 30, | |
| 321 | min: 30, | |
| 322 | max: 3650, | |
| 323 | reason: "Stopping service is the penalty for not paying; losing someone's work never is, so nothing is removed automatically and never before this.", | |
| 324 | }, | |
| 307 | 325 | shell_idle_minutes: { |
| 308 | 326 | label: "Minutes a machine shell may be silent before it stops", |
| 309 | 327 | unit: "minutes", |
| @@ -374,6 +392,41 @@ export function limitValue(db: Database, key: LimitKey): number { | ||
| 374 | 392 | return stored(db, key) ?? LIMITS[key].default; |
| 375 | 393 | } |
| 376 | 394 | |
| 395 | /** The stored value of every plain (non-capacity) limit in one read, valid ones only. */ | |
| 396 | function storedAll(db: Database): Map<string, number> { | |
| 397 | const out = new Map<string, number>(); | |
| 398 | for (const row of db.query<{ key: string; value: string }, []>("SELECT key, value FROM forge_setting WHERE key LIKE 'limit.%'").all()) { | |
| 399 | const key = row.key.slice("limit.".length); | |
| 400 | if (!isLimitKey(key) || !/^\d+$/.test(row.value)) continue; | |
| 401 | const n = Number(row.value); | |
| 402 | if (validLimit(key, n)) out.set(key, n); | |
| 403 | } | |
| 404 | return out; | |
| 405 | } | |
| 406 | ||
| 407 | /** The values of several limits in one read: what `limitValue` answers for each, without a query apiece. */ | |
| 408 | export function limitValues<K extends LimitKey>(db: Database, keys: readonly K[]): Record<K, number> { | |
| 409 | const all = storedAll(db); | |
| 410 | const out = {} as Record<K, number>; | |
| 411 | for (const key of keys) out[key] = capacityKey(key) !== undefined ? limitValue(db, key) : (all.get(key) ?? LIMITS[key].default); | |
| 412 | return out; | |
| 413 | } | |
| 414 | ||
| 415 | /** `limitState` for every limit, the stored ones read once between them. */ | |
| 416 | export function limitStates(db: Database): Record<LimitKey, { value: number; isSet: boolean; defaultValue: number }> { | |
| 417 | const all = storedAll(db); | |
| 418 | const out = {} as Record<LimitKey, { value: number; isSet: boolean; defaultValue: number }>; | |
| 419 | for (const key of LIMIT_KEYS) { | |
| 420 | if (capacityKey(key) !== undefined) { | |
| 421 | out[key] = limitState(db, key); | |
| 422 | continue; | |
| 423 | } | |
| 424 | const set = all.get(key); | |
| 425 | out[key] = { value: set ?? LIMITS[key].default, isSet: set !== undefined, defaultValue: LIMITS[key].default }; | |
| 426 | } | |
| 427 | return out; | |
| 428 | } | |
| 429 | ||
| 377 | 430 | /** Whether an admin has set `key` (rather than it being the default). */ |
| 378 | 431 | export function limitIsSet(db: Database, key: LimitKey): boolean { |
| 379 | 432 | const cap = capacityKey(key); |
src/spawn/clients.ts +13
| @@ -20,6 +20,7 @@ import { childAwake, hostedChildApps } from "./host.ts"; | ||
| 20 | 20 | import { hasAdmin, linkOf, spawnedOrg, type LinkInfo, type LinkState } from "./claim.ts"; |
| 21 | 21 | import { lastHeard, type Beat } from "./heartbeat.ts"; |
| 22 | 22 | import { reachOf, reachWords, type ChildReach } from "./reach.ts"; |
| 23 | import { lapseNow, payAgainHref, type Lapse } from "../billing/lapse.ts"; | |
| 23 | 24 | import type { Size } from "./sizes.ts"; |
| 24 | 25 | import { forgeUse, type ForgeUse } from "./usage.ts"; |
| 25 | 26 | |
| @@ -71,6 +72,10 @@ export interface ClientRow { | ||
| 71 | 72 | readonly lastHeartbeatAt: string | null; |
| 72 | 73 | /** The first step its person has not taken, read from the child's heartbeat. */ |
| 73 | 74 | readonly nextStep: NextStep; |
| 75 | /** Whether its payment has lapsed (`billing/lapse.ts`); absent reads as running. */ | |
| 76 | readonly lapse?: Lapse; | |
| 77 | /** Where its owner pays again when the operator set a buy link for its size. */ | |
| 78 | readonly payHref?: string; | |
| 74 | 79 | } |
| 75 | 80 | |
| 76 | 81 | export type NextStepKey = "unreported" | "claim" | "everyday" | "tell" | "going"; |
| @@ -207,6 +212,13 @@ function ask(app: App, child: Child): Promise<ForgeState | undefined> { | ||
| 207 | 212 | return asked; |
| 208 | 213 | } |
| 209 | 214 | |
| 215 | /** A forge's lapse, and where to pay when it is not running and a buy link is set. */ | |
| 216 | function lapseView(app: App, name: string, size: string | undefined, now: number): { lapse: Lapse; payHref?: string } { | |
| 217 | const lapse = lapseNow(app.db, name, now); | |
| 218 | const payHref = lapse.state === "running" ? undefined : payAgainHref(app.db, size); | |
| 219 | return payHref === undefined ? { lapse } : { lapse, payHref }; | |
| 220 | } | |
| 221 | ||
| 210 | 222 | /** |
| 211 | 223 | * Every child this forge sent, newest first. A child never heard from is |
| 212 | 224 | * asked now (all at once, each for at most two seconds); one heard from |
| @@ -250,6 +262,7 @@ export async function clientRows(app: App): Promise<ClientRow[]> { | ||
| 250 | 262 | lastHeartbeatAt: beats[i] === undefined ? null : new Date(beats[i]!.receivedAt).toISOString(), |
| 251 | 263 | link: states[i]?.link ?? null, |
| 252 | 264 | nextStep: nextStepOf(states[i]?.claimed ?? null, beats[i]?.beat), |
| 265 | ...lapseView(app, c.name, c.size, now), | |
| 253 | 266 | })), |
| 254 | 267 | now, |
| 255 | 268 | ); |
src/spawn/host.ts +41 −2
| @@ -5,7 +5,7 @@ | ||
| 5 | 5 | * truth; BodyStore is only for placement capacity. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { childDirOf } from "../actions/spawn.ts"; | |
| 8 | import { childDirOf, listChildrenNow } from "../actions/spawn.ts"; | |
| 9 | 9 | import { createApp, type App } from "../app.ts"; |
| 10 | 10 | import { appsRuntime, type AppsRuntime } from "../apps/runtime.ts"; |
| 11 | 11 | import { resolveAppHost, type AppSocket, type AppTarget } from "../apps/proxy.ts"; |
| @@ -31,6 +31,8 @@ import { floorRefusal } from "./disk_floor.ts"; | ||
| 31 | 31 | import { limitValue } from "../settings/limits.ts"; |
| 32 | 32 | import { awakeRefusal, idleAfterMs, WakeRate } from "./sleep.ts"; |
| 33 | 33 | import { wakingResponse } from "../web/pages/waking.ts"; |
| 34 | import { lapseNow, lapseOf, lapseWords } from "../billing/lapse.ts"; | |
| 35 | import { lapsedResponse } from "../web/pages/lapsed.ts"; | |
| 34 | 36 | import { takeDoor } from "../http/strangers.ts"; |
| 35 | 37 | import { vouched } from "./vouch.ts"; |
| 36 | 38 | import { during } from "../perf/jobs.ts"; |
| @@ -203,6 +205,17 @@ export async function sleepIdleChildren(parent: App, idleMs = idleAfterMs(), now | ||
| 203 | 205 | return asleep; |
| 204 | 206 | } |
| 205 | 207 | |
| 208 | /** Put to sleep every awake child whose payment has lapsed (#11140); their data stays. Answers the names. */ | |
| 209 | export async function sleepLapsed(parent: App): Promise<string[]> { | |
| 210 | const asleep: string[] = []; | |
| 211 | for (const child of listChildrenNow(parent)) { | |
| 212 | if (lapseOf(parent.db, child.name).state !== "asleep" || !childAwake(parent, child.name)) continue; | |
| 213 | if (await sleepChild(parent, child.name)) asleep.push(child.name); | |
| 214 | } | |
| 215 | for (const name of asleep) parent.log.info("child forge asleep, payment lapsed", { name }); | |
| 216 | return asleep; | |
| 217 | } | |
| 218 | ||
| 206 | 219 | /** |
| 207 | 220 | * Below the disk floor (`spawn/disk_floor.ts`) no child forge stays awake: |
| 208 | 221 | * every hosted child closes and every cell stops, busy or not, so nothing |
| @@ -256,6 +269,21 @@ export async function sleepChild(parent: App, name: string): Promise<boolean> { | ||
| 256 | 269 | return true; |
| 257 | 270 | } |
| 258 | 271 | |
| 272 | const lapsing = new WeakMap<App, Set<Promise<unknown>>>(); | |
| 273 | ||
| 274 | /** A request met a lapsed forge that is awake: sleep it without making the request wait. */ | |
| 275 | function sleepLapsedChild(parent: App, name: string): void { | |
| 276 | let mine = lapsing.get(parent); | |
| 277 | if (mine === undefined) lapsing.set(parent, (mine = new Set())); | |
| 278 | const going: Promise<unknown> = sleepChild(parent, name).catch(() => {}).finally(() => mine.delete(going)); | |
| 279 | mine.add(going); | |
| 280 | } | |
| 281 | ||
| 282 | /** Resolves once every sleep a request began for a lapsed forge has closed it (tests, shutdown). */ | |
| 283 | export async function settleLapseSleeps(parent: App): Promise<void> { | |
| 284 | await Promise.all([...(lapsing.get(parent) ?? [])]); | |
| 285 | } | |
| 286 | ||
| 259 | 287 | /** Whether a child is awake: open in this process or running in a cell. */ |
| 260 | 288 | export function childAwake(parent: App, name: string): boolean { |
| 261 | 289 | const ledger = readLedgerSync(parent, name); |
| @@ -283,7 +311,7 @@ async function closeOne(parent: App, cache: Map<string, App>, bodyId: string, ch | ||
| 283 | 311 | function keepSweeping(parent: App): void { |
| 284 | 312 | if (sweepers.has(parent)) return; |
| 285 | 313 | const every = Math.max(1000, Math.min(60_000, Math.floor(idleAfterMs() / 4))); |
| 286 | const timer = setInterval(() => void during("spawn-idle", () => sleepIdleChildren(parent)).catch(() => {}), every); | |
| 314 | const timer = setInterval(() => void during("spawn-idle", async () => (await sleepIdleChildren(parent), await sleepLapsed(parent))).catch(() => {}), every); | |
| 287 | 315 | timer.unref?.(); |
| 288 | 316 | sweepers.set(parent, timer); |
| 289 | 317 | } |
| @@ -333,6 +361,12 @@ export function wakeGate(parent: App, request: Request): Response | undefined { | ||
| 333 | 361 | if (ledger === undefined || !ledger.done) return undefined; |
| 334 | 362 | keepSweeping(parent); |
| 335 | 363 | keepWatchingFloor(parent); |
| 364 | // A lapsed payment: asleep and unwakeable until it is paid; the data stays (#11140). | |
| 365 | const lapse = lapseNow(parent.db, name); | |
| 366 | if (lapse.state === "asleep") { | |
| 367 | if (isAwakeBody(parent, ledger.bodyId)) sleepLapsedChild(parent, name); | |
| 368 | return lapsedResponse(parent, request, name, lapse, ledger.size); | |
| 369 | } | |
| 336 | 370 | // Below the disk floor an awake child is put to sleep now, not at the next look, |
| 337 | 371 | // and this request is answered with why: it writes nothing (#10873). |
| 338 | 372 | const floor = floorRefusal(parent.config.dataDir); |
| @@ -601,6 +635,11 @@ export async function resolveHostedChildApp( | ||
| 601 | 635 | if (!CHILD_NAME.test(name)) continue; |
| 602 | 636 | const ledger = readLedgerSync(parent, name); |
| 603 | 637 | if (ledger === undefined || !ledger.done) continue; |
| 638 | const lapse = lapseNow(parent.db, name); | |
| 639 | if (lapse.state === "asleep") { | |
| 640 | if (isAwakeBody(parent, ledger.bodyId)) sleepLapsedChild(parent, name); | |
| 641 | return { refused: lapseWords(name).what }; | |
| 642 | } | |
| 604 | 643 | if (!isAwakeBody(parent, ledger.bodyId)) { |
| 605 | 644 | const refused = startRefused(parent, ledger); |
| 606 | 645 | if (refused !== undefined) return { refused }; |
src/tui/screens/forges.ts +17 −3
| @@ -1,12 +1,13 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * The forges this one sent (#2211) in a card: one row per client with its |
| 3 | * claim state, the apps-running note and the crew's spend today, in the words /forges uses. Never a | |
| 3 | * claim state, a lapsed payment (and where to pay), the apps-running note and the crew's spend today, in the words /forges uses. Never a | |
| 4 | 4 | * claim link; that stays on the page. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import type { Ctx, Screen } from "../app/app.ts"; |
| 8 | 8 | import { binding } from "../app/keys.ts"; |
| 9 | 9 | import { ATTENTION_WORDS, CLAIM_WORDS, claimState, creditWords, runningWords, spendWords, type ClientRow } from "../../spawn/clients.ts"; |
| 10 | import { lapseBadge } from "../../billing/lapse.ts"; | |
| 10 | 11 | import { useLine } from "../../spawn/usage.ts"; |
| 11 | 12 | import { timeAgo } from "../../web/ui.ts"; |
| 12 | 13 | import { card } from "../ui/widgets.ts"; |
| @@ -26,10 +27,23 @@ export function forgeLines(rows: readonly ClientRow[]): [string, string][] { | ||
| 26 | 27 | if (rows.length === 0) return [["", "You have not sent a forge yet"]]; |
| 27 | 28 | return rows.flatMap((r): [string, string][] => [[ |
| 28 | 29 | r.name, |
| 29 | [r.made ? (r.awake === true ? "awake" : "asleep") : null, r.attention === null ? null : ATTENTION_WORDS[r.attention], r.for === null ? null : `for ${r.for}`, CLAIM_WORDS[claimState(r)], linkWords(r.link), runningWords(r), r.stage?.words ?? null, r.nextStep.words, spendWords(r)?.words ?? null, creditWords(r), useLine(r.size, r.use), r.made ? diskWords(r.disk) : null, r.lastHeartbeatAt === null ? "no heartbeat yet" : `heartbeat ${timeAgo(r.lastHeartbeatAt)}`] | |
| 30 | [r.made ? (r.awake === true ? "awake" : "asleep") : null, lapseWords(r), r.attention === null ? null : ATTENTION_WORDS[r.attention], r.for === null ? null : `for ${r.for}`, CLAIM_WORDS[claimState(r)], linkWords(r.link), runningWords(r), r.stage?.words ?? null, r.nextStep.words, spendWords(r)?.words ?? null, creditWords(r), useLine(r.size, r.use), r.made ? diskWords(r.disk) : null, r.lastHeartbeatAt === null ? "no heartbeat yet" : `heartbeat ${timeAgo(r.lastHeartbeatAt)}`] | |
| 30 | 31 | .filter((m): m is string => m !== null) |
| 31 | 32 | .join(" · "), |
| 32 | ], ...addressLines(r)]); | |
| 33 | ], ...payLines(r), ...addressLines(r)]); | |
| 34 | } | |
| 35 | ||
| 36 | /** "Asleep, unpaid, data kept to 2026-12-11": a lapsed payment as /forges says it; null for a forge that is running. */ | |
| 37 | export function lapseWords(r: ClientRow): string | null { | |
| 38 | if (r.lapse === undefined || r.lapse.state === "running") return null; | |
| 39 | const l = lapseBadge(r.lapse); | |
| 40 | return `${l.state}, ${l.until}`; | |
| 41 | } | |
| 42 | ||
| 43 | /** Under a forge that is not paid up: where its owner pays, or that no link is set. */ | |
| 44 | function payLines(r: ClientRow): [string, string][] { | |
| 45 | if (r.lapse === undefined || r.lapse.state === "running") return []; | |
| 46 | return [["", r.payHref === undefined ? " Pay: no link set (Billing links)" : ` Pay: ${r.payHref}`]]; | |
| 33 | 47 | } |
| 34 | 48 | |
| 35 | 49 | /** "link open", "link ended (undo with u)": what the sender can do about the link, as /forges shows it. */ |
src/web/pages/forges.ts +9
| @@ -22,6 +22,7 @@ import { diskWords } from "../../spawn/disk_mount.ts"; | ||
| 22 | 22 | import { listChildren } from "../../actions/spawn.ts"; |
| 23 | 23 | import { ownCode, removeForge, stopForge, type Managed } from "../../spawn/manage.ts"; |
| 24 | 24 | import { readOwnCode } from "../../spawn/own_code.ts"; |
| 25 | import { lapseBadge } from "../../billing/lapse.ts"; | |
| 25 | 26 | import { claimLinkBody } from "./new-forge.ts"; |
| 26 | 27 | |
| 27 | 28 | |
| @@ -35,6 +36,13 @@ function runningNote(r: ClientRow): Html | null { | ||
| 35 | 36 | >`; |
| 36 | 37 | } |
| 37 | 38 | |
| 39 | /** A lapsed payment: the state in plain words, the date that matters, and one pay action when a buy link is set. */ | |
| 40 | function lapseNote(r: ClientRow): Html | null { | |
| 41 | if (r.lapse === undefined || r.lapse.state === "running") return null; | |
| 42 | const l = lapseBadge(r.lapse); | |
| 43 | return html`<span data-lapse="${r.lapse.state}">${badge(l.state, { tone: "attn" })} ${l.until}${r.payHref === undefined ? null : html` ${btn("Pay", { href: r.payHref, size: "sm" })}`}</span>`; | |
| 44 | } | |
| 45 | ||
| 38 | 46 | /** The crew's spend today against its cap; attention-toned from 80%. */ |
| 39 | 47 | function spendNote(r: ClientRow): Html | null { |
| 40 | 48 | const s = spendWords(r); |
| @@ -53,6 +61,7 @@ export function forgeRow(r: ClientRow, now: number): Html { | ||
| 53 | 61 | r.made ? badge(r.awake === true ? "awake" : "asleep", r.awake === true ? { tone: "success" } : { variant: "outline" }) : null, |
| 54 | 62 | r.made ? html`${sizeWords(r.size)}` : null, |
| 55 | 63 | r.made ? html`<span data-disk="${r.disk.own ? "own" : "shared"}">${diskWords(r.disk)}</span>` : null, |
| 64 | lapseNote(r), | |
| 56 | 65 | runningNote(r), |
| 57 | 66 | spendNote(r), |
| 58 | 67 | creditWords(r) === null ? null : html`<span data-credit>${creditWords(r)}</span>`, |
src/web/pages/lapsed.ts added +39
| @@ -0,0 +1,39 @@ | ||
| 1 | /** | |
| 2 | * What a visitor sees at a forge asleep because its payment lapsed (#11140): | |
| 3 | * what happened, a button to pay again (or who to ask when no link is set), and how to take the data. No dates: the operator sees those on /forges. A browser | |
| 4 | * gets the page; a git client or an API call gets the same words as text. | |
| 5 | * 402 and never cached, so paying wakes the forge on the next request. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { App } from "../../app.ts"; | |
| 9 | import type { Ctx } from "../../http/context.ts"; | |
| 10 | import { ASK_OPERATOR, lapseWords, payAgainHref, type Lapse } from "../../billing/lapse.ts"; | |
| 11 | import { btn, empty } from "../ui.ts"; | |
| 12 | import { html } from "../html.ts"; | |
| 13 | import { page } from "../layout.ts"; | |
| 14 | ||
| 15 | const HEADERS = { "cache-control": "no-store", "content-type": "text/plain; charset=utf-8" }; | |
| 16 | ||
| 17 | export function lapsedResponse(app: App, request: Request, name: string, lapse: Extract<Lapse, { state: "asleep" }>, size?: string): Response { | |
| 18 | const words = lapseWords(name); | |
| 19 | const href = payAgainHref(app.db, size); | |
| 20 | if (!(request.headers.get("accept") ?? "").includes("text/html")) | |
| 21 | return new Response(`${words.what}\n${words.export}\n${href === undefined ? ASK_OPERATOR : `Pay again: ${href}`}\n`, { status: 402, headers: HEADERS }); | |
| 22 | const url = new URL(request.url); | |
| 23 | const ctx: Ctx = { app, request, url, params: {}, auth: { user: undefined, scope: undefined, via: "none" }, theme: undefined }; | |
| 24 | const response = page( | |
| 25 | { | |
| 26 | ctx, | |
| 27 | bare: true, | |
| 28 | title: "Asleep until paid", | |
| 29 | body: html`<div class="narrow-wide"> | |
| 30 | ${empty({ icon: "history", title: "Asleep until paid", note: words.what, ...(href === undefined ? {} : { action: btn("Pay again", { href, variant: "primary" }) }) })} | |
| 31 | ${href === undefined ? html`<p class="muted small">${ASK_OPERATOR}</p>` : null} | |
| 32 | <p class="muted small">${words.export}</p> | |
| 33 | </div>`, | |
| 34 | }, | |
| 35 | 402, | |
| 36 | ); | |
| 37 | response.headers.set("cache-control", "no-store"); | |
| 38 | return response; | |
| 39 | } |
test/billing-lapse.test.ts added +206
| @@ -0,0 +1,206 @@ | ||
| 1 | // A lapsed payment sleeps a forge and never deletes one (#11140): active → grace → none → active through the Stripe hook. | |
| 2 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 3 | import { existsSync, readFileSync } from "node:fs"; | |
| 4 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 5 | import { tmpdir } from "node:os"; | |
| 6 | import { join } from "node:path"; | |
| 7 | import { childDirOf, childNamed, spawnForge } from "../src/actions/spawn.ts"; | |
| 8 | import { createApp, type App } from "../src/app.ts"; | |
| 9 | import { sealKey, sealWebhook } from "../src/billing/connection.ts"; | |
| 10 | import { lapseNow, lapseOf } from "../src/billing/lapse.ts"; | |
| 11 | import { forgetLapses } from "../src/billing/lapse_seen.ts"; | |
| 12 | import { putEntitlement } from "../src/billing/store.ts"; | |
| 13 | import { createUser } from "../src/core/users.ts"; | |
| 14 | import { setStripeFetch } from "../src/billing/sync.ts"; | |
| 15 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 16 | import { setBillingLinks } from "../src/settings/billing.ts"; | |
| 17 | import { setLimit } from "../src/settings/limits.ts"; | |
| 18 | import { childAwake, settleLapseSleeps, resolveHostedChild, sleepLapsed, wakeGate } from "../src/spawn/host.ts"; | |
| 19 | import { hostedPlacement } from "../src/spawn/placement.ts"; | |
| 20 | import { quietLogs } from "./helpers/globals.ts"; | |
| 21 | ||
| 22 | quietLogs(); | |
| 23 | ||
| 24 | const secret = "whsec_lapse_test_secret"; | |
| 25 | const CHILD_HOST = "acme--forge.test"; | |
| 26 | let dir = ""; | |
| 27 | let app: App; | |
| 28 | let servers: Servers; | |
| 29 | let admin: { id: string }; | |
| 30 | let status = "active"; | |
| 31 | let n = 0; | |
| 32 | ||
| 33 | async function sign(body: string): Promise<string> { | |
| 34 | const t = Math.floor(Date.now() / 1000); | |
| 35 | const k = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); | |
| 36 | const mac = new Uint8Array(await crypto.subtle.sign("HMAC", k, new TextEncoder().encode(`${t}.${body}`))); | |
| 37 | return `t=${t},v1=${Buffer.from(mac).toString("hex")}`; | |
| 38 | } | |
| 39 | /** Stripe says `status` now; deliver an event naming the subscription. */ | |
| 40 | async function pay(now: string): Promise<void> { | |
| 41 | status = now; | |
| 42 | const body = JSON.stringify({ id: `evt_l${++n}`, type: "customer.subscription.updated", data: { object: { id: "sub_l", status: now } } }); | |
| 43 | const r = await fetch(`${servers.url}/hooks/stripe`, { method: "POST", headers: { "stripe-signature": await sign(body), "x-forwarded-for": `10.8.0.${n}` }, body }); | |
| 44 | expect(r.status).toBe(200); | |
| 45 | } | |
| 46 | const visit = (accept = "text/plain", path = "/") => fetch(`${servers.url}${path}`, { headers: { host: CHILD_HOST, accept } }); | |
| 47 | /** Move the start of the forge's current status back `days` days. */ | |
| 48 | const backdate = (days: number) => { | |
| 49 | app.db.query("UPDATE entitlement_change SET at = ?1 WHERE forge = 'acme'").run(new Date(Date.now() - days * 86_400_000).toISOString()); | |
| 50 | forgetLapses(app.db); | |
| 51 | }; | |
| 52 | /** Wait for `ok` to hold, up to two seconds, a loaded machine being slow: a fire-and-forget sleep has no promise to await. */ | |
| 53 | async function until(ok: () => boolean): Promise<void> { | |
| 54 | for (let i = 0; i < 100 && !ok(); i++) await Bun.sleep(20); | |
| 55 | } | |
| 56 | ||
| 57 | beforeAll(async () => { | |
| 58 | dir = await mkdtemp(join(tmpdir(), "billing-lapse-")); | |
| 59 | app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 }); | |
| 60 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", isAdmin: true }); | |
| 61 | if (!made.ok) throw new Error("user"); | |
| 62 | admin = made.value; | |
| 63 | const spawned = await spawnForge( | |
| 64 | app, made.value, | |
| 65 | { name: "acme", org: "acme", apps: [], carryBriefs: false, carrySubscriptions: false }, | |
| 66 | { catalog: [], briefs: [], subscriptions: [] }, | |
| 67 | { | |
| 68 | placement: hostedPlacement({ host: "forge.test" }), | |
| 69 | request: new Request("https://forge.test/spawn", { method: "POST", headers: { origin: "https://forge.test" } }), | |
| 70 | url: new URL("https://forge.test/spawn"), | |
| 71 | }, | |
| 72 | ); | |
| 73 | if (!spawned.ok) throw new Error(JSON.stringify(spawned.error)); | |
| 74 | servers = await serve(app); | |
| 75 | sealKey(app.db, dir, "sk_test_abcdefgh12345678"); | |
| 76 | sealWebhook(app.db, dir, secret); | |
| 77 | setStripeFetch(app, (async () => | |
| 78 | new Response(JSON.stringify({ id: "sub_l", status, customer: "cus_l", metadata: { forge: "acme", plan: "medium" }, items: { data: [{ current_period_end: 1900000000 }] } }), { status: 200 })) as unknown as typeof fetch); | |
| 79 | }); | |
| 80 | afterAll(async () => { | |
| 81 | setStripeFetch(app, undefined); | |
| 82 | await servers.stop(); | |
| 83 | await rm(dir, { recursive: true, force: true }); | |
| 84 | }); | |
| 85 | ||
| 86 | describe("a lapsed payment sleeps a forge, and nothing deletes it", () => { | |
| 87 | test("active: the forge answers", async () => { | |
| 88 | await pay("active"); | |
| 89 | expect(lapseOf(app.db, "acme").state).toBe("running"); | |
| 90 | expect((await visit()).status).not.toBe(402); | |
| 91 | expect(childAwake(app, "acme")).toBe(true); | |
| 92 | }); | |
| 93 | ||
| 94 | test("grace: still running", async () => { | |
| 95 | await pay("past_due"); | |
| 96 | const l = lapseOf(app.db, "acme"); | |
| 97 | expect(l.state).toBe("grace"); | |
| 98 | expect((await visit()).status).not.toBe(402); | |
| 99 | expect(childAwake(app, "acme")).toBe(true); | |
| 100 | }); | |
| 101 | ||
| 102 | test("grace is a setting: past it the forge is asleep with a plain page, a pay button and the export words", async () => { | |
| 103 | backdate(8); // default grace is 7 days | |
| 104 | expect(lapseOf(app.db, "acme").state).toBe("asleep"); | |
| 105 | const text = await visit(); | |
| 106 | expect(text.status).toBe(402); | |
| 107 | const said = await text.text(); | |
| 108 | expect(said).toContain("Nothing was deleted"); | |
| 109 | expect(said).not.toMatch(/\d{4}-\d{2}-\d{2}/); // a visitor is told it sleeps, not until when the data is kept | |
| 110 | expect(said).toContain("ask the operator of this forge to pay"); // no buy link is set: nothing here pays for a new forge | |
| 111 | const web = await visit("text/html"); | |
| 112 | const body = await web.text(); | |
| 113 | expect(web.status).toBe(402); | |
| 114 | expect(body).not.toContain("Pay again"); | |
| 115 | expect(body).not.toMatch(/\d{4}-\d{2}-\d{2}/); | |
| 116 | expect(body).not.toContain("/forges/new"); | |
| 117 | expect(body).toContain("ask the operator of this forge for an export"); | |
| 118 | expect(web.headers.get("cache-control")).toBe("no-store"); | |
| 119 | }); | |
| 120 | ||
| 121 | test("the request that met the lapse put the awake forge to sleep; a wake is refused", async () => { | |
| 122 | await until(() => !childAwake(app, "acme")); | |
| 123 | await settleLapseSleeps(app); // the close itself, not just the child leaving the cache | |
| 124 | await sleepLapsed(app); // or the sweep lands it, should the request's not have begun | |
| 125 | expect(childAwake(app, "acme")).toBe(false); | |
| 126 | expect(await sleepLapsed(app)).toEqual([]); | |
| 127 | const gated = wakeGate(app, new Request("https://forge.test/", { headers: { host: CHILD_HOST } })); | |
| 128 | expect(gated?.status).toBe(402); | |
| 129 | expect(childAwake(app, "acme")).toBe(false); | |
| 130 | }); | |
| 131 | ||
| 132 | test("with a buy link set the page has one pay button to it", async () => { | |
| 133 | setBillingLinks(app.db, { small: "https://buy.test/small" }, admin.id); | |
| 134 | const body = await (await visit("text/html")).text(); | |
| 135 | expect(body).toContain('href="https://buy.test/small"'); | |
| 136 | expect(await (await visit()).text()).toContain("Pay again: https://buy.test/small"); | |
| 137 | setBillingLinks(app.db, {}, admin.id); | |
| 138 | }); | |
| 139 | ||
| 140 | test("a read of the lapse is reused for a moment, and an entitlement written drops it", () => { | |
| 141 | expect(lapseNow(app.db, "acme").state).toBe("asleep"); | |
| 142 | app.db.query("UPDATE entitlement SET status = 'active' WHERE forge = 'acme'").run(); // behind the cache's back | |
| 143 | expect(lapseOf(app.db, "acme").state).toBe("running"); | |
| 144 | expect(lapseNow(app.db, "acme").state).toBe("asleep"); | |
| 145 | putEntitlement(app.db, { forge: "acme", plan: "medium", status: "active", source: "stripe" }, "small", admin.id); | |
| 146 | expect(lapseNow(app.db, "acme").state).toBe("running"); | |
| 147 | putEntitlement(app.db, { forge: "acme", plan: "medium", status: "grace", source: "stripe" }, "small", admin.id); | |
| 148 | backdate(8); | |
| 149 | expect(lapseNow(app.db, "acme").state).toBe("asleep"); | |
| 150 | }); | |
| 151 | ||
| 152 | test("a longer grace keeps it running", () => { | |
| 153 | setLimit(app.db, "billing.grace_days", 30, admin.id); | |
| 154 | expect(lapseOf(app.db, "acme").state).toBe("grace"); | |
| 155 | setLimit(app.db, "billing.grace_days", 7, admin.id); | |
| 156 | }); | |
| 157 | ||
| 158 | test("none: asleep, its apps stop answering, and its data is kept at least 30 days", async () => { | |
| 159 | await pay("canceled"); | |
| 160 | const l = lapseOf(app.db, "acme"); | |
| 161 | expect(l.state).toBe("asleep"); | |
| 162 | if (l.state !== "asleep") return; | |
| 163 | expect(l.keptUntil - l.since).toBeGreaterThanOrEqual(30 * 86_400_000); | |
| 164 | expect((await visit()).status).toBe(402); | |
| 165 | expect((await fetch(`${servers.url}/`, { headers: { host: `site--${CHILD_HOST}` } })).status).toBe(503); | |
| 166 | }); | |
| 167 | ||
| 168 | test("a granted forge and a free one are untouched", () => { | |
| 169 | for (const source of ["granted", "code:abc"]) { | |
| 170 | putEntitlement(app.db, { forge: "acme", plan: "free", status: "none", source }, "small", admin.id); | |
| 171 | expect(lapseOf(app.db, "acme").state).toBe("running"); | |
| 172 | } | |
| 173 | expect(lapseOf(app.db, "nobody").state).toBe("running"); | |
| 174 | }); | |
| 175 | ||
| 176 | test("paying again wakes it as it was, data and all", async () => { | |
| 177 | await pay("canceled"); | |
| 178 | expect(lapseOf(app.db, "acme").state).toBe("asleep"); | |
| 179 | await pay("active"); | |
| 180 | expect(lapseOf(app.db, "acme").state).toBe("running"); | |
| 181 | const opened = await resolveHostedChild(app, new Request("https://forge.test/healthz", { headers: { host: CHILD_HOST } })); | |
| 182 | expect(opened === undefined || opened === "unknown" || opened === "cell").toBe(false); | |
| 183 | expect((await visit()).status).not.toBe(402); | |
| 184 | }); | |
| 185 | ||
| 186 | test("the sweep sleeps an awake forge whose payment lapsed with no request to notice", async () => { | |
| 187 | expect(childAwake(app, "acme")).toBe(true); | |
| 188 | putEntitlement(app.db, { forge: "acme", plan: "free", status: "none", source: "stripe" }, "small", "stripe"); | |
| 189 | expect(await sleepLapsed(app)).toEqual(["acme"]); | |
| 190 | expect(childAwake(app, "acme")).toBe(false); | |
| 191 | }); | |
| 192 | ||
| 193 | test("no lapse removed the forge's directory or ledger", async () => { | |
| 194 | const child = await childNamed(app, "acme"); | |
| 195 | expect(child).toBeDefined(); | |
| 196 | expect(existsSync(childDirOf(app, child!.bodyId))).toBe(true); | |
| 197 | expect(existsSync(join(dir, "spawn", "acme.json"))).toBe(true); | |
| 198 | }); | |
| 199 | ||
| 200 | test("no code the webhook reaches can remove a directory", () => { | |
| 201 | const deleting = /\b(rm|rmSync|unlink|unlinkSync|rmdir|rmdirSync|removeForge)\b|recursive:\s*true/; | |
| 202 | for (const f of ["src/billing/lapse.ts", "src/billing/subscription.ts", "src/billing/checkout_completed.ts", "src/billing/store.ts", "src/http/stripe_hook.ts", "src/web/pages/lapsed.ts"]) { | |
| 203 | expect(readFileSync(join(import.meta.dir, "..", f), "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/.*$/gm, "")).not.toMatch(deleting); | |
| 204 | } | |
| 205 | }); | |
| 206 | }); |
test/lapse-forges.test.ts added +60
| @@ -0,0 +1,60 @@ | ||
| 1 | // A lapsed payment on the operator's two doors: the /forges row and the terminal's "Forges you sent" (#11140). | |
| 2 | import { describe, expect, test } from "bun:test"; | |
| 3 | import { forgeLines } from "../src/tui/screens/forges.ts"; | |
| 4 | import { forgeRow } from "../src/web/pages/forges.ts"; | |
| 5 | import type { ClientRow } from "../src/spawn/clients.ts"; | |
| 6 | import { limitStates, limitValues } from "../src/settings/limits.ts"; | |
| 7 | import { createApp } from "../src/app.ts"; | |
| 8 | import { mkdtempSync, rmSync } from "node:fs"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | ||
| 12 | const DAY = 86_400_000; | |
| 13 | const row = (over: Partial<ClientRow>): ClientRow => ({ | |
| 14 | name: "maria", url: "https://maria.test", for: null, apps: [], stage: null, sentAt: null, made: true, claimed: false, | |
| 15 | lastActivityAt: null, running: null, reach: null, link: null, attention: null, spendTodayUsd: null, ceilingUsd: null, | |
| 16 | size: "small", use: { kind: "shared" }, disk: { own: false, path: "/d/children/c" }, lastHeartbeatAt: null, | |
| 17 | nextStep: { key: "unreported", words: "has not reported yet", lastTellAt: null }, ...over, | |
| 18 | }); | |
| 19 | const asleep = row({ lapse: { state: "asleep", since: 0, keptUntil: Date.parse("2026-12-11T00:00:00Z") }, payHref: "https://buy.test/small" }); | |
| 20 | const late = row({ lapse: { state: "grace", since: 0, graceEnds: Date.parse("2026-11-18T00:00:00Z") } }); | |
| 21 | ||
| 22 | describe("a lapsed payment in the terminal", () => { | |
| 23 | test("the row says the state in plain words, the date, and where to pay", () => { | |
| 24 | const lines = forgeLines([asleep]); | |
| 25 | expect(lines[0]![1]).toContain("Asleep, unpaid, data kept to 2026-12-11"); | |
| 26 | expect(lines[1]![1]).toBe(" Pay: https://buy.test/small"); | |
| 27 | }); | |
| 28 | test("no buy link set says so instead of pointing anywhere", () => { | |
| 29 | expect(forgeLines([late])[0]![1]).toContain("Payment late, runs to 2026-11-18"); | |
| 30 | expect(forgeLines([late])[1]![1]).toContain("no link set"); | |
| 31 | }); | |
| 32 | test("a forge that is running says nothing of payment", () => { | |
| 33 | expect(forgeLines([row({ lapse: { state: "running" } })]).flat().join(" ")).not.toMatch(/Pay|unpaid/); | |
| 34 | }); | |
| 35 | }); | |
| 36 | ||
| 37 | describe("a lapsed payment on /forges", () => { | |
| 38 | test("one badge, the date and one pay action", () => { | |
| 39 | const html = String(forgeRow(asleep, Date.now() + DAY)); | |
| 40 | expect(html).toContain("Asleep, unpaid"); | |
| 41 | expect(html).toContain("data kept to 2026-12-11"); | |
| 42 | expect(html).toContain('href="https://buy.test/small"'); | |
| 43 | }); | |
| 44 | test("with no buy link there is no pay action", () => { | |
| 45 | expect(String(forgeRow(late, Date.now()))).not.toContain(">Pay<"); | |
| 46 | }); | |
| 47 | }); | |
| 48 | ||
| 49 | describe("limits are read together", () => { | |
| 50 | test("limitValues and limitStates agree with the defaults and one read each", () => { | |
| 51 | const dir = mkdtempSync(join(tmpdir(), "lapse-limits-")); | |
| 52 | const app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 }); | |
| 53 | try { | |
| 54 | expect(limitValues(app.db, ["billing.grace_days", "billing.keep_days"])).toEqual({ "billing.grace_days": 7, "billing.keep_days": 30 }); | |
| 55 | expect(limitStates(app.db)["billing.grace_days"]).toEqual({ value: 7, isSet: false, defaultValue: 7 }); | |
| 56 | } finally { | |
| 57 | rmSync(dir, { recursive: true, force: true }); | |
| 58 | } | |
| 59 | }); | |
| 60 | }); |
test/snapshot-resume.test.ts +2 −2
| @@ -143,14 +143,14 @@ test("a kill that runs no finally still leaves the journal, written on a clock", | ||
| 143 | 143 | }; |
| 144 | 144 | void takeSnapshot(forge(false, 20), hung, at).catch(() => {}); |
| 145 | 145 | let journal: { path: string }[] = []; |
| 146 | for (let i = 0; i < 100 && journal.length < 2; i++) { | |
| 146 | for (let i = 0; i < 300 && journal.length < 2; i++) { | |
| 147 | 147 | await Bun.sleep(50); |
| 148 | 148 | const body = await inner.get(prefix + JOURNAL); |
| 149 | 149 | if (body !== undefined) journal = JSON.parse(new TextDecoder().decode(body)) as { path: string }[]; |
| 150 | 150 | } |
| 151 | 151 | expect(journal.map((e) => e.path).sort()).toEqual(["repos/alice/one.bundle", "repos/alice/two.bundle"]); |
| 152 | 152 | expect(await inner.get(prefix + "manifest.json")).toBeUndefined(); |
| 153 | }, 15_000); | |
| 153 | }, 30_000); | |
| 154 | 154 | |
| 155 | 155 | test("a bundle of the same size but other content is put again", async () => { |
| 156 | 156 | const inner = dirStore(join(root, "store-stale")); |
new above
offline