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

Self-deploy, step 4: rollback to a kept release, from `--rollback <sha>` and a writer's button on a releases page that lists sha, landing and healthy-since #1778

Closed opened this
Closed without merging

scout/forge:scout/1664-self-deploy-step-4-rollback-to-a-kept-re → main 9 commits fork 7 threads · 7 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
40 files changed +817 −11
.bash_profile added
No content changes.
.bashrc added
No content changes.
.claude/agents added
No content changes.
.claude/commands added
No content changes.
.claude/hooks added
No content changes.
.claude/launch.json added
No content changes.
.claude/loop.md added
No content changes.
.claude/output-styles added
No content changes.
.claude/routines added
No content changes.
.claude/scheduled_tasks.json added
No content changes.
.claude/settings.json added
No content changes.
.claude/settings.local.json added
No content changes.
.claude/skills added
No content changes.
.claude/workflows added
No content changes.
.gitconfig added
No content changes.
.gitmodules added
No content changes.
.idea added
No content changes.
.mcp.json added
No content changes.
.profile added
No content changes.
.ripgreprc added
No content changes.
.vscode added
No content changes.
.zprofile added
No content changes.
.zshrc added
No content changes.
README.md +2
@@ -40,6 +40,8 @@ bun src/main.ts --preflight # can this tree boot? config parses, migrations run
4040
4141 Set `FORGE_REPO=owner/name` to the forge's own code and a pull the crew lands there is written to `$FORGE_DATA/releases/<sha>/` (the newest `FORGE_RELEASES_KEEP`, default 5, are kept), preflighted with that tree's own `--preflight`, and recorded in the `release` table (sha, landed pull, verdict, its line, when). A red preflight is asked again once (the copy of the live database can tear under load); a second red is logged and told to the landed pull. Other repositories are untouched, and nothing is swapped unless `FORGE_SELF_SWAP=1`: then the forge binds its port with SO_REUSEPORT, a green release is started from `releases/<sha>/` beside it on the same port (`FORGE_COMMIT` set to the sha), `/api/v1/health` is read until an answer names that sha and is well (`FORGE_SWAP_BUDGET_S`, default 60), and only then does this process drain as a SIGTERM does. A release not healthy in its budget is killed, the old keeps serving, and the log and the landed pull say so. One swap per process: a landing while another swap is in its budget, or after one succeeded, is released and recorded but not started (the new process runs it from the next restart). The SSH terminal is not handed over yet (the new process cannot bind the old one's port), so a process holding the SSH listener refuses the swap and tells the landed pull; run with `FORGE_SSH_PORT=0` to swap. The swap also needs `net.ipv4.tcp_migrate_req=1` (Linux 5.14+): without it the kernel resets the connections still queued on the old listener when it closes, so a swap is refused (and told to the landed pull) rather than failing requests. The release is a child of the old process, so the swap is for a forge run directly, not under a supervisor that kills its children when the old process exits (PID 1 of a container, a systemd unit with the default `KillMode=control-group`). SO_REUSEPORT lets any process of the forge's user bind the same port and take a share of its connections, so `FORGE_SELF_SWAP=1` assumes nothing else runs as the forge's user on the host network (agents and apps are sandboxed or in cells). `FORGE_REPO` also names the parent code that spawned child forges fork.
4242
43 Rolling back: `bun src/main.ts --rollback <sha>` (a full sha or a unique prefix of 7 or more) starts a kept `releases/<sha>/` through the same hand-over, with the same `PORT`, `FORGE_DATA` and `FORGE_SSH_PORT=0`, then SIGTERMs the serving process named in `$FORGE_DATA/forge.pid` — only when that pid is alive and a forge answers `/api/v1/health` on `PORT` (a crash leaves a stale file; the forge removes it on a clean exit), otherwise the rollback is refused before anything starts; a sha that is not kept is refused in one line and exit 1. `/releases` lists every release (sha, landed pull, when, healthy since, the live one marked) and shows a writer of `FORGE_REPO` a Roll back button on each kept, green, not-live one; the page needs read access to `FORGE_REPO` (anyone else gets a 404); the home says `live: <sha> since <time>`. Over SSH, `ssh <terminal> releases` prints the same rows and `ssh <terminal> rollback <sha>` is refused with a line pointing to `/releases` or `--rollback`, because the process holding the SSH listener cannot hand it over (a non-writer is told only a writer may; the terminal is the one in `FORGE_SSH_PORT`; git is the only other exec command). A rollback boots an older tree on the newer schema, so a build with the migration table now serves on a database ahead of it instead of refusing (migrations only add: `test/schema-additive.test.ts`). The CLI cannot tell which commit is serving, so it does not refuse the live sha; the button does.
outdated

Once the commands exist, say how to list releases and roll back from the SSH terminal too.

44
4345 If your shell already has `FORGE_URL` set — a crew workspace sets it to the
4446 forge you work for — this forge takes it as its own canonical address and
4547 refuses every form a browser posts to `localhost`: run it with
scripts/gate.ts +1
@@ -72,6 +72,7 @@ export const GATE: readonly string[] = [
7272 "test/recovery-doc.test.ts",
7373 "test/release-checkout.test.ts",
7474 "test/release-preflight.test.ts",
75 "test/release-rollback.test.ts",
7576 "test/release-swap.test.ts",
7677 "test/threats-doc.test.ts",
7778 "test/returns.test.ts",
src/core/reserved.ts +1
@@ -93,6 +93,7 @@ export const SYSTEM_NAMES: readonly string[] = [
9393 "signin",
9494 "signup",
9595 "sitemap.xml",
96 "releases",
9697 "releases.json",
9798 "sw.js",
9899 "tell",
src/core/schema.ts +10
@@ -1754,6 +1754,16 @@ export const migrations: readonly string[] = [
17541754 );
17551755 CREATE INDEX deploy_pull_issue ON deploy_pull(issue_id);
17561756 `,
1757 // 87 — what is live (#1664): one row each time a process comes up as a
1758 // release commit, so the releases page can say "healthy since".
1759 `
1760 CREATE TABLE release_live (
1761 id INTEGER PRIMARY KEY AUTOINCREMENT,
1762 sha TEXT NOT NULL,
1763 since TEXT NOT NULL
1764 );
1765 CREATE INDEX release_live_sha ON release_live(sha, id);
1766 `,
17571767 ];
17581768
17591769 /**
src/http/server.ts +3
@@ -106,6 +106,7 @@ import { confirmPage, searchPage } from "../web/pages/search.ts";
106106 import { followingSubmit } from "../web/pages/following.ts";
107107 import { reconnectSubmit } from "../web/pages/frozen.ts";
108108 import { activityAtom } from "../web/feeds.ts";
109 import { releasesPage, releasesRollback } from "../web/pages/releases.ts";
109110 import { auditCsv, auditPage, auditProbeSubmit } from "../web/pages/audit.ts";
110111 import { secretDelete, secretSet, secretsPage } from "../web/pages/secrets.ts";
111112 import {
@@ -616,6 +617,8 @@ export function buildRouter(): Router<Handler> {
616617 // is registered before /:owner/:name can claim the shape.
617618 router.add("GET", "/-/confirm", confirmPage);
618619 router.add("GET", "/new", newRepoPage);
620 router.add("GET", "/releases", releasesPage);
621 router.add("POST", "/releases/rollback", releasesRollback);
619622 router.add("GET", "/audit", auditPage);
620623 router.add("GET", "/audit.csv", auditCsv);
621624 router.add("POST", "/audit/:owner/:name/probe", auditProbeSubmit);
src/kernel/guard.ts +3
@@ -38,6 +38,8 @@ export interface ForgeHealth {
3838 readonly version: string;
3939 readonly commit: string | null;
4040 readonly draining: boolean;
41 /** The answering process, so `--rollback` signals the forge it means (#1664). */
42 readonly pid: number;
4143 readonly rollout: Rollout;
4244 readonly incidents: Incident[];
4345 readonly stale: boolean;
@@ -120,6 +122,7 @@ export function forgeHealth(
120122 version,
121123 commit,
122124 draining: health.draining,
125 pid: process.pid,
123126 rollout,
124127 incidents: guard.incidents,
125128 stale,
src/kernel/migrate.ts +6 −7
@@ -21,7 +21,8 @@
2121 *
2222 * `user_version` is still written — the count of applied migrations — so a
2323 * build from before this table refuses a database that is ahead of it the
24 * way it always did.
24 * way it always did. A build with the table does not: it serves on a newer
25 * schema, since migrations only add, which is how a rollback boots.
2526 */
2627
2728 import type { Database } from "bun:sqlite";
@@ -56,12 +57,10 @@ export function migrate(db: Database, migrations: readonly string[]): void {
5657 });
5758
5859 const applied = appliedIds(db, migrations, ids);
59 if (applied.size > migrations.length) {
60 defect(
61 "db.future_schema",
62 `database has applied ${applied.size} migrations, this build only knows ${migrations.length} — refusing to run`,
63 );
64 }
60 // A database ahead of this build was migrated by a newer one. Every
61 // migration is additive (`notAdditive`), so this build serves on it as it
62 // serves beside a newer process: that is what lets a rollback boot an older
63 // release (#1664). The newer build's rows are left alone.
6564 for (let i = 0; i < migrations.length; i++) {
6665 const id = ids[i]!;
6766 if (applied.has(id)) continue;
src/main.ts +44
@@ -6,6 +6,8 @@
66
77 import { sweepStanding } from "./crew/standing.ts";
88 import { handover } from "./release/swap.ts";
9 import { resolveKept, rollback } from "./release/rollback.ts";
10 import { clearPid, recordLive, servingPid, writePid } from "./release/live.ts";
911 import { parentUrlProblem } from "./core/parent_releases.ts";
1012 import { releaseEnv } from "./release/env.ts";
1113 import { createApp } from "./app.ts";
@@ -100,6 +102,45 @@ if (problem !== null) {
100102 process.exit(1);
101103 }
102104
105 // `--rollback <sha>` swaps the serving forge to a kept `releases/<sha>/`
106 // through the same hand-over as a landing, then exits (#1664). The serving
107 // process is the one named in the data directory's forge.pid.
108 const rollbackAt = process.argv.indexOf("--rollback");
109 if (rollbackAt !== -1) {
110 const port = Number(process.env.PORT ?? 3000);
111 // forge.pid can outlive a crash and name a stranger: signal only a pid that
112 // is alive while a forge answers health on the port.
113 const wanted = resolveKept(dataDir, process.argv[rollbackAt + 1] ?? "");
114 if (!wanted.ok) {
115 console.error(`rollback refused: ${wanted.line}`);
116 process.exit(1);
117 }
118 const serving = await servingPid(dataDir, port);
119 if (serving === undefined) {
120 console.error(`rollback refused: no forge is serving on port ${port} (forge.pid is missing or stale)`);
121 process.exit(1);
122 }
123 const budget = releaseEnv(process.env).swapBudgetMs;
124 handover.ssh = hosted
outdated

forge.pid may be stale after a crash, so this can SIGTERM an unrelated process. Before signalling, check that the pid is still a live forge (for example, its health answer on PORT), and remove the pid file on shutdown.

125 ? Number(process.env.FORGE_SSH_PORT ?? 0) > 0
126 : Number(process.env.FORGE_SSH_PORT ?? 2222) > 0;
127 const done = await rollback({
128 dataDir,
129 sha: process.argv[rollbackAt + 1] ?? "",
130 live: null,
131 port,
132 env: process.env,
133 ...(budget === undefined ? {} : { budgetMs: budget }),
134 drain: () => {
135 process.kill(serving, "SIGTERM");
136 },
137 });
138 // CLI answer on the stream a person or a script reads.
139 if (done.ok) console.log(`rolled back to ${done.sha}`);
140 else console.error(`rollback refused: ${done.line}`);
141 process.exit(done.ok ? 0 : 1);
142 }
143
103144 // FORGE_DRAIN_LINGER_S: seconds a SIGTERM'd forge keeps answering while
104145 // routers learn it is going (`http/health.ts`).
105146 const lingerMs = drainLingerMs(process.env.FORGE_DRAIN_LINGER_S);
@@ -443,6 +484,9 @@ const leaseTimer = setInterval(() => {
443484
444485 // A release that read healthy beside this process takes over (#1663).
445486 handover.drain = () => shutdown("SIGTERM");
487 recordLive(app.db, running().commit);
488 writePid(dataDir, process.pid);
489 process.on("exit", () => clearPid(dataDir));
446490 handover.ssh = ssh !== undefined;
447491 process.on("SIGINT", shutdown);
448492 process.on("SIGTERM", shutdown);
src/release/forge.ts added +75
@@ -0,0 +1,75 @@
1 /**
2 * The forge's own releases as a viewer may see them (#1664): one answer for
3 * the page and the SSH terminal, so what a writer can do in one door is what
4 * they can do in the other.
5 */
6
7 import type { App } from "../app.ts";
8 import { canRead, canWrite, getRepo } from "../core/repos.ts";
9 import type { Repo } from "../core/repos.ts";
10 import type { User } from "../core/users.ts";
11 import { running } from "../kernel/version.ts";
12 import { healthySince } from "./live.ts";
13 import { listReleases } from "./record.ts";
14 import type { Release } from "./record.ts";
15 import { keptShas, rollback } from "./rollback.ts";
16 import { handover } from "./swap.ts";
17
18 export function forgeRepo(app: App): Repo | undefined {
19 const name = app.config.forgeRepo;
20 if (name === undefined) return undefined;
21 const [owner = "", repo = ""] = name.split("/");
22 return getRepo(app.db, owner, repo);
23 }
24
25 export interface ReleaseRow extends Release {
26 live: boolean;
27 kept: boolean;
28 healthySince: string | undefined;
29 }
30
31 export interface ReleaseView {
32 repo: Repo;
33 writer: boolean;
34 rows: ReleaseRow[];
35 }
36
37 /** Undefined unless the viewer can read the forge's repository: the rows name its pulls. */
38 export function releaseView(app: App, user: User | undefined): ReleaseView | undefined {
39 const repo = forgeRepo(app);
40 if (repo === undefined || !canRead(app.db, repo, user)) return undefined;
41 const live = running().commit;
42 const kept = new Set(keptShas(app.config.dataDir));
43 const rows = listReleases(app.db, 50).map((r) => ({
44 ...r,
45 live: r.sha === live,
46 kept: kept.has(r.sha),
47 healthySince: r.sha === live ? healthySince(app.db, r.sha) : undefined,
48 }));
49 return { repo, writer: user !== undefined && canWrite(app.db, repo, user), rows };
50 }
51
52 export type RolledBackNow = { ok: true; sha: string } | { ok: false; line: string };
53
54 /** Roll the serving process back for a writer of the forge's repository. */
55 export async function rollbackNow(app: App, user: User | undefined, sha: string): Promise<RolledBackNow> {
56 const repo = forgeRepo(app);
57 if (repo === undefined || user === undefined || !canWrite(app.db, repo, user))
58 return { ok: false, line: "only a writer of the forge's repository can roll back" };
59 const drain = handover.drain;
60 const port = app.config.port ?? 0;
61 if (drain === undefined || port <= 0)
62 return { ok: false, line: "this process cannot hand over its port; restart the forge on that release" };
63 const done = await rollback({
64 dataDir: app.config.dataDir,
65 sha,
66 live: running().commit,
67 port,
68 env: process.env,
69 ...(app.config.swapBudgetMs === undefined ? {} : { budgetMs: app.config.swapBudgetMs }),
70 // After the answer is on its way: draining stops this process's apps and checks.
71 drain: () => void setTimeout(drain, 0),
72 });
73 app.log.info("rollback", { by: user.username, ok: done.ok });
74 return done.ok ? { ok: true, sha: done.sha } : { ok: false, line: done.line };
75 }
src/release/live.ts added +70
@@ -0,0 +1,70 @@
1 /**
2 * Which release is live, and since when (#1664). A process that comes up as a
3 * release commit writes a row; "healthy since" is the first row of that commit
4 * after the last row of any other, so a restart of the same release does not
5 * move it.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
10 import { join } from "node:path";
11
12 /** Note that this process is up as `sha`; a second call for the same commit is a no-op. */
13 export function recordLive(db: Database, sha: string | null): void {
14 if (sha === null) return;
15 const last = db
16 .query<{ sha: string }, []>(`SELECT sha FROM release_live ORDER BY id DESC LIMIT 1`)
17 .get();
18 if (last?.sha === sha) return;
19 db.query(
20 `INSERT INTO release_live (sha, since) VALUES (?1, strftime('%Y-%m-%dT%H:%M:%fZ','now'))`,
21 ).run(sha);
22 }
23
24 /** When `sha` last became the live release, or undefined if it never did. */
25 export function healthySince(db: Database, sha: string): string | undefined {
26 return db
27 .query<{ since: string }, [string]>(
28 `SELECT since FROM release_live WHERE sha = ?1 ORDER BY id DESC LIMIT 1`,
29 )
30 .get(sha)?.since;
31 }
32
33 const pidFile = (dataDir: string): string => join(dataDir, "forge.pid");
34
35 /** Say which process serves, so `--rollback` can drain it once the other is well. */
36 export function writePid(dataDir: string, pid: number): void {
37 mkdirSync(dataDir, { recursive: true });
38 writeFileSync(pidFile(dataDir), `${pid}\n`);
39 }
40
41 /** Forget the pid file if it still names this process, so a crash-free exit leaves no stale pid. */
42 export function clearPid(dataDir: string): void {
43 if (readPid(dataDir) === process.pid) rmSync(pidFile(dataDir), { force: true });
44 }
45
46 /**
47 * The pid in `forge.pid` only when it is alive and the forge answering health on
48 * `port` reports that same pid: after a crash the file is stale and the pid may be a stranger's.
49 */
50 export async function servingPid(dataDir: string, port: number): Promise<number | undefined> {
51 const pid = readPid(dataDir);
52 if (pid === undefined) return undefined;
53 try {
54 process.kill(pid, 0);

Medium: kill(pid, 0) plus a healthy answer on PORT doesn't prove the pid is the forge on PORT. A stale forge.pid whose pid was reused, with any forge on the port, still gets a SIGTERM. Compare the pid that health reports (or one written by the answering process) before signalling.

55 const res = await fetch(`http://127.0.0.1:${port}/api/v1/health`, {
56 headers: { connection: "close" },
57 signal: AbortSignal.timeout(2_000),
58 });
59 const body = res.ok ? ((await res.json()) as { ok?: unknown; pid?: unknown }) : undefined;
60 return body?.ok === true && body.pid === pid ? pid : undefined;
61 } catch {
62 return undefined;
63 }
64 }
65
66 export function readPid(dataDir: string): number | undefined {
67 if (!existsSync(pidFile(dataDir))) return undefined;
68 const pid = Number(readFileSync(pidFile(dataDir), "utf8").trim());
69 return Number.isInteger(pid) && pid > 1 ? pid : undefined;
70 }
src/release/rollback.ts added +72
@@ -0,0 +1,72 @@
1 /**
2 * Roll back to a kept release (#1664): the same swap as a landing (step 3),
3 * aimed at a `releases/<sha>/` that is already on disk. Nothing is fetched or
4 * built; a sha that was pruned, or never cut, is refused in one line.
5 */
6
7 import { existsSync, readdirSync, utimesSync } from "node:fs";
8 import { releaseDir, releasesRoot } from "./checkout.ts";
9 import { beginSwap, endSwap, startRelease } from "./swap.ts";
10
11 export type RolledBack = { ok: true; sha: string; pid: number } | { ok: false; line: string };
12
13 /** The releases still on disk, by full sha. */
14 export function keptShas(dataDir: string): string[] {
15 const root = releasesRoot(dataDir);
16 if (!existsSync(root)) return [];
17 return readdirSync(root).filter((name) => /^[0-9a-f]{40}$/.test(name));
18 }
19
20 /** A full sha or a unique prefix (7 or more) of a kept one. */
21 export function resolveKept(
22 dataDir: string,
23 input: string,
24 ): { ok: true; sha: string } | { ok: false; line: string } {
25 const want = input.trim().toLowerCase();
26 const kept = /^[0-9a-f]{7,40}$/.test(want) ? keptShas(dataDir).filter((s) => s.startsWith(want)) : [];
27 if (kept.length === 1) return { ok: true, sha: kept[0]! };
28 const shown = /^[0-9a-f]{1,40}$/.test(want) ? want : "that";
29 return {
30 ok: false,
31 line:
32 kept.length > 1
33 ? `${shown} names more than one kept release; give more of the sha`
34 : `no kept release ${shown}`,
35 };
36 }
37
38 export interface RollbackInput {
39 dataDir: string;
40 /** What the person typed or the form sent. */
41 sha: string;
42 /** The commit serving now, if known. */
43 live: string | null;
44 port: number;
45 env: Record<string, string | undefined>;
46 budgetMs?: number;
47 /** What retires the serving process once the other reads healthy. */
48 drain: () => void;
49 }
50
51 export async function rollback(input: RollbackInput): Promise<RolledBack> {
52 const found = resolveKept(input.dataDir, input.sha);
53 if (!found.ok) return found;
54 if (input.live === found.sha) return { ok: false, line: `${found.sha.slice(0, 12)} is already live` };
55 const turn = beginSwap();
56 if (!turn.ok) return { ok: false, line: turn.line };
57 const dir = releaseDir(input.dataDir, found.sha);
58 // Touched, so the next landing's pruning keeps what was just chosen.
59 const now = new Date();
60 utimesSync(dir, now, now);
61 const swapped = await startRelease({
62 dir,
63 sha: found.sha,
64 port: input.port,
65 env: input.env,
66 ...(input.budgetMs === undefined ? {} : { budgetMs: input.budgetMs }),
67 });
68 endSwap(swapped.ok);
69 if (!swapped.ok) return { ok: false, line: swapped.line };
70 input.drain();
71 return { ok: true, sha: found.sha, pid: swapped.pid };
72 }
src/tui/ssh.ts +50 −1
@@ -12,6 +12,7 @@
1212
1313 import { holdOpen } from "../http/caller.ts";
1414 import { join } from "node:path";
15 import { releaseView } from "../release/forge.ts";
1516 import type { App as Forge } from "../app.ts";
1617 import { findKeyByFingerprint, touchKey } from "../core/keys.ts";
1718 import { canRead, canWrite, getRepo } from "../core/repos.ts";
@@ -223,6 +224,53 @@ export function forgeSshSession(forge: Forge): (session: SshSession) => void {
223224 };
224225 }
225226
227 /**
228 * `releases` lists the forge's releases and `rollback <sha>` rolls back to a
229 * kept one, under the same rules as /releases: reading needs a reader of the
230 * forge's repository, rolling back a writer. False when the command is
231 * neither, so git's parser answers.
232 */
233 export async function serveReleaseCommand(
234 forge: Forge,
235 session: SshSession,
236 user: User | undefined,
237 ): Promise<boolean> {
238 const words = (session.command ?? "").trim().split(/\s+/);
239 const done = (lines: string[], code: number): true => {
240 for (const l of lines) (code === 0 ? session.write : session.writeStderr).call(session, `${l}${CRLF}`);
241 session.exit(code);
242 return true;
243 };
244 if (words[0] === "releases" && words.length === 1) {
245 const view = releaseView(forge, user);
246 if (view === undefined) return done(["forge: no releases here"], 1);
247 return done(
248 view.rows.map((r) =>
249 [
250 r.sha.slice(0, 12),
251 r.live ? "live" : r.ok ? (r.kept ? "kept" : "pruned") : "failed",
252 r.pullNumber === null ? "no pull" : `#${r.pullNumber}`,
253 r.createdAt,
254 r.healthySince === undefined ? "" : `healthy since ${r.healthySince}`,
255 ]
256 .filter((w) => w !== "")
257 .join(" "),
258 ),
259 0,
260 );
261 }
262 if (words[0] === "rollback" && words.length === 2) {

High: this branch only runs in the process that holds the SSH listener, and beginSwap() refuses whenever handover.ssh === true. A writer's rollback <sha> here always ends in "this process holds the SSH terminal…". Either refuse it honestly up front (pointing to /releases or --rollback), with a test for the writer case, or wait for the SSH hand-over. As written, the second door doesn't open.

263 const view = releaseView(forge, user);
264 if (view === undefined || !view.writer) return done(["forge: only a writer of the forge's repository can roll back"], 1);
265 // This process holds the SSH listener, and a swap refuses to hand that over.
266 return done(
267 ["forge: the terminal cannot hand itself over; roll back from /releases or with `bun src/main.ts --rollback <sha>`"],
268 1,
269 );
270 }
271 return false;
272 }
273
226274 /**
227275 * Git over an exec channel. The access matrix is exactly the HTTP one:
228276 * upload-pack → `canRead`; a guest may read a public repo.
@@ -238,8 +286,9 @@ async function serveGitCommand(
238286 const parsed =
239287 session.command === undefined ? null : parseGitCommand(session.command);
240288 if (parsed === null) {
289 if (session.command !== undefined && (await serveReleaseCommand(forge, session, user))) return;
241290 session.writeStderr(
242 `forge: only git is available over ssh; run 'ssh ${session.username}@host' for the terminal UI${CRLF}`,
291 `forge: only git, releases and rollback are available over ssh; run 'ssh ${session.username}@host' for the terminal UI${CRLF}`,
243292 );
244293 session.exit(1);
245294 return;
src/web/pages/releases.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * The forge's own releases (#1664): every landing cut and preflighted, which
3 * is live and since when, and for a writer of the forge's repository the
4 * button that rolls back to one still on disk.
5 */
6
7 import { running } from "../../kernel/version.ts";
8 import { healthySince } from "../../release/live.ts";
9 import { releaseView, rollbackNow } from "../../release/forge.ts";
10 import type { Ctx } from "../../http/context.ts";
11 import { notFoundPage, repoBase, signInFirst } from "../chrome.ts";
12 import { readForm } from "../form.ts";
13 import { html, type Html } from "../html.ts";
14 import { flashTo, page } from "../layout.ts";
15 import { btn, card, empty, icon, row, time } from "../ui.ts";
16
17 /** The home's line: "live: <sha> since <time>", or nothing when no release is known. */
18 export function liveLine(ctx: Ctx): Html | undefined {
19 const sha = running().commit;
20 if (sha === null) return undefined;
21 const since = healthySince(ctx.app.db, sha);
22 return html`<p class="muted small">
23 live: <a href="/releases"><code>${sha.slice(0, 12)}</code></a>${since === undefined
24 ? null
25 : html` since ${time(since)}`}
26 </p>`;
27 }
28
29 export function releasesPage(ctx: Ctx): Response {
30 const view = releaseView(ctx.app, ctx.auth.user);
31 if (view === undefined) return notFoundPage(ctx);
32 const { repo, writer } = view;
33 const rows = view.rows.map((r) => {
34 const canRoll = writer && !r.live && r.ok && r.kept;
35 return row({
36 lead: icon(r.live ? "check" : r.ok ? "history" : "alert"),
37 title: html`<code>${r.sha.slice(0, 12)}</code>${r.live ? html` <strong>live</strong>` : null}`,
38 meta: html`${r.pullNumber === null
39 ? "no pull"
40 : html`landed <a href="${repoBase(repo)}/pulls/${r.pullNumber}">#${r.pullNumber}</a>`}
outdated

No read gate: a guest gets every release with its pull links and failed-preflight lines. Return notFoundPage unless the viewer can read FORGE_REPO, and add a guest test.

41 · ${time(r.createdAt)}${r.healthySince === undefined ? null : html` · healthy since ${time(r.healthySince)}`}${r.ok
42 ? r.kept
43 ? null
44 : " · no longer kept"
45 : html` · failed preflight: ${r.line}`}`,
46 trail: canRoll
47 ? html`<form method="post" action="/releases/rollback">
48 <input type="hidden" name="sha" value="${r.sha}" />
49 ${btn("Roll back", { type: "submit", size: "sm", icon: "history" })}
50 </form>`
51 : html``,
52 });
53 });
54 return page({
55 ctx,
56 title: "Releases",
57 body: html`<div class="page-head"><h1>Releases</h1></div>
58 ${rows.length === 0
59 ? empty({
60 icon: "history",
61 title: "No releases yet",
62 note: "A landing on this forge's own repository is cut and kept here.",
63 })
64 : card(html`<ul class="list">${rows}</ul>`, { pad: false })}`,
65 });
66 }
67
68 export async function releasesRollback(ctx: Ctx): Promise<Response> {
69 if (!ctx.auth.user) return signInFirst(ctx);
70 const form = await readForm(ctx, "rw");
71 if (form instanceof Response) return form;
72 const view = releaseView(ctx.app, ctx.auth.user);
73 if (view === undefined || !view.writer) return notFoundPage(ctx);
74 const sha = form.get("sha");
75 const done = await rollbackNow(ctx.app, ctx.auth.user, typeof sha === "string" ? sha : "");
76 return flashTo(
77 ctx,
78 "/releases",
79 done.ok
80 ? { message: `Rolled back to ${done.sha.slice(0, 12)}.` }
81 : { tone: "danger", message: `Not rolled back: ${done.line}.` },
82 );
83 }
src/web/studio/home.ts +2 −1
@@ -6,6 +6,7 @@
66 * best of what is public (`actions/front.ts`).
77 */
88
9 import { liveLine } from "../pages/releases.ts";
910 import {
1011 frontPage,
1112 frontPicksJson,
@@ -187,7 +188,7 @@ export async function studioHome(
187188 // everyday account themselves (#600); anywhere else, #803's card asks.
188189 const firstSteps = await nextStepsCard(ctx, user);
189190 const body = html`<h1 class="sr-only">Home</h1>
190 ${firstSteps ?? everydayCard(ctx, user)} ${address}
191 ${firstSteps ?? everydayCard(ctx, user)} ${address} ${liveLine(ctx) ?? null}
191192 ${homeTabs("feed")}
192193 <div class="dash">
193194 <div class="dash-main stack">
test/kernel.test.ts +17 −1
@@ -1,4 +1,5 @@
11 import { describe, expect, test } from "bun:test";
2 import { Database } from "bun:sqlite";
23 import { mkdtempSync, rmSync } from "node:fs";
34 import { tmpdir } from "node:os";
45 import { join } from "node:path";
@@ -136,12 +137,27 @@ describe("db", () => {
136137 ).toThrow();
137138 });
138139
139 test("future schema refuses to run", () => {
140 test("a database ahead of this build serves, so a rollback can boot", () => {
140141 const dir = mkdtempSync(join(tmpdir(), "forge-kernel-"));
141142 try {
142143 const path = join(dir, "forge.db");
143144 const db = openDb(path, ["CREATE TABLE a (x INTEGER)"]);
144145 db.close();
146 const older = openDb(path, []);
147 expect(older.query("SELECT count(*) AS n FROM a").get()).toEqual({ n: 0 });
148 older.close();
149 } finally {
150 rmSync(dir, { recursive: true, force: true });
151 }
152 });
153
154 test("a database from before the migration table, ahead of this build, refuses to run", () => {
155 const dir = mkdtempSync(join(tmpdir(), "forge-kernel-"));
156 try {
157 const path = join(dir, "forge.db");
158 const raw = new Database(path);
159 raw.exec("PRAGMA user_version = 5");
160 raw.close();
145161 expect(() => openDb(path, [])).toThrow(ForgeError);
146162 } finally {
147163 rmSync(dir, { recursive: true, force: true });
test/release-rollback.test.ts added +364
@@ -0,0 +1,364 @@
1 /**
2 * Rolling back to a kept release (#1664): the swap of step 3 aimed at a
3 * `releases/<sha>/` already on disk, from `--rollback <sha>` and from a
4 * writer's button on /releases. An older release must boot on the newer
5 * schema it is rolled back onto, and serve.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { createRepo } from "../src/actions/repos.ts";
15 import { signUp } from "../src/actions/users.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { migrations } from "../src/core/schema.ts";
18 import { openDb } from "../src/kernel/db.ts";
19 import { healthySince, recordLive } from "../src/release/live.ts";
20 import { recordRelease } from "../src/release/record.ts";
21 import type { User } from "../src/core/users.ts";
22 import { serveReleaseCommand } from "../src/tui/ssh.ts";
23 import { resolveKept } from "../src/release/rollback.ts";
24 import { endSwap, handover } from "../src/release/swap.ts";
25 import { serve, type Servers } from "../src/http/server.ts";
26 import { proveAll } from "./helpers/verified.ts";
27
28 const LIVE = "a".repeat(40);
29 const OLDER = "b".repeat(40);
30 const GONE = "c".repeat(40);
31 const FAILED = "d".repeat(40);
32
33 const STAND_IN = `
34 setTimeout(() => process.exit(0), 25000);
35 if (process.argv.includes("--preflight")) { console.log("preflight ok"); process.exit(0); }
36 Bun.serve({
37 port: Number(process.env.PORT),
38 reusePort: true,
39 fetch: () => Response.json({ ok: true, draining: false, commit: process.env.FORGE_COMMIT }),
40 });
41 `;
42
43 const realMigrate = (() => {
44 try {
45 return readFileSync("/proc/sys/net/ipv4/tcp_migrate_req", "utf8").trim() === "1";
46 } catch {
47 return false;
48 }
49 })();
50 const whenMigrating = realMigrate ? test : test.skip;
51
52 async function freePort(): Promise<number> {
53 const s = Bun.serve({ port: 0, fetch: () => new Response("") });
54 const port = s.port ?? 0;
55 s.stop(true);
56 return port;
57 }
58
59 const commitAt = async (port: number): Promise<string | undefined> => {
60 try {
61 const res = await fetch(`http://127.0.0.1:${port}/api/v1/health`, {
62 headers: { connection: "close" },
63 signal: AbortSignal.timeout(3_000),
64 });
65 return ((await res.json()) as { commit?: string }).commit;
66 } catch {
67 return undefined;
68 }
69 };
70
71 function keep(dataDir: string, sha: string): void {
72 const dir = join(dataDir, "releases", sha, "src");
73 mkdirSync(dir, { recursive: true });
74 writeFileSync(join(dir, "main.ts"), STAND_IN);
75 }
76
77 describe("naming a kept release", () => {
78 let dataDir: string;
79 beforeAll(async () => {
80 dataDir = await mkdtemp(join(tmpdir(), "forge-rb-names-"));
81 keep(dataDir, LIVE);
82 keep(dataDir, OLDER);
83 });
84 afterAll(() => rm(dataDir, { recursive: true, force: true }));
85
86 test("a full sha or a unique prefix resolves; anything else is refused in one line", () => {
87 expect(resolveKept(dataDir, OLDER)).toEqual({ ok: true, sha: OLDER });
88 expect(resolveKept(dataDir, OLDER.slice(0, 9))).toEqual({ ok: true, sha: OLDER });
89 for (const bad of [GONE, "bbbb", "", "../../etc", "b".repeat(41), "zzzzzzzz"]) {
90 const out = resolveKept(dataDir, bad);
91 expect(out.ok).toBe(false);
92 if (!out.ok) {
93 expect(out.line).toMatch(/^no kept release /);
94 expect(out.line).not.toContain("\n");
95 expect(out.line).not.toContain("..");
96 }
97 }
98 });
99
100 test("a prefix that fits two is refused", () => {
101 keep(dataDir, "b" + "e".repeat(39));
102 const out = resolveKept(dataDir, "b".repeat(7));
103 expect(out.ok && out.sha === OLDER).toBe(true);
104 const both = resolveKept(dataDir, "b");
105 expect(both.ok).toBe(false);
106 });
107
108 test("healthy since is the first boot of the commit after any other", async () => {
109 const db = openDb(join(dataDir, "live.db"), migrations);
110 recordLive(db, LIVE);
111 const first = healthySince(db, LIVE);
112 recordLive(db, LIVE);
113 expect(healthySince(db, LIVE)).toBe(first);
114 recordLive(db, null);
115 recordLive(db, OLDER);
116 recordLive(db, LIVE);
117 expect(healthySince(db, LIVE)).not.toBeUndefined();
118 expect(db.query("SELECT COUNT(*) AS n FROM release_live").get()).toEqual({ n: 3 });
119 db.close();
120 });
121 });
122
123 describe("--rollback", () => {
124 let dataDir: string;
125 beforeAll(async () => {
126 dataDir = await mkdtemp(join(tmpdir(), "forge-rb-cli-"));
127 keep(dataDir, OLDER);
128 });
129 afterAll(() => rm(dataDir, { recursive: true, force: true }));
130
131 const run = async (sha: string) => {
132 const proc = Bun.spawn([process.execPath, "src/main.ts", "--rollback", sha], {
133 env: { ...process.env, FORGE_DATA: dataDir, PORT: String(await freePort()), FORGE_SSH_PORT: "0" },
134 stdout: "pipe",
135 stderr: "pipe",
136 });
137 const [out, errText, code] = await Promise.all([
138 new Response(proc.stdout).text(),
139 new Response(proc.stderr).text(),
140 proc.exited,
141 ]);
142 return { out, errText, code };
143 };
144
145 test("an unknown sha is refused with one line and a failing exit", async () => {
146 const { out, errText, code } = await run(GONE);
147 expect(code).toBe(1);
148 expect(out).toBe("");
149 expect(errText.trim().split("\n")).toEqual([`rollback refused: no kept release ${GONE}`]);
150 });
151
152 test("a stale forge.pid is not signalled: no forge answers on the port, so it is refused first", async () => {
153 // This test process is alive, so a bare kill(pid, 0) would pass; only the health read says no.
154 writeFileSync(join(dataDir, "forge.pid"), `${process.pid}\n`);
155 const { errText, code } = await run(OLDER);
156 expect(code).toBe(1);
157 expect(errText).toContain("forge.pid is missing or stale");
158 });
159
160 test("no sha at all is refused the same way", async () => {
161 const { errText, code } = await run("");
162 expect(code).toBe(1);
163 expect(errText.trim().split("\n").length).toBe(1);
164 });
165 });
166
167 describe("an older release on a newer schema", () => {
168 let dataDir: string;
169 beforeAll(async () => {
170 dataDir = await mkdtemp(join(tmpdir(), "forge-rb-schema-"));
171 });
172 afterAll(() => rm(dataDir, { recursive: true, force: true }));
173
174 test("a build that knows fewer migrations opens the database a newer one migrated", () => {
175 const path = join(dataDir, "a.db");
176 openDb(path, [...migrations, "ALTER TABLE release ADD COLUMN later TEXT"]).close();
177 const db = openDb(path, migrations);
178 expect(db.query("SELECT COUNT(*) AS n FROM release").get()).toEqual({ n: 0 });
179 db.close();
180 });
181
182 test("this tree boots and serves on a database one migration ahead of it", async () => {
183 openDb(join(dataDir, "forge.db"), [...migrations, "CREATE TABLE from_the_future (x INTEGER)"]).close();
184 const port = await freePort();
185 const proc = Bun.spawn([process.execPath, "src/main.ts"], {
186 env: {
187 ...process.env,
188 FORGE_DATA: dataDir,
189 PORT: String(port),
190 FORGE_SSH_PORT: "0",
191 FORGE_COMMIT: OLDER,
192 },
193 stdout: "ignore",
194 stderr: "ignore",
195 });
196 try {
197 let seen: string | undefined;
198 for (let i = 0; i < 100 && seen === undefined; i++) {
199 seen = await commitAt(port);
200 if (seen === undefined) await Bun.sleep(100);
201 }
202 expect(seen).toBe(OLDER);
203 expect((await fetch(`http://127.0.0.1:${port}/`)).status).toBe(200);
204 } finally {
205 proc.kill("SIGKILL");
206 await proc.exited;
207 }
208 }, 20_000);
209 });
210
211 describe("the releases page and its button", () => {
212 let dataDir: string;
213 let app: App;
214 let servers: Servers;
215 let base: string;
216 let port: number;
217 let writer: { authorization: string };
218 let reader: { authorization: string };
219 let drained = 0;
220 let olive: User;
221 let nosy: User;
222
223 beforeAll(async () => {
224 handover.migrate = true;
225 handover.drain = () => {
226 drained++;
227 };
228 dataDir = await mkdtemp(join(tmpdir(), "forge-rb-page-"));
229 port = await freePort();
230 app = createApp({ dataDir, port, forgeRepo: "olive/forge", selfSwap: true, url: "https://forge.example", edgeToken: "e" });
231 servers = await serve(app);
232 base = servers.url;
233 const mk = async (username: string) => {
234 const u = await signUp(app, { username, email: `${username}@f.dev`, password: "a-long-passphrase" });
235 if (!u.ok) throw new Error(u.error);
236 return u.value;
237 };
238 olive = await mk("olive");
239 nosy = await mk("nosy");
240 proveAll(app);
241 writer = { authorization: `Bearer ${createToken(app.db, olive.id, "t", "rw").token}` };
242 reader = { authorization: `Bearer ${createToken(app.db, nosy.id, "t", "rw").token}` };
243 const made = await createRepo(app, olive, { name: "forge" });
244 if (!made.ok) throw new Error(made.error);
245 const repoId = made.value.id;
246 for (const [sha, pull, ok] of [[OLDER, 3, true], [GONE, 2, true], [FAILED, 4, false], [LIVE, 5, true]] as const)
247 recordRelease(app.db, { sha, repoId, pullNumber: pull, ok, line: ok ? "preflight ok" : "<b>boom</b>" });
248 keep(dataDir, OLDER);
249 keep(dataDir, LIVE);
250 process.env.FORGE_COMMIT = LIVE;
251 recordLive(app.db, LIVE);
252 });
253 afterAll(async () => {
254 endSwap(false);
255 delete process.env.FORGE_COMMIT;
256 delete handover.migrate;
257 delete handover.drain;
258 servers.stop();
259 app.close();
260 await rm(dataDir, { recursive: true, force: true });
261 });
262
263 const post = (headers: Record<string, string>, sha: string) =>
264 fetch(`${base}/releases/rollback`, {
265 method: "POST",
266 redirect: "manual",
267 headers: { ...headers, "content-type": "application/x-www-form-urlencoded" },
268 body: new URLSearchParams({ sha }).toString(),
269 });
270
271 test("each release shows its sha, pull, live mark and healthy-since; a writer gets the button on a kept one only", async () => {
272 const body = await (await fetch(`${base}/releases`, { headers: writer })).text();
273 expect(body).toContain(OLDER.slice(0, 12));
274 expect(body).toContain("/olive/forge/pulls/3");
275 expect(body).toContain("healthy since");
276 expect(body).toContain("<strong>live</strong>");
277 expect(body).toContain("no longer kept");
278 expect(body).toContain("failed preflight: &lt;b&gt;boom&lt;/b&gt;");
279 expect(body).not.toContain("<b>boom</b>");
280 // Only OLDER is kept, ok and not live.
281 expect(body.match(/action="\/releases\/rollback"/g)?.length).toBe(1);
282 expect(body).toContain(`value="${OLDER}"`);
283 });
284
285 test("someone who cannot write sees no button and cannot press it", async () => {
286 const body = await (await fetch(`${base}/releases`, { headers: reader })).text();
287 expect(body).not.toContain("/releases/rollback");
288 expect((await post(reader, OLDER)).status).toBe(404);
289 expect(drained).toBe(0);
290 });
291
292 test("a guest or a stranger gets nothing of a private forge repository, on the page or in the terminal", async () => {
293 expect((await fetch(`${base}/releases`)).status).toBe(404);
294 const stranger = await fetch(`${base}/releases`, { headers: reader });
295 expect(stranger.status).toBe(404);
296 expect(await stranger.text()).not.toContain("boom");
297 const said = { out: [] as string[], err: [] as string[], code: -1 };
298 const session = {
299 command: "releases",
300 write: (t: string) => said.out.push(t),
301 writeStderr: (t: string) => said.err.push(t),
302 exit: (c: number) => (said.code = c),
303 };
304 expect(await serveReleaseCommand(app, session as never, undefined)).toBe(true);
305 expect(said.code).toBe(1);
306 expect(said.out).toEqual([]);
307 });
308
309 test("the terminal lists the same rows and rolls back only for a writer", async () => {
310 const say = async (command: string, user: User | undefined) => {
311 const said = { out: [] as string[], err: [] as string[], code: -1 };
312 const session = {
313 command,
314 write: (t: string) => said.out.push(t),
315 writeStderr: (t: string) => said.err.push(t),
316 exit: (c: number) => (said.code = c),
317 };
318 const handled = await serveReleaseCommand(app, session as never, user);
319 return { handled, ...said };
320 };
321 const listed = await say("releases", olive);
322 expect(listed.code).toBe(0);
323 const text = listed.out.join("");
324 expect(text).toContain(`${LIVE.slice(0, 12)} live`);
325 expect(text).toContain(`${OLDER.slice(0, 12)} kept #3`);
326 expect(text).toContain(`${FAILED.slice(0, 12)} failed`);
327 const denied = await say(`rollback ${OLDER}`, nosy);
328 expect(denied.code).toBe(1);
329 expect(denied.err.join("")).toContain("only a writer");
330 const writerTry = await say(`rollback ${OLDER}`, olive);
outdated

The terminal test covers a refused non-writer and an unknown sha, but never a writer rolling back to a kept sha. That case would show the handover.ssh refusal. Add it, and assert whatever the honest answer is.

331 expect(writerTry.code).toBe(1);
332 expect(writerTry.err.join("")).toContain("cannot hand itself over");
333 expect(writerTry.err.join("")).toContain("/releases");
334 expect((await say("ls", olive)).handled).toBe(false);
335 expect(drained).toBe(0);
336 });
337
338 test("a cross-origin press and an unknown sha change nothing", async () => {
339 expect((await post({ ...writer, origin: "https://evil.example" }, OLDER)).status).toBe(403);
340 const unknown = await post(writer, GONE);
341 expect(unknown.status).toBe(303);
342 expect(unknown.headers.get("location")).toBe("/releases");
343 const live = await post(writer, LIVE);
344 expect(live.status).toBe(303);
345 expect(drained).toBe(0);
346 });
347
348 test("the home says what is live and since when", async () => {
349 const body = await (await fetch(`${base}/`, { headers: writer })).text();
350 expect(body).toContain("live:");
351 expect(body).toContain(LIVE.slice(0, 12));
352 expect(body).toContain(" since ");
353 });
354
355 test("pressing it starts the kept release, which serves its sha, and drains this process", async () => {
356 const res = await post(writer, OLDER);
357 expect(res.status).toBe(303);
358 await Bun.sleep(50);
359 expect(drained).toBe(1);
360 let served = false;
361 for (let i = 0; i < 60 && !served; i++) served = (await commitAt(port)) === OLDER;
362 expect(served).toBe(true);
363 }, 30_000);
364 });
test/schema-migrations.test.ts +14 −1
@@ -147,8 +147,21 @@ describe("a preview booting on copied data", () => {
147147 db.close();
148148 });
149149
150 test("data ahead of this build is still refused", () => {
150 test("data ahead of this build is served, not refused: a rollback boots an older release", () => {
151151 const path = production(["CREATE TABLE a (x INTEGER)", "CREATE TABLE b (y INTEGER)"]);
152 const db = openDb(path, ["CREATE TABLE a (x INTEGER)"]);
153 expect(has(db, "a")).toBe(true);
154 expect(has(db, "b")).toBe(true);
155 db.close();
156 });
157
158 test("a database from before the tracking table, ahead of this build, is refused", () => {
159 const path = fresh();
160 const { Database } = require("bun:sqlite") as typeof import("bun:sqlite");
161 const old = new Database(path, { create: true, strict: true });
162 old.exec("CREATE TABLE a (x INTEGER)");
163 old.exec("PRAGMA user_version = 2");
164 old.close();
152165 expect(() => openDb(path, ["CREATE TABLE a (x INTEGER)"])).toThrow(ForgeError);
153166 });
154167 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs