Skip to main content

cdp_driver/
client.rs

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