Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/http/HTTPThread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1175,6 +1175,23 @@ fn abort_tracker() -> &'static mut ArrayHashMap<u32, uws::AnySocket> {
crate::abort_tracker()
}

/// Debug+ASAN invariant check: every socket pointer in the abort tracker must
/// point at live (unfreed) memory. A stale entry here means some socket-close
/// path forgot `unregister_abort_tracker`, which later manifests as a
/// use-after-free in `drain_queued_shutdowns`/`drain_queued_writes` when the
/// JS thread aborts that request id. Runs before and after each loop tick so
/// the report fires at the tick that leaked, not at the eventual abort.
#[inline]
fn assert_abort_tracker_sockets_alive() {
if cfg!(debug_assertions) {
for socket in abort_tracker().values() {
if let Some(usocket) = socket.socket().get() {
bun_core::asan::assert_unpoisoned(usocket);
}
}
}
}

use core::cell::Cell;

// ═══════════════════════════════════════════════════════════════════════════
Expand Down Expand Up @@ -1347,12 +1364,14 @@ mod _event_loop_draft {
}
}
self.drain_events();
assert_abort_tracker_sockets_alive();
Output::flush();

let uws_loop = self.uws_loop_mut();
uws_loop.inc();
uws_loop.tick();
uws_loop.dec();
assert_abort_tracker_sockets_alive();

if cfg!(debug_assertions) {
Output::flush();
Expand Down
25 changes: 18 additions & 7 deletions src/runtime/webcore/fetch/FetchTasklet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -670,13 +670,16 @@ impl FetchTasklet {
bytes.on_data(StreamResult::Err(StreamError::JSValue(js_err)))?;
}
}
if let Some(sink) = self.sink_mut() {
if js_err.is_empty() {
js_err = err.to_js(&global_this);
js_err.ensure_still_alive();
}
sink.cancel(js_err);
return Ok(());
// A failure result is terminal (`to_result` forces `has_more =
// false` once `fail` is set), so everything pending must settle
// here: a still-streaming request-body sink does not exempt the
// response body. Returning right after `sink.cancel()` used to
// leave a buffered `arrayBuffer()`/`text()` promise pending
// forever when a fetch with an in-flight streaming request body
// was aborted mid-response.
if self.sink_mut().is_some() && js_err.is_empty() {
js_err = err.to_js(&global_this);
js_err.ensure_still_alive();
}
// if we are buffering resolve the promise
if let Some(response) = self.current_response_mut() {
Expand All @@ -688,6 +691,14 @@ impl FetchTasklet {
body.to_error_instance(err, &global_this)
.map_err(|_| bun_jsc::JsTerminated::JSTerminated)?;
}
// Cancel the request-body sink last: `ResumableSink::cancel`
// invokes the stream's JS cancel callback synchronously via
// `run_callback`, which can re-enter the tasklet.
if !js_err.is_empty() {
if let Some(sink) = self.sink_mut() {
sink.cancel(js_err);
}
}
return Ok(());
}

Expand Down
52 changes: 52 additions & 0 deletions test/js/web/fetch/fetch-abort-buffered-body-fixture.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 24 additions & 0 deletions test/js/web/fetch/fetch-abort-stream-body.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,30 @@ import { expect, test } from "bun:test";
import { bunEnv, bunExe } from "harness";
import { join } from "node:path";

// Aborting a fetch whose request body stream is still uploading must also
// settle the response side. The failure callback used to return right after
// cancelling the request-body sink, so a buffered body promise
// (arrayBuffer/text/json) never rejected and awaiting it hung forever.
// Runs in a subprocess because the buggy build leaves zombie requests behind
// that keep the process from exiting.
test.concurrent(
"abort mid-response rejects buffered body promises while the request body stream is active",
async () => {
await using proc = Bun.spawn({
cmd: [bunExe(), join(import.meta.dir, "fetch-abort-buffered-body-fixture.ts")],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});

const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

expect(stderr).toBe("");
expect(stdout).toBe("arrayBuffer rejected AbortError\ntext rejected AbortError\n");
expect(exitCode).toBe(0);
},
);

test("aborting fetch with a ReadableStream request body does not double-cancel the sink", async () => {
await using proc = Bun.spawn({
cmd: [bunExe(), join(import.meta.dir, "fetch-abort-stream-body-fixture.ts")],
Expand Down
Loading