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 #3974
torque/forge:torque/3967-production-deploys-stop-interrupting-peo → main 4 commits fork 2 threads · 2 unresolved
12 files
changed +877
−12
README.md +5
| @@ -1340,6 +1340,11 @@ crew may spend across every repository in a UTC day, whatever each | ||
| 1340 | 1340 | repository's own ceiling says; `FORGE_APPS=0` turns apps and crew off. A preview whose pull nobody has |
| 1341 | 1341 | pushed to or commented on for `FORGE_PREVIEW_IDLE_DAYS` (default 3; `0` keeps |
| 1342 | 1342 | every preview warm) is stopped and reads as asleep, and asking for it wakes it. |
| 1343 | Production deploys from landings are batched to one per | |
| 1344 | `FORGE_DEPLOY_EVERY_MIN` (default 15; `0` deploys every landing), held while | |
| 1345 | production is busy, and swapped without dropping a request (`docs/APPS.md`). | |
| 1346 | The window is kept in memory: a forge restart resets it and deploys | |
| 1347 | production on boot. | |
| 1343 | 1348 | An admin with more than one Claude account keeps them under Settings → |
| 1344 | 1349 | Subscriptions, sealed, and grants each to a repository (Settings → Crew) or |
| 1345 | 1350 | an organization (its page), down to one crew member: a work plan pays for |
docs/APPS.md +32
| @@ -241,6 +241,38 @@ Only `text/html` responses the app sends uncompressed with a `Content-Length` | ||
| 241 | 241 | (up to 4 MiB) are rewritten; JSON, images, compressed or chunked HTML and |
| 242 | 242 | `HEAD` requests pass through byte for byte. `"toolbar": false` keeps it out. |
| 243 | 243 | |
| 244 | Production deploys from landings are batched, because every restart drops | |
| 245 | every viewer's connection (`apps/batch.ts`). The first landing on the | |
| 246 | default branch after a quiet window deploys at once; every landing inside | |
| 247 | the window since production's last deploy waits for the window's end and | |
| 248 | rides one deploy of the branch's tip as it is then. The window is 15 | |
| 249 | minutes (`FORGE_DEPLOY_EVERY_MIN` on the forge; `0` deploys every landing), | |
| 250 | and an app sets its own with `"deploy": { "every": 5 }` inside `app` — | |
| 251 | whole minutes, 0–1440, read from the commit that landed. While landings | |
| 252 | wait, the app page says `next production deploy at 02:09 UTC (3 changes | |
| 253 | waiting)` and Redeploy reads **Deploy now**: pressing it deploys the tip at | |
| 254 | once and starts the window again. Previews are never batched. | |
| 255 | ||
| 256 | A deploy is not sent while production is busy (`apps/busy.ts`: a stream or | |
| 257 | websocket held open to it, a request it has not answered, a child process | |
| 258 | still working). A batch whose window ends then — or the first landing after | |
| 259 | a quiet window — is held and asked again every minute, and the page adds | |
| 260 | `held while busy — a stream to it is still open`; it goes once production | |
| 261 | is idle, or after the busy grace (the length of a crew run, 45 minutes by | |
| 262 | default) even if it never is, so an app that is always busy is still | |
| 263 | deployed. Deploy now does not wait. | |
| 264 | ||
| 265 | The swap itself drops no request: the new deployment starts beside the old | |
| 266 | one and takes every new request the moment it answers, and the old one is | |
| 267 | stopped only once the requests it was already answering are answered (at | |
| 268 | most 10 seconds). Streams and websockets open to the old one are closed at | |
| 269 | that point; a client that reconnects reaches the new one. | |
| 270 | ||
| 271 | The window and what is held live in the forge's memory, not its database. | |
| 272 | A forge restart forgets them: boot deploys production's tip at once (so | |
| 273 | nothing held is lost) and starts a fresh window, which means a forge in a | |
| 274 | crash loop restarts production on every boot. | |
| 275 | ||
| 244 | 276 | Two more fields say what the app's code may use (rule 9): |
| 245 | 277 | |
| 246 | 278 | json |
src/actions/apps.ts +14
| @@ -15,6 +15,7 @@ import type { App } from "../app.ts"; | ||
| 15 | 15 | import { goldenPath, goldenPathLine } from "../apps/golden_path.ts"; |
| 16 | 16 | import { appVitals, type AppVitals } from "../apps/vitals.ts"; |
| 17 | 17 | import { appsRuntime, envsFor, type EnvStatus } from "../apps/runtime.ts"; |
| 18 | import { batchedPhrase } from "../apps/batch.ts"; | |
| 18 | 19 | import { grantUrl, originFor } from "../apps/proxy.ts"; |
| 19 | 20 | import { scaffoldFiles } from "../apps/scaffold.ts"; |
| 20 | 21 | import { |
| @@ -504,6 +505,19 @@ export function appVisitors(app: App, actor: User | undefined, repo: Repo): AppV | ||
| 504 | 505 | return record === undefined ? undefined : appVitals(app.db, record.id); |
| 505 | 506 | } |
| 506 | 507 | |
| 508 | /** | |
| 509 | * Production's held landings in words (`apps/batch.ts`), for anyone who can | |
| 510 | * see the app's environments; `""` when nothing waits — the line the | |
| 511 | * terminal's Deploys screen shows, the same the web page and the JSON say. | |
| 512 | */ | |
| 513 | export function appHeld(app: App, actor: User | undefined, repo: Repo): string { | |
| 514 | if (!requireReader(app, actor, repo).ok) return ""; | |
| 515 | const record = getAppByRepo(app.db, repo.id); | |
| 516 | if (record === undefined) return ""; | |
| 517 | const held = envsFor(app, actor, record).find((e) => e.env === "production")?.batched; | |
| 518 | return held === undefined ? "" : batchedPhrase(held); | |
| 519 | } | |
| 520 | ||
| 507 | 521 | /** The golden path's pace line, for whoever may read the app's repository; `""` until there is one. */ |
| 508 | 522 | export function appPace(app: App, actor: User | undefined, repo: Repo): string { |
| 509 | 523 | if (!requireReader(app, actor, repo).ok) return ""; |
src/apps/batch.ts added +89
| @@ -0,0 +1,89 @@ | ||
| 1 | /** | |
| 2 | * How often production may be redeployed by landings. Every restart drops | |
| 3 | * every viewer's WebSocket and whoever is driving the app (issue #3967: | |
| 4 | * nine deploys in twelve minutes, one per landed pull), so the default | |
| 5 | * branch moving deploys production at most once per window: the first | |
| 6 | * landing after a quiet window goes at once, and every landing inside the | |
| 7 | * window rides one deploy at the window's end, of the branch's tip as it is | |
| 8 | * then. Previews stay immediate — a preview is looked at by its author. | |
| 9 | * | |
| 10 | * Pure: plain numbers in, plain numbers out. `AppsRuntime` holds the timer. | |
| 11 | */ | |
| 12 | ||
| 13 | /** The window when neither `forge.json` nor the runtime says otherwise. */ | |
| 14 | export const DEPLOY_EVERY_DEFAULT_MS = 15 * 60_000; | |
| 15 | ||
| 16 | /** The longest window `app.deploy.every` may name, in minutes: one day. */ | |
| 17 | export const DEPLOY_EVERY_MAX_MINUTES = 24 * 60; | |
| 18 | ||
| 19 | /** A production deploy waiting for its window, as the app page says it. */ | |
| 20 | export interface DeployBatch { | |
| 21 | /** When it goes, epoch milliseconds. */ | |
| 22 | readonly at: number; | |
| 23 | /** Landings it carries since the last production deploy. */ | |
| 24 | readonly changes: number; | |
| 25 | } | |
| 26 | ||
| 27 | /** | |
| 28 | * When a landing at `now` may deploy production: `now` itself when the | |
| 29 | * last production deploy started at least `everyMs` ago (or never), else | |
| 30 | * the end of that window. A window of 0 deploys every landing. | |
| 31 | */ | |
| 32 | export function deployAt( | |
| 33 | lastAt: number | undefined, | |
| 34 | everyMs: number, | |
| 35 | now: number, | |
| 36 | ): number { | |
| 37 | if (lastAt === undefined || everyMs <= 0) return now; | |
| 38 | return Math.max(now, lastAt + everyMs); | |
| 39 | } | |
| 40 | ||
| 41 | /** | |
| 42 | * The window for one commit: its `forge.json`'s `app.deploy.every` | |
| 43 | * (minutes) when it declares one, the runtime's otherwise. | |
| 44 | */ | |
| 45 | export function windowMs( | |
| 46 | declaredMinutes: number | undefined, | |
| 47 | runtimeMs: number, | |
| 48 | ): number { | |
| 49 | return declaredMinutes === undefined ? runtimeMs : declaredMinutes * 60_000; | |
| 50 | } | |
| 51 | ||
| 52 | /** How long a busy production waits before its held deploy asks again. */ | |
| 53 | export const BUSY_RETRY_MS = 60_000; | |
| 54 | ||
| 55 | /** | |
| 56 | * Whether a deploy due at `now` waits for a busy production (`apps/busy.ts`): | |
| 57 | * `undefined` sends it now — production is idle, or has been busy for a | |
| 58 | * whole `graceMs` since `heldSince`, so an app that is always busy is still | |
| 59 | * deployed — otherwise the epoch ms to ask again at, never past the grace. | |
| 60 | */ | |
| 61 | export function busyRetryAt( | |
| 62 | busy: boolean, | |
| 63 | heldSince: number | undefined, | |
| 64 | now: number, | |
| 65 | graceMs: number, | |
| 66 | retryMs: number, | |
| 67 | ): number | undefined { | |
| 68 | if (!busy) return undefined; | |
| 69 | const since = heldSince ?? now; | |
| 70 | if (now - since >= graceMs) return undefined; | |
| 71 | return Math.min(now + Math.max(1, retryMs), since + graceMs); | |
| 72 | } | |
| 73 | ||
| 74 | /** | |
| 75 | * Production's held landings in a person's words: `next production deploy | |
| 76 | * at 02:15 UTC (3 changes waiting)`, and why it waits past its window while | |
| 77 | * production is busy. The clock is UTC, said so, because every door renders | |
| 78 | * it on the server and never guesses the reader's zone. | |
| 79 | */ | |
| 80 | export function batchedPhrase(b: { | |
| 81 | readonly at: string; | |
| 82 | readonly changes: number; | |
| 83 | readonly busy?: string | undefined; | |
| 84 | }): string { | |
| 85 | const at = new Date(b.at).toISOString().slice(11, 16); | |
| 86 | const n = b.changes === 1 ? "1 change" : `${b.changes} changes`; | |
| 87 | const phrase = `next production deploy at ${at} UTC (${n} waiting)`; | |
| 88 | return b.busy === undefined ? phrase : `${phrase}; held while ${b.busy}`; | |
| 89 | } |
src/apps/manifest.ts +36
| @@ -15,6 +15,7 @@ import { err, ok, type Result } from "../kernel/result.ts"; | ||
| 15 | 15 | import { parseService, type ServiceSpec } from "./service.ts"; |
| 16 | 16 | import type { DeclaredLimits } from "./contain.ts"; |
| 17 | 17 | import { isPublicAddress } from "./egress.ts"; |
| 18 | import { DEPLOY_EVERY_MAX_MINUTES } from "./batch.ts"; | |
| 18 | 19 | |
| 19 | 20 | export interface AppManifest { |
| 20 | 21 | /** The command that serves on `$PORT`. Run through `sh -c`, `exec`-ed. */ |
| @@ -58,6 +59,12 @@ export interface AppManifest { | ||
| 58 | 59 | * out of the app's HTML pages. Unset is on. |
| 59 | 60 | */ |
| 60 | 61 | readonly toolbar?: boolean | undefined; |
| 62 | /** | |
| 63 | * `app.deploy.every`: at most one production deploy per this many | |
| 64 | * minutes from landings on the default branch (`apps/batch.ts`); 0 | |
| 65 | * deploys every landing. Unset takes the forge's default. | |
| 66 | */ | |
| 67 | readonly deployEvery?: number | undefined; | |
| 61 | 68 | } |
| 62 | 69 | |
| 63 | 70 | export type ManifestError = |
| @@ -149,6 +156,8 @@ export function parseManifest( | ||
| 149 | 156 | const toolbar = parsed.value["toolbar"]; |
| 150 | 157 | if (toolbar !== undefined && typeof toolbar !== "boolean") |
| 151 | 158 | return invalid("forge.json: toolbar must be true or false"); |
| 159 | const deploy = deployField(app); | |
| 160 | if (!deploy.ok) return deploy; | |
| 152 | 161 | const kind = app["kind"]; |
| 153 | 162 | if (kind !== undefined && kind !== "web" && kind !== "service") |
| 154 | 163 | return invalid('forge.json: app.kind must be "web" or "service"'); |
| @@ -178,9 +187,36 @@ export function parseManifest( | ||
| 178 | 187 | egress: egress.value, |
| 179 | 188 | limits: limits.value, |
| 180 | 189 | toolbar: toolbar ?? true, |
| 190 | ...(deploy.value === undefined ? {} : { deployEvery: deploy.value }), | |
| 181 | 191 | }); |
| 182 | 192 | } |
| 183 | 193 | |
| 194 | /** | |
| 195 | * `app.deploy`: `{ every }`, whole minutes 0–1440 between production | |
| 196 | * deploys from landings. Absent is the forge's default. | |
| 197 | */ | |
| 198 | function deployField(app: Json): Result<number | undefined, ManifestError> { | |
| 199 | const value = app["deploy"]; | |
| 200 | if (value === undefined) return ok(undefined); | |
| 201 | if (!isObject(value)) | |
| 202 | return invalid("forge.json: app.deploy must be an object"); | |
| 203 | for (const field of Object.keys(value)) | |
| 204 | if (field !== "every") | |
| 205 | return invalid(`forge.json: app.deploy takes every, not ${field}`); | |
| 206 | const every = value["every"]; | |
| 207 | if (every === undefined) return ok(undefined); | |
| 208 | if ( | |
| 209 | typeof every !== "number" || | |
| 210 | !Number.isInteger(every) || | |
| 211 | every < 0 || | |
| 212 | every > DEPLOY_EVERY_MAX_MINUTES | |
| 213 | ) | |
| 214 | return invalid( | |
| 215 | `forge.json: app.deploy.every must be a whole number of minutes, 0–${DEPLOY_EVERY_MAX_MINUTES}`, | |
| 216 | ); | |
| 217 | return ok(every); | |
| 218 | } | |
| 219 | ||
| 184 | 220 | const EGRESS_MAX = 32; |
| 185 | 221 | const HOST_RE = |
| 186 | 222 | /^(\*\.)?([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)*[a-z0-9]([a-z0-9-]*[a-z0-9])?(:[1-9]\d{0,4})?$/; |
src/apps/runtime.ts +260 −7
| @@ -10,7 +10,9 @@ | ||
| 10 | 10 | * a run row with a log; a failed deploy leaves the previous deployment |
| 11 | 11 | * serving. Deploys are serial per environment and a newer request |
| 12 | 12 | * supersedes one still queued, so a burst of pushes ends at the last |
| 13 | * commit, once. | |
| 13 | * commit, once. Production is batched on top of that: a landing inside | |
| 14 | * the window since its last deploy waits for the window's end and rides | |
| 15 | * one deploy with every other landing in it (`apps/batch.ts`). | |
| 14 | 16 | */ |
| 15 | 17 | |
| 16 | 18 | import type { Database } from "bun:sqlite"; |
| @@ -69,6 +71,13 @@ import { | ||
| 69 | 71 | } from "../core/meter.ts"; |
| 70 | 72 | import { dirBytes } from "./bytes.ts"; |
| 71 | 73 | import { BUSY_WORDS, busyReason, type BusyReason } from "./busy.ts"; |
| 74 | import { | |
| 75 | BUSY_RETRY_MS, | |
| 76 | busyRetryAt, | |
| 77 | deployAt, | |
| 78 | windowMs, | |
| 79 | type DeployBatch, | |
| 80 | } from "./batch.ts"; | |
| 72 | 81 | import { exportTree, readFileAt } from "./checkout.ts"; |
| 73 | 82 | import { seconds, Stopwatch } from "./timing.ts"; |
| 74 | 83 | import type { DomainResolver } from "./domains.ts"; |
| @@ -149,6 +158,24 @@ export interface RuntimeOptions { | ||
| 149 | 158 | * instead of beside it. @default a gate of `concurrency` |
| 150 | 159 | */ |
| 151 | 160 | readonly gate?: Gate | undefined; |
| 161 | /** | |
| 162 | * The least time between two production deploys a landing on the | |
| 163 | * default branch asks for; a commit's `app.deploy.every` overrides it. | |
| 164 | * The forge's boot passes 15 minutes (`DEPLOY_EVERY_DEFAULT_MS`). | |
| 165 | * @default 0 — every landing deploys at once | |
| 166 | */ | |
| 167 | readonly deployEveryMs?: number | undefined; | |
| 168 | /** | |
| 169 | * How long a held production deploy waits before asking again while | |
| 170 | * production is busy (`apps/busy.ts`), up to `busyGraceMs` in all. | |
| 171 | * @default one minute (`BUSY_RETRY_MS`) | |
| 172 | */ | |
| 173 | readonly busyRetryMs?: number | undefined; | |
| 174 | /** | |
| 175 | * How long a swap waits for the requests still in flight to the previous | |
| 176 | * deployment to be answered before stopping it. @default 10 seconds | |
| 177 | */ | |
| 178 | readonly drainMs?: number | undefined; | |
| 152 | 179 | } |
| 153 | 180 | |
| 154 | 181 | export type EnvState = |
| @@ -161,6 +188,7 @@ export type EnvState = | ||
| 161 | 188 | const SLEEP_AFTER_MS = { production: 24 * 3_600_000, preview: 30 * 60_000 }; |
| 162 | 189 | const SWEEP_EVERY_MS = 60_000; |
| 163 | 190 | const BUSY_GRACE_MS = 45 * 60_000; |
| 191 | const DRAIN_MS = 10_000; | |
| 164 | 192 | |
| 165 | 193 | /** The sentence a serving environment carries while its tests still run; |
| 166 | 194 | * the studio reads the same constant to word its badge. */ |
| @@ -239,6 +267,18 @@ export interface EnvStatus { | ||
| 239 | 267 | * A stopped preview with this set is asleep, never failed. |
| 240 | 268 | */ |
| 241 | 269 | readonly dormant?: { readonly since: string; readonly idleSince: string } | undefined; |
| 270 | /** | |
| 271 | * Production only: landings waiting for the window since its last | |
| 272 | * deploy to end, and when they go (`apps/batch.ts`). Unset when none wait. | |
| 273 | */ | |
| 274 | readonly batched?: | |
| 275 | | { | |
| 276 | readonly at: string; | |
| 277 | readonly changes: number; | |
| 278 | /** Why it waits past its window, in `BUSY_WORDS`, while production is busy. */ | |
| 279 | readonly busy?: string | undefined; | |
| 280 | } | |
| 281 | | undefined; | |
| 242 | 282 | } |
| 243 | 283 | |
| 244 | 284 | interface Live { |
| @@ -348,6 +388,19 @@ interface Environment { | ||
| 348 | 388 | lastErrorCommitOid?: string | undefined; |
| 349 | 389 | /** Crash restarts in the current window, for backing off. */ |
| 350 | 390 | restarts: number[]; |
| 391 | /** When production last had a deploy asked of it, epoch ms — what the batch window runs from. */ | |
| 392 | lastDeployAt?: number | undefined; | |
| 393 | /** Landings waiting for the window to end, and the timer that sends them. */ | |
| 394 | batch?: | |
| 395 | | (DeployBatch & { | |
| 396 | readonly timer: ReturnType<typeof setTimeout>; | |
| 397 | readonly reason: string; | |
| 398 | readonly actorId: string | undefined; | |
| 399 | /** When production was first found busy at the batch's time. */ | |
| 400 | readonly heldSince?: number | undefined; | |
| 401 | readonly busy?: BusyReason | undefined; | |
| 402 | }) | |
| 403 | | undefined; | |
| 351 | 404 | } |
| 352 | 405 | |
| 353 | 406 | /** The deploy reasons that mean a person touched the change. */ |
| @@ -402,6 +455,8 @@ export class AppsRuntime { | ||
| 402 | 455 | private unsubscribe: (() => void) | undefined; |
| 403 | 456 | private sweeper: ReturnType<typeof setInterval> | undefined; |
| 404 | 457 | private stopped = false; |
| 458 | /** Requests in flight to each deployment, so a swap can let them finish. */ | |
| 459 | private readonly inFlight = new WeakMap<ProcessHandle, number>(); | |
| 405 | 460 | |
| 406 | 461 | constructor( |
| 407 | 462 | readonly app: App, |
| @@ -465,14 +520,15 @@ export class AppsRuntime { | ||
| 465 | 520 | envStatus(record: AppRecord, env: EnvName): EnvStatus | undefined { |
| 466 | 521 | const state = this.envs.get(key(record.id, env)); |
| 467 | 522 | if (state === undefined) return undefined; |
| 468 | return this.describe(state); | |
| 523 | return this.withBatch(state, this.describe(state)); | |
| 469 | 524 | } |
| 470 | 525 | |
| 471 | 526 | /** Every environment of an app, production first. */ |
| 472 | 527 | status(record: AppRecord): EnvStatus[] { |
| 473 | 528 | const out: EnvStatus[] = []; |
| 474 | 529 | for (const state of this.envs.values()) { |
| 475 | if (state.app.id === record.id) out.push(this.describe(state)); | |
| 530 | if (state.app.id === record.id) | |
| 531 | out.push(this.withBatch(state, this.describe(state))); | |
| 476 | 532 | } |
| 477 | 533 | // Production first, then previews by pull number — a number, not a |
| 478 | 534 | // string, so `pull-10` follows `pull-9`. |
| @@ -485,6 +541,20 @@ export class AppsRuntime { | ||
| 485 | 541 | ); |
| 486 | 542 | } |
| 487 | 543 | |
| 544 | private withBatch(state: Environment, status: EnvStatus): EnvStatus { | |
| 545 | if (state.batch === undefined) return status; | |
| 546 | return { | |
| 547 | ...status, | |
| 548 | batched: { | |
| 549 | at: new Date(state.batch.at).toISOString(), | |
| 550 | changes: state.batch.changes, | |
| 551 | ...(state.batch.busy === undefined | |
| 552 | ? {} | |
| 553 | : { busy: BUSY_WORDS[state.batch.busy] }), | |
| 554 | }, | |
| 555 | }; | |
| 556 | } | |
| 557 | ||
| 488 | 558 | private describe(state: Environment): EnvStatus { |
| 489 | 559 | const url = this.urlFor(state.app, state.env); |
| 490 | 560 | // Once a deploy's own commit has answered and swapped in, it is |
| @@ -665,6 +735,7 @@ export class AppsRuntime { | ||
| 665 | 735 | this.unsubscribe?.(); |
| 666 | 736 | const stops: Promise<void>[] = []; |
| 667 | 737 | for (const state of this.envs.values()) { |
| 738 | this.dropBatch(state); | |
| 668 | 739 | state.deploying?.abort.abort(); |
| 669 | 740 | if (state.queued) |
| 670 | 741 | cancelRun(this.app.db, state.queued.id, STOPPED_SUMMARY); |
| @@ -791,10 +862,9 @@ export class AppsRuntime { | ||
| 791 | 862 | const branch = update.ref.slice("refs/heads/".length); |
| 792 | 863 | const deleted = /^0+$/.test(update.newOid); |
| 793 | 864 | if (branch === repo.defaultBranch && !deleted) { |
| 794 | this.requestDeploy( | |
| 865 | await this.landed( | |
| 795 | 866 | record, |
| 796 | 867 | repo, |
| 797 | "production", | |
| 798 | 868 | update.newOid, |
| 799 | 869 | "push", |
| 800 | 870 | event.actorId ?? undefined, |
| @@ -902,10 +972,9 @@ export class AppsRuntime { | ||
| 902 | 972 | if (event.kind === "pull.merged") { |
| 903 | 973 | const tip = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`); |
| 904 | 974 | if (tip !== undefined) |
| 905 | this.requestDeploy( | |
| 975 | await this.landed( | |
| 906 | 976 | record, |
| 907 | 977 | repo, |
| 908 | "production", | |
| 909 | 978 | tip, |
| 910 | 979 | "merge", |
| 911 | 980 | event.actorId ?? undefined, |
| @@ -927,6 +996,171 @@ export class AppsRuntime { | ||
| 927 | 996 | |
| 928 | 997 | // ---- deploying ---- |
| 929 | 998 | |
| 999 | /** | |
| 1000 | * The default branch moved to `commitOid`: deploy production now if its | |
| 1001 | * window has passed, or hold the landing for the window's end — when the | |
| 1002 | * branch's tip *then* deploys, carrying every landing held meanwhile. | |
| 1003 | */ | |
| 1004 | private async landed( | |
| 1005 | record: AppRecord, | |
| 1006 | repo: Repo, | |
| 1007 | commitOid: string, | |
| 1008 | reason: string, | |
| 1009 | actorId: string | undefined, | |
| 1010 | ): Promise<void> { | |
| 1011 | const state = this.envFor(record, "production"); | |
| 1012 | if (state.batch !== undefined) { | |
| 1013 | state.batch = { ...state.batch, changes: state.batch.changes + 1 }; | |
| 1014 | return; | |
| 1015 | } | |
| 1016 | const every = windowMs( | |
| 1017 | await this.declaredEvery(repo, commitOid), | |
| 1018 | this.options.deployEveryMs ?? 0, | |
| 1019 | ); | |
| 1020 | const now = Date.now(); | |
| 1021 | const at = deployAt(state.lastDeployAt, every, now); | |
| 1022 | if (this.stopped) { | |
| 1023 | this.requestDeploy(record, repo, "production", commitOid, reason, actorId); | |
| 1024 | return; | |
| 1025 | } | |
| 1026 | // Asked twice while the manifest was read: the first one holds it. | |
| 1027 | const held = state.batch as Environment["batch"]; | |
| 1028 | if (held !== undefined) { | |
| 1029 | state.batch = { ...held, changes: held.changes + 1 }; | |
| 1030 | return; | |
| 1031 | } | |
| 1032 | if (at > now) { | |
| 1033 | this.hold(record, state, at, { changes: 1, reason, actorId }); | |
| 1034 | log.info("production deploy batched", { | |
| 1035 | app: record.id, | |
| 1036 | at: new Date(at).toISOString(), | |
| 1037 | }); | |
| 1038 | return; | |
| 1039 | } | |
| 1040 | // The window has passed, but someone is in the middle of something. | |
| 1041 | const busy = this.busyNow(state); | |
| 1042 | const retry = busyRetryAt( | |
| 1043 | busy !== undefined, | |
| 1044 | undefined, | |
| 1045 | now, | |
| 1046 | this.options.busyGraceMs ?? BUSY_GRACE_MS, | |
| 1047 | this.options.busyRetryMs ?? BUSY_RETRY_MS, | |
| 1048 | ); | |
| 1049 | if (retry === undefined) { | |
| 1050 | this.requestDeploy(record, repo, "production", commitOid, reason, actorId); | |
| 1051 | return; | |
| 1052 | } | |
| 1053 | this.hold(record, state, retry, { | |
| 1054 | changes: 1, | |
| 1055 | reason, | |
| 1056 | actorId, | |
| 1057 | heldSince: now, | |
| 1058 | busy, | |
| 1059 | }); | |
| 1060 | } | |
| 1061 | ||
| 1062 | /** Until `handle` has no request in flight, for no longer than `drainMs`. */ | |
| 1063 | private async drained( | |
| 1064 | handle: ProcessHandle, | |
| 1065 | write: (line: string) => void, | |
| 1066 | ): Promise<void> { | |
| 1067 | const deadline = Date.now() + (this.options.drainMs ?? DRAIN_MS); | |
| 1068 | if ((this.inFlight.get(handle) ?? 0) === 0) return; | |
| 1069 | write("waiting for the previous deployment to answer its requests"); | |
| 1070 | while ((this.inFlight.get(handle) ?? 0) > 0) { | |
| 1071 | if (Date.now() >= deadline) { | |
| 1072 | write( | |
| 1073 | `stopping it with ${this.inFlight.get(handle)} request(s) unanswered after ${seconds(this.options.drainMs ?? DRAIN_MS)}`, | |
| 1074 | ); | |
| 1075 | return; | |
| 1076 | } | |
| 1077 | await Bun.sleep(25); | |
| 1078 | } | |
| 1079 | } | |
| 1080 | ||
| 1081 | /** Production is held until `at`, when `sendBatch` looks again. */ | |
| 1082 | private hold( | |
| 1083 | record: AppRecord, | |
| 1084 | state: Environment, | |
| 1085 | at: number, | |
| 1086 | batch: Omit<NonNullable<Environment["batch"]>, "at" | "timer">, | |
| 1087 | ): void { | |
| 1088 | const timer = setTimeout( | |
| 1089 | () => void this.sendBatch(record, state), | |
| 1090 | Math.max(0, at - Date.now()), | |
outdated
A manual Deploy now and a batch both start the window here. That is intended. In-memory only: note in the README that a forge restart resets it. |
||
| 1091 | ); | |
| 1092 | state.batch = { ...batch, at, timer }; | |
| 1093 | } | |
| 1094 | ||
| 1095 | /** Why production is mid-work right now (`apps/busy.ts`), if it is. */ | |
| 1096 | private busyNow(state: Environment): BusyReason | undefined { | |
| 1097 | const live = state.live; | |
| 1098 | if (live === undefined) return undefined; | |
| 1099 | return busyReason(live.handle.pid, state.openStreams, state.openRequests); | |
| 1100 | } | |
| 1101 | ||
| 1102 | /** | |
| 1103 | * The window ended: production deploys the default branch's tip as it is | |
| 1104 | * now — unless it is busy, when the batch asks again a little later, for | |
| 1105 | * no longer in all than the busy grace. | |
| 1106 | */ | |
| 1107 | private async sendBatch(record: AppRecord, state: Environment): Promise<void> { | |
| 1108 | const batch = state.batch; | |
| 1109 | if (batch === undefined || this.stopped) return; | |
| 1110 | if (this.envs.get(key(record.id, "production")) !== state) return; | |
| 1111 | const now = Date.now(); | |
| 1112 | const busy = this.busyNow(state); | |
| 1113 | const retry = busyRetryAt( | |
| 1114 | busy !== undefined, | |
| 1115 | batch.heldSince, | |
| 1116 | now, | |
| 1117 | this.options.busyGraceMs ?? BUSY_GRACE_MS, | |
| 1118 | this.options.busyRetryMs ?? BUSY_RETRY_MS, | |
| 1119 | ); | |
| 1120 | if (retry !== undefined) { | |
| 1121 | if (batch.busy !== busy) | |
| 1122 | log.info("production deploy held while busy", { | |
| 1123 | app: record.id, | |
| 1124 | busy, | |
| 1125 | }); | |
| 1126 | this.hold(record, state, retry, { | |
| 1127 | changes: batch.changes, | |
| 1128 | reason: batch.reason, | |
| 1129 | actorId: batch.actorId, | |
| 1130 | heldSince: batch.heldSince ?? now, | |
| 1131 | busy, | |
| 1132 | }); | |
| 1133 | return; | |
| 1134 | } | |
| 1135 | state.batch = undefined; | |
| 1136 | const repo = getRepoById(this.app.db, record.repoId); | |
| 1137 | if (!repo) return; | |
| 1138 | const dir = repoDir(this.app.reposRoot, repo.ownerName, repo.name); | |
| 1139 | const tip = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`); | |
| 1140 | if (tip === undefined) return; | |
| 1141 | this.requestDeploy(record, repo, "production", tip, batch.reason, batch.actorId); | |
| 1142 | } | |
| 1143 | ||
| 1144 | private dropBatch(state: Environment): void { | |
| 1145 | if (state.batch === undefined) return; | |
| 1146 | clearTimeout(state.batch.timer); | |
| 1147 | state.batch = undefined; | |
| 1148 | } | |
| 1149 | ||
| 1150 | /** `app.deploy.every` at `commitOid`, in minutes, when it declares one. */ | |
| 1151 | private async declaredEvery( | |
| 1152 | repo: Repo, | |
| 1153 | commitOid: string, | |
| 1154 | ): Promise<number | undefined> { | |
| 1155 | const dir = repoDir(this.app.reposRoot, repo.ownerName, repo.name); | |
| 1156 | const [forgeJson, packageJson] = await Promise.all([ | |
| 1157 | readFileAt(dir, commitOid, "forge.json"), | |
| 1158 | readFileAt(dir, commitOid, "package.json"), | |
| 1159 | ]); | |
| 1160 | const manifest = parseManifest(forgeJson, packageJson); | |
| 1161 | return manifest.ok ? manifest.value.deployEvery : undefined; | |
| 1162 | } | |
| 1163 | ||
| 930 | 1164 | /** |
| 931 | 1165 | * Ask for `env` to run `commitOid`. Returns the run that will do it — or |
| 932 | 1166 | * the one already serving that commit, when nothing needs to happen. |
| @@ -975,6 +1209,12 @@ export class AppsRuntime { | ||
| 975 | 1209 | ...(actorId === undefined ? {} : { actorId }), |
| 976 | 1210 | }); |
| 977 | 1211 | announceRun(this.app, run, actorId); |
| 1212 | // Any production deploy — a landing's, a batch's, a Deploy now — starts | |
| 1213 | // the window again and carries whatever was held for it. | |
| 1214 | if (env === "production") { | |
| 1215 | state.lastDeployAt = Date.now(); | |
| 1216 | this.dropBatch(state); | |
| 1217 | } | |
| 978 | 1218 | if (state.queued !== undefined) { |
| 979 | 1219 | cancelRun( |
| 980 | 1220 | this.app.db, |
| @@ -1161,6 +1401,10 @@ export class AppsRuntime { | ||
| 1161 | 1401 | write( |
| 1162 | 1402 | `stopping the previous deployment (${previous.commitOid.slice(0, 7)})`, |
| 1163 | 1403 | ); |
| 1404 | // New requests already reach the new deployment; the ones the old | |
| 1405 | // one is still answering finish first, so a swap drops none of them. | |
| 1406 | // Open streams and websockets are cut here, and reconnect to the new. | |
| 1407 | await this.drained(previous.handle, write); | |
| 1164 | 1408 | revokeAppToken(this.app.db, previous.tokenId); |
| 1165 | 1409 | await previous.handle.stop(); |
| 1166 | 1410 | if (previous.dir !== live.dir) |
| @@ -1547,12 +1791,19 @@ export class AppsRuntime { | ||
| 1547 | 1791 | const state = this.envs.get(key(record.id, env)); |
| 1548 | 1792 | if (state === undefined) return () => {}; |
| 1549 | 1793 | state.openRequests++; |
| 1794 | // The proxy picked its port from this deployment a moment ago, with | |
| 1795 | // nothing awaited between: the request is this deployment's to answer. | |
| 1796 | const handle = state.live?.handle; | |
| 1797 | if (handle !== undefined) | |
| 1798 | this.inFlight.set(handle, (this.inFlight.get(handle) ?? 0) + 1); | |
| 1550 | 1799 | let held = true; |
| 1551 | 1800 | return () => { |
| 1552 | 1801 | if (!held) return; |
| 1553 | 1802 | held = false; |
| 1554 | 1803 | state.openRequests--; |
| 1555 | 1804 | state.lastRequestAt = Date.now(); |
| 1805 | if (handle !== undefined) | |
| 1806 | this.inFlight.set(handle, (this.inFlight.get(handle) ?? 1) - 1); | |
| 1556 | 1807 | }; |
| 1557 | 1808 | } |
| 1558 | 1809 | |
| @@ -2001,6 +2252,7 @@ export class AppsRuntime { | ||
| 2001 | 2252 | const state = this.envs.get(k); |
| 2002 | 2253 | if (state !== undefined) { |
| 2003 | 2254 | this.envs.delete(k); |
| 2255 | this.dropBatch(state); | |
| 2004 | 2256 | if (state.queued) |
| 2005 | 2257 | cancelRun(this.app.db, state.queued.id, "the environment was removed"); |
| 2006 | 2258 | state.deploying?.abort.abort(); |
| @@ -2041,6 +2293,7 @@ export class AppsRuntime { | ||
| 2041 | 2293 | async stopEnv(record: AppRecord, env: EnvName): Promise<void> { |
| 2042 | 2294 | const state = this.envs.get(key(record.id, env)); |
| 2043 | 2295 | if (state === undefined) return; |
| 2296 | this.dropBatch(state); | |
| 2044 | 2297 | if (state.queued) cancelRun(this.app.db, state.queued.id, "stopped"); |
| 2045 | 2298 | state.deploying?.abort.abort(); |
| 2046 | 2299 | await state.chain.catch(() => {}); |
src/http/mcp.ts +5 −1
| @@ -441,7 +441,7 @@ const TOOLS: readonly Tool[] = [ | ||
| 441 | 441 | { |
| 442 | 442 | name: "apps", |
| 443 | 443 | description: |
| 444 | "The apps you can see: whether each is live, where it is served, how it runs itself, what is working.", | |
| 444 | "The apps you can see: whether each is live, where it is served, how it runs itself, what is working, and — as nextDeploy — the landings held for production's next deploy (at, changes, busy).", | |
| 445 | 445 | inputSchema: { type: "object", properties: {} }, |
| 446 | 446 | writes: false, |
| 447 | 447 | async run(ctx, user) { |
| @@ -461,6 +461,10 @@ const TOOLS: readonly Tool[] = [ | ||
| 461 | 461 | app: `${repo.ownerName}/${repo.name}`, |
| 462 | 462 | description: repo.description, |
| 463 | 463 | live: production?.state ?? "stopped", |
| 464 | // Landings held for production's next deploy (`apps/batch.ts`). | |
| 465 | ...(production?.batched === undefined | |
| 466 | ? {} | |
| 467 | : { nextDeploy: production.batched }), | |
| 464 | 468 | url: runtime?.urlFor(record, "production") ?? null, |
| 465 | 469 | autonomy: repo.autonomy, |
| 466 | 470 | working: active.filter((r) => r.repoId === repo.id).length, |
src/main.ts +3
| @@ -329,6 +329,9 @@ const apps = appDomain?.ok | ||
| 329 | 329 | forgeUrl, |
| 330 | 330 | concurrency: positive(process.env.FORGE_APPS_CONCURRENCY, 2), |
| 331 | 331 | busyGraceMs: crewRunMs, |
| 332 | // Minutes between production deploys from landings; 0 deploys each. | |
| 333 | deployEveryMs: | |
| 334 | nonNegative(process.env.FORGE_DEPLOY_EVERY_MIN, 15) * 60_000, | |
| 332 | 335 | // Days a pull may sit untouched before its preview sleeps; 0 keeps |
| 333 | 336 | // every preview warm. |
| 334 | 337 | idlePullMs: nonNegative(process.env.FORGE_PREVIEW_IDLE_DAYS, 3) * 86_400_000, |
src/spawn/child-apps.ts +1
| @@ -47,6 +47,7 @@ export async function startChildApps(parent: App, child: App, name: string): Pro | ||
| 47 | 47 | forgeUrl: childPublicUrl(name, parentOrigin(parent.config)), |
| 48 | 48 | gate: own.lane, |
| 49 | 49 | busyGraceMs: own.options.busyGraceMs, |
| 50 | deployEveryMs: own.options.deployEveryMs, | |
| 50 | 51 | idlePullMs: own.options.idlePullMs, |
| 51 | 52 | sleepAfterMs: own.options.sleepAfterMs, |
| 52 | 53 | sweepEveryMs: own.options.sweepEveryMs, |
src/tui/screens/deploys.ts +5 −3
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | * joined to `deploy_pull` in one grouped read for `carries #3 #5`. |
| 8 | 8 | */ |
| 9 | 9 | |
| 10 | import { appPace, appVisitors } from "../../actions/apps.ts"; | |
| 10 | import { appHeld, appPace, appVisitors } from "../../actions/apps.ts"; | |
| 11 | 11 | import { trendLine, visitorsLine } from "../../apps/vitals.ts"; |
| 12 | 12 | import { listRepoRuns } from "../../actions/runs.ts"; |
| 13 | 13 | import { carriedByRuns, carriesText } from "../../core/carried.ts"; |
| @@ -42,6 +42,7 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 42 | 42 | let visitors = ""; |
| 43 | 43 | let trend = ""; |
| 44 | 44 | let pace = ""; |
| 45 | let held = ""; | |
| 45 | 46 | |
| 46 | 47 | const read = (): void => { |
| 47 | 48 | const runs = readDeploys(f, repo); |
| @@ -54,6 +55,7 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 54 | 55 | visitors = seen === undefined ? "" : visitorsLine(seen); |
| 55 | 56 | trend = seen === undefined ? "" : trendLine(seen.loadDays); |
| 56 | 57 | pace = appPace(f.app, f.user, repo); |
| 58 | held = appHeld(f.app, f.user, repo); | |
| 57 | 59 | loaded = true; |
| 58 | 60 | ctx.invalidate(); |
| 59 | 61 | }; |
| @@ -70,7 +72,7 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 70 | 72 | load: async () => read(), |
| 71 | 73 | render(area, s) { |
| 72 | 74 | const c = ctx.theme.c; |
| 73 | const [head, body] = split(area, "v", [len(1 + (visitors === "" ? 0 : 1) + (trend === "" ? 0 : 1) + (pace === "" ? 0 : 1)), fill(1)]); | |
| 75 | const [head, body] = split(area, "v", [len(1 + (held === "" ? 0 : 1) + (visitors === "" ? 0 : 1) + (trend === "" ? 0 : 1) + (pace === "" ? 0 : 1)), fill(1)]); | |
| 74 | 76 | s.text( |
| 75 | 77 | head!.x, |
| 76 | 78 | head!.y, |
| @@ -78,7 +80,7 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 78 | 80 | style(c.mutedFg, c.bg), |
| 79 | 81 | head!.x + head!.w, |
| 80 | 82 | ); |
| 81 | [visitors, trend, pace] | |
| 83 | [held, visitors, trend, pace] | |
| 82 | 84 | .filter((line) => line !== "") |
| 83 | 85 | .forEach((line, i) => |
| 84 | 86 | s.text(head!.x, head!.y + 1 + i, truncate(line, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w), |
src/web/ui.ts +12 −1
| @@ -12,6 +12,7 @@ | ||
| 12 | 12 | |
| 13 | 13 | import { VERIFYING_NOTE, type EnvState, type EnvStatus } from "../apps/runtime.ts"; |
| 14 | 14 | import type { PreviewData } from "../apps/data.ts"; |
| 15 | import { batchedPhrase } from "../apps/batch.ts"; | |
| 15 | 16 | import type { Mark } from "../core/marks.ts"; |
| 16 | 17 | import type { RunKind, RunState } from "../core/runs.ts"; |
| 17 | 18 | import { |
| @@ -25,6 +26,7 @@ import { icon, type IconName } from "./icons.ts"; | ||
| 25 | 26 | import { Html, html, raw, when } from "./html.ts"; |
| 26 | 27 | |
| 27 | 28 | export { icon, type IconName }; |
| 29 | export { batchedPhrase }; | |
| 28 | 30 | |
| 29 | 31 | export type Tone = "default" | "success" | "danger" | "merged" | "attn"; |
| 30 | 32 | |
| @@ -490,6 +492,12 @@ export function envFacts( | ||
| 490 | 492 | ${busy}; kept awake past its idle window |
| 491 | 493 | </p>`, |
| 492 | 494 | )} |
| 495 | ${when( | |
| 496 | env.batched, | |
| 497 | (b) => html`<p class="muted small" data-batched> | |
| 498 | ${dot("attn")} ${batchedPhrase(b)} | |
| 499 | </p>`, | |
| 500 | )} | |
| 493 | 501 | ${when(env.error, (error) => html`<p class="env-error">${error}</p>`)} |
| 494 | 502 | ${when( |
| 495 | 503 | env.failedDeploy, |
| @@ -594,7 +602,10 @@ export function envActions( | ||
| 594 | 602 | writer, |
| 595 | 603 | () => |
| 596 | 604 | html`<form method="post" action="${base}/app/${env.env}/redeploy"> |
| 597 | ${btn("Redeploy", { size: "sm", icon: "sync" })} | |
| 605 | ${btn(env.batched === undefined ? "Redeploy" : "Deploy now", { | |
| 606 | size: "sm", | |
| 607 | icon: "sync", | |
| 608 | })} | |
| 598 | 609 | </form> |
| 599 | 610 | ${when( |
| 600 | 611 | env.state !== "stopped", |
test/apps-batch.test.ts added +415
| @@ -0,0 +1,415 @@ | ||
| 1 | /** | |
| 2 | * Production deploys from landings are batched (issue #3967): the first | |
| 3 | * landing after a quiet window deploys at once, every landing inside the | |
| 4 | * window rides one deploy of the branch's tip at the window's end, and | |
| 5 | * Deploy now sends what is held immediately. Previews are not batched. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { AppsRuntime, type EnvStatus } from "../src/apps/runtime.ts"; | |
| 13 | import { busyRetryAt, deployAt, windowMs } from "../src/apps/batch.ts"; | |
| 14 | import { BUSY_WORDS } from "../src/apps/busy.ts"; | |
| 15 | import { parseManifest } from "../src/apps/manifest.ts"; | |
| 16 | import { appHeld, newApp, redeployEnv } from "../src/actions/apps.ts"; | |
| 17 | import { createToken } from "../src/core/tokens.ts"; | |
| 18 | import { commitToBranch } from "../src/actions/repos.ts"; | |
| 19 | import type { AppRecord } from "../src/core/apps.ts"; | |
| 20 | import type { Repo } from "../src/core/repos.ts"; | |
| 21 | import { listRuns, type Run } from "../src/core/runs.ts"; | |
| 22 | import { createUser, type User } from "../src/core/users.ts"; | |
| 23 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 24 | import { batchedPhrase, envFacts, envActions } from "../src/web/ui.ts"; | |
| 25 | ||
| 26 | describe("the batch window", () => { | |
| 27 | test("the first landing after a quiet window goes at once", () => { | |
| 28 | expect(deployAt(undefined, 900_000, 5_000)).toBe(5_000); | |
| 29 | expect(deployAt(0, 900_000, 900_000)).toBe(900_000); | |
| 30 | expect(deployAt(0, 900_000, 2_000_000)).toBe(2_000_000); | |
| 31 | }); | |
| 32 | ||
| 33 | test("a landing inside the window waits for its end", () => { | |
| 34 | // Last deploy at 01:54:00, window 15 min: a landing at 01:57 goes at 02:09. | |
| 35 | const last = Date.parse("2026-10-21T01:54:00Z"); | |
| 36 | const now = Date.parse("2026-10-21T01:57:00Z"); | |
| 37 | expect(new Date(deployAt(last, 15 * 60_000, now)).toISOString()).toBe( | |
| 38 | "2026-10-21T02:09:00.000Z", | |
| 39 | ); | |
| 40 | }); | |
| 41 | ||
| 42 | test("a window of 0 deploys every landing", () => { | |
| 43 | expect(deployAt(1_000, 0, 1_001)).toBe(1_001); | |
| 44 | }); | |
| 45 | ||
| 46 | test("forge.json's minutes override the runtime's window", () => { | |
| 47 | expect(windowMs(undefined, 900_000)).toBe(900_000); | |
| 48 | expect(windowMs(5, 900_000)).toBe(300_000); | |
| 49 | expect(windowMs(0, 900_000)).toBe(0); | |
| 50 | }); | |
| 51 | ||
| 52 | test("the page's words: UTC clock and the count", () => { | |
| 53 | expect( | |
| 54 | batchedPhrase({ at: "2026-10-21T02:09:00.000Z", changes: 9 }), | |
| 55 | ).toBe("next production deploy at 02:09 UTC (9 changes waiting)"); | |
| 56 | expect(batchedPhrase({ at: "2026-10-21T23:59:30.000Z", changes: 1 })).toBe( | |
| 57 | "next production deploy at 23:59 UTC (1 change waiting)", | |
| 58 | ); | |
| 59 | expect( | |
| 60 | batchedPhrase({ | |
| 61 | at: "2026-10-21T02:10:00.000Z", | |
| 62 | changes: 2, | |
| 63 | busy: BUSY_WORDS.stream, | |
| 64 | }), | |
| 65 | ).toBe( | |
| 66 | "next production deploy at 02:10 UTC (2 changes waiting); held while busy — a stream to it is still open", | |
| 67 | ); | |
| 68 | }); | |
| 69 | ||
| 70 | test("a busy production is asked again each retry, never past the grace", () => { | |
| 71 | const grace = 45 * 60_000; | |
| 72 | const retry = 60_000; | |
| 73 | // Idle: it goes now. | |
| 74 | expect(busyRetryAt(false, undefined, 1_000, grace, retry)).toBeUndefined(); | |
| 75 | expect(busyRetryAt(false, 0, 1_000, grace, retry)).toBeUndefined(); | |
| 76 | // Busy at its time: one retry later. | |
| 77 | expect(busyRetryAt(true, undefined, 1_000, grace, retry)).toBe(61_000); | |
| 78 | // Still busy 44:30 after it was first held: the retry stops at the grace. | |
| 79 | expect(busyRetryAt(true, 0, 44.5 * 60_000, grace, retry)).toBe(grace); | |
| 80 | // Busy for the whole grace: it goes anyway. | |
| 81 | expect(busyRetryAt(true, 0, grace, grace, retry)).toBeUndefined(); | |
| 82 | }); | |
| 83 | }); | |
| 84 | ||
| 85 | describe("app.deploy.every in forge.json", () => { | |
| 86 | const manifest = (deploy: unknown) => | |
| 87 | parseManifest(JSON.stringify({ app: { run: "bun x", deploy } }), undefined); | |
| 88 | ||
| 89 | test("whole minutes 0–1440 are taken", () => { | |
| 90 | for (const every of [0, 15, 1440]) { | |
| 91 | const parsed = manifest({ every }); | |
| 92 | expect(parsed.ok && parsed.value.deployEvery).toBe(every); | |
| 93 | } | |
| 94 | }); | |
| 95 | ||
| 96 | test("absent leaves the forge's default", () => { | |
| 97 | const parsed = parseManifest( | |
| 98 | JSON.stringify({ app: { run: "bun x" } }), | |
| 99 | undefined, | |
| 100 | ); | |
| 101 | expect(parsed.ok && parsed.value.deployEvery).toBeUndefined(); | |
| 102 | const empty = manifest({}); | |
| 103 | expect(empty.ok && empty.value.deployEvery).toBeUndefined(); | |
| 104 | }); | |
| 105 | ||
| 106 | test("anything else fails closed, naming the field", () => { | |
| 107 | for (const bad of [-1, 1441, 1.5, "15", null]) { | |
| 108 | const parsed = manifest({ every: bad }); | |
| 109 | expect(parsed.ok).toBe(false); | |
| 110 | if (!parsed.ok) | |
| 111 | expect(parsed.error).toMatchObject({ | |
| 112 | kind: "invalid", | |
| 113 | message: expect.stringContaining("app.deploy.every"), | |
| 114 | }); | |
| 115 | } | |
| 116 | expect(manifest(5).ok).toBe(false); | |
| 117 | const unknown = manifest({ every: 5, sometimes: true }); | |
| 118 | expect(!unknown.ok && unknown.error).toMatchObject({ | |
| 119 | message: "forge.json: app.deploy takes every, not sometimes", | |
| 120 | }); | |
| 121 | }); | |
| 122 | }); | |
| 123 | ||
| 124 | describe("production deploys from landings", () => { | |
| 125 | let dataDir: string; | |
| 126 | let app: App; | |
| 127 | let servers: Servers; | |
| 128 | let runtime: AppsRuntime; | |
| 129 | let alice: User; | |
| 130 | let repo: Repo; | |
| 131 | let record: AppRecord; | |
| 132 | const WINDOW = 10_000; | |
| 133 | ||
| 134 | async function until<T>(read: () => T | undefined, ms = 60_000): Promise<T> { | |
| 135 | const deadline = Date.now() + ms; | |
| 136 | while (Date.now() < deadline) { | |
| 137 | const value = read(); | |
| 138 | if (value !== undefined) return value; | |
| 139 | await Bun.sleep(50); | |
| 140 | } | |
| 141 | throw new Error("did not happen in time"); | |
| 142 | } | |
| 143 | const deploys = (): Run[] => | |
| 144 | listRuns(app.db, repo.id, { kind: "deploy", limit: 100 }).filter( | |
| 145 | (r) => r.env === "production", | |
| 146 | ); | |
| 147 | const settled = (where: (run: Run) => boolean) => | |
| 148 | until(() => | |
| 149 | deploys().find( | |
| 150 | (r) => where(r) && (r.state === "ok" || r.state === "failed"), | |
| 151 | ), | |
| 152 | ); | |
| 153 | const production = (): EnvStatus | undefined => | |
| 154 | runtime.status(record).find((e) => e.env === "production"); | |
| 155 | const runtimeFor = ( | |
| 156 | deployEveryMs: number, | |
| 157 | more: { busyGraceMs?: number; busyRetryMs?: number; drainMs?: number } = {}, | |
| 158 | ) => | |
| 159 | new AppsRuntime(app, { | |
| 160 | domain: "apps.test", | |
| 161 | scheme: "http", | |
| 162 | publicPort: servers.port, | |
| 163 | forgeUrl: servers.url, | |
| 164 | deployEveryMs, | |
| 165 | ...more, | |
| 166 | }); | |
| 167 | /** A fresh runtime, its boot deploy of production settled. */ | |
| 168 | async function restart( | |
| 169 | deployEveryMs: number, | |
| 170 | more: Parameters<typeof runtimeFor>[1] = {}, | |
| 171 | ): Promise<void> { | |
| 172 | await runtime.stop(); | |
| 173 | runtime = runtimeFor(deployEveryMs, more); | |
| 174 | await runtime.start(); | |
| 175 | await until(() => | |
| 176 | production()?.state === "running" ? true : undefined, | |
| 177 | ); | |
| 178 | } | |
| 179 | async function mcpApps(token: string): Promise<any[]> { | |
| 180 | const res = await fetch(`${servers.url}/mcp`, { | |
| 181 | method: "POST", | |
| 182 | headers: { | |
| 183 | "content-type": "application/json", | |
| 184 | accept: "application/json, text/event-stream", | |
| 185 | authorization: `Bearer ${token}`, | |
| 186 | }, | |
| 187 | body: JSON.stringify({ | |
| 188 | jsonrpc: "2.0", | |
| 189 | id: 1, | |
| 190 | method: "tools/call", | |
| 191 | params: { name: "apps", arguments: {} }, | |
| 192 | }), | |
| 193 | }); | |
| 194 | const body = (await res.json()) as any; | |
| 195 | return JSON.parse(body.result.content[0].text); | |
| 196 | } | |
| 197 | let n = 0; | |
| 198 | async function land(): Promise<string> { | |
| 199 | n += 1; | |
| 200 | const committed = await commitToBranch(app, alice, repo, { | |
| 201 | message: `Landing ${n}`, | |
| 202 | files: [{ path: "notes.txt", content: `landing ${n}\n` }], | |
| 203 | }); | |
| 204 | if (!committed.ok) throw new Error(String(committed.error)); | |
| 205 | return committed.value.commitOid; | |
| 206 | } | |
| 207 | ||
| 208 | beforeAll(async () => { | |
| 209 | dataDir = await mkdtemp(join(tmpdir(), "forge-batch-")); | |
| 210 | app = createApp({ dataDir, port: 0 }); | |
| 211 | servers = await serve(app); | |
| 212 | runtime = runtimeFor(0); | |
| 213 | await runtime.start(); | |
| 214 | const created = await createUser(app.db, { | |
| 215 | origin: "seed", | |
| 216 | trusted: true, | |
| 217 | username: "alice", | |
| 218 | email: "[email protected]", | |
| 219 | password: "a-good-passphrase", | |
| 220 | adminIfFirst: true, | |
| 221 | }); | |
| 222 | if (!created.ok) throw new Error(created.error); | |
| 223 | alice = created.value; | |
| 224 | const made = await newApp(app, alice, { | |
| 225 | name: "steady", | |
| 226 | description: "An app people stay connected to", | |
| 227 | visibility: "public", | |
| 228 | }); | |
| 229 | if (!made.ok) throw new Error(String(made.error)); | |
| 230 | repo = made.value.repo; | |
| 231 | record = made.value.app; | |
| 232 | await settled(() => true); | |
| 233 | }, 180_000); | |
| 234 | ||
| 235 | afterAll(async () => { | |
| 236 | await runtime.stop(); | |
| 237 | servers.stop(); | |
| 238 | app.close(); | |
| 239 | await rm(dataDir, { recursive: true, force: true }); | |
| 240 | }); | |
| 241 | ||
| 242 | test("with no window, every landing asks for a deploy", async () => { | |
| 243 | const before = deploys().length; | |
| 244 | const tip = await land(); | |
| 245 | const run = await until(() => deploys().find((r) => r.commitOid === tip)); | |
| 246 | expect(run.reason).toBe("push"); | |
| 247 | expect(deploys().length).toBe(before + 1); | |
| 248 | expect(production()?.batched).toBeUndefined(); | |
| 249 | await settled((r) => r.id === run.id); | |
| 250 | }, 120_000); | |
| 251 | ||
| 252 | test("ten landings inside the window are one production deploy, of the last", async () => { | |
| 253 | await runtime.stop(); | |
| 254 | // Booting deploys production, which starts the window. | |
| 255 | runtime = runtimeFor(WINDOW); | |
| 256 | await runtime.start(); | |
| 257 | const before = deploys().length; | |
| 258 | const tips: string[] = []; | |
| 259 | for (let i = 0; i < 10; i++) tips.push(await land()); | |
| 260 | const held = await until(() => { | |
| 261 | const b = production()?.batched; | |
| 262 | return b?.changes === 10 ? b : undefined; | |
| 263 | }); | |
| 264 | // No landing asked for a deploy of its own while the window runs. | |
| 265 | expect(deploys().length).toBe(before); | |
| 266 | expect(Date.parse(held.at)).toBeGreaterThan(Date.now()); | |
| 267 | // The page says when, how many, and offers to send them now. | |
| 268 | const base = `/${repo.ownerName}/${repo.name}`; | |
| 269 | const facts = envFacts(base, production()!).text; | |
| 270 | expect(facts).toContain("(10 changes waiting)"); | |
| 271 | expect(facts).toContain('data-tone="attn"'); | |
| 272 | expect(envActions(base, production()!, true).text).toContain("Deploy now"); | |
| 273 | // Every other door says the same: the JSON API, MCP, and the terminal. | |
| 274 | const api = (await ( | |
| 275 | await fetch(`${servers.url}/api/v1/repos${base}/app`) | |
| 276 | ).json()) as { environments: EnvStatus[] }; | |
| 277 | expect( | |
| 278 | api.environments.find((e) => e.env === "production")?.batched, | |
| 279 | ).toEqual({ at: held.at, changes: 10 }); | |
| 280 | const token = createToken(app.db, alice.id, "ro", "ro").token; | |
| 281 | const listed = (await mcpApps(token)).find( | |
| 282 | (a) => a.app === `${repo.ownerName}/${repo.name}`, | |
| 283 | ); | |
| 284 | expect(listed?.nextDeploy).toEqual({ at: held.at, changes: 10 }); | |
| 285 | expect(appHeld(app, alice, repo)).toContain("(10 changes waiting)"); | |
| 286 | const last = tips[tips.length - 1]!; | |
| 287 | const run = await until( | |
| 288 | () => deploys().find((r) => r.commitOid === last), | |
| 289 | WINDOW + 30_000, | |
| 290 | ); | |
| 291 | expect(run.reason).toBe("push"); | |
| 292 | expect(deploys().length).toBe(before + 1); | |
| 293 | for (const tip of tips.slice(0, -1)) | |
| 294 | expect(deploys().some((r) => r.commitOid === tip)).toBe(false); | |
| 295 | expect(production()?.batched).toBeUndefined(); | |
| 296 | await settled((r) => r.id === run.id); | |
| 297 | }, 120_000); | |
| 298 | ||
| 299 | test("Deploy now sends what is held at once", async () => { | |
| 300 | const before = deploys().length; | |
| 301 | const tip = await land(); | |
| 302 | await until(() => (production()?.batched?.changes === 1 ? true : undefined)); | |
| 303 | expect(deploys().length).toBe(before); | |
| 304 | const sent = await redeployEnv(app, alice, repo, "production"); | |
| 305 | expect(sent.ok && sent.value?.commitOid).toBe(tip); | |
| 306 | expect(production()?.batched).toBeUndefined(); | |
| 307 | expect(deploys().length).toBe(before + 1); | |
| 308 | const run = await settled((r) => r.commitOid === tip); | |
| 309 | // Nothing held: the same form says Redeploy, posts to the same place, | |
| 310 | // and still deploys again. | |
| 311 | const base = `/${repo.ownerName}/${repo.name}`; | |
| 312 | const actions = envActions(base, production()!, true).text; | |
| 313 | expect(actions).toContain(`action="${base}/app/production/redeploy"`); | |
| 314 | expect(actions).toContain("Redeploy"); | |
| 315 | expect(actions).not.toContain("Deploy now"); | |
| 316 | expect(appHeld(app, alice, repo)).toBe(""); | |
| 317 | const again = await redeployEnv(app, alice, repo, "production"); | |
| 318 | expect(again.ok && again.value?.id).not.toBe(run.id); | |
| 319 | expect(again.ok && again.value?.reason).toBe("redeploy"); | |
| 320 | if (again.ok && again.value) { | |
| 321 | const id = again.value.id; | |
| 322 | await settled((r) => r.id === id); | |
| 323 | } | |
| 324 | }, 120_000); | |
| 325 | ||
| 326 | test("a batch whose window ends while production is busy waits until it is not", async () => { | |
| 327 | await restart(3_000, { busyRetryMs: 300, busyGraceMs: 120_000 }); | |
| 328 | // Someone holds a stream open to production: a websocket, say. | |
| 329 | const release = runtime.holdStream(record, "production"); | |
| 330 | const before = deploys().length; | |
| 331 | const tip = await land(); | |
| 332 | await until(() => (production()?.batched !== undefined ? true : undefined)); | |
| 333 | // Past the window's end, it is still held, and says why. | |
| 334 | const busy = await until(() => production()?.batched?.busy, 10_000); | |
| 335 | expect(busy).toBe(BUSY_WORDS.stream); | |
| 336 | await Bun.sleep(1_000); | |
| 337 | expect(deploys().length).toBe(before); | |
| 338 | expect(appHeld(app, alice, repo)).toContain("held while busy"); | |
| 339 | release(); | |
| 340 | const run = await until( | |
| 341 | () => deploys().find((r) => r.commitOid === tip), | |
| 342 | 10_000, | |
| 343 | ); | |
| 344 | expect(deploys().length).toBe(before + 1); | |
| 345 | expect(production()?.batched).toBeUndefined(); | |
| 346 | await settled((r) => r.id === run.id); | |
| 347 | }, 120_000); | |
| 348 | ||
| 349 | test("the first landing after a quiet window waits for a busy production too", async () => { | |
| 350 | await restart(1, { busyRetryMs: 300, busyGraceMs: 120_000 }); | |
| 351 | await Bun.sleep(50); | |
| 352 | const release = runtime.holdStream(record, "production"); | |
| 353 | const before = deploys().length; | |
| 354 | const tip = await land(); | |
| 355 | const held = await until(() => production()?.batched); | |
| 356 | expect(held.busy).toBe(BUSY_WORDS.stream); | |
| 357 | await Bun.sleep(800); | |
| 358 | expect(deploys().length).toBe(before); | |
| 359 | release(); | |
| 360 | const run = await until( | |
| 361 | () => deploys().find((r) => r.commitOid === tip), | |
| 362 | 10_000, | |
| 363 | ); | |
| 364 | await settled((r) => r.id === run.id); | |
| 365 | }, 120_000); | |
| 366 | ||
| 367 | test("busy holds a deploy for the busy grace, never longer", async () => { | |
| 368 | await restart(1, { busyRetryMs: 300, busyGraceMs: 1_500 }); | |
| 369 | await Bun.sleep(50); | |
| 370 | const release = runtime.holdStream(record, "production"); | |
| 371 | const tip = await land(); | |
| 372 | const heldAt = Date.now(); | |
| 373 | await until(() => production()?.batched); | |
| 374 | const run = await until( | |
| 375 | () => deploys().find((r) => r.commitOid === tip), | |
| 376 | 10_000, | |
| 377 | ); | |
| 378 | expect(Date.now() - heldAt).toBeGreaterThanOrEqual(1_000); | |
| 379 | release(); | |
| 380 | await settled((r) => r.id === run.id); | |
| 381 | }, 120_000); | |
| 382 | ||
| 383 | test("a swap lets the previous deployment answer what it was asked before stopping it", async () => { | |
| 384 | await restart(0, { drainMs: 30_000 }); | |
| 385 | const old = production()!; | |
| 386 | const oldPort = old.port!; | |
| 387 | expect((await fetch(`http://127.0.0.1:${oldPort}/`)).ok).toBe(true); | |
| 388 | // A request the proxy passed to the running deployment, not answered yet. | |
| 389 | const answered = runtime.holdRequest(record, "production"); | |
| 390 | const sent = await redeployEnv(app, alice, repo, "production"); | |
| 391 | if (!sent.ok || sent.value === undefined) throw new Error("no redeploy"); | |
| 392 | // The new deployment serves... | |
| 393 | const now = await until(() => { | |
| 394 | const p = production(); | |
| 395 | return p?.state === "running" && p.port !== oldPort ? p : undefined; | |
| 396 | }); | |
| 397 | expect(now.runId).toBe(sent.value.id); | |
| 398 | // ...while the old one is still up to finish its answer. | |
| 399 | await Bun.sleep(500); | |
| 400 | expect((await fetch(`http://127.0.0.1:${oldPort}/`)).ok).toBe(true); | |
| 401 | answered(); | |
| 402 | // Answered: now it stops. | |
| 403 | const deadline = Date.now() + 15_000; | |
| 404 | let gone = false; | |
| 405 | while (!gone && Date.now() < deadline) { | |
| 406 | gone = await fetch(`http://127.0.0.1:${oldPort}/`).then( | |
| 407 | () => false, | |
| 408 | () => true, | |
| 409 | ); | |
| 410 | if (!gone) await Bun.sleep(100); | |
| 411 | } | |
| 412 | expect(gone).toBe(true); | |
| 413 | await settled((r) => r.id === sent.value!.id); | |
| 414 | }, 120_000); | |
| 415 | }); |
new above
offline
Check busyReason here and push the batch back a short interval while the app is busy, up to the existing busy grace. Without this, 'not while busy' is not implemented.