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::{Sink, Stream};
14use futures_util::{SinkExt, StreamExt};
15use serde::de::DeserializeOwned;
16use serde::Serialize;
17use serde_json::{json, Value};
18use tokio::sync::{broadcast, mpsc, oneshot, Mutex};
19use tokio_tungstenite::connect_async;
20use tokio_tungstenite::tungstenite::{Error as WsError, Message};
21use tracing::{debug, warn};
22
23use crate::error::{CdpError, Result};
24use crate::types::*;
25
26/// Default per-command timeout, in milliseconds. Override with
27/// [`CdpClient::set_command_timeout`]. A value of `0` disables the timeout.
28const DEFAULT_COMMAND_TIMEOUT_MS: u64 = 30_000;
29
30/// How many events may queue for a subscriber before the oldest are dropped.
31const EVENT_BACKLOG: usize = 256;
32
33/// What every in-flight command is told when the socket goes away.
34const CONNECTION_CLOSED: &str = "connection closed";
35
36type PendingMap = Arc<Mutex<HashMap<u64, oneshot::Sender<Result<Value>>>>>;
37
38type Events = broadcast::Sender<(String, Value)>;
39
40/// Decode the base64 payload a screenshot command answers with.
41fn png_bytes_from(result: &Value) -> Result<Vec<u8>> {
42    let data = result["data"]
43        .as_str()
44        .ok_or_else(|| CdpError::Protocol("screenshot response has no data".into()))?;
45    base64::engine::general_purpose::STANDARD
46        .decode(data)
47        .map_err(|e| CdpError::Protocol(e.to_string()))
48}
49
50/// The reply a command frame carries: its result, or the error it reports.
51fn reply_in(frame: &Value, id: u64) -> Result<Value> {
52    let Some(error) = frame.get("error") else {
53        debug!(id, "recv");
54        return Ok(frame.get("result").cloned().unwrap_or(Value::Null));
55    };
56    let message = error["message"]
57        .as_str()
58        .unwrap_or("protocol error")
59        .to_string();
60    warn!(id, %message, "protocol error");
61    Err(CdpError::Protocol(message))
62}
63
64/// Hand a reply to whoever is waiting on `id`, if anyone still is. Nobody is
65/// waiting once a command has timed out, and that is not an error.
66async fn deliver(pending: &PendingMap, id: u64, reply: Result<Value>) {
67    if let Some(waiting) = pending.lock().await.remove(&id) {
68        let _ = waiting.send(reply);
69    }
70}
71
72/// Publish an unsolicited frame to event subscribers.
73fn publish(events: &Events, frame: &Value) {
74    let Some(method) = frame.get("method").and_then(Value::as_str) else {
75        return;
76    };
77    debug!(%method, "event");
78    let params = frame.get("params").cloned().unwrap_or(Value::Null);
79    let _ = events.send((method.to_owned(), params));
80}
81
82/// Route one text frame. A frame carrying an `id` answers a command; anything
83/// else is an event. Frames that are not JSON at all are dropped.
84async fn route(text: &str, pending: &PendingMap, events: &Events) {
85    let Ok(frame) = serde_json::from_str::<Value>(text) else {
86        return;
87    };
88    match frame.get("id").and_then(Value::as_u64) {
89        Some(id) => deliver(pending, id, reply_in(&frame, id)).await,
90        None => publish(events, &frame),
91    }
92}
93
94/// Fail every command still awaiting a reply.
95async fn abandon_pending(pending: &PendingMap) {
96    for (_, waiting) in pending.lock().await.drain() {
97        let _ = waiting.send(Err(CdpError::Protocol(CONNECTION_CLOSED.into())));
98    }
99}
100
101/// Forward queued commands to the socket until the client is dropped or the
102/// socket refuses them.
103async fn write_outgoing<S>(mut sink: S, mut outgoing: mpsc::UnboundedReceiver<Message>)
104where
105    S: Sink<Message> + Unpin,
106{
107    while let Some(message) = outgoing.recv().await {
108        if sink.send(message).await.is_err() {
109            break;
110        }
111    }
112}
113
114/// Demultiplex the socket for the client's lifetime, sending replies to their
115/// callers and events to subscribers.
116///
117/// However the stream ends, whether closed cleanly, failed, or simply exhausted,
118/// the commands still in flight are failed rather than left to time out.
119async fn read_incoming<S>(mut stream: S, pending: PendingMap, events: Events)
120where
121    S: Stream<Item = std::result::Result<Message, WsError>> + Unpin,
122{
123    while let Some(message) = stream.next().await {
124        match message {
125            Ok(Message::Text(text)) => route(&text, &pending, &events).await,
126            Ok(Message::Close(_)) | Err(_) => break,
127            _ => {}
128        }
129    }
130    abandon_pending(&pending).await;
131}
132
133/// A single WebSocket session to one Chrome debugging target.
134///
135/// Cloning is not supported; share a client across tasks with `Arc<CdpClient>`
136/// (see [`Cluster`](crate::cluster::Cluster) for an example). Every command sent
137/// concurrently gets its own response future, matched by CDP message id.
138pub struct CdpClient {
139    tx: tokio::sync::mpsc::UnboundedSender<Message>,
140    pending: PendingMap,
141    next_id: Arc<AtomicU64>,
142    events_tx: broadcast::Sender<(String, Value)>,
143    command_timeout_ms: Arc<AtomicU64>,
144}
145
146impl CdpClient {
147    /// Open a CDP WebSocket session at `ws_url` (a target's `webSocketDebuggerUrl`).
148    ///
149    /// Spawns background tasks that pump outgoing commands and demultiplex incoming
150    /// replies/events for the lifetime of the returned client.
151    pub async fn connect(ws_url: &str) -> Result<Self> {
152        debug!(%ws_url, "connecting");
153        let (ws_stream, _) = connect_async(ws_url).await?;
154        let (sink, stream) = ws_stream.split();
155
156        let pending: PendingMap = Arc::new(Mutex::new(HashMap::new()));
157        let (events_tx, _) = broadcast::channel::<(String, Value)>(EVENT_BACKLOG);
158        let (tx, outgoing) = mpsc::unbounded_channel::<Message>();
159
160        tokio::spawn(write_outgoing(sink, outgoing));
161        tokio::spawn(read_incoming(stream, pending.clone(), events_tx.clone()));
162
163        Ok(CdpClient {
164            tx,
165            pending,
166            next_id: Arc::new(AtomicU64::new(1)),
167            events_tx,
168            command_timeout_ms: Arc::new(AtomicU64::new(DEFAULT_COMMAND_TIMEOUT_MS)),
169        })
170    }
171
172    /// Set the per-command timeout applied to every CDP command this client sends.
173    /// Passing a zero duration disables the timeout (commands wait indefinitely).
174    pub fn set_command_timeout(&self, timeout: Duration) {
175        let ms = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX);
176        self.command_timeout_ms.store(ms, Ordering::Relaxed);
177    }
178
179    /// The current per-command timeout.
180    pub fn command_timeout(&self) -> Duration {
181        Duration::from_millis(self.command_timeout_ms.load(Ordering::Relaxed))
182    }
183
184    pub(crate) async fn send_command(&self, method: &str, params: Value) -> Result<Value> {
185        let id = self.next_id.fetch_add(1, Ordering::SeqCst);
186        debug!(%method, id, "send");
187        let (tx, rx) = oneshot::channel();
188
189        self.pending.lock().await.insert(id, tx);
190
191        if let Err(e) = self.tx.send(Message::Text(
192            json!({ "id": id, "method": method, "params": params })
193                .to_string()
194                .into(),
195        )) {
196            // Writer task is gone; don't leave a dangling entry in `pending`.
197            self.pending.lock().await.remove(&id);
198            return Err(CdpError::Protocol(e.to_string()));
199        }
200
201        let closed = || CdpError::Protocol("response channel closed".into());
202
203        let timeout_ms = self.command_timeout_ms.load(Ordering::Relaxed);
204        if timeout_ms == 0 {
205            return match rx.await {
206                Ok(outcome) => outcome,
207                Err(_) => Err(closed()),
208            };
209        }
210
211        match tokio::time::timeout(Duration::from_millis(timeout_ms), rx).await {
212            Ok(Ok(outcome)) => outcome,
213            Ok(Err(_)) => Err(closed()),
214            Err(_) => {
215                // Timed out waiting for a reply: drop the pending sender so the
216                // map doesn't grow unbounded for commands the browser never answers.
217                self.pending.lock().await.remove(&id);
218                Err(CdpError::Timeout)
219            }
220        }
221    }
222
223    /// Send any CDP command and deserialize its result into `R`.
224    ///
225    /// The typed wrappers on this client cover only a small, curated slice of the
226    /// DevTools Protocol; this is the escape hatch for everything else, including
227    /// domains this crate has no wrappers for at all (`Target`, `Storage`,
228    /// `Debugger`, ...). `params` must serialize to a JSON object, since that is
229    /// what CDP expects; use `json!({})` for commands that take no parameters.
230    ///
231    /// ```no_run
232    /// # use cdp_driver::CdpClient;
233    /// # use serde::Deserialize;
234    /// # use serde_json::json;
235    /// #[derive(Deserialize)]
236    /// #[serde(rename_all = "camelCase")]
237    /// struct CreateTarget {
238    ///     target_id: String,
239    /// }
240    ///
241    /// # async fn run(client: &CdpClient) -> cdp_driver::Result<()> {
242    /// let created: CreateTarget = client
243    ///     .call("Target.createTarget", json!({ "url": "about:blank" }))
244    ///     .await?;
245    /// # Ok(())
246    /// # }
247    /// ```
248    pub async fn call<P: Serialize, R: DeserializeOwned>(
249        &self,
250        method: &str,
251        params: P,
252    ) -> Result<R> {
253        let result = self.call_raw(method, serde_json::to_value(params)?).await?;
254        Ok(serde_json::from_value(result)?)
255    }
256
257    /// Send any CDP command and return its raw `result` object unparsed.
258    ///
259    /// Prefer [`call`](Self::call) when you have a type to deserialize into. This is
260    /// the lower-level form, useful for exploring a response's shape or for commands
261    /// whose result you only want to index into. Commands that return no result
262    /// yield [`Value::Null`].
263    pub async fn call_raw(&self, method: &str, params: Value) -> Result<Value> {
264        self.send_command(method, params).await
265    }
266
267    /// Subscribe to raw CDP events as `(method, params)` pairs.
268    ///
269    /// Only events for domains enabled via [`enable_domain`](Self::enable_domain)
270    /// are emitted. Lagging receivers silently drop the oldest events rather than
271    /// blocking the connection.
272    pub fn subscribe_events(&self) -> broadcast::Receiver<(String, Value)> {
273        self.events_tx.subscribe()
274    }
275
276    /// Wait for the next event named `method`, up to `timeout_ms` milliseconds.
277    pub async fn wait_for_event(&self, method: &str, timeout_ms: u64) -> Result<Value> {
278        let mut rx = self.events_tx.subscribe();
279        tokio::time::timeout(std::time::Duration::from_millis(timeout_ms), async move {
280            loop {
281                match rx.recv().await {
282                    Ok((m, params)) if m == method => return Ok(params),
283                    Ok(_) => continue,
284                    Err(broadcast::error::RecvError::Lagged(_)) => continue,
285                    Err(_) => return Err(CdpError::Protocol("event channel closed".into())),
286                }
287            }
288        })
289        .await
290        .map_err(|_| CdpError::Timeout)?
291    }
292
293    /// Enable a CDP domain (e.g. `"Page"`, `"Runtime"`, `"Network"`), required before
294    /// that domain's events start flowing or some of its commands work.
295    pub async fn enable_domain(&self, domain: &str) -> Result<()> {
296        self.send_command(&format!("{domain}.enable"), json!({}))
297            .await?;
298        Ok(())
299    }
300
301    /// Navigate to `url`. Returns as soon as navigation starts, without waiting for
302    /// the page to finish loading; use [`navigate_and_wait`](Self::navigate_and_wait)
303    /// to block until `Page.loadEventFired`.
304    pub async fn navigate(&self, url: &str) -> Result<NavigationResult> {
305        let result = self
306            .send_command("Page.navigate", json!({ "url": url }))
307            .await?;
308        Ok(serde_json::from_value(result)?)
309    }
310
311    /// Navigate to `url` and wait for `Page.loadEventFired`, up to `timeout_ms`.
312    /// Requires the `"Page"` domain to be enabled.
313    pub async fn navigate_and_wait(&self, url: &str, timeout_ms: u64) -> Result<NavigationResult> {
314        let mut rx = self.events_tx.subscribe();
315        let nav = self.navigate(url).await?;
316        tokio::time::timeout(std::time::Duration::from_millis(timeout_ms), async move {
317            loop {
318                match rx.recv().await {
319                    Ok((m, _)) if m == "Page.loadEventFired" => return Ok(nav),
320                    Ok(_) => continue,
321                    Err(broadcast::error::RecvError::Lagged(_)) => continue,
322                    Err(_) => return Err(CdpError::Protocol("event channel closed".into())),
323                }
324            }
325        })
326        .await
327        .map_err(|_| CdpError::Timeout)?
328    }
329
330    /// Evaluate a JS expression and return its result stringified. Prefer
331    /// [`evaluate`](Self::evaluate) when you need the structured result or exception
332    /// details.
333    pub async fn eval(&self, expression: &str) -> Result<String> {
334        let result = self.evaluate(expression).await?;
335        Ok(result
336            .result
337            .value
338            .map(|v| match v {
339                Value::String(s) => s,
340                other => other.to_string(),
341            })
342            .unwrap_or_default())
343    }
344
345    /// Evaluate a JS expression via `Runtime.evaluate` and return the full result,
346    /// including any exception details.
347    pub async fn evaluate(&self, expression: &str) -> Result<EvaluateResult> {
348        let result = self
349            .send_command(
350                "Runtime.evaluate",
351                json!({ "expression": expression, "returnByValue": true }),
352            )
353            .await?;
354        Ok(serde_json::from_value(result)?)
355    }
356
357    /// Fetch the document's root node. Requires the `"DOM"` domain to be enabled.
358    pub async fn get_document(&self) -> Result<DocumentNode> {
359        let result = self
360            .send_command("DOM.getDocument", json!({ "depth": 0 }))
361            .await?;
362        let root = result["root"].clone();
363        if root.is_null() {
364            return Err(CdpError::Protocol(
365                "DOM.getDocument returned no root".into(),
366            ));
367        }
368        Ok(serde_json::from_value(root)?)
369    }
370
371    /// Returns the matched `nodeId`, or `None` when nothing matches.
372    /// CDP reports a missing match as `nodeId` 0; this surfaces that as `None`
373    /// rather than a node id that looks valid.
374    pub async fn query_selector(&self, node_id: i64, selector: &str) -> Result<Option<i64>> {
375        let result = self
376            .send_command(
377                "DOM.querySelector",
378                json!({ "nodeId": node_id, "selector": selector }),
379            )
380            .await?;
381        Ok(match result["nodeId"].as_i64() {
382            Some(id) if id > 0 => Some(id),
383            _ => None,
384        })
385    }
386
387    /// Serialize a node's outer HTML.
388    pub async fn get_outer_html(&self, node_id: i64) -> Result<String> {
389        let result = self
390            .send_command("DOM.getOuterHTML", json!({ "nodeId": node_id }))
391            .await?;
392        Ok(result["outerHTML"].as_str().unwrap_or("").to_string())
393    }
394
395    /// Close the tab this client is attached to.
396    pub async fn close(&self) -> Result<()> {
397        // Ignore errors, connection drops immediately after the tab closes
398        let _ = self.send_command("Page.close", json!({})).await;
399        Ok(())
400    }
401
402    /// Capture a PNG screenshot of the current viewport.
403    pub async fn screenshot(&self) -> Result<Vec<u8>> {
404        let result = self
405            .send_command(
406                "Page.captureScreenshot",
407                json!({ "format": "png", "fromSurface": true }),
408            )
409            .await?;
410        png_bytes_from(&result)
411    }
412
413    /// [`screenshot`](Self::screenshot), written directly to `path`.
414    pub async fn screenshot_to_file(&self, path: &str) -> Result<()> {
415        tokio::fs::write(path, self.screenshot().await?).await?;
416        Ok(())
417    }
418
419    /// Capture a PNG screenshot of the full page, resizing the viewport to the
420    /// page's scroll size first (restoring it is the caller's responsibility).
421    pub async fn full_page_screenshot(&self) -> Result<Vec<u8>> {
422        let size = self
423            .evaluate(
424                "(() => ({ \
425                w: Math.max(document.body.scrollWidth, document.documentElement.scrollWidth), \
426                h: Math.max(document.body.scrollHeight, document.documentElement.scrollHeight) \
427            }))()",
428            )
429            .await?;
430
431        let dims = size.result.value.as_ref();
432        let w = dims.and_then(|v| v["w"].as_i64()).unwrap_or(1920) as i32;
433        let h = dims.and_then(|v| v["h"].as_i64()).unwrap_or(1200) as i32;
434        self.set_viewport(w.max(1920), h.max(1200), false).await?;
435
436        let result = self
437            .send_command(
438                "Page.captureScreenshot",
439                json!({
440                    "format": "png",
441                    "captureBeyondViewport": true,
442                    "fromSurface": true,
443                }),
444            )
445            .await?;
446        png_bytes_from(&result)
447    }
448
449    /// [`full_page_screenshot`](Self::full_page_screenshot), written directly to `path`.
450    pub async fn full_page_screenshot_to_file(&self, path: &str) -> Result<()> {
451        tokio::fs::write(path, self.full_page_screenshot().await?).await?;
452        Ok(())
453    }
454
455    /// Override the viewport size and mobile emulation flag.
456    pub async fn set_viewport(&self, width: i32, height: i32, mobile: bool) -> Result<()> {
457        self.send_command(
458            "Emulation.setDeviceMetricsOverride",
459            json!({ "width": width, "height": height, "deviceScaleFactor": 1, "mobile": mobile }),
460        )
461        .await?;
462        Ok(())
463    }
464
465    /// List cookies visible to the current page.
466    pub async fn get_cookies(&self) -> Result<Vec<Cookie>> {
467        let result = self.send_command("Network.getCookies", json!({})).await?;
468        Ok(serde_json::from_value(result["cookies"].clone())?)
469    }
470
471    /// `GET /json/version` on Chrome's debugging HTTP endpoint.
472    pub async fn get_version(host: &str, port: u16) -> Result<BrowserVersion> {
473        let url = format!("http://{host}:{port}/json/version");
474        Ok(reqwest::get(&url).await?.json().await?)
475    }
476
477    /// `GET /json/list`: enumerate debuggable targets (tabs, workers, ...).
478    pub async fn list_targets(host: &str, port: u16) -> Result<Vec<Target>> {
479        let url = format!("http://{host}:{port}/json/list");
480        Ok(reqwest::get(&url).await?.json().await?)
481    }
482
483    /// Connect to the first target of type `"page"` reported by [`list_targets`](Self::list_targets).
484    /// Returns [`CdpError::NoTarget`] if none exists.
485    pub async fn connect_to_page(host: &str, port: u16) -> Result<Self> {
486        let targets = Self::list_targets(host, port).await?;
487        let page = targets
488            .into_iter()
489            .find(|t| t.target_type == "page")
490            .ok_or(CdpError::NoTarget)?;
491        let ws_url = page
492            .web_socket_debugger_url
493            .ok_or_else(|| CdpError::InvalidUrl("target has no debugger URL".into()))?;
494        Self::connect(&ws_url).await
495    }
496
497    /// Open a new tab, optionally navigating it to `url` immediately. Uses `PUT
498    /// /json/new` since modern Chrome rejects `GET` for this endpoint.
499    pub async fn create_tab(host: &str, port: u16, url: Option<&str>) -> Result<Target> {
500        // Chrome requires PUT for /json/new (GET returns 405 in modern versions)
501        let endpoint = match url {
502            Some(u) => format!("http://{host}:{port}/json/new?{u}"),
503            None => format!("http://{host}:{port}/json/new"),
504        };
505        Ok(reqwest::Client::new()
506            .put(&endpoint)
507            .send()
508            .await?
509            .json()
510            .await?)
511    }
512}