Skip to main content

cdp_driver/
client.rs

1use std::collections::HashMap;
2use std::sync::atomic::{AtomicU64, Ordering};
3use std::sync::Arc;
4use std::time::Duration;
5
6use base64::Engine;
7use futures_util::{SinkExt, StreamExt};
8use serde_json::{json, Value};
9use tokio::sync::{broadcast, oneshot, Mutex};
10use tokio_tungstenite::{connect_async, tungstenite::Message};
11use tracing::{debug, warn};
12
13use crate::error::{CdpError, Result};
14use crate::types::*;
15
16type PendingMap = Arc<Mutex<HashMap<u64, oneshot::Sender<Result<Value>>>>>;
17
18/// Default per-command timeout, in milliseconds. Override with
19/// [`CdpClient::set_command_timeout`]. A value of `0` disables the timeout.
20const DEFAULT_COMMAND_TIMEOUT_MS: u64 = 30_000;
21
22pub struct CdpClient {
23    tx: tokio::sync::mpsc::UnboundedSender<Message>,
24    pending: PendingMap,
25    next_id: Arc<AtomicU64>,
26    events_tx: broadcast::Sender<(String, Value)>,
27    command_timeout_ms: Arc<AtomicU64>,
28}
29
30impl CdpClient {
31    pub async fn connect(ws_url: &str) -> Result<Self> {
32        debug!(%ws_url, "connecting");
33        let (ws_stream, _) = connect_async(ws_url).await?;
34        let (mut sink, mut stream) = ws_stream.split();
35
36        let pending: PendingMap = Arc::new(Mutex::new(HashMap::new()));
37        let pending_clone = pending.clone();
38
39        let (events_tx, _) = broadcast::channel::<(String, Value)>(256);
40        let events_tx_clone = events_tx.clone();
41
42        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Message>();
43
44        tokio::spawn(async move {
45            while let Some(msg) = rx.recv().await {
46                if sink.send(msg).await.is_err() {
47                    break;
48                }
49            }
50        });
51
52        tokio::spawn(async move {
53            while let Some(msg) = stream.next().await {
54                match msg {
55                    Ok(Message::Text(text)) => {
56                        let Ok(val) = serde_json::from_str::<Value>(&text) else {
57                            continue;
58                        };
59                        let Some(id) = val.get("id").and_then(|v| v.as_u64()) else {
60                            if let (Some(method), params) = (
61                                val.get("method")
62                                    .and_then(|v| v.as_str())
63                                    .map(str::to_owned),
64                                val.get("params").cloned().unwrap_or(Value::Null),
65                            ) {
66                                debug!(%method, "event");
67                                let _ = events_tx_clone.send((method, params));
68                            }
69                            continue;
70                        };
71                        let outcome = if val.get("error").is_some() {
72                            let msg = val["error"]["message"]
73                                .as_str()
74                                .unwrap_or("protocol error")
75                                .to_string();
76                            warn!(id, %msg, "protocol error");
77                            Err(CdpError::Protocol(msg))
78                        } else {
79                            debug!(id, "recv");
80                            Ok(val.get("result").cloned().unwrap_or(Value::Null))
81                        };
82                        let mut map = pending_clone.lock().await;
83                        if let Some(tx) = map.remove(&id) {
84                            let _ = tx.send(outcome);
85                        }
86                    }
87                    Ok(Message::Close(_)) | Err(_) => {
88                        let mut map = pending_clone.lock().await;
89                        for (_, tx) in map.drain() {
90                            let _ = tx.send(Err(CdpError::Protocol("connection closed".into())));
91                        }
92                        break;
93                    }
94                    _ => {}
95                }
96            }
97        });
98
99        Ok(CdpClient {
100            tx,
101            pending,
102            next_id: Arc::new(AtomicU64::new(1)),
103            events_tx,
104            command_timeout_ms: Arc::new(AtomicU64::new(DEFAULT_COMMAND_TIMEOUT_MS)),
105        })
106    }
107
108    /// Set the per-command timeout applied to every [`send_command`](Self::send_command)
109    /// call. Passing a zero duration disables the timeout (commands wait indefinitely).
110    pub fn set_command_timeout(&self, timeout: Duration) {
111        let ms = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX);
112        self.command_timeout_ms.store(ms, Ordering::Relaxed);
113    }
114
115    /// The current per-command timeout.
116    pub fn command_timeout(&self) -> Duration {
117        Duration::from_millis(self.command_timeout_ms.load(Ordering::Relaxed))
118    }
119
120    pub(crate) async fn send_command(&self, method: &str, params: Value) -> Result<Value> {
121        let id = self.next_id.fetch_add(1, Ordering::SeqCst);
122        debug!(%method, id, "send");
123        let (tx, rx) = oneshot::channel();
124
125        self.pending.lock().await.insert(id, tx);
126
127        if let Err(e) = self.tx.send(Message::Text(
128            json!({ "id": id, "method": method, "params": params })
129                .to_string()
130                .into(),
131        )) {
132            // Writer task is gone; don't leave a dangling entry in `pending`.
133            self.pending.lock().await.remove(&id);
134            return Err(CdpError::Protocol(e.to_string()));
135        }
136
137        let closed = || CdpError::Protocol("response channel closed".into());
138
139        let timeout_ms = self.command_timeout_ms.load(Ordering::Relaxed);
140        if timeout_ms == 0 {
141            return match rx.await {
142                Ok(outcome) => outcome,
143                Err(_) => Err(closed()),
144            };
145        }
146
147        match tokio::time::timeout(Duration::from_millis(timeout_ms), rx).await {
148            Ok(Ok(outcome)) => outcome,
149            Ok(Err(_)) => Err(closed()),
150            Err(_) => {
151                // Timed out waiting for a reply: drop the pending sender so the
152                // map doesn't grow unbounded for commands the browser never answers.
153                self.pending.lock().await.remove(&id);
154                Err(CdpError::Timeout)
155            }
156        }
157    }
158
159    pub fn subscribe_events(&self) -> broadcast::Receiver<(String, Value)> {
160        self.events_tx.subscribe()
161    }
162
163    pub async fn wait_for_event(&self, method: &str, timeout_ms: u64) -> Result<Value> {
164        let mut rx = self.events_tx.subscribe();
165        tokio::time::timeout(std::time::Duration::from_millis(timeout_ms), async move {
166            loop {
167                match rx.recv().await {
168                    Ok((m, params)) if m == method => return Ok(params),
169                    Ok(_) => continue,
170                    Err(broadcast::error::RecvError::Lagged(_)) => continue,
171                    Err(_) => return Err(CdpError::Protocol("event channel closed".into())),
172                }
173            }
174        })
175        .await
176        .map_err(|_| CdpError::Timeout)?
177    }
178
179    pub async fn enable_domain(&self, domain: &str) -> Result<()> {
180        self.send_command(&format!("{domain}.enable"), json!({}))
181            .await?;
182        Ok(())
183    }
184
185    pub async fn navigate(&self, url: &str) -> Result<NavigationResult> {
186        let result = self
187            .send_command("Page.navigate", json!({ "url": url }))
188            .await?;
189        Ok(serde_json::from_value(result)?)
190    }
191
192    pub async fn navigate_and_wait(&self, url: &str, timeout_ms: u64) -> Result<NavigationResult> {
193        let mut rx = self.events_tx.subscribe();
194        let nav = self.navigate(url).await?;
195        tokio::time::timeout(std::time::Duration::from_millis(timeout_ms), async move {
196            loop {
197                match rx.recv().await {
198                    Ok((m, _)) if m == "Page.loadEventFired" => return Ok(nav),
199                    Ok(_) => continue,
200                    Err(broadcast::error::RecvError::Lagged(_)) => continue,
201                    Err(_) => return Err(CdpError::Protocol("event channel closed".into())),
202                }
203            }
204        })
205        .await
206        .map_err(|_| CdpError::Timeout)?
207    }
208
209    pub async fn eval(&self, expression: &str) -> Result<String> {
210        let result = self.evaluate(expression).await?;
211        Ok(result
212            .result
213            .value
214            .map(|v| match v {
215                Value::String(s) => s,
216                other => other.to_string(),
217            })
218            .unwrap_or_default())
219    }
220
221    pub async fn evaluate(&self, expression: &str) -> Result<EvaluateResult> {
222        let result = self
223            .send_command(
224                "Runtime.evaluate",
225                json!({ "expression": expression, "returnByValue": true }),
226            )
227            .await?;
228        Ok(serde_json::from_value(result)?)
229    }
230
231    pub async fn get_document(&self) -> Result<DocumentNode> {
232        let result = self
233            .send_command("DOM.getDocument", json!({ "depth": 0 }))
234            .await?;
235        let root = result["root"].clone();
236        if root.is_null() {
237            return Err(CdpError::Protocol(
238                "DOM.getDocument returned no root".into(),
239            ));
240        }
241        Ok(serde_json::from_value(root)?)
242    }
243
244    /// Returns the matched `nodeId`, or `None` when nothing matches.
245    /// CDP reports a missing match as `nodeId` 0; this surfaces that as `None`
246    /// rather than a node id that looks valid.
247    pub async fn query_selector(&self, node_id: i64, selector: &str) -> Result<Option<i64>> {
248        let result = self
249            .send_command(
250                "DOM.querySelector",
251                json!({ "nodeId": node_id, "selector": selector }),
252            )
253            .await?;
254        Ok(match result["nodeId"].as_i64() {
255            Some(id) if id > 0 => Some(id),
256            _ => None,
257        })
258    }
259
260    pub async fn get_outer_html(&self, node_id: i64) -> Result<String> {
261        let result = self
262            .send_command("DOM.getOuterHTML", json!({ "nodeId": node_id }))
263            .await?;
264        Ok(result["outerHTML"].as_str().unwrap_or("").to_string())
265    }
266
267    pub async fn close(&self) -> Result<()> {
268        // Ignore errors, connection drops immediately after the tab closes
269        let _ = self.send_command("Page.close", json!({})).await;
270        Ok(())
271    }
272
273    pub async fn screenshot(&self) -> Result<Vec<u8>> {
274        let result = self
275            .send_command(
276                "Page.captureScreenshot",
277                json!({ "format": "png", "fromSurface": true }),
278            )
279            .await?;
280        png_bytes_from(&result)
281    }
282
283    pub async fn screenshot_to_file(&self, path: &str) -> Result<()> {
284        tokio::fs::write(path, self.screenshot().await?).await?;
285        Ok(())
286    }
287
288    pub async fn full_page_screenshot(&self) -> Result<Vec<u8>> {
289        let size = self
290            .evaluate(
291                "(() => ({ \
292                w: Math.max(document.body.scrollWidth, document.documentElement.scrollWidth), \
293                h: Math.max(document.body.scrollHeight, document.documentElement.scrollHeight) \
294            }))()",
295            )
296            .await?;
297
298        let dims = size.result.value.as_ref();
299        let w = dims.and_then(|v| v["w"].as_i64()).unwrap_or(1920) as i32;
300        let h = dims.and_then(|v| v["h"].as_i64()).unwrap_or(1200) as i32;
301        self.set_viewport(w.max(1920), h.max(1200), false).await?;
302
303        let result = self
304            .send_command(
305                "Page.captureScreenshot",
306                json!({
307                    "format": "png",
308                    "captureBeyondViewport": true,
309                    "fromSurface": true,
310                }),
311            )
312            .await?;
313        png_bytes_from(&result)
314    }
315
316    pub async fn full_page_screenshot_to_file(&self, path: &str) -> Result<()> {
317        tokio::fs::write(path, self.full_page_screenshot().await?).await?;
318        Ok(())
319    }
320
321    pub async fn set_viewport(&self, width: i32, height: i32, mobile: bool) -> Result<()> {
322        self.send_command(
323            "Emulation.setDeviceMetricsOverride",
324            json!({ "width": width, "height": height, "deviceScaleFactor": 1, "mobile": mobile }),
325        )
326        .await?;
327        Ok(())
328    }
329
330    pub async fn get_cookies(&self) -> Result<Vec<Cookie>> {
331        let result = self.send_command("Network.getCookies", json!({})).await?;
332        Ok(serde_json::from_value(result["cookies"].clone())?)
333    }
334
335    pub async fn get_version(host: &str, port: u16) -> Result<BrowserVersion> {
336        let url = format!("http://{host}:{port}/json/version");
337        Ok(reqwest::get(&url).await?.json().await?)
338    }
339
340    pub async fn list_targets(host: &str, port: u16) -> Result<Vec<Target>> {
341        let url = format!("http://{host}:{port}/json/list");
342        Ok(reqwest::get(&url).await?.json().await?)
343    }
344
345    pub async fn connect_to_page(host: &str, port: u16) -> Result<Self> {
346        let targets = Self::list_targets(host, port).await?;
347        let page = targets
348            .into_iter()
349            .find(|t| t.target_type == "page")
350            .ok_or(CdpError::NoTarget)?;
351        let ws_url = page
352            .web_socket_debugger_url
353            .ok_or_else(|| CdpError::InvalidUrl("target has no debugger URL".into()))?;
354        Self::connect(&ws_url).await
355    }
356
357    pub async fn create_tab(host: &str, port: u16, url: Option<&str>) -> Result<Target> {
358        // Chrome requires PUT for /json/new (GET returns 405 in modern versions)
359        let endpoint = match url {
360            Some(u) => format!("http://{host}:{port}/json/new?{u}"),
361            None => format!("http://{host}:{port}/json/new"),
362        };
363        Ok(reqwest::Client::new()
364            .put(&endpoint)
365            .send()
366            .await?
367            .json()
368            .await?)
369    }
370}
371
372fn png_bytes_from(result: &Value) -> Result<Vec<u8>> {
373    let data = result["data"]
374        .as_str()
375        .ok_or_else(|| CdpError::Protocol("screenshot response has no data".into()))?;
376    base64::engine::general_purpose::STANDARD
377        .decode(data)
378        .map_err(|e| CdpError::Protocol(e.to_string()))
379}