Public: anyone can read this; the crew can change it.
Fast test/apps-adversarial.test.ts: chop and rewrite under the budget (1 s a test, 10 s a file) #1282
scout/forge:scout/1247-fast-test-apps-adversarial-test-ts-chop → main 5 commits fork 1 thread · 1 unresolved
4 files
changed +408
−370
scripts/gate.ts +2
| @@ -93,10 +93,12 @@ export const GATE: readonly string[] = [ | ||
| 93 | 93 | "test/fork-pull-approval.test.ts", |
| 94 | 94 | "test/cross-repo-pull.test.ts", |
| 95 | 95 | "test/pulls.test.ts", |
| 96 | "test/plan-route.test.ts", | |
| 96 | 97 | "test/api-reader-marks.test.ts", |
| 97 | 98 | "test/app-members.test.ts", |
| 98 | 99 | "test/apps.test.ts", |
| 99 | 100 | "test/apps-adversarial.test.ts", |
| 101 | "test/apps-adversarial-deploys.test.ts", | |
| 100 | 102 | "test/apps-busy.test.ts", |
| 101 | 103 | "test/apps-token.test.ts", |
| 102 | 104 | "test/contain.test.ts", |
src/apps/runtime.ts +13 −3
| @@ -137,6 +137,13 @@ export interface RuntimeOptions { | ||
| 137 | 137 | readonly placement?: Placement | undefined; |
| 138 | 138 | /** How often storage is sampled for the meter. @default one hour */ |
| 139 | 139 | readonly storageEveryMs?: number | undefined; |
| 140 | /** | |
| 141 | * How a process is started: `startProcess` unless a test hands in a fake, | |
| 142 | * so teardown and restart races are checked without real processes. | |
| 143 | */ | |
| 144 | readonly start?: typeof startProcess | undefined; | |
| 145 | /** The waits before each restart of a crashed process. @default 2 s, 10 s, 30 s */ | |
| 146 | readonly restartBackoffMs?: readonly number[] | undefined; | |
| 140 | 147 | } |
| 141 | 148 | |
| 142 | 149 | export type EnvState = |
| @@ -381,12 +388,14 @@ export class AppsRuntime { | ||
| 381 | 388 | private unsubscribe: (() => void) | undefined; |
| 382 | 389 | private sweeper: ReturnType<typeof setInterval> | undefined; |
| 383 | 390 | private stopped = false; |
| 391 | private readonly startFn: typeof startProcess; | |
| 384 | 392 | |
| 385 | 393 | constructor( |
| 386 | 394 | readonly app: App, |
| 387 | 395 | readonly options: RuntimeOptions, |
| 388 | 396 | ) { |
| 389 | 397 | this.gate = new Gate(options.concurrency ?? 2); |
| 398 | this.startFn = options.start ?? startProcess; | |
| 390 | 399 | runtimes.set(app, this); |
| 391 | 400 | } |
| 392 | 401 | |
| @@ -1221,7 +1230,7 @@ export class AppsRuntime { | ||
| 1221 | 1230 | write(clock.line("starting the process")); |
| 1222 | 1231 | const start = async (): ReturnType<typeof startProcess> => { |
| 1223 | 1232 | try { |
| 1224 | return await startProcess({ ...startInput, signal }); | |
| 1233 | return await this.startFn({ ...startInput, signal }); | |
| 1225 | 1234 | } catch (error) { |
| 1226 | 1235 | revokeAppToken(this.app.db, token.id); |
| 1227 | 1236 | throw error; |
| @@ -1366,7 +1375,8 @@ export class AppsRuntime { | ||
| 1366 | 1375 | appendRunLog(this.app.config.dataDir, live.runId, state.lastError); |
| 1367 | 1376 | return; |
| 1368 | 1377 | } |
| 1369 | const delay = RESTART_BACKOFF_MS[state.restarts.length] ?? 30_000; | |
| 1378 | const backoff = this.options.restartBackoffMs ?? RESTART_BACKOFF_MS; | |
| 1379 | const delay = backoff[state.restarts.length] ?? 30_000; | |
| 1370 | 1380 | state.restarts.push(now); |
| 1371 | 1381 | setTimeout(() => { |
| 1372 | 1382 | if (this.stopped) return; |
| @@ -1485,7 +1495,7 @@ export class AppsRuntime { | ||
| 1485 | 1495 | }; |
| 1486 | 1496 | write("waking: a request came"); |
| 1487 | 1497 | const token = mintAppToken(this.app.db, repo.ownerId, record.slug, env); |
| 1488 | const started = await startProcess({ | |
| 1498 | const started = await this.startFn({ | |
| 1489 | 1499 | dir: asleep.dir, |
| 1490 | 1500 | dataDir: envDataDir(this.app.config.dataDir, record.id, env), |
| 1491 | 1501 | manifest: asleep.manifest, |
test/apps-adversarial-deploys.test.ts added +393
| @@ -0,0 +1,393 @@ | ||
| 1 | /** | |
| 2 | * Teardown and start races of the apps runtime, checked in milliseconds: a | |
| 3 | * closed pull must not resurrect, orphan a test step, or leave a directory; | |
| 4 | * a failed install must stop before test or start; a forge addressed by IP | |
| 5 | * must hand its apps a URL that parses. The runtime is handed a fake | |
| 6 | * `start` and a short restart backoff (`RuntimeOptions`), so no deploy | |
| 7 | * waits on a real process; `startProcess` itself is driven with steps that | |
| 8 | * finish at once. Split from apps-adversarial.test.ts (#1247). | |
| 9 | */ | |
| 10 | ||
| 11 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 12 | import { existsSync } from "node:fs"; | |
| 13 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 14 | import { tmpdir } from "node:os"; | |
| 15 | import { join } from "node:path"; | |
| 16 | import { createApp, type App } from "../src/app.ts"; | |
| 17 | import { AppsRuntime } from "../src/apps/runtime.ts"; | |
| 18 | import { envDir, type EnvName } from "../src/apps/data.ts"; | |
| 19 | import { resolveAppDomain } from "../src/apps/host.ts"; | |
| 20 | import type { AppManifest } from "../src/apps/manifest.ts"; | |
| 21 | import { | |
| 22 | startProcess, | |
| 23 | type ProcessHandle, | |
| 24 | type StartInput, | |
| 25 | } from "../src/apps/process.ts"; | |
| 26 | import { enableApp } from "../src/actions/apps.ts"; | |
| 27 | import { mergePull, openPull } from "../src/actions/pulls.ts"; | |
| 28 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 29 | import type { AppRecord } from "../src/core/apps.ts"; | |
| 30 | import type { Repo } from "../src/core/repos.ts"; | |
| 31 | import { getPull } from "../src/core/pulls.ts"; | |
| 32 | import { listRuns } from "../src/core/runs.ts"; | |
| 33 | import { createUser, type User } from "../src/core/users.ts"; | |
| 34 | import { err, ok } from "../src/kernel/result.ts"; | |
| 35 | ||
| 36 | const DOMAIN = "apps.test"; | |
| 37 | ||
| 38 | /** A process that is "live" until stopped or told to crash. */ | |
| 39 | function fakeHandle(): ProcessHandle & { crash(code: number): void } { | |
| 40 | let finish: (code: number) => void = () => {}; | |
| 41 | const exited = new Promise<number>((resolve) => { | |
| 42 | finish = resolve; | |
| 43 | }); | |
| 44 | return { | |
| 45 | pid: 0, | |
| 46 | port: 1, | |
| 47 | exited, | |
| 48 | stop: async () => finish(0), | |
| 49 | crash: (code) => finish(code), | |
| 50 | }; | |
| 51 | } | |
| 52 | ||
| 53 | /** | |
| 54 | * An app of the smallest kind the runtime deploys: a manifest and nothing | |
| 55 | * else (the scaffold is thousands of lines, and not what is under test). | |
| 56 | */ | |
| 57 | async function makeApp(app: App, user: User, name: string) { | |
| 58 | const repo = await createRepo(app, user, { name, visibility: "public" }); | |
| 59 | if (!repo.ok) throw new Error(repo.error); | |
| 60 | const committed = await commitToBranch(app, user, repo.value, { | |
| 61 | message: `Start ${name}`, | |
| 62 | files: [{ path: "forge.json", content: '{"app":{"run":"true"}}\n' }], | |
| 63 | }); | |
| 64 | if (!committed.ok) throw new Error(JSON.stringify(committed.error)); | |
| 65 | const record = enableApp(app, user, repo.value, {}); | |
| 66 | if (!record.ok) throw new Error(record.error); | |
| 67 | return { repo: repo.value, app: record.value }; | |
| 68 | } | |
| 69 | ||
| 70 | /** | |
| 71 | * A stand-in for `startProcess`. While `hang` is set, a preview never | |
| 72 | * answers: its start waits for its abort and fails as a cancelled one | |
| 73 | * does. Otherwise a start | |
| 74 | * answers at once with a test step that stays pending until aborted. | |
| 75 | */ | |
| 76 | function fakeStart() { | |
| 77 | const state = { hang: false }; | |
| 78 | const starts: StartInput[] = []; | |
| 79 | const handles: Array<ProcessHandle & { crash(code: number): void }> = []; | |
| 80 | const aborted: string[] = []; | |
| 81 | const testsEnded: string[] = []; | |
| 82 | let entered: (() => void) | undefined; | |
| 83 | const start: typeof startProcess = async (input) => { | |
| 84 | starts.push(input); | |
| 85 | if (input.env !== "production") entered?.(); | |
| 86 | if (state.hang && input.env !== "production") { | |
| 87 | await new Promise<void>((resolve) => | |
| 88 | input.signal.addEventListener("abort", () => resolve(), { once: true }), | |
| 89 | ); | |
| 90 | aborted.push(input.env); | |
| 91 | return err({ stage: "start", message: "cancelled" }); | |
| 92 | } | |
| 93 | const handle = fakeHandle(); | |
| 94 | handles.push(handle); | |
| 95 | const tested = new Promise<ReturnType<typeof ok<void>>>((resolve) => { | |
| 96 | input.signal.addEventListener( | |
| 97 | "abort", | |
| 98 | () => { | |
| 99 | aborted.push(input.env); | |
| 100 | testsEnded.push(input.env); | |
| 101 | resolve(ok()); | |
| 102 | }, | |
| 103 | { once: true }, | |
| 104 | ); | |
| 105 | // A crashed app takes its test step's verdict with it. | |
| 106 | void handle.exited.then(() => resolve(ok())); | |
| 107 | }); | |
| 108 | return ok({ handle, tested }); | |
| 109 | }; | |
| 110 | return { | |
| 111 | start, | |
| 112 | state, | |
| 113 | starts, | |
| 114 | handles, | |
| 115 | aborted, | |
| 116 | testsEnded, | |
| 117 | /** Resolves when the next preview reaches `start`. */ | |
| 118 | reached: () => new Promise<void>((resolve) => (entered = resolve)), | |
| 119 | }; | |
| 120 | } | |
| 121 | ||
| 122 | const until = async (done: () => boolean, ms = 3_000): Promise<void> => { | |
| 123 | const deadline = Date.now() + ms; | |
| 124 | while (!done() && Date.now() < deadline) await Bun.sleep(5); | |
| 125 | }; | |
| 126 | ||
| 127 | describe("apps adversarial: teardown races with a faked process", () => { | |
| 128 | let dataDir: string; | |
| 129 | let app: App; | |
| 130 | let runtime: AppsRuntime; | |
| 131 | let alice: User; | |
| 132 | const fake = fakeStart(); | |
| 133 | ||
| 134 | /** Until the environment answers: its tests may still be running. */ | |
| 135 | const live = (record: AppRecord, env: EnvName) => | |
| 136 | until(() => runtime.envStatus(record, env)?.state === "running"); | |
| 137 | ||
| 138 | let record: AppRecord; | |
| 139 | let repo: Repo; | |
| 140 | ||
| 141 | /** Open a pull from `branch`, let `between` look at it, then close it. */ | |
| 142 | const openAndClose = async ( | |
| 143 | branch: string, | |
| 144 | between: (number: number) => Promise<void>, | |
| 145 | ) => { | |
| 146 | const opened = await openPull(app, alice, repo, { | |
| 147 | title: "Change", | |
| 148 | baseBranch: repo.defaultBranch, | |
| 149 | headBranch: branch, | |
| 150 | }); | |
| 151 | if (!opened.ok) throw new Error(opened.error); | |
| 152 | const number = opened.value.number; | |
| 153 | await between(number); | |
| 154 | const closed = await mergePull( | |
| 155 | app, | |
| 156 | alice, | |
| 157 | repo, | |
| 158 | getPull(app.db, repo.id, number)!, | |
| 159 | "merge", | |
| 160 | ); | |
| 161 | expect(closed.ok).toBe(true); | |
| 162 | return number; | |
| 163 | }; | |
| 164 | ||
| 165 | beforeAll(async () => { | |
| 166 | dataDir = await mkdtemp(join(tmpdir(), "forge-adv-")); | |
| 167 | app = createApp({ dataDir, port: 0 }); | |
| 168 | runtime = new AppsRuntime(app, { | |
| 169 | domain: DOMAIN, | |
| 170 | scheme: "http", | |
| 171 | forgeUrl: "http://forge.test", | |
| 172 | concurrency: 2, | |
| 173 | start: fake.start, | |
| 174 | restartBackoffMs: [20, 20, 20], | |
| 175 | }); | |
| 176 | await runtime.start(); | |
| 177 | const created = await createUser(app.db, { | |
| 178 | trusted: true, | |
| 179 | username: "alice", | |
| 180 | email: "[email protected]", | |
| 181 | password: "a-good-passphrase", | |
| 182 | adminIfFirst: true, | |
| 183 | }); | |
| 184 | if (!created.ok) throw new Error(created.error); | |
| 185 | alice = created.value; | |
| 186 | // The slow part — real git — is done once, here: an app with production | |
| 187 | // up and a branch for each test to open as a pull. | |
| 188 | ({ repo, app: record } = await makeApp(app, alice, "teardown")); | |
| 189 | for (const branch of ["resurrect", "midclose", "slowtest"]) { | |
| 190 | const committed = await commitToBranch(app, alice, repo, { | |
| 191 | branch, | |
| 192 | base: repo.defaultBranch, | |
| 193 | message: `change for ${branch}`, | |
| 194 | files: [{ path: `${branch}.md`, content: "hi\n" }], | |
| 195 | }); | |
| 196 | if (!committed.ok) throw new Error(JSON.stringify(committed.error)); | |
| 197 | } | |
| 198 | await live(record, "production"); | |
| 199 | }, 30_000); | |
| 200 | ||
| 201 | afterAll(async () => { | |
| 202 | await runtime.stop(); | |
| 203 | app.close(); | |
| 204 | await rm(dataDir, { recursive: true, force: true }); | |
| 205 | }); | |
| 206 | ||
| 207 | test("a crashed process is restarted after the backoff (the control for the next test)", async () => { | |
| 208 | const before = fake.starts.length; | |
| 209 | fake.handles.at(-1)!.crash(1); | |
| 210 | await until(() => fake.starts.length > before); | |
| 211 | expect(fake.starts.length).toBeGreaterThan(before); | |
| 212 | expect( | |
| 213 | listRuns(app.db, repo.id, { env: "production" }).some( | |
| 214 | (r) => r.reason === "restart", | |
| 215 | ), | |
| 216 | ).toBe(true); | |
| 217 | }); | |
| 218 | ||
| 219 | test("closing an already-live preview does not resurrect it after the restart backoff", async () => { | |
| 220 | const number = await openAndClose("resurrect", async (n) => { | |
| 221 | await live(record, `pull-${n}`); | |
| 222 | expect(runtime.envStatus(record, `pull-${n}`)?.state).toBe("running"); | |
| 223 | }); | |
| 224 | const dir = envDir(dataDir, record.id, `pull-${number}`); | |
| 225 | await until(() => !existsSync(dir)); | |
| 226 | expect(existsSync(dir)).toBe(false); | |
| 227 | ||
| 228 | // The bug: `watch()`'s exit handler mistook the deliberate stop for a | |
| 229 | // crash and scheduled a restart after the backoff. Wait past it (20 ms | |
| 230 | // here) and confirm nothing came back. | |
| 231 | const starts = fake.starts.length; | |
| 232 | await Bun.sleep(120); | |
| 233 | expect(fake.starts.length).toBe(starts); | |
| 234 | expect(existsSync(dir)).toBe(false); | |
| 235 | expect(runtime.envStatus(record, `pull-${number}`)).toBeUndefined(); | |
| 236 | expect( | |
| 237 | listRuns(app.db, repo.id, { env: `pull-${number}` }).filter( | |
| 238 | (r) => r.reason === "restart", | |
| 239 | ), | |
| 240 | ).toEqual([]); | |
| 241 | }); | |
| 242 | ||
| 243 | test("closing a pull mid-deploy aborts the start and leaves no directory and no process", async () => { | |
| 244 | fake.state.hang = true; | |
| 245 | const reached = fake.reached(); | |
| 246 | const number = await openAndClose("midclose", () => reached); | |
| 247 | const dir = envDir(dataDir, record.id, `pull-${number}`); | |
| 248 | await until(() => fake.aborted.includes(`pull-${number}`)); | |
| 249 | expect(fake.aborted).toContain(`pull-${number}`); | |
| 250 | await until(() => !existsSync(dir)); | |
| 251 | expect(existsSync(dir)).toBe(false); | |
| 252 | const starts = fake.starts.length; | |
| 253 | await Bun.sleep(120); | |
| 254 | expect(fake.starts.length).toBe(starts); | |
| 255 | expect(runtime.envStatus(record, `pull-${number}`)).toBeUndefined(); | |
| 256 | fake.state.hang = false; | |
| 257 | }); | |
| 258 | ||
| 259 | test("closing a pull whose deploy already answered aborts its still-running test step", async () => { | |
| 260 | const ended = fake.testsEnded.length; | |
| 261 | await openAndClose("slowtest", async (n) => { | |
| 262 | await live(record, `pull-${n}`); | |
| 263 | // The fake's test step is pending: it ends only on the abort the | |
| 264 | // teardown raises. | |
| 265 | await until(() => fake.starts.some((s) => s.env === `pull-${n}`)); | |
| 266 | expect(fake.testsEnded.length).toBe(ended); | |
| 267 | }); | |
| 268 | await until(() => fake.testsEnded.length > ended); | |
| 269 | expect(fake.testsEnded.length).toBeGreaterThan(ended); | |
| 270 | }); | |
| 271 | }); | |
| 272 | ||
| 273 | describe("startProcess: the order of install, test and run, and aborts", () => { | |
| 274 | const manifest = (over: Partial<AppManifest>): AppManifest => ({ | |
| 275 | run: "true", | |
| 276 | install: null, | |
| 277 | test: null, | |
| 278 | health: "/", | |
| 279 | ready: 2, | |
| 280 | tty: null, | |
| 281 | service: null, | |
| 282 | looks: ["/"], | |
| 283 | ...over, | |
| 284 | }); | |
| 285 | let dir: string; | |
| 286 | beforeAll(async () => { | |
| 287 | dir = await mkdtemp(join(tmpdir(), "forge-start-")); | |
| 288 | }); | |
| 289 | afterAll(() => rm(dir, { recursive: true, force: true })); | |
| 290 | ||
| 291 | const input = (m: AppManifest, signal: AbortSignal): StartInput => ({ | |
| 292 | dir, | |
| 293 | dataDir: dir, | |
| 294 | manifest: m, | |
| 295 | env: "production", | |
| 296 | url: "http://app.test", | |
| 297 | commitOid: "0".repeat(40), | |
| 298 | forgeUrl: "http://forge.test", | |
| 299 | identityKey: "key", | |
| 300 | log: () => {}, | |
| 301 | signal, | |
| 302 | }); | |
| 303 | ||
| 304 | test("install failing fails before test or start ever run", async () => { | |
| 305 | const testMarker = join(dir, "install-test-marker"); | |
| 306 | const runMarker = join(dir, "install-run-marker"); | |
| 307 | const started = await startProcess( | |
| 308 | input( | |
| 309 | manifest({ | |
| 310 | install: "exit 1", | |
| 311 | run: `touch ${runMarker}`, | |
| 312 | test: `touch ${testMarker}`, | |
| 313 | }), | |
| 314 | new AbortController().signal, | |
| 315 | ), | |
| 316 | ); | |
| 317 | expect(started.ok).toBe(false); | |
| 318 | if (started.ok) return; | |
| 319 | expect(started.error.stage).toBe("install"); | |
| 320 | expect(existsSync(testMarker)).toBe(false); | |
| 321 | expect(existsSync(runMarker)).toBe(false); | |
| 322 | }); | |
| 323 | ||
| 324 | test("aborting after the app answered kills the still-running test step", async () => { | |
| 325 | const marker = join(dir, "slowtest-marker"); | |
| 326 | const abort = new AbortController(); | |
| 327 | const started = await startProcess( | |
| 328 | input( | |
| 329 | manifest({ | |
| 330 | run: `bun -e "Bun.serve({port:+process.env.PORT,fetch:()=>new Response('ok')})"`, | |
| 331 | test: `sleep 5 && touch ${marker}`, | |
| 332 | }), | |
| 333 | abort.signal, | |
| 334 | ), | |
| 335 | ); | |
| 336 | expect(started.ok).toBe(true); | |
| 337 | if (!started.ok) return; | |
| 338 | const at = Date.now(); | |
| 339 | abort.abort(); | |
| 340 | const tested = await started.value.tested; | |
| 341 | await started.value.handle.stop(); | |
| 342 | expect(tested.ok).toBe(false); | |
| 343 | expect(Date.now() - at).toBeLessThan(1_000); | |
| 344 | expect(existsSync(marker)).toBe(false); | |
| 345 | }); | |
| 346 | }); | |
| 347 | ||
| 348 | describe("boot: a forge addressed by IP hands every app a host that works (issue #269)", () => { | |
| 349 | let dataDir: string; | |
| 350 | let app: App; | |
| 351 | beforeAll(async () => { | |
| 352 | dataDir = await mkdtemp(join(tmpdir(), "forge-ip-")); | |
| 353 | app = createApp({ dataDir, port: 0 }); | |
| 354 | }); | |
| 355 | afterAll(async () => { | |
| 356 | app.close(); | |
| 357 | await rm(dataDir, { recursive: true, force: true }); | |
| 358 | }); | |
| 359 | ||
| 360 | test("the URL an app is started with parses — never the FORGE_APP_URL crash loop", () => { | |
| 361 | // The exact computation main.ts does at boot, for a forge reached at | |
| 362 | // `http://127.0.0.1:<port>` with no FORGE_APP_DOMAIN set. Before the | |
| 363 | // fix the domain was `127.0.0.1` and every app's FORGE_APP_URL failed | |
| 364 | // `new URL()` before it ever answered. | |
| 365 | const resolved = resolveAppDomain({ | |
| 366 | explicit: undefined, | |
| 367 | hosted: false, | |
| 368 | hostname: "127.0.0.1", | |
| 369 | }); | |
| 370 | if (!resolved.ok) throw new Error(resolved.reason); | |
| 371 | const runtime = new AppsRuntime(app, { | |
| 372 | domain: resolved.domain, | |
| 373 | scheme: "http", | |
| 374 | publicPort: 3000, | |
| 375 | forgeUrl: "http://127.0.0.1:3000", | |
| 376 | }); | |
| 377 | const record: AppRecord = { | |
| 378 | id: "app1", | |
| 379 | repoId: "repo1", | |
| 380 | slug: "ip-forge", | |
| 381 | access: "public", | |
| 382 | previewData: "copy", | |
| 383 | createdAt: new Date().toISOString(), | |
| 384 | }; | |
| 385 | for (const env of ["production", "pull-7"] as const) { | |
| 386 | const url = runtime.urlFor(record, env); | |
| 387 | // The exact check the scaffold makes at import time on FORGE_APP_URL. | |
| 388 | expect(() => new URL(url)).not.toThrow(); | |
| 389 | expect(new URL(url).hostname).not.toBe("127.0.0.1"); | |
| 390 | expect(new URL(url).hostname.startsWith("ip-forge")).toBe(true); | |
| 391 | } | |
| 392 | }); | |
| 393 | }); |
test/apps-adversarial.test.ts −367
| @@ -1128,269 +1128,6 @@ describe("apps adversarial: teardown races, grants, the proxy, and rule 1/4", () | ||
| 1128 | 1128 | await rm(work, { recursive: true, force: true }); |
| 1129 | 1129 | }); |
| 1130 | 1130 | |
| 1131 | test("closing an already-live preview does not resurrect it a few seconds later", async () => { | |
| 1132 | const made = await newApp(app, alice, { | |
| 1133 | name: "resurrect", | |
| 1134 | visibility: "public", | |
| 1135 | }); | |
| 1136 | expect(made.ok).toBe(true); | |
| 1137 | if (!made.ok) return; | |
| 1138 | const repo = made.value.repo; | |
| 1139 | const record = made.value.app; | |
| 1140 | await settled(repo.id, (r) => r.env === "production"); | |
| 1141 | ||
| 1142 | const committed = await commitToBranch(app, alice, repo, { | |
| 1143 | branch: "preview-branch", | |
| 1144 | base: repo.defaultBranch, | |
| 1145 | message: "preview change", | |
| 1146 | files: [{ path: "PREVIEW.md", content: "hi\n" }], | |
| 1147 | }); | |
| 1148 | expect(committed.ok).toBe(true); | |
| 1149 | const opened = await openPull(app, alice, repo, { | |
| 1150 | title: "Preview", | |
| 1151 | baseBranch: repo.defaultBranch, | |
| 1152 | headBranch: "preview-branch", | |
| 1153 | }); | |
| 1154 | expect(opened.ok).toBe(true); | |
| 1155 | if (!opened.ok) return; | |
| 1156 | const pull = opened.value; | |
| 1157 | ||
| 1158 | // Wait for the preview to actually come up (live, not just queued). | |
| 1159 | await settled(repo.id, (r) => r.env === `pull-${pull.number}`); | |
| 1160 | expect((await viaHost(`resurrect--${pull.number}.${DOMAIN}`)).status).toBe( | |
| 1161 | 200, | |
| 1162 | ); | |
| 1163 | ||
| 1164 | const closed = await mergePull( | |
| 1165 | app, | |
| 1166 | alice, | |
| 1167 | repo, | |
| 1168 | getPull(app.db, repo.id, pull.number)!, | |
| 1169 | "merge", | |
| 1170 | ); | |
| 1171 | expect(closed.ok).toBe(true); | |
| 1172 | ||
| 1173 | // The teardown itself must remove the directory promptly. | |
| 1174 | const goneDeadline = Date.now() + 10_000; | |
| 1175 | while ( | |
| 1176 | existsSync(envDir(dataDir, record.id, `pull-${pull.number}`)) && | |
| 1177 | Date.now() < goneDeadline | |
| 1178 | ) | |
| 1179 | await Bun.sleep(50); | |
| 1180 | expect(existsSync(envDir(dataDir, record.id, `pull-${pull.number}`))).toBe( | |
| 1181 | false, | |
| 1182 | ); | |
| 1183 | ||
| 1184 | // The bug: `watch()`'s exit handler mistook the deliberate stop for a | |
| 1185 | // crash and scheduled a restart ~2s later (RESTART_BACKOFF_MS[0]). Wait | |
| 1186 | // well past that window and confirm nothing came back — no directory, | |
| 1187 | // no live process answering the preview's host, no new "restart" run. | |
| 1188 | await Bun.sleep(3_500); | |
| 1189 | expect(existsSync(envDir(dataDir, record.id, `pull-${pull.number}`))).toBe( | |
| 1190 | false, | |
| 1191 | ); | |
| 1192 | const stillGone = await viaHost(`resurrect--${pull.number}.${DOMAIN}`); | |
| 1193 | expect(stillGone.status).toBe(404); | |
| 1194 | expect(await stillGone.text()).toContain("is gone"); | |
| 1195 | const resurrectionRuns = listRuns(app.db, repo.id, { | |
| 1196 | env: `pull-${pull.number}`, | |
| 1197 | }).filter((r) => r.reason === "restart"); | |
| 1198 | expect(resurrectionRuns.length).toBe(0); | |
| 1199 | }, 60_000); | |
| 1200 | ||
| 1201 | test("closing a pull mid-deploy still leaves no directory and no process", async () => { | |
| 1202 | const made = await newApp(app, alice, { | |
| 1203 | name: "midclose", | |
| 1204 | visibility: "public", | |
| 1205 | }); | |
| 1206 | expect(made.ok).toBe(true); | |
| 1207 | if (!made.ok) return; | |
| 1208 | const repo = made.value.repo; | |
| 1209 | const record = made.value.app; | |
| 1210 | await settled(repo.id, (r) => r.env === "production"); | |
| 1211 | ||
| 1212 | const committed = await commitToBranch(app, alice, repo, { | |
| 1213 | branch: "slow-branch", | |
| 1214 | base: repo.defaultBranch, | |
| 1215 | message: "a change", | |
| 1216 | files: [{ path: "SLOW.md", content: "hi\n" }], | |
| 1217 | }); | |
| 1218 | expect(committed.ok).toBe(true); | |
| 1219 | const opened = await openPull(app, alice, repo, { | |
| 1220 | title: "Slow", | |
| 1221 | baseBranch: repo.defaultBranch, | |
| 1222 | headBranch: "slow-branch", | |
| 1223 | }); | |
| 1224 | expect(opened.ok).toBe(true); | |
| 1225 | if (!opened.ok) return; | |
| 1226 | const pull = opened.value; | |
| 1227 | ||
| 1228 | // Close it immediately — almost certainly while the deploy is still | |
| 1229 | // installing/testing/starting, never having reached `live`. | |
| 1230 | const closedQuickly = await mergePull( | |
| 1231 | app, | |
| 1232 | alice, | |
| 1233 | repo, | |
| 1234 | getPull(app.db, repo.id, pull.number)!, | |
| 1235 | "merge", | |
| 1236 | ); | |
| 1237 | expect(closedQuickly.ok).toBe(true); | |
| 1238 | ||
| 1239 | const deadline = Date.now() + 15_000; | |
| 1240 | while ( | |
| 1241 | existsSync(envDir(dataDir, record.id, `pull-${pull.number}`)) && | |
| 1242 | Date.now() < deadline | |
| 1243 | ) | |
| 1244 | await Bun.sleep(50); | |
| 1245 | expect(existsSync(envDir(dataDir, record.id, `pull-${pull.number}`))).toBe( | |
| 1246 | false, | |
| 1247 | ); | |
| 1248 | await Bun.sleep(3_500); | |
| 1249 | expect(existsSync(envDir(dataDir, record.id, `pull-${pull.number}`))).toBe( | |
| 1250 | false, | |
| 1251 | ); | |
| 1252 | expect((await viaHost(`midclose--${pull.number}.${DOMAIN}`)).status).toBe( | |
| 1253 | 404, | |
| 1254 | ); | |
| 1255 | }, 60_000); | |
| 1256 | ||
| 1257 | test("install failing fails before test or start ever run — nothing from a half-installed tree", async () => { | |
| 1258 | const made = await newApp(app, alice, { | |
| 1259 | name: "badinstall", | |
| 1260 | visibility: "public", | |
| 1261 | }); | |
| 1262 | expect(made.ok).toBe(true); | |
| 1263 | if (!made.ok) return; | |
| 1264 | const repo = made.value.repo; | |
| 1265 | await settled(repo.id, (r) => r.env === "production"); | |
| 1266 | ||
| 1267 | const testMarker = join(work, `install-test-marker-${Date.now()}`); | |
| 1268 | const runMarker = join(work, `install-run-marker-${Date.now()}`); | |
| 1269 | const committed = await commitToBranch(app, alice, repo, { | |
| 1270 | branch: "bad-install", | |
| 1271 | base: repo.defaultBranch, | |
| 1272 | message: "install fails", | |
| 1273 | files: [ | |
| 1274 | { | |
| 1275 | path: "forge.json", | |
| 1276 | content: `${JSON.stringify( | |
| 1277 | { | |
| 1278 | app: { | |
| 1279 | install: "exit 1", | |
| 1280 | run: `touch ${runMarker} && bun run src/server.ts`, | |
| 1281 | test: `touch ${testMarker} && bun test`, | |
| 1282 | }, | |
| 1283 | }, | |
| 1284 | null, | |
| 1285 | 2, | |
| 1286 | )}\n`, | |
| 1287 | }, | |
| 1288 | ], | |
| 1289 | }); | |
| 1290 | expect(committed.ok).toBe(true); | |
| 1291 | if (!committed.ok) return; | |
| 1292 | const opened = await openPull(app, alice, repo, { | |
| 1293 | title: "Bad install", | |
| 1294 | baseBranch: repo.defaultBranch, | |
| 1295 | headBranch: "bad-install", | |
| 1296 | }); | |
| 1297 | expect(opened.ok).toBe(true); | |
| 1298 | if (!opened.ok) return; | |
| 1299 | ||
| 1300 | const failed = await settled( | |
| 1301 | repo.id, | |
| 1302 | (r) => | |
| 1303 | r.env === `pull-${opened.value.number}` && | |
| 1304 | r.commitOid === committed.value.commitOid, | |
| 1305 | ); | |
| 1306 | expect(failed.state).toBe("failed"); | |
| 1307 | expect(failed.summary).toContain("install"); | |
| 1308 | // Neither `test` nor `run` ever executed. | |
| 1309 | expect(existsSync(testMarker)).toBe(false); | |
| 1310 | expect(existsSync(runMarker)).toBe(false); | |
| 1311 | expect( | |
| 1312 | (await viaHost(`badinstall--${opened.value.number}.${DOMAIN}`)).status, | |
| 1313 | ).toBe(502); | |
| 1314 | }, 60_000); | |
| 1315 | ||
| 1316 | test("closing a pull whose deploy already answered kills its still-running test step — no orphan `bun test`", async () => { | |
| 1317 | const made = await newApp(app, alice, { | |
| 1318 | name: "slowtest", | |
| 1319 | visibility: "public", | |
| 1320 | }); | |
| 1321 | expect(made.ok).toBe(true); | |
| 1322 | if (!made.ok) return; | |
| 1323 | const repo = made.value.repo; | |
| 1324 | await settled(repo.id, (r) => r.env === "production"); | |
| 1325 | ||
| 1326 | // A merge lands this same forge.json on the default branch and | |
| 1327 | // production redeploys it too, running this same test step to | |
| 1328 | // completion (nothing aborts a deploy that was never in flight when the | |
| 1329 | // pull closed) — a marker keyed by $FORGE_APP_ENV keeps that legitimate | |
| 1330 | // production run from being mistaken for the preview's orphan. | |
| 1331 | const marker = join(work, `slowtest-marker-${Date.now()}`); | |
| 1332 | const committed = await commitToBranch(app, alice, repo, { | |
| 1333 | branch: "slow-test", | |
| 1334 | base: repo.defaultBranch, | |
| 1335 | message: "slow test", | |
| 1336 | files: [ | |
| 1337 | { | |
| 1338 | path: "forge.json", | |
| 1339 | content: `${JSON.stringify( | |
| 1340 | { | |
| 1341 | app: { | |
| 1342 | run: "bun run src/server.ts", | |
| 1343 | test: `sleep 5 && touch ${marker}-$FORGE_APP_ENV`, | |
| 1344 | }, | |
| 1345 | }, | |
| 1346 | null, | |
| 1347 | 2, | |
| 1348 | )}\n`, | |
| 1349 | }, | |
| 1350 | ], | |
| 1351 | }); | |
| 1352 | expect(committed.ok).toBe(true); | |
| 1353 | if (!committed.ok) return; | |
| 1354 | const opened = await openPull(app, alice, repo, { | |
| 1355 | title: "Slow test", | |
| 1356 | baseBranch: repo.defaultBranch, | |
| 1357 | headBranch: "slow-test", | |
| 1358 | }); | |
| 1359 | expect(opened.ok).toBe(true); | |
| 1360 | if (!opened.ok) return; | |
| 1361 | ||
| 1362 | // Wait for the app to answer — well before the test step's sleep ends. | |
| 1363 | const upDeadline = Date.now() + 10_000; | |
| 1364 | let up = false; | |
| 1365 | while (Date.now() < upDeadline) { | |
| 1366 | if ( | |
| 1367 | (await viaHost(`slowtest--${opened.value.number}.${DOMAIN}`)) | |
| 1368 | .status === 200 | |
| 1369 | ) { | |
| 1370 | up = true; | |
| 1371 | break; | |
| 1372 | } | |
| 1373 | await Bun.sleep(50); | |
| 1374 | } | |
| 1375 | expect(up).toBe(true); | |
| 1376 | ||
| 1377 | // Close it while the test step is still sleeping. | |
| 1378 | const closed = await mergePull( | |
| 1379 | app, | |
| 1380 | alice, | |
| 1381 | repo, | |
| 1382 | getPull(app.db, repo.id, opened.value.number)!, | |
| 1383 | "merge", | |
| 1384 | ); | |
| 1385 | expect(closed.ok).toBe(true); | |
| 1386 | ||
| 1387 | // Wait well past the sleep the test step was doing, and confirm it | |
| 1388 | // never finished: the preview's own marker is not there (production's, | |
| 1389 | // from its own unrelated redeploy of the same merged commit, may be). | |
| 1390 | await Bun.sleep(6_500); | |
| 1391 | expect(existsSync(`${marker}-preview`)).toBe(false); | |
| 1392 | }, 60_000); | |
| 1393 | ||
| 1394 | 1131 | test("private grant: forged, tampered, expired, wrong-env, and open-redirect are all refused; cookie is HttpOnly/SameSite", async () => { |
| 1395 | 1132 | const made = await newApp(app, alice, { |
| 1396 | 1133 | name: "grants", |
| @@ -2008,110 +1745,6 @@ describe("apps adversarial: teardown races, grants, the proxy, and rule 1/4", () | ||
| 2008 | 1745 | }, 30_000); |
| 2009 | 1746 | }); |
| 2010 | 1747 | |
| 2011 | describe("boot: a forge addressed by IP hands every app a host that works (issue #269)", () => { | |
| 2012 | let dataDir: string; | |
| 2013 | let work: string; | |
| 2014 | let app: App; | |
| 2015 | let servers: Servers; | |
| 2016 | let runtime: AppsRuntime; | |
| 2017 | let alice: User; | |
| 2018 | let domain: string; | |
| 2019 | ||
| 2020 | const viaHost = (host: string, path = "/", init: RequestInit = {}) => | |
| 2021 | fetch(`${servers.url}${path}`, { | |
| 2022 | ...init, | |
| 2023 | headers: { ...(init.headers as Record<string, string>), host }, | |
| 2024 | redirect: "manual", | |
| 2025 | }); | |
| 2026 | ||
| 2027 | async function settled( | |
| 2028 | repoId: string, | |
| 2029 | where: (run: Run) => boolean, | |
| 2030 | timeoutMs = 60_000, | |
| 2031 | ): Promise<Run> { | |
| 2032 | const deadline = Date.now() + timeoutMs; | |
| 2033 | while (Date.now() < deadline) { | |
| 2034 | const run = listRuns(app.db, repoId, { kind: "deploy", limit: 50 }).find( | |
| 2035 | where, | |
| 2036 | ); | |
| 2037 | if ( | |
| 2038 | run && | |
| 2039 | (run.state === "ok" || | |
| 2040 | run.state === "failed" || | |
| 2041 | run.state === "cancelled") | |
| 2042 | ) | |
| 2043 | return run; | |
| 2044 | await Bun.sleep(50); | |
| 2045 | } | |
| 2046 | throw new Error("run did not settle in time"); | |
| 2047 | } | |
| 2048 | ||
| 2049 | beforeAll(async () => { | |
| 2050 | dataDir = await mkdtemp(join(tmpdir(), "forge-ip-")); | |
| 2051 | work = await mkdtemp(join(tmpdir(), "forge-ip-work-")); | |
| 2052 | app = createApp({ dataDir, port: 0 }); | |
| 2053 | servers = await serve(app); | |
| 2054 | // The exact computation main.ts does at boot, for a forge reached at | |
| 2055 | // `http://127.0.0.1:<port>` with no FORGE_APP_DOMAIN set — the report in | |
| 2056 | // the issue. Before this fix, the domain below was `127.0.0.1` and every | |
| 2057 | // app's FORGE_APP_URL failed `new URL()` before it ever answered. | |
| 2058 | const resolved = resolveAppDomain({ | |
| 2059 | explicit: undefined, | |
| 2060 | hosted: false, | |
| 2061 | hostname: "127.0.0.1", | |
| 2062 | }); | |
| 2063 | expect(resolved.ok).toBe(true); | |
| 2064 | if (!resolved.ok) throw new Error(resolved.reason); | |
| 2065 | domain = resolved.domain; | |
| 2066 | runtime = new AppsRuntime(app, { | |
| 2067 | domain, | |
| 2068 | scheme: "http", | |
| 2069 | publicPort: servers.port, | |
| 2070 | forgeUrl: servers.url, | |
| 2071 | concurrency: 2, | |
| 2072 | }); | |
| 2073 | await runtime.start(); | |
| 2074 | const created = await createUser(app.db, { trusted: true, | |
| 2075 | username: "alice", | |
| 2076 | email: "[email protected]", | |
| 2077 | password: "a-good-passphrase", | |
| 2078 | adminIfFirst: true, | |
| 2079 | }); | |
| 2080 | if (!created.ok) throw new Error(created.error); | |
| 2081 | alice = created.value; | |
| 2082 | }, 30_000); | |
| 2083 | ||
| 2084 | afterAll(async () => { | |
| 2085 | await runtime.stop(); | |
| 2086 | servers.stop(); | |
| 2087 | app.close(); | |
| 2088 | await rm(dataDir, { recursive: true, force: true }); | |
| 2089 | await rm(work, { recursive: true, force: true }); | |
| 2090 | }); | |
| 2091 | ||
| 2092 | test("the scaffolded app deploys and answers — never the FORGE_APP_URL crash loop", async () => { | |
| 2093 | const made = await newApp(app, alice, { | |
| 2094 | name: "ip-forge", | |
| 2095 | visibility: "public", | |
| 2096 | }); | |
| 2097 | expect(made.ok).toBe(true); | |
| 2098 | if (!made.ok) return; | |
| 2099 | const repo = made.value.repo; | |
| 2100 | const record = made.value.app; | |
| 2101 | const run = await settled(repo.id, (r) => r.env === "production"); | |
| 2102 | // Before this fix: "start: exited with code 1 before answering" — the | |
| 2103 | // scaffold's own src/env.ts throwing on `new URL(FORGE_APP_URL)`. | |
| 2104 | expect(run.state).toBe("ok"); | |
| 2105 | const url = runtime.urlFor(record, "production"); | |
| 2106 | // The exact check the scaffold makes at import time on FORGE_APP_URL. | |
| 2107 | expect(() => new URL(url)).not.toThrow(); | |
| 2108 | const host = new URL(url).host; | |
| 2109 | const page = await viaHost(host); | |
| 2110 | expect(page.status).toBe(200); | |
| 2111 | expect(await page.text()).toContain("<h1>ip-forge</h1>"); | |
| 2112 | }, 90_000); | |
| 2113 | }); | |
| 2114 | ||
| 2115 | 1748 | describe("manifest: service kind", () => { |
| 2116 | 1749 | const svc = (app: object) => |
| 2117 | 1750 | parseManifest( |
new above
offline
The imports from here down are largely unused (appHostSuffix, domainHoldsAppHosts, the crew, tokens, runs-log and proxy imports, and others). Trim them to what these five tests use.