Skip to content
Closed
3 changes: 3 additions & 0 deletions src/bun_core/env_var.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,9 @@ pub mod feature_flag {
new_feature_flag!(pub BUN_INTERNAL_BUNX_INSTALL, "BUN_INTERNAL_BUNX_INSTALL", {});
// Debug-only fault injection for test/js/bun/spawn/spawn-pipe-start-error.test.ts.
new_feature_flag!(pub BUN_INTERNAL_FAIL_PIPE_READER_START, "BUN_INTERNAL_FAIL_PIPE_READER_START", {});
// Debug-only fault injection for test/js/web/fetch/exiting.test.ts (delays
// `FetchTasklet::deref_from_thread` into the exit window).
Comment thread
robobun marked this conversation as resolved.
Resolved
new_feature_flag!(pub BUN_INTERNAL_FETCH_DELAY_DEREF_FROM_THREAD, "BUN_INTERNAL_FETCH_DELAY_DEREF_FROM_THREAD", {});
// Test-only: bypass the stdin isatty gate in `bun update --interactive` so
// tests can drive the multi-select by writing keystrokes to a pipe.
new_feature_flag!(pub BUN_INTERNAL_INTERACTIVE_ASSUME_TTY, "BUN_INTERNAL_INTERACTIVE_ASSUME_TTY", {});
Expand Down
2 changes: 2 additions & 0 deletions src/event_loop/ConcurrentTask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ pub mod task_tag {
FChown,
Fdatasync,
FetchTasklet,
FetchTaskletDeinit, // last-ref handoff from the HTTP thread (deref_from_thread)
FetchTaskletResumeRequestStream, // request-body drain hop; the queued entry owns a +1
FetchTaskletPromiseSettle,
FileResponseStreamEof,
Fstat,
Expand Down
23 changes: 22 additions & 1 deletion src/runtime/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,14 @@ pub(crate) fn run_task(
task_tag::FetchTasklet => {
cast!(FetchTasklet).on_progress_update()?;
}
// Frees the tasklet, so no `&mut` at this boundary.
task_tag::FetchTaskletDeinit => {
FetchTasklet::deinit_queued(cast_ptr!(FetchTasklet));
}
// May drop the queued entry's ref, so no `&mut` at this boundary.
task_tag::FetchTaskletResumeRequestStream => {
FetchTasklet::resume_request_data_stream(cast_ptr!(FetchTasklet));
}
// `cast_ptr!` yields the heap-allocated S3 task; JS-thread dispatch
// is the sole owner here.
task_tag::S3HttpSimpleTask => {
Expand Down Expand Up @@ -698,7 +706,7 @@ fn run_task_cold(task: Task) {
/// Compile-time guard that the arm count above tracks
/// `bun_event_loop::task_tag::COUNT`. Bump when adding a variant.
const _: () = assert!(
task_tag::COUNT == 112,
task_tag::COUNT == 114,
"dispatch::run_task arm count out of sync with bun_event_loop::task_tag",
);

Expand Down Expand Up @@ -1283,6 +1291,19 @@ fn __bun_release_task_at_shutdown(task: bun_event_loop::Task) -> bool {
FetchTasklet::deref(task.ptr.cast::<FetchTasklet>());
true
}
// A handoff the loop never dispatched; deinit before `destructOnExit`.
task_tag::FetchTaskletDeinit => {
FetchTasklet::deinit_queued(task.ptr.cast::<FetchTasklet>());
true
}
// Drop the queued drain hop's ref without running `sink.on_drain`
// (the loop is past its last tick; there is nothing left to resume).
Comment thread
robobun marked this conversation as resolved.
Resolved
task_tag::FetchTaskletResumeRequestStream => {
// SAFETY: `task.ptr` is the live heap `FetchTasklet`; the queued
// entry owns the `on_write_request_data_drain` ref released here.
FetchTasklet::deref(task.ptr.cast::<FetchTasklet>());
true
}
task_tag::SendQueueDeferred => {
// SAFETY: `task.ptr` is the SendQueue root queued with a held ref.
unsafe {
Expand Down
63 changes: 37 additions & 26 deletions src/runtime/webcore/fetch/FetchTasklet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,6 @@ use crate::webcore::streams::{SourceHandle, StreamError, StreamResult, Writable}
use crate::webcore::{AbortSignal, DrainResult, FetchHeaders, InternalBlob, Response, SinkHandle};

use bun_jsc::JsTerminatedResult;
// `bun_event_loop::JsResult` (cycle-broken erased error) — used by
// ConcurrentTask callbacks at the tier-3 layer.
type ElJsResult<T> = bun_event_loop::JsResult<T>;

use boringssl::c::{X509_free, d2i_X509};

Expand Down Expand Up @@ -392,6 +389,14 @@ impl FetchTasklet {
// stay `*mut` because the call may drop the last ref and free the allocation.
#[allow(clippy::not_unsafe_ptr_arg_deref)]
fn deref_from_thread(this: *mut FetchTasklet) {
// Debug-only fault injection (exiting.test.ts): lets the JS thread win
// the final-deref race so the handoff below lands in the exit window.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[cfg(debug_assertions)]
if bun_core::env_var::feature_flag::BUN_INTERNAL_FETCH_DELAY_DEREF_FROM_THREAD.get()
== Some(true)
{
std::thread::sleep(core::time::Duration::from_millis(200));
}
// SAFETY: caller contract.
if !unsafe { bun_ptr::ThreadSafeRefCount::<Self>::release(this) } {
return;
Expand All @@ -406,22 +411,27 @@ impl FetchTasklet {
unsafe { FetchTasklet::dealloc_for_shutdown(this) };
return;
}
// this is really unlikely to happen, but can happen
// lets make sure that we always call deinit from main thread
// `from_callback` heap-allocates a fresh `ConcurrentTaskItem`; the queue
// takes ownership of it.
// Dedicated tag, not `from_callback`: a queued `ManagedTask` the loop
// never dispatches is freed unrun at shutdown, leaking the tasklet ⇄
// `Box<AsyncHTTP>` cycle. The `FetchTaskletDeinit` shutdown arm reclaims it.
Comment thread
robobun marked this conversation as resolved.
Resolved
Self::enqueue_concurrent(
self_.javascript_vm,
ConcurrentTask::from_callback(this, FetchTasklet::deinit_callback),
ConcurrentTask::create(Task::new(
bun_event_loop::task_tag::FetchTaskletDeinit,
this.cast(),
)),
);
}

// ConcurrentTask::from_callback takes `fn(*mut T) -> bun_event_loop::JsResult<()>`
// (cycle-broken erased error).
fn deinit_callback(this: *mut FetchTasklet) -> ElJsResult<()> {
// SAFETY: enqueued with last ref; exclusive access on main thread
/// Reclaim a tasklet queued by [`Self::deref_from_thread`]'s last-ref
/// handoff. JS thread only; both callers (dispatch, shutdown release)
/// precede `destructOnExit`, so `deinit` may still drop JSC handles.
// Signature stays `*mut`: this frees the allocation.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub(crate) fn deinit_queued(this: *mut FetchTasklet) {
// SAFETY: enqueued by `deref_from_thread` on the 1→0 transition — the
// queued task is the sole owner of a live heap allocation from `get()`.
unsafe { FetchTasklet::deinit(this) };
Ok(())
}

fn clear_sink(&mut self) {
Expand Down Expand Up @@ -561,6 +571,10 @@ impl FetchTasklet {
/// `callback` and the JS-thread `on_progress_update`; the JS thread is
/// parked in `wait_timeout_while` here, so the load is race-free.
///
/// Drain-hop refs (`on_write_request_data_drain`'s `+1`) are outside this
/// ledger: each is owned by its queued `FetchTaskletResumeRequestStream`
/// entry and released by `release_queued_tasks_for_shutdown`.
///
Comment thread
robobun marked this conversation as resolved.
Resolved
/// SAFETY: `this` is the live `*mut FetchTasklet` registered as
/// `result_callback.ctx` in `get()`; HTTP-thread-only at this point.
unsafe fn release_at_shutdown(this: *mut ()) {
Expand Down Expand Up @@ -2173,34 +2187,31 @@ impl FetchTasklet {
}
// ref until the main thread callback is called
this_ref.ref_();
// `from_callback` heap-allocates a fresh `ConcurrentTaskItem`; the queue
// takes ownership of it.
// Tagged task for the same reason as `deref_from_thread`: the shutdown
// release pass must be able to drop the queued ref if the loop never
// dispatches this.
Comment thread
robobun marked this conversation as resolved.
Resolved
Self::enqueue_concurrent(
this_ref.javascript_vm,
ConcurrentTask::from_callback(this, FetchTasklet::resume_request_data_stream),
ConcurrentTask::create(Task::new(
bun_event_loop::task_tag::FetchTaskletResumeRequestStream,
this.cast(),
)),
);
}

/// This is ALWAYS called from the main thread
// ConcurrentTask::from_callback expects `fn(*mut T) -> bun_event_loop::JsResult<()>`.
fn resume_request_data_stream(this: *mut FetchTasklet) -> ElJsResult<()> {
pub(crate) fn resume_request_data_stream(this: *mut FetchTasklet) {
let this_ref = Self::from_raw_mut(this);
bun_output::scoped_log!(FetchTasklet, "resumeRequestDataStream");
let result = (|| {
if this_ref.signal_aborted() {
// already aborted; nothing to drain
return;
}
if !this_ref.signal_aborted() {
let global_this = this_ref.global_this;
if let Some(sink) = this_ref.sink_mut() {
sink.on_drain(&global_this);
}
})();
}
// deref when done because we ref inside onWriteRequestDataDrain
// SAFETY: `this` is the live heap tasklet; we hold a ref.
FetchTasklet::deref(this);
let () = result;
Ok(())
}

/// Whether the request body should skip chunked transfer encoding framing.
Expand Down
Loading
Loading