Skip to content
Closed
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
13 changes: 13 additions & 0 deletions packages/bun-usockets/src/context.c
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,19 @@ int start_connections(struct us_connecting_socket_t *c, int count) {
return opened;
}

/* RFC 8305 connection-attempt delay (Happy Eyeballs): start one more untried
* address. Driven by the HTTP client's per-attempt timer so a blackholed
* address (SYN silently dropped, connect() stuck in EINPROGRESS until kernel
* SYN-retry exhaustion, ~130 s on Linux) does not block a reachable later
* address in the same DNS answer. Without this, start_connections only
* advances when an in-flight attempt hard-fails. */
void us_connecting_socket_start_next(struct us_connecting_socket_t *c) {
if (c->closed || c->addrinfo_head == NULL) {
return;
}
start_connections(c, 1);
}

void us_internal_socket_after_resolve(struct us_connecting_socket_t *c) {
/* close_all() may have run between the DNS thread queuing this callback and
* us reaching it; c->group is NULL'd at close so it can't be touched. The
Expand Down
4 changes: 4 additions & 0 deletions packages/bun-usockets/src/libusockets.h
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,10 @@ struct us_socket_t *us_socket_group_connect_unix(us_socket_group_r group,
int us_socket_is_established(us_socket_r s) nonnull_fn_decl;
void us_connecting_socket_free(struct us_connecting_socket_t *c) nonnull_fn_decl;
void us_connecting_socket_close(struct us_connecting_socket_t *c) nonnull_fn_decl;
/* RFC 8305 connection-attempt delay: start one more untried resolved address
* so a blackholed earlier address does not block a reachable later one.
* No-op if `c` is closed or every address has already been attempted. */
void us_connecting_socket_start_next(struct us_connecting_socket_t *c) nonnull_fn_decl;
void us_connecting_socket_timeout(struct us_connecting_socket_t *c, unsigned int seconds) nonnull_fn_decl;
void us_connecting_socket_long_timeout(struct us_connecting_socket_t *c, unsigned int minutes) nonnull_fn_decl;
void us_connecting_socket_shutdown(struct us_connecting_socket_t *c) nonnull_fn_decl;
Expand Down
1 change: 1 addition & 0 deletions src/codegen/generate-js2native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,7 @@ export function getJS2NativeRust() {
const handExported = new Set<string>([
"JS2Rust___src_runtime_dns_jsc_dns_rs__Resolver_getRuntimeDefaultResultOrderOption",
"JS2Rust___src_runtime_dns_jsc_dns_rs__Resolver_newResolver",
"JS2Rust___src_runtime_dns_jsc_dns_rs__internal_seedCacheForTesting",
]);

const srcRoot = path.resolve(import.meta.dir, "..");
Expand Down
3 changes: 3 additions & 0 deletions src/event_loop/EventLoopTimer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,8 @@ pub enum Tag {
CronJob,
GcOneShot,
GcRepeating,
/// RFC 8305 happy-eyeballs connection-attempt delay on `FetchTasklet`.
FetchConnectAttempt,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

impl Tag {
Expand All @@ -215,6 +217,7 @@ impl Tag {
| Tag::EventLoopDelayMonitor // probably important
| Tag::StatWatcherScheduler
| Tag::GcOneShot | Tag::GcRepeating // internal GC pacing
| Tag::FetchConnectAttempt // internal network pacing, never user-visible
=> false,
_ => true,
}
Expand Down
15 changes: 5 additions & 10 deletions src/http/AsyncHTTP.rs
Original file line number Diff line number Diff line change
Expand Up @@ -455,16 +455,11 @@ impl<'a> AsyncHTTP<'a> {
redirect_type: FetchRedirect,
options: Options<'a>,
) -> AsyncHTTP<'a> {
let async_http_id = if options
.signals
.as_ref()
.map(|s| s.aborted.is_some())
.unwrap_or(false)
{
crate::ASYNC_HTTP_ID_MONOTONIC.fetch_add(1, Ordering::Relaxed)
} else {
0
};
// Every request gets an id and an abort-tracker entry (not just
// abortable ones): the happy-eyeballs connect-attempt nudge
// (`HTTPThread::schedule_connect_nudge`) addresses the in-flight
// socket by this id.
let async_http_id = crate::ASYNC_HTTP_ID_MONOTONIC.fetch_add(1, Ordering::Relaxed);

let signals = options.signals.unwrap_or_default();
let http_proxy = options.http_proxy.clone();
Expand Down
44 changes: 44 additions & 0 deletions src/http/HTTPThread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,17 @@ pub struct HttpThread {
pub queued_writes: Vec<WriteMessage>,
pub queued_receive_resumes: Vec<u32>,
pub queued_cert_check_resumes: Vec<CertCheckResumeMessage>,
/// RFC 8305 happy-eyeballs connection-attempt delay ticks from the JS
/// thread (`FetchTasklet`'s 300 ms timer). Each entry asks the still
/// DNS-deferred connecting socket for `async_http_id` to start one more
/// untried resolved address; a no-op once the socket has connected.
pub queued_connect_nudges: Vec<u32>,

pub queued_shutdowns_lock: Mutex,
pub queued_writes_lock: Mutex,
pub queued_receive_resumes_lock: Mutex,
pub queued_cert_check_resumes_lock: Mutex,
pub queued_connect_nudges_lock: Mutex,

pub queued_threadlocal_proxy_derefs: Vec<*mut ProxyTunnel>,

Expand Down Expand Up @@ -179,10 +185,12 @@ impl HttpThread {
queued_writes: Vec::new(),
queued_receive_resumes: Vec::new(),
queued_cert_check_resumes: Vec::new(),
queued_connect_nudges: Vec::new(),
queued_shutdowns_lock: Mutex::new(),
queued_writes_lock: Mutex::new(),
queued_receive_resumes_lock: Mutex::new(),
queued_cert_check_resumes_lock: Mutex::new(),
queued_connect_nudges_lock: Mutex::new(),
queued_threadlocal_proxy_derefs: Vec::new(),
has_awoken: AtomicBool::new(false),
timer: Instant::now(),
Expand Down Expand Up @@ -853,6 +861,25 @@ impl HttpThread {
}
}

fn drain_queued_connect_nudges(&mut self) {
loop {
let queued = {
let _guard = self.queued_connect_nudges_lock.lock_guard();
core::mem::take(&mut self.queued_connect_nudges)
};
if queued.is_empty() {
return;
}
for id in queued {
// Ids whose socket has already settled (or that never had one:
// h2/h3 sessions, not-yet-started requests) are simply absent.
if let Some(socket_ptr) = abort_tracker().get(&id) {
socket_ptr.start_next_connect_attempt();
}
}
}
}

pub fn drain_events(&mut self) {
// Process any pending writes **before** aborting.
self.drain_queued_receive_resumes();
Expand All @@ -862,6 +889,9 @@ impl HttpThread {
// turn removes the abort-tracker entry first, so the resume becomes a
// no-op and the request is never transmitted after a same-tick abort.
self.drain_queued_cert_check_resumes();
// Same post-shutdown rule: a connect nudge scheduled in the same JS
// turn as an abort finds no tracker entry and is a no-op.
self.drain_queued_connect_nudges();
h3::PendingConnect::drain_resolved();

for http in self.queued_threadlocal_proxy_derefs.drain(..) {
Expand Down Expand Up @@ -968,6 +998,20 @@ impl HttpThread {
self.wakeup();
}

/// RFC 8305 happy-eyeballs connection-attempt delay tick. Called from the
/// JS thread (`FetchTasklet`'s per-attempt timer); the HTTP thread drains
/// it in [`Self::drain_queued_connect_nudges`].
pub fn schedule_connect_nudge(&mut self, async_http_id: u32) {
{
let _guard = self.queued_connect_nudges_lock.lock_guard();
if self.queued_connect_nudges.last() == Some(&async_http_id) {
return;
}
self.queued_connect_nudges.push(async_http_id);
}
self.wakeup();
}

pub fn schedule_shutdown(&mut self, http: &AsyncHttp) {
self.schedule_shutdown_by_id(http.async_http_id);
}
Expand Down
24 changes: 10 additions & 14 deletions src/http/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1174,7 +1174,7 @@ pub(crate) fn abort_tracker() -> &'static mut ArrayHashMap<u32, uws::AnySocket>
/// to `DeadSocket`/`PooledSocket`, the client/session dispatch is skipped and
/// any stale entry would survive into `us_internal_free_closed_sockets`,
/// leaving `drain_queued_shutdowns` to dereference freed memory on a later
/// abort. O(n) over live abortable requests; no-op on a `Detached` socket.
/// abort. O(n) over live tracked requests; no-op on a `Detached` socket.
pub(crate) fn unregister_abort_tracker_for_socket(socket: uws::InternalSocket) {
if socket.is_detached() {
return;
Expand Down Expand Up @@ -1752,22 +1752,18 @@ impl<'a> HTTPClient<'a> {
}

pub fn register_abort_tracker<const IS_SSL: bool>(&mut self, socket: HttpSocket<IS_SSL>) {
if self.signals.aborted.is_some() {
let any = if IS_SSL {
uws::AnySocket::SocketTls(uws::SocketTLS::from_any(socket.socket))
} else {
uws::AnySocket::SocketTcp(uws::SocketTCP::from_any(socket.socket))
};
// SAFETY: HTTP-thread only; per-statement reborrow.
let _ = abort_tracker().put(self.async_http_id, any);
}
let any = if IS_SSL {
uws::AnySocket::SocketTls(uws::SocketTLS::from_any(socket.socket))
} else {
uws::AnySocket::SocketTcp(uws::SocketTCP::from_any(socket.socket))
};
// SAFETY: HTTP-thread only; per-statement reborrow.
let _ = abort_tracker().put(self.async_http_id, any);
Comment thread
robobun marked this conversation as resolved.
Resolved
}

pub fn unregister_abort_tracker(&mut self) {
if self.signals.aborted.is_some() {
// SAFETY: HTTP-thread only; per-statement reborrow.
let _ = abort_tracker().swap_remove(&self.async_http_id);
}
// SAFETY: HTTP-thread only; per-statement reborrow.
let _ = abort_tracker().swap_remove(&self.async_http_id);
}

pub fn on_open<const IS_SSL: bool>(
Expand Down
11 changes: 11 additions & 0 deletions src/js/internal-for-testing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,17 @@ export type SocketFaultRule = {
fd?: number;
};

/**
* Inject a pre-resolved entry into the internal DNS cache so `fetch()` and
* `Bun.connect()` to `hostname` try `addresses` in exactly that order without
* a real getaddrinfo call.
*/
export const dnsCacheSeed: (hostname: string, addresses: string[]) => void = $newRustFunction(
"runtime/dns_jsc/dns.rs",
"internal.seedCacheForTesting",
2,
);

export const socketFaultInjection = {
/** True when the current binary was built with `--socket-fault-injection=on` (defaults to on for ASan builds). */
available: $newRustFunction(
Expand Down
4 changes: 4 additions & 0 deletions src/runtime/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -988,6 +988,10 @@ pub unsafe fn __bun_fire_timer(t: *mut EventLoopTimer, now: *const ElTimespec, v
|c, _now, vm| GarbageCollectionController::on_gc_repeating_timer(c, vm)
)
}
EventLoopTimerTag::FetchConnectAttempt => {
timer_arm!(FetchTasklet, connect_attempt_timer, |c, _now, _vm| (*c)
.on_connect_attempt_timer())
}
EventLoopTimerTag::DateHeaderTimer => {
timer_arm!(DateHeaderTimer, event_loop_timer, |c, _now, vm| (*c)
.run(&mut *vm))
Expand Down
110 changes: 110 additions & 0 deletions src/runtime/dns_jsc/dns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2990,6 +2990,112 @@ pub mod internal {
Ok(object)
}

/// Test-only (`bun:internal-for-testing`): inject a pre-resolved entry into
/// the internal DNS cache so `fetch()` / `Bun.connect()` to `hostname` will
/// try `addresses` in order without a real getaddrinfo call.
#[host_fn]
pub(crate) fn seed_cache_for_testing(
global: &JSGlobalObject,
frame: &CallFrame,
) -> JsResult<JSValue> {
let args = frame.arguments();
if args.len() < 2 || !args[0].is_string() || !args[1].is_array() {
return Err(global.throw_invalid_arguments(format_args!(
"expected (hostname: string, addresses: string[])"
)));
}
let hostname_slice = args[0].to_slice(global)?;
let hostname_z = bun::ZBox::from_bytes(hostname_slice.slice());
let count = args[1].get_length(global)? as usize;
if count == 0 {
return Err(global.throw_invalid_arguments(format_args!("addresses is empty")));
}
// `length` is JS-controlled and a sparse array can claim an arbitrarily
// large one; cap it before the native allocation below.
if count > 64 {
return Err(global
.throw_invalid_arguments(format_args!("addresses has too many entries (max 64)")));
}

let mut results: Box<[MaybeUninit<ResultEntry>]> = Box::new_uninit_slice(count);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
for i in 0..count {
let addr_val = args[1].get_index(global, i as u32)?;
let addr_slice = addr_val.to_slice(global)?;
let addr_z = bun::ZBox::from_bytes(addr_slice.slice());
// SAFETY: results[i] is a MaybeUninit slot we fully initialize here;
// ares_inet_pton only writes sizeof(in_addr)/sizeof(in6_addr) bytes
// into the zeroed 128-byte `addr` storage.
unsafe {
let entry = results[i].as_mut_ptr();
(*entry).info = bun_core::ffi::zeroed();
(*entry).addr = bun_core::ffi::zeroed();
(*entry).info.ai_socktype = netc::SOCK_STREAM;
let v4 = (&raw mut (*entry).addr).cast::<netc::sockaddr_in>();
let v6 = (&raw mut (*entry).addr).cast::<netc::sockaddr_in6>();
if c_ares::ares_inet_pton(
netc::AF_INET,
addr_z.as_ptr().cast::<c_char>(),
(&raw mut (*v4).sin_addr).cast::<c_void>(),
) > 0
{
(*v4).sin_family = netc::AF_INET as _;
(*entry).info.ai_family = netc::AF_INET;
(*entry).info.ai_addrlen = core::mem::size_of::<netc::sockaddr_in>() as _;
} else if c_ares::ares_inet_pton(
netc::AF_INET6,
addr_z.as_ptr().cast::<c_char>(),
(&raw mut (*v6).sin6_addr).cast::<c_void>(),
) > 0
{
(*v6).sin6_family = netc::AF_INET6 as _;
(*entry).info.ai_family = netc::AF_INET6;
(*entry).info.ai_addrlen = core::mem::size_of::<netc::sockaddr_in6>() as _;
} else {
return Err(global.throw_invalid_arguments(format_args!(
"addresses[{i}] is not an IPv4 or IPv6 literal"
)));
}
}
}
// SAFETY: every slot 0..count was fully initialized above.
let mut results: Box<[ResultEntry]> = unsafe { results.assume_init() };
for idx in 0..count {
let (left, right) = results.split_at_mut(idx + 1);
let entry = &mut left[idx];
entry.info.ai_canonname = ptr::null_mut();
entry.info.ai_addr = (&raw mut entry.addr).cast::<Sockaddr>();
entry.info.ai_next = if idx + 1 < count {
&raw mut right[0].info
} else {
ptr::null_mut()
};
}

// Port 0: the cache key hashes/compares the hostname only, so this
// entry matches a connect to any port.
let key = RequestKey::init(Some(hostname_z.as_zstr()), 0);
let req = Request::new(key.to_owned(), 0, GlobalCache::get_cache_timestamp());
// SAFETY: `req` is a freshly heap-allocated Request we exclusively own
// until try_push transfers it to the lock-guarded cache.
unsafe {
(*req).result_buf = Some(results);
let info = (*req)
.result_buf
.as_mut()
.and_then(|b| NonNull::new(b.as_mut_ptr()));
(*req).result = Some(RequestResult { info, err: 0 });
}
let mut guard = global_cache().lock();
if !guard.try_push(req) {
drop(guard);
Request::deinit(req);
return Err(global.throw_invalid_arguments(format_args!("DNS cache is full")));
}
DNS_CACHE_SIZE.store(guard.len, Ordering::Relaxed);
drop(guard);
Ok(JSValue::UNDEFINED)
}

pub(crate) fn getaddrinfo(
loop_: *mut Loop,
host: Option<&ZStr>,
Expand Down Expand Up @@ -6086,3 +6192,7 @@ export_host_fn!(
Resolver::get_runtime_default_result_order_option,
"JS2Rust___src_runtime_dns_jsc_dns_rs__Resolver_getRuntimeDefaultResultOrderOption"
);
export_host_fn!(
internal::seed_cache_for_testing,
"JS2Rust___src_runtime_dns_jsc_dns_rs__internal_seedCacheForTesting"
);
Loading
Loading