The headless browser for AI agents and web scraping
perf: avoid CDP reply stalls and redundant DOM traversal
ice Zeusb210d15cc213
diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rsindex a4276956..cdb92d9d 100644--- a/crates/obscura-cdp/src/server.rs+++ b/crates/obscura-cdp/src/server.rs@@ -683,9 +683,9 @@ fn release_idle_connection_memory() {}}-/// Run one WebSocket connection on its own OS thread: a `current_thread` tokio-/// runtime + `LocalSet` hosting this connection's `cdp_processor` (with its own-/// `CdpContext` and pages) and its frame reader. Confining a connection's pages+/// Run each connection's `cdp_processor` (with its own `CdpContext` and pages)+/// on a dedicated `current_thread` Tokio runtime and `LocalSet`. A second thread+/// handles WebSocket I/O independently. Confining a connection's pages/// to one thread is what removes the #430 abort; the interception handshake and/// the nav `spawn_local` all stay on this one thread, so no cross-thread V8/// plumbing is needed.@@ -735,29 +735,70 @@ fn run_connection(return;}};+ // Socket I/O must not share the renderer's LocalSet: a synchronous+ // V8/layout task otherwise delays even replies already queued by a+ // completed navigation. Keep all page/isolate work on this thread,+ // and move only Send protocol strings and the socket to an I/O thread.+ let (msg_tx, msg_rx) = mpsc::unbounded_channel::<ServerMessage>();+ let (io_stop_tx, io_stop_rx) = tokio::sync::oneshot::channel::<()>();+ let (io_done_tx, io_done_rx) = tokio::sync::oneshot::channel::<()>();+ let io_thread = match std::thread::Builder::new()+ .name("obscura-cdp-io".into())+ .spawn(move || {+ // Dropping this sender also signals early setup failures.+ let _io_done = io_done_tx;+ let io_rt = match tokio::runtime::Builder::new_current_thread()+ .enable_all().build()+ {+ Ok(runtime) => runtime,+ Err(error) => {+ error!("connection I/O runtime build failed: {error}");+ return;+ }+ };+ let io_local = tokio::task::LocalSet::new();+ io_local.block_on(&io_rt, async move {+ let stream = match TcpStream::from_std(std_stream) {+ Ok(stream) => stream,+ Err(error) => {+ error!("TcpStream::from_std failed: {error}");+ return;+ }+ };+ tokio::select! {+ result = handle_connection_ws(stream, msg_tx) => {+ if let Err(error) = result {+ error!("WebSocket connection error: {error}");+ }+ }+ _ = io_stop_rx => {}+ }+ });+ })+ {+ Ok(thread) => thread,+ Err(error) => {+ error!("connection I/O thread spawn failed: {error}");+ return;+ }+ };let local = tokio::task::LocalSet::new();local.block_on(&rt, async move {- let tokio_stream = match TcpStream::from_std(std_stream) {- Ok(s) => s,- Err(e) => {- error!("TcpStream::from_std failed: {}", e);- return;- }- };- let (msg_tx, msg_rx) = mpsc::unbounded_channel::<ServerMessage>();- let processor = tokio::task::spawn_local(cdp_processor(- msg_rx,- default_context,- shutdown_notify,+ let mut processor = tokio::task::spawn_local(cdp_processor(+ msg_rx, default_context, shutdown_notify,));- if let Err(e) = handle_connection_ws(tokio_stream, msg_tx).await {- error!("WebSocket connection error: {}", e);+ tokio::select! {+ _ = &mut processor => {}+ _ = io_done_rx => {+ // A disconnected client must cancel an in-flight+ // navigation/evaluation rather than wait its deadline.+ processor.abort();+ let _ = processor.await;+ }}- // Connection closed (or shutting down): stop this connection's- // processor so the thread can exit.- processor.abort();- let _ = processor.await;});+ let _ = io_stop_tx.send(());+ let _ = io_thread.join();// `LocalSet` owns any detached local navigation tasks, and the// runtime owns their scheduler allocations. Drop both before the@@ -2127,6 +2168,63 @@ mod tests {assert_eq!(websocket_authority(malformed, 9223), "127.0.0.1:9223");}+ #[tokio::test(flavor = "current_thread")]+ async fn websocket_replies_are_not_blocked_by_renderer_tasks() {+ use futures_util::{SinkExt, StreamExt};+ use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};+ use std::time::{Duration, Instant};+ use tokio_tungstenite::tungstenite::Message;++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let live = Arc::new(AtomicUsize::new(1));+ let live_server = live.clone();+ let accept = tokio::spawn(async move {+ let (stream, _) = listener.accept().await.unwrap();+ stream.set_nodelay(true).unwrap();+ let context = crate::dispatch::CdpContext::new().default_context;+ super::run_connection(stream.into_std().unwrap(), context.clone(), context,+ Arc::new(std::sync::Mutex::new(())), Arc::new(tokio::sync::Notify::new()), live_server);+ });+ let (mut ws, _) = tokio_tungstenite::connect_async(format!("ws://{address}/devtools/browser")).await.unwrap();+ accept.await.unwrap();+ ws.send(Message::Text(json!({"id":1,"method":"Target.createTarget","params":{"url":"about:blank"}}).to_string().into())).await.unwrap();+ let mut session = None;+ loop {+ let msg = tokio::time::timeout(Duration::from_secs(5), ws.next()).await.unwrap().unwrap().unwrap();+ if let Message::Text(text) = msg {+ let value: serde_json::Value = serde_json::from_str(&text).unwrap();+ if let Some(sid) = value["params"]["sessionId"].as_str() { session = Some(sid.to_string()); }+ if value["id"] == 1 { break; }+ }+ }+ let started = Instant::now();+ ws.send(Message::Text(json!({"id":2,"method":"Runtime.evaluate","sessionId":session.as_ref().unwrap(),+ "params":{"expression":"setTimeout(() => { const end=Date.now()+600; while(Date.now()<end){} },0); { const end=Date.now()+30; while(Date.now()<end){} }; 'armed'","returnByValue":true}}).to_string().into())).await.unwrap();+ loop {+ let msg = tokio::time::timeout(Duration::from_secs(5), ws.next()).await.unwrap().unwrap().unwrap();+ if let Message::Text(text) = msg {+ let value: serde_json::Value = serde_json::from_str(&text).unwrap();+ if value["id"] == 2 {+ assert!(value.get("error").is_none(), "{value}");+ break;+ }+ }+ }+ assert!(started.elapsed() < Duration::from_millis(300),+ "a completed reply was trapped behind unrelated renderer work: {:?}", started.elapsed());+ tokio::time::sleep(Duration::from_millis(650)).await;+ ws.send(Message::Text(json!({"id":3,"method":"Runtime.evaluate","sessionId":session.as_ref().unwrap(),+ "params":{"expression":"new Promise(() => {})","awaitPromise":true}}).to_string().into())).await.unwrap();+ tokio::time::sleep(Duration::from_millis(25)).await;+ ws.close(None).await.unwrap();+ tokio::time::timeout(Duration::from_secs(5), async {+ while live.load(Ordering::Acquire) != 0 {+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ }).await.expect("connection and I/O threads must stop on socket close");+ }+fn cookie(name: &str, value: &str) -> CookieInfo {CookieInfo {name: name.to_string(),diff --git a/crates/obscura-dom/src/selector.rs b/crates/obscura-dom/src/selector.rsindex 962cbaa2..a769502e 100644--- a/crates/obscura-dom/src/selector.rs+++ b/crates/obscura-dom/src/selector.rs@@ -322,10 +322,8 @@ impl<'a> Element for DomElement<'a> {}fn parent_element(&self) -> Option<Self> {- let node = self.tree.get_node(self.node_id)?;- let parent_id = node.parent?;- let parent = self.tree.get_node(parent_id)?;- if parent.is_element() {+ let parent_id = self.tree.with_node(self.node_id, |node| node.parent)??;+ if self.tree.with_node(parent_id, |parent| parent.is_element())? {Some(DomElement::new(self.tree, parent_id))} else {None@@ -354,40 +352,40 @@ impl<'a> Element for DomElement<'a> {}fn prev_sibling_element(&self) -> Option<Self> {- let node = self.tree.get_node(self.node_id)?;- let mut current = node.prev_sibling;+ let mut current = self.tree.with_node(self.node_id, |node| node.prev_sibling)?;while let Some(sibling_id) = current {- let sibling = self.tree.get_node(sibling_id)?;- if sibling.is_element() {+ let (element, previous) = self.tree.with_node(sibling_id,+ |sibling| (sibling.is_element(), sibling.prev_sibling))?;+ if element {return Some(DomElement::new(self.tree, sibling_id));}- current = sibling.prev_sibling;+ current = previous;}None}fn next_sibling_element(&self) -> Option<Self> {- let node = self.tree.get_node(self.node_id)?;- let mut current = node.next_sibling;+ let mut current = self.tree.with_node(self.node_id, |node| node.next_sibling)?;while let Some(sibling_id) = current {- let sibling = self.tree.get_node(sibling_id)?;- if sibling.is_element() {+ let (element, next) = self.tree.with_node(sibling_id,+ |sibling| (sibling.is_element(), sibling.next_sibling))?;+ if element {return Some(DomElement::new(self.tree, sibling_id));}- current = sibling.next_sibling;+ current = next;}None}fn first_element_child(&self) -> Option<Self> {- let node = self.tree.get_node(self.node_id)?;- let mut current = node.first_child;+ let mut current = self.tree.with_node(self.node_id, |node| node.first_child)?;while let Some(child_id) = current {- let child = self.tree.get_node(child_id)?;- if child.is_element() {+ let (element, next) = self.tree.with_node(child_id,+ |child| (child.is_element(), child.next_sibling))?;+ if element {return Some(DomElement::new(self.tree, child_id));}- current = child.next_sibling;+ current = next;}None}@@ -1273,6 +1271,40 @@ mod tests {use super::{DomElement, SelectorKey};+ #[test]+ fn borrowed_selector_traversal_preserves_links_and_shadow_boundaries() {+ let payload = "x".repeat(4096);+ let tree = parse_html(&format!(+ "<main id='parent' data-payload='{payload}'>text<!--gap--><i id='a'></i>text<!--gap--><b id='b'></b></main><div id='host'></div>"+ ));+ let parent = tree.get_element_by_id("parent").unwrap();+ let a = tree.get_element_by_id("a").unwrap();+ let b = tree.get_element_by_id("b").unwrap();+ let element = |id| DomElement::new(&tree, id);+ assert_eq!(element(parent).first_element_child(), Some(element(a)));+ assert_eq!(element(a).next_sibling_element(), Some(element(b)));+ assert_eq!(element(b).prev_sibling_element(), Some(element(a)));+ assert_eq!(element(b).parent_element(), Some(element(parent)));+ assert!(tree.matches_selector(b, "main:has(> i) > i + b:nth-child(2)").unwrap());+ tree.detach(a);+ assert_eq!(element(a).parent_element(), None);+ assert_eq!(element(a).next_sibling_element(), None);+ assert_eq!(element(parent).first_element_child(), Some(element(b)));+ assert_eq!(element(b).prev_sibling_element(), None);+ assert!(tree.matches_selector(b, "main > b:first-child").unwrap());+ let host = tree.get_element_by_id("host").unwrap();+ let root = tree.attach_shadow_root(host, ShadowRootMode::Open).unwrap();+ tree.append_child(root, a);+ assert_eq!(element(a).parent_element(), None);+ assert!(element(a).parent_node_is_shadow_root());+ assert_eq!(element(a).containing_shadow_host(), Some(element(host)));+ tree.remove(a);+ assert_eq!(element(a).parent_element(), None);+ assert_eq!(element(a).first_element_child(), None);+ assert_eq!(element(a).next_sibling_element(), None);+ assert_eq!(element(a).prev_sibling_element(), None);+ }+fn shadow_element(tree: &crate::tree::DomTree,tag: &str,diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 0346a104..99b2238b 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -3826,6 +3826,14 @@ impl ObscuraJsRuntime {#[cfg(feature = "render")]self.service_render_resources();self.begin_javascript_task();+ // An already-resolved evaluation only needs its promise reactions.+ // Polling the whole event loop first also executes unrelated ready+ // timers/rendering callbacks, which can delay a trivial CDP read by+ // seconds. Keep those tasks for the autonomous browser pump.+ self.runtime().v8_isolate().perform_microtask_checkpoint();+ if self.recover_heap_limit() {+ return false;+ }if done_check(self) {return true;}@@ -3834,14 +3842,23 @@ impl ObscuraJsRuntime {}// Pump for a short slice. If the loop returns idle in <tick_ms,// run_event_loop returns Ok and we check the predicate again.+ let slice_deadline = (tokio::time::Instant::now()+ + tokio::time::Duration::from_millis(tick_ms)).min(deadline);let event_loop = entered_runtime_future(&mut self.js_runtime, |runtime| {runtime.run_event_loop(deno_core::PollEventLoopOptions::default())});- let _ =- tokio::time::timeout(tokio::time::Duration::from_millis(tick_ms), event_loop).await;+ let _ = tokio::time::timeout_at(slice_deadline, event_loop).await;if self.recover_heap_limit() {return false;}+ if done_check(self) {+ return true;+ }+ // An idle event loop can return immediately while an unresolvable+ // promise remains pending. Yield here so connection shutdown can+ // cancel the evaluation, and actually back off instead of spinning.+ // Reuse the slice deadline so a busy poll does not pay twice.+ tokio::time::sleep_until(slice_deadline).await;// Backoff so a hung promise doesn't burn CPU. Caps at 50ms;// worst case we miss the result by <50ms.if tick_ms < 50 {@@ -16128,6 +16145,40 @@ mod tests {assert_eq!(result.value.unwrap().as_f64().unwrap() as i64, 42);}+ #[tokio::test(flavor = "current_thread")]+ async fn pending_promise_wait_yields_to_other_tasks() {+ use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};++ let mut rt = setup_runtime("<html><body></body></html>");+ let turns = Arc::new(AtomicUsize::new(0));+ let observed = turns.clone();+ let heartbeat = tokio::spawn(async move {+ loop {+ tokio::time::sleep(std::time::Duration::from_millis(1)).await;+ observed.fetch_add(1, Ordering::Relaxed);+ }+ });+ tokio::task::yield_now().await;+ assert!(!rt.resolve_promises_until(|_| false, 80).await);+ heartbeat.abort();+ assert!(turns.load(Ordering::Relaxed) > 1,+ "an idle promise wait must yield instead of spinning until its deadline");+ }++ #[tokio::test(flavor = "current_thread")]+ async fn resolved_cdp_promise_does_not_run_unrelated_ready_timer() {+ let mut rt = setup_runtime("<html><body></body></html>");+ rt.execute_script("ready-timer", "globalThis.timerRan = false; setTimeout(() => timerRan = true, 0);").unwrap();+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ let result = rt.evaluate_for_cdp("Promise.resolve(42)", true, true).await.unwrap();+ assert_eq!(result.value.unwrap(), serde_json::json!(42.0));+ assert_eq!(rt.evaluate("timerRan").unwrap(), serde_json::json!(false),+ "an already-resolved CDP promise must not drain unrelated tasks");+ rt.run_autonomous_event_loop_turn().await.unwrap();+ assert_eq!(rt.evaluate("timerRan").unwrap(), serde_json::json!(true),+ "the timer must still run on the autonomous pump");+ }+#[tokio::test(flavor = "current_thread")]async fn test_evaluate_for_cdp_awaits_timer_promise() {let mut rt = setup_runtime("<html><body></body></html>");diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rsindex 90bea55e..e8031c7d 100644--- a/crates/obscura-render/src/dom.rs+++ b/crates/obscura-render/src/dom.rs@@ -2735,7 +2735,10 @@ fn cascade_node_style(.and_then(|root| shadow_sheets.get(&root));let mut slotted_scopes = Vec::new();let mut assigned_slot = tree.assigned_slot(id);- for _ in 0..tree.len() {+ // len() counts live arena entries. Avoid scanning the entire document+ // for every ordinary, unslotted element in the cascade.+ let slot_limit = if assigned_slot.is_some() { tree.len() } else { 0 };+ for _ in 0..slot_limit {let Some(slot) = assigned_slot else { break };let Some(root) = tree.containing_shadow_root(slot) else {break;