Public: anyone can read this; the crew can change it.
Self-deploy, step 4: rollback to a kept release, from `--rollback <sha>` and a writer's button on a releases page that lists sha, landing and healthy-since #1759
scout/forge:scout/1664-self-deploy-step-4-rollback-to-a-kept-re → main 2 commits fork
36 files
changed +609
−9
.bash_profile added
No content changes.
.bashrc added
No content changes.
.claude/agents added
No content changes.
.claude/commands added
No content changes.
.claude/hooks added
No content changes.
.claude/launch.json added
No content changes.
.claude/loop.md added
No content changes.
.claude/output-styles added
No content changes.
.claude/routines added
No content changes.
.claude/scheduled_tasks.json added
No content changes.
.claude/settings.json added
No content changes.
.claude/settings.local.json added
No content changes.
.claude/skills added
No content changes.
.claude/workflows added
No content changes.
.gitconfig added
No content changes.
.gitmodules added
No content changes.
.idea added
No content changes.
.mcp.json added
No content changes.
.profile added
No content changes.
.ripgreprc added
No content changes.
.vscode added
No content changes.
.zprofile added
No content changes.
.zshrc added
No content changes.
README.md +2
Diff not shown — a line 2,153 characters wide (limit 2,000). +2
View filescripts/gate.ts +1
| @@ -71,6 +71,7 @@ export const GATE: readonly string[] = [ | ||
| 71 | 71 | "test/recovery-doc.test.ts", |
| 72 | 72 | "test/release-checkout.test.ts", |
| 73 | 73 | "test/release-preflight.test.ts", |
| 74 | "test/release-rollback.test.ts", | |
| 74 | 75 | "test/release-swap.test.ts", |
| 75 | 76 | "test/threats-doc.test.ts", |
| 76 | 77 | "test/returns.test.ts", |
src/core/reserved.ts +1
| @@ -60,6 +60,7 @@ export const SYSTEM_NAMES: readonly string[] = [ | ||
| 60 | 60 | "asks", |
| 61 | 61 | "assets", |
| 62 | 62 | "audit", |
| 63 | "releases", | |
| 63 | 64 | "audit.csv", |
| 64 | 65 | "big", |
| 65 | 66 | "board", |
src/core/schema.ts +11
| @@ -1741,6 +1741,17 @@ export const migrations: readonly string[] = [ | ||
| 1741 | 1741 | ALTER TABLE repo ADD COLUMN decisions_by TEXT NOT NULL DEFAULT 'me' |
| 1742 | 1742 | CHECK (decisions_by IN ('me', 'decider', 'decider_tell')); |
| 1743 | 1743 | `, |
| 1744 | // 86 — what is live (#1664): one row each time a process comes up as a | |
| 1745 | // release commit, so the releases page can say "healthy since". | |
| 1746 | ` | |
| 1747 | CREATE TABLE release_live ( | |
| 1748 | id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| 1749 | sha TEXT NOT NULL, | |
| 1750 | since TEXT NOT NULL | |
| 1751 | ); | |
| 1752 | CREATE INDEX release_live_sha ON release_live(sha, id); | |
| 1753 | ||
| 1754 | `, | |
| 1744 | 1755 | ]; |
| 1745 | 1756 | |
| 1746 | 1757 | /** |
src/http/server.ts +3
| @@ -103,6 +103,7 @@ import { confirmPage, searchPage } from "../web/pages/search.ts"; | ||
| 103 | 103 | import { followingSubmit } from "../web/pages/following.ts"; |
| 104 | 104 | import { reconnectSubmit } from "../web/pages/frozen.ts"; |
| 105 | 105 | import { activityAtom } from "../web/feeds.ts"; |
| 106 | import { releasesPage, releasesRollback } from "../web/pages/releases.ts"; | |
| 106 | 107 | import { auditCsv, auditPage, auditProbeSubmit } from "../web/pages/audit.ts"; |
| 107 | 108 | import { secretDelete, secretSet, secretsPage } from "../web/pages/secrets.ts"; |
| 108 | 109 | import { |
| @@ -611,6 +612,8 @@ export function buildRouter(): Router<Handler> { | ||
| 611 | 612 | // is registered before /:owner/:name can claim the shape. |
| 612 | 613 | router.add("GET", "/-/confirm", confirmPage); |
| 613 | 614 | router.add("GET", "/new", newRepoPage); |
| 615 | router.add("GET", "/releases", releasesPage); | |
| 616 | router.add("POST", "/releases/rollback", releasesRollback); | |
| 614 | 617 | router.add("GET", "/audit", auditPage); |
| 615 | 618 | router.add("GET", "/audit.csv", auditCsv); |
| 616 | 619 | router.add("POST", "/audit/:owner/:name/probe", auditProbeSubmit); |
src/kernel/migrate.ts +6 −7
| @@ -21,7 +21,8 @@ | ||
| 21 | 21 | * |
| 22 | 22 | * `user_version` is still written — the count of applied migrations — so a |
| 23 | 23 | * build from before this table refuses a database that is ahead of it the |
| 24 | * way it always did. | |
| 24 | * way it always did. A build with the table does not: it serves on a newer | |
| 25 | * schema, since migrations only add, which is how a rollback boots. | |
| 25 | 26 | */ |
| 26 | 27 | |
| 27 | 28 | import type { Database } from "bun:sqlite"; |
| @@ -56,12 +57,10 @@ export function migrate(db: Database, migrations: readonly string[]): void { | ||
| 56 | 57 | }); |
| 57 | 58 | |
| 58 | 59 | const applied = appliedIds(db, migrations, ids); |
| 59 | if (applied.size > migrations.length) { | |
| 60 | defect( | |
| 61 | "db.future_schema", | |
| 62 | `database has applied ${applied.size} migrations, this build only knows ${migrations.length} — refusing to run`, | |
| 63 | ); | |
| 64 | } | |
| 60 | // A database ahead of this build was migrated by a newer one. Every | |
| 61 | // migration is additive (`notAdditive`), so this build serves on it as it | |
| 62 | // serves beside a newer process: that is what lets a rollback boot an older | |
| 63 | // release (#1664). The newer build's rows are left alone. | |
| 65 | 64 | for (let i = 0; i < migrations.length; i++) { |
| 66 | 65 | const id = ids[i]!; |
| 67 | 66 | if (applied.has(id)) continue; |
src/main.ts +32
| @@ -6,6 +6,8 @@ | ||
| 6 | 6 | |
| 7 | 7 | import { sweepStanding } from "./crew/standing.ts"; |
| 8 | 8 | import { handover } from "./release/swap.ts"; |
| 9 | import { rollback } from "./release/rollback.ts"; | |
| 10 | import { readPid, recordLive, writePid } from "./release/live.ts"; | |
| 9 | 11 | import { parentUrlProblem } from "./core/parent_releases.ts"; |
| 10 | 12 | import { releaseEnv } from "./release/env.ts"; |
| 11 | 13 | import { createApp } from "./app.ts"; |
| @@ -100,6 +102,34 @@ if (problem !== null) { | ||
| 100 | 102 | process.exit(1); |
| 101 | 103 | } |
| 102 | 104 | |
| 105 | // `--rollback <sha>` swaps the serving forge to a kept `releases/<sha>/` | |
| 106 | // through the same hand-over as a landing, then exits (#1664). The serving | |
| 107 | // process is the one named in the data directory's forge.pid. | |
| 108 | const rollbackAt = process.argv.indexOf("--rollback"); | |
| 109 | if (rollbackAt !== -1) { | |
| 110 | const serving = readPid(dataDir); | |
| 111 | const port = Number(process.env.PORT ?? 3000); | |
| 112 | const budget = releaseEnv(process.env).swapBudgetMs; | |
| 113 | handover.ssh = hosted | |
| 114 | ? Number(process.env.FORGE_SSH_PORT ?? 0) > 0 | |
| 115 | : Number(process.env.FORGE_SSH_PORT ?? 2222) > 0; | |
| 116 | const done = await rollback({ | |
| 117 | dataDir, | |
| 118 | sha: process.argv[rollbackAt + 1] ?? "", | |
| 119 | live: null, | |
| 120 | port, | |
| 121 | env: process.env, | |
| 122 | ...(budget === undefined ? {} : { budgetMs: budget }), | |
| 123 | drain: () => { | |
| 124 | if (serving !== undefined) process.kill(serving, "SIGTERM"); | |
| 125 | }, | |
| 126 | }); | |
| 127 | // CLI answer on the stream a person or a script reads. | |
| 128 | if (done.ok) console.log(`rolled back to ${done.sha}`); | |
| 129 | else console.error(`rollback refused: ${done.line}`); | |
| 130 | process.exit(done.ok ? 0 : 1); | |
| 131 | } | |
| 132 | ||
| 103 | 133 | // FORGE_DRAIN_LINGER_S: seconds a SIGTERM'd forge keeps answering while |
| 104 | 134 | // routers learn it is going (`http/health.ts`). |
| 105 | 135 | const lingerMs = drainLingerMs(process.env.FORGE_DRAIN_LINGER_S); |
| @@ -443,6 +473,8 @@ const leaseTimer = setInterval(() => { | ||
| 443 | 473 | |
| 444 | 474 | // A release that read healthy beside this process takes over (#1663). |
| 445 | 475 | handover.drain = () => shutdown("SIGTERM"); |
| 476 | recordLive(app.db, running().commit); | |
| 477 | writePid(dataDir, process.pid); | |
| 446 | 478 | handover.ssh = ssh !== undefined; |
| 447 | 479 | process.on("SIGINT", shutdown); |
| 448 | 480 | process.on("SIGTERM", shutdown); |
src/release/live.ts added +45
| @@ -0,0 +1,45 @@ | ||
| 1 | /** | |
| 2 | * Which release is live, and since when (#1664). A process that comes up as a | |
| 3 | * release commit writes a row; "healthy since" is the first row of that commit | |
| 4 | * after the last row of any other, so a restart of the same release does not | |
| 5 | * move it. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; | |
| 10 | import { join } from "node:path"; | |
| 11 | ||
| 12 | /** Note that this process is up as `sha`; a second call for the same commit is a no-op. */ | |
| 13 | export function recordLive(db: Database, sha: string | null): void { | |
| 14 | if (sha === null) return; | |
| 15 | const last = db | |
| 16 | .query<{ sha: string }, []>(`SELECT sha FROM release_live ORDER BY id DESC LIMIT 1`) | |
| 17 | .get(); | |
| 18 | if (last?.sha === sha) return; | |
| 19 | db.query( | |
| 20 | `INSERT INTO release_live (sha, since) VALUES (?1, strftime('%Y-%m-%dT%H:%M:%fZ','now'))`, | |
| 21 | ).run(sha); | |
| 22 | } | |
| 23 | ||
| 24 | /** When `sha` last became the live release, or undefined if it never did. */ | |
| 25 | export function healthySince(db: Database, sha: string): string | undefined { | |
| 26 | return db | |
| 27 | .query<{ since: string }, [string]>( | |
| 28 | `SELECT since FROM release_live WHERE sha = ?1 ORDER BY id DESC LIMIT 1`, | |
| 29 | ) | |
| 30 | .get(sha)?.since; | |
| 31 | } | |
| 32 | ||
| 33 | const pidFile = (dataDir: string): string => join(dataDir, "forge.pid"); | |
| 34 | ||
| 35 | /** Say which process serves, so `--rollback` can drain it once the other is well. */ | |
| 36 | export function writePid(dataDir: string, pid: number): void { | |
| 37 | mkdirSync(dataDir, { recursive: true }); | |
| 38 | writeFileSync(pidFile(dataDir), `${pid}\n`); | |
| 39 | } | |
| 40 | ||
| 41 | export function readPid(dataDir: string): number | undefined { | |
| 42 | if (!existsSync(pidFile(dataDir))) return undefined; | |
| 43 | const pid = Number(readFileSync(pidFile(dataDir), "utf8").trim()); | |
| 44 | return Number.isInteger(pid) && pid > 1 ? pid : undefined; | |
| 45 | } |
src/release/rollback.ts added +72
| @@ -0,0 +1,72 @@ | ||
| 1 | /** | |
| 2 | * Roll back to a kept release (#1664): the same swap as a landing (step 3), | |
| 3 | * aimed at a `releases/<sha>/` that is already on disk. Nothing is fetched or | |
| 4 | * built; a sha that was pruned, or never cut, is refused in one line. | |
| 5 | */ | |
| 6 | ||
| 7 | import { existsSync, readdirSync, utimesSync } from "node:fs"; | |
| 8 | import { releaseDir, releasesRoot } from "./checkout.ts"; | |
| 9 | import { beginSwap, endSwap, startRelease } from "./swap.ts"; | |
| 10 | ||
| 11 | export type RolledBack = { ok: true; sha: string; pid: number } | { ok: false; line: string }; | |
| 12 | ||
| 13 | /** The releases still on disk, by full sha. */ | |
| 14 | export function keptShas(dataDir: string): string[] { | |
| 15 | const root = releasesRoot(dataDir); | |
| 16 | if (!existsSync(root)) return []; | |
| 17 | return readdirSync(root).filter((name) => /^[0-9a-f]{40}$/.test(name)); | |
| 18 | } | |
| 19 | ||
| 20 | /** A full sha or a unique prefix (7 or more) of a kept one. */ | |
| 21 | export function resolveKept( | |
| 22 | dataDir: string, | |
| 23 | input: string, | |
| 24 | ): { ok: true; sha: string } | { ok: false; line: string } { | |
| 25 | const want = input.trim().toLowerCase(); | |
| 26 | const kept = /^[0-9a-f]{7,40}$/.test(want) ? keptShas(dataDir).filter((s) => s.startsWith(want)) : []; | |
| 27 | if (kept.length === 1) return { ok: true, sha: kept[0]! }; | |
| 28 | const shown = /^[0-9a-f]{1,40}$/.test(want) ? want : "that"; | |
| 29 | return { | |
| 30 | ok: false, | |
| 31 | line: | |
| 32 | kept.length > 1 | |
| 33 | ? `${shown} names more than one kept release; give more of the sha` | |
| 34 | : `no kept release ${shown}`, | |
| 35 | }; | |
| 36 | } | |
| 37 | ||
| 38 | export interface RollbackInput { | |
| 39 | dataDir: string; | |
| 40 | /** What the person typed or the form sent. */ | |
| 41 | sha: string; | |
| 42 | /** The commit serving now, if known. */ | |
| 43 | live: string | null; | |
| 44 | port: number; | |
| 45 | env: Record<string, string | undefined>; | |
| 46 | budgetMs?: number; | |
| 47 | /** What retires the serving process once the other reads healthy. */ | |
| 48 | drain: () => void; | |
| 49 | } | |
| 50 | ||
| 51 | export async function rollback(input: RollbackInput): Promise<RolledBack> { | |
| 52 | const found = resolveKept(input.dataDir, input.sha); | |
| 53 | if (!found.ok) return found; | |
| 54 | if (input.live === found.sha) return { ok: false, line: `${found.sha.slice(0, 12)} is already live` }; | |
| 55 | const turn = beginSwap(); | |
| 56 | if (!turn.ok) return { ok: false, line: turn.line }; | |
| 57 | const dir = releaseDir(input.dataDir, found.sha); | |
| 58 | // Touched, so the next landing's pruning keeps what was just chosen. | |
| 59 | const now = new Date(); | |
| 60 | utimesSync(dir, now, now); | |
| 61 | const swapped = await startRelease({ | |
| 62 | dir, | |
| 63 | sha: found.sha, | |
| 64 | port: input.port, | |
| 65 | env: input.env, | |
| 66 | ...(input.budgetMs === undefined ? {} : { budgetMs: input.budgetMs }), | |
| 67 | }); | |
| 68 | endSwap(swapped.ok); | |
| 69 | if (!swapped.ok) return { ok: false, line: swapped.line }; | |
| 70 | input.drain(); | |
| 71 | return { ok: true, sha: found.sha, pid: swapped.pid }; | |
| 72 | } |
src/web/pages/releases.ts added +114
| @@ -0,0 +1,114 @@ | ||
| 1 | /** | |
| 2 | * The forge's own releases (#1664): every landing cut and preflighted, which | |
| 3 | * is live and since when, and for a writer of the forge's repository the | |
| 4 | * button that rolls back to one still on disk. | |
| 5 | */ | |
| 6 | ||
| 7 | import { getRepo, canWrite } from "../../core/repos.ts"; | |
| 8 | import type { Repo } from "../../core/repos.ts"; | |
| 9 | import { running } from "../../kernel/version.ts"; | |
| 10 | import { healthySince } from "../../release/live.ts"; | |
| 11 | import { keptShas, rollback } from "../../release/rollback.ts"; | |
| 12 | import { handover } from "../../release/swap.ts"; | |
| 13 | import { listReleases } from "../../release/record.ts"; | |
| 14 | import type { Ctx } from "../../http/context.ts"; | |
| 15 | import { notFoundPage, repoBase, signInFirst } from "../chrome.ts"; | |
| 16 | import { readForm } from "../form.ts"; | |
| 17 | import { html, type Html } from "../html.ts"; | |
| 18 | import { flashTo, page } from "../layout.ts"; | |
| 19 | import { btn, card, empty, icon, row, time } from "../ui.ts"; | |
| 20 | ||
| 21 | const forgeRepo = (ctx: Ctx): Repo | undefined => { | |
| 22 | const name = ctx.app.config.forgeRepo; | |
| 23 | if (name === undefined) return undefined; | |
| 24 | const [owner = "", repo = ""] = name.split("/"); | |
| 25 | return getRepo(ctx.app.db, owner, repo); | |
| 26 | }; | |
| 27 | ||
| 28 | /** The home's line: "live: <sha> since <time>", or nothing when no release is known. */ | |
| 29 | export function liveLine(ctx: Ctx): Html | undefined { | |
| 30 | const sha = running().commit; | |
| 31 | if (sha === null) return undefined; | |
| 32 | const since = healthySince(ctx.app.db, sha); | |
| 33 | return html`<p class="muted small"> | |
| 34 | live: <a href="/releases"><code>${sha.slice(0, 12)}</code></a>${since === undefined | |
| 35 | ? null | |
| 36 | : html` since ${time(since)}`} | |
| 37 | </p>`; | |
| 38 | } | |
| 39 | ||
| 40 | export function releasesPage(ctx: Ctx): Response { | |
| 41 | const repo = forgeRepo(ctx); | |
| 42 | const live = running().commit; | |
| 43 | const writer = repo !== undefined && canWrite(ctx.app.db, repo, ctx.auth.user); | |
| 44 | const kept = new Set(keptShas(ctx.app.config.dataDir)); | |
| 45 | const rows = listReleases(ctx.app.db, 50).map((r) => { | |
| 46 | const isLive = r.sha === live; | |
| 47 | const since = isLive ? healthySince(ctx.app.db, r.sha) : undefined; | |
| 48 | const canRoll = writer && !isLive && r.ok && kept.has(r.sha); | |
| 49 | return row({ | |
| 50 | lead: icon(isLive ? "check" : r.ok ? "history" : "alert"), | |
| 51 | title: html`<code>${r.sha.slice(0, 12)}</code>${isLive ? html` <strong>live</strong>` : null}`, | |
| 52 | meta: html`${r.pullNumber === null || repo === undefined | |
| 53 | ? "no pull" | |
| 54 | : html`landed <a href="${repoBase(repo)}/pulls/${r.pullNumber}">#${r.pullNumber}</a>`} | |
| 55 | · ${time(r.createdAt)}${since === undefined ? null : html` · healthy since ${time(since)}`}${r.ok | |
| 56 | ? kept.has(r.sha) | |
| 57 | ? null | |
| 58 | : " · no longer kept" | |
| 59 | : html` · failed preflight: ${r.line}`}`, | |
| 60 | trail: canRoll | |
| 61 | ? html`<form method="post" action="/releases/rollback"> | |
| 62 | <input type="hidden" name="sha" value="${r.sha}" /> | |
| 63 | ${btn("Roll back", { type: "submit", size: "sm", icon: "history" })} | |
| 64 | </form>` | |
| 65 | : html``, | |
| 66 | }); | |
| 67 | }); | |
| 68 | return page({ | |
| 69 | ctx, | |
| 70 | title: "Releases", | |
| 71 | body: html`<div class="page-head"><h1>Releases</h1></div> | |
| 72 | ${rows.length === 0 | |
| 73 | ? empty({ | |
| 74 | icon: "history", | |
| 75 | title: "No releases yet", | |
| 76 | note: "A landing on this forge's own repository is cut and kept here.", | |
| 77 | }) | |
| 78 | : card(html`<ul class="list">${rows}</ul>`, { pad: false })}`, | |
| 79 | }); | |
| 80 | } | |
| 81 | ||
| 82 | export async function releasesRollback(ctx: Ctx): Promise<Response> { | |
| 83 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 84 | const form = await readForm(ctx, "rw"); | |
| 85 | if (form instanceof Response) return form; | |
| 86 | const repo = forgeRepo(ctx); | |
| 87 | if (repo === undefined || !canWrite(ctx.app.db, repo, ctx.auth.user)) return notFoundPage(ctx); | |
| 88 | const drain = handover.drain; | |
| 89 | const port = ctx.app.config.port ?? 0; | |
| 90 | if (drain === undefined || port <= 0) | |
| 91 | return flashTo(ctx, "/releases", { | |
| 92 | tone: "danger", | |
| 93 | message: "This process cannot hand over its port; restart the forge on that release.", | |
| 94 | }); | |
| 95 | const sha = form.get("sha"); | |
| 96 | const done = await rollback({ | |
| 97 | dataDir: ctx.app.config.dataDir, | |
| 98 | sha: typeof sha === "string" ? sha : "", | |
| 99 | live: running().commit, | |
| 100 | port, | |
| 101 | env: process.env, | |
| 102 | ...(ctx.app.config.swapBudgetMs === undefined ? {} : { budgetMs: ctx.app.config.swapBudgetMs }), | |
| 103 | // After the answer is on its way: draining stops this process's apps and checks. | |
| 104 | drain: () => void setTimeout(drain, 0), | |
| 105 | }); | |
| 106 | ctx.app.log.info("rollback", { by: ctx.auth.user.username, ok: done.ok }); | |
| 107 | return flashTo( | |
| 108 | ctx, | |
| 109 | "/releases", | |
| 110 | done.ok | |
| 111 | ? { message: `Rolled back to ${done.sha.slice(0, 12)}.` } | |
| 112 | : { tone: "danger", message: `Not rolled back: ${done.line}.` }, | |
| 113 | ); | |
| 114 | } |
src/web/studio/home.ts +2 −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, |
| @@ -187,7 +188,7 @@ export async function studioHome( | ||
| 187 | 188 | // everyday account themselves (#600); anywhere else, #803's card asks. |
| 188 | 189 | const firstSteps = await nextStepsCard(ctx, user); |
| 189 | 190 | const body = html`<h1 class="sr-only">Home</h1> |
| 190 | ${firstSteps ?? everydayCard(ctx, user)} ${address} | |
| 191 | ${firstSteps ?? everydayCard(ctx, user)} ${address} ${liveLine(ctx) ?? null} | |
| 191 | 192 | ${homeTabs("feed")} |
| 192 | 193 | <div class="dash"> |
| 193 | 194 | <div class="dash-main stack"> |
test/release-rollback.test.ts added +306
| @@ -0,0 +1,306 @@ | ||
| 1 | /** | |
| 2 | * Rolling back to a kept release (#1664): the swap of step 3 aimed at a | |
| 3 | * `releases/<sha>/` already on disk, from `--rollback <sha>` and from a | |
| 4 | * writer's button on /releases. An older release must boot on the newer | |
| 5 | * schema it is rolled back onto, and serve. | |
| 6 | */ | |
| 7 | ||
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; | |
| 10 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 11 | import { tmpdir } from "node:os"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { createRepo } from "../src/actions/repos.ts"; | |
| 15 | import { signUp } from "../src/actions/users.ts"; | |
| 16 | import { createToken } from "../src/core/tokens.ts"; | |
| 17 | import { migrations } from "../src/core/schema.ts"; | |
| 18 | import { openDb } from "../src/kernel/db.ts"; | |
| 19 | import { healthySince, recordLive } from "../src/release/live.ts"; | |
| 20 | import { recordRelease } from "../src/release/record.ts"; | |
| 21 | import { resolveKept } from "../src/release/rollback.ts"; | |
| 22 | import { endSwap, handover } from "../src/release/swap.ts"; | |
| 23 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 24 | import { proveAll } from "./helpers/verified.ts"; | |
| 25 | ||
| 26 | const LIVE = "a".repeat(40); | |
| 27 | const OLDER = "b".repeat(40); | |
| 28 | const GONE = "c".repeat(40); | |
| 29 | const FAILED = "d".repeat(40); | |
| 30 | ||
| 31 | const STAND_IN = ` | |
| 32 | setTimeout(() => process.exit(0), 25000); | |
| 33 | if (process.argv.includes("--preflight")) { console.log("preflight ok"); process.exit(0); } | |
| 34 | Bun.serve({ | |
| 35 | port: Number(process.env.PORT), | |
| 36 | reusePort: true, | |
| 37 | fetch: () => Response.json({ ok: true, draining: false, commit: process.env.FORGE_COMMIT }), | |
| 38 | }); | |
| 39 | `; | |
| 40 | ||
| 41 | const realMigrate = (() => { | |
| 42 | try { | |
| 43 | return readFileSync("/proc/sys/net/ipv4/tcp_migrate_req", "utf8").trim() === "1"; | |
| 44 | } catch { | |
| 45 | return false; | |
| 46 | } | |
| 47 | })(); | |
| 48 | const whenMigrating = realMigrate ? test : test.skip; | |
| 49 | ||
| 50 | async function freePort(): Promise<number> { | |
| 51 | const s = Bun.serve({ port: 0, fetch: () => new Response("") }); | |
| 52 | const port = s.port ?? 0; | |
| 53 | s.stop(true); | |
| 54 | return port; | |
| 55 | } | |
| 56 | ||
| 57 | const commitAt = async (port: number): Promise<string | undefined> => { | |
| 58 | try { | |
| 59 | const res = await fetch(`http://127.0.0.1:${port}/api/v1/health`, { | |
| 60 | headers: { connection: "close" }, | |
| 61 | signal: AbortSignal.timeout(3_000), | |
| 62 | }); | |
| 63 | return ((await res.json()) as { commit?: string }).commit; | |
| 64 | } catch { | |
| 65 | return undefined; | |
| 66 | } | |
| 67 | }; | |
| 68 | ||
| 69 | function keep(dataDir: string, sha: string): void { | |
| 70 | const dir = join(dataDir, "releases", sha, "src"); | |
| 71 | mkdirSync(dir, { recursive: true }); | |
| 72 | writeFileSync(join(dir, "main.ts"), STAND_IN); | |
| 73 | } | |
| 74 | ||
| 75 | describe("naming a kept release", () => { | |
| 76 | let dataDir: string; | |
| 77 | beforeAll(async () => { | |
| 78 | dataDir = await mkdtemp(join(tmpdir(), "forge-rb-names-")); | |
| 79 | keep(dataDir, LIVE); | |
| 80 | keep(dataDir, OLDER); | |
| 81 | }); | |
| 82 | afterAll(() => rm(dataDir, { recursive: true, force: true })); | |
| 83 | ||
| 84 | test("a full sha or a unique prefix resolves; anything else is refused in one line", () => { | |
| 85 | expect(resolveKept(dataDir, OLDER)).toEqual({ ok: true, sha: OLDER }); | |
| 86 | expect(resolveKept(dataDir, OLDER.slice(0, 9))).toEqual({ ok: true, sha: OLDER }); | |
| 87 | for (const bad of [GONE, "bbbb", "", "../../etc", "b".repeat(41), "zzzzzzzz"]) { | |
| 88 | const out = resolveKept(dataDir, bad); | |
| 89 | expect(out.ok).toBe(false); | |
| 90 | if (!out.ok) { | |
| 91 | expect(out.line).toMatch(/^no kept release /); | |
| 92 | expect(out.line).not.toContain("\n"); | |
| 93 | expect(out.line).not.toContain(".."); | |
| 94 | } | |
| 95 | } | |
| 96 | }); | |
| 97 | ||
| 98 | test("a prefix that fits two is refused", () => { | |
| 99 | keep(dataDir, "b" + "e".repeat(39)); | |
| 100 | const out = resolveKept(dataDir, "b".repeat(7)); | |
| 101 | expect(out.ok && out.sha === OLDER).toBe(true); | |
| 102 | const both = resolveKept(dataDir, "b"); | |
| 103 | expect(both.ok).toBe(false); | |
| 104 | }); | |
| 105 | ||
| 106 | test("healthy since is the first boot of the commit after any other", async () => { | |
| 107 | const db = openDb(join(dataDir, "live.db"), migrations); | |
| 108 | recordLive(db, LIVE); | |
| 109 | const first = healthySince(db, LIVE); | |
| 110 | recordLive(db, LIVE); | |
| 111 | expect(healthySince(db, LIVE)).toBe(first); | |
| 112 | recordLive(db, null); | |
| 113 | recordLive(db, OLDER); | |
| 114 | recordLive(db, LIVE); | |
| 115 | expect(healthySince(db, LIVE)).not.toBeUndefined(); | |
| 116 | expect(db.query("SELECT COUNT(*) AS n FROM release_live").get()).toEqual({ n: 3 }); | |
| 117 | db.close(); | |
| 118 | }); | |
| 119 | }); | |
| 120 | ||
| 121 | describe("--rollback", () => { | |
| 122 | let dataDir: string; | |
| 123 | beforeAll(async () => { | |
| 124 | dataDir = await mkdtemp(join(tmpdir(), "forge-rb-cli-")); | |
| 125 | keep(dataDir, OLDER); | |
| 126 | }); | |
| 127 | afterAll(() => rm(dataDir, { recursive: true, force: true })); | |
| 128 | ||
| 129 | const run = async (sha: string) => { | |
| 130 | const proc = Bun.spawn([process.execPath, "src/main.ts", "--rollback", sha], { | |
| 131 | env: { ...process.env, FORGE_DATA: dataDir, PORT: String(await freePort()), FORGE_SSH_PORT: "0" }, | |
| 132 | stdout: "pipe", | |
| 133 | stderr: "pipe", | |
| 134 | }); | |
| 135 | const [out, errText, code] = await Promise.all([ | |
| 136 | new Response(proc.stdout).text(), | |
| 137 | new Response(proc.stderr).text(), | |
| 138 | proc.exited, | |
| 139 | ]); | |
| 140 | return { out, errText, code }; | |
| 141 | }; | |
| 142 | ||
| 143 | test("an unknown sha is refused with one line and a failing exit", async () => { | |
| 144 | const { out, errText, code } = await run(GONE); | |
| 145 | expect(code).toBe(1); | |
| 146 | expect(out).toBe(""); | |
| 147 | expect(errText.trim().split("\n")).toEqual([`rollback refused: no kept release ${GONE}`]); | |
| 148 | }); | |
| 149 | ||
| 150 | test("no sha at all is refused the same way", async () => { | |
| 151 | const { errText, code } = await run(""); | |
| 152 | expect(code).toBe(1); | |
| 153 | expect(errText.trim().split("\n").length).toBe(1); | |
| 154 | }); | |
| 155 | }); | |
| 156 | ||
| 157 | describe("an older release on a newer schema", () => { | |
| 158 | let dataDir: string; | |
| 159 | beforeAll(async () => { | |
| 160 | dataDir = await mkdtemp(join(tmpdir(), "forge-rb-schema-")); | |
| 161 | }); | |
| 162 | afterAll(() => rm(dataDir, { recursive: true, force: true })); | |
| 163 | ||
| 164 | test("a build that knows fewer migrations opens the database a newer one migrated", () => { | |
| 165 | const path = join(dataDir, "a.db"); | |
| 166 | openDb(path, [...migrations, "ALTER TABLE release ADD COLUMN later TEXT"]).close(); | |
| 167 | const db = openDb(path, migrations); | |
| 168 | expect(db.query("SELECT COUNT(*) AS n FROM release").get()).toEqual({ n: 0 }); | |
| 169 | db.close(); | |
| 170 | }); | |
| 171 | ||
| 172 | test("this tree boots and serves on a database one migration ahead of it", async () => { | |
| 173 | openDb(join(dataDir, "forge.db"), [...migrations, "CREATE TABLE from_the_future (x INTEGER)"]).close(); | |
| 174 | const port = await freePort(); | |
| 175 | const proc = Bun.spawn([process.execPath, "src/main.ts"], { | |
| 176 | env: { | |
| 177 | ...process.env, | |
| 178 | FORGE_DATA: dataDir, | |
| 179 | PORT: String(port), | |
| 180 | FORGE_SSH_PORT: "0", | |
| 181 | FORGE_COMMIT: OLDER, | |
| 182 | }, | |
| 183 | stdout: "ignore", | |
| 184 | stderr: "ignore", | |
| 185 | }); | |
| 186 | try { | |
| 187 | let seen: string | undefined; | |
| 188 | for (let i = 0; i < 100 && seen === undefined; i++) { | |
| 189 | seen = await commitAt(port); | |
| 190 | if (seen === undefined) await Bun.sleep(100); | |
| 191 | } | |
| 192 | expect(seen).toBe(OLDER); | |
| 193 | expect((await fetch(`http://127.0.0.1:${port}/`)).status).toBe(200); | |
| 194 | } finally { | |
| 195 | proc.kill("SIGKILL"); | |
| 196 | await proc.exited; | |
| 197 | } | |
| 198 | }, 20_000); | |
| 199 | }); | |
| 200 | ||
| 201 | describe("the releases page and its button", () => { | |
| 202 | let dataDir: string; | |
| 203 | let app: App; | |
| 204 | let servers: Servers; | |
| 205 | let base: string; | |
| 206 | let port: number; | |
| 207 | let writer: { authorization: string }; | |
| 208 | let reader: { authorization: string }; | |
| 209 | let drained = 0; | |
| 210 | ||
| 211 | beforeAll(async () => { | |
| 212 | handover.migrate = true; | |
| 213 | handover.drain = () => { | |
| 214 | drained++; | |
| 215 | }; | |
| 216 | dataDir = await mkdtemp(join(tmpdir(), "forge-rb-page-")); | |
| 217 | port = await freePort(); | |
| 218 | app = createApp({ dataDir, port, forgeRepo: "olive/forge", selfSwap: true, url: "https://forge.example", edgeToken: "e" }); | |
| 219 | servers = await serve(app); | |
| 220 | base = servers.url; | |
| 221 | const mk = async (username: string) => { | |
| 222 | const u = await signUp(app, { username, email: `${username}@f.dev`, password: "a-long-passphrase" }); | |
| 223 | if (!u.ok) throw new Error(u.error); | |
| 224 | return u.value; | |
| 225 | }; | |
| 226 | const olive = await mk("olive"); | |
| 227 | const nosy = await mk("nosy"); | |
| 228 | proveAll(app); | |
| 229 | writer = { authorization: `Bearer ${createToken(app.db, olive.id, "t", "rw").token}` }; | |
| 230 | reader = { authorization: `Bearer ${createToken(app.db, nosy.id, "t", "rw").token}` }; | |
| 231 | const made = await createRepo(app, olive, { name: "forge" }); | |
| 232 | if (!made.ok) throw new Error(made.error); | |
| 233 | const repoId = made.value.id; | |
| 234 | for (const [sha, pull, ok] of [[OLDER, 3, true], [GONE, 2, true], [FAILED, 4, false], [LIVE, 5, true]] as const) | |
| 235 | recordRelease(app.db, { sha, repoId, pullNumber: pull, ok, line: ok ? "preflight ok" : "<b>boom</b>" }); | |
| 236 | keep(dataDir, OLDER); | |
| 237 | keep(dataDir, LIVE); | |
| 238 | process.env.FORGE_COMMIT = LIVE; | |
| 239 | recordLive(app.db, LIVE); | |
| 240 | }); | |
| 241 | afterAll(async () => { | |
| 242 | endSwap(false); | |
| 243 | delete process.env.FORGE_COMMIT; | |
| 244 | delete handover.migrate; | |
| 245 | delete handover.drain; | |
| 246 | servers.stop(); | |
| 247 | app.close(); | |
| 248 | await rm(dataDir, { recursive: true, force: true }); | |
| 249 | }); | |
| 250 | ||
| 251 | const post = (headers: Record<string, string>, sha: string) => | |
| 252 | fetch(`${base}/releases/rollback`, { | |
| 253 | method: "POST", | |
| 254 | redirect: "manual", | |
| 255 | headers: { ...headers, "content-type": "application/x-www-form-urlencoded" }, | |
| 256 | body: new URLSearchParams({ sha }).toString(), | |
| 257 | }); | |
| 258 | ||
| 259 | test("each release shows its sha, pull, live mark and healthy-since; a writer gets the button on a kept one only", async () => { | |
| 260 | const body = await (await fetch(`${base}/releases`, { headers: writer })).text(); | |
| 261 | expect(body).toContain(OLDER.slice(0, 12)); | |
| 262 | expect(body).toContain("/olive/forge/pulls/3"); | |
| 263 | expect(body).toContain("healthy since"); | |
| 264 | expect(body).toContain("<strong>live</strong>"); | |
| 265 | expect(body).toContain("no longer kept"); | |
| 266 | expect(body).toContain("failed preflight: <b>boom</b>"); | |
| 267 | expect(body).not.toContain("<b>boom</b>"); | |
| 268 | // Only OLDER is kept, ok and not live. | |
| 269 | expect(body.match(/action="\/releases\/rollback"/g)?.length).toBe(1); | |
| 270 | expect(body).toContain(`value="${OLDER}"`); | |
| 271 | }); | |
| 272 | ||
| 273 | test("someone who cannot write sees no button and cannot press it", async () => { | |
| 274 | const body = await (await fetch(`${base}/releases`, { headers: reader })).text(); | |
| 275 | expect(body).not.toContain("/releases/rollback"); | |
| 276 | expect((await post(reader, OLDER)).status).toBe(404); | |
| 277 | expect(drained).toBe(0); | |
| 278 | }); | |
| 279 | ||
| 280 | test("a cross-origin press and an unknown sha change nothing", async () => { | |
| 281 | expect((await post({ ...writer, origin: "https://evil.example" }, OLDER)).status).toBe(403); | |
| 282 | const unknown = await post(writer, GONE); | |
| 283 | expect(unknown.status).toBe(303); | |
| 284 | expect(unknown.headers.get("location")).toBe("/releases"); | |
| 285 | const live = await post(writer, LIVE); | |
| 286 | expect(live.status).toBe(303); | |
| 287 | expect(drained).toBe(0); | |
| 288 | }); | |
| 289 | ||
| 290 | test("the home says what is live and since when", async () => { | |
| 291 | const body = await (await fetch(`${base}/`, { headers: writer })).text(); | |
| 292 | expect(body).toContain("live:"); | |
| 293 | expect(body).toContain(LIVE.slice(0, 12)); | |
| 294 | expect(body).toContain(" since "); | |
| 295 | }); | |
| 296 | ||
| 297 | test("pressing it starts the kept release, which serves its sha, and drains this process", async () => { | |
| 298 | const res = await post(writer, OLDER); | |
| 299 | expect(res.status).toBe(303); | |
| 300 | await Bun.sleep(50); | |
| 301 | expect(drained).toBe(1); | |
| 302 | let served = false; | |
| 303 | for (let i = 0; i < 60 && !served; i++) served = (await commitAt(port)) === OLDER; | |
| 304 | expect(served).toBe(true); | |
| 305 | }, 30_000); | |
| 306 | }); |
test/schema-migrations.test.ts +14 −1
| @@ -147,8 +147,21 @@ describe("a preview booting on copied data", () => { | ||
| 147 | 147 | db.close(); |
| 148 | 148 | }); |
| 149 | 149 | |
| 150 | test("data ahead of this build is still refused", () => { | |
| 150 | test("data ahead of this build is served, not refused: a rollback boots an older release", () => { | |
| 151 | 151 | const path = production(["CREATE TABLE a (x INTEGER)", "CREATE TABLE b (y INTEGER)"]); |
| 152 | const db = openDb(path, ["CREATE TABLE a (x INTEGER)"]); | |
| 153 | expect(has(db, "a")).toBe(true); | |
| 154 | expect(has(db, "b")).toBe(true); | |
| 155 | db.close(); | |
| 156 | }); | |
| 157 | ||
| 158 | test("a database from before the tracking table, ahead of this build, is refused", () => { | |
| 159 | const path = fresh(); | |
| 160 | const { Database } = require("bun:sqlite") as typeof import("bun:sqlite"); | |
| 161 | const old = new Database(path, { create: true, strict: true }); | |
| 162 | old.exec("CREATE TABLE a (x INTEGER)"); | |
| 163 | old.exec("PRAGMA user_version = 2"); | |
| 164 | old.close(); | |
| 152 | 165 | expect(() => openDb(path, ["CREATE TABLE a (x INTEGER)"])).toThrow(ForgeError); |
| 153 | 166 | }); |
| 154 | 167 | }); |
new above
offline