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 #1494
scout/forge:scout/1432-the-forge-deploys-itself-from-its-own-ma → main 8 commits fork 12 threads · 12 unresolved
README.md +2
| @@ -419,6 +419,8 @@ stands, taking updates, and the crew's part when both sides moved. | ||
| 419 | 419 | `docs/FLEET.md` is one change across many repositories, runs or issues: a |
| 420 | 420 | query, a dry-run plan of every row before → after, a receipt, and undo. |
| 421 | 421 | |
| 422 | `docs/RELEASES.md` is the forge deploying itself from its own main: the swap, `/releases`, rollback. | |
| 423 | ||
| 422 | 424 | `docs/MCP.md` is the forge as a connector, and `docs/STANDARDS.md` is what |
| 423 | 425 | it answers by default: `.well-known`, feeds, cards, the manifest. |
| 424 | 426 |
docs/RELEASES.md added +21
| @@ -0,0 +1,21 @@ | ||
| 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 (`pull.merged`) on that repository (the full gate has already passed on the merge) then deploys that event's merge commit — not the branch tip when the job runs. A plain push to the default branch deploys nothing. The landing: | |
| 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 with the new tree's stderr tail. No comment is posted on the pull: the forge has no author of its own, and stderr must not appear under a person's name. The failure is on `/releases`. | |
| 11 | ||
| 12 | - `bun src/main.ts --rollback <sha>` (or the button on `/releases`, or `b` in the terminal) swaps back to a release directory on disk the same way. | |
| 13 | - Who: writers of the forge repository and site admins may read `/releases` (it shows failure notes) and roll back; everyone else gets a 404, and the home's `live:` line is plain text for them. | |
| 14 | - Terminal: `R` on the dashboard opens the same list (`src/tui/screens/releases.ts`); `b` on a retired release rolls back after a confirmation. Connect with the command in `FORGE_APP_SSH`. | |
| 15 | - One queue (`release/queue.ts`) orders every swap — a landing, the web button, the terminal — so two never race on `forge.pid`. | |
| 16 | - State: `$FORGE_DATA/releases.json` (the list), `$FORGE_DATA/forge.pid`, `$FORGE_DATA/releases/<sha>/`. The home shows `live: <sha> since <time>`. | |
| 17 | - `FORGE_COMMIT` is the landed sha for `/api/v1/health`. | |
| 18 | ||
| 19 | 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). | |
| 20 | ||
| 21 | Overlap: for the seconds both processes live, the new one serves and answers health at once but starts no loop (apps supervisor, checks, crew, timers) until the pid in `forge.pid` that it replaces has exited (`release/hold.ts`), so nothing is claimed twice. The old side drains and a run in flight there finishes there. A new process killed while waiting has started nothing. | |
scripts/gate.ts +6
| @@ -82,6 +82,12 @@ export const GATE: readonly string[] = [ | ||
| 82 | 82 | "test/sole-owner-suspend.test.ts", |
| 83 | 83 | "test/standing-every-process.test.ts", |
| 84 | 84 | "test/steer.test.ts", |
| 85 | "test/release-gate.test.ts", | |
| 86 | "test/release-handoff.test.ts", | |
| 87 | "test/release-hold.test.ts", | |
| 88 | "test/release-preflight.test.ts", | |
| 89 | "test/release-routes.test.ts", | |
| 90 | "test/release-swap.test.ts", | |
| 85 | 91 | "test/sealed-git.test.ts", |
| 86 | 92 | "test/sealed-issues.test.ts", |
| 87 | 93 | "test/sealed-release.test.ts", |
src/app.ts +2
| @@ -32,6 +32,8 @@ export interface ForgeConfig { | ||
| 32 | 32 | dataDir: string; |
| 33 | 33 | /** @default 3000 */ |
| 34 | 34 | port?: number; |
| 35 | /** Share the port with another process: the new side of a release. */ | |
| 36 | reusePort?: boolean; | |
| 35 | 37 | /** The hostname clone URLs are built from. @default "localhost" */ |
| 36 | 38 | host?: string; |
| 37 | 39 | /** |
src/core/reserved.ts +1
| @@ -87,6 +87,7 @@ export const SYSTEM_NAMES: readonly string[] = [ | ||
| 87 | 87 | "runs", |
| 88 | 88 | "search", |
| 89 | 89 | "settings", |
| 90 | "releases", | |
| 90 | 91 | "signin", |
| 91 | 92 | "signup", |
| 92 | 93 | "sitemap.xml", |
src/http/server.ts +10
| @@ -87,6 +87,7 @@ import { | ||
| 87 | 87 | verifyPage, |
| 88 | 88 | themeSubmit, |
| 89 | 89 | } from "../web/pages/site.ts"; |
| 90 | import { releasesPage, releasesRollback } from "../web/pages/releases.ts"; | |
| 90 | 91 | import { confirmPage, searchPage } from "../web/pages/search.ts"; |
| 91 | 92 | import { followingSubmit } from "../web/pages/following.ts"; |
| 92 | 93 | import { reconnectSubmit } from "../web/pages/frozen.ts"; |
| @@ -670,6 +671,8 @@ export function buildRouter(): Router<Handler> { | ||
| 670 | 671 | router.add("GET", "/admin/limits", limitsPage); |
| 671 | 672 | router.add("POST", "/admin/limits", limitsSet); |
| 672 | 673 | router.add("GET", "/settings/backups", backupsPage); |
| 674 | router.add("GET", "/releases", releasesPage); | |
| 675 | router.add("POST", "/releases/rollback", releasesRollback); | |
| 673 | 676 | router.add("POST", "/settings/backups/now", backupsNow); |
| 674 | 677 | router.add("POST", "/settings/backups/destination", backupsDestination); |
| 675 | 678 | router.add("POST", "/settings/backups/test", backupsTest); |
| @@ -1542,6 +1545,8 @@ async function handleHook(app: App, request: Request): Promise<Response> { | ||
| 1542 | 1545 | export interface Servers { |
| 1543 | 1546 | readonly url: string; |
| 1544 | 1547 | readonly port: number; |
| 1548 | /** Stop taking new connections; what is in flight finishes. A handoff's old side. */ | |
| 1549 | closeListener(): void; | |
| 1545 | 1550 | stop(): void; |
| 1546 | 1551 | } |
| 1547 | 1552 | |
| @@ -1682,6 +1687,8 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1682 | 1687 | |
| 1683 | 1688 | const web = Bun.serve({ |
| 1684 | 1689 | port: app.config.port ?? 3000, |
| 1690 | // A release starts beside the old process on the same port (`release/swap.ts`). | |
| 1691 | reusePort: app.config.reusePort === true, | |
| 1685 | 1692 | idleTimeout: 120, |
| 1686 | 1693 | // The largest thing anyone may send — a git push. Every reader below it |
| 1687 | 1694 | // keeps its own, smaller cap (\`http/limits.ts\`); the runtime enforces |
| @@ -1781,6 +1788,9 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1781 | 1788 | return { |
| 1782 | 1789 | url: `http://localhost:${port}`, |
| 1783 | 1790 | port, |
| 1791 | closeListener() { | |
| 1792 | web.stop(); | |
| 1793 | }, | |
| 1784 | 1794 | stop() { |
| 1785 | 1795 | endOpen(); |
| 1786 | 1796 | clearInterval(sweep); |
src/main.ts +49
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | * environment-only — a handful of variables, all with sane defaults. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { resolve } from "node:path"; | |
| 7 | 8 | import { parseCidrs } from "./kernel/cidr.ts"; |
| 8 | 9 | import { createApp } from "./app.ts"; |
| 9 | 10 | import { reconcile } from "./core/reconcile.ts"; |
| @@ -39,6 +40,10 @@ import { startPromptRoutine } from "./crew/prompts.ts"; | ||
| 39 | 40 | import { pruneTokens } from "./core/tokens.ts"; |
| 40 | 41 | import { dataHomeRefusal } from "./kernel/data_home.ts"; |
| 41 | 42 | import { running } from "./kernel/version.ts"; |
| 43 | import { predecessor, untilGone } from "./release/hold.ts"; | |
| 44 | import { announceReady } from "./release/swap.ts"; | |
| 45 | import { rollback } from "./release/deploy.ts"; | |
| 46 | import { startReleases } from "./release/service.ts"; | |
| 42 | 47 | |
| 43 | 48 | // `forge hook <name>` re-enters here from a git hook stub. It relays to the |
| 44 | 49 | // running forge over its socket and exits — it must never boot a server. |
| @@ -84,6 +89,20 @@ if (refusal !== null) { | ||
| 84 | 89 | process.exit(1); |
| 85 | 90 | } |
| 86 | 91 | |
| 92 | // `--rollback <sha>`: swap back to a release directory already on this | |
| 93 | // machine, the way a landing swaps forward, then exit (docs/RELEASES.md). | |
| 94 | if (process.argv[2] === "--rollback") { | |
| 95 | const done = await rollback({ | |
| 96 | dataDir: resolve(dataDir), | |
| 97 | sha: process.argv[3] ?? "", | |
| 98 | by: "rollback", | |
| 99 | }); | |
| 100 | // CLI message on stdout/stderr for the person at the terminal. | |
| 101 | if (!done.ok) console.error(`rollback failed, the running forge is untouched: ${done.error}`); | |
| 102 | else console.log(`rolled back to ${done.value.sha.slice(0, 7)} in ${done.value.ms} ms`); | |
| 103 | process.exit(done.ok ? 0 : 1); | |
| 104 | } | |
| 105 | ||
| 87 | 106 | // FORGE_TRUSTED_PROXIES is checked here so a typo fails the boot, not a |
| 88 | 107 | // limit that quietly counts every stranger as one. |
| 89 | 108 | const trustedProxies = (process.env.FORGE_TRUSTED_PROXIES ?? "") |
| @@ -101,6 +120,9 @@ const trustedProxies = (process.env.FORGE_TRUSTED_PROXIES ?? "") | ||
| 101 | 120 | const app = createApp({ |
| 102 | 121 | dataDir, |
| 103 | 122 | port: Number(process.env.PORT ?? 3000), |
| 123 | // FORGE_HANDOFF=1: listen beside another forge on the same port, so a | |
| 124 | // release starts before the old one stops (`release/swap.ts`). | |
| 125 | ...(process.env.FORGE_HANDOFF === "1" ? { reusePort: true } : {}), | |
| 104 | 126 | ...(process.env.FORGE_HOST === undefined |
| 105 | 127 | ? {} |
| 106 | 128 | : { host: process.env.FORGE_HOST }), |
| @@ -163,6 +185,14 @@ const app = createApp({ | ||
| 163 | 185 | }), |
| 164 | 186 | }); |
| 165 | 187 | |
| 188 | // `--preflight`: this tree's config parsed, schema migrated (createApp | |
| 189 | // opens and migrates the database): proof it boots, before anything swaps. | |
| 190 | if (process.argv.includes("--preflight")) { | |
| 191 | app.close(); | |
| 192 | console.log("preflight ok"); | |
| 193 | process.exit(0); | |
| 194 | } | |
| 195 | ||
| 166 | 196 | await reconcile(app); |
| 167 | 197 | // Issues linked under a pillar's umbrella before pillars had labels. |
| 168 | 198 | const labelled = syncAllPillars(app); |
| @@ -178,6 +208,16 @@ if (sshStarted && !sshStarted.ok) | ||
| 178 | 208 | }); |
| 179 | 209 | const ssh = sshStarted?.ok ? sshStarted.value : undefined; |
| 180 | 210 | |
| 211 | // A release overlaps the forge it replaces. This one serves and says it is | |
| 212 | // ready now, but starts no loop (apps, checks, crew, timers) until that | |
| 213 | // process has exited: nothing may run twice (`release/hold.ts`). | |
| 214 | const replaced = predecessor(app.config.dataDir); | |
| 215 | announceReady(app.config.dataDir, app.hookAddress.current); | |
| 216 | if (replaced !== undefined) { | |
| 217 | app.log.info("waiting for the old forge to exit before starting loops", { pid: replaced }); | |
| 218 | await untilGone(replaced); | |
| 219 | } | |
| 220 | ||
| 181 | 221 | // Apps and the crew (docs/APPS.md). Both are on unless FORGE_APPS=0: an app |
| 182 | 222 | // is served by Host on the same port, and the crew runs agents as child |
| 183 | 223 | // processes. The public URL is what apps and agents are told about the |
| @@ -333,6 +373,12 @@ const tickAsks = async (): Promise<void> => { | ||
| 333 | 373 | const staleTimer = setInterval(() => void tickAsks(), 120_000); |
| 334 | 374 | void tickAsks(); |
| 335 | 375 | |
| 376 | // A landing on the forge's own default branch deploys it (`release/`). | |
| 377 | const selfRepo = (process.env.FORGE_SELF_REPO ?? "").trim(); | |
| 378 | const releases = /^[\w.-]+\/[\w.-]+$/.test(selfRepo) | |
| 379 | ? startReleases(app, selfRepo) | |
| 380 | : undefined; | |
| 381 | ||
| 336 | 382 | app.log.info("forge is up", { url: servers.url, data: app.config.dataDir }); |
| 337 | 383 | // Only an agent is on a crew (the `repo_crew_agents_only` trigger refuses anyone else). A person |
| 338 | 384 | // put on one before that is reported here for the owner to take off — the |
| @@ -399,6 +445,9 @@ function shutdown(signal: NodeJS.Signals): void { | ||
| 399 | 445 | // Streams end now, with a resume hint: their browsers reconnect to the |
| 400 | 446 | // process that replaced this one, not to this one while it finishes. |
| 401 | 447 | drainStreams(); |
| 448 | // The release that replaced this one already takes new connections. | |
| 449 | if (process.env.FORGE_HANDOFF === "1") servers.closeListener(); | |
| 450 | releases?.stop(); | |
| 402 | 451 | clearInterval(deliveryTimer); |
| 403 | 452 | clearInterval(syncTimer); |
| 404 | 453 | clearInterval(staleTimer); |
src/release/access.ts added +22
| @@ -0,0 +1,22 @@ | ||
| 1 | /** | |
| 2 | * Who may see and steer releases: the writers of the forge's own repository | |
| 3 | * and site admins. A failed release carries the new tree's stderr, which can | |
| 4 | * name paths and configuration, so reading is as guarded as rolling back. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import { canWrite, getRepo, type Repo } from "../core/repos.ts"; | |
| 9 | import type { User } from "../core/users.ts"; | |
| 10 | ||
| 11 | /** The forge's own repository, when `FORGE_SELF_REPO` names one that exists. */ | |
| 12 | export function selfRepo(app: App): Repo | undefined { | |
| 13 | const [owner, name] = (process.env["FORGE_SELF_REPO"] ?? "").split("/"); | |
| 14 | return owner && name ? getRepo(app.db, owner, name) : undefined; | |
| 15 | } | |
| 16 | ||
| 17 | export function mayManageReleases(app: App, user: User | undefined): boolean { | |
| 18 | if (user === undefined) return false; | |
| 19 | if (user.isAdmin) return true; | |
| 20 | const repo = selfRepo(app); | |
| 21 | return repo !== undefined && canWrite(app.db, repo, user); | |
| 22 | } |
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/hold.ts added +37
| @@ -0,0 +1,37 @@ | ||
| 1 | /** | |
| 2 | * Two forges share a database for the seconds a release overlaps. The new | |
| 3 | * one serves at once, but its loops (crew, checks, apps, timers) wait until | |
| 4 | * the process it replaces has exited, so nothing is claimed twice. | |
| 5 | */ | |
| 6 | ||
| 7 | import { readPid } from "./swap.ts"; | |
| 8 | ||
| 9 | const isAlive = (pid: number): boolean => { | |
| 10 | try { | |
| 11 | process.kill(pid, 0); | |
| 12 | return true; | |
| 13 | } catch { | |
| 14 | return false; | |
| 15 | } | |
| 16 | }; | |
| 17 | ||
| 18 | /** The live process this boot replaces: only in a handoff, never itself. */ | |
| 19 | export function predecessor( | |
| 20 | dataDir: string, | |
| 21 | env: Record<string, string | undefined> = process.env, | |
| 22 | self: number = process.pid, | |
| 23 | alive: (pid: number) => boolean = isAlive, | |
| 24 | ): number | undefined { | |
| 25 | if (env["FORGE_HANDOFF"] !== "1") return undefined; | |
| 26 | const pid = readPid(dataDir); | |
| 27 | return pid !== undefined && pid !== self && alive(pid) ? pid : undefined; | |
| 28 | } | |
| 29 | ||
| 30 | /** Resolves once `pid` is gone; at once when there is none. */ | |
| 31 | export async function untilGone( | |
| 32 | pid: number | undefined, | |
| 33 | alive: (pid: number) => boolean = isAlive, | |
| 34 | sleep: (ms: number) => Promise<unknown> = Bun.sleep, | |
| 35 | ): Promise<void> { | |
| 36 | while (pid !== undefined && alive(pid)) await sleep(200); | |
| 37 | } |
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/queue.ts added +23
| @@ -0,0 +1,23 @@ | ||
| 1 | /** | |
| 2 | * One swap at a time. A landing, a click on the page and a key in the | |
| 3 | * terminal all move `forge.pid` and the ready file, so they all go through | |
| 4 | * this chain: the next waits for the one in front, whatever that one did. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { Result } from "../kernel/result.ts"; | |
| 8 | import { rollback, type Options } from "./deploy.ts"; | |
| 9 | import type { Release } from "./releases.ts"; | |
| 10 | ||
| 11 | let tail: Promise<unknown> = Promise.resolve(); | |
| 12 | ||
| 13 | /** Run `job` after every job queued before it has settled. */ | |
| 14 | export function serial<T>(job: () => Promise<T>): Promise<T> { | |
| 15 | const next = tail.then(job, job); | |
| 16 | tail = next.catch(() => undefined); | |
| 17 | return next; | |
| 18 | } | |
| 19 | ||
| 20 | /** A rollback that waits its turn. */ | |
| 21 | export function queuedRollback(o: Options): Promise<Result<Release, string>> { | |
| 22 | return serial(() => rollback(o)); | |
| 23 | } |
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 +49
| @@ -0,0 +1,49 @@ | ||
| 1 | /** | |
| 2 | * A landing on the forge's own default branch deploys the forge. Only a | |
| 3 | * landing: the merge has passed the full gate (`checks/landing.ts`), and | |
| 4 | * what runs is that event's merge commit, not whatever the branch holds when | |
| 5 | * the job starts. A plain push deploys nothing. Off unless `FORGE_SELF_REPO` | |
| 6 | * names the repository (`owner/name`). A failed roll leaves the old forge | |
| 7 | * serving and says so in the log with the new tree's stderr; the page for | |
| 8 | * writers (`/releases`) shows the same. No comment is posted: the forge has | |
| 9 | * no author of its own, and stderr must not appear under a person's name. | |
| 10 | */ | |
| 11 | ||
| 12 | import type { App } from "../app.ts"; | |
| 13 | import { getRepoById } from "../core/repos.ts"; | |
| 14 | import { repoDir } from "../git/repos.ts"; | |
outdated
Unused import: |
||
| 15 | import { deploy } from "./deploy.ts"; | |
| 16 | import { serial } from "./queue.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 | const run = async (repoId: string, sha: string, pull: number) => { | |
| 26 | const repo = getRepoById(app.db, repoId); | |
| 27 | if (repo === undefined || repo.ownerName !== owner || repo.name !== name) return; | |
| 28 | if (readReleases(app.config.dataDir)[0]?.sha === sha) return; | |
| 29 | const bareDir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 30 | const by = `#${pull}`; | |
| 31 | const done = await deploy({ dataDir: app.config.dataDir, bareDir, sha, by }); | |
| 32 | if (done.ok) { | |
| 33 | app.log.info("released", { sha, ms: done.value.ms ?? 0, by }); | |
| 34 | return; | |
| 35 | } | |
| 36 | app.log.error(`RELEASE FAILED, the old forge is still serving: ${sha.slice(0, 7)} ${done.error}`); | |
| 37 | }; | |
| 38 | const off = app.bus.subscribe((event) => { | |
| 39 | if (event.kind !== "pull.merged" || event.repoId === null) return; | |
| 40 | const number = event.payload["number"]; | |
| 41 | const sha = event.payload["mergeOid"]; | |
| 42 | if (typeof number !== "number" || typeof sha !== "string" || !isSha(sha)) return; | |
| 43 | const repoId = event.repoId; | |
outdated
Medium: this posts stderr from a failed boot as a comment written under the merger's name. Post it as the forge, and leave the stderr tail in the log. |
||
| 44 | void serial(() => | |
| 45 | run(repoId, sha, number).catch((error) => app.log.error("release crashed", { error: String(error) })), | |
| 46 | ); | |
| 47 | }); | |
outdated
High: a plain |
||
| 48 | return { stop: off }; | |
| 49 | } |
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/tui/screens/dashboard.ts +8
| @@ -66,7 +66,9 @@ import { | ||
| 66 | 66 | plural, |
| 67 | 67 | } from "./common.ts"; |
| 68 | 68 | import { issueScreen } from "./issue.ts"; |
| 69 | import { mayManageReleases } from "../../release/access.ts"; | |
| 69 | 70 | import { newRepoScreen } from "./newrepo.ts"; |
| 71 | import { releasesScreen } from "./releases.ts"; | |
| 70 | 72 | import { pullScreen } from "./pull.ts"; |
| 71 | 73 | import { repoScreen } from "./repo.ts"; |
| 72 | 74 | import { local } from "./where.ts"; |
| @@ -399,6 +401,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen { | ||
| 399 | 401 | binding(["n"], "new repo", { disabled: !f.signedIn }), |
| 400 | 402 | binding(["A"], "account", { disabled: !f.signedIn }), |
| 401 | 403 | binding(["s"], "sign in", { disabled: f.signedIn }), |
| 404 | binding(["R"], "releases", { disabled: !mayManageReleases(f.app, f.user) }), | |
| 402 | 405 | binding(["r"], "refresh"), |
| 403 | 406 | ]; |
| 404 | 407 | }, |
| @@ -530,6 +533,11 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen { | ||
| 530 | 533 | openOnWeb(f, ctx, "/settings", "Account settings"); |
| 531 | 534 | return true; |
| 532 | 535 | } |
| 536 | if (e.key === "R") { | |
| 537 | const releases = releasesScreen(f, ctx); | |
| 538 | if (releases !== undefined) ctx.push(releases); | |
| 539 | return true; | |
| 540 | } | |
| 533 | 541 | if (e.key === "s" && !f.signedIn) { |
| 534 | 542 | ctx.push(signInScreen(f, ctx, reload)); |
| 535 | 543 | return true; |
src/tui/screens/releases.ts added +100
| @@ -0,0 +1,100 @@ | ||
| 1 | /** | |
| 2 | * `R` — the releases the forge has run, newest first, and a way back. | |
| 3 | * | |
| 4 | * The same list as `/releases` (`release/releases.ts`), for the same people | |
| 5 | * (`release/access.ts`: writers of the forge's own repository and admins). | |
| 6 | * `b` rolls back to the selected retired release, through the one queue the | |
| 7 | * landing and the web button use (`release/queue.ts`), after a confirmation. | |
| 8 | */ | |
| 9 | ||
| 10 | import { mayManageReleases } from "../../release/access.ts"; | |
| 11 | import { queuedRollback } from "../../release/queue.ts"; | |
| 12 | import { liveRelease, readReleases, type Release } from "../../release/releases.ts"; | |
| 13 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 14 | import { binding } from "../app/keys.ts"; | |
| 15 | import type { Session } from "../session.ts"; | |
| 16 | import { card, emptyState, type Tone } from "../ui/widgets.ts"; | |
| 17 | import { ListState, confirmScreen, drawList, metaOf, relTime, runAsync, type ListRow } from "./common.ts"; | |
| 18 | ||
| 19 | const tone = (r: Release): Tone | undefined => | |
| 20 | r.status === "failed" ? "danger" : r.status === "live" ? "success" : undefined; | |
| 21 | ||
| 22 | export function releaseRows(list: readonly Release[]): ListRow[] { | |
| 23 | const live = liveRelease(list); | |
| 24 | return list.map((r) => { | |
| 25 | const t = tone(r); | |
| 26 | return { | |
| 27 | title: `${r.sha.slice(0, 7)} ${r.status.padEnd(8)} ${r.by}${r === live ? " (serving)" : ""}`, | |
| 28 | ...(t === undefined ? {} : { tone: t }), | |
| 29 | ...(r.status === "retired" ? { hollow: true } : {}), | |
| 30 | secondary: r.note, | |
| 31 | meta: metaOf(r.ms === null ? "" : `${r.ms} ms`, relTime(new Date(r.at).toISOString())), | |
| 32 | }; | |
| 33 | }); | |
| 34 | } | |
| 35 | ||
| 36 | /** The screen, or nothing for someone who may not see releases. */ | |
| 37 | export function releasesScreen(f: Session, ctx: Ctx): Screen | undefined { | |
| 38 | if (!mayManageReleases(f.app, f.user)) return undefined; | |
| 39 | let list: Release[] = readReleases(f.app.config.dataDir); | |
| 40 | const state = new ListState(); | |
| 41 | const reload = (): void => { | |
| 42 | list = readReleases(f.app.config.dataDir); | |
| 43 | state.clamp(list.length); | |
| 44 | }; | |
| 45 | const screen: Screen = { | |
| 46 | title: "Releases", | |
| 47 | get keys() { | |
| 48 | return [ | |
| 49 | binding(["j", "k"], "move"), | |
| 50 | binding(["b"], "roll back", { disabled: list[state.index]?.status !== "retired" }), | |
| 51 | binding(["r"], "refresh"), | |
| 52 | binding(["esc"], "close"), | |
| 53 | ]; | |
| 54 | }, | |
| 55 | render(area, s) { | |
| 56 | const inner = card(s, area, ctx.theme.c, { title: "Releases" }); | |
| 57 | if (list.length === 0) | |
| 58 | emptyState(s, inner, ctx.theme.c, { title: "No release yet" }); | |
| 59 | else drawList(s, inner, ctx.theme.c, state, releaseRows(list)); | |
| 60 | }, | |
| 61 | key(e) { | |
| 62 | if (state.key(e, list.length)) return true; | |
| 63 | if (e.key === "esc" || e.key === "q") { | |
| 64 | ctx.pop(); | |
| 65 | return true; | |
| 66 | } | |
| 67 | if (e.key === "r") { | |
| 68 | reload(); | |
| 69 | return true; | |
| 70 | } | |
| 71 | const picked = list[state.index]; | |
| 72 | if (e.key === "b" && picked !== undefined && picked.status === "retired") { | |
| 73 | ctx.push( | |
| 74 | confirmScreen(ctx, screen, { | |
| 75 | title: "Roll back", | |
| 76 | body: [`Serve ${picked.sha.slice(0, 7)} again?`], | |
| 77 | actions: [{ label: "Roll back", variant: "danger" }, { label: "Cancel" }], | |
| 78 | selected: 1, | |
| 79 | onChoose: (i) => { | |
| 80 | if (i !== 0) return; | |
| 81 | runAsync(ctx, async () => { | |
| 82 | const done = await queuedRollback({ | |
| 83 | dataDir: f.app.config.dataDir, | |
| 84 | sha: picked.sha, | |
| 85 | by: `rollback by @${f.user?.username ?? "unknown"}`, | |
| 86 | }); | |
| 87 | reload(); | |
| 88 | if (done.ok) ctx.toast(`rolled back to ${picked.sha.slice(0, 7)}`, "success"); | |
| 89 | else ctx.toast(`rollback failed, nothing changed: ${done.error}`, "danger"); | |
| 90 | }); | |
| 91 | }, | |
| 92 | }), | |
| 93 | ); | |
| 94 | return true; | |
| 95 | } | |
| 96 | return false; | |
| 97 | }, | |
| 98 | }; | |
| 99 | return screen; | |
| 100 | } |
src/web/pages/releases.ts added +78
| @@ -0,0 +1,78 @@ | ||
| 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 { mayManageReleases } from "../../release/access.ts"; | |
| 10 | import { queuedRollback } from "../../release/queue.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 iso = (ms: number): string => new Date(ms).toISOString(); | |
| 19 | ||
| 20 | /** "live: a1b2c3d since <time>" for the home page; nothing before a first release. */ | |
| 21 | export function liveLine(ctx: Ctx): Html | undefined { | |
| 22 | const live = liveRelease(readReleases(ctx.app.config.dataDir)); | |
| 23 | if (live === undefined) return undefined; | |
| 24 | return html`<p class="small muted" id="forge-live"> | |
| 25 | ${mayManageReleases(ctx.app, ctx.auth.user) | |
| 26 | ? html`<a href="/releases">live: ${live.sha.slice(0, 7)}</a>` | |
| 27 | : html`live: ${live.sha.slice(0, 7)}`} since | |
| 28 | ${time(iso(live.healthySince ?? live.at))} | |
| 29 | </p>`; | |
| 30 | } | |
| 31 | ||
| 32 | /** GET /releases */ | |
| 33 | export function releasesPage(ctx: Ctx): Response { | |
| 34 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 35 | if (!mayManageReleases(ctx.app, ctx.auth.user)) return new Response("not found", { status: 404 }); | |
No test fails if this check is removed. Add a route test: a signed-in outsider gets 404 here, and a non-admin writer of the self repo gets 200. |
||
| 36 | const list = readReleases(ctx.app.config.dataDir); | |
| 37 | const row = (r: Release): Html => html`<tr> | |
outdated
Medium: every signed-in user can read this, including the stderr notes of failed releases. Gate it with the same writer/admin check the rollback uses. |
||
| 38 | <td><code>${r.sha.slice(0, 7)}</code></td> | |
| 39 | <td>${time(iso(r.at))}</td> | |
| 40 | <td>${r.by}</td> | |
| 41 | <td>${r.status}${when(r.note || undefined, (n) => html` — ${n}`)}</td> | |
| 42 | <td>${r.healthySince === null ? "never" : time(iso(r.healthySince))}</td> | |
| 43 | <td>${r.ms === null ? "" : `${r.ms} ms`}</td> | |
| 44 | <td>${when( | |
| 45 | r.status === "retired" ? r : undefined, | |
| 46 | (x) => html`<form method="post" action="/releases/rollback"> | |
| 47 | <input type="hidden" name="sha" value="${x.sha}" /> | |
| 48 | ${btn("Roll back to this", { type: "submit" })} | |
| 49 | </form>`, | |
| 50 | )}</td> | |
| 51 | </tr>`; | |
| 52 | return page({ | |
| 53 | ctx, | |
| 54 | title: "Releases", | |
| 55 | body: html`<div class="page-head"><h1>Releases</h1></div> | |
| 56 | ${list.length === 0 | |
| 57 | ? empty({ title: "No release yet", note: "A landing on the forge's own default branch makes the first." }) | |
| 58 | : card(html`<table> | |
| 59 | <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> | |
| 60 | <tbody>${list.map(row)}</tbody> | |
| 61 | </table>`)}`, | |
| 62 | }); | |
| 63 | } | |
| 64 | ||
| 65 | /** POST /releases/rollback — swap back to a retired release; a writer's. */ | |
| 66 | export async function releasesRollback(ctx: Ctx): Promise<Response> { | |
| 67 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 68 | const form = await readForm(ctx, "rw"); | |
| 69 | if (form instanceof Response) return form; | |
| 70 | if (!mayManageReleases(ctx.app, ctx.auth.user)) | |
Same for the rollback: an outsider's POST should get 404 and leave |
||
| 71 | return new Response("not found", { status: 404 }); | |
| 72 | const sha = String(form.get("sha") ?? ""); | |
| 73 | if (!isSha(sha)) return flashTo(ctx, "/releases", { tone: "danger", message: "Not a release." }); | |
| 74 | const done = await queuedRollback({ dataDir: ctx.app.config.dataDir, sha, by: `rollback by @${ctx.auth.user.username}` }); | |
outdated
Record who rolled back ( |
||
| 75 | return flashTo(ctx, "/releases", done.ok | |
| 76 | ? { message: `Rolled back to ${sha.slice(0, 7)} in ${done.value.ms} ms.` } | |
| 77 | : { tone: "danger", message: `Rollback failed, the running release is untouched: ${done.error}` }); | |
| 78 | } |
src/web/studio/home.ts +3 −1
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | * best of what is public (`actions/front.ts`). |
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | import { liveLine } from "../pages/releases.ts"; | |
| 9 | 10 | import { |
| 10 | 11 | frontPage, |
| 11 | 12 | frontPicksJson, |
| @@ -176,6 +177,7 @@ export async function studioHome( | ||
| 176 | 177 | const { repos: appRepos } = writableAppsOf(ctx, user); |
| 177 | 178 | // A spawned forge says where it lives: the address its person shares. |
| 178 | 179 | const spawned = await spawnedOrg(ctx.app); |
| 180 | const live = liveLine(ctx); | |
| 179 | 181 | const address = when( |
| 180 | 182 | spawned?.url, |
| 181 | 183 | (url) => |
| @@ -187,7 +189,7 @@ export async function studioHome( | ||
| 187 | 189 | // everyday account themselves (#600); anywhere else, #803's card asks. |
| 188 | 190 | const firstSteps = await nextStepsCard(ctx, user); |
| 189 | 191 | const body = html`<h1 class="sr-only">Home</h1> |
| 190 | ${firstSteps ?? everydayCard(ctx, user)} ${address} | |
| 192 | ${firstSteps ?? everydayCard(ctx, user)} ${address} ${live} | |
| 191 | 193 | ${homeTabs("feed")} |
| 192 | 194 | <div class="dash"> |
| 193 | 195 | <div class="dash-main stack"> |
test/release-gate.test.ts added +84
| @@ -0,0 +1,84 @@ | ||
| 1 | /** | |
| 2 | * Only a landing deploys, and what it deploys is the landed commit; one | |
| 3 | * queue orders every swap; only writers of the self repo (and admins) may | |
| 4 | * see or steer releases. | |
| 5 | */ | |
| 6 | ||
| 7 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 8 | import { mkdtempSync, rmSync } from "node:fs"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { createRepo } from "../src/actions/repos.ts"; | |
| 13 | import { signUp } from "../src/actions/users.ts"; | |
| 14 | import { mayManageReleases } from "../src/release/access.ts"; | |
| 15 | import { serial } from "../src/release/queue.ts"; | |
| 16 | import { readReleases } from "../src/release/releases.ts"; | |
| 17 | import { startReleases } from "../src/release/service.ts"; | |
| 18 | ||
| 19 | let dir = ""; | |
| 20 | let app: App; | |
| 21 | let repoId = ""; | |
| 22 | let stop: () => void = () => {}; | |
| 23 | const SHA = "a".repeat(40); | |
| 24 | ||
| 25 | const settle = () => Bun.sleep(300); | |
| 26 | ||
| 27 | beforeAll(async () => { | |
| 28 | dir = mkdtempSync(join(process.env["TMPDIR"] ?? tmpdir(), "release-gate-")); | |
| 29 | app = createApp({ dataDir: dir, port: 0, url: "https://forge.example", edgeToken: "e" }); | |
| 30 | const owner = await signUp(app, { username: "olive", email: "[email protected]", password: "owner-passphrase" }); | |
| 31 | if (!owner.ok) throw new Error(owner.error); | |
| 32 | const made = await createRepo(app, owner.value, { name: "forge" }); | |
| 33 | if (!made.ok) throw new Error(made.error); | |
| 34 | repoId = made.value.id; | |
| 35 | process.env["FORGE_SELF_REPO"] = "olive/forge"; | |
| 36 | stop = startReleases(app, "olive/forge").stop; | |
| 37 | }); | |
| 38 | ||
| 39 | afterAll(() => { | |
| 40 | stop(); | |
| 41 | delete process.env["FORGE_SELF_REPO"]; | |
| 42 | rmSync(dir, { recursive: true, force: true }); | |
| 43 | }); | |
| 44 | ||
| 45 | test("a plain push to the default branch deploys nothing; a landing deploys its merge commit", async () => { | |
| 46 | app.bus.append({ kind: "push", repoId, payload: { ref: "refs/heads/main", newOid: SHA } }); | |
| 47 | await settle(); | |
| 48 | expect(readReleases(dir)).toEqual([]); | |
| 49 | ||
| 50 | app.bus.append({ kind: "pull.merged", repoId, payload: { number: 7, strategy: "squash", mergeOid: SHA } }); | |
| 51 | await settle(); | |
| 52 | const [first] = readReleases(dir); | |
| 53 | expect(first?.sha).toBe(SHA); | |
| 54 | expect(first?.by).toBe("#7"); | |
| 55 | ||
| 56 | app.bus.append({ kind: "pull.merged", repoId, payload: { number: 8, strategy: "squash", mergeOid: "not a sha" } }); | |
| 57 | await settle(); | |
| 58 | expect(readReleases(dir).length).toBe(1); | |
| 59 | }); | |
| 60 | ||
| 61 | test("a second swap waits for the first", async () => { | |
| 62 | const order: string[] = []; | |
| 63 | const a = serial(async () => { | |
| 64 | order.push("a:start"); | |
| 65 | await Bun.sleep(100); | |
| 66 | order.push("a:end"); | |
| 67 | }); | |
| 68 | const b = serial(async () => { | |
| 69 | order.push("b:start"); | |
| 70 | }); | |
| 71 | await Promise.all([a, b]); | |
| 72 | expect(order).toEqual(["a:start", "a:end", "b:start"]); | |
| 73 | await expect(serial(() => Promise.reject(new Error("x")))).rejects.toThrow(); | |
| 74 | expect(await serial(async () => 1)).toBe(1); | |
| 75 | }); | |
| 76 | ||
| 77 | test("releases are for writers of the self repo and admins", async () => { | |
| 78 | const olive = (await import("../src/core/users.ts")).getUserByName(app.db, "olive")!; | |
| 79 | const eve = await signUp(app, { username: "eve", email: "[email protected]", password: "outsider-passphrase" }); | |
| 80 | if (!eve.ok) throw new Error(eve.error); | |
| 81 | expect(mayManageReleases(app, olive)).toBe(true); | |
olive is the first signup and therefore an admin, so this assertion never reaches the |
||
| 82 | expect(mayManageReleases(app, eve.value)).toBe(eve.value.isAdmin); | |
| 83 | expect(mayManageReleases(app, undefined)).toBe(false); | |
| 84 | }); |
test/release-handoff.test.ts added +34
| @@ -0,0 +1,34 @@ | ||
| 1 | /** | |
| 2 | * The real `serve()` twice on one port (`reusePort`), as a swap does it: the | |
| 3 | * old side lets go of its listener and every new connection is the new side's. | |
| 4 | */ | |
| 5 | ||
| 6 | import { expect, test } from "bun:test"; | |
| 7 | import { mkdtempSync, rmSync } from "node:fs"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp } from "../src/app.ts"; | |
| 11 | import { serve } from "../src/http/server.ts"; | |
| 12 | ||
| 13 | test("two real servers share a port; after closeListener only the new one answers", async () => { | |
| 14 | const root = mkdtempSync(join(process.env["TMPDIR"] ?? tmpdir(), "release-handoff-")); | |
| 15 | const oldApp = createApp({ dataDir: join(root, "old"), port: 0, reusePort: true }); | |
| 16 | const oldSide = await serve(oldApp); | |
| 17 | const newApp = createApp({ dataDir: join(root, "new"), port: oldSide.port, reusePort: true }); | |
| 18 | const newSide = await serve(newApp); | |
| 19 | try { | |
| 20 | expect(newSide.port).toBe(oldSide.port); | |
| 21 | expect((await fetch(`${newSide.url}/`, { redirect: "manual" })).status).toBeLessThan(500); | |
| 22 | oldSide.closeListener(); | |
| 23 | for (let i = 0; i < 10; i++) { | |
| 24 | const res = await fetch(`${newSide.url}/`, { redirect: "manual", headers: { connection: "close" } }); | |
| 25 | expect(res.status).toBeLessThan(500); | |
| 26 | } | |
| 27 | } finally { | |
| 28 | oldSide.stop(); | |
| 29 | newSide.stop(); | |
| 30 | oldApp.close(); | |
| 31 | newApp.close(); | |
| 32 | rmSync(root, { recursive: true, force: true }); | |
| 33 | } | |
| 34 | }); |
test/release-hold.test.ts added +32
| @@ -0,0 +1,32 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync, writeFileSync } from "node:fs"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { predecessor, untilGone } from "../src/release/hold.ts"; | |
| 6 | ||
| 7 | const dir = () => mkdtempSync(join(tmpdir(), "hold-")); | |
| 8 | ||
| 9 | test("loops start only after the old pid is gone", async () => { | |
| 10 | const events: string[] = []; | |
| 11 | let checks = 0; | |
| 12 | const alive = () => ++checks < 4; | |
| 13 | await untilGone(4242, alive, async () => void events.push("wait")); | |
| 14 | events.push("loops start"); | |
| 15 | expect(events).toEqual(["wait", "wait", "wait", "loops start"]); | |
| 16 | }); | |
| 17 | ||
| 18 | test("no predecessor, no wait", async () => { | |
| 19 | let slept = 0; | |
| 20 | await untilGone(undefined, () => true, async () => void slept++); | |
| 21 | expect(slept).toBe(0); | |
| 22 | }); | |
| 23 | ||
| 24 | test("a predecessor is a different live pid, and only in a handoff", () => { | |
| 25 | const d = dir(); | |
| 26 | writeFileSync(join(d, "forge.pid"), "4242"); | |
| 27 | const yes = () => true; | |
| 28 | expect(predecessor(d, { FORGE_HANDOFF: "1" }, 1, yes)).toBe(4242); | |
| 29 | expect(predecessor(d, {}, 1, yes)).toBeUndefined(); | |
| 30 | expect(predecessor(d, { FORGE_HANDOFF: "1" }, 4242, yes)).toBeUndefined(); | |
| 31 | expect(predecessor(d, { FORGE_HANDOFF: "1" }, 1, () => false)).toBeUndefined(); | |
| 32 | }); |
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-routes.test.ts added +144
| @@ -0,0 +1,144 @@ | ||
| 1 | /** | |
| 2 | * The doors to releases — the page, the rollback form, the home line and the | |
| 3 | * terminal screen — open for writers of the forge's own repository and admins | |
| 4 | * and for nobody else. Each refusal here fails if its check is removed. | |
| 5 | */ | |
| 6 | ||
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtempSync, readFileSync, rmSync } from "node:fs"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { addTeamMember, createOrg, createTeam } from "../src/actions/orgs.ts"; | |
| 13 | import { createRepo } from "../src/actions/repos.ts"; | |
| 14 | import { createSession } from "../src/core/sessions.ts"; | |
| 15 | import { createUser, type User } from "../src/core/users.ts"; | |
| 16 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 17 | import { listFile, recordRelease } from "../src/release/releases.ts"; | |
| 18 | import { Session } from "../src/tui/session.ts"; | |
| 19 | import { dashboardScreen } from "../src/tui/screens/dashboard.ts"; | |
| 20 | import { releasesScreen } from "../src/tui/screens/releases.ts"; | |
| 21 | import type { Ctx } from "../src/tui/app/app.ts"; | |
| 22 | ||
| 23 | const OLD = "b".repeat(40); | |
| 24 | const NEW = "c".repeat(40); | |
| 25 | ||
| 26 | describe("releases doors", () => { | |
| 27 | let dir = ""; | |
| 28 | let app: App; | |
| 29 | let servers: Servers; | |
| 30 | const users: Record<string, User> = {}; | |
| 31 | const cookies: Record<string, string> = {}; | |
| 32 | ||
| 33 | const send = (path: string, who?: string, init: RequestInit = {}) => | |
| 34 | fetch(`${servers.url}${path}`, { | |
| 35 | redirect: "manual", | |
| 36 | ...init, | |
| 37 | headers: { | |
| 38 | cookie: `${who ? `${cookies[who]}; ` : ""}forge_mode=studio`, | |
| 39 | ...((init.headers as Record<string, string> | undefined) ?? {}), | |
| 40 | }, | |
| 41 | }); | |
| 42 | const rollback = (who: string, origin?: string) => | |
| 43 | send("/releases/rollback", who, { | |
| 44 | method: "POST", | |
| 45 | headers: { | |
| 46 | "content-type": "application/x-www-form-urlencoded", | |
| 47 | ...(origin ? { origin } : {}), | |
| 48 | }, | |
| 49 | body: `sha=${OLD}`, | |
| 50 | }); | |
| 51 | const session = (who?: string) => | |
| 52 | new Session(app, { | |
| 53 | sshUsername: who ?? "guest", | |
| 54 | remoteAddress: "127.0.0.1", | |
| 55 | user: who ? users[who] : undefined, | |
| 56 | }); | |
| 57 | const ctx = {} as Ctx; | |
| 58 | ||
| 59 | beforeAll(async () => { | |
| 60 | dir = mkdtempSync(join(process.env["TMPDIR"] ?? tmpdir(), "release-routes-")); | |
| 61 | app = createApp({ dataDir: dir, port: 0 }); | |
| 62 | servers = await serve(app); | |
| 63 | for (const [i, name] of ["olive", "wren", "rae", "eve"].entries()) { | |
| 64 | const made = await createUser(app.db, { | |
| 65 | trusted: true, | |
| 66 | username: name, | |
| 67 | email: `${name}@forge.local`, | |
| 68 | password: "a-good-passphrase", | |
| 69 | adminIfFirst: i === 0, | |
| 70 | }); | |
| 71 | if (!made.ok) throw new Error(made.error); | |
| 72 | users[name] = made.value; | |
| 73 | cookies[name] = `forge_session=${createSession(app.db, made.value.id).token}`; | |
| 74 | } | |
| 75 | const org = createOrg(app, users["olive"]!, "guild"); | |
| 76 | if (!org.ok) throw new Error(String(org.error)); | |
| 77 | for (const [name, member, perm] of [["makers", "wren", "write"], ["readers", "rae", "read"]] as const) { | |
| 78 | const team = createTeam(app, users["olive"]!, org.value, name, perm); | |
| 79 | if (!team.ok) throw new Error(String(team.error)); | |
| 80 | if (!addTeamMember(app, users["olive"]!, org.value, team.value, member).ok) throw new Error(member); | |
| 81 | } | |
| 82 | const repo = await createRepo(app, users["olive"]!, { name: "forge", owner: "guild" }); | |
| 83 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 84 | process.env["FORGE_SELF_REPO"] = "guild/forge"; | |
| 85 | const at = Date.now(); | |
| 86 | recordRelease(dir, { sha: OLD, at, by: "#1", status: "retired", healthySince: at, ms: 10, note: "" }); | |
| 87 | recordRelease(dir, { sha: NEW, at: at + 1, by: "#2", status: "live", healthySince: at + 1, ms: 10, note: "" }); | |
| 88 | }); | |
| 89 | ||
| 90 | afterAll(() => { | |
| 91 | servers.stop(); | |
| 92 | delete process.env["FORGE_SELF_REPO"]; | |
| 93 | rmSync(dir, { recursive: true, force: true }); | |
| 94 | }); | |
| 95 | ||
| 96 | test("signed out, /releases sends you to sign in", async () => { | |
| 97 | const res = await send("/releases"); | |
| 98 | expect(res.status).toBeGreaterThanOrEqual(300); | |
| 99 | expect(res.status).toBeLessThan(400); | |
| 100 | expect(res.headers.get("location") ?? "").toContain("/signin"); | |
| 101 | }); | |
| 102 | ||
| 103 | test("an outsider and a reader get 404; a writer sees the rollback button", async () => { | |
| 104 | expect((await send("/releases", "eve")).status).toBe(404); | |
| 105 | expect((await send("/releases", "rae")).status).toBe(404); | |
| 106 | const res = await send("/releases", "wren"); | |
| 107 | expect(res.status).toBe(200); | |
| 108 | expect(await res.text()).toContain("Roll back to this"); | |
| 109 | }); | |
| 110 | ||
| 111 | test("an outsider's or reader's rollback is 404 and changes nothing", async () => { | |
| 112 | const before = readFileSync(listFile(dir), "utf8"); | |
| 113 | expect((await rollback("eve")).status).toBe(404); | |
| 114 | expect((await rollback("rae")).status).toBe(404); | |
| 115 | expect(readFileSync(listFile(dir), "utf8")).toBe(before); | |
| 116 | }); | |
| 117 | ||
| 118 | test("a writer's cross-origin rollback is 403 and changes nothing", async () => { | |
| 119 | const before = readFileSync(listFile(dir), "utf8"); | |
| 120 | expect((await rollback("wren", "https://evil.example")).status).toBe(403); | |
| 121 | expect(readFileSync(listFile(dir), "utf8")).toBe(before); | |
| 122 | }); | |
| 123 | ||
| 124 | test("the home line is a link for a writer and plain text for a guest", async () => { | |
| 125 | const writer = await (await send("/", "wren")).text(); | |
| 126 | expect(writer).toContain(`<a href="/releases">live: ${NEW.slice(0, 7)}</a>`); | |
| 127 | const guest = await (await send("/", "eve")).text(); | |
| 128 | expect(guest).toContain(`live: ${NEW.slice(0, 7)}`); | |
| 129 | expect(guest).not.toContain(`href="/releases"`); | |
| 130 | }); | |
| 131 | ||
| 132 | test("the terminal screen exists for a writer only, and its key is disabled for the rest", () => { | |
| 133 | expect(releasesScreen(session("wren"), ctx)).toBeDefined(); | |
| 134 | expect(releasesScreen(session("olive"), ctx)).toBeDefined(); | |
| 135 | expect(releasesScreen(session("eve"), ctx)).toBeUndefined(); | |
| 136 | expect(releasesScreen(session("rae"), ctx)).toBeUndefined(); | |
| 137 | expect(releasesScreen(session(), ctx)).toBeUndefined(); | |
| 138 | const disabled = (who?: string) => | |
| 139 | dashboardScreen(session(who), ctx).keys.find((k) => k.keys.includes("R"))?.disabled; | |
| 140 | expect(disabled("wren")).toBe(false); | |
| 141 | expect(disabled("eve")).toBe(true); | |
| 142 | expect(disabled()).toBe(true); | |
| 143 | }); | |
| 144 | }); |
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); |
This is the known limit that blocks the pull. Fix it here rather than document it: nothing should be able to run twice on a landing.