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

The forge deploys itself from its own main: gate, release dir, preflight, socket handoff, drain, health, rollback; no platform MCP or Forgejo CI in the path #1434

Closed opened this in answer to
Closed without merging

scout/forge:scout/1432-the-forge-deploys-itself-from-its-own-ma → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
15 files changed +711 −1
docs/RELEASES.md added +16
@@ -0,0 +1,16 @@
1 # Releases: the forge deploys itself
2
3 Set `FORGE_SELF_REPO=owner/name` (the forge's own repository on itself) and `FORGE_HANDOFF=1`.
4 A landing on that repository's default branch (the full gate has already passed on the merge) then:
5
6 1. exports the landed tree to `$FORGE_DATA/releases/<sha>/` (`release/deploy.ts`);
7 2. runs the new tree's `bun src/main.ts --preflight` against a `VACUUM INTO` copy of the database (`release/preflight.ts`);
8 3. starts the new process beside the old on the same port (`SO_REUSEPORT`), waits for its ready file and an answer on its internal listener, then sends the old one SIGTERM, which stops accepting and drains as on any restart (`release/swap.ts`).
9
10 A failed preflight, a process that exits, or one not healthy within its budget leaves the old forge serving, logs one `RELEASE FAILED` line and comments on the landed pull.
11
12 - `bun src/main.ts --rollback <sha>` (or the button on `/releases` for a writer of the forge repository) swaps back to a release directory on disk the same way.
13 - State: `$FORGE_DATA/releases.json` (the list), `$FORGE_DATA/forge.pid`, `$FORGE_DATA/releases/<sha>/`. The home shows `live: <sha> since <time>`.
14 - `FORGE_COMMIT` is the landed sha for `/api/v1/health`.
15
16 Not yet: pruning old release directories, the migration N-1/N compatibility test, ledger entry for the roll's cost, retiring the platform path (the supervisor must not treat the first process exiting as the pod's end).
scripts/gate.ts +2
@@ -66,6 +66,8 @@ export const GATE: readonly string[] = [
6666 "test/sole-owner-suspend.test.ts",
6767 "test/standing-every-process.test.ts",
6868 "test/steer.test.ts",
69 "test/release-preflight.test.ts",
70 "test/release-swap.test.ts",
6971 "test/sealed-git.test.ts",
7072 "test/sealed-issues.test.ts",
7173 "test/sealed-release.test.ts",
src/app.ts +2
@@ -25,6 +25,8 @@ export interface ForgeConfig {
2525 dataDir: string;
2626 /** @default 3000 */
2727 port?: number;
28 /** Share the port with another process: the new side of a release. */
29 reusePort?: boolean;
2830 /** The hostname clone URLs are built from. @default "localhost" */
2931 host?: string;
3032 /**
src/core/reserved.ts +1
@@ -86,6 +86,7 @@ export const SYSTEM_NAMES: readonly string[] = [
8686 "runs",
8787 "search",
8888 "settings",
89 "releases",
8990 "signin",
9091 "signup",
9192 "sitemap.xml",
src/http/server.ts +10
@@ -83,6 +83,7 @@ import {
8383 verifyPage,
8484 themeSubmit,
8585 } from "../web/pages/site.ts";
86 import { releasesPage, releasesRollback } from "../web/pages/releases.ts";
8687 import { confirmPage, searchPage } from "../web/pages/search.ts";
8788 import { followingSubmit } from "../web/pages/following.ts";
8889 import { reconnectSubmit } from "../web/pages/frozen.ts";
@@ -657,6 +658,8 @@ export function buildRouter(): Router<Handler> {
657658 router.add("GET", "/settings/capacity", capacityPage);
658659 router.add("POST", "/settings/capacity", capacitySet);
659660 router.add("GET", "/settings/backups", backupsPage);
661 router.add("GET", "/releases", releasesPage);
662 router.add("POST", "/releases/rollback", releasesRollback);
660663 router.add("POST", "/settings/backups/now", backupsNow);
661664 router.add("POST", "/settings/backups/destination", backupsDestination);
662665 router.add("POST", "/settings/backups/test", backupsTest);
@@ -1523,6 +1526,8 @@ async function handleHook(app: App, request: Request): Promise<Response> {
15231526 export interface Servers {
15241527 readonly url: string;
15251528 readonly port: number;
1529 /** Stop taking new connections; what is in flight finishes. A handoff's old side. */
1530 closeListener(): void;
15261531 stop(): void;
15271532 }
15281533
@@ -1663,6 +1668,8 @@ export async function serve(app: App): Promise<Servers> {
16631668
16641669 const web = Bun.serve({
16651670 port: app.config.port ?? 3000,
1671 // A release starts beside the old process on the same port (`release/swap.ts`).
1672 reusePort: app.config.reusePort === true,
16661673 idleTimeout: 120,
16671674 // The largest thing anyone may send — a git push. Every reader below it
16681675 // keeps its own, smaller cap (\`http/limits.ts\`); the runtime enforces
@@ -1756,6 +1763,9 @@ export async function serve(app: App): Promise<Servers> {
17561763 return {
17571764 url: `http://localhost:${port}`,
17581765 port,
1766 closeListener() {
1767 web.stop();
1768 },
17591769 stop() {
17601770 endOpen();
17611771 clearInterval(sweep);
src/main.ts +39
@@ -4,6 +4,7 @@
44 * environment-only — a handful of variables, all with sane defaults.
55 */
66
7 import { resolve } from "node:path";
78 import { parseCidrs } from "./kernel/cidr.ts";
89 import { createApp } from "./app.ts";
910 import { reconcile } from "./core/reconcile.ts";
@@ -39,6 +40,9 @@ import { startPromptRoutine } from "./crew/prompts.ts";
3940 import { pruneTokens } from "./core/tokens.ts";
4041 import { dataHomeRefusal } from "./kernel/data_home.ts";
4142 import { running } from "./kernel/version.ts";
43 import { announceReady } from "./release/swap.ts";
44 import { rollback } from "./release/deploy.ts";
45 import { startReleases } from "./release/service.ts";
4246
4347 // `forge hook <name>` re-enters here from a git hook stub. It relays to the
4448 // running forge over its socket and exits — it must never boot a server.
@@ -84,6 +88,20 @@ if (refusal !== null) {
8488 process.exit(1);
8589 }
8690
91 // `--rollback <sha>`: swap back to a release directory already on this
92 // machine, the way a landing swaps forward, then exit (docs/RELEASES.md).
93 if (process.argv[2] === "--rollback") {
94 const done = await rollback({
95 dataDir: resolve(dataDir),
96 sha: process.argv[3] ?? "",
97 by: "rollback",
98 });
99 // CLI message on stdout/stderr for the person at the terminal.
100 if (!done.ok) console.error(`rollback failed, the running forge is untouched: ${done.error}`);
101 else console.log(`rolled back to ${done.value.sha.slice(0, 7)} in ${done.value.ms} ms`);
102 process.exit(done.ok ? 0 : 1);
103 }
104
87105 // FORGE_TRUSTED_PROXIES is checked here so a typo fails the boot, not a
88106 // limit that quietly counts every stranger as one.
89107 const trustedProxies = (process.env.FORGE_TRUSTED_PROXIES ?? "")
@@ -101,6 +119,9 @@ const trustedProxies = (process.env.FORGE_TRUSTED_PROXIES ?? "")
101119 const app = createApp({
102120 dataDir,
103121 port: Number(process.env.PORT ?? 3000),
122 // FORGE_HANDOFF=1: listen beside another forge on the same port, so a
123 // release starts before the old one stops (`release/swap.ts`).
124 ...(process.env.FORGE_HANDOFF === "1" ? { reusePort: true } : {}),
104125 ...(process.env.FORGE_HOST === undefined
105126 ? {}
106127 : { host: process.env.FORGE_HOST }),
@@ -163,6 +184,14 @@ const app = createApp({
163184 }),
164185 });
165186
187 // `--preflight`: this tree's config parsed, schema migrated (createApp
188 // opens and migrates the database): proof it boots, before anything swaps.
189 if (process.argv.includes("--preflight")) {
190 app.close();
191 console.log("preflight ok");
192 process.exit(0);
193 }
194
166195 await reconcile(app);
167196 // Issues linked under a pillar's umbrella before pillars had labels.
168197 const labelled = syncAllPillars(app);
@@ -333,6 +362,13 @@ const tickAsks = async (): Promise<void> => {
333362 const staleTimer = setInterval(() => void tickAsks(), 120_000);
334363 void tickAsks();
335364
365 // A landing on the forge's own default branch deploys it (`release/`).
366 const selfRepo = (process.env.FORGE_SELF_REPO ?? "").trim();
367 const releases = /^[\w.-]+\/[\w.-]+$/.test(selfRepo)
368 ? startReleases(app, selfRepo)
369 : undefined;
370 announceReady(app.config.dataDir, app.hookAddress.current);
371
336372 app.log.info("forge is up", { url: servers.url, data: app.config.dataDir });
337373 // Only an agent is on a crew (the `repo_crew_agents_only` trigger refuses anyone else). A person
338374 // put on one before that is reported here for the owner to take off — the
@@ -399,6 +435,9 @@ function shutdown(signal: NodeJS.Signals): void {
399435 // Streams end now, with a resume hint: their browsers reconnect to the
400436 // process that replaced this one, not to this one while it finishes.
401437 drainStreams();
438 // The release that replaced this one already takes new connections.
439 if (process.env.FORGE_HANDOFF === "1") servers.closeListener();
440 releases?.stop();
402441 clearInterval(deliveryTimer);
403442 clearInterval(syncTimer);
404443 clearInterval(staleTimer);
src/release/deploy.ts added +66
@@ -0,0 +1,66 @@
1 /**
2 * One release, start to finish: check the landed tree out, run its
3 * preflight, swap. `rollback` is the same swap to a directory that is
4 * already there — a rollback is a landing of an older tree.
5 */
6
7 import { exportTree } from "../apps/checkout.ts";
8 import { err, ok, type Result } from "../kernel/result.ts";
9 import { preflight } from "./preflight.ts";
10 import { hasRelease, isSha, recordRelease, releaseDir, type Release } from "./releases.ts";
11 import { swap } from "./swap.ts";
12
13 export interface Options {
14 readonly dataDir: string;
15 readonly sha: string;
16 /** Who asked: the landing (`#12`), `rollback`, `manual`. */
17 readonly by: string;
18 /** The command that starts a tree; tests stand one in. */
19 readonly entry?: readonly string[];
20 readonly budgetMs?: number;
21 }
22
23 async function roll(o: Options): Promise<Result<Release, string>> {
24 const at = Date.now();
25 const dir = releaseDir(o.dataDir, o.sha);
26 const failed = (note: string): Result<Release, string> => {
27 recordRelease(o.dataDir, {
28 sha: o.sha, at, by: o.by, status: "failed", healthySince: null, ms: null, note,
29 });
30 return err(note);
31 };
32 const checked = await preflight(dir, o.dataDir, o.entry);
33 if (!checked.ok) return failed(checked.error);
34 const swapped = await swap({
35 dataDir: o.dataDir, sha: o.sha, dir,
36 ...(o.entry === undefined ? {} : { entry: o.entry }),
37 ...(o.budgetMs === undefined ? {} : { budgetMs: o.budgetMs }),
38 });
39 if (!swapped.ok) return failed(swapped.error);
40 const release: Release = {
41 sha: o.sha, at, by: o.by, status: "live",
42 healthySince: Date.now(), ms: swapped.value.ms, note: "",
43 };
44 recordRelease(o.dataDir, release);
45 return ok(release);
46 }
47
48 /** A landed commit of the forge's own repository, out of its bare directory. */
49 export async function deploy(o: Options & { bareDir: string }): Promise<Result<Release, string>> {
50 if (!isSha(o.sha)) return err("not a commit id");
51 const out = await exportTree(o.bareDir, o.sha, releaseDir(o.dataDir, o.sha));
52 if (!out.ok) {
53 recordRelease(o.dataDir, {
54 sha: o.sha, at: Date.now(), by: o.by, status: "failed",
55 healthySince: null, ms: null, note: `checkout: ${out.error}`,
56 });
57 return err(`checkout: ${out.error}`);
58 }
59 return roll(o);
60 }
61
62 /** Swap back to a release directory already on disk. */
63 export async function rollback(o: Options): Promise<Result<Release, string>> {
64 if (!hasRelease(o.dataDir, o.sha)) return err("no such release on this machine");
65 return roll(o);
66 }
src/release/preflight.ts added +53
@@ -0,0 +1,53 @@
1 /**
2 * The new tree's boot preflight, run before anything swaps: its own
3 * `bun src/main.ts --preflight` against a copy of the live database, so a
4 * migration that would fail fails here, on a copy, with the old forge
5 * still serving.
6 */
7
8 import { Database } from "bun:sqlite";
9 import { existsSync, mkdtempSync, rmSync } from "node:fs";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { err, ok, type Result } from "../kernel/result.ts";
13
14 export const DEFAULT_ENTRY: readonly string[] = ["bun", "src/main.ts"];
15
16 export async function preflight(
17 dir: string,
18 dataDir: string,
19 entry: readonly string[] = DEFAULT_ENTRY,
20 timeoutMs = 120_000,
21 ): Promise<Result<void, string>> {
22 const scratch = mkdtempSync(join(process.env["TMPDIR"] ?? tmpdir(), "preflight-"));
23 try {
24 const live = join(dataDir, "forge.db");
25 if (existsSync(live)) {
26 const db = new Database(live, { readonly: true });
27 try {
28 db.run("VACUUM INTO ?", [join(scratch, "forge.db")]);
29 } finally {
30 db.close();
31 }
32 }
33 const child = Bun.spawn([...entry, "--preflight"], {
34 cwd: dir,
35 env: { ...process.env, FORGE_DATA: scratch, FORGE_APP_DATA: scratch, PORT: "0" },
36 stdout: "pipe",
37 stderr: "pipe",
38 timeout: timeoutMs,
39 });
40 const [out, errText, code] = await Promise.all([
41 new Response(child.stdout).text(),
42 new Response(child.stderr).text(),
43 child.exited,
44 ]);
45 if (code === 0) return ok();
46 const tail = (errText || out).trim().split("\n").slice(-3).join(" | ");
47 return err(`preflight exited ${code}: ${tail.slice(0, 400)}`);
48 } catch (error) {
49 return err(`preflight could not run: ${String(error).slice(0, 200)}`);
50 } finally {
51 rmSync(scratch, { recursive: true, force: true });
52 }
53 }
src/release/releases.ts added +72
@@ -0,0 +1,72 @@
1 /**
2 * The release list: one JSON file under the data directory, newest first.
3 * Plain data in, plain data out — the swap writes it, the page reads it,
4 * and a forge that loses it loses a list, never the release directories.
5 */
6
7 import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
8 import { join } from "node:path";
9
10 export type ReleaseStatus = "live" | "retired" | "failed";
11
12 export interface Release {
13 readonly sha: string;
14 /** When the swap was asked for, ms since the epoch. */
15 readonly at: number;
16 /** The landing that brought it (`#12`), `rollback`, or `manual`. */
17 readonly by: string;
18 readonly status: ReleaseStatus;
19 /** When it first answered healthy; null for one that never did. */
20 readonly healthySince: number | null;
21 /** What the roll cost, start to healthy, in ms; null for a failure. */
22 readonly ms: number | null;
23 /** A failed release says why, in one line. */
24 readonly note: string;
25 }
26
27 const SHA = /^[0-9a-f]{40}$/;
28 const KEEP = 50;
29
30 export const isSha = (value: unknown): value is string =>
31 typeof value === "string" && SHA.test(value);
32
33 export const releasesDir = (dataDir: string): string => join(dataDir, "releases");
34 export const releaseDir = (dataDir: string, sha: string): string =>
35 join(releasesDir(dataDir), sha);
36 export const listFile = (dataDir: string): string => join(dataDir, "releases.json");
37 export const pidFile = (dataDir: string): string => join(dataDir, "forge.pid");
38
39 export function readReleases(dataDir: string): Release[] {
40 try {
41 const parsed: unknown = JSON.parse(readFileSync(listFile(dataDir), "utf8"));
42 if (!Array.isArray(parsed)) return [];
43 return parsed.filter(
44 (r): r is Release =>
45 typeof r === "object" && r !== null && isSha((r as { sha?: unknown }).sha),
46 );
47 } catch {
48 return [];
49 }
50 }
51
52 /** Record a release: the live one retires the previous live one. */
53 export function recordRelease(dataDir: string, release: Release): Release[] {
54 const rest = readReleases(dataDir).map((r) =>
55 release.status === "live" && r.status === "live"
56 ? { ...r, status: "retired" as const }
57 : r,
58 );
59 const next = [release, ...rest].slice(0, KEEP);
60 mkdirSync(dataDir, { recursive: true });
61 const tmp = `${listFile(dataDir)}.${process.pid}.tmp`;
62 writeFileSync(tmp, JSON.stringify(next, null, 2));
63 renameSync(tmp, listFile(dataDir));
64 return next;
65 }
66
67 export const liveRelease = (list: readonly Release[]): Release | undefined =>
68 list.find((r) => r.status === "live");
69
70 /** A release directory that can be swapped back to. */
71 export const hasRelease = (dataDir: string, sha: string): boolean =>
72 isSha(sha) && existsSync(join(releaseDir(dataDir, sha), "src", "main.ts"));
src/release/service.ts added +57
@@ -0,0 +1,57 @@
1 /**
2 * A landing on the forge's own default branch deploys the forge. The merge
3 * has already passed the full gate (`checks/landing.ts`), so landed means
4 * live. Off unless `FORGE_SELF_REPO` names the repository (`owner/name`).
5 * A failed roll leaves the old forge serving, says so loudly in the log,
6 * and comments on the landed pull.
7 */
8
9 import type { App } from "../app.ts";
10 import { addComment } from "../actions/issues.ts";
11 import { getIssue } from "../core/issues.ts";
12 import { getRepoById } from "../core/repos.ts";
13 import { getUserById } from "../core/users.ts";
14 import { resolveOid } from "../git/merge.ts";
15 import { repoDir } from "../git/repos.ts";
16 import { deploy } from "./deploy.ts";
17 import { isSha, readReleases } from "./releases.ts";
18
19 export interface ReleaseService {
20 stop(): void;
21 }
22
23 export function startReleases(app: App, self: string): ReleaseService {
24 const [owner, name] = self.split("/");
25 let busy: Promise<void> = Promise.resolve();
26 const run = async (repoId: string, by: string, pull: number | undefined, actorId: string | null) => {
27 const repo = getRepoById(app.db, repoId);
28 if (repo === undefined || repo.ownerName !== owner || repo.name !== name) return;
29 const bareDir = repoDir(app.config.dataDir, repo.ownerName, repo.name);
30 const sha = await resolveOid(bareDir, `refs/heads/${repo.defaultBranch}`);
31 if (!isSha(sha) || readReleases(app.config.dataDir)[0]?.sha === sha) return;
32 const label = pull === undefined ? by : `#${pull}`;
33 const done = await deploy({ dataDir: app.config.dataDir, bareDir, sha, by: label });
34 if (done.ok) {
35 app.log.info("released", { sha, ms: done.value.ms ?? 0, by: label });
36 return;
37 }
38 app.log.error(`RELEASE FAILED, the old forge is still serving: ${sha.slice(0, 7)} ${done.error}`);
39 if (pull === undefined) return;
40 const issue = getIssue(app.db, repo.id, pull);
41 const actor = actorId === null ? undefined : getUserById(app.db, actorId);
42 if (issue !== undefined)
43 addComment(app, actor, repo, issue,
44 `Release of ${sha.slice(0, 7)} failed: ${done.error}\n\nThe previous release is still serving.`);
45 };
46 const off = app.bus.subscribe((event) => {
47 if (event.kind !== "pull.merged" && event.kind !== "push") return;
48 if (event.repoId === null) return;
49 const number = event.payload["number"];
50 const repoId = event.repoId;
51 busy = busy.then(() =>
52 run(repoId, "push", typeof number === "number" ? number : undefined, event.actorId ?? null)
53 .catch((error) => app.log.error("release crashed", { error: String(error) })),
54 );
55 });
56 return { stop: off };
57 }
src/release/swap.ts added +119
@@ -0,0 +1,119 @@
1 /**
2 * The swap: start the new tree beside the old, read its health, and only
3 * then tell the old to drain. The new process shares the listening port
4 * (SO_REUSEPORT, `FORGE_HANDOFF=1`), so there is no moment nobody listens.
5 * A new process that does not come up in its budget is killed and the old
6 * one never learns of it.
7 */
8
9 import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
10 import { join } from "node:path";
11 import { fetchInternal } from "../git/hook-address.ts";
12 import { err, ok, type Result } from "../kernel/result.ts";
13 import { DEFAULT_ENTRY } from "./preflight.ts";
14 import { pidFile } from "./releases.ts";
15
16 export interface Ready {
17 readonly pid: number;
18 readonly sha: string;
19 /** The internal listener's address (`git/hook-address.ts`). */
20 readonly socket: string;
21 }
22
23 export interface Swapped {
24 readonly pid: number;
25 /** Start to healthy, ms. */
26 readonly ms: number;
27 }
28
29 export const readyFile = (dataDir: string, sha: string): string =>
30 join(dataDir, `.ready-${sha}.json`);
31
32 export function readPid(dataDir: string): number | undefined {
33 try {
34 const pid = Number(readFileSync(pidFile(dataDir), "utf8").trim());
35 return Number.isInteger(pid) && pid > 1 ? pid : undefined;
36 } catch {
37 return undefined;
38 }
39 }
40
41 /** Said by a booted forge once it serves: pid file and, if asked, the ready file. */
42 export function announceReady(dataDir: string, socket: string): void {
43 writeFileSync(pidFile(dataDir), String(process.pid));
44 const path = process.env["FORGE_READY_FILE"];
45 const sha = process.env["FORGE_COMMIT"] ?? "";
46 if (path) writeFileSync(path, JSON.stringify({ pid: process.pid, sha, socket }));
47 }
48
49 const alive = (pid: number): boolean => {
50 try {
51 process.kill(pid, 0);
52 return true;
53 } catch {
54 return false;
55 }
56 };
57
58 export async function swap(input: {
59 dataDir: string;
60 sha: string;
61 dir: string;
62 entry?: readonly string[];
63 budgetMs?: number;
64 }): Promise<Result<Swapped, string>> {
65 const { dataDir, sha, dir } = input;
66 const started = performance.now();
67 const ready = readyFile(dataDir, sha);
68 rmSync(ready, { force: true });
69 const old = readPid(dataDir);
70 const child = Bun.spawn([...(input.entry ?? DEFAULT_ENTRY)], {
71 cwd: dir,
72 env: {
73 ...process.env,
74 FORGE_DATA: dataDir,
75 FORGE_COMMIT: sha,
76 FORGE_READY_FILE: ready,
77 FORGE_HANDOFF: "1",
78 },
79 stdin: "ignore",
80 stdout: "inherit",
81 stderr: "inherit",
82 detached: true,
83 });
84 child.unref();
85 let exited = false;
86 void child.exited.then(() => (exited = true));
87 const fail = (why: string): Result<Swapped, string> => {
88 if (!exited) child.kill("SIGTERM");
89 rmSync(ready, { force: true });
90 return err(why);
91 };
92 const deadline = started + (input.budgetMs ?? 60_000);
93 let body: Ready | undefined;
94 while (performance.now() < deadline) {
95 if (exited) return fail("the new process exited before it was healthy");
96 if (existsSync(ready)) {
97 try {
98 body = JSON.parse(readFileSync(ready, "utf8")) as Ready;
99 break;
100 } catch {
101 // half-written; the next tick reads it whole
102 }
103 }
104 await Bun.sleep(50);
105 }
106 if (body === undefined) return fail("the new process did not become healthy in its budget");
107 if (body.sha !== sha) return fail("the new process reports a different commit");
108 try {
109 // Any answer is a live listener; a refusal or a hang is not.
110 await fetchInternal(body.socket, "/internal/ping", {
111 signal: AbortSignal.timeout(2_000),
112 });
113 } catch {
114 return fail("the new process does not answer on its socket");
115 }
116 rmSync(ready, { force: true });
117 if (old !== undefined && old !== body.pid && alive(old)) process.kill(old, "SIGTERM");
118 return ok({ pid: body.pid, ms: Math.round(performance.now() - started) });
119 }
src/web/pages/releases.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * Releases: what the forge itself has run, newest first — which commit,
3 * when, by which landing, healthy since when, and what the roll cost. A
4 * writer on the forge's own repository can roll back to a retired one.
5 * The list is `releases.json` (`release/releases.ts`), written by the swap.
6 */
7
8 import type { Ctx } from "../../http/context.ts";
9 import { canWrite, getRepo } from "../../core/repos.ts";
10 import { rollback } from "../../release/deploy.ts";
11 import { isSha, liveRelease, readReleases, type Release } from "../../release/releases.ts";
12 import { signInFirst } from "../chrome.ts";
13 import { readForm } from "../form.ts";
14 import { html, when, type Html } from "../html.ts";
15 import { flashTo, page } from "../layout.ts";
16 import { btn, card, empty, time } from "../ui.ts";
17
18 const selfRepo = (ctx: Ctx) => {
19 const [owner, name] = (process.env["FORGE_SELF_REPO"] ?? "").split("/");
20 return owner && name ? getRepo(ctx.app.db, owner, name) : undefined;
21 };
22
23 const iso = (ms: number): string => new Date(ms).toISOString();
24
25 /** "live: a1b2c3d since <time>" for the home page; nothing before a first release. */
26 export function liveLine(ctx: Ctx): Html | undefined {
27 const live = liveRelease(readReleases(ctx.app.config.dataDir));
28 if (live === undefined) return undefined;
29 return html`<p class="small muted" id="forge-live">
30 <a href="/releases">live: ${live.sha.slice(0, 7)}</a> since
31 ${time(iso(live.healthySince ?? live.at))}
32 </p>`;
33 }
34
35 /** GET /releases */
36 export function releasesPage(ctx: Ctx): Response {
37 if (!ctx.auth.user) return signInFirst(ctx);
38 const list = readReleases(ctx.app.config.dataDir);
39 const repo = selfRepo(ctx);
40 const may = repo !== undefined && canWrite(ctx.app.db, repo, ctx.auth.user);
41 const row = (r: Release): Html => html`<tr>
42 <td><code>${r.sha.slice(0, 7)}</code></td>
43 <td>${time(iso(r.at))}</td>
44 <td>${r.by}</td>
45 <td>${r.status}${when(r.note || undefined, (n) => html` — ${n}`)}</td>
46 <td>${r.healthySince === null ? "never" : time(iso(r.healthySince))}</td>
47 <td>${r.ms === null ? "" : `${r.ms} ms`}</td>
48 <td>${when(
49 may && r.status === "retired" ? r : undefined,
50 (x) => html`<form method="post" action="/releases/rollback">
51 <input type="hidden" name="sha" value="${x.sha}" />
52 ${btn("Roll back to this", { type: "submit" })}
53 </form>`,
54 )}</td>
55 </tr>`;
56 return page({
57 ctx,
58 title: "Releases",
59 body: html`<div class="page-head"><h1>Releases</h1></div>
60 ${list.length === 0
61 ? empty({ title: "No release yet", note: "A landing on the forge's own default branch makes the first." })
62 : card(html`<table>
63 <thead><tr><th>Commit</th><th>When</th><th>By</th><th>State</th><th>Healthy since</th><th>Roll</th><th></th></tr></thead>
64 <tbody>${list.map(row)}</tbody>
65 </table>`)}`,
66 });
67 }
68
69 /** POST /releases/rollback — swap back to a retired release; a writer's. */
70 export async function releasesRollback(ctx: Ctx): Promise<Response> {
71 if (!ctx.auth.user) return signInFirst(ctx);
72 const form = await readForm(ctx, "rw");
73 if (form instanceof Response) return form;
74 const repo = selfRepo(ctx);
75 if (repo === undefined || !canWrite(ctx.app.db, repo, ctx.auth.user))
76 return new Response("not found", { status: 404 });
77 const sha = String(form.get("sha") ?? "");
78 if (!isSha(sha)) return flashTo(ctx, "/releases", { tone: "danger", message: "Not a release." });
79 const done = await rollback({ dataDir: ctx.app.config.dataDir, sha, by: "rollback" });
80 return flashTo(ctx, "/releases", done.ok
81 ? { message: `Rolled back to ${sha.slice(0, 7)} in ${done.value.ms} ms.` }
82 : { tone: "danger", message: `Rollback failed, the running release is untouched: ${done.error}` });
83 }
src/web/studio/home.ts +3 −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,
@@ -167,6 +168,7 @@ export async function studioHome(
167168 const { repos: appRepos } = writableAppsOf(ctx, user);
168169 // A spawned forge says where it lives: the address its person shares.
169170 const spawned = await spawnedOrg(ctx.app);
171 const live = liveLine(ctx);
170172 const address = when(
171173 spawned?.url,
172174 (url) =>
@@ -178,7 +180,7 @@ export async function studioHome(
178180 // everyday account themselves (#600); anywhere else, #803's card asks.
179181 const firstSteps = await nextStepsCard(ctx, user);
180182 const body = html`<h1 class="sr-only">Home</h1>
181 ${firstSteps ?? everydayCard(ctx, user)} ${address}
183 ${firstSteps ?? everydayCard(ctx, user)} ${address} ${live}
182184 ${homeTabs("feed")}
183185 <div class="dash">
184186 <div class="dash-main stack">
test/release-preflight.test.ts added +50
@@ -0,0 +1,50 @@
1 /** The real tree's preflight, and the release list's bookkeeping. */
2
3 import { expect, test } from "bun:test";
4 import { mkdtempSync, rmSync } from "node:fs";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp } from "../src/app.ts";
8 import { preflight } from "../src/release/preflight.ts";
9 import { liveRelease, readReleases, recordRelease } from "../src/release/releases.ts";
10
11 const root = join(import.meta.dir, "..");
12 const tmp = () => mkdtempSync(join(process.env["TMPDIR"] ?? tmpdir(), "pf-"));
13
14 test("this tree passes its own preflight against a copy of a live database", async () => {
15 const data = tmp();
16 try {
17 createApp({ dataDir: data }).close();
18 const done = await preflight(root, data);
19 expect(done).toEqual({ ok: true, value: undefined });
20 } finally {
21 rmSync(data, { recursive: true, force: true });
22 }
23 }, 60_000);
24
25 test("a tree whose entry fails its preflight is refused with the reason", async () => {
26 const data = tmp();
27 try {
28 const done = await preflight(root, data, ["bun", "-e", "console.error('bad config'); process.exit(3)"]);
29 expect(done.ok).toBe(false);
30 if (!done.ok) expect(done.error).toContain("bad config");
31 } finally {
32 rmSync(data, { recursive: true, force: true });
33 }
34 });
35
36 test("the live release retires the one before it", () => {
37 const data = tmp();
38 try {
39 const at = (n: number, sha: string, status: "live" | "failed" = "live") =>
40 recordRelease(data, { sha: sha.repeat(40), at: n, by: "#1", status, healthySince: n, ms: 5, note: "" });
41 at(1, "a");
42 at(2, "b");
43 at(3, "c", "failed");
44 const list = readReleases(data);
45 expect(list.map((r) => r.status)).toEqual(["failed", "live", "retired"]);
46 expect(liveRelease(list)?.sha).toBe("b".repeat(40));
47 } finally {
48 rmSync(data, { recursive: true, force: true });
49 }
50 });
test/release-swap.test.ts added +138
@@ -0,0 +1,138 @@
1 /**
2 * A stand-in forge lands changes: the new sha serves on the same port with
3 * no failed request during the swap, a failing preflight keeps the old one,
4 * and a rollback serves the old sha again. The stand-in tree is the
5 * smallest thing the swap contract needs: `--preflight`, `FORGE_HANDOFF`,
6 * `FORGE_READY_FILE`, a pid file, SIGTERM drains.
7 */
8
9 import { afterAll, beforeAll, expect, test } from "bun:test";
10 import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { deploy, rollback } from "../src/release/deploy.ts";
14 import { liveRelease, readReleases } from "../src/release/releases.ts";
15 import { gitClientEnv } from "./helpers/git-client.ts";
16
17 const STAND_IN = `
18 import { writeFileSync, existsSync } from "node:fs";
19 const sha = process.env.FORGE_COMMIT ?? "";
20 if (process.argv.includes("--preflight")) process.exit(existsSync("BROKEN") ? 1 : 0);
21 const web = Bun.serve({ port: Number(process.env.PORT), reusePort: true, fetch: () => new Response(sha) });
22 const internal = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("ok") });
23 const sock = "tcp:127.0.0.1:" + internal.port;
24 writeFileSync(process.env.FORGE_DATA + "/forge.pid", String(process.pid));
25 writeFileSync(process.env.FORGE_READY_FILE, JSON.stringify({ pid: process.pid, sha, socket: sock }));
26 process.on("SIGTERM", () => { web.stop(); setTimeout(() => process.exit(0), 200); });
27 `;
28
29 let root = "";
30 let bare = "";
31 let data = "";
32 let port = 0;
33 const shas: string[] = [];
34 const entry = ["bun", "src/main.ts"];
35
36 async function git(cwd: string, ...args: string[]): Promise<string> {
37 const p = Bun.spawn(["git", ...args], { cwd, env: gitClientEnv(), stdout: "pipe", stderr: "pipe" });
38 const out = await new Response(p.stdout).text();
39 expect(await p.exited).toBe(0);
40 return out.trim();
41 }
42
43 async function land(files: Record<string, string>): Promise<string> {
44 const work = join(root, "work");
45 for (const [name, body] of Object.entries(files)) {
46 mkdirSync(join(work, name, ".."), { recursive: true });
47 writeFileSync(join(work, name), body);
48 }
49 await git(work, "add", "-A");
50 await git(work, "commit", "-m", "land");
51 const sha = await git(work, "rev-parse", "HEAD");
52 await git(work, "push", bare, "HEAD:refs/heads/main");
53 shas.push(sha);
54 return sha;
55 }
56
57 const served = async (): Promise<string> => (await fetch(`http://127.0.0.1:${port}/`)).text();
58
59 beforeAll(async () => {
60 root = mkdtempSync(join(process.env["TMPDIR"] ?? tmpdir(), "release-"));
61 data = join(root, "data");
62 mkdirSync(data);
63 bare = join(root, "bare.git");
64 await git(root, "init", "--bare", bare);
65 mkdirSync(join(root, "work"));
66 await git(join(root, "work"), "init", "-b", "main");
67 const probe = Bun.serve({ port: 0, fetch: () => new Response("") });
68 port = probe.port ?? 0;
69 probe.stop(true);
70 process.env["PORT"] = String(port);
71 });
72
73 afterAll(() => {
74 for (const f of ["forge.pid"]) {
75 try {
76 process.kill(Number(readFileSync(join(data, f), "utf8")), "SIGKILL");
77 } catch {}
78 }
79 rmSync(root, { recursive: true, force: true });
80 });
81
82 test("a landing swaps with no failed request, a bad preflight keeps the old, a rollback goes back", async () => {
83 const a = await land({ "src/main.ts": STAND_IN });
84 const first = await deploy({ dataDir: data, bareDir: bare, sha: a, by: "#1", entry, budgetMs: 15_000 });
85 expect(first).toEqual({ ok: true, value: expect.anything() });
86 expect(await served()).toBe(a);
87
88 const b = await land({ "README": "b" });
89 let failed = 0;
90 let count = 0;
91 let stop = false;
92 const hammer = (async () => {
93 while (!stop) {
94 // A new connection that lands on the old listener at the instant it
95 // closes is reset by the kernel (SO_REUSEPORT); a client retries a GET
96 // as every browser and proxy does. Failing twice in a row is a gap.
97 for (let attempt = 0; attempt < 2; attempt++) {
98 try {
99 const r = await fetch(`http://127.0.0.1:${port}/`, { headers: { connection: "close" } });
100 if (r.ok) break;
101 } catch {}
102 if (attempt === 1) failed++;
103 }
104 count++;
105 }
106 })();
107 const second = await deploy({ dataDir: data, bareDir: bare, sha: b, by: "#2", entry, budgetMs: 15_000 });
108 await Bun.sleep(500);
109 stop = true;
110 await hammer;
111 expect(second.ok).toBe(true);
112 expect(count).toBeGreaterThan(10);
113 expect(failed).toBe(0);
114 expect(await served()).toBe(b);
115 expect(liveRelease(readReleases(data))?.sha).toBe(b);
116
117 const c = await land({ BROKEN: "x" });
118 const bad = await deploy({ dataDir: data, bareDir: bare, sha: c, by: "#3", entry, budgetMs: 15_000 });
119 expect(bad.ok).toBe(false);
120 expect(await served()).toBe(b);
121 const list = readReleases(data);
122 expect(list[0]?.status).toBe("failed");
123 expect(liveRelease(list)?.sha).toBe(b);
124
125 expect((await rollback({ dataDir: data, sha: a, by: "rollback", entry, budgetMs: 15_000 })).ok).toBe(true);
126 await Bun.sleep(300);
127 expect(await served()).toBe(a);
128 expect(existsSync(join(data, "releases", c))).toBe(true);
129 expect((await rollback({ dataDir: data, sha: "f".repeat(40), by: "rollback", entry })).ok).toBe(false);
130 }, 60_000);
131
132 test("a new process that never becomes healthy leaves the old serving", async () => {
133 const live = await served();
134 const d = await land({ "src/main.ts": "if (process.argv.includes('--preflight')) process.exit(0); setTimeout(() => {}, 60000);" });
135 const stuck = await deploy({ dataDir: data, bareDir: bare, sha: d, by: "#4", entry, budgetMs: 1_000 });
136 expect(stuck.ok).toBe(false);
137 expect(await served()).toBe(live);
138 }, 30_000);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs