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

Pinned forges end on a date: a notice a day before, Keep, and retire with data kept #16699

Merged opened this

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

Merged

sold/lifetimes → main 0 commits 4 threads · 4 unresolved

  • Merged. sold/lifetimes was merged into main as 2517396.

Review

Sign in to review this change.
17 files changed +510 −24
docs/features/experiments.md +2
@@ -24,4 +24,6 @@ All three read and write through `src/cloud/experiments.ts`, and only a forge ad
2424 - A pinned forge that costs money and is on no experiment shows as **idle spend**, below the experiments and the New experiment form: its name and monthly cost first, then what bills (`bills`: its machine, or the disk a retired forge kept). A running one offers Attach (or, with no experiment yet, a link to the form) and Retire its machine; a retired one offers Delete its kept disk, through the same confirm that asks for its name.
2525 - New experiment's Runs on offers exactly the machines that cost money: the idle ones and those on an experiment now.
2626
27 A forge attached to an experiment ends on its own 7 days later unless kept: its machine line says when, with Keep and End now beside it ([lifetime](pinned-forge.md#lifetime-16696)).
28
2729 Each begin, attach and result is an event (`pinned.experiment_begun`, `pinned.experiment_attached`, `pinned.experiment_result`) naming who did it. Retiring a machine stays on the pinned forge itself.
docs/features/pinned-forge.md +4
@@ -105,6 +105,10 @@ A test forge, or one whose buyer left, would bill forever without a way out. **R
105105
106106 What each forge's spend answers, and what it found: [Experiments](experiments.md).
107107
108 ## Lifetime (#16696)
109
110 A forge can end on its own. `lifetimeDays` at deploy (1 to 90) sets when, and a forge put on an experiment gets 7 days; a sold or claimed forge never does. The row says when ("Ends Thu 3 Dec (in 6 days)"). **Keep** moves it 7 days later, and **End now** is Retire through its confirm, on the row, the experiment's machine line, the terminal (`e`), the API (`POST /api/v1/admin/pinned/:name/keep`) and the MCP (`keep`). The `pinned-lifetimes` duty says once, a day before, `pinned.ending_soon` with a finding; at the end it retires the machine with its data kept (`pinned.ended`). A forge claimed meanwhile is skipped and its end cleared (`pinned.lifetime_cleared`).
111
108112 ## After the claim: what the host can still do (#16204)
109113
110114 Nobody marks a forge claimed by hand: the deployed forge says so. Check, and every Update, Roll back and request for a new claim link, asks it first; when one hears `claimed` (The claim, above), the selling forge records it once (`pinned_forge.claimed_at`, event `pinned.claimed`). From then it refuses `update`, `rollback` and a new claim link for that forge, each with the same sentence (`CLAIMED_REFUSAL`): updates are the buyer's to take, and no machine of theirs is replaced from here. A forge that cannot be asked is never recorded as claimed, and is not taken as unclaimed either: once its current machine has answered about its claim (`pinned_forge.reached`), silence from it (a broken DNS record, a forge that is down) refuses Update, Roll back and a new claim link, with a sentence saying the forge could not be reached to confirm nobody claimed it and to run Check until it answers. A forge whose current machine has never answered (still booting, DNS not pointed yet, a first boot that failed) may still be replaced, or it could never be recovered. The question starts with a read of the machine at its cloud: when the cloud refuses that read the change is refused with the cloud's answer, before anything is recorded; a machine that is gone (404) has nobody to ask and is replaced. `/pinned` (once, when any forge is claimed) and `/deploy-to` say what the host still can while the machine is in the host's cloud account (`HOST_CAN` in `src/core/pinned.ts`): open its console, boot it into rescue, snapshot its disk, read its boot data. It never says "no access". The path that gives the host none is the buyer's own cloud account: deploy there (the account picker on `/deploy-to`; choosing it at purchase is #16203).
src/actions/pinned.ts +52 −6
@@ -42,7 +42,7 @@ import { target as targetOf } from "../cloud/targets.ts";
4242 import { getCloudAccount, listCloudAccounts, secretNameOf } from "../core/cloud_account.ts";
4343 import { FIRST_ADMIN_SEED_TTL_MS, firstAdminLink, newFirstAdminCode, type SeedState } from "../core/first_admin.ts";
4444 import {
45 APP, CLAIMED_REFUSAL, NAME, changesOf, checkConfig, dnsRecordOf, getPinned, insertPinned, listPinned, placeIdOf, previousOf,
45 APP, CLAIMED_REFUSAL, NAME, changesOf, lifetimeOf, setLifetime, checkConfig, dnsRecordOf, getPinned, insertPinned, listPinned, placeIdOf, previousOf,
4646 dnsOf, dropDns, dropPinned, keepDns, markClaimed, markReached, recordChange, setClaim, setHost, setRemote, urlOf, validHost, validSource, validVersion, unconfirmedRefusal, type Change, type Pinned,
4747 } from "../core/pinned.ts";
4848 import { resolveSecrets } from "../core/secret_store.ts";
@@ -120,6 +120,8 @@ export interface PinnedView extends Omit<Pinned, "claimHash"> {
120120 * What the forge says when it stopped waiting for this forge without an answer; empty otherwise.
121121 */
122122 readonly stuck: string;
123 /** When the forge retires it on its own (#16696), ISO; null when it never does. */
124 readonly endsAt: string | null;
123125 readonly crew: false;
124126 readonly autoRelease: false;
125127 readonly changes: Change[];
@@ -133,7 +135,7 @@ const view = (app: App, p: Pinned): PinnedView => {
133135 const keepCents = p.state === "retired" && p.volume !== "" ? rowCents(p, priced(app.db)) : 0;
134136 const watch = watchOf(app.db, p.id);
135137 const stuck = watch !== undefined && watch.gaveUpAt !== "" && watch.answeredAt === "" ? stuckWords(p.name, watch.addressAt !== "", watch.dnsAt !== "") : "";
136 return { ...shown, url: urlOf(p), dns: dnsRecordOf(p), keepCents, dnsWrittenBy: written ? `cloudflare/${kept.account}` : "", dnsAuto: dnsWriters(app).length > 0, watch, stuck, crew: false, autoRelease: false, changes: changesOf(app.db, p.id) };
138 return { ...shown, endsAt: lifetimeOf(app.db, p.id)?.endsAt ?? null, url: urlOf(p), dns: dnsRecordOf(p), keepCents, dnsWrittenBy: written ? `cloudflare/${kept.account}` : "", dnsAuto: dnsWriters(app).length > 0, watch, stuck, crew: false, autoRelease: false, changes: changesOf(app.db, p.id) };
137139 };
138140
139141 /** A claim just issued: the link is in this value and nowhere else, so it is shown once. */
@@ -429,6 +431,8 @@ export type DeployInput = {
429431 name: string; host: string; target: string; account: string; app: string; source?: string; version?: string; place?: string | undefined; config?: unknown;
430432 /** The plan whose default place is chosen when none is asked for; small when absent. */
431433 plan?: PlanName | undefined;
434 /** Days until the forge retires it on its own (#16696); absent, it never does. Never for an order. */
435 lifetimeDays?: number | undefined;
432436 };
433437
434438 export async function deployPinned(app: App, actor: User | undefined, input: DeployInput): Promise<Result<Issued, string>> {
@@ -442,6 +446,7 @@ async function deployAs(app: App, who: Who, input: DeployInput): Promise<Result<
442446 if (t.status === "refused") return err(t.refused);
443447 if (t.status !== "first") return err(`${t.label} is not written yet: ${t.refused}`);
444448 if (!NAME.test(input.name)) return err("A name is lowercase letters, digits and dashes, starting with a letter.");
449 if (input.lifetimeDays !== undefined && !(Number.isInteger(input.lifetimeDays) && input.lifetimeDays >= 1 && input.lifetimeDays <= MAX_LIFETIME_DAYS)) return err(`A lifetime is a whole number of days, 1 to ${MAX_LIFETIME_DAYS}.`);
445450 const host = hostFor(app, input.name, input.host);
446451 if (!host.ok) return host;
447452 if (!APP.test(input.app)) return err("Name the app as owner/name.");
@@ -471,9 +476,10 @@ async function deployAs(app: App, who: Who, input: DeployInput): Promise<Result<
471476 if (!at.ok) return at;
472477 if (old) dropPinned(app.db, old.name);
473478 const claim = newClaim();
474 const { place: _asked, plan: _plan, ...rest } = input;
479 const { place: _asked, plan: _plan, lifetimeDays, ...rest } = input;
475480 const p = insertPinned(app.db, { ...rest, ...code.value, target: t.id, config: config.value, host: host.value, claimHash: claim.hash, claimExpires: claim.expires, datacenter: at.value.datacenter, size: at.value.size }, who.by);
476481 app.bus.append({ kind: "pinned.deployed", actorId: who.id, payload: { name: p.name, target: p.target, version: p.version, ...orderOf(who) } });
482 if (lifetimeDays !== undefined && who.order === undefined) setLifetime(app.db, p.id, new Date(Date.now() + lifetimeDays * DAY_MS).toISOString());
477483 if (old?.volume) setRemote(app.db, p.name, { volume: old.volume });
478484 const made = await create(
479485 app, who, p, "deploy",
@@ -708,10 +714,11 @@ export type Retired = PinnedView & { readonly dnsRemoved: "none" | "removed" | "
708714 * kept. A machine or volume already gone at the provider is done, so the same call asked again
709715 * finishes a failed one, and a retired forge asked again changes nothing. A forge the deployed
710716 * forge says is claimed is refused unless `despiteClaim`: the buyer's data is on that volume. One
711 * change at a time per forge, like an Update.
717 * change at a time per forge, like an Update. `"lifetime"` is the forge's own lifetime duty
718 * (#16696), which no request can name: it retires as the system, keeping the data.
712719 */
713 export const retirePinned = (app: App, actor: User | undefined, name: string, o: { withData?: boolean | undefined; despiteClaim?: boolean | undefined } = {}): Promise<Result<Retired, string>> => {
714 const who = admin(actor);
720 export const retirePinned = (app: App, actor: User | undefined | "lifetime", name: string, o: { withData?: boolean | undefined; despiteClaim?: boolean | undefined } = {}): Promise<Result<Retired, string>> => {
721 const who = actor === "lifetime" ? ok(lifetimeWho) : admin(actor);
715722 return who.ok ? oneChange(app, name, () => retireNow(app, who.value, name, o)) : Promise.resolve(who);
716723 };
717724
@@ -745,6 +752,45 @@ async function retireNow(app: App, who: Who, name: string, o: { withData?: boole
745752 return done(getPinned(app.db, name)!, dnsRemoved);
746753 }
747754
755 const DAY_MS = 86_400_000;
756 /** What a forge on an experiment is given, and what Keep adds (#16696). */
757 export const LIFETIME_DAYS = 7;
758 export const MAX_LIFETIME_DAYS = 90;
759 const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
760 const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
761
762 /** When a forge ends, as people say it: `Tue 3 Dec (in 6 days)`, UTC; never a raw ISO. */
763 export function endsWords(endsAt: string, now = new Date()): string {
764 const d = new Date(endsAt);
765 const days = Math.round((d.getTime() - now.getTime()) / DAY_MS);
766 const when = days <= 0 ? (d.getTime() <= now.getTime() ? "now" : "today") : days === 1 ? "tomorrow" : `in ${days} days`;
767 return `${WEEKDAYS[d.getUTCDay()]} ${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]} (${when})`;
768 }
769
770 /**
771 * Keep (#16696): the forge ends `LIFETIME_DAYS` later than it would have (from now, when its end
772 * is past), and the day-before warning is owed again. A forge with no end, or a claimed one, has
773 * no lifetime to keep: Keep never gives a forge an end it did not have. An admin's, at every door.
774 */
775 export function keepPinned(app: App, actor: User | undefined, name: string, now = new Date()): Result<PinnedView, string> {
776 const who = admin(actor);
777 if (!who.ok) return who;
778 const p = getPinned(app.db, name);
779 if (!p) return err("No such pinned forge.");
780 if (p.state === "retired") return err(`${name} is retired: there is nothing left to keep running.`);
781 if (p.claimedAt !== "") return err(`${name} was handed to its buyer: it never ends on its own.`);
782 const life = lifetimeOf(app.db, p.id);
783 if (life === undefined) return err(`${name} has no end to extend: it keeps running until it is retired.`);
outdated

High: when the forge has no lifetime this still computes an end from now and sets it, so Keep schedules the retirement of a forge that never ended. Refuse when lifetimeOf is undefined.

784 const from = Math.max(now.getTime(), Date.parse(life.endsAt) || 0);
785 const endsAt = new Date(from + LIFETIME_DAYS * DAY_MS).toISOString();
786 setLifetime(app.db, p.id, endsAt);
787 app.bus.append({ kind: "pinned.kept", actorId: who.value.id, payload: { name, endsAt } });
788 return ok(view(app, getPinned(app.db, name)!));
789 }
790
791 /** The system actor a forge's own lifetime retires it as (`retirePinned(app, "lifetime", …)`). */
792 const lifetimeWho: Who = { id: undefined, by: "lifetime" };
793
748794 /** What retiring did, in the one sentence every door says. */
749795 export function retireWords(v: Retired): string {
750796 const dns = v.dnsRemoved === "removed" ? ", and the DNS record the forge wrote for it is removed" : v.dnsRemoved === "kept" ? `; its DNS record ${v.host} could not be removed and is yours to delete` : "";
src/cloud/experiments.ts +11 −1
@@ -14,12 +14,15 @@
1414 import { billingSentence, billsOf, type Bills } from "./billing.ts";
1515 import type { Database } from "bun:sqlite";
1616 import type { App } from "../app.ts";
17 import { getPinned, listPinned, type Pinned } from "../core/pinned.ts";
17 import { getPinned, lifetimeOf, lifetimes, listPinned, setLifetime, type Pinned } from "../core/pinned.ts";
1818 import { id as newId } from "../kernel/id.ts";
1919 import { err, ok, type Result } from "../kernel/result.ts";
2020 import { priced, rowCents } from "./ceiling.ts";
21 import { LIFETIME_DAYS } from "../actions/pinned.ts";
2122
outdated

Second definition of the 7-day lifetime; import LIFETIME_DAYS so there is one way.

2223 const DAY_MS = 86_400_000;
24 /** What a forge attached to an experiment is given to live: what Keep gives. */
25 const LIFETIME_MS = LIFETIME_DAYS * DAY_MS;
2326 /** The month the reckoning bills by: 30 days. */
2427 const MONTH_DAYS = 30;
2528 const QUESTION_MAX = 300;
@@ -44,6 +47,8 @@ export interface Machine {
4447 readonly bills: Bills;
4548 /** The same as a sentence a reader cannot misread (`billingSentence`). */
4649 readonly billing: string;
50 /** When the forge retires it on its own (#16696), ISO; null when it never does. */
51 readonly endsAt: string | null;
4752 }
4853
4954 export interface Experiment {
@@ -95,6 +100,7 @@ export function experiments(db: Database, now = new Date()): Experiments {
95100 const prices = priced(db);
96101 const forges = new Map(listPinned(db).map((p) => [p.id, p]));
97102 const links = db.query<Link, []>("SELECT pinned_id, experiment_id, attached_at, detached_at FROM experiment_machine ORDER BY id").all();
103 const ends = new Map(lifetimes(db).map((l) => [l.pinnedId, l.endsAt]));
98104 const machine = (p: Pinned, since: string, until: string): Machine => {
99105 const monthlyCents = rowCents(p, prices);
100106 return {
@@ -106,6 +112,7 @@ export function experiments(db: Database, now = new Date()): Experiments {
106112 until,
107113 bills: billsOf(p),
108114 billing: billingSentence(p, monthlyCents),
115 endsAt: ends.get(p.id) ?? null,
109116 };
110117 };
111118 const items = db
@@ -177,6 +184,9 @@ export function attachMachine(app: App, actorId: string, id: string, name: strin
177184 db.query("UPDATE experiment_machine SET detached_at = ?2 WHERE pinned_id = ?1 AND detached_at = ''").run(p.id, at);
178185 db.query("INSERT INTO experiment_machine (experiment_id, pinned_id, attached_at) VALUES (?1, ?2, ?3)").run(id, p.id, at);
179186 })();
187 // A forge on an experiment ends on its own a week on (#16696), unless it has an end already or
188 // its buyer claimed it: Keep gives it longer.
189 if (lifetimeOf(db, p.id) === undefined && p.claimedAt === "" && p.state !== "retired") setLifetime(db, p.id, new Date(now.getTime() + LIFETIME_MS).toISOString());
180190 app.bus.append({ kind: "pinned.experiment_attached", actorId, payload: { id, name: p.name, from: open?.experiment_id ?? "" } });
181191 return ok();
182192 }
src/contract/openapi/routes/index.ts +1
@@ -303,6 +303,7 @@ export { route as postApiV1AdminMaintenanceResume } from "./postApiV1AdminMainte
303303 export { route as postApiV1AdminPinned } from "./postApiV1AdminPinned.ts";
304304 export { route as postApiV1AdminPinnedNameCheck } from "./postApiV1AdminPinnedNameCheck.ts";
305305 export { route as postApiV1AdminPinnedNameClaim } from "./postApiV1AdminPinnedNameClaim.ts";
306 export { route as postApiV1AdminPinnedNameKeep } from "./postApiV1AdminPinnedNameKeep.ts";
306307 export { route as postApiV1AdminPinnedNameRetire } from "./postApiV1AdminPinnedNameRetire.ts";
307308 export { route as postApiV1AdminPinnedNameRollback } from "./postApiV1AdminPinnedNameRollback.ts";
308309 export { route as postApiV1AdminPinnedNameUpdate } from "./postApiV1AdminPinnedNameUpdate.ts";
src/contract/openapi/routes/postApiV1AdminPinnedNameKeep.ts added +14
@@ -0,0 +1,14 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: "/api/v1/admin/pinned/{name}/keep",
6 summary: "Keep a pinned forge seven more days before it retires on its own",
7 detail: "Moves its `endsAt` a week later (from now when it had none or it is past) and owes the day-before warning again; a claimed or retired forge is refused",
8 auth: true,
9 role: "admin",
10 refusals: {
11 not_found: "only a forge administrator sees this route",
12 refused: "the request was understood and refused; the message says why (422)",
13 },
14 };
src/core/migration-pins/20261129100000-pinned-lifetime.pin added +1
@@ -0,0 +1,1 @@
1 a9cb0b3115b7412e82bd1d95bd9719018ebfd752c1884830442e1fa45909f911
src/core/migrations/20261129100000-pinned-lifetime.ts added +10
@@ -0,0 +1,10 @@
1 // A pinned forge's lifetime (#16696): when the forge retires it on its own (`ends_at`, ISO), and
2 // when it said so a day before (`warned_at`, empty until then), so the warning is said once. No
3 // row, no lifetime: a sold or claimed forge never ends on its own. One row a forge; small.
4 export default `
5 CREATE TABLE IF NOT EXISTS pinned_lifetime (
6 pinned_id TEXT PRIMARY KEY,
7 ends_at TEXT NOT NULL,
8 warned_at TEXT NOT NULL DEFAULT ''
9 );
10 `;
src/core/pinned.ts +28
@@ -299,10 +299,38 @@ export function keepDns(db: Database, pinnedId: string, d: DnsKept): void {
299299 ).run(pinnedId, d.account, d.zone, d.record, d.host, d.address, new Date().toISOString());
300300 }

This comment described dropPinned and now sits above the Lifetime interface. Move it back.

301301
302 /** A forge's lifetime (#16696): when it ends on its own and when it was told a day before. */
303 export interface Lifetime {
304 readonly endsAt: string;
305 /** When the day-before warning was said; empty until then. */
306 readonly warnedAt: string;
307 }
308
309 export function lifetimeOf(db: Database, pinnedId: string): Lifetime | undefined {
310 const r = db.query<{ ends_at: string; warned_at: string }, [string]>("SELECT ends_at, warned_at FROM pinned_lifetime WHERE pinned_id = ?1").get(pinnedId);
311 return r === null ? undefined : { endsAt: r.ends_at, warnedAt: r.warned_at };
312 }
313
314 /** Set when a forge ends, warning again before the new end; `undefined` clears its lifetime. */
315 export function setLifetime(db: Database, pinnedId: string, endsAt: string | undefined): void {
316 if (endsAt === undefined) db.query("DELETE FROM pinned_lifetime WHERE pinned_id = ?1").run(pinnedId);
317 else db.query("INSERT INTO pinned_lifetime (pinned_id, ends_at) VALUES (?1, ?2) ON CONFLICT(pinned_id) DO UPDATE SET ends_at = excluded.ends_at, warned_at = ''").run(pinnedId, endsAt);
318 }
319
320 /** Mark the day-before warning said; true only for the call that marked it. */
321 export function markWarned(db: Database, pinnedId: string, at: string): boolean {
322 return db.query("UPDATE pinned_lifetime SET warned_at = ?2 WHERE pinned_id = ?1 AND warned_at = ''").run(pinnedId, at).changes === 1;
323 }
324
325 /** Every lifetime with its forge's name, for the duty that ends them. */
326 export const lifetimes = (db: Database): (Lifetime & { pinnedId: string })[] =>
327 db.query<{ pinned_id: string; ends_at: string; warned_at: string }, []>("SELECT pinned_id, ends_at, warned_at FROM pinned_lifetime ORDER BY ends_at").all().map((r) => ({ pinnedId: r.pinned_id, endsAt: r.ends_at, warnedAt: r.warned_at }));
328
302329 /** The row of a deploy that never reached a droplet, so its name can be tried again; its recorded change stays as history. */
303330 export function dropPinned(db: Database, name: string): void {
304331 db.query("DELETE FROM pinned_size WHERE pinned_id IN (SELECT id FROM pinned_forge WHERE name = ?1 AND remote = '' AND state = 'failed')").run(name);
305332 db.query("DELETE FROM pinned_dns WHERE pinned_id IN (SELECT id FROM pinned_forge WHERE name = ?1 AND remote = '' AND state = 'failed')").run(name);
333 db.query("DELETE FROM pinned_lifetime WHERE pinned_id IN (SELECT id FROM pinned_forge WHERE name = ?1 AND remote = '' AND state = 'failed')").run(name);
306334 db.query("DELETE FROM pinned_forge WHERE name = ?1 AND remote = '' AND state = 'failed'").run(name);
307335 }
308336
src/http/api/admin.ts +9 −1
@@ -23,7 +23,7 @@ import { inviteLink, list as listInviteLinks, mint as mintInviteLink, revoke as
2323 import { changeLimit, listLimits } from "../../actions/limits.ts";
2424 import { changePlans } from "../../actions/plans.ts";
2525 import { setAccountCeilings, setAccountGrant } from "../../actions/model_grant.ts";
26 import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, claimPinned, deployPinned, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned } from "../../actions/pinned.ts";
26 import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, keepPinned, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, claimPinned, deployPinned, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned } from "../../actions/pinned.ts";
2727 import { TARGETS } from "../../cloud/targets.ts";
2828 import { changeQuotas, readQuotas } from "../../actions/quotas.ts";
2929 import { allowRequest, declineRequest, listRequests } from "../../actions/requests.ts";
@@ -122,6 +122,14 @@ export function adminRoutes(router: Router<Handler>): void {
122122 return done.ok ? json(done.value) : pinnedFail(done.error);
123123 });
124124
125 // Keep (#16696): the forge ends seven days later than it would have.
126 router.add("POST", "/api/v1/admin/pinned/:name/keep", (ctx) => {
127 const denied = accountAdmin(ctx, "admin");
128 if (denied) return denied;
129 const kept = keepPinned(ctx.app, ctx.auth.user, ctx.params.name!);
130 return kept.ok ? json(kept.value) : pinnedFail(kept.error);
131 });
132
125133 // Delete a forge's machine and keep its data; `withData` deletes the volume too, and
126134 // `despiteClaim` retires a forge its buyer has claimed.
127135 router.add("POST", "/api/v1/admin/pinned/:name/retire", async (ctx) => {
src/http/mcp/tools/pinned_forge.ts +11 −5
@@ -1,4 +1,4 @@
1 import { DOMAIN_WORDS, changeBaseDomain, checkPinned, checkWords, claimPinned, claimWords, deployPinned, fileForge, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, strayCloud, strayWords, updatePinned } from "../../../actions/pinned.ts";
1 import { DOMAIN_WORDS, endsWords, keepPinned, changeBaseDomain, checkPinned, checkWords, claimPinned, claimWords, deployPinned, fileForge, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, strayCloud, strayWords, updatePinned } from "../../../actions/pinned.ts";
22 import { TARGETS } from "../../../cloud/targets.ts";
33 import { scopeAllows } from "../../../core/tokens.ts";
44 import { good, bad, type Tool, str } from "../shared.ts";
@@ -6,7 +6,7 @@ import { good, bad, type Tool, str } from "../shared.ts";
66 export const tool: Tool = {
77 name: "pinned_forge",
88 listedTo: "admin",
9 doc: "`{ verb, name?, host?, domain?, withData?, despiteClaim?, target?, account?, app?, source?, version?, place?, config? }`: a forge on the owner's cloud. `deploy`: `app` from `source` at `version` on a writable `account`, at `place` (default: the small plan's), on `host` (default `<name>.<domain>`; Cloudflare writes the record); answers once with `claim.link` and `dns`. `claim`: a fresh link while unclaimed. `update`: change `version` or `config`. `rollback`: back one. `domain`: read or set the domain. `check`: `waiting` or `url`, `healthy`, `claim`. `retire`: delete the machine, keep the data (`withData` deletes it). `strays` (`target`, `account`): labelled machines and volumes no row owns. `file`: put its machine and volume in its cloud account's project (a forge made before the project was set). `list`: all, with changes. A forge admin with an admin-scope token",
9 doc: "`{ verb, name?, host?, domain?, withData?, despiteClaim?, target?, account?, app?, source?, version?, place?, config?, lifetimeDays? }`: a forge on the owner's cloud. `deploy`: `app` from `source` at `version` on a writable `account`, at `place` (default: the small plan's), on `host` (default `<name>.<domain>`; Cloudflare writes the record); answers once with `claim.link` and `dns`. `claim`: a fresh link. `update`: change `version` or `config`. `rollback`: back one. `domain`: read or set. `check`: `waiting` or `url`, `healthy`, `claim`. `retire`: delete the machine, keep the data (`withData` deletes it). `strays` (`target`, `account`): labelled machines and volumes no row owns. `file`: into its account's project. `keep`: 7 more days to `endsAt` (`deploy` sets `lifetimeDays`). `list`: all, with changes. A forge admin with an admin-scope token",
1010 description: "Pinned forges on your cloud: list, deploy, claim, update, rollback, check, retire (admin).",
1111 tier: "delete",
1212 deletes: (args) => args["verb"] === "retire" && args["withData"] === true,
@@ -14,7 +14,8 @@ export const tool: Tool = {
1414 inputSchema: {
1515 type: "object",
1616 properties: {
17 verb: { type: "string", enum: ["list", "deploy", "claim", "update", "rollback", "check", "domain", "retire", "file", "strays"] },
17 verb: { type: "string", enum: ["list", "deploy", "claim", "update", "rollback", "check", "domain", "retire", "file", "strays", "keep"] },
18 lifetimeDays: { type: "integer", minimum: 1, maximum: 90 },
1819 withData: { type: "boolean", description: "Retire: delete the data too; no undo." },
1920 despiteClaim: { type: "boolean", description: "Retire a forge its buyer claimed." },
2021 domain: { type: "string", maxLength: 253, description: "Domain for deployed forges; empty clears." },
@@ -34,7 +35,7 @@ export const tool: Tool = {
3435 writes: true,
3536 // Its listing is a read: the forge's agent is never held on it; a read-only token is still
3637 // refused.
37 heldNotWhen: (args) => args["verb"] === "list" || args["verb"] === "strays",
38 heldNotWhen: (args) => args["verb"] === "list" || args["verb"] === "strays" || args["verb"] === "keep",
3839 async run(ctx, user, args) {
3940 if (!user.isAdmin) return bad("not_found", "no such tool here");
4041 const verb = str(args["verb"]);
@@ -61,6 +62,7 @@ export const tool: Tool = {
6162 ? await deployPinned(ctx.app, user, {
6263 name, host: str(args["host"]), target: str(args["target"]), account: str(args["account"]), app: str(args["app"]),
6364 source: str(args["source"]), version: str(args["version"]), place: str(args["place"]), config: args["config"],
65 ...(typeof args["lifetimeDays"] === "number" ? { lifetimeDays: args["lifetimeDays"] } : {}),
6466 })
6567 : await claimPinned(ctx.app, user, name, { host: args["host"] === undefined ? undefined : str(args["host"]) });
6668 if (!made.ok) return bad("refused", made.error);
@@ -70,6 +72,10 @@ export const tool: Tool = {
7072 const done = await retirePinned(ctx.app, user, name, { withData: args["withData"] === true, despiteClaim: args["despiteClaim"] === true });
7173 return done.ok ? good({ says: retireWords(done.value), forge: done.value }) : bad("refused", done.error);
7274 }
75 if (verb === "keep") {
76 const kept = keepPinned(ctx.app, user, name);
77 return kept.ok ? good({ says: `${name} now ends ${endsWords(kept.value.endsAt!)}.`, forge: kept.value }) : bad("refused", kept.error);
78 }
7379 if (verb === "strays") {
7480 const seen = await strayCloud(ctx.app, user, str(args["target"]), str(args["account"]));
7581 return seen.ok ? good({ says: strayWords(seen.value), ...seen.value }) : bad("refused", seen.error);
@@ -91,7 +97,7 @@ export const tool: Tool = {
9197 : verb === "rollback"
9298 ? await rollbackPinned(ctx.app, user, name)
9399 : undefined;
94 if (done === undefined) return bad("bad_verb", "verb is list, deploy, claim, update, rollback, check, retire, file, strays or domain");
100 if (done === undefined) return bad("bad_verb", "verb is list, deploy, claim, update, rollback, check, retire, file, strays, keep or domain");
95101 if (!done.ok) return bad("refused", done.error);
96102 return good({ says: `${verb} ${name}: now ${done.value.version}, ${done.value.state}${done.value.url ? ` at ${done.value.url}` : ""}.`, forge: done.value });
97103 },
src/http/pinned_routes.ts +4 −1
@@ -7,7 +7,7 @@
77 * never through a redirect or a flash: it is shown once and stored nowhere.
88 */
99
10 import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, deployPinned, fileForge, deployPlaces, pinnedForges, retirePinned, retireWords, rollbackPinned, updatePinned, type Issued } from "../actions/pinned.ts";
10 import { DOMAIN_WORDS, endsWords, keepPinned, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, deployPinned, fileForge, deployPlaces, pinnedForges, retirePinned, retireWords, rollbackPinned, updatePinned, type Issued } from "../actions/pinned.ts";
1111 import { EXPERIMENT_WORDS, attachMachine, beginExperiment, experiments, recordResult } from "../cloud/experiments.ts";
1212 import { TARGETS } from "../cloud/targets.ts";
1313 import { listCloudAccounts } from "../core/cloud_account.ts";
@@ -115,6 +115,9 @@ async function pinnedAct(ctx: Ctx): Promise<Response> {
115115 // the confirm page. A claimed forge is retired only when the form says the owner means it.
116116 const gone = await retirePinned(ctx.app, user, name, { withData: act === "retire-data", despiteClaim: field(form, "despite_claim") === "1" });
117117 return flashTo(ctx, "/pinned", gone.ok ? { tone: "success", message: retireWords(gone.value) } : { tone: "danger", message: gone.error });
118 } else if (act === "keep") {
119 const kept = keepPinned(ctx.app, user, name);
120 return flashTo(ctx, "/pinned", kept.ok ? { tone: "success", message: `${name} now ends ${endsWords(kept.value.endsAt!)}.` } : { tone: "danger", message: kept.error });
118121 } else if (act === "file") {
119122 const filed = await fileForge(ctx.app, user, name);
120123 return flashTo(ctx, "/pinned", filed.ok ? { tone: "success", message: filed.value } : { tone: "danger", message: filed.error });
src/maintain/duties/pinned_lifetimes.ts added +77
@@ -0,0 +1,77 @@
1 /**
2 * Pinned forge lifetimes (#16696): every quarter hour, read each forge's lifetime from its row.
3 * A day before it ends, say so once: one `pinned.ending_soon` event and one finding the owner
4 * reads where the cloud watch's are. At its end, retire its machine and keep its data, through the
5 * same retire every door uses, and say `pinned.ended`. A forge its buyer claimed never ends on its
6 * own: its lifetime is cleared, with `pinned.lifetime_cleared` saying why. The rows are the state,
7 * so a restart loses nothing and a late run catches up.
8 */
9
10 import type { App } from "../../app.ts";
11 import { LIFETIME_DAYS, endsWords, retirePinned } from "../../actions/pinned.ts";
12 import { lifetimes, listPinned, markWarned, setLifetime } from "../../core/pinned.ts";
13 import type { Duty, Finding } from "../duty.ts";
14
15 const WARN_MS = 86_400_000;
16
17 /** One pass over every lifetime; `retire` is the lifetime retire, a seam for tests only. */
18 export async function tickLifetimes(
19 app: App,
20 now: Date,
21 retire: (app: App, name: string) => ReturnType<typeof retirePinned> = (a, name) => retirePinned(a, "lifetime", name),
22 ): Promise<{ findings: Finding[]; actions: string[] }> {
23 const findings: Finding[] = [];
24 const actions: string[] = [];
25 const forges = new Map(listPinned(app.db).map((p) => [p.id, p]));
26 for (const l of lifetimes(app.db)) {
27 const p = forges.get(l.pinnedId);
28 if (p === undefined || p.state === "retired") {
29 setLifetime(app.db, l.pinnedId, undefined);
30 continue;
31 }
32 if (p.claimedAt !== "") {
33 setLifetime(app.db, p.id, undefined);
34 app.bus.append({
35 kind: "pinned.lifetime_cleared",
36 payload: { name: p.name, why: "claimed by its buyer, so it never ends on its own" },
37 });
38 actions.push(`cleared ${p.name}'s lifetime: its buyer claimed it`);
39 continue;
40 }
41 const ends = Date.parse(l.endsAt);
42 if (ends <= now.getTime()) {
43 const gone = await retire(app, p.name);
44 if (gone.ok) {
45 setLifetime(app.db, p.id, undefined);
46 app.bus.append({ kind: "pinned.ended", payload: { name: p.name, endsAt: l.endsAt, dataKept: gone.value.volume !== "" } });
47 actions.push(`retired ${p.name} at the end of its lifetime, its data kept`);
48 } else if (gone.error.includes("claimed")) {
49 setLifetime(app.db, p.id, undefined);
50 app.bus.append({ kind: "pinned.lifetime_cleared", payload: { name: p.name, why: gone.error } });
51 actions.push(`cleared ${p.name}'s lifetime: ${gone.error}`);
52 } else findings.push({ summary: `${p.name} reached the end of its lifetime and could not be retired: ${gone.error}` });
53 continue;
54 }
55 if (ends - now.getTime() <= WARN_MS && markWarned(app.db, p.id, now.toISOString())) {
56 app.bus.append({ kind: "pinned.ending_soon", payload: { name: p.name, endsAt: l.endsAt } });
57 findings.push({
58 summary: `${p.name} ends ${endsWords(l.endsAt, now)}: Keep it on /pinned for ${LIFETIME_DAYS} more days, or let it retire with its data kept`,
59 });
60 }
61 }
62 return { findings, actions };
63 }
64
65 export const duty: Duty = {
66 name: "pinned-lifetimes",
67 intervalMs: 15 * 60_000,
68 budget: {
69 runsPerDay: 110,
70 dollarsPerDay: 1,
71 reason: "every quarter hour is 96 a day, the rest room for a catch-up; it reads rows and retires only a forge whose time is up",
72 },
73 async run({ app, now }) {
74 if (app === undefined) return { findings: [], actions: [] };
75 return tickLifetimes(app, now);
76 },
77 };
src/tui/screens/pinned.ts +8 −5
@@ -12,7 +12,7 @@
1212 * nothing and does nothing.
1313 */
1414
15 import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, claimWords, deployPinned, fileForge, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, strayCloud, strayWords, updatePinned, type Issued } from "../../actions/pinned.ts";
15 import { DOMAIN_WORDS, endsWords, keepPinned, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, claimWords, deployPinned, fileForge, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, strayCloud, strayWords, updatePinned, type Issued } from "../../actions/pinned.ts";
1616 import type { Ctx, Screen } from "../app/app.ts";
1717 import { binding } from "../app/keys.ts";
1818 import { style } from "../term/style.ts";
@@ -164,9 +164,9 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen {
164164
165165 const screen: Screen = {
166166 title: "Pinned forges",
167 keys: [binding(["j", "k"], "move cursor"), binding(["d"], "deploy"), binding(["u"], "update"), binding(["r"], "roll back"), binding(["c"], "check"), binding(["f"], "file in its cloud project"), binding(["n"], "new claim link"), binding(["b"], "domain for forges"), binding(["p"], "paid forges run on"), binding(["s"], "strays in a cloud account"), binding(["x"], "retire")],
167 keys: [binding(["j", "k"], "move cursor"), binding(["d"], "deploy"), binding(["u"], "update"), binding(["r"], "roll back"), binding(["c"], "check"), binding(["f"], "file in its cloud project"), binding(["n"], "new claim link"), binding(["b"], "domain for forges"), binding(["p"], "paid forges run on"), binding(["s"], "strays in a cloud account"), binding(["x"], "retire"), binding(["e"], "keep 7 more days")],
168168 async load(signal) {
169 live(f, signal, { kinds: ["pinned.deployed", "pinned.update", "pinned.rollback", "pinned.check", "pinned.claim_issued", "pinned.claimed"] }, () => ctx.invalidate());
169 live(f, signal, { kinds: ["pinned.deployed", "pinned.update", "pinned.rollback", "pinned.check", "pinned.claim_issued", "pinned.claimed", "pinned.kept", "pinned.ended", "pinned.retired"] }, () => ctx.invalidate());
170170 },
171171 render(area, s) {
172172 const c = ctx.theme.c;
@@ -178,7 +178,7 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen {
178178 const rows: ListRow[] = forges().map((p) => ({
179179 title: p.name,
180180 ...(p.state === "failed" ? { tone: "danger" as const } : {}),
181 secondary: `${p.target} · ${short(p.version)} · ${p.state}${p.url !== "" ? ` · ${p.url}` : ""}${p.stuck === "" ? "" : ` · ${p.stuck}`}`,
181 secondary: `${p.target} · ${short(p.version)} · ${p.state}${p.endsAt === null || p.state === "retired" ? "" : ` · ends ${endsWords(p.endsAt)}`}${p.url !== "" ? ` · ${p.url}` : ""}${p.stuck === "" ? "" : ` · ${p.stuck}`}`,
182182 meta: p.changes[0] ? `${p.changes[0].kind} ${p.changes[0].at.slice(0, 16).replace("T", " ")}` : "",
183183 }));
184184 drawList(s, list!, c, state, rows);
@@ -241,7 +241,10 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen {
241241 void fileForge(f.app, f.user, p.name).then((r) => say(r.ok ? r.value : r.error));
242242 } else if (e.key === "n") offerClaim(f, ctx, screen, say, p);
243243 else if (e.key === "x") offerRetire(f, ctx, screen, say, p);
244 else if (e.key === "u")
244 else if (e.key === "e") {
245 const kept = keepPinned(f.app, f.user, p.name);
246 say(kept.ok ? `${p.name} now ends ${endsWords(kept.value.endsAt!)}.` : kept.error);
247 } else if (e.key === "u")
245248 ctx.push(
246249 promptScreen(ctx, screen, {
247250 title: `Update ${p.name}`,
src/web/pages/pinned.ts +16 −4
@@ -4,7 +4,7 @@
44 * is when the newest `pinned.check` event for the forge was written.
55 */
66
7 import type { PinnedView } from "../../actions/pinned.ts";
7 import { LIFETIME_DAYS, endsWords, type PinnedView } from "../../actions/pinned.ts";
88 import type { Experiment, Experiments, Machine } from "../../cloud/experiments.ts";
99 import { dollars } from "../../cloud/prices.ts";
1010 import { billsWords } from "../../cloud/billing.ts";
@@ -41,6 +41,14 @@ const retireForm = (name: string, act: "retire" | "retire-data", label: string,
4141 ${btn(label, { variant: "ghost", label: `${label}: ${name}` })}
4242 </form>`;
4343
44 /** Keep (#16696): the forge ends `LIFETIME_DAYS` later; a reversible change, so no confirm page. */
45 const keepForm = (name: string): Html => html`<form method="post" action="/pinned/${name}/keep">
46 ${btn(`Keep ${LIFETIME_DAYS} more days`, { variant: "ghost", label: `Keep ${name} ${LIFETIME_DAYS} more days` })}
47 </form>`;
48
49 /** A forge with a lifetime: Keep, and End now, which is Retire through its confirm. */
50 const lifetimeActions = (name: string, claimed: boolean): Html => html`${keepForm(name)}${retireForm(name, "retire", "End now", claimed)}`;
51
4452 /**
4553 * Update asks for the version, Roll back, Check and New claim link for nothing (a forge deployed
4654 * before forges had names is asked for its hostname); each goes through the confirm page, which
@@ -78,14 +86,17 @@ function actions(p: PinnedView): Html {
7886 ${p.host === "" ? html`<input class="mono" name="host" placeholder="forge.example.com" maxlength="253" required spellcheck="false" autocomplete="off" aria-label="Hostname for ${p.name}" />` : null}
7987 ${btn("New claim link", { variant: "ghost", label: `New claim link for ${p.name}` })}
8088 </form>
81 ${retire("retire", "Retire", false)}
89 ${p.endsAt === null ? retire("retire", "Retire", false) : lifetimeActions(p.name, false)}
8290 ${retire("retire-data", "Retire and delete its data", false)}
8391 </div>`;
8492 }
8593
8694 const month = (cents: number): string => `${dollars(cents)} a month`;
8795 const machineLine = (m: Machine): Html =>
88 html`<a class="mono" href="#forge-${m.name}">${m.name}</a> on ${m.account}, ${m.until !== "" ? "moved on" : billsWords(m)}, ${month(m.monthlyCents)}`;
96 html`<a class="mono" href="#forge-${m.name}">${m.name}</a> on ${m.account}, ${m.until !== "" ? "moved on" : billsWords(m)}, ${month(m.monthlyCents)}${m.endsAt === null || m.until !== "" ? "" : `, ends ${endsWords(m.endsAt)}`}`;
97 /** A machine on an experiment now, with its lifetime's Keep and End now where it stands. */
98 const machineWithEnd = (m: Machine): Html =>
99 m.endsAt === null || m.until !== "" || m.bills !== "machine" ? machineLine(m) : html`${machineLine(m)}<span class="row-fields">${lifetimeActions(m.name, false)}</span>`;
89100
90101 /**
91102 * One idle machine: its name and what it costs lead (a row's title is one line, so the money is
@@ -123,7 +134,7 @@ function experimentRow(e: Experiment): Html {
123134 data: { experiment: e.id },
124135 trail: badge(e.state, { tone: e.state === "running" ? "success" : "default" }),
125136 facts: [
126 { label: "Runs on", value: e.machines.length === 0 ? "no machine yet" : html`${e.machines.map((m, i) => html`${i > 0 ? "; " : ""}${machineLine(m)}`)}` },
137 { label: "Runs on", value: e.machines.length === 0 ? "no machine yet" : html`${e.machines.map((m, i) => html`${i > 0 ? "; " : ""}${machineWithEnd(m)}`)}` },
127138 { label: "Costs now", value: month(e.monthlyCents) },
128139 { label: "Has cost", value: `about ${dollars(e.spentCents)} since ${e.startedAt.slice(0, 10)}` },
129140 { label: "Result", value: e.result === "" ? "not recorded" : e.result },
@@ -183,6 +194,7 @@ function forge(p: PinnedView, f: PinnedFacts): Html {
183194 ${fact("Health", badge(p.state, { tone: TONE[p.state] ?? "default" }))}
184195 ${fact("Last check", checked ? time(checked) : none("never checked"))}
185196 ${fact("Last change", last ? html`${last.kind} to <span class="mono">${last.toVersion.slice(0, 12)}</span>` : none("none"))}
197 ${p.state === "retired" ? null : fact("Ends", p.endsAt === null ? none("never on its own") : html`${endsWords(p.endsAt)}`)}
186198 ${fact("Claimed by its buyer", p.claimedAt === "" ? none("not as of the last check") : time(p.claimedAt))}
187199 ${last ? fact("Changed by", html`${f.names.get(last.by) ?? last.by} ${time(last.at)}`) : null}
188200 </dl>
test/openapi-errors.test.ts +1 −1
@@ -29,7 +29,7 @@ const BASE = "http://localhost";
2929 /** Not called: these would end the session, stop the forge or reach beyond the test's own data. */
3030 const NOT_CALLED = /\/(sessions|maintenance|migrate|first-admin|heartbeat|release|fleet-ops|drills|forges|sandbox|broker|admin\/(pinned|releases|accounts|settings))/;
3131 /** How many routes NOT_CALLED leaves out; a change to it changes this on purpose. */
32 const SKIPPED = 56;
32 const SKIPPED = 57;
3333
3434 let dataDir: string;
3535 let app: App;
test/pinned-lifetimes.test.ts added +261
@@ -0,0 +1,261 @@
1 /**

Missing: deploy lifetimeDays validation, the page keep route, the API keep route with its role check, dropPinned clearing the row, and Keep refused on a forge with no lifetime.

2 * Pinned forge lifetimes (#16696): a forge put on an experiment ends a week on; Keep moves that a
3 * week later at every door; a day before, the duty says so once; at the end it retires the
4 * machine with the data kept and says `pinned.ended`; a claimed forge never ends on its own. No
5 * socket: the duty's retire is the seam, and the doors are called as their routes call them.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { LIFETIME_DAYS, deployPinned, endsWords, keepPinned, pinnedForges, type Retired } from "../src/actions/pinned.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { attachMachine, beginExperiment } from "../src/cloud/experiments.ts";
14 import type { ForgeEvent } from "../src/core/events.ts";
15 import { dropPinned, getPinned, insertPinned, lifetimeOf, markClaimed, setLifetime, setRemote } from "../src/core/pinned.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { forgeHttp } from "../src/http/server.ts";
18 import { createUser, getUserByName, type User } from "../src/core/users.ts";
19 import { tool } from "../src/http/mcp/tools/pinned_forge.ts";
20 import { tickLifetimes } from "../src/maintain/duties/pinned_lifetimes.ts";
21 import { ok } from "../src/kernel/result.ts";
22 import { createForgeApp } from "../src/tui/forge.ts";
23 import { pinnedScreen } from "../src/tui/screens/pinned.ts";
24 import { headlessTerminal } from "../src/tui/term/terminal.ts";
25 import { pinnedListPage } from "../src/web/pages/pinned.ts";
26 import { quietLogs } from "./helpers/globals.ts";
27 import { seedPlaces } from "./helpers/places-fixture.ts";
28 import { settleApp } from "./helpers/tui.ts";
29
30 quietLogs();
31
32 const DAY = 86_400_000;
33
34 describe("pinned forge lifetimes", () => {
35 let dataDir = "";
36 let app: App;
37 let admin: User;
38 const seen: ForgeEvent[] = [];
39 const kinds = (k: string) => seen.filter((e) => e.kind === k);
40 const make = (name: string) => {
41 insertPinned(
42 app.db,
43 {
44 name,
45 target: "digitalocean",
46 account: "main",
47 app: "trevato/forge",
48 source: "https://forge.example.org/trevato/forge",
49 version: "a".repeat(40),
50 config: {},
51 host: `${name}.forge.test`,
52 claimHash: "",
53 claimExpires: "",
54 datacenter: "nyc3",
55 size: "s-1vcpu-2gb",
56 },
57 admin.id,
58 );
59 setRemote(app.db, name, { remote: `d-${name}`, volume: `v-${name}`, state: "running" });
60 return getPinned(app.db, name)!;
61 };
62 /** The duty's retire, standing in for the cloud: the machine goes, the volume stays. */
63 const retired: string[] = [];
64 const fakeRetire = async (a: App, name: string) => {
65 retired.push(name);
66 setRemote(a.db, name, { remote: "", state: "retired" });
67 return ok({ ...getPinned(a.db, name)!, dnsRemoved: "none" } as unknown as Retired);
68 };
69
70 beforeAll(async () => {
71 dataDir = await mkdtemp(join(tmpdir(), "forge-lifetimes-"));
72 app = createApp({ dataDir, port: 0 });
73 await seedPlaces(app.db);
74 const made = await createUser(app.db, {
75 origin: "seed",
76 trusted: true,
77 username: "alice",
78 email: "[email protected]",
79 password: "a-good-passphrase",
80 adminIfFirst: true,
81 });
82 if (!made.ok) throw new Error(made.error);
83 admin = getUserByName(app.db, "alice")!;
84 app.bus.subscribe((e) => {
85 if (e.kind.startsWith("pinned.")) seen.push(e);
86 }, "local");
87 }, 30_000);
88
89 afterAll(async () => {
90 app.close();
91 await rm(dataDir, { recursive: true, force: true });
92 });
93
94 test("an end reads as a day and a distance, never a raw ISO", () => {
95 expect(endsWords("2026-12-03T10:00:00.000Z", new Date("2026-11-27T10:00:00.000Z"))).toBe("Thu 3 Dec (in 6 days)");
96 expect(endsWords("2026-11-28T09:00:00.000Z", new Date("2026-11-27T10:00:00.000Z"))).toBe("Sat 28 Nov (tomorrow)");
97 });
98
99 test("a forge put on an experiment ends a week on; one with no experiment never does", () => {
100 const p = make("exp1");
101 make("plain1");
102 expect(lifetimeOf(app.db, getPinned(app.db, "plain1")!.id)).toBeUndefined();
103 const e = beginExperiment(app, admin.id, "Does a week tell us?", []);
104 if (!e.ok) throw new Error(e.error);
105 expect(attachMachine(app, admin.id, e.value, "exp1").ok).toBe(true);
106 const ends = Date.parse(lifetimeOf(app.db, p.id)!.endsAt);
107 expect(Math.abs(ends - (Date.now() + LIFETIME_DAYS * DAY))).toBeLessThan(60_000);
108 const view = pinnedForges(app, admin);
109 expect(view.ok && view.value.find((v) => v.name === "plain1")!.endsAt).toBeNull();
110 });
111
112 test("a claimed forge put on an experiment gets no end", () => {
113 const p = make("sold1");
114 markClaimed(app.db, "sold1");
115 const e = beginExperiment(app, admin.id, "Does the buyer use it?", ["sold1"]);
116 expect(e.ok).toBe(true);
117 expect(lifetimeOf(app.db, p.id)).toBeUndefined();
118 });
119
120 test("Keep moves the end a week later, owes the warning again, says pinned.kept, and refuses a claimed forge", () => {
121 const p = getPinned(app.db, "exp1")!;
122 const before = Date.parse(lifetimeOf(app.db, p.id)!.endsAt);
123 const kept = keepPinned(app, admin, "exp1");
124 expect(kept.ok).toBe(true);
125 expect(Date.parse(lifetimeOf(app.db, p.id)!.endsAt)).toBe(before + LIFETIME_DAYS * DAY);
126 expect(lifetimeOf(app.db, p.id)!.warnedAt).toBe("");
127 expect(kinds("pinned.kept").map((e) => e.payload["name"])).toEqual(["exp1"]);
128 expect(keepPinned(app, admin, "sold1").ok).toBe(false);
129 expect(keepPinned(app, undefined, "exp1").ok).toBe(false);
130 });
131
132 test("Keep never gives an end to a forge that had none", () => {
133 const plain = getPinned(app.db, "plain1")!;
134 const kept = keepPinned(app, admin, "plain1");
135 expect(kept.ok ? "" : kept.error).toContain("has no end to extend");
136 expect(lifetimeOf(app.db, plain.id)).toBeUndefined();
137 });
138
139 test("deploy refuses a lifetime that is not 1 to 90 whole days, before anything is made", async () => {
140 const base = { name: "life-check", host: "", target: "digitalocean", account: "main", app: "trevato/forge", source: "https://forge.example.org/trevato/forge", version: "a".repeat(40) };
141 for (const lifetimeDays of [0, 91, 2.5, -1]) {
142 const r = await deployPinned(app, admin, { ...base, lifetimeDays });
143 expect(r.ok ? "" : r.error, `lifetimeDays ${lifetimeDays}`).toContain("A lifetime is a whole number of days, 1 to 90");
144 }
145 const fine = await deployPinned(app, admin, { ...base, lifetimeDays: 3 });
146 expect(fine.ok ? "" : fine.error, "a good lifetime passes that check").not.toContain("A lifetime is");
147 expect(getPinned(app.db, "life-check")?.state ?? "none", "a refused deploy makes no row").not.toBe("running");
148 });
149
150 test("dropping a deploy that never reached a machine drops its lifetime too", () => {
151 const p = make("never1");
152 setRemote(app.db, "never1", { remote: "", volume: "", state: "failed" });
153 setLifetime(app.db, p.id, new Date(Date.now() + DAY).toISOString());
154 dropPinned(app.db, "never1");
155 expect(getPinned(app.db, "never1")).toBeUndefined();
156 expect(lifetimeOf(app.db, p.id)).toBeUndefined();
157 });
158
159 test("the page's and the API's keep routes move the end; anyone but an admin is refused", async () => {
160 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
161 if (!made.ok) throw new Error(made.error);
162 const adminTok = createToken(app.db, admin.id, "admin", "admin").token;
163 const bobTok = createToken(app.db, made.value.id, "admin", "admin").token;
164 const http = forgeHttp(app);
165 const ORIGIN = "http://forge.test";
166 const post = (path: string, tok: string, form = true) =>
167 http.handle(new Request(ORIGIN + path, {
168 method: "POST",
169 headers: { authorization: `Bearer ${tok}`, origin: ORIGIN, "content-type": form ? "application/x-www-form-urlencoded" : "application/json" },
170 body: form ? "" : "{}",
171 }));
172 const p = make("route1");
173 setLifetime(app.db, p.id, new Date(Date.now() + 2 * DAY).toISOString());
174 const end = () => Date.parse(lifetimeOf(app.db, p.id)!.endsAt);
175 const t0 = end();
176
177 const page = await post("/pinned/route1/keep", adminTok);
178 expect(page.status, "the page's form").toBe(303);
179 expect(page.headers.get("location") ?? "").toStartWith("/pinned");
180 expect(end()).toBe(t0 + LIFETIME_DAYS * DAY);
181 expect([403, 404], "a non-admin at the page").toContain((await post("/pinned/route1/keep", bobTok)).status);
182 expect(end(), "a refused keep changes nothing").toBe(t0 + LIFETIME_DAYS * DAY);
183
184 const api = await post("/api/v1/admin/pinned/route1/keep", adminTok, false);
185 expect(api.status, "the API").toBe(200);
186 expect(((await api.json()) as { endsAt: string }).endsAt).toBe(new Date(t0 + 2 * LIFETIME_DAYS * DAY).toISOString());
187 expect([403, 404], "a non-admin at the API").toContain((await post("/api/v1/admin/pinned/route1/keep", bobTok, false)).status);
188 expect((await post("/api/v1/admin/pinned/plain1/keep", adminTok, false)).status, "no end to extend").toBe(422);
189 expect(end()).toBe(t0 + 2 * LIFETIME_DAYS * DAY);
190 });
191
192 test("a day before its end the duty says so once: one event and one finding", async () => {
193 const p = make("soon1");
194 const now = new Date();
195 setLifetime(app.db, p.id, new Date(now.getTime() + 20 * 3_600_000).toISOString());
196 const first = await tickLifetimes(app, now, fakeRetire);
197 const second = await tickLifetimes(app, new Date(now.getTime() + 60_000), fakeRetire);
198 expect(kinds("pinned.ending_soon").map((e) => e.payload["name"])).toEqual(["soon1"]);
199 expect(first.findings.map((f) => f.summary).join(" ")).toContain("soon1 ends");
200 expect(second.findings).toEqual([]);
201 expect(retired).toEqual([]);
202 });
203
204 test("at its end the forge's machine is retired with its data kept, pinned.ended is said, and its end is cleared", async () => {
205 const p = getPinned(app.db, "soon1")!;
206 const after = new Date(Date.now() + 2 * DAY);
207 const r = await tickLifetimes(app, after, fakeRetire);
208 expect(retired).toEqual(["soon1"]);
209 expect(r.actions.join(" ")).toContain("retired soon1");
210 expect(kinds("pinned.ended").map((e) => [e.payload["name"], e.payload["dataKept"]])).toEqual([["soon1", true]]);
211 expect(getPinned(app.db, "soon1")!.volume).toBe("v-soon1");
212 expect(lifetimeOf(app.db, p.id)).toBeUndefined();
213 await tickLifetimes(app, new Date(after.getTime() + DAY), fakeRetire);
214 expect(retired).toEqual(["soon1"]);
215 });
216
217 test("a forge its buyer claimed is skipped: its end is cleared and the reason said", async () => {
218 const p = make("late1");
219 setLifetime(app.db, p.id, new Date(Date.now() - 60_000).toISOString());
220 markClaimed(app.db, "late1");
221 await tickLifetimes(app, new Date(), fakeRetire);
222 expect(retired).not.toContain("late1");
223 expect(lifetimeOf(app.db, p.id)).toBeUndefined();
224 expect(kinds("pinned.lifetime_cleared").map((e) => e.payload["name"])).toEqual(["late1"]);
225 });
226
227 test("the doors: the page's Ends fact with Keep and End now, the MCP keep, the terminal's e", async () => {
228 const forges = pinnedForges(app, admin);
229 if (!forges.ok) throw new Error("not admin");
230 const page = String(pinnedListPage(forges.value, { names: new Map(), checks: new Map(), domain: "" }));
231 const ends = getPinned(app.db, "exp1")!;
232 expect(page).toContain(`<dt>Ends</dt><dd>${endsWords(lifetimeOf(app.db, ends.id)!.endsAt)}</dd>`);
233 expect(page).toContain('action="/pinned/exp1/keep"');
234 expect(page).toContain('value="/pinned/exp1/retire"');
235 expect(page).toContain("End now");
236 expect(page).not.toMatch(/<dt>Ends<\/dt><dd>\d{4}-/);
237
238 const before = Date.parse(lifetimeOf(app.db, ends.id)!.endsAt);
239 const call = await tool.run({ app, auth: { user: admin, scope: "admin" } } as any, admin, { verb: "keep", name: "exp1" });
240 expect((call as any).ok).toBe(true);
241 expect(Date.parse((call as any).value.forge.endsAt)).toBe(before + LIFETIME_DAYS * DAY);
242 expect(tool.heldNotWhen?.({ verb: "keep" })).toBe(true);
243 const listed: any = await tool.run({ app, auth: { user: admin, scope: "admin" } } as any, admin, { verb: "list" });
244 expect(listed.value.items.find((f: { name: string }) => f.name === "exp1").endsAt).toBe(lifetimeOf(app.db, ends.id)!.endsAt);
245
246 const { app: tui, session } = createForgeApp(
247 app,
248 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin },
249 { terminal: headlessTerminal(160, 24), exitHooks: false },
250 );
251 tui.start();
252 tui.ctx.push(pinnedScreen(session, tui.ctx));
253 await settleApp(tui);
254 const mid = Date.parse(lifetimeOf(app.db, ends.id)!.endsAt);
255 tui.dispatch({ type: "key", key: "e", ctrl: false, alt: false, shift: false });
256 await settleApp(tui);
257 expect(Date.parse(lifetimeOf(app.db, ends.id)!.endsAt)).toBe(mid + LIFETIME_DAYS * DAY);
258 expect(tui.screen.toText()).toContain("exp1 now ends");
259 tui.stop?.();
260 });
261 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs