The headless browser for AI agents and web scraping
fix(cli): bound spawned batch jobs by concurrency
vvinayakkka4dca822e612
diff --git a/README.md b/README.mdindex 6ccf4b2b..ac1e5635 100644--- a/README.md+++ b/README.md@@ -502,6 +502,10 @@ Fetch and render a single page.Scrape multiple URLs in parallel with worker processes.+`scrape` and `fetch --file ... --dump original` keep at most `--concurrency`+jobs active, starting the next URL as soon as a slot becomes available. Results+remain in input order. URL input and completed results are still held in memory.+| Flag | Default | Description ||------|---------|-------------|| `--concurrency` | `10` | Parallel workers |diff --git a/crates/obscura-cli/src/batch.rs b/crates/obscura-cli/src/batch.rsnew file mode 100644index 00000000..60a6217a--- /dev/null+++ b/crates/obscura-cli/src/batch.rs@@ -0,0 +1,130 @@+use std::collections::HashMap;+use std::future::Future;++use tokio::task::{JoinError, JoinSet};++/// Keep at most `concurrency` spawned jobs alive, returning results in input order.+pub(crate) async fn run_bounded<T, R, F, Fut>(+ items: impl IntoIterator<Item = T>,+ concurrency: usize,+ mut job: F,+) -> Vec<Result<R, JoinError>>+where+ R: Send + 'static,+ F: FnMut(T) -> Fut,+ Fut: Future<Output = R> + Send + 'static,+{+ assert!(concurrency > 0);+ let mut items = items.into_iter();+ let mut running = JoinSet::new();+ let mut indices = HashMap::new();+ let mut results = Vec::new();++ loop {+ while running.len() < concurrency {+ let Some(item) = items.next() else { break };+ let index = results.len();+ results.push(None);+ let handle = running.spawn(job(item));+ indices.insert(handle.id(), index);+ }++ let Some(completed) = running.join_next_with_id().await else {+ break;+ };+ let (id, result) = match completed {+ Ok((id, value)) => (id, Ok(value)),+ Err(error) => (error.id(), Err(error)),+ };+ let index = indices.remove(&id).expect("each job has an input index");+ results[index] = Some(result);+ }++ results+ .into_iter()+ .map(|result| result.expect("each job completed"))+ .collect()+}++#[cfg(test)]+mod tests {+ use super::run_bounded;+ use std::sync::{Arc, Mutex};+ use tokio::sync::oneshot;+ use tokio::time::{timeout, Duration};++ #[tokio::test]+ async fn bounded_jobs_create_only_the_active_window_and_refill_promptly() {+ let (release, blocked) = oneshot::channel();+ let mut blocked = Some(blocked);+ let (started, third_started) = oneshot::channel();+ let mut started = Some(started);+ let created = Arc::new(Mutex::new(Vec::new()));+ let observed = created.clone();+ let runner = tokio::spawn(async move {+ run_bounded(0..1000, 2, move |index| {+ created.lock().unwrap().push(index);+ let blocked = if index == 0 { blocked.take() } else { None };+ let started = if index == 2 { started.take() } else { None };+ async move {+ if let Some(started) = started {+ // Wait here so the number of created futures is deterministic.+ let (release_third, wait) = oneshot::channel();+ started.send(release_third).unwrap();+ wait.await.unwrap();+ }+ if let Some(blocked) = blocked {+ blocked.await.unwrap();+ }+ index+ }+ })+ .await+ });+ let release_third = timeout(Duration::from_secs(5), third_started)+ .await+ .unwrap()+ .unwrap();+ // Job 1 freed a slot while job 0 is still blocked. No futures for the+ // remaining 997 inputs should have been created yet.+ assert_eq!(*observed.lock().unwrap(), vec![0, 1, 2]);+ release.send(()).unwrap();+ release_third.send(()).unwrap();+ let results = runner+ .await+ .unwrap()+ .into_iter()+ .map(Result::unwrap)+ .collect::<Vec<_>>();+ assert_eq!(results, (0..1000).collect::<Vec<_>>());+ }++ #[tokio::test]+ async fn bounded_jobs_preserve_panic_positions_and_continue() {+ let results = run_bounded(0..10, 3, |index| async move {+ if index == 2 {+ panic!("test job failed");+ }+ tokio::task::yield_now().await;+ index+ })+ .await;+ assert_eq!(results.len(), 10);+ for (index, result) in results.into_iter().enumerate() {+ if index == 2 {+ assert!(result.unwrap_err().is_panic());+ } else {+ assert_eq!(result.unwrap(), index);+ }+ }+ }++ #[tokio::test]+ async fn bounded_jobs_accept_empty_input() {+ assert!(+ run_bounded(Vec::<usize>::new(), 2, |index| async move { index })+ .await+ .is_empty()+ );+ }+}diff --git a/crates/obscura-cli/src/main.rs b/crates/obscura-cli/src/main.rsindex fd19f24c..a201e3a8 100644--- a/crates/obscura-cli/src/main.rs+++ b/crates/obscura-cli/src/main.rs@@ -1,3 +1,5 @@+mod batch;+use std::sync::Arc;use std::time::Instant;@@ -1408,18 +1410,14 @@ async fn run_batch_fetch(}let start = Instant::now();- let semaphore = Arc::new(tokio::sync::Semaphore::new(concurrency));let user_agent = Arc::new(user_agent);let proxy = Arc::new(proxy);- let mut handles = Vec::with_capacity(total);- for (i, url) in urls.into_iter().enumerate() {- let sem = semaphore.clone();+ let completed = batch::run_bounded(urls.into_iter().enumerate(), concurrency, |(i, url)| {let user_agent = user_agent.clone();let proxy = proxy.clone();- handles.push(tokio::spawn(async move {- let _permit = sem.acquire().await.unwrap();+ async move {let task_start = Instant::now();let result = fetch_original_response(&url,@@ -1448,13 +1446,14 @@ async fn run_batch_fetch(}),};(i, line)- }));- }+ }+ })+ .await;let mut results: Vec<Option<serde_json::Value>> = vec![None; total];let mut failures = 0usize;- for handle in handles {- if let Ok((i, line)) = handle.await {+ for result in completed {+ if let Ok((i, line)) = result {if !line["ok"].as_bool().unwrap_or(false) {failures += 1;}@@ -1784,23 +1783,18 @@ async fn run_parallel_scrape();}- let semaphore = Arc::new(tokio::sync::Semaphore::new(concurrency));let eval = Arc::new(eval);let worker_path = Arc::new(worker_path);let worker_timeout = Duration::from_secs(timeout_secs);let read_timeout = Duration::from_secs(timeout_secs.min(30));let shutdown_timeout = Duration::from_secs(5);- let mut handles = Vec::new();-- for (i, url) in urls.into_iter().enumerate() {- let sem = semaphore.clone();+ let completed = batch::run_bounded(urls.into_iter().enumerate(), concurrency, |(i, url)| {let eval = eval.clone();let worker_path = worker_path.clone();let proxy = proxy.clone();- let handle = tokio::spawn(async move {- let _permit = sem.acquire().await.unwrap();+ async move {let task_start = Instant::now();let mut child = match TokioCommand::new(worker_path.as_ref())@@ -1938,14 +1932,13 @@ async fn run_parallel_scrape(})}}- });-- handles.push(handle);- }+ }+ })+ .await;let mut results = Vec::new();- for handle in handles {- match handle.await {+ for result in completed {+ match result {Ok(result) => results.push(result),Err(e) => results.push(serde_json::json!({"error": e.to_string()})),}