1use std::future::Future;
2use std::sync::Arc;
3use std::time::{Duration, Instant};
4
5use tokio::sync::Mutex;
6use tokio::task::JoinSet;
7
8use crate::client::CdpClient;
9use crate::config::Config;
10use crate::error::{CdpError, Result};
11
12pub struct ClusterConfig {
13 pub host: String,
14 pub port: u16,
15 pub concurrency: usize,
16 pub retries: u32,
17 pub monitor: bool,
18 pub viewport_width: i32,
19 pub viewport_height: i32,
20}
21
22impl Default for ClusterConfig {
23 fn default() -> Self {
24 let base = Config::default();
25 Self::from(base)
26 }
27}
28
29impl From<Config> for ClusterConfig {
30 fn from(c: Config) -> Self {
31 ClusterConfig {
32 host: c.host,
33 port: c.port,
34 concurrency: 5,
35 retries: 2,
36 monitor: false,
37 viewport_width: c.viewport_width,
38 viewport_height: c.viewport_height,
39 }
40 }
41}
42
43pub struct TaskResult<R> {
44 pub result: std::result::Result<R, String>,
45 pub elapsed: Duration,
46 pub attempts: u32,
47}
48
49impl<R> TaskResult<R> {
50 pub fn is_ok(&self) -> bool {
51 self.result.is_ok()
52 }
53}
54
55struct Pool {
56 clients: Mutex<Vec<Arc<CdpClient>>>,
57 semaphore: tokio::sync::Semaphore,
58}
59
60pub struct Cluster {
61 pool: Arc<Pool>,
62 config: Arc<ClusterConfig>,
63}
64
65impl Cluster {
66 pub async fn new(config: ClusterConfig) -> Result<Self> {
67 let mut clients = Vec::with_capacity(config.concurrency);
68
69 for i in 0..config.concurrency {
70 let target = CdpClient::create_tab(&config.host, config.port, None).await?;
71 let ws_url = target
72 .web_socket_debugger_url
73 .ok_or_else(|| CdpError::InvalidUrl(format!("worker {i}: no WS URL")))?;
74 let client = CdpClient::connect(&ws_url).await?;
75 client.enable_domain("Page").await?;
76 client.enable_domain("Runtime").await?;
77 client
78 .set_viewport(config.viewport_width, config.viewport_height, false)
79 .await?;
80 clients.push(Arc::new(client));
81 }
82
83 Ok(Cluster {
84 pool: Arc::new(Pool {
85 semaphore: tokio::sync::Semaphore::new(config.concurrency),
86 clients: Mutex::new(clients),
87 }),
88 config: Arc::new(config),
89 })
90 }
91
92 pub async fn execute<D, R, F, Fut>(&self, data: D, task: F) -> TaskResult<R>
93 where
94 D: Clone + Send + 'static,
95 R: Send + 'static,
96 F: Fn(Arc<CdpClient>, D) -> Fut + Send + Sync + 'static,
97 Fut: Future<Output = Result<R>> + Send + 'static,
98 {
99 let _permit = self
100 .pool
101 .semaphore
102 .acquire()
103 .await
104 .expect("semaphore closed");
105 let client = self
106 .pool
107 .clients
108 .lock()
109 .await
110 .pop()
111 .expect("worker missing");
112
113 let (result, elapsed, attempts) =
114 run_with_retries(Arc::clone(&client), data, &task, self.config.retries).await;
115
116 self.pool.clients.lock().await.push(client);
117
118 if self.config.monitor {
119 match &result {
120 Ok(_) => println!("[cluster] ok {:.1}s ({attempts}x)", elapsed.as_secs_f64()),
121 Err(e) => println!(
122 "[cluster] err {:.1}s ({attempts}x): {e}",
123 elapsed.as_secs_f64()
124 ),
125 }
126 }
127
128 TaskResult {
129 result,
130 elapsed,
131 attempts,
132 }
133 }
134
135 pub async fn run<D, R, F, Fut>(
136 &self,
137 items: impl IntoIterator<Item = D>,
138 task: F,
139 ) -> Vec<TaskResult<R>>
140 where
141 D: Clone + Send + Sync + 'static,
142 R: Send + 'static,
143 F: Fn(Arc<CdpClient>, D) -> Fut + Send + Sync + Clone + 'static,
144 Fut: Future<Output = Result<R>> + Send + 'static,
145 {
146 let mut set = JoinSet::new();
147
148 for data in items {
149 let pool = self.pool.clone();
150 let config = self.config.clone();
151 let task = task.clone();
152
153 set.spawn(async move {
154 let _permit = pool.semaphore.acquire().await.expect("semaphore closed");
155 let client = pool.clients.lock().await.pop().expect("worker missing");
156
157 let (result, elapsed, attempts) =
158 run_with_retries(Arc::clone(&client), data, &task, config.retries).await;
159
160 pool.clients.lock().await.push(client);
161
162 if config.monitor {
163 match &result {
164 Ok(_) => {
165 println!("[cluster] ok {:.1}s ({attempts}x)", elapsed.as_secs_f64())
166 }
167 Err(e) => println!(
168 "[cluster] err {:.1}s ({attempts}x): {e}",
169 elapsed.as_secs_f64()
170 ),
171 }
172 }
173
174 TaskResult {
175 result,
176 elapsed,
177 attempts,
178 }
179 });
180 }
181
182 let mut results = Vec::new();
183 while let Some(res) = set.join_next().await {
184 if let Ok(r) = res {
185 results.push(r);
186 }
187 }
188 results
189 }
190
191 pub async fn close(self) {
192 let clients = self.pool.clients.lock().await;
193 for client in clients.iter() {
194 let _ = client.close().await;
195 }
196 }
197}
198
199async fn run_with_retries<D, R, F, Fut>(
200 client: Arc<CdpClient>,
201 data: D,
202 task: &F,
203 retries: u32,
204) -> (std::result::Result<R, String>, Duration, u32)
205where
206 D: Clone,
207 F: Fn(Arc<CdpClient>, D) -> Fut,
208 Fut: Future<Output = Result<R>>,
209{
210 let start = Instant::now();
211 let mut attempts = 0u32;
212
213 loop {
214 attempts += 1;
215 match task(Arc::clone(&client), data.clone()).await {
216 Ok(r) => return (Ok(r), start.elapsed(), attempts),
217 Err(e) => {
218 if attempts > retries {
219 return (Err(e.to_string()), start.elapsed(), attempts);
220 }
221 }
222 }
223 }
224}