The headless browser for AI agents and web scraping
fix(cdp): keep the accept thread live behind silent connections
xrip2e82757023f4
diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rsindex 3b4b5f25..8040543b 100644--- a/crates/obscura-cdp/src/server.rs+++ b/crates/obscura-cdp/src/server.rs@@ -183,8 +183,10 @@ pub async fn start_with_serve_options_and_limit(// forwarded to the existing LocalSet for CDP processing.let std_listener = std::net::TcpListener::bind(addr).map_err(|e| anyhow::anyhow!("bind {}:{}: {}", host, port, e))?;+ // Non-blocking so the accept thread can alternate between draining the+ // backlog and re-polling parked connections (see the accept thread below).std_listener- .set_nonblocking(false)+ .set_nonblocking(true).map_err(|e| anyhow::anyhow!("set_nonblocking: {}", e))?;info!("Obscura CDP server listening on ws://{}:{}", host, port);@@ -205,23 +207,91 @@ pub async fn start_with_serve_options_and_limit(// Dedicated accept thread: drains the kernel backlog immediately and// handles HTTP endpoints (/json/version, /json, /json/protocol) with// blocking I/O so they never contend with the LocalSet's V8 work.+ //+ // A connection that is accepted but never sends its request head+ // (speculative browser preconnects, port probes, slow-loris clients)+ // must not be able to park this single thread in a blocking read: every+ // later connection, including CDP clients like Playwright's+ // connectOverCDP, would then sit in the kernel backlog unanswered until+ // its own connect timeout (issue #715). The thread therefore never+ // blocks on a *stream* — undecided connections are parked and re-polled+ // every ACCEPT_POLL_INTERVAL, and dropped once they outlive+ // SILENT_CONNECTION_TTL without sending a request head.+ //+ // While nothing is parked the thread blocks in accept() itself, the+ // pre-#715 fast path: zero added latency for the next connection and no+ // CPU while idle. Blocking on the listener is safe — it waits for the+ // kernel, not for client bytes. While something is parked, the listener+ // is drained without blocking at least once per 1 ms poll round, far+ // above any real connect rate, so the kernel backlog cannot overflow+ // under a connection burst.let accept_flag = shutdown_flag.clone();std::thread::Builder::new().name("obscura-cdp-accept".into()).spawn(move || {- for stream in std_listener.incoming() {- if accept_flag.load(Ordering::Relaxed) {- break;+ let mut pending: Vec<(std::net::TcpStream, std::time::Instant)> = Vec::new();+ while !accept_flag.load(Ordering::Relaxed) {+ if pending.is_empty() {+ // Fast path: nothing parked, block until a connection+ // arrives, then classify it in the sweep below.+ let _ = std_listener.set_nonblocking(false);+ match std_listener.accept() {+ Ok((stream, _)) => {+ let _ = stream.set_nonblocking(true);+ pending.push((stream, std::time::Instant::now()));+ }+ Err(e) => {+ error!("Accept error: {}", e);+ // A persistent error (e.g. EMFILE) must not turn+ // into a log flood while the thread idles.+ std::thread::sleep(ACCEPT_POLL_INTERVAL);+ }+ }+ let _ = std_listener.set_nonblocking(true);+ } else {+ // Drain everything the kernel has already queued for us.+ loop {+ match std_listener.accept() {+ Ok((stream, _)) => {+ let _ = stream.set_nonblocking(true);+ if pending.len() < MAX_SILENT_PENDING {+ pending.push((stream, std::time::Instant::now()));+ } else {+ warn!(+ "dropping connection: {} connections parked without a request head",+ MAX_SILENT_PENDING+ );+ }+ }+ Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,+ Err(e) => {+ error!("Accept error: {}", e);+ break;+ }+ }+ }}- match stream {- Ok(stream) => {- if let Err(e) = accept_dispatch(stream, port, &ws_tx) {- if !format!("{}", e).contains("close") {- error!("Accept dispatch error: {}", e);+ // Give every parked connection a chance to speak; keep the+ // ones still silent and inside the TTL, dispatch the ones+ // with a request head. Dropping a stream closes its socket.+ for (stream, since) in std::mem::take(&mut pending) {+ if since.elapsed() >= SILENT_CONNECTION_TTL {+ continue;+ }+ match peek_request_head(&stream) {+ PeekStatus::NotReady => pending.push((stream, since)),+ PeekStatus::Closed => {}+ PeekStatus::Head(head) => {+ if let Err(e) = accept_dispatch(stream, port, &ws_tx, &head) {+ if !format!("{}", e).contains("close") {+ error!("Accept dispatch error: {}", e);+ }}}}- Err(e) => error!("Accept error: {}", e),+ }+ if !pending.is_empty() {+ std::thread::sleep(ACCEPT_POLL_INTERVAL);}}})?;@@ -597,45 +667,91 @@ fn refuse_connection(stream: std::net::TcpStream) {}const HTTP_PEEK_BUF: usize = 4096;-const WS_PEEK_BUF: usize = 4;++/// How long a freshly accepted connection may sit without sending a request+/// head before the accept thread drops it. Real clients send their handshake+/// immediately after connecting; only probes and preconnects linger.+const SILENT_CONNECTION_TTL: std::time::Duration = std::time::Duration::from_secs(10);++/// How often the accept thread re-polls parked connections that have not sent+/// a request head yet. Also the retry delay on a persistent accept error, so+/// it cannot become a log flood. Only paid while something is actually+/// parked; an idle server blocks in accept() and polls nothing.+const ACCEPT_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(1);++/// Cap on connections parked without a request head. Bounds the accept+/// thread's polling work and the server's fd usage under probe floods.+const MAX_SILENT_PENDING: usize = 256;++/// Result of polling a freshly accepted connection for its request head.+enum PeekStatus {+ /// No classifiable request head yet; poll again next accept round.+ NotReady,+ /// Peer went away without sending a full head.+ Closed,+ /// A classifiable request head.+ Head(String),+}++/// Peek — without consuming — at a freshly accepted connection's request+/// head. `GET` requests are only classified once the terminating blank line+/// has arrived, so `/json` route matching never sees a truncated head;+/// anything that cannot be a `GET` is handed over immediately so non-HTTP+/// garbage still gets tungstenite's prompt rejection instead of waiting out+/// the silent-connection TTL.+fn peek_request_head(stream: &std::net::TcpStream) -> PeekStatus {+ let mut buf = [0u8; HTTP_PEEK_BUF];+ let n = match stream.peek(&mut buf) {+ Ok(0) => return PeekStatus::Closed,+ Ok(n) => n,+ Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => return PeekStatus::NotReady,+ Err(_) => return PeekStatus::Closed,+ };+ let head = &buf[..n];+ if n >= 4 && head[..4] != *b"GET " {+ return PeekStatus::Head(String::from_utf8_lossy(head).into_owned());+ }+ // A head that overflows the peek buffer is classified with what arrived,+ // matching the pre-polling behavior for oversized headers.+ let complete = n == HTTP_PEEK_BUF || head.windows(4).any(|w| w == b"\r\n\r\n");+ if !complete {+ return PeekStatus::NotReady;+ }+ PeekStatus::Head(String::from_utf8_lossy(head).into_owned())+}/// Dispatch a freshly-accepted TCP connection on the dedicated accept thread.///-/// Peek at the first bytes to decide HTTP vs WebSocket:+/// The connection's request head has already been peeked by the accept loop+/// (`peek_request_head`) and is passed in as `head`:/// - HTTP (`GET /json/*`): serve synchronously via blocking I/O so the/// response is never stalled by the LocalSet.-/// - WebSocket: set non-blocking, convert to tokio `TcpStream`, and forward-/// to the LocalSet for CDP processing.+/// - WebSocket: forward to the LocalSet for CDP processing.fn accept_dispatch(stream: std::net::TcpStream,port: u16,ws_tx: &mpsc::Sender<std::net::TcpStream>,+ head: &str,) -> anyhow::Result<()> {- let mut buf = [0u8; WS_PEEK_BUF];- let n = stream.peek(&mut buf)?;-- if n >= 4 && &buf == b"GET " {- let mut peek_buf = [0u8; HTTP_PEEK_BUF];- let n = stream.peek(&mut peek_buf)?;- let line = String::from_utf8_lossy(&peek_buf[..n]);-- let endpoint = if line.contains("/json/version") {- Some("version")- } else if line.contains("/json/list") || line.contains("/json\r\n") || line.contains("/json HTTP") {- Some("list")- } else if line.contains("/json/protocol") {- Some("protocol")- } else {- None- };+ let endpoint = if head.contains("/json/version") {+ Some("version")+ } else if head.contains("/json/list") || head.contains("/json\r\n") || head.contains("/json HTTP") {+ Some("list")+ } else if head.contains("/json/protocol") {+ Some("protocol")+ } else {+ None+ };- if let Some(ep) = endpoint {- return handle_http_json_blocking(stream, port, ep);- }- // Fall through: GET request that isn't a /json endpoint → treat as- // WebSocket upgrade (Chromium DevTools clients issue GET with- // Upgrade: websocket).+ if let Some(ep) = endpoint {+ // The request head is already sitting in the kernel receive buffer;+ // switch back to blocking mode for the synchronous /json serve.+ let _ = stream.set_nonblocking(false);+ return handle_http_json_blocking(stream, port, ep);}+ // Fall through: GET request that isn't a /json endpoint → treat as+ // WebSocket upgrade (Chromium DevTools clients issue GET with+ // Upgrade: websocket).// Try to hand off the WS stream to the LocalSet. If the bounded channel// is full the LocalSet is saturated — drop the connection cleanlydiff --git a/crates/obscura-cdp/tests/accept_thread_survives_silent_connections.rs b/crates/obscura-cdp/tests/accept_thread_survives_silent_connections.rsnew file mode 100644index 00000000..f11a56ee--- /dev/null+++ b/crates/obscura-cdp/tests/accept_thread_survives_silent_connections.rs@@ -0,0 +1,130 @@+//! The accept thread must survive connections that never send a request head.+//!+//! The accept thread is one OS thread shared by every client. Before issue+//! #715 it classified each fresh connection with a *blocking* peek, so a+//! single connection that was accepted but never sent anything (speculative+//! browser preconnect, port probe, stalled client) parked the thread forever.+//! Every later connection then sat in the kernel backlog with no 101 and no+//! error until its own connect timeout: Playwright's `connectOverCDP` hangs+//! exactly like that while a raw WebSocket client appears to work — it only+//! works as long as it connects while no silent connection is parked.+//!+//! This test parks several silent connections and then requires that+//! 1. a real CDP WebSocket handshake plus a `Target.getTargets` round-trip+//! still completes promptly, and+//! 2. the `/json/version` control plane — served by the same thread — stays+//! reachable too.+//!+//! Run with `cargo nextest run -p obscura-cdp -E 'test(accept_thread_survives)'`.++use std::time::Duration;++use futures_util::{SinkExt, StreamExt};+use serde_json::json;+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::net::TcpListener;+use tokio_tungstenite::{connect_async, tungstenite::Message};++const SILENT_CONNECTIONS: usize = 4;++async fn pick_port() -> u16 {+ let l = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = l.local_addr().unwrap().port();+ drop(l);+ port+}++#[test]+fn accept_thread_survives_silent_connections() {+ let rt = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap();+ let local = tokio::task::LocalSet::new();++ local.block_on(&rt, async move {+ let ws_port = pick_port().await;+ tokio::task::spawn_local(async move {+ let _ = obscura_cdp::start_with_serve_options_and_limit(+ ws_port,+ "127.0.0.1",+ None,+ false,+ None,+ false,+ None,+ true,+ 128,+ )+ .await;+ });+ tokio::time::sleep(Duration::from_millis(300)).await;++ // Park connections that connect and then never send a byte. They must+ // be held by the server without occupying its attention.+ let mut silent = Vec::new();+ for _ in 0..SILENT_CONNECTIONS {+ silent.push(+ tokio::net::TcpStream::connect(("127.0.0.1", ws_port))+ .await+ .expect("silent connection must open"),+ );+ }+ // Give the accept thread a moment to pick them up before the real+ // clients arrive, so the test cannot pass by racing the park.+ tokio::time::sleep(Duration::from_millis(200)).await;++ // 1. A real WebSocket client still gets its handshake and a CDP+ // round-trip. Before the fix this hung until the timeout because+ // the accept thread was parked inside a blocking peek.+ let url = format!("ws://127.0.0.1:{}/devtools/browser", ws_port);+ let cdp = tokio::time::timeout(Duration::from_secs(5), async {+ let (mut ws, _) = connect_async(&url).await.expect("handshake");+ ws.send(Message::Text(+ json!({"id": 1, "method": "Target.getTargets"}).to_string().into(),+ ))+ .await+ .expect("send");+ loop {+ let msg = tokio::time::timeout(Duration::from_secs(5), ws.next())+ .await+ .expect("per-message timeout")+ .expect("ws closed")+ .expect("ws error");+ if let Message::Text(t) = msg {+ let v: serde_json::Value = serde_json::from_str(&t).expect("cdp json");+ if v.get("id").and_then(|i| i.as_u64()) == Some(1) {+ assert!(v["result"]["targetInfos"].is_array(), "getTargets reply: {v}");+ return;+ }+ }+ }+ })+ .await;+ assert!(cdp.is_ok(), "CDP handshake wedged behind silent connections");++ // 2. The /json control plane shares the accept thread and must stay+ // reachable too.+ let mut http = tokio::net::TcpStream::connect(("127.0.0.1", ws_port))+ .await+ .expect("http connect");+ let req = format!(+ "GET /json/version HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nConnection: close\r\n\r\n",+ ws_port+ );+ http.write_all(req.as_bytes()).await.expect("http write");+ let mut buf = vec![0u8; 2048];+ let body = tokio::time::timeout(Duration::from_secs(5), http.read(&mut buf))+ .await+ .expect("/json/version timed out behind silent connections")+ .expect("/json/version read");+ let body = String::from_utf8_lossy(&buf[..body]).to_string();+ assert!(+ body.starts_with("HTTP/1.1 200"),+ "/json/version must answer, got: {:?}",+ body.lines().next()+ );++ drop(silent);+ });+}