Repository navigation
fetch: cap the GC-triggered drain of an abandoned Response body #35819
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
8bfccf7
fetch: cap the GC-triggered drain of an abandoned Response body
robobun f4bdff3
fetch: lock mutex around body_size read and compare wire bytes directly
robobun 9d481e4
trim doc comments
robobun a9e3a17
fetch: drop the mutex lock in the finalizer drain check (JS-thread re…
robobun 188fd7c
fetch: read content-length via an atomic in the finalizer; guard on_w…
robobun 420c493
[autofix.ci] apply automated fixes
autofix-ci[bot] f81d23d
ci: retrigger
robobun File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
111 changes: 111 additions & 0 deletions
111
test/js/web/fetch/fetch-response-abandoned-drain.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| // When a fetch() Response is dropped without the body being read, the Weak | ||
| // finalizer on the JS Response wrapper reaches | ||
| // FetchTasklet::on_response_finalize (scenario 3: Locked body, no stream, no | ||
| // promise). Previously that path unconditionally drained the remaining body so | ||
| // the connection could be pooled, with no upper bound: an abandoned 32 MB | ||
| // response was read in full and the socket reused. Now the drain is capped at | ||
| // 256 KiB of remaining Content-Length; anything larger (or chunked/unknown) | ||
| // closes the connection instead. | ||
|
|
||
| import { describe, expect, test } from "bun:test"; | ||
| import { bunEnv, bunExe, isWindows } from "harness"; | ||
|
|
||
| // The server writes the body in 16 KiB chunks, pausing on backpressure so | ||
| // `bodyWritten` tracks what the client actually pulled plus at most one kernel | ||
| // send buffer. The client fetches, drops the Response, forces GC so the Weak | ||
| // finalizer runs, and then waits until the server has either sent the whole | ||
| // body or seen the socket close. | ||
| function fixture(contentLength: number) { | ||
| return /* js */ ` | ||
| const net = require("node:net"); | ||
|
|
||
| const contentLength = ${contentLength}; | ||
| const chunk = Buffer.alloc(16 * 1024, 0x61); | ||
| let bodyWritten = 0; | ||
| let conn; | ||
| const { promise: done, resolve: onDone } = Promise.withResolvers(); | ||
|
|
||
| const server = net.createServer(socket => { | ||
| conn = socket; | ||
| socket.on("error", () => {}); | ||
| socket.on("close", onDone); | ||
| let replied = false; | ||
| socket.on("data", () => { | ||
| if (replied) return; | ||
| replied = true; | ||
| socket.write( | ||
| "HTTP/1.1 200 OK\\r\\n" + | ||
| "Content-Length: " + contentLength + "\\r\\n" + | ||
| "Connection: keep-alive\\r\\n" + | ||
| "\\r\\n", | ||
| ); | ||
| const writeMore = () => { | ||
| while (bodyWritten < contentLength && !socket.destroyed) { | ||
| const n = Math.min(chunk.length, contentLength - bodyWritten); | ||
| const ok = socket.write(n === chunk.length ? chunk : chunk.subarray(0, n)); | ||
| bodyWritten += n; | ||
| if (!ok) return socket.once("drain", writeMore); | ||
| } | ||
| onDone(); | ||
| }; | ||
| writeMore(); | ||
| }); | ||
| }); | ||
| await new Promise(r => server.listen(0, "127.0.0.1", r)); | ||
| const port = server.address().port; | ||
|
|
||
| let collected = false; | ||
| const reg = new FinalizationRegistry(() => { collected = true; }); | ||
| async function once() { | ||
| const res = await fetch("http://127.0.0.1:" + port + "/"); | ||
| if (res.status !== 200) throw new Error("status " + res.status); | ||
| reg.register(res, 0); | ||
| // Drop the Response without touching .body / .text() etc. | ||
| } | ||
| await once(); | ||
| while (!collected) { | ||
| Bun.gc(true); | ||
| await new Promise(r => setImmediate(r)); | ||
| } | ||
|
|
||
| await done; | ||
| await new Promise(r => setImmediate(r)); | ||
|
|
||
| console.log(bodyWritten + " " + (conn.destroyed ? "closed" : "open")); | ||
| conn.destroy(); | ||
| server.close(); | ||
| `; | ||
| } | ||
|
|
||
| async function run(contentLength: number) { | ||
| await using proc = Bun.spawn({ | ||
| cmd: [bunExe(), "-e", fixture(contentLength)], | ||
| env: bunEnv, | ||
| stdout: "pipe", | ||
| stderr: "pipe", | ||
| }); | ||
| const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); | ||
| expect({ stderr, exitCode }).toEqual({ stderr: expect.any(String), exitCode: 0 }); | ||
| const [bodyWritten, state] = stdout.trim().split(" "); | ||
| return { bodyWritten: Number(bodyWritten), state }; | ||
| } | ||
|
|
||
| // Platform-independent code path; collectContinuously-style GC tests are slow | ||
| // on Windows CI so keep this off there (matches fetch-response-finalizer-sweep). | ||
| describe.skipIf(isWindows)("fetch: abandoned Response body drain policy", () => { | ||
| test("small body (64 KiB) is drained so the connection stays poolable", async () => { | ||
| const { bodyWritten, state } = await run(64 * 1024); | ||
| expect({ bodyWritten, state }).toEqual({ bodyWritten: 64 * 1024, state: "open" }); | ||
| }, 60_000); | ||
|
robobun marked this conversation as resolved.
Resolved
|
||
|
|
||
| test("large body (32 MiB) is closed instead of drained in full", async () => { | ||
| const total = 32 * 1024 * 1024; | ||
| const { bodyWritten, state } = await run(total); | ||
| // The server front-loads one kernel send buffer before the client ever | ||
| // pauses, so `bodyWritten` includes that window on top of the 256 KiB cap. | ||
| // Without the cap the full 32 MiB is drained; a quarter of that is well | ||
| // above any loopback send buffer and well below the unbounded drain. | ||
| expect(bodyWritten).toBeLessThan(total / 4); | ||
| expect(state).toBe("closed"); | ||
| }, 60_000); | ||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.