1use 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
15pub struct ClusterConfig {
17 pub host: String,
19 pub port: u16,
21 pub concurrency: usize,
23 pub retries: u32,
25 pub monitor: bool,
27 pub viewport_width: i32,
29 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
54pub struct TaskResult<R> {
56 pub result: std::result::Result<R, String>,
59 pub elapsed: Duration,
61 pub attempts: u32,
63}
64
65impl<R> TaskResult<R> {
66 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
77pub struct Cluster {
81 pool: Arc<Pool>,
82 config: Arc<ClusterConfig>,
83}
84
85impl Cluster {
86 pub async fn new(config: ClusterConfig) -> Result<Self> {
88 let mut clients = Vec::with_capacity(config.concurrency);
89
90 for i in 0..config.concurrency {
91 let target = CdpClient::create_tab(&config.host, config.port, None).await?;
92 let ws_url = target
93 .web_socket_debugger_url
94 .ok_or_else(|| CdpError::InvalidUrl(format!("worker {i}: no WS URL")))?;
95 let client = CdpClient::connect(&ws_url).await?;
96 client.enable_domain("Page").await?;
97 client.enable_domain("Runtime").await?;
98 client
99 .set_viewport(config.viewport_width, config.viewport_height, false)
100 .await?;
101 clients.push(Arc::new(client));
102 }
103
104 Ok(Cluster {
105 pool: Arc::new(Pool {
106 semaphore: tokio::sync::Semaphore::new(config.concurrency),
107 clients: Mutex::new(clients),
108 }),
109 config: Arc::new(config),
110 })
111 }
112
113 pub async fn execute<D, R, F, Fut>(&self, data: D, task: F) -> TaskResult<R>
116 where
117 D: Clone + Send + 'static,
118 R: Send + 'static,
119 F: Fn(Arc<CdpClient>, D) -> Fut + Send + Sync + 'static,
120 Fut: Future<Output = Result<R>> + Send + 'static,
121 {
122 let _permit = self
123 .pool
124 .semaphore
125 .acquire()
126 .await
127 .expect("semaphore closed");
128 let client = self
129 .pool
130 .clients
131 .lock()
132 .await
133 .pop()
134 .expect("worker missing");
135
136 let (result, elapsed, attempts) =
137 run_with_retries(Arc::clone(&client), data, &task, self.config.retries).await;
138
139 self.pool.clients.lock().await.push(client);
140
141 if self.config.monitor {
142 match &result {
143 Ok(_) => println!("[cluster] ok {:.1}s ({attempts}x)", elapsed.as_secs_f64()),
144 Err(e) => println!(
145 "[cluster] err {:.1}s ({attempts}x): {e}",
146 elapsed.as_secs_f64()
147 ),
148 }
149 }
150
151 TaskResult {
152 result,
153 elapsed,
154 attempts,
155 }
156 }
157
158 pub async fn run<D, R, F, Fut>(
162 &self,
163 items: impl IntoIterator<Item = D>,
164 task: F,
165 ) -> Vec<TaskResult<R>>
166 where
167 D: Clone + Send + Sync + 'static,
168 R: Send + 'static,
169 F: Fn(Arc<CdpClient>, D) -> Fut + Send + Sync + Clone + 'static,
170 Fut: Future<Output = Result<R>> + Send + 'static,
171 {
172 let mut set = JoinSet::new();
173
174 for data in items {
175 let pool = self.pool.clone();
176 let config = self.config.clone();
177 let task = task.clone();
178
179 set.spawn(async move {
180 let _permit = pool.semaphore.acquire().await.expect("semaphore closed");
181 let client = pool.clients.lock().await.pop().expect("worker missing");
182
183 let (result, elapsed, attempts) =
184 run_with_retries(Arc::clone(&client), data, &task, config.retries).await;
185
186 pool.clients.lock().await.push(client);
187
188 if config.monitor {
189 match &result {
190 Ok(_) => {
191 println!("[cluster] ok {:.1}s ({attempts}x)", elapsed.as_secs_f64())
192 }
193 Err(e) => println!(
194 "[cluster] err {:.1}s ({attempts}x): {e}",
195 elapsed.as_secs_f64()
196 ),
197 }
198 }
199
200 TaskResult {
201 result,
202 elapsed,
203 attempts,
204 }
205 });
206 }
207
208 let mut results = Vec::new();
209 while let Some(res) = set.join_next().await {
210 if let Ok(r) = res {
211 results.push(r);
212 }
213 }
214 results
215 }
216
217 pub async fn close(self) {
219 let clients = self.pool.clients.lock().await;
220 for client in clients.iter() {
221 let _ = client.close().await;
222 }
223 }
224}
225
226async fn run_with_retries<D, R, F, Fut>(
227 client: Arc<CdpClient>,
228 data: D,
229 task: &F,
230 retries: u32,
231) -> (std::result::Result<R, String>, Duration, u32)
232where
233 D: Clone,
234 F: Fn(Arc<CdpClient>, D) -> Fut,
235 Fut: Future<Output = Result<R>>,
236{
237 let start = Instant::now();
238 let mut attempts = 0u32;
239
240 loop {
241 attempts += 1;
242 match task(Arc::clone(&client), data.clone()).await {
243 Ok(r) => return (Ok(r), start.elapsed(), attempts),
244 Err(e) => {
245 if attempts > retries {
246 return (Err(e.to_string()), start.elapsed(), attempts);
247 }
248 }
249 }
250 }
251}