Skip to main content

cdp_driver/
cluster.rs

1//! A worker pool of pre-created tabs, distributing tasks with retries
2//! (puppeteer-cluster style). See [`Cluster`].
3
4use std::future::Future;
5use std::sync::Arc;
6use std::time::{Duration, Instant};
7
8use tokio::sync::Mutex;
9use tokio::task::JoinSet;
10
11use crate::client::CdpClient;
12use crate::config::Config;
13use crate::error::{CdpError, Result};
14
15/// Settings for [`Cluster::new`].
16pub struct ClusterConfig {
17    /// Chrome's remote-debugging host.
18    pub host: String,
19    /// Chrome's remote-debugging port.
20    pub port: u16,
21    /// Number of worker tabs to pre-create and run concurrently.
22    pub concurrency: usize,
23    /// Retries per task before it's reported as failed.
24    pub retries: u32,
25    /// Print per-task timing/outcome to stdout as tasks complete.
26    pub monitor: bool,
27    /// Viewport width applied to every worker tab.
28    pub viewport_width: i32,
29    /// Viewport height applied to every worker tab.
30    pub viewport_height: i32,
31}
32
33impl Default for ClusterConfig {
34    fn default() -> Self {
35        let base = Config::default();
36        Self::from(base)
37    }
38}
39
40impl From<Config> for ClusterConfig {
41    fn from(c: Config) -> Self {
42        ClusterConfig {
43            host: c.host,
44            port: c.port,
45            concurrency: 5,
46            retries: 2,
47            monitor: false,
48            viewport_width: c.viewport_width,
49            viewport_height: c.viewport_height,
50        }
51    }
52}
53
54/// Outcome of one task run through [`Cluster::execute`] or [`Cluster::run`].
55pub struct TaskResult<R> {
56    /// The task's return value, or its final error stringified after retries
57    /// were exhausted.
58    pub result: std::result::Result<R, String>,
59    /// Total wall time across all attempts.
60    pub elapsed: Duration,
61    /// Number of attempts made (1 if it succeeded on the first try).
62    pub attempts: u32,
63}
64
65impl<R> TaskResult<R> {
66    /// Shorthand for `self.result.is_ok()`.
67    pub fn is_ok(&self) -> bool {
68        self.result.is_ok()
69    }
70}
71
72struct Pool {
73    clients: Mutex<Vec<Arc<CdpClient>>>,
74    semaphore: tokio::sync::Semaphore,
75}
76
77/// Run one task, retrying up to `retries` more times after a failure.
78///
79/// Returns the outcome alongside how long every attempt took together and
80/// how many attempts it needed, which is what the monitor reports.
81async fn run_with_retries<D, R, F, Fut>(
82    client: Arc<CdpClient>,
83    data: D,
84    task: &F,
85    retries: u32,
86) -> (std::result::Result<R, String>, Duration, u32)
87where
88    D: Clone,
89    F: Fn(Arc<CdpClient>, D) -> Fut,
90    Fut: Future<Output = Result<R>>,
91{
92    let start = Instant::now();
93    let mut attempts = 0u32;
94
95    loop {
96        attempts += 1;
97        match task(Arc::clone(&client), data.clone()).await {
98            Ok(r) => return (Ok(r), start.elapsed(), attempts),
99            Err(e) => {
100                if attempts > retries {
101                    return (Err(e.to_string()), start.elapsed(), attempts);
102                }
103            }
104        }
105    }
106}
107
108/// A pool of `config.concurrency` pre-created tabs shared across tasks, with
109/// per-task retries. Workers are reused between tasks, avoiding per-task
110/// create/close overhead.
111pub struct Cluster {
112    pool: Arc<Pool>,
113    config: Arc<ClusterConfig>,
114}
115
116impl Cluster {
117    /// Create `config.concurrency` tabs and enable `Page`/`Runtime` on each.
118    pub async fn new(config: ClusterConfig) -> Result<Self> {
119        let mut clients = Vec::with_capacity(config.concurrency);
120
121        for i in 0..config.concurrency {
122            let target = CdpClient::create_tab(&config.host, config.port, None).await?;
123            let ws_url = target
124                .web_socket_debugger_url
125                .ok_or_else(|| CdpError::InvalidUrl(format!("worker {i}: no WS URL")))?;
126            let client = CdpClient::connect(&ws_url).await?;
127            client.enable_domain("Page").await?;
128            client.enable_domain("Runtime").await?;
129            client
130                .set_viewport(config.viewport_width, config.viewport_height, false)
131                .await?;
132            clients.push(Arc::new(client));
133        }
134
135        Ok(Cluster {
136            pool: Arc::new(Pool {
137                semaphore: tokio::sync::Semaphore::new(config.concurrency),
138                clients: Mutex::new(clients),
139            }),
140            config: Arc::new(config),
141        })
142    }
143
144    /// Run `task` on one available worker, retrying up to `config.retries` times on
145    /// failure. Blocks until a worker is free.
146    pub async fn execute<D, R, F, Fut>(&self, data: D, task: F) -> TaskResult<R>
147    where
148        D: Clone + Send + 'static,
149        R: Send + 'static,
150        F: Fn(Arc<CdpClient>, D) -> Fut + Send + Sync + 'static,
151        Fut: Future<Output = Result<R>> + Send + 'static,
152    {
153        let _permit = self
154            .pool
155            .semaphore
156            .acquire()
157            .await
158            .expect("semaphore closed");
159        let client = self
160            .pool
161            .clients
162            .lock()
163            .await
164            .pop()
165            .expect("worker missing");
166
167        let (result, elapsed, attempts) =
168            run_with_retries(Arc::clone(&client), data, &task, self.config.retries).await;
169
170        self.pool.clients.lock().await.push(client);
171
172        if self.config.monitor {
173            match &result {
174                Ok(_) => println!("[cluster] ok  {:.1}s ({attempts}x)", elapsed.as_secs_f64()),
175                Err(e) => println!(
176                    "[cluster] err {:.1}s ({attempts}x): {e}",
177                    elapsed.as_secs_f64()
178                ),
179            }
180        }
181
182        TaskResult {
183            result,
184            elapsed,
185            attempts,
186        }
187    }
188
189    /// Run `task` once per item in `items`, distributed across all workers
190    /// concurrently (bounded by `config.concurrency`). Order of results is
191    /// completion order, not input order.
192    pub async fn run<D, R, F, Fut>(
193        &self,
194        items: impl IntoIterator<Item = D>,
195        task: F,
196    ) -> Vec<TaskResult<R>>
197    where
198        D: Clone + Send + Sync + 'static,
199        R: Send + 'static,
200        F: Fn(Arc<CdpClient>, D) -> Fut + Send + Sync + Clone + 'static,
201        Fut: Future<Output = Result<R>> + Send + 'static,
202    {
203        let mut set = JoinSet::new();
204
205        for data in items {
206            let pool = self.pool.clone();
207            let config = self.config.clone();
208            let task = task.clone();
209
210            set.spawn(async move {
211                let _permit = pool.semaphore.acquire().await.expect("semaphore closed");
212                let client = pool.clients.lock().await.pop().expect("worker missing");
213
214                let (result, elapsed, attempts) =
215                    run_with_retries(Arc::clone(&client), data, &task, config.retries).await;
216
217                pool.clients.lock().await.push(client);
218
219                if config.monitor {
220                    match &result {
221                        Ok(_) => {
222                            println!("[cluster] ok  {:.1}s ({attempts}x)", elapsed.as_secs_f64())
223                        }
224                        Err(e) => println!(
225                            "[cluster] err {:.1}s ({attempts}x): {e}",
226                            elapsed.as_secs_f64()
227                        ),
228                    }
229                }
230
231                TaskResult {
232                    result,
233                    elapsed,
234                    attempts,
235                }
236            });
237        }
238
239        let mut results = Vec::new();
240        while let Some(res) = set.join_next().await {
241            if let Ok(r) = res {
242                results.push(r);
243            }
244        }
245        results
246    }
247
248    /// Close every worker tab.
249    pub async fn close(self) {
250        let clients = self.pool.clients.lock().await;
251        for client in clients.iter() {
252            let _ = client.close().await;
253        }
254    }
255}