Public: anyone can read this; the crew can change it.
Bun process hygiene on a long-lived forge: no piped stdio we never read, RSS beside heap on /system #2062
mason/forge:mason/2041-bun-process-hygiene-on-a-long-lived-forg → main 3 commits fork
15 files
changed +476
−8
scripts/gate.ts +3
| @@ -356,6 +356,9 @@ export const GATE: readonly string[] = [ | ||
| 356 | 356 | "test/roll.test.ts", |
| 357 | 357 | "test/rehearsal.test.ts", |
| 358 | 358 | "test/tui-tell.test.ts", |
| 359 | "test/spawn_stdio.test.ts", | |
| 360 | "test/memory_hours.test.ts", | |
| 361 | "test/settle_on_abort.test.ts", | |
| 359 | 362 | ]; |
| 360 | 363 | |
| 361 | 364 | export const EXCLUDED: readonly Exclusion[] = [ |
src/app.ts +8 −2
| @@ -26,6 +26,7 @@ import { | ||
| 26 | 26 | type Log, |
| 27 | 27 | } from "./kernel/log.ts"; |
| 28 | 28 | import { RefusedLedger } from "./kernel/internal_refused.ts"; |
| 29 | import { MemoryLedger } from "./kernel/memory_hours.ts"; | |
| 29 | 30 | import { closeReadersUnder } from "./git/read.ts"; |
| 30 | 31 | |
| 31 | 32 | export interface ForgeConfig { |
| @@ -191,7 +192,12 @@ export interface App { | ||
| 191 | 192 | /** Per-boot secret every internal request must carry (`FORGE_HOOK_SECRET` in a hook's env). */ |
| 192 | 193 | readonly hookSecret: string; |
| 193 | 194 | /** What `vitals` turns into needs: this forge's own, not the process's. */ |
| 194 | readonly signals: { errors: ErrorLedger; refused: RefusedLedger }; | |
| 195 | readonly signals: { | |
| 196 | errors: ErrorLedger; | |
| 197 | refused: RefusedLedger; | |
| 198 | /** RSS beside the heap, hour by hour (`kernel/memory_hours.ts`). */ | |
| 199 | memory: MemoryLedger; | |
| 200 | }; | |
| 195 | 201 | close(): void; |
| 196 | 202 | } |
| 197 | 203 | |
| @@ -227,7 +233,7 @@ export function createApp(config: ForgeConfig): App { | ||
| 227 | 233 | db, |
| 228 | 234 | bus, |
| 229 | 235 | log: createLog("forge", owner), |
| 230 | signals: { errors, refused: new RefusedLedger() }, | |
| 236 | signals: { errors, refused: new RefusedLedger(), memory: new MemoryLedger() }, | |
| 231 | 237 | reposRoot, |
| 232 | 238 | // This process's own: two forges share a data directory for the length |
| 233 | 239 | // of a release, and each spawns git with its own socket in the env. |
src/chaos/invariants.ts +2
| @@ -63,6 +63,8 @@ const pullsKeepHeads: Invariant = { | ||
| 63 | 63 | const dir = repoDir(world.app.reposRoot, p.owner, p.name); |
| 64 | 64 | const has = Bun.spawnSync(["git", "cat-file", "-e", `${p.head_oid}^{commit}`], { |
| 65 | 65 | cwd: dir, |
| 66 | stdout: "ignore", | |
| 67 | stderr: "ignore", | |
| 66 | 68 | }); |
| 67 | 69 | if (has.exitCode !== 0) broken.push(`pull head ${p.head_oid} is gone from ${p.owner}/${p.name}`); |
| 68 | 70 | } |
src/cli/config.ts +1 −1
| @@ -71,7 +71,7 @@ async function security( | ||
| 71 | 71 | const proc = Bun.spawn(["security", ...args], { |
| 72 | 72 | stdin: stdin === undefined ? "ignore" : new Blob([stdin]), |
| 73 | 73 | stdout: "pipe", |
| 74 | stderr: "pipe", | |
| 74 | stderr: "ignore", | |
| 75 | 75 | }); |
| 76 | 76 | const [out, code] = await Promise.all([ |
| 77 | 77 | new Response(proc.stdout).text(), |
src/crew/claude.ts +1 −1
| @@ -528,7 +528,7 @@ export async function detectClaude( | ||
| 528 | 528 | env: childEnv({}), |
| 529 | 529 | stdin: "ignore", |
| 530 | 530 | stdout: "pipe", |
| 531 | stderr: "pipe", | |
| 531 | stderr: "ignore", | |
| 532 | 532 | }); |
| 533 | 533 | const timer = setTimeout(() => proc.kill("SIGKILL"), 10_000); |
| 534 | 534 | const [out, code] = await Promise.all([ |
src/git/smart-http.ts +4 −2
| @@ -127,7 +127,9 @@ async function spawnService( | ||
| 127 | 127 | env: gitEnv(env), |
| 128 | 128 | stdin: "pipe", |
| 129 | 129 | stdout: "pipe", |
| 130 | stderr: "pipe", | |
| 130 | // Nothing reads git's narration here; a pipe left unread holds native | |
| 131 | // memory for the whole transfer and stalls git once it fills (#2041). | |
| 132 | stderr: "ignore", | |
| 131 | 133 | }); |
| 132 | 134 | let proc: ReturnType<typeof spawn>; |
| 133 | 135 | try { |
| @@ -174,7 +176,7 @@ async function spawnService( | ||
| 174 | 176 | * loose in the process. |
| 175 | 177 | */ |
| 176 | 178 | async function feedStdin( |
| 177 | proc: Bun.Subprocess<"pipe", "pipe", "pipe">, | |
| 179 | proc: Bun.Subprocess<"pipe", "pipe", "ignore">, | |
| 178 | 180 | service: GitService, |
| 179 | 181 | request: Request, |
| 180 | 182 | ): Promise<void> { |
src/http/abort.ts added +31
| @@ -0,0 +1,31 @@ | ||
| 1 | /** | |
| 2 | * A request whose client hung up is answered at once with 499, whatever the | |
| 3 | * handler is still waiting on. Bun holds a request's context until the | |
| 4 | * promise `fetch` returned settles, so a handler parked on something that | |
| 5 | * never comes back — a queue, a lock, a child — would hold it for the life | |
| 6 | * of the process once its caller left (#2041). The handler keeps running to | |
| 7 | * its end; only the answer nobody will read is let go. | |
| 8 | */ | |
| 9 | ||
| 10 | /** Client Closed Request: nginx's code, for an answer no one is waiting for. */ | |
| 11 | export const CLIENT_CLOSED = 499; | |
| 12 | ||
| 13 | export function settleOnAbort<T extends Response | undefined>( | |
| 14 | request: Request, | |
| 15 | handled: Promise<T>, | |
| 16 | ): Promise<T | Response> { | |
| 17 | const { signal } = request; | |
| 18 | // A handler that fails after its client left fails into nobody's hands. | |
| 19 | handled.catch(() => {}); | |
| 20 | if (signal.aborted) return Promise.resolve(closed()); | |
| 21 | let onAbort: () => void = () => {}; | |
| 22 | const aborted = new Promise<Response>((resolve) => { | |
| 23 | onAbort = () => resolve(closed()); | |
| 24 | signal.addEventListener("abort", onAbort, { once: true }); | |
| 25 | }); | |
| 26 | return Promise.race([handled, aborted]).finally(() => | |
| 27 | signal.removeEventListener("abort", onAbort), | |
| 28 | ); | |
| 29 | } | |
| 30 | ||
| 31 | const closed = (): Response => new Response(null, { status: CLIENT_CLOSED }); |
src/http/server.ts +3 −1
| @@ -53,6 +53,7 @@ import { | ||
| 53 | 53 | isActive, |
| 54 | 54 | verifyPassword, |
| 55 | 55 | } from "../core/users.ts"; |
| 56 | import { settleOnAbort } from "./abort.ts"; | |
| 56 | 57 | import { edgeIdentity } from "./edge.ts"; |
| 57 | 58 | import { liveResponse, readyResponse } from "./health.ts"; |
| 58 | 59 | import { runGit } from "../git/env.ts"; |
| @@ -1879,7 +1880,8 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1879 | 1880 | // The only sockets the forge holds are an app's, carried through the |
| 1880 | 1881 | // proxy; its own live surfaces are SSE (`sse.ts`) and stay so. |
| 1881 | 1882 | websocket: appWebSocket, |
| 1882 | fetch: handle, | |
| 1883 | // A client that hung up is answered 499 at once, so its context goes. | |
| 1884 | fetch: (request, server) => settleOnAbort(request, handle(request, server)), | |
| 1883 | 1885 | error(error) { |
| 1884 | 1886 | const refused = refusedByDatabase(error); |
| 1885 | 1887 | if (refused !== undefined) { |
src/kernel/memory_hours.ts added +72
| @@ -0,0 +1,72 @@ | ||
| 1 | /** | |
| 2 | * This process's memory, hour by hour: resident size beside the JavaScript | |
| 3 | * heap. RSS that climbs while the heap stays flat is native memory — a pipe | |
| 4 | * nobody reads, a request context never released (#2041) — and the two side | |
| 5 | * by side are how a person tells that from a heap that is simply growing. | |
| 6 | * Kept in memory and bounded: the latest reading of each hour, two days of | |
| 7 | * them; a restart starts the table again, as it starts the process again. | |
| 8 | */ | |
| 9 | ||
| 10 | import { heapStats } from "bun:jsc"; | |
| 11 | ||
| 12 | /** How many hours the table keeps. */ | |
| 13 | export const HOURS_KEPT = 48; | |
| 14 | const HOUR_MS = 3_600_000; | |
| 15 | ||
| 16 | export interface MemoryReading { | |
| 17 | /** The hour this reading stands for, `YYYY-MM-DDTHH:00Z`. */ | |
| 18 | readonly hour: string; | |
| 19 | readonly at: string; | |
| 20 | readonly rssBytes: number; | |
| 21 | readonly heapBytes: number; | |
| 22 | readonly heapCapacityBytes: number; | |
| 23 | readonly objects: number; | |
| 24 | } | |
| 25 | ||
| 26 | /** Read this process's memory now. */ | |
| 27 | export function readMemory(now: number = Date.now()): MemoryReading { | |
| 28 | const heap = heapStats(); | |
| 29 | return { | |
| 30 | hour: `${new Date(Math.floor(now / HOUR_MS) * HOUR_MS).toISOString().slice(0, 13)}:00Z`, | |
| 31 | at: new Date(now).toISOString(), | |
| 32 | rssBytes: process.memoryUsage().rss, | |
| 33 | heapBytes: heap.heapSize, | |
| 34 | heapCapacityBytes: heap.heapCapacity, | |
| 35 | objects: heap.objectCount, | |
| 36 | }; | |
| 37 | } | |
| 38 | ||
| 39 | /** One forge's hourly memory (`App.signals.memory`). */ | |
| 40 | export class MemoryLedger { | |
| 41 | private hours: MemoryReading[] = []; | |
| 42 | ||
| 43 | /** Keep `reading` as its hour's; a later reading in the same hour replaces it. */ | |
| 44 | note(reading: MemoryReading): void { | |
| 45 | if (this.hours.at(-1)?.hour === reading.hour) this.hours[this.hours.length - 1] = reading; | |
| 46 | else this.hours.push(reading); | |
| 47 | if (this.hours.length > HOURS_KEPT) this.hours = this.hours.slice(-HOURS_KEPT); | |
| 48 | } | |
| 49 | ||
| 50 | /** The kept hours, newest first. */ | |
| 51 | recent(): MemoryReading[] { | |
| 52 | return this.hours.slice().reverse(); | |
| 53 | } | |
| 54 | } | |
| 55 | ||
| 56 | /** | |
| 57 | * How far RSS moved over the kept hours against how far the heap did, as | |
| 58 | * a share of the first reading: `{ rss: 0.4, heap: 0.02 }` is native growth. | |
| 59 | * Undefined with fewer than two hours. | |
| 60 | */ | |
| 61 | export function memoryDrift( | |
| 62 | hours: readonly MemoryReading[], | |
| 63 | ): { rss: number; heap: number } | undefined { | |
| 64 | if (hours.length < 2) return undefined; | |
| 65 | const newest = hours[0]!; | |
| 66 | const oldest = hours.at(-1)!; | |
| 67 | const share = (to: number, from: number) => (from === 0 ? 0 : (to - from) / from); | |
| 68 | return { | |
| 69 | rss: share(newest.rssBytes, oldest.rssBytes), | |
| 70 | heap: share(newest.heapBytes, oldest.heapBytes), | |
| 71 | }; | |
| 72 | } |
src/main.ts +8
| @@ -22,6 +22,7 @@ import { isHookName, runHookClient } from "./git/hooks.ts"; | ||
| 22 | 22 | import { drainStreams } from "./http/sse.ts"; |
| 23 | 23 | import { serve } from "./http/server.ts"; |
| 24 | 24 | import { runSync } from "./origins/sync.ts"; |
| 25 | import { readMemory } from "./kernel/memory_hours.ts"; | |
| 25 | 26 | import { startForgeSsh } from "./tui/ssh.ts"; |
| 26 | 27 | import { AppsRuntime } from "./apps/runtime.ts"; |
| 27 | 28 | import { resolveAppDomain } from "./apps/host.ts"; |
| @@ -404,6 +405,12 @@ function positive(value: string | undefined, fallback: number): number { | ||
| 404 | 405 | const syncTimer = setInterval(() => runSync(app), 60_000); |
| 405 | 406 | runSync(app); // one pass on boot: a forge that was down has fetching to do |
| 406 | 407 | |
| 408 | // RSS beside the heap, kept per hour for the capacity page: a reading every | |
| 409 | // ten minutes, the hour's latest kept (`kernel/memory_hours.ts`). | |
| 410 | const noteMemory = () => app.signals.memory.note(readMemory()); | |
| 411 | const memoryTimer = setInterval(noteMemory, 10 * 60_000); | |
| 412 | noteMemory(); | |
| 413 | ||
| 407 | 414 | // Which green pulls no longer merge as they stand, so the asks can leave |
| 408 | 415 | // them out (`crew/stale_asks.ts`): git answers, off the request path, and an |
| 409 | 416 | // unchanged pull costs two ref reads. Never throws into the timer. |
| @@ -513,6 +520,7 @@ function shutdown(signal: NodeJS.Signals): void { | ||
| 513 | 520 | clearInterval(deliveryTimer); |
| 514 | 521 | clearInterval(heartbeatTimer); |
| 515 | 522 | clearInterval(syncTimer); |
| 523 | clearInterval(memoryTimer); | |
| 516 | 524 | clearInterval(staleTimer); |
| 517 | 525 | clearInterval(leaseTimer); |
| 518 | 526 | // The platform's SIGTERM: the listener stays open while routers learn |
src/web/pages/capacity.ts +69 −1
| @@ -4,6 +4,8 @@ | ||
| 4 | 4 | * refused or reported (`core/capacity.ts`). A change here is honoured by |
| 5 | 5 | * the next run, check or cell — never by a restart, which is the point — |
| 6 | 6 | * and each one is listed below the settings: who, when, from what to what. |
| 7 | * Above them, what is happening: errors, refused calls, and this process's | |
| 8 | * memory — resident size beside the heap, hour by hour. | |
| 7 | 9 | */ |
| 8 | 10 | |
| 9 | 11 | import { changeCapacity, listCapacity } from "../../actions/capacity.ts"; |
| @@ -15,6 +17,72 @@ import { html, when } from "../html.ts"; | ||
| 15 | 17 | import { flashTo, page } from "../layout.ts"; |
| 16 | 18 | import { btn, card, icon, row, time } from "../ui.ts"; |
| 17 | 19 | import { accountSections } from "./origins.ts"; |
| 20 | import { | |
| 21 | memoryDrift, | |
| 22 | readMemory, | |
| 23 | type MemoryReading, | |
| 24 | } from "../../kernel/memory_hours.ts"; | |
| 25 | ||
| 26 | const mb = (bytes: number): string => `${Math.round(bytes / 1_048_576)} MB`; | |
| 27 | const percent = (share: number): string => | |
| 28 | `${share >= 0 ? "+" : ""}${Math.round(share * 100)}%`; | |
| 29 | ||
| 30 | function memoryRow(r: MemoryReading) { | |
| 31 | return html`<tr> | |
| 32 | <td class="mono">${r.hour}</td> | |
| 33 | <td class="mono">${mb(r.rssBytes)}</td> | |
| 34 | <td class="mono">${mb(r.heapBytes)}</td> | |
| 35 | <td class="mono">${mb(r.heapCapacityBytes)}</td> | |
| 36 | <td class="mono">${String(r.objects)}</td> | |
| 37 | </tr>`; | |
| 38 | } | |
| 39 | ||
| 40 | /** | |
| 41 | * RSS beside the heap: now, and the latest reading of each kept hour. A | |
| 42 | * resident size that climbs while the heap holds is native memory. | |
| 43 | */ | |
| 44 | function memoryCard(hours: readonly MemoryReading[]) { | |
| 45 | const now = readMemory(); | |
| 46 | const drift = memoryDrift(hours); | |
| 47 | return card( | |
| 48 | html`<div class="card-body"> | |
| 49 | <p class="muted small"> | |
| 50 | Now: resident <span class="mono">${mb(now.rssBytes)}</span>, heap | |
| 51 | <span class="mono">${mb(now.heapBytes)}</span> of | |
| 52 | <span class="mono">${mb(now.heapCapacityBytes)}</span>, | |
| 53 | <span class="mono">${String(now.objects)}</span> objects. | |
| 54 | ${drift === undefined | |
| 55 | ? "Hourly readings appear once the forge has run two hours." | |
| 56 | : html`Over the ${String(hours.length)} hours kept, resident moved | |
| 57 | <span class="mono">${percent(drift.rss)}</span> and the heap | |
| 58 | <span class="mono">${percent(drift.heap)}</span>; resident | |
| 59 | climbing while the heap holds is native memory.`} | |
| 60 | </p> | |
| 61 | </div> | |
| 62 | ${when( | |
| 63 | hours.length > 0, | |
| 64 | () => html`<div class="table-scroll"><table class="table" data-dense> | |
| 65 | <thead> | |
| 66 | <tr> | |
| 67 | <th>Hour</th> | |
| 68 | <th>Resident</th> | |
| 69 | <th>Heap</th> | |
| 70 | <th>Heap capacity</th> | |
| 71 | <th>Objects</th> | |
| 72 | </tr> | |
| 73 | </thead> | |
| 74 | <tbody> | |
| 75 | ${hours.map(memoryRow)} | |
| 76 | </tbody> | |
| 77 | </table></div>`, | |
| 78 | )}`, | |
| 79 | { | |
| 80 | head: html`${icon("activity")} | |
| 81 | <h2 id="memory">Memory</h2>`, | |
| 82 | pad: false, | |
| 83 | }, | |
| 84 | ); | |
| 85 | } | |
| 18 | 86 | |
| 19 | 87 | function requireAdmin(ctx: Ctx): Response | undefined { |
| 20 | 88 | if (!ctx.auth.user) return signInFirst(ctx); |
| @@ -128,7 +196,7 @@ export function capacityPage(ctx: Ctx): Response { | ||
| 128 | 196 | pad: false, |
| 129 | 197 | }, |
| 130 | 198 | ); |
| 131 | const body = html`${happened}${when( | |
| 199 | const body = html`${happened}${memoryCard(ctx.app.signals.memory.recent())}${when( | |
| 132 | 200 | reported, |
| 133 | 201 | () => html`<p class="muted small mb" id="egress-reported"> |
| 134 | 202 | ${icon("activity")} Egress is reported, not enforced: every new app, |
test/capacity.test.ts +26
| @@ -190,6 +190,32 @@ describe("capacity: only a forge admin reads or changes it", () => { | ||
| 190 | 190 | expect(capacityChanges(app.db)).toEqual([]); |
| 191 | 191 | }); |
| 192 | 192 | |
| 193 | test("an admin sees resident memory beside the heap, now and per kept hour; a member does not", async () => { | |
| 194 | app.signals.memory.note({ | |
| 195 | hour: "2026-10-16T03:00Z", | |
| 196 | at: "2026-10-16T03:50:00.000Z", | |
| 197 | rssBytes: 300 * 1_048_576, | |
| 198 | heapBytes: 40 * 1_048_576, | |
| 199 | heapCapacityBytes: 64 * 1_048_576, | |
| 200 | objects: 123_456, | |
| 201 | }); | |
| 202 | const cookie = await login("alice"); | |
| 203 | const page = await ( | |
| 204 | await fetch(`${servers.url}/settings/capacity`, { headers: { cookie } }) | |
| 205 | ).text(); | |
| 206 | expect(page).toContain('id="memory"'); | |
| 207 | expect(page).toMatch(/Now: resident <span class="mono">\d+ MB<\/span>, heap/); | |
| 208 | expect(page).toContain("2026-10-16T03:00Z"); | |
| 209 | expect(page).toContain("300 MB"); | |
| 210 | expect(page).toContain("123456"); | |
| 211 | ||
| 212 | const bobPage = await fetch(`${servers.url}/settings/capacity`, { | |
| 213 | headers: { cookie: await login("bob") }, | |
| 214 | }); | |
| 215 | expect(bobPage.status).toBe(404); | |
| 216 | expect(await bobPage.text()).not.toContain("123456"); | |
| 217 | }); | |
| 218 | ||
| 193 | 219 | test("an admin with a read-only token may read, not change", async () => { |
| 194 | 220 | expect((await api(aliceRo, "GET", "/admin/capacity")).status).toBe(200); |
| 195 | 221 | expect( |
test/memory_hours.test.ts added +59
| @@ -0,0 +1,59 @@ | ||
| 1 | /** | |
| 2 | * RSS beside the heap, hour by hour (#2041): one reading kept per hour, the | |
| 3 | * hour's latest; two days of them; and the drift that tells native growth | |
| 4 | * from a heap that is simply growing. | |
| 5 | */ | |
| 6 | ||
| 7 | import { describe, expect, test } from "bun:test"; | |
| 8 | import { | |
| 9 | HOURS_KEPT, | |
| 10 | MemoryLedger, | |
| 11 | memoryDrift, | |
| 12 | readMemory, | |
| 13 | type MemoryReading, | |
| 14 | } from "../src/kernel/memory_hours.ts"; | |
| 15 | ||
| 16 | const HOUR = 3_600_000; | |
| 17 | const at = (hour: number, rss: number, heap: number): MemoryReading => ({ | |
| 18 | ...readMemory(Date.UTC(2026, 9, 16) + hour * HOUR), | |
| 19 | rssBytes: rss, | |
| 20 | heapBytes: heap, | |
| 21 | }); | |
| 22 | ||
| 23 | describe("memory, hour by hour", () => { | |
| 24 | test("a reading names its hour, and carries both the resident size and the heap", () => { | |
| 25 | const r = readMemory(Date.UTC(2026, 9, 16, 4, 37)); | |
| 26 | expect(r.hour).toBe("2026-10-16T04:00Z"); | |
| 27 | expect(r.rssBytes).toBeGreaterThan(0); | |
| 28 | expect(r.heapBytes).toBeGreaterThan(0); | |
| 29 | expect(r.heapCapacityBytes).toBeGreaterThanOrEqual(r.heapBytes); | |
| 30 | expect(r.objects).toBeGreaterThan(0); | |
| 31 | }); | |
| 32 | ||
| 33 | test("a later reading in the same hour replaces it; a new hour adds one, newest first", () => { | |
| 34 | const ledger = new MemoryLedger(); | |
| 35 | ledger.note(at(0, 100, 10)); | |
| 36 | ledger.note({ ...at(0, 110, 10), at: "later" }); | |
| 37 | ledger.note(at(1, 120, 10)); | |
| 38 | expect(ledger.recent().map((r) => [r.hour, r.rssBytes])).toEqual([ | |
| 39 | ["2026-10-16T01:00Z", 120], | |
| 40 | ["2026-10-16T00:00Z", 110], | |
| 41 | ]); | |
| 42 | }); | |
| 43 | ||
| 44 | test("only the last two days are kept", () => { | |
| 45 | const ledger = new MemoryLedger(); | |
| 46 | for (let h = 0; h < HOURS_KEPT + 5; h++) ledger.note(at(h, 100, 10)); | |
| 47 | const kept = ledger.recent(); | |
| 48 | expect(kept).toHaveLength(HOURS_KEPT); | |
| 49 | expect(kept.at(-1)!.hour).toBe(at(5, 0, 0).hour); | |
| 50 | }); | |
| 51 | ||
| 52 | test("drift: resident climbing beside a flat heap is told apart from both climbing", () => { | |
| 53 | expect(memoryDrift([])).toBeUndefined(); | |
| 54 | expect(memoryDrift([at(0, 100, 10)])).toBeUndefined(); | |
| 55 | // newest first, as the ledger hands them out | |
| 56 | expect(memoryDrift([at(2, 150, 10), at(0, 100, 10)])).toEqual({ rss: 0.5, heap: 0 }); | |
| 57 | expect(memoryDrift([at(2, 200, 20), at(0, 100, 10)])).toEqual({ rss: 1, heap: 1 }); | |
| 58 | }); | |
| 59 | }); |
test/settle_on_abort.test.ts added +79
| @@ -0,0 +1,79 @@ | ||
| 1 | /** | |
| 2 | * A request whose client hung up is answered 499 at once, whatever its | |
| 3 | * handler still waits on, so Bun lets its context go (#2041) — directly, and | |
| 4 | * through the forge's own server. | |
| 5 | */ | |
| 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 { CLIENT_CLOSED, settleOnAbort } from "../src/http/abort.ts"; | |
| 13 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 14 | ||
| 15 | const never = <T>() => new Promise<T>(() => {}); | |
| 16 | ||
| 17 | describe("an aborted request", () => { | |
| 18 | test("settles 499 when its client hangs up, though the handler never does", async () => { | |
| 19 | const client = new AbortController(); | |
| 20 | const request = new Request("http://forge/x", { signal: client.signal }); | |
| 21 | const answer = settleOnAbort(request, never<Response>()); | |
| 22 | client.abort(); | |
| 23 | expect((await answer).status).toBe(CLIENT_CLOSED); | |
| 24 | }); | |
| 25 | ||
| 26 | test("already aborted on arrival is answered 499 without waiting", async () => { | |
| 27 | const request = new Request("http://forge/x", { signal: AbortSignal.abort() }); | |
| 28 | expect((await settleOnAbort(request, never<Response>())).status).toBe(CLIENT_CLOSED); | |
| 29 | }); | |
| 30 | ||
| 31 | test("a handler that answers first is the answer, and a later hang-up changes nothing", async () => { | |
| 32 | const client = new AbortController(); | |
| 33 | const request = new Request("http://forge/x", { signal: client.signal }); | |
| 34 | const answer = await settleOnAbort(request, Promise.resolve(new Response("ok"))); | |
| 35 | client.abort(); | |
| 36 | expect(answer.status).toBe(200); | |
| 37 | expect(await answer.text()).toBe("ok"); | |
| 38 | }); | |
| 39 | ||
| 40 | test("a handler's failure before any hang-up still reaches the server's error door", async () => { | |
| 41 | const request = new Request("http://forge/x", { signal: new AbortController().signal }); | |
| 42 | await expect(settleOnAbort(request, Promise.reject(new Error("boom")))).rejects.toThrow("boom"); | |
| 43 | }); | |
| 44 | ||
| 45 | test("a handler that fails after its client left raises nothing", async () => { | |
| 46 | const client = new AbortController(); | |
| 47 | const request = new Request("http://forge/x", { signal: client.signal }); | |
| 48 | let fail: (e: Error) => void = () => {}; | |
| 49 | const handled = new Promise<Response>((_, reject) => (fail = reject)); | |
| 50 | const answer = settleOnAbort(request, handled); | |
| 51 | client.abort(); | |
| 52 | expect((await answer).status).toBe(CLIENT_CLOSED); | |
| 53 | fail(new Error("too late")); | |
| 54 | await Bun.sleep(0); | |
| 55 | }); | |
| 56 | }); | |
| 57 | ||
| 58 | describe("the forge's server", () => { | |
| 59 | let dataDir: string; | |
| 60 | let app: App; | |
| 61 | let servers: Servers; | |
| 62 | ||
| 63 | beforeAll(async () => { | |
| 64 | dataDir = await mkdtemp(join(tmpdir(), "forge-abort-")); | |
| 65 | app = createApp({ dataDir, port: 0 }); | |
| 66 | servers = await serve(app); | |
| 67 | }); | |
| 68 | ||
| 69 | afterAll(async () => { | |
| 70 | servers.stop(); | |
| 71 | app.close(); | |
| 72 | await rm(dataDir, { recursive: true, force: true }); | |
| 73 | }); | |
| 74 | ||
| 75 | test("still answers an ordinary request in full", async () => { | |
| 76 | const res = await fetch(`${servers.url}/healthz`); | |
| 77 | expect(res.status).toBe(200); | |
| 78 | }); | |
| 79 | }); |
test/spawn_stdio.test.ts added +110
| @@ -0,0 +1,110 @@ | ||
| 1 | /** | |
| 2 | * A pipe nobody reads is native memory held for the child's whole life, and | |
| 3 | * a full one stalls the child (#2041, oven-sh/bun#18265). Every `Bun.spawn` | |
| 4 | * and `Bun.spawnSync` in `src` either ignores a stream or reads it: a | |
| 5 | * stream that is piped, by name or by Bun's default, must be met by a read | |
| 6 | * of that stream in the same top-level declaration (or, where the process | |
| 7 | * is returned, by its callers in the same file). | |
| 8 | */ | |
| 9 | ||
| 10 | import { describe, expect, test } from "bun:test"; | |
| 11 | import { readdirSync, readFileSync } from "node:fs"; | |
| 12 | import { join, relative } from "node:path"; | |
| 13 | ||
| 14 | const root = new URL("..", import.meta.url).pathname; | |
| 15 | ||
| 16 | function sources(dir: string): string[] { | |
| 17 | return readdirSync(dir, { withFileTypes: true }).flatMap((e) => { | |
| 18 | const path = join(dir, e.name); | |
| 19 | if (e.isDirectory()) return sources(path); | |
| 20 | return e.name.endsWith(".ts") ? [path] : []; | |
| 21 | }); | |
| 22 | } | |
| 23 | ||
| 24 | interface Site { | |
| 25 | readonly id: string; | |
| 26 | readonly sync: boolean; | |
| 27 | /** From the call to the next top-level declaration. */ | |
| 28 | readonly body: string; | |
| 29 | /** The whole file: a site that returns its process is read by its callers. */ | |
| 30 | readonly file: string; | |
| 31 | } | |
| 32 | ||
| 33 | function spawnSites(file: string, text: string): Site[] { | |
| 34 | const sites: Site[] = []; | |
| 35 | for (const m of text.matchAll(/Bun\.spawn(Sync)?\(/g)) { | |
| 36 | const start = m.index!; | |
| 37 | const rest = text.slice(start); | |
| 38 | const end = rest.search(/\n(?:export |async |function |const |let |class |interface |type )/); | |
| 39 | const line = text.slice(0, start).split("\n").length; | |
| 40 | sites.push({ | |
| 41 | id: `${file}:${line}`, | |
| 42 | sync: m[1] === "Sync", | |
| 43 | body: end === -1 ? rest : rest.slice(0, end), | |
| 44 | file: text, | |
| 45 | }); | |
| 46 | } | |
| 47 | return sites; | |
| 48 | } | |
| 49 | ||
| 50 | /** The unread pipes at one site, by stream name. */ | |
| 51 | function unreadPipes(site: Site): string[] { | |
| 52 | const handedOn = /\breturn (?:this\.)?proc\b/.test(site.body); | |
| 53 | const unread: string[] = []; | |
| 54 | // A terminal stands in for both streams. | |
| 55 | if (/\bterminal\b/.test(site.body)) return unread; | |
| 56 | for (const stream of ["stdout", "stderr"] as const) { | |
| 57 | // Bun's defaults: spawnSync collects both; spawn pipes stdout only. | |
| 58 | const named = | |
| 59 | new RegExp(`\\b${stream}:\\s*"(\\w+)"`).exec(site.body)?.[1] ?? | |
| 60 | (site.sync || stream === "stdout" ? "pipe" : "inherit"); | |
| 61 | if (named !== "pipe") continue; | |
| 62 | const read = new RegExp(`\\.${stream}\\b`); | |
| 63 | if (!read.test(site.body) && !(handedOn && read.test(site.file))) | |
| 64 | unread.push(stream); | |
| 65 | } | |
| 66 | return unread; | |
| 67 | } | |
| 68 | ||
| 69 | describe("spawned processes", () => { | |
| 70 | test("never pipe a stream nobody reads", () => { | |
| 71 | const found: string[] = []; | |
| 72 | for (const path of sources(join(root, "src"))) { | |
| 73 | const file = relative(root, path); | |
| 74 | for (const site of spawnSites(file, readFileSync(path, "utf8"))) | |
| 75 | for (const stream of unreadPipes(site)) found.push(`${site.id} ${stream}`); | |
| 76 | } | |
| 77 | expect(found).toEqual([]); | |
| 78 | }); | |
| 79 | ||
| 80 | test("the audit names a piped stream left unread, and passes one that is read", () => { | |
| 81 | const [unread] = spawnSites( | |
| 82 | "x.ts", | |
| 83 | `async function f() { | |
| 84 | const proc = Bun.spawn(["git"], { stdout: "pipe", stderr: "pipe" }); | |
| 85 | return new Response(proc.stdout); | |
| 86 | } | |
| 87 | `, | |
| 88 | ); | |
| 89 | expect(unreadPipes(unread!)).toEqual(["stderr"]); | |
| 90 | const [sync] = spawnSites("x.ts", `const r = Bun.spawnSync(["git"], { cwd });\n`); | |
| 91 | expect(unreadPipes(sync!)).toEqual(["stdout", "stderr"]); | |
| 92 | const [read] = spawnSites( | |
| 93 | "x.ts", | |
| 94 | `const p = Bun.spawn(["git"], { stdout: "ignore", stderr: "pipe" }); | |
| 95 | await new Response(p.stderr).text(); | |
| 96 | `, | |
| 97 | ); | |
| 98 | expect(unreadPipes(read!)).toEqual([]); | |
| 99 | const [returned] = spawnSites( | |
| 100 | "x.ts", | |
| 101 | `function spawn() { | |
| 102 | const proc = Bun.spawn(["git"], { stdout: "pipe", stderr: "pipe" }); | |
| 103 | return proc; | |
| 104 | } | |
| 105 | const body = spawn().stdout; | |
| 106 | `, | |
| 107 | ); | |
| 108 | expect(unreadPipes(returned!)).toEqual(["stderr"]); | |
| 109 | }); | |
| 110 | }); |
new above
offline