Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(curl): share HTTP and WebSocket connection limits
ldm04b3b8993bb53
diff --git a/Cargo.lock b/Cargo.lockindex f0baf4b97..925cf8807 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -846,7 +846,7 @@ dependencies = [[[package]]name = "curl"version = "0.4.49"-source = "git+https://github.com/lexmount/curl-rust?branch=moli#608f08d6b724877e940fd13db808395685e98a25"+source = "git+https://github.com/lexmount/curl-rust?branch=moli#f28fe3049962d1be917c2d4064f1c6574b331fac"dependencies = ["curl-sys","libc",@@ -860,7 +860,7 @@ dependencies = [[[package]]name = "curl-sys"version = "0.4.87+curl-8.19.0"-source = "git+https://github.com/lexmount/curl-rust?branch=moli#608f08d6b724877e940fd13db808395685e98a25"+source = "git+https://github.com/lexmount/curl-rust?branch=moli#f28fe3049962d1be917c2d4064f1c6574b331fac"dependencies = ["brotlic-sys","cc",@@ -2467,7 +2467,6 @@ dependencies = ["anyhow","crossbeam-channel","curl",- "curl-sys","moli-dns-resolver","openssl-sys","parking_lot",diff --git a/moli-curl/Cargo.toml b/moli-curl/Cargo.tomlindex dbb9b585e..4bed4413c 100644--- a/moli-curl/Cargo.toml+++ b/moli-curl/Cargo.toml@@ -8,7 +8,6 @@ edition = "2024"anyhow = "1.0.100"crossbeam-channel = "0.5.15"curl = { version = "0.4.49", default-features = false, features = ["brotli", "http2", "poll_7_68_0", "ssl", "static-curl", "websocket"] }-curl-sys = { version = "0.4.87", default-features = false }moli-dns-resolver = { path = "../moli-dns-resolver" }openssl-sys = { version = "0.9", features = ["aws-lc"] }parking_lot = "0.12"diff --git a/moli-curl/README.md b/moli-curl/README.mdindex 701b6dc56..f641eb12b 100644--- a/moli-curl/README.md+++ b/moli-curl/README.md@@ -113,11 +113,19 @@ owner, and an explicitly supplied closed connector fails without a standalonefallback. Fetch, Page and Worker use the connector from their network runtime.The Fetch semantic thread and WebSocket Tokio session thread remain separate.-WebSockets have an owner-local CURLSH connection cache, so resident sockets do-not consume HTTP host/total connection limits. HTTP retains the Multi's default-connection pool; WebSocket session admission bounds its separate cache. This-shares scheduling and ownership, not TCP/TLS connections. WebSocket transport-still uses HTTP/1.1 Upgrade; this change does not implement RFC 8441.+HTTP/1, HTTP/2 and WebSocket sockets share the Multi's default connection pool+and its host/total connection limits. A live WebSocket consumes one connection;+additional HTTP/2 streams can reuse an existing socket. Work requiring a new+connection waits when the pool is full, and that wait counts towards its HTTP+request or WebSocket handshake deadline. No protocol has reserved connections.+Long-lived WebSockets can therefore keep new HTTP connections waiting until+their deadline. Established WebSockets must never be evicted as idle HTTP+connections; the pinned curl fork protects them in both eviction paths.++The native WebSocket admission bound (255 pending/open sessions), event queue+and frame/message memory limits remain separate work and memory bounds. They+do not grant additional sockets beyond the shared pool limits. WebSocket+transport still uses HTTP/1.1 Upgrade; it does not implement RFC 8441.In shared mode, poll/turn counters include HTTP work and HTTP wakeups. A fastpoll with no WebSocket byte progress can therefore reflect useful HTTP work.diff --git a/moli-curl/src/runtime/config.rs b/moli-curl/src/runtime/config.rsindex f47886d02..161f39512 100644--- a/moli-curl/src/runtime/config.rs+++ b/moli-curl/src/runtime/config.rs@@ -15,9 +15,11 @@ pub struct CurlMultiRuntimeConfig {/// Keep this separate from `max_host_connections`: the latter is a curl/// transport connection-pool cap and should not throttle HTTP/2 streams.pub max_host_active: Option<NonZeroUsize>,- /// libcurl per-host connection cap, matching Chromium's HTTP/1 socket-pool- /// concept when configured by the higher fetch runtime.+ /// Shared libcurl per-host socket cap for HTTP/1, HTTP/2 and WebSockets.+ /// Requests needing a new connection wait when the cap is reached; an+ /// existing HTTP/2 connection can still carry additional streams.pub max_host_connections: Option<NonZeroUsize>,+ /// Shared socket cap across all hosts and protocols on this runtime.pub max_total_connections: Option<NonZeroUsize>,pub max_concurrent_streams: Option<NonZeroUsize>,pub poll_interval: Duration,diff --git a/moli-curl/src/websocket.rs b/moli-curl/src/websocket.rsindex 36b54af61..1a4daba2d 100644--- a/moli-curl/src/websocket.rs+++ b/moli-curl/src/websocket.rs@@ -11,7 +11,6 @@//! resume paused work, such as a new frame or restored receive capacity.mod connection;-mod connection_pool;mod connector;mod readiness;pub(crate) mod registry;@@ -35,6 +34,8 @@ pub use standalone::CurlWebSocketRuntime;/// Fragment large messages above this layer to bound native write residence.pub const MAX_SEND_FRAME_BYTES: usize = 64 * 1024;const MAX_PENDING_EVENTS: usize = 8;+// Bounds pending/open native work and its memory, without granting sockets+// beyond the runtime's shared host/total connection limits.const SESSION_CAPACITY: usize = 255;#[derive(Debug)]@@ -80,8 +81,8 @@ pub enum CurlWebSocketEvent {/// CONT marks every non-final fragment, including empty ones./// UTF-8, Close contents and application size limits belong to the caller.Chunk { data: Vec<u8>, frame: WsFrame },- /// Emitted once, after all previously admitted events. Ok means TCP EOF;- /// it does not assert that a WebSocket close handshake was completed.+ /// Emitted once, after all previously admitted events. Ok means TCP EOF or+ /// requested cancellation; it does not assert a completed close handshake.Closed {result: std::result::Result<(), String>,},diff --git a/moli-curl/src/websocket/connection.rs b/moli-curl/src/websocket/connection.rsindex 7490976f8..4d01acaad 100644--- a/moli-curl/src/websocket/connection.rs+++ b/moli-curl/src/websocket/connection.rs@@ -32,6 +32,8 @@ pub(super) struct Control {pub(super) read_waiting: tokio::sync::Notify,#[cfg(test)]pub(super) owner_thread: Mutex<Option<std::thread::ThreadId>>,+ #[cfg(test)]+ pub(super) pool_waiting: Arc<tokio::sync::Notify>,}impl Control {@@ -139,6 +141,8 @@ impl CurlWebSocketConnection {read_waiting: tokio::sync::Notify::new(),#[cfg(test)]owner_thread: Mutex::new(None),+ #[cfg(test)]+ pool_waiting: Arc::new(tokio::sync::Notify::new()),});let (event_tx, events) = mpsc::channel(MAX_PENDING_EVENTS);let io = SessionIo {@@ -191,9 +195,10 @@ impl Drop for CurlWebSocketConnection {}pub(super) struct SessionIo {+ // Release admission before closing the event channel publishes the terminal.+ _slot: OwnedSemaphorePermit,pub(super) events: mpsc::Sender<CurlWebSocketEvent>,pub(super) control: Arc<Control>,- _slot: OwnedSemaphorePermit,}impl SessionIo {diff --git a/moli-curl/src/websocket/connection_pool.rs b/moli-curl/src/websocket/connection_pool.rsdeleted file mode 100644index 4e18ac656..000000000--- a/moli-curl/src/websocket/connection_pool.rs+++ /dev/null@@ -1,54 +0,0 @@-//! A separate connection cache for persistent WebSockets on the shared Multi.-//! HTTP pool limits continue to apply to HTTP connections. WebSocket admission-//! bounds this cache instead. Everything using it stays on the owner thread.-use std::{ptr::NonNull, rc::Rc};--use anyhow::{Context, Result, bail};-use curl::easy::Easy2;--use super::request::Handshake;--pub(super) struct ConnectionPool(NonNull<curl_sys::CURLSH>);--impl ConnectionPool {- pub(super) fn new() -> Result<Rc<Self>> {- // Multi has already initialized libcurl. The pointer is owned here and- // is never sent across threads; each bound handler retains an Rc.- let pool = Self(- NonNull::new(unsafe { curl_sys::curl_share_init() })- .context("failed to create WebSocket connection cache")?,- );- let result = unsafe {- curl_sys::curl_share_setopt(- pool.0.as_ptr(),- curl_sys::CURLSHOPT_SHARE,- curl_sys::CURL_LOCK_DATA_CONNECT,- )- };- if result != curl_sys::CURLSHE_OK {- bail!("failed to configure WebSocket connection cache: {result}");- }- Ok(Rc::new(pool))- }-- pub(super) fn bind(self: &Rc<Self>, easy: &mut Easy2<Handshake>) -> Result<()> {- // CURLOPT_SHARE borrows the pointer. Easy2 runs curl_easy_cleanup- // before dropping its Handler, whose Rc therefore outlives that borrow.- let result = unsafe {- curl_sys::curl_easy_setopt(easy.raw(), curl_sys::CURLOPT_SHARE, self.0.as_ptr())- };- if result != curl_sys::CURLE_OK {- return Err(curl::Error::new(result).into());- }- easy.get_mut().connection_pool = Some(self.clone());- Ok(())- }-}--impl Drop for ConnectionPool {- fn drop(&mut self) {- // All easy handles borrowing the share have already been cleaned up.- let result = unsafe { curl_sys::curl_share_cleanup(self.0.as_ptr()) };- debug_assert_eq!(result, curl_sys::CURLSHE_OK);- }-}diff --git a/moli-curl/src/websocket/connector.rs b/moli-curl/src/websocket/connector.rsindex 15ebc6b6d..5445a740a 100644--- a/moli-curl/src/websocket/connector.rs+++ b/moli-curl/src/websocket/connector.rs@@ -34,6 +34,11 @@ struct ConnectorInner {}impl CurlWebSocketConnector {+ #[cfg(test)]+ pub(super) fn available_session_slots(&self) -> usize {+ self.inner.slots.available_permits()+ }+pub(crate) fn channel() -> (crossbeam_channel::Sender<Submission>,crossbeam_channel::Receiver<Submission>,diff --git a/moli-curl/src/websocket/registry.rs b/moli-curl/src/websocket/registry.rsindex 5fe6a6861..1b8bf23fb 100644--- a/moli-curl/src/websocket/registry.rs+++ b/moli-curl/src/websocket/registry.rs@@ -1,7 +1,7 @@//! Persistent WebSocket residences on the common HTTP/WebSocket Multi.//! The runtime owns perform, completion dispatch and the single wait loop.-use std::{collections::HashMap, rc::Rc, time::Instant};+use std::{collections::HashMap, time::Instant};use curl::{easy::Easy2,@@ -10,7 +10,6 @@ use curl::{use super::{SessionIo, Submission,- connection_pool::ConnectionPool,readiness::SocketReadiness,request::{self, Handshake},session::{Session, Step},@@ -34,7 +33,6 @@ pub(crate) struct WebSocketRegistry {dns: CurlDnsOwnerResidence<CurlTransferId, Pending>,readiness: SocketReadiness,receive: Vec<u8>,- pool: Option<Rc<ConnectionPool>>,closed: bool,}@@ -46,7 +44,6 @@ impl WebSocketRegistry {dns: CurlDnsOwnerResidence::default(),readiness: SocketReadiness::default(),receive: Vec::new(),- pool: None,closed: false,}}@@ -87,23 +84,19 @@ impl WebSocketRegistry {.finish(Err("curl WebSocket runtime shut down".to_owned()));return;}- let easy = request::configure(&submission.request).and_then(|mut easy| {- if self.pool.is_none() {- self.pool = Some(ConnectionPool::new()?);- }- self.pool- .as_ref()- .expect("pool initialized")- .bind(&mut easy)?;- Ok(easy)- });- let easy = match easy {+ let easy = match request::configure(&submission.request) {Ok(easy) => easy,Err(error) => {submission.io.finish(Err(error.to_string()));return;}};+ #[cfg(test)]+ let easy = {+ let mut easy = easy;+ easy.get_mut().pool_waiting = Some(submission.io.control.pool_waiting.clone());+ easy+ };let Some(deadline) = Instant::now().checked_add(submission.request.handshake_timeout)else {submissiondiff --git a/moli-curl/src/websocket/request.rs b/moli-curl/src/websocket/request.rsindex 250b9cc50..4157a8b54 100644--- a/moli-curl/src/websocket/request.rs+++ b/moli-curl/src/websocket/request.rs@@ -10,7 +10,8 @@ pub(super) struct Handshake {pub request: Vec<u8>,pub response: Vec<u8>,pub error: Option<String>,- pub connection_pool: Option<std::rc::Rc<super::connection_pool::ConnectionPool>>,+ #[cfg(test)]+ pub pool_waiting: Option<std::sync::Arc<tokio::sync::Notify>>,proxy_connect: bool,header_bytes: usize,}@@ -44,6 +45,16 @@ impl Handler for Handshake {}fn debug(&mut self, kind: InfoType, data: &[u8]) {+ // Observe libcurl's actual admission decision in tests. Merely seeing+ // connect() return does not prove that a handle is waiting for a slot.+ #[cfg(test)]+ if matches!(kind, InfoType::Text)+ && (data.starts_with(b"No more connections allowed to host")+ || data.starts_with(b"No connections available, total of"))+ && let Some(waiting) = &self.pool_waiting+ {+ waiting.notify_one();+ }if matches!(kind, InfoType::HeaderOut) {self.proxy_connect = data.starts_with(b"CONNECT ");if data.starts_with(b"GET ") && data.len() <= MAX_HEADERS {diff --git a/moli-curl/src/websocket/tests/shared.rs b/moli-curl/src/websocket/tests/shared.rsindex 8f55dfe3b..043fa5d92 100644--- a/moli-curl/src/websocket/tests/shared.rs+++ b/moli-curl/src/websocket/tests/shared.rs@@ -1,6 +1,6 @@use std::num::NonZeroUsize;-use curl::easy::{Easy2, Handler, WriteError};+use curl::easy::{Easy2, Handler, InfoType, WriteError};use super::*;use crate::{CurlMultiJob, CurlMultiRuntime, CurlMultiRuntimeConfig, CurlOriginKey};@@ -10,9 +10,21 @@ struct HttpCapture {body: Vec<u8>,owner: Option<thread::ThreadId>,headers: Option<tokio::sync::oneshot::Sender<()>>,+ queued: Option<tokio::sync::oneshot::Sender<()>>,}impl Handler for HttpCapture {+ fn debug(&mut self, kind: InfoType, data: &[u8]) {+ // Wait for the native connection-pool decision, not wall-clock delay.+ if matches!(kind, InfoType::Text)+ && (data.starts_with(b"No more connections allowed to host")+ || data.starts_with(b"No connections available, total of"))+ && let Some(queued) = self.queued.take()+ {+ queued.send(()).unwrap();+ }+ }+fn header(&mut self, data: &[u8]) -> bool {if data == b"\r\n"&& let Some(sender) = self.headers.take()@@ -33,6 +45,7 @@ fn request(url: &str, handler: HttpCapture, timeout: Duration) -> CurlMultiJob<Hlet mut easy = Easy2::new(handler);easy.url(url).unwrap();easy.proxy("").unwrap();+ easy.verbose(easy.get_ref().queued.is_some()).unwrap();let url = url::Url::parse(url).unwrap();CurlMultiJob {easy,@@ -54,13 +67,14 @@ fn request(url: &str, handler: HttpCapture, timeout: Duration) -> CurlMultiJob<Hfn peer() -> (String,crossbeam_channel::Sender<()>,- thread::JoinHandle<()>,+ thread::JoinHandle<Vec<String>>,) {let listener = TcpListener::bind("127.0.0.1:0").unwrap();let base = format!("http://{}", listener.local_addr().unwrap());let (release, released) = crossbeam_channel::bounded(1);let task = thread::spawn(move || {let mut children = Vec::new();+ let mut paths = Vec::new();loop {let (mut stream, _) = listener.accept().unwrap();stream.set_read_timeout(Some(DEADLINE)).unwrap();@@ -69,6 +83,7 @@ fn peer() -> (if request.starts_with("GET /stop ") {break;}+ paths.push(request.split_whitespace().nth(1).unwrap().to_owned());let released = released.clone();children.push(thread::spawn(move || {if request.starts_with("GET /native ") {@@ -98,17 +113,18 @@ fn peer() -> (for child in children {child.join().unwrap();}+ paths});(base, release, task)}-fn stop_peer(base: &str, peer: thread::JoinHandle<()>) {+fn stop_peer(base: &str, peer: thread::JoinHandle<Vec<String>>) -> Vec<String> {let authority = base.strip_prefix("http://").unwrap();let mut stream = TcpStream::connect(authority).unwrap();stream.write_all(b"GET /stop HTTP/1.1\r\nHost: localhost\r\n\r\n").unwrap();- peer.join().unwrap();+ peer.join().unwrap()}fn config(total: bool) -> CurlMultiRuntimeConfig {@@ -120,53 +136,85 @@ fn config(total: bool) -> CurlMultiRuntimeConfig {}}+fn websocket_request(base: &str) -> CurlWebSocketRequest {+ let mut request = CurlWebSocketRequest::new(base.replacen("http", "ws", 1) + "/native");+ request.handshake_timeout = DEADLINE;+ request+}++async fn hold_http(runtime: &CurlMultiRuntime<HttpCapture, ()>, base: &str) {+ let (headers, ready) = oneshot::channel();+ runtime+ .http_sender()+ .submit(request(+ &format!("{base}/held"),+ HttpCapture {+ headers: Some(headers),+ ..HttpCapture::default()+ },+ DEADLINE,+ ))+ .unwrap();+ timeout(DEADLINE, ready).await.unwrap().unwrap();+}++async fn pool_waiting(connection: &CurlWebSocketConnection) {+ timeout(+ DEADLINE,+ connection.sender().control.pool_waiting.notified(),+ )+ .await+ .expect("WebSocket must reach the native connection pool wait");+}++async fn echo(connection: &mut CurlWebSocketConnection) {+ connection.sender().set_reading(true);+ connection+ .sender()+ .send_frame(CurlWebSocketSend {+ flags: WsFlags::BINARY,+ data: vec![42],+ })+ .await+ .unwrap();+ assert!(+ matches!(event(connection).await, CurlWebSocketEvent::Chunk { data, .. } if data == [42])+ );+}+#[tokio::test]-async fn shared_owner_keeps_http_and_websocket_pools_independent() {+async fn shared_connection_limits_resume_http_after_websocket_release() {for total in [false, true] {let (base, _, peer) = peer();let (runtime, completed) = CurlMultiRuntime::new(config(total)).unwrap();let connector = runtime.websocket_connector();- let mut connections = Vec::new();- // Neither the HTTP host cap nor its total cap of 1 limits these sessions.- for _ in 0..2 {- let mut request = CurlWebSocketRequest::new(base.replacen("http", "ws", 1) + "/native");- request.handshake_timeout = DEADLINE;- let mut connection = connector.connect(request).unwrap();- opened(&mut connection).await;- connections.push(connection);- }- runtime+ let mut connection = connector.connect(websocket_request(&base)).unwrap();+ opened(&mut connection).await;+ let owner = *connection.sender().control.owner_thread.lock();+ let (queued, waiting) = oneshot::channel();+ let id = runtime.http_sender().submit(request(- &(base.clone() + "/ok"),- HttpCapture::default(),+ &(base.clone() + "/queued"),+ HttpCapture {+ queued: Some(queued),+ ..HttpCapture::default()+ },DEADLINE,)).unwrap();+ timeout(DEADLINE, waiting).await.unwrap().unwrap();+ assert!(completed.is_empty());+ // It was silent during admission. Pool pressure must not evict it.+ echo(&mut connection).await;+ drop(connection);let completion = completed.recv_timeout(DEADLINE).unwrap();+ assert_eq!(completion.transfer_id, id);completion.result.unwrap();let easy = completion.easy.unwrap();assert_eq!(easy.get_ref().body, b"ok");- for mut connection in connections {- assert_eq!(- *connection.sender().control.owner_thread.lock(),- easy.get_ref().owner- );- connection.sender().set_reading(true);- connection- .sender()- .send_frame(CurlWebSocketSend {- flags: WsFlags::BINARY,- data: vec![42],- })- .await- .unwrap();- assert!(- matches!(event(&mut connection).await, CurlWebSocketEvent::Chunk { data, .. } if data == [42])- );- drop(connection);- }- // Retiring WS does not retire the shared owner or its HTTP pool.+ assert_eq!(easy.get_ref().owner, owner);+ // HTTP remains usable on this same native owner after WS teardown.runtime.http_sender().submit(request(@@ -177,93 +225,153 @@ async fn shared_owner_keeps_http_and_websocket_pools_independent() {.unwrap();completed.recv_timeout(DEADLINE).unwrap().result.unwrap();drop(runtime);- assert!(- connector- .connect(CurlWebSocketRequest::new(- base.replacen("http", "ws", 1) + "/native"- ))- .is_err()- );- stop_peer(&base, peer);+ assert!(connector.connect(websocket_request(&base)).is_err());+ assert_eq!(stop_peer(&base, peer), ["/native", "/queued", "/after"]);}}#[tokio::test]-async fn shared_owner_preserves_http_connection_caps_with_live_websocket() {+async fn shared_connection_limits_keep_quiet_websocket_through_http_timeout() {for total in [false, true] {- let (base, release, peer) = peer();+ let (base, _, peer) = peer();let (runtime, completed) = CurlMultiRuntime::new(config(total)).unwrap();- let connector = runtime.websocket_connector();- let mut connection = connector- .connect(CurlWebSocketRequest::new(- base.replacen("http", "ws", 1) + "/native",- ))+ let mut connection = runtime+ .websocket_connector()+ .connect(websocket_request(&base)).unwrap();opened(&mut connection).await;- let (headers, ready) = tokio::sync::oneshot::channel();- let first = runtime+ let id = runtime.http_sender().submit(request(- &(base.clone() + "/held"),- HttpCapture {- headers: Some(headers),- ..HttpCapture::default()- },- DEADLINE,- ))- .unwrap();- timeout(DEADLINE, ready).await.unwrap().unwrap();- // Both HTTP jobs fit max_active=2. Only the connection cap keeps the- // second waiting until its own deadline, while the first is held open.- let second = runtime- .http_sender()- .submit(request(- &(base.clone() + "/queued"),+ &(base.clone() + "/timed-out"),HttpCapture::default(),Duration::from_millis(200),)).unwrap();let completion = completed.recv_timeout(DEADLINE).unwrap();- assert_eq!(completion.transfer_id, second);+ assert_eq!(completion.transfer_id, id);assert!(completion.result.unwrap_err().chain().any(|error| {error.downcast_ref::<curl::Error>().is_some_and(curl::Error::is_operation_timedout)}));+ echo(&mut connection).await;+ drop(connection);+ drop(runtime);+ assert_eq!(stop_peer(&base, peer), ["/native"]);+ }+}++#[tokio::test]+async fn shared_connection_limits_resume_websocket_after_http_release() {+ for total in [false, true] {+ let (base, release, peer) = peer();+ let (runtime, completed) = CurlMultiRuntime::new(config(total)).unwrap();+ hold_http(&runtime, &base).await;+ let mut connection = runtime+ .websocket_connector()+ .connect(websocket_request(&base))+ .unwrap();+ pool_waiting(&connection).await;+ assert!(connection.events.is_empty());release.send(()).unwrap();- let completion = completed.recv_timeout(DEADLINE).unwrap();- assert_eq!(completion.transfer_id, first);- completion.result.unwrap();+ completed.recv_timeout(DEADLINE).unwrap().result.unwrap();+ opened(&mut connection).await;+ echo(&mut connection).await;drop(connection);- runtime.shutdown();- stop_peer(&base, peer);+ drop(runtime);+ assert_eq!(stop_peer(&base, peer), ["/held", "/native"]);}}#[tokio::test]-async fn shared_owner_shutdown_releases_websocket_with_live_connector() {- let (base, _, peer) = peer();- let (runtime, _) = CurlMultiRuntime::<HttpCapture, ()>::new(config(true)).unwrap();- let connector = runtime.websocket_connector();- let mut connection = connector- .connect(CurlWebSocketRequest::new(- base.replacen("http", "ws", 1) + "/native",- ))- .unwrap();- opened(&mut connection).await;- // Keep both capabilities alive. Neither owns the native thread's lifetime.- drop(runtime);- while let Some(event) = timeout(DEADLINE, connection.recv()).await.unwrap() {- if let CurlWebSocketEvent::Closed { result } = event {- assert!(result.is_err());+async fn shared_connection_limits_cancel_waiting_websocket_and_release_admission() {+ for total in [false, true] {+ let (base, release, peer) = peer();+ let (runtime, completed) = CurlMultiRuntime::new(config(total)).unwrap();+ hold_http(&runtime, &base).await;+ let connector = runtime.websocket_connector();+ let mut connection = connector.connect(websocket_request(&base)).unwrap();+ pool_waiting(&connection).await;+ assert_eq!(connector.available_session_slots(), SESSION_CAPACITY - 1);+ connection.sender().cancel();+ assert!(matches!(+ event(&mut connection).await,+ CurlWebSocketEvent::Closed { result: Ok(()) }+ ));+ // Terminal delivery guarantees the native admission has been released,+ // even while the application's receiver and connector remain alive.+ assert_eq!(connector.available_session_slots(), SESSION_CAPACITY);+ release.send(()).unwrap();+ completed.recv_timeout(DEADLINE).unwrap().result.unwrap();+ runtime+ .http_sender()+ .submit(request(+ &(base.clone() + "/after"),+ HttpCapture::default(),+ DEADLINE,+ ))+ .unwrap();+ completed.recv_timeout(DEADLINE).unwrap().result.unwrap();+ drop(runtime);+ // The cancelled waiter must never issue its upgrade after capacity returns.+ assert_eq!(stop_peer(&base, peer), ["/held", "/after"]);+ }+}++#[tokio::test]+async fn shared_connection_limits_include_pool_wait_in_websocket_deadline() {+ for total in [false, true] {+ let (base, release, peer) = peer();+ let (runtime, completed) = CurlMultiRuntime::new(config(total)).unwrap();+ hold_http(&runtime, &base).await;+ let connector = runtime.websocket_connector();+ let mut request = websocket_request(&base);+ request.handshake_timeout = Duration::from_millis(200);+ let mut connection = connector.connect(request).unwrap();+ pool_waiting(&connection).await;+ let mut timed_out = false;+ while let Some(event) = timeout(DEADLINE, connection.recv()).await.unwrap() {+ match event {+ CurlWebSocketEvent::Handshake {+ result: Err(error), ..+ }+ | CurlWebSocketEvent::Closed { result: Err(error) } => {+ let error = error.to_ascii_lowercase();+ timed_out |= error.contains("timed out") || error.contains("timeout");+ }+ other => panic!("unexpected event while waiting for pool capacity: {other:?}"),+ }}+ assert!(timed_out);+ assert_eq!(connector.available_session_slots(), SESSION_CAPACITY);+ release.send(()).unwrap();+ completed.recv_timeout(DEADLINE).unwrap().result.unwrap();+ drop(runtime);+ assert_eq!(stop_peer(&base, peer), ["/held"]);+ }+}++#[tokio::test]+async fn shared_owner_shutdown_releases_open_and_waiting_websockets_with_live_connector() {+ for total in [false, true] {+ let (base, _, peer) = peer();+ let (runtime, _) = CurlMultiRuntime::<HttpCapture, ()>::new(config(total)).unwrap();+ let connector = runtime.websocket_connector();+ let mut connection = connector.connect(websocket_request(&base)).unwrap();+ opened(&mut connection).await;+ let mut waiting = connector.connect(websocket_request(&base)).unwrap();+ pool_waiting(&waiting).await;+ // Keep the capabilities alive. Neither owns the native thread's lifetime.+ drop(runtime);+ for connection in [&mut connection, &mut waiting] {+ assert!(matches!(+ event(connection).await,+ CurlWebSocketEvent::Closed { result: Err(_) }+ ));+ }+ assert_eq!(connector.available_session_slots(), SESSION_CAPACITY);+ assert!(connector.connect(websocket_request(&base)).is_err());+ assert_eq!(stop_peer(&base, peer), ["/native"]);}- assert!(- connector- .connect(CurlWebSocketRequest::new(- "ws://127.0.0.1:1/native".to_owned()- ))- .is_err()- );- stop_peer(&base, peer);}diff --git a/moli-fetch/src/config.rs b/moli-fetch/src/config.rsindex 108db34c1..b47397f48 100644--- a/moli-fetch/src/config.rs+++ b/moli-fetch/src/config.rs@@ -25,11 +25,10 @@ pub struct FetchConfig {// HTTP/2 can use multiple streams without being limited by the HTTP/1// socket default.http_max_host_open: Option<NonZeroU32>,- // Transport cap passed to libcurl's per-host connection pool. When unset,- // Moli uses Chromium's HTTP/1-style default of six connections per- // host/group.+ // Shared HTTP/WS transport cap passed to libcurl's per-host connection+ // pool. When unset, use six connections per host/group.http_max_host_connections: Option<u8>,- // Transport cap for total cached/open connections across hosts.+ // Shared HTTP/WS transport cap for cached/open connections across hosts.http_max_total_connections: Option<u16>,// HTTP/2 stream cap; this is separate from HTTP/1 connection count.http2_max_concurrent_streams: Option<u16>,@@ -132,9 +131,8 @@ impl FetchConfig {http_max_total_connections: Option<u16>,http2_max_concurrent_streams: Option<u16>,) {- // These are transport-level limits handed to curl. Keep them out of the- // runtime scheduler so a Chromium-like HTTP/1 connection default does- // not accidentally throttle HTTP/2 streams or queued browser work.+ // Host/total limits count HTTP and WebSocket sockets together. The+ // runtime scheduler and HTTP/2 stream limits count work separately.self.http_max_host_connections = http_max_host_connections;self.http_max_total_connections = http_max_total_connections;self.http2_max_concurrent_streams = http2_max_concurrent_streams;diff --git a/moli-fetch/src/tests/mixed_transport.rs b/moli-fetch/src/tests/mixed_transport.rsindex 8e98a6a11..4d732e2b5 100644--- a/moli-fetch/src/tests/mixed_transport.rs+++ b/moli-fetch/src/tests/mixed_transport.rs@@ -126,7 +126,9 @@ async fn mixed_http2_and_websocket(tls: bool, shutdown: bool) -> Result<()> {});let mut config = FetchConfig::default();config.set_tls_verify_host(false);- config.set_transport_connection_limits(Some(1), Some(1), Some(8));+ // One H2 socket and one WS/WSS socket fill the shared total budget. The+ // concurrent H2 streams below must reuse their single physical connection.+ config.set_transport_connection_limits(Some(1), Some(2), Some(8));let client = FetchClient::new(&config, new_shared_browser_cookie_store());let handle = client.handle();let held_url = format!("{h2_url}/held");diff --git a/moli/src/cli.rs b/moli/src/cli.rsindex 09f20c765..b1a6641f8 100644--- a/moli/src/cli.rs+++ b/moli/src/cli.rs@@ -460,7 +460,7 @@ pub struct CommonArgs {#[arg(long)]pub http_max_host_open: Option<NonZeroU32>,- /// Limit transport connections per host/group.+ /// Limit shared HTTP and WebSocket connections per host/group.////// Defaults to 6 to match Chromium's normal HTTP/1 socket-pool shape. This/// does not limit HTTP/2 streams; use `--http2-max-concurrent-streams` for@@ -468,7 +468,7 @@ pub struct CommonArgs {#[arg(long)]pub http_max_host_connections: Option<u8>,- /// Limit total transport connections across all hosts.+ /// Limit total HTTP and WebSocket connections across all hosts.#[arg(long)]pub http_max_total_connections: Option<u16>,