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

Production deploys stop interrupting people: batched (one per 15 min), not while busy, and swapped with zero downtime #16867

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/3967-production-deploys-stop-interrupting-peo → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/3967-production-deploys-stop-interrupting-peo was merged into main as b8689ca.

Review

Sign in to review this change.
13 files changed +639 −3
docs/APPS.md +26
@@ -559,6 +559,32 @@ a pick happened and `plan: null` otherwise, planning being unavailable included.
559559
560560 A template repository's `forge.json` may carry `"firstAsk": "…"`: 1 to 280 characters of plain text (anything else makes the file invalid). A forge made from the template files it as its first tell on first boot, and the template's page shows it (`docs/features/first-ask.md`).
561561
562 ## Production deploys are paced
563
564 A push or merge to the default branch does not restart production at once: every restart drops
565 each viewer's websocket and the driver's control. Production deploys at most once per
566 `app.deploy.every` minutes (default 15, counted from when the running version began serving),
567 always the newest commit, so landings in between ride the next batch; previews stay immediate.
568 It also waits for a safe moment: no stream open through the proxy, no child still working, and,
569 when the app declares `app.deploy.busy` (a path), that path answering 200 rather than 409 (say,
570 while someone is driving). After `app.deploy.maxWait` minutes (default 10) of busy it deploys
571 anyway and the run log says so. A restart, an out-of-memory restart and a redeploy someone asked
572 for are never held. `FORGE_DEPLOY_EVERY_MIN` and `FORGE_DEPLOY_MAX_WAIT_MIN` set the forge-wide
573 defaults; `0` for `every` turns batching off. A deploy already started the usual way: the new
574 process serves before the old one is stopped, requests the old one took are answered, and its
575 websockets are told to reconnect (`apps/handoff.ts`, #4496). That is not changed here, and this
576 pacing does not claim zero downtime.
577
578 The forge's own release (not an app's deploy) also waits, for at most two hours, until no full
579 check of the default branch is running, because a swap aborts it and it would start again from
580 nothing (`release/main_check_idle.ts`). Past two hours it swaps anyway, which can still cut off
581 a check that runs back to back; resuming the check across a swap is the proper fix and is left
582 out.
583
584 ```json
585 { "app": { "run": "bun src/app.ts", "deploy": { "every": 15, "maxWait": 10, "busy": "/busy" } } }
586 ```
587
562588 ## How an app is declared
563589
564590 The repository says how to run itself, in `forge.json` at its root:
src/apps/deploy_hold.ts added +125
@@ -0,0 +1,125 @@
1 /**
2 * When a production deploy may go ahead. A push or merge to the default branch asks for one,
3 * but every restart drops each viewer's websocket and the driver's control, so production
4 * deploys are batched and polite:
5 *
6 * - at most one per `every` (default 15 min, `forge.json` `app.deploy.every`), counted from when
7 * the running version began serving; landings in between ride the next batch, and the batch
8 * deploys the newest commit (a later request supersedes the held one);
9 * - not while the app says it is busy: a stream open through the proxy, a child still working,
10 * or its own `app.deploy.busy` path answering 409. After `maxWait` (default 10 min) of that,
11 * it deploys anyway and the run log says so.
12 *
13 * Only reasons a ref moving gives are held; a restart, a redeploy someone asked for, boot and
14 * previews go ahead at once. The deploy itself is the usual one: the new process serves before
15 * the old one is stopped (`apps/handoff.ts`).
16 */
17
18 import type { AppManifest } from "./manifest.ts";
19
20 export const DEPLOY_EVERY_MS = 15 * 60_000;
21 export const DEPLOY_MAX_WAIT_MS = 10 * 60_000;
22 const POLL_MS = 1_000;
23
24 /**
25 * The reasons a landing gives; the rest are someone's or the forge's own ask and are never held.
26 */
27 const HELD = new Set(["push", "merge"]);
28
29 export interface DeployPolicy {
30 readonly everyMs: number;
31 readonly maxWaitMs: number;
32 /** A path on the app answering 200 when a restart is safe, 409 while busy. */
33 readonly busyPath?: string | undefined;
34 }
35
36 /** The policy a manifest declares, over the defaults (or the overrides a test passes). */
37 export function deployPolicy(
38 manifest: AppManifest | undefined,
39 base: { everyMs?: number | undefined; maxWaitMs?: number | undefined } = {},
40 ): DeployPolicy {
41 const declared = manifest?.deploy;
42 return {
43 everyMs: declared?.everyMs ?? base.everyMs ?? DEPLOY_EVERY_MS,
44 maxWaitMs: declared?.maxWaitMs ?? base.maxWaitMs ?? DEPLOY_MAX_WAIT_MS,
45 busyPath: declared?.busy,
46 };
47 }
48
49 /** Whether a deploy for `reason` may be held at all. */
50 export function isHeldReason(reason: string): boolean {
51 return HELD.has(reason);
52 }
53
54 /** When the batch window opens: `every` after the running version began serving. */
55 export function windowOpensAt(servedAtMs: number, policy: DeployPolicy): number {
56 return servedAtMs + policy.everyMs;
57 }
58
59 export interface HoldInput {
60 readonly policy: DeployPolicy;
61 /** When the running version began serving; undefined when nothing runs (nothing to protect). */
62 readonly servedAtMs: number | undefined;
63 /** Still the run to execute? False once a newer request replaced it, or the forge stops. */
64 readonly current: () => boolean;
65 /** A reason the app is busy, or undefined when it is safe to restart. */
66 readonly busy: () => Promise<string | undefined>;
67 readonly now: () => number;
68 readonly sleep: (ms: number) => Promise<void>;
69 readonly say: (line: string) => void;
70 readonly pollMs?: number | undefined;
71 }
72
73 /**
74 * Wait for the batch window, then for a safe moment. True to deploy now, false when this run
75 * was superseded (the newer one carries the work).
76 */
77 export async function holdDeploy(input: HoldInput): Promise<boolean> {
78 const { policy, now, sleep, say } = input;
79 const poll = input.pollMs ?? POLL_MS;
80 if (input.servedAtMs === undefined) return input.current();
81 const opens = windowOpensAt(input.servedAtMs, policy);
82 let announced = false;
83 while (input.current() && now() < opens) {
84 if (!announced) {
85 const at = new Date(opens).toISOString().slice(11, 16);
86 say(`held for the next production deploy at ${at}Z: one per ${Math.round(policy.everyMs / 60_000)} min, landings in between ride it`);
87 announced = true;
88 }
89 await sleep(Math.min(poll, Math.max(1, opens - now())));
90 }
91 const waitFrom = Math.max(now(), opens);
92 let told = false;
93 while (input.current()) {
94 const busy = await input.busy();
95 if (busy === undefined) return true;
96 if (now() - waitFrom >= policy.maxWaitMs) {
97 say(`deploying anyway: still ${busy} after ${Math.round(policy.maxWaitMs / 60_000)} min`);
98 return true;
99 }
100 if (!told) {
101 say(`waiting for a safe moment: ${busy}`);
102 told = true;
103 }
104 await sleep(poll);
105 }
106 return false;
107 }
108
109 /** Ask an app's own busy path: a 409 is busy, anything else (even no answer) is safe. */
110 export async function askBusyPath(
111 port: number,
112 path: string,
113 get: typeof fetch = fetch,
114 ): Promise<string | undefined> {
115 try {
116 const response = await get(`http://127.0.0.1:${port}${path}`, {
117 signal: AbortSignal.timeout(2_000),
118 redirect: "manual",
119 });
120 await response.body?.cancel();
121 return response.status === 409 ? `its ${path} says it is busy` : undefined;
122 } catch {
123 return undefined;
124 }
125 }
src/apps/manifest.ts +35
@@ -83,6 +83,12 @@ export interface AppManifest {
8383 * cell's proxy (`apps/contain.ts`). Empty when nothing is declared.
8484 */
8585 readonly egress?: readonly string[] | undefined;
86 /**
87 * `app.deploy`: how production deploys of this app are paced (`apps/deploy_hold.ts`): `every`
88 * minutes between them (0 = each landing deploys), `maxWait` minutes to wait for a safe
89 * moment, `busy` a path answering 200 when a restart is safe and 409 while busy.
90 */
91 readonly deploy?: DeclaredDeploy | undefined;
8692 /** `app.limits`: the app process's memory, CPU and disk, within the machine's maximum. */
8793 readonly limits?: DeclaredLimits | undefined;
8894 /**
@@ -119,6 +125,32 @@ export interface AppManifest {
119125 readonly beat?: BeatSpec | undefined;
120126 }
121127
128 export interface DeclaredDeploy {
129 readonly everyMs?: number | undefined;
130 readonly maxWaitMs?: number | undefined;
131 readonly busy?: string | undefined;
132 }
133
134 /** `app.deploy`: `{ every, maxWait, busy }`, each optional. */
135 function deployField(app: Json): Result<DeclaredDeploy | undefined, ManifestError> {
136 const value = app["deploy"];
137 if (value === undefined) return ok(undefined);
138 if (!isObject(value)) return invalid("forge.json: app.deploy must be an object");
139 const out: { everyMs?: number; maxWaitMs?: number; busy?: string } = {};
140 for (const [field, raw] of Object.entries(value)) {
141 if (field === "every" || field === "maxWait") {
142 if (typeof raw !== "number" || !(raw >= 0 && raw <= 1440))
143 return invalid(`forge.json: app.deploy.${field} must be a number of minutes, 0–1440`);
144 out[field === "every" ? "everyMs" : "maxWaitMs"] = raw * 60_000;
145 } else if (field === "busy") {
146 if (typeof raw !== "string" || !/^\/[\x21-\x7e]{0,199}$/.test(raw))
147 return invalid("forge.json: app.deploy.busy must be a path starting with /");
148 out.busy = raw;
149 } else return invalid(`forge.json: app.deploy takes every, maxWait and busy, not ${field}`);
150 }
151 return ok(out);
152 }
153
122154 export type ManifestError =
123155 /** Neither `forge.json` nor a `package.json` start script. */
124156 | { readonly kind: "not_an_app" }
@@ -224,6 +256,8 @@ export function parseManifest(
224256 if (!egress.ok) return egress;
225257 const limits = limitsField(app, "app");
226258 if (!limits.ok) return limits;
259 const deploy = deployField(app);
260 if (!deploy.ok) return deploy;
227261 const needs = parseNeeds(parsed.value["env"]);
228262 if (!needs.ok) return invalid(needs.error);
229263 const toolbar = parsed.value["toolbar"];
@@ -286,6 +320,7 @@ export function parseManifest(
286320 service,
287321 egress: egress.value,
288322 limits: limits.value,
323 ...(deploy.value === undefined ? {} : { deploy: deploy.value }),
289324 toolbar: toolbar ?? true,
290325 ...(sync === true ? { sync: true as const } : {}),
291326 ...(needs.value.length === 0 ? {} : { env: needs.value }),
src/apps/runtime_env.ts +7
@@ -73,6 +73,13 @@ export interface RuntimeOptions {
7373 * that only claims to be busy cannot stay up forever.
7474 */
7575 readonly busyGraceMs?: number | undefined;
76 /**
77 * Production deploys' pace when a manifest does not say (`apps/deploy_hold.ts`); main sets 15 and
78 * 10 minutes, unset here is no batching.
79 */
80 readonly deployEveryMs?: number | undefined;
81 readonly deployMaxWaitMs?: number | undefined;
82 readonly deployPollMs?: number | undefined;
7683 /**
7784 * What a domain check asks: the system resolver unless a test hands in
7885 * its own, so proving `app.example.com` needs no network in a test.
src/apps/runtime_events.ts +34 −1
@@ -29,7 +29,11 @@ import { previewCommit } from "../git/combined.ts";
2929 import { readFileAt } from "./checkout.ts";
3030 import { appsRoot, variantEnv, envPull, isEnvName, previewEnv, type EnvName } from "./data.ts";
3131 import type { AppsRuntime } from "./runtime.ts";
32 import { log, AGAIN, key } from "./runtime_env.ts";
32 import { log, AGAIN, key, type Environment } from "./runtime_env.ts";
33 import { askBusyPath, deployPolicy, holdDeploy, isHeldReason } from "./deploy_hold.ts";
34 import { BUSY_WORDS, busyReason } from "./busy.ts";
35 import { appendRunLog } from "../runs/log.ts";
36 import { during } from "../perf/jobs.ts";
3337
3438 /**
3539 * At boot, remove checkouts no deployment serves, rests on or is making: what a failed or
@@ -341,12 +345,41 @@ export function requestDeploy(
341345 if (reason === "boot" && env === "production") rt.bootRuns.set(state, run.id);
342346 state.chain = state.chain.then(async () => {
343347 if (state.queued?.id !== run.id) return; // superseded
348 if (env === "production" && isHeldReason(reason) && !(await holdProduction(rt, state, run)))

This wiring (held reasons, supersession, busy state) has no test through the real runtime. Add one with a short window; the unit tests only cover holdDeploy.

349 return; // a newer landing carries the work
350 if (state.queued?.id !== run.id) return;
344351 state.queued = undefined;
345352 await rt.execute(state, repo, run);
346353 });
347354 return run;
348355 }
349356
357 /** Wait out the batch window and a busy app (`apps/deploy_hold.ts`); false when superseded. */
358 async function holdProduction(rt: AppsRuntime, state: Environment, run: Run): Promise<boolean> {
359 const live = state.live;
360 const policy = deployPolicy(live?.manifest, {
361 everyMs: rt.options.deployEveryMs ?? 0,
362 maxWaitMs: rt.options.deployMaxWaitMs,
363 });
364 const servedAt = live === undefined ? undefined : Date.parse(live.servingAt ?? live.since);
365 return holdDeploy({
366 policy,
367 servedAtMs: servedAt === undefined || Number.isNaN(servedAt) ? undefined : servedAt,
368 current: () => !rt.stopped && state.queued?.id === run.id,
369 busy: async () => {
370 const l = state.live;
371 if (l === undefined) return undefined;
372 const reason = busyReason(l.handle.pid, state.openStreams, state.openRequests);
373 if (reason !== undefined) return BUSY_WORDS[reason];
374 return policy.busyPath === undefined ? undefined : askBusyPath(l.handle.port, policy.busyPath);
375 },
376 now: () => rt.now(),
377 sleep: (ms) => new Promise<void>((done) => { setTimeout(() => during("deploy-hold", done), ms).unref(); }),
378 say: (line) => appendRunLog(rt.app.config.dataDir, run.id, line),
379 pollMs: rt.options.deployPollMs,
380 });
381 }
382
350383 /**
351384 * A pull's preview at `head`, after a push, an opening or an approval. One that something asks
352385 * for at the push (`apps/prepared.ts`), or that is up or coming up already, deploys the
src/checks/landing.ts +14 −2
@@ -23,6 +23,7 @@ import {
2323 type Verdict,
2424 pruneReleases,
2525 } from "../release/checkout.ts";
26 import { mainCheckRunning, untilMainIdle } from "../release/main_check_idle.ts";
2627 import { beginSwap, endSwap, handover, startRelease } from "../release/swap.ts";
2728 import { running } from "../kernel/version.ts";
2829 import { noteReleased } from "../crew/note_closed.ts";
@@ -254,8 +255,15 @@ async function cutTree(
254255 export interface DeployDeps {
255256 readonly wait: typeof waitForCheck;
256257 readonly swap: (app: App, by: User, repo: Repo, pull: Pull, sha: string, dir: string) => Promise<void>;
258 /**
259 * Resolves when no full check of main is running (a swap would cut it off); default polls the
260 * runs.
261 */
262 readonly idle?: (app: App, repo: Repo) => Promise<unknown>;
257263 }
258 const realDeps: DeployDeps = { wait: waitForCheck, swap: (...a) => swapIn(...a) };
264 const mainIdle: NonNullable<DeployDeps["idle"]> = (app, repo) =>
265 untilMainIdle({ running: () => mainCheckRunning(app.db, repo.id, repo.defaultBranch) });
266 const realDeps: DeployDeps = { wait: waitForCheck, swap: (...a) => swapIn(...a), idle: mainIdle };
259267
260268 /**
261269 * Swap in only on a green check of the commit; red, superseded or late is a log line and, when
@@ -281,7 +289,11 @@ export async function deployWhenChecked(
281289 checks: checksFor(app) !== undefined,
282290 ...(budgetMs === undefined ? {} : { budgetMs }),
283291 });
284 if (waited.ok) return deps.swap(app, by, repo, pull, sha, dir);
292 if (waited.ok) {
293 // Never cut off main's full check already running: release between main verdicts.
294 await (deps.idle ?? mainIdle)(app, repo);
295 return deps.swap(app, by, repo, pull, sha, dir);
296 }
outdated

The realDeps.idle! non-null assertion is a smell. Make idle required or default it once. The 2 h hold itself is a new cap; justify it or avoid aborting the check on swap.

285297 app.log.warn("release not swapped in: check not green", { sha: sha.slice(0, 12), line: waited.line });
286298 if (tell)
287299 addComment(
src/main.ts +11
@@ -5,6 +5,7 @@
55 */
66
77 import "./kernel/bun_guard.ts";
outdated

Import placed before ./kernel/bun_guard.ts; the guard must run first. Move it below.

8 import { DEPLOY_EVERY_MS, DEPLOY_MAX_WAIT_MS } from "./apps/deploy_hold.ts";
89 import { join } from "node:path";
910 import { sweepEntitlements } from "./billing/sync.ts";
1011 import { sweepDesk } from "./actions/desk.ts";
@@ -619,6 +620,9 @@ const apps = appDomain?.ok
619620 forgeUrl,
620621 concurrency: positive(process.env.FORGE_APPS_CONCURRENCY, 2),
621622 busyGraceMs: crewRunMs,
623 // Production deploys: one per this many minutes, waiting at most so long for a safe moment.
624 deployEveryMs: minutes(process.env.FORGE_DEPLOY_EVERY_MIN, DEPLOY_EVERY_MS / 60_000) * 60_000,
625 deployMaxWaitMs: positive(process.env.FORGE_DEPLOY_MAX_WAIT_MIN, DEPLOY_MAX_WAIT_MS / 60_000) * 60_000,
622626 upstreamWaitMs: positive(process.env.FORGE_UPSTREAM_WAIT_MS, UPSTREAM_WAIT_MS),
623627 // Days a pull may sit untouched before its preview sleeps; 0 keeps
624628 // every preview warm. Unset follows the profit slider, live.
@@ -867,6 +871,13 @@ app.log.info(`engine shape: ${shapeWords({ ...engineShape, mode: split !== undef
867871 why: app.config.engine?.why ?? engineShape.why,
868872 });
869873
874 /** Minutes, where 0 is a real answer (no batching); anything unreadable is the fallback. */
875 function minutes(value: string | undefined, fallback: number): number {
876 if (value === undefined || value.trim() === "") return fallback;
877 const parsed = Number(value);
878 return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
879 }
880
870881 function positive(value: string | undefined, fallback: number): number {
871882 const parsed = Number(value);
872883 return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback;
src/release/main_check_idle.ts added +47
@@ -0,0 +1,47 @@
1 /**
2 * A release swaps the process, and a swap aborts every check running here: the check is queued
3 * again and starts from nothing (`interrupted by a release; queued again`). With a release every
4 * few minutes, main's full check (about an hour) would never finish. So a release waits for the
5 * moment between main verdicts: no full check of the default branch is running.
6 *
7 * Bounded: past `maxMs` the release goes ahead, so a check that hangs cannot hold every release.
8 */
9
10 import type { Database } from "bun:sqlite";
11 import { during } from "../perf/jobs.ts";
12
13 export const MAIN_CHECK_WAIT_MS = 2 * 60 * 60_000;
14 const POLL_MS = 15_000;
15
16 /** Whether the default branch's full check (never a pull's fast tier) is running now. */
17 export function mainCheckRunning(db: Database, repoId: string, branch: string): boolean {
18 return (
19 db
20 .query(
21 `SELECT 1 FROM run
22 WHERE repo_id = ?1 AND kind = 'check' AND issue_id IS NULL AND env = ?2 AND state = 'running'
23 LIMIT 1`,
24 )
25 .get(repoId, branch) !== null
26 );
27 }
28
29 export interface IdleInput {
30 readonly running: () => boolean;
31 readonly sleep?: (ms: number) => Promise<void>;
32 readonly now?: () => number;
33 readonly maxMs?: number;
34 readonly pollMs?: number;
35 }
36
37 /** Resolves true once no main check runs, false when `maxMs` passed first. */
38 export async function untilMainIdle(input: IdleInput): Promise<boolean> {
39 const sleep = input.sleep ?? ((ms: number) => new Promise<void>((done) => { setTimeout(() => during("release-main-idle", done), ms).unref(); }));
40 const now = input.now ?? Date.now;
41 const until = now() + (input.maxMs ?? MAIN_CHECK_WAIT_MS);
42 while (input.running()) {
43 if (now() >= until) return false;
44 await sleep(input.pollMs ?? POLL_MS);
45 }
46 return true;
47 }
test/apps-token.test.ts +2
@@ -233,6 +233,8 @@ describe("app tokens: live, end to end", () => {
233233 publicPort: servers.port,
234234 forgeUrl: servers.url,
235235 sweepEveryMs: 20,
236 // The test deploys under an open stream on purpose: do not wait for a safe moment.
237 deployMaxWaitMs: 0,
236238 clock: () => Date.now() + skew,
237239 });
238240 await runtime.start();
test/deploy-hold-runtime.test.ts added +145
@@ -0,0 +1,145 @@
1 /**
2 * Production deploys are held through the real runtime (`holdProduction` in
3 * apps/runtime_events.ts):
4 * a push waits for the batch window and for an open stream to close, a newer landing replaces the
5 * held one, and a redeploy someone asked for goes ahead at once. Short windows, no fake clock: the
6 * wiring is what is under test, `holdDeploy` itself has its own suite (deploy-hold.test.ts).
7 */
8 import { afterAll, beforeAll, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { AppsRuntime } from "../src/apps/runtime.ts";
14 import { newApp } from "../src/actions/apps.ts";
15 import { commitToBranch } from "../src/actions/repos.ts";
16 import type { AppRecord } from "../src/core/apps.ts";
17 import type { Repo } from "../src/core/repos.ts";
18 import { listRuns, type Run } from "../src/core/runs.ts";
19 import type { User } from "../src/core/users.ts";
20 import { seedAdmin } from "./helpers/admin.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22 import { readRunLog } from "../src/runs/log.ts";
23
24 const server = (version: string) => `const port = Number(process.env.PORT ?? "0");
25 export const server = Bun.serve({
26 port,
27 fetch(request) {
28 const url = new URL(request.url);
29 if (url.pathname === "/stream") {
30 let timer: ReturnType<typeof setInterval> | undefined;
31 return new Response(new ReadableStream({
32 start(c) { c.enqueue(new TextEncoder().encode("data: hello\\n\\n")); timer = setInterval(() => c.enqueue(new TextEncoder().encode(": tick\\n\\n")), 100); },
33 cancel() { clearInterval(timer); },
34 }), { headers: { "content-type": "text/event-stream" } });
35 }
36 return new Response("${version}");
37 },
38 });
39 `;
40 const TEST = `import { expect, test } from "bun:test";
41 process.env.PORT = "0"; // env-restored: this line is text committed to the app repository, not this process
42 const { server } = await import("./server.ts");
43 test("serves", async () => {
44 expect((await fetch(\`http://\${server.hostname}:\${server.port}/\`)).status).toBe(200);
45 });
46 `;
47 const SCAFFOLD_TESTS = ["src/audit.test.ts", "src/openapi.test.ts", "src/security.test.ts", "src/site.test.ts"].map((path) => ({ path, content: null }));
48
49 let dataDir: string;
50 let app: App;
51 let servers: Servers;
52 let runtime: AppsRuntime;
53 let alice: User;
54 let repo: Repo;
55 let record: AppRecord;
56 const HOST = "held.apps.test";
57
58 const viaHost = (path: string, init: RequestInit = {}) => fetch(`${servers.url}${path}`, { ...init, headers: { host: HOST } });
59 const runOf = (oid: string, reason?: string): Run | undefined =>
60 listRuns(app.db, repo.id, { kind: "deploy", limit: 50 }).find((r) => r.env === "production" && r.commitOid === oid && (reason === undefined || r.reason === reason));
61 const log = (run: Run): string => readRunLog(dataDir, run.id, 64 * 1024).lines.join("\n");
62 async function until<T>(read: () => T | undefined, ms = 60_000): Promise<T> {
63 const deadline = Date.now() + ms;
64 while (Date.now() < deadline) {
65 const v = read();
66 if (v !== undefined) return v;
67 await new Promise((r) => setImmediate(r));
68 }
69 throw new Error("did not happen in time");
70 }
71 const finished = (oid: string, reason?: string) => until(() => { const r = runOf(oid, reason); return r !== undefined && ["ok", "failed", "cancelled"].includes(r.state) ? r : undefined; });
72 async function land(version: string): Promise<string> {
73 const c = await commitToBranch(app, alice, repo, { message: `serve ${version}`, files: [{ path: "src/server.ts", content: server(version) }, { path: "src/server.test.ts", content: TEST }, ...SCAFFOLD_TESTS] });
74 if (!c.ok) throw new Error(String(c.error));
75 return c.value.commitOid;
76 }
77 async function openStream() {
78 const abort = new AbortController();
79 const response = await viaHost("/stream", { signal: abort.signal });
80 const reader = response.body!.getReader();
81 await reader.read();
82 return async () => { abort.abort(); await reader.cancel().catch(() => {}); };
83 }
84
85 beforeAll(async () => {
86 dataDir = await mkdtemp(join(tmpdir(), "forge-deploy-hold-"));
87 app = createApp({ dataDir, port: 0 });
88 servers = await serve(app);
89 runtime = new AppsRuntime(app, {
90 domain: "apps.test", scheme: "http", publicPort: servers.port, forgeUrl: servers.url,
91 // A short window and a quick poll; a long maxWait, so only the open stream can hold a deploy.
92 deployEveryMs: 300, deployPollMs: 20, deployMaxWaitMs: 120_000,
93 });
94 await runtime.start();
95 const u = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-good-passphrase" });
96 if (!u.ok) throw new Error(u.error);
97 alice = u.value;
98 const made = await newApp(app, alice, { name: "held", description: "Held deploys", visibility: "public" });
99 if (!made.ok) throw new Error(String(made.error));
100 repo = made.value.repo;
101 record = made.value.app;
102 await until(() => listRuns(app.db, repo.id, { kind: "deploy", limit: 50 }).find((r) => r.env === "production" && r.state === "ok"));
103 const first = await land("v1");
104 const done = await finished(first);
105 if (done.state !== "ok") throw new Error(`deploy failed: ${done.summary}`);
106 }, 240_000);
107
108 afterAll(async () => {
109 await runtime.stop();
110 servers.stop();
111 app.close();
112 await rm(dataDir, { recursive: true, force: true });
113 });
114
115 test("a redeploy someone asked for is not held, even under an open stream", async () => {
116 const close = await openStream();
117 const tip = runtime.status(record).find((e) => e.env === "production")!.commitOid!;
118 const run = runtime.requestDeploy(record, repo, "production", tip, "redeploy", alice.id);
119 const done = await finished(tip, "redeploy");
120 expect(run).toBeDefined();
121 expect(done.id).toBe(run!.id);
122 expect(done.state).toBe("ok");
123 expect(log(done)).not.toContain("held for");
124 expect(log(done)).not.toContain("safe moment");
125 await close();
126 });
127
128 test("a push waits for the open stream, and a newer landing replaces the held one", async () => {
129 const close = await openStream();
130 const a = await land("v2");
131 const b = await land("v3");
132 // The window (0.3 s) passes with the stream still open: the newest landing waits for it.
133 await until(() => (log(runOf(b)!).includes("waiting for a safe moment") ? true : undefined));
134 expect(log(runOf(b)!)).toContain("stream");
135 expect(["queued", "running"]).toContain(runOf(b)!.state);
136 // The older landing was replaced, never deployed.
137 const older = await finished(a);
138 expect(older.state).toBe("cancelled");
139 expect(older.summary).toContain("superseded");
140 // The stream closes: the newest goes ahead and serves.
141 await close();
142 const newest = await finished(b);
143 expect(`${newest.state}: ${newest.summary}\n${log(newest)}`).toStartWith("ok");
144 expect(await (await viaHost("/")).text()).toBe("v3");
145 }, 120_000);
test/deploy-hold.test.ts added +114
@@ -0,0 +1,114 @@
1 /**
2 * Production deploys are batched (one per window, the newest commit), wait for a safe moment
3 * for at most maxWait, and a manifest can declare the pace (`apps/deploy_hold.ts`).
4 */
5 import { describe, expect, test } from "bun:test";
6 import { askBusyPath, deployPolicy, holdDeploy, isHeldReason } from "../src/apps/deploy_hold.ts";
7 import { parseManifest } from "../src/apps/manifest.ts";
8
9 const MIN = 60_000;
10
11 /** A fake clock whose sleep only advances time. */
12 function clock(start = 0) {
13 let t = start;
14 return { now: () => t, sleep: async (ms: number) => void (t += ms), at: () => t };
15 }
16
17 describe("holdDeploy", () => {
18 const policy = { everyMs: 15 * MIN, maxWaitMs: 10 * MIN };
19
20 test("ten landings in five minutes deploy once, the newest, at the window's end", async () => {
21 // Virtual time: a sleep parks until the driver reaches its moment; landings arrive on the way.
22 let t = 0;
23 const timers: Array<{ at: number; wake: () => void }> = [];
24 const sleep = (ms: number) => new Promise<void>((wake) => timers.push({ at: t + ms, wake }));
25 let latest = -1;
26 const runs: Array<Promise<{ n: number; went: boolean; at: number }>> = [];
27 const land = (n: number) => {
28 latest = n; // a later request supersedes every earlier one
29 runs.push(holdDeploy({ policy, servedAtMs: 0, current: () => latest === n, busy: async () => undefined, now: () => t, sleep, say: () => {}, pollMs: 30_000 }).then((went) => ({ n, went, at: t })));
30 };
31 const settle = async () => { for (let i = 0; i < 10; i++) await Promise.resolve(); };
32 const step = async (until: number) => {
33 while (timers.some((x) => x.at <= until)) {
34 const next = timers.sort((a, b) => a.at - b.at).shift()!;
35 t = next.at;
36 next.wake();
37 await settle();
38 }
39 };
40 for (let n = 0; n < 10; n++) {
41 // Landing n arrives 30 s after the one before: all ten within five minutes.
42 await step(n * 30_000);
43 t = n * 30_000;
44 land(n);
45 await settle();
46 }
47 await step(Infinity);
48 const done = await Promise.all(runs);
49 expect(done.filter((r) => r.went).map((r) => r.n)).toEqual([9]);
50 expect(done.find((r) => r.went)!.at).toBeGreaterThanOrEqual(15 * MIN);
51 });
52
53 test("nothing running means nothing to protect: no wait", async () => {
54 const c = clock(0);
55 const ok = await holdDeploy({ policy, servedAtMs: undefined, current: () => true, busy: async () => "x", now: c.now, sleep: c.sleep, say: () => {} });
56 expect(ok).toBe(true);
57 expect(c.at()).toBe(0);
58 });
59
60 test("a busy app delays the deploy until idle", async () => {
61 const c = clock(20 * MIN);
62 let busyFor = 3;
63 const said: string[] = [];
64 const ok = await holdDeploy({
65 policy, servedAtMs: 0, current: () => true, now: c.now, sleep: c.sleep, say: (l) => said.push(l), pollMs: 1000,
66 busy: async () => (busyFor-- > 0 ? "someone is driving" : undefined),
67 });
68 expect(ok).toBe(true);
69 expect(c.at()).toBe(20 * MIN + 3000);
70 expect(said.join("\n")).toContain("someone is driving");
71 });
72
73 test("a busy app is deployed anyway after maxWait, and it says so", async () => {
74 const c = clock(20 * MIN);
75 const said: string[] = [];
76 const ok = await holdDeploy({ policy, servedAtMs: 0, current: () => true, busy: async () => "busy", now: c.now, sleep: c.sleep, say: (l) => said.push(l), pollMs: 10_000 });
77 expect(ok).toBe(true);
78 expect(c.at() - 20 * MIN).toBe(10 * MIN);
79 expect(said.at(-1)).toContain("deploying anyway");
80 });
81
82 test("a superseded run stops waiting", async () => {
83 const c = clock(0);
84 let calls = 0;
85 const ok = await holdDeploy({ policy, servedAtMs: 0, current: () => ++calls < 3, busy: async () => undefined, now: c.now, sleep: c.sleep, say: () => {} });
86 expect(ok).toBe(false);
87 });
88 });
89
90 describe("what is held", () => {
91 test("only a landing is held; a restart or a person's redeploy is not", () => {
92 expect(isHeldReason("push")).toBe(true);
93 expect(isHeldReason("merge")).toBe(true);
94 for (const r of ["restart", "oom", "boot", "redeploy", "moved"]) expect(isHeldReason(r)).toBe(false);
95 });
96
97 test("the manifest declares the pace and the defaults are 15 and 10 minutes", () => {
98 const m = parseManifest(JSON.stringify({ app: { run: "bun x", deploy: { every: 5, maxWait: 2, busy: "/busy" } } }), undefined);
99 expect(m.ok && m.value.deploy).toEqual({ everyMs: 5 * MIN, maxWaitMs: 2 * MIN, busy: "/busy" });
100 expect(deployPolicy(m.ok ? m.value : undefined).everyMs).toBe(5 * MIN);
101 expect(deployPolicy(undefined)).toMatchObject({ everyMs: 15 * MIN, maxWaitMs: 10 * MIN });
102 for (const bad of [{ every: -1 }, { busy: "x" }, { nope: 1 }, "x"]) {
103 const r = parseManifest(JSON.stringify({ app: { run: "bun x", deploy: bad } }), undefined);
104 expect(r.ok).toBe(false);
105 }
106 });
107
108 test("a 409 from the busy path is busy; 200 or no answer is safe", async () => {
109 const answer = (status: number) => (async () => new Response("", { status })) as unknown as typeof fetch;
110 expect(await askBusyPath(1, "/busy", answer(409))).toContain("busy");
111 expect(await askBusyPath(1, "/busy", answer(200))).toBeUndefined();
112 expect(await askBusyPath(1, "/busy", (async () => { throw new Error("down"); }) as unknown as typeof fetch)).toBeUndefined();
113 });
114 });
test/job-slices.test.ts +2
@@ -268,6 +268,8 @@ const UNTIMED: Record<string, string> = {
268268 "places-page-wait": "a one-shot timer in the new-forge page that only resolves the race when the Places catalog refresh outlives PAGE_WAIT_MS; no work of its own; new-forge-refresh.test.ts drives the refresh",
269269 "tell-origin-wait": "a one-shot timer that only resolves the race when an origin has not answered a copy's report in TELL_MS; no work of its own; copies-elsewhere.test.ts tells a forge that answers",
270270 "presence-ping": "a per-stream timer (one per open Talk or repository page) that only refreshes its own seat's time in an in-memory map (core/presence.ts stillHere): no query, no write; together.test.ts drives the seat it keeps",
271 "deploy-hold": "a one-shot timer in apps/runtime_events.ts that only resolves the sleep between a production deploy's looks for a safe moment; no work of its own; the deploy-batching tests drive it with a fake sleep",
272 "release-main-idle": "a one-shot timer in release/main_check_idle.ts that only resolves the sleep between a release's looks at main's running check; no work of its own; the release-wait tests inject the sleep",
271273 "deploy-permit-ceiling": "a one-shot timer armed per deploy that only aborts it and resolves the race when a deploy outlives 30 minutes; permit-ceiling.test.ts and deploy-permit-ceiling.test.ts drive it with a short ceiling",
272274 "upstream-wait": "a one-shot timer that only aborts one proxied request when its app sends no headers in 30 s; no work of its own, cleared when the headers arrive; the upstream-wait tests drive it with a short wait",
273275 "bring-wait": "a one-shot timer that only resolves a promise when a bring's mirror is still copying after 60 s, so the answer says it is copying (actions/bring.ts, bringToWork); no work of its own; talk-bring.test.ts brings a repository that settles first",
test/release-waits-for-main-check.test.ts added +77
@@ -0,0 +1,77 @@
1 /**
2 * A release never cuts off main's full check already running: it swaps between main verdicts
3 * (`release/main_check_idle.ts`), so releases every few minutes cannot starve main of a verdict.
4 */
5 import { expect, test } from "bun:test";
6 import { mkdtempSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp } from "../src/app.ts";
10 import { createRun, claimRun, finishRun } from "../src/core/runs.ts";
11 import { mainCheckRunning, untilMainIdle } from "../src/release/main_check_idle.ts";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { seedAdmin } from "./helpers/admin.ts";
14 import { deployWhenChecked, type DeployDeps } from "../src/checks/landing.ts";
15 import type { Pull } from "../src/core/pulls.ts";
16
17 const SHA = "c".repeat(40);
18
19 async function fixture() {
20 const app = createApp({ dataDir: mkdtempSync(join(tmpdir(), "forge-main-idle-")), port: 0, selfSwap: true, forgeRepo: "alice/forge-code" });
21 const u = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-good-passphrase" });
22 if (!u.ok) throw new Error("user");
23 const r = await createRepo(app, u.value, { name: "forge-code", visibility: "public" });
24 if (!r.ok) throw new Error("repo");
25 return { app, user: u.value, repo: r.value };
26 }
27
28 const startCheck = (f: Awaited<ReturnType<typeof fixture>>, env: string, issueId?: string) => {
29 const run = createRun(f.app.db, { repoId: f.repo.id, kind: "check", env, commitOid: "d".repeat(40), issueId });
30 claimRun(f.app.db, run.id);
31 return run;
32 };
33
34 test("only a running full check of the default branch counts", async () => {
35 const f = await fixture();
36 const b = f.repo.defaultBranch;
37 expect(mainCheckRunning(f.app.db, f.repo.id, b)).toBe(false);
38 startCheck(f, "other-branch");
39 expect(mainCheckRunning(f.app.db, f.repo.id, b)).toBe(false);
40 const run = startCheck(f, b);
41 expect(mainCheckRunning(f.app.db, f.repo.id, b)).toBe(true);
42 finishRun(f.app.db, run.id, { state: "ok", summary: "" });
43 expect(mainCheckRunning(f.app.db, f.repo.id, b)).toBe(false);
44 });
45
46 test("a release waits while main's check runs, then swaps", async () => {
47 const f = await fixture();
48 const b = f.repo.defaultBranch;
49 const run = startCheck(f, b);
50 const swaps: string[] = [];
51 const deps: DeployDeps = {
52 wait: async () => ({ ok: true }),
53 swap: async (_a, _b, _c, _d, sha) => void swaps.push(sha),
54 idle: (app, repo) =>
55 untilMainIdle({
56 running: () => mainCheckRunning(app.db, repo.id, repo.defaultBranch),
57 sleep: async () => void finishRun(app.db, run.id, { state: "ok", summary: "" }),
58 }),
59 };
60 const pull = { id: "x", number: 1 } as unknown as Pull;
61 const done = deployWhenChecked(f.app, f.user, f.repo, pull, SHA, "/x", deps);
62 await done;
63 // The swap came only after the check finished, never over it.
64 expect(swaps).toEqual([SHA]);
65 expect(mainCheckRunning(f.app.db, f.repo.id, b)).toBe(false);
66 });
67
68 test("the wait is bounded: a check that hangs cannot hold every release", async () => {
69 let t = 0;
70 const idle = await untilMainIdle({ running: () => true, now: () => t, sleep: async (ms) => void (t += ms), maxMs: 60_000, pollMs: 10_000 });
71 expect(idle).toBe(false);
72 expect(t).toBe(60_000);
73 });
74
75 test("with no main check running the release swaps at once", async () => {
76 expect(await untilMainIdle({ running: () => false, sleep: async () => { throw new Error("slept"); } })).toBe(true);
77 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs