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::Arc;
9use std::sync::atomic::{AtomicU64, Ordering};
10use std::time::Duration;
11
12use futures_util::{Sink, Stream};
13use futures_util::{SinkExt, StreamExt};
14use serde::Serialize;
15use serde::de::DeserializeOwned;
16use serde_json::{Value, json};
17use tokio::sync::{Mutex, broadcast, mpsc, oneshot};
18use tokio_tungstenite::connect_async;
19use tokio_tungstenite::tungstenite::{Error as WsError, Message};
20use tracing::{debug, warn};
21
22use crate::error::{CdpError, Result};
23use crate::session::SessionEvent;
24
25/// Default per-command timeout, in milliseconds. Override with
26/// [`CdpClient::set_command_timeout`]. A value of `0` disables the timeout.
27const DEFAULT_COMMAND_TIMEOUT_MS: u64 = 30_000;
28
29/// How many events may queue for a subscriber before the oldest are dropped.
30const EVENT_BACKLOG: usize = 256;
31
32/// What every in-flight command is told when the socket goes away.
33const CONNECTION_CLOSED: &str = "connection closed";
34
35/// Stands in for the `code` of an error frame that carries none. CDP never uses
36/// zero itself, so it cannot be mistaken for a code Chrome actually reported.
37const UNREPORTED_ERROR_CODE: i64 = 0;
38
39/// What an error frame with no message of its own is called.
40const UNDESCRIBED_ERROR: &str = "protocol error";
41
42type PendingMap = Arc<Mutex<HashMap<u64, oneshot::Sender<Result<Value>>>>>;
43
44type Events = broadcast::Sender<(String, Value)>;
45
46type SessionEvents = broadcast::Sender<SessionEvent>;
47
48/// Build the frame one command goes out as. A command addressed to an attached
49/// session carries its `sessionId` beside `id`, never inside `params`; a command
50/// for the target this client connected to carries no `sessionId` at all.
51fn outgoing(id: u64, session_id: Option<&str>, method: &str, params: Value) -> Value {
52    let mut frame = json!({ "id": id, "method": method, "params": params });
53    if let Some(session_id) = session_id {
54        frame["sessionId"] = json!(session_id);
55    }
56    frame
57}
58
59/// Read the error object Chrome answers a rejected command with. Only `message`
60/// is reliably present, so a frame carrying less still has to yield an error a
61/// caller can match on.
62fn browser_error_in(error: &Value) -> CdpError {
63    CdpError::Browser {
64        code: error["code"].as_i64().unwrap_or(UNREPORTED_ERROR_CODE),
65        message: error["message"]
66            .as_str()
67            .unwrap_or(UNDESCRIBED_ERROR)
68            .to_string(),
69        data: match &error["data"] {
70            Value::Null => None,
71            Value::String(detail) => Some(detail.clone()),
72            detail => Some(detail.to_string()),
73        },
74    }
75}
76
77/// The reply a command frame carries: its result, or the error it reports.
78fn reply_in(frame: &Value, id: u64) -> Result<Value> {
79    let Some(error) = frame.get("error") else {
80        debug!(id, "recv");
81        return Ok(frame.get("result").cloned().unwrap_or(Value::Null));
82    };
83    let rejection = browser_error_in(error);
84    warn!(id, %rejection, "protocol error");
85    Err(rejection)
86}
87
88/// Hand a reply to whoever is waiting on `id`, if anyone still is. Nobody is
89/// waiting once a command has timed out, and that is not an error.
90async fn deliver(pending: &PendingMap, id: u64, reply: Result<Value>) {
91    if let Some(waiting) = pending.lock().await.remove(&id) {
92        let _ = waiting.send(reply);
93    }
94}
95
96/// Publish an unsolicited frame to event subscribers.
97///
98/// Session-aware subscribers see every event with the session it came from.
99/// [`CdpClient::subscribe_events`] sees only the events of the target this client
100/// connected to: it has no way to report a session, and a waiter there watching
101/// for `Page.loadEventFired` must not be woken by some attached tab's load.
102fn publish(events: &Events, session_events: &SessionEvents, frame: &Value) {
103    let Some(method) = frame.get("method").and_then(Value::as_str) else {
104        return;
105    };
106    let session_id = frame.get("sessionId").and_then(Value::as_str);
107    debug!(%method, "event");
108    let params = frame.get("params").cloned().unwrap_or(Value::Null);
109
110    let _ = session_events.send(SessionEvent {
111        session_id: session_id.map(str::to_owned),
112        method: method.to_owned(),
113        params: params.clone(),
114    });
115    if session_id.is_none() {
116        let _ = events.send((method.to_owned(), params));
117    }
118}
119
120/// Route one text frame. A frame carrying an `id` answers a command; anything
121/// else is an event. Frames that are not JSON at all are dropped.
122///
123/// Ids are unique across the whole connection, sessions included, so a reply is
124/// matched by id alone and the `sessionId` it echoes needs no attention here.
125async fn route(text: &str, pending: &PendingMap, events: &Events, session_events: &SessionEvents) {
126    let Ok(frame) = serde_json::from_str::<Value>(text) else {
127        return;
128    };
129    match frame.get("id").and_then(Value::as_u64) {
130        Some(id) => deliver(pending, id, reply_in(&frame, id)).await,
131        None => publish(events, session_events, &frame),
132    }
133}
134
135/// Fail every command still awaiting a reply.
136async fn abandon_pending(pending: &PendingMap) {
137    for (_, waiting) in pending.lock().await.drain() {
138        let _ = waiting.send(Err(CdpError::Protocol(CONNECTION_CLOSED.into())));
139    }
140}
141
142/// Forward queued commands to the socket until the client is dropped or the
143/// socket refuses them.
144async fn write_outgoing<S>(mut sink: S, mut outgoing: mpsc::UnboundedReceiver<Message>)
145where
146    S: Sink<Message> + Unpin,
147{
148    while let Some(message) = outgoing.recv().await {
149        if sink.send(message).await.is_err() {
150            break;
151        }
152    }
153}
154
155/// Demultiplex the socket for the client's lifetime, sending replies to their
156/// callers and events to subscribers.
157///
158/// However the stream ends, whether closed cleanly, failed, or simply exhausted,
159/// the commands still in flight are failed rather than left to time out.
160async fn read_incoming<S>(
161    mut stream: S,
162    pending: PendingMap,
163    events: Events,
164    session_events: SessionEvents,
165) where
166    S: Stream<Item = std::result::Result<Message, WsError>> + Unpin,
167{
168    while let Some(message) = stream.next().await {
169        match message {
170            Ok(Message::Text(text)) => route(&text, &pending, &events, &session_events).await,
171            Ok(Message::Close(_)) | Err(_) => break,
172            _ => {}
173        }
174    }
175    abandon_pending(&pending).await;
176}
177
178/// A single WebSocket session to one Chrome debugging target.
179///
180/// Cloning is not supported; share a client across tasks with `Arc<CdpClient>`
181/// (see [`Cluster`](crate::cluster::Cluster) for an example). Every command sent
182/// concurrently gets its own response future, matched by CDP message id.
183pub struct CdpClient {
184    tx: tokio::sync::mpsc::UnboundedSender<Message>,
185    pending: PendingMap,
186    next_id: Arc<AtomicU64>,
187    events_tx: broadcast::Sender<(String, Value)>,
188    session_events_tx: SessionEvents,
189    command_timeout_ms: Arc<AtomicU64>,
190}
191
192impl CdpClient {
193    /// Open a CDP WebSocket session at `ws_url` (a target's `webSocketDebuggerUrl`).
194    ///
195    /// Spawns background tasks that pump outgoing commands and demultiplex incoming
196    /// replies/events for the lifetime of the returned client.
197    pub async fn connect(ws_url: &str) -> Result<Self> {
198        debug!(%ws_url, "connecting");
199        let (ws_stream, _) = connect_async(ws_url).await?;
200        let (sink, stream) = ws_stream.split();
201
202        let pending: PendingMap = Arc::new(Mutex::new(HashMap::new()));
203        let (events_tx, _) = broadcast::channel::<(String, Value)>(EVENT_BACKLOG);
204        let (session_events_tx, _) = broadcast::channel::<SessionEvent>(EVENT_BACKLOG);
205        let (tx, outgoing) = mpsc::unbounded_channel::<Message>();
206
207        tokio::spawn(write_outgoing(sink, outgoing));
208        tokio::spawn(read_incoming(
209            stream,
210            pending.clone(),
211            events_tx.clone(),
212            session_events_tx.clone(),
213        ));
214
215        Ok(CdpClient {
216            tx,
217            pending,
218            next_id: Arc::new(AtomicU64::new(1)),
219            events_tx,
220            session_events_tx,
221            command_timeout_ms: Arc::new(AtomicU64::new(DEFAULT_COMMAND_TIMEOUT_MS)),
222        })
223    }
224
225    /// Set the per-command timeout applied to every CDP command this client sends.
226    /// Passing a zero duration disables the timeout (commands wait indefinitely).
227    pub fn set_command_timeout(&self, timeout: Duration) {
228        let ms = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX);
229        self.command_timeout_ms.store(ms, Ordering::Relaxed);
230    }
231
232    /// The current per-command timeout.
233    pub fn command_timeout(&self) -> Duration {
234        Duration::from_millis(self.command_timeout_ms.load(Ordering::Relaxed))
235    }
236
237    /// Send one command, optionally addressed to an attached session, and wait for
238    /// the reply the browser matches to it by id.
239    pub(crate) async fn send_command_on(
240        &self,
241        session_id: Option<&str>,
242        method: &str,
243        params: Value,
244    ) -> Result<Value> {
245        let id = self.next_id.fetch_add(1, Ordering::SeqCst);
246        debug!(%method, id, "send");
247        let (tx, rx) = oneshot::channel();
248
249        self.pending.lock().await.insert(id, tx);
250
251        if let Err(e) = self.tx.send(Message::Text(
252            outgoing(id, session_id, method, params).to_string().into(),
253        )) {
254            // Writer task is gone; don't leave a dangling entry in `pending`.
255            self.pending.lock().await.remove(&id);
256            return Err(CdpError::Protocol(e.to_string()));
257        }
258
259        let closed = || CdpError::Protocol("response channel closed".into());
260
261        let timeout_ms = self.command_timeout_ms.load(Ordering::Relaxed);
262        if timeout_ms == 0 {
263            return match rx.await {
264                Ok(outcome) => outcome,
265                Err(_) => Err(closed()),
266            };
267        }
268
269        match tokio::time::timeout(Duration::from_millis(timeout_ms), rx).await {
270            Ok(Ok(outcome)) => outcome,
271            Ok(Err(_)) => Err(closed()),
272            Err(_) => {
273                // Timed out waiting for a reply: drop the pending sender so the
274                // map doesn't grow unbounded for commands the browser never answers.
275                self.pending.lock().await.remove(&id);
276                Err(CdpError::Timeout)
277            }
278        }
279    }
280
281    pub(crate) async fn send_command(&self, method: &str, params: Value) -> Result<Value> {
282        self.send_command_on(None, method, params).await
283    }
284
285    /// Send any CDP command and deserialize its result into `R`.
286    ///
287    /// The typed wrappers on this client cover only a small, curated slice of the
288    /// DevTools Protocol; this is the escape hatch for everything else, including
289    /// domains this crate has no wrappers for at all (`Target`, `Storage`,
290    /// `Debugger`, ...). `params` must serialize to a JSON object, since that is
291    /// what CDP expects; use `json!({})` for commands that take no parameters.
292    ///
293    /// ```no_run
294    /// # use cdp_driver::CdpClient;
295    /// # use serde::Deserialize;
296    /// # use serde_json::json;
297    /// #[derive(Deserialize)]
298    /// #[serde(rename_all = "camelCase")]
299    /// struct CreateTarget {
300    ///     target_id: String,
301    /// }
302    ///
303    /// # async fn run(client: &CdpClient) -> cdp_driver::Result<()> {
304    /// let created: CreateTarget = client
305    ///     .call("Target.createTarget", json!({ "url": "about:blank" }))
306    ///     .await?;
307    /// # Ok(())
308    /// # }
309    /// ```
310    pub async fn call<P: Serialize, R: DeserializeOwned>(
311        &self,
312        method: &str,
313        params: P,
314    ) -> Result<R> {
315        let result = self.call_raw(method, serde_json::to_value(params)?).await?;
316        Ok(serde_json::from_value(result)?)
317    }
318
319    /// Send any CDP command and return its raw `result` object unparsed.
320    ///
321    /// Prefer [`call`](Self::call) when you have a type to deserialize into. This is
322    /// the lower-level form, useful for exploring a response's shape or for commands
323    /// whose result you only want to index into. Commands that return no result
324    /// yield [`Value::Null`].
325    pub async fn call_raw(&self, method: &str, params: Value) -> Result<Value> {
326        self.send_command(method, params).await
327    }
328
329    /// Subscribe to raw CDP events as `(method, params)` pairs.
330    ///
331    /// Only events for domains enabled via [`enable_domain`](Self::enable_domain)
332    /// are emitted. Lagging receivers silently drop the oldest events rather than
333    /// blocking the connection.
334    ///
335    /// These are the events of the target this client connected to. Events raised
336    /// by an attached session ([`attach_to_target`](Self::attach_to_target)) do not
337    /// appear here, because a `(method, params)` pair cannot say which target it
338    /// came from; use [`subscribe_session_events`](Self::subscribe_session_events)
339    /// to see those.
340    pub fn subscribe_events(&self) -> broadcast::Receiver<(String, Value)> {
341        self.events_tx.subscribe()
342    }
343
344    /// Subscribe to every CDP event on this connection, each tagged with the
345    /// session it came from ([`SessionEvent::session_id`] is `None` for the target
346    /// this client connected to directly).
347    pub fn subscribe_session_events(&self) -> broadcast::Receiver<SessionEvent> {
348        self.session_events_tx.subscribe()
349    }
350
351    /// Wait for the next event named `method`, up to `timeout_ms` milliseconds.
352    pub async fn wait_for_event(&self, method: &str, timeout_ms: u64) -> Result<Value> {
353        let mut rx = self.events_tx.subscribe();
354        tokio::time::timeout(std::time::Duration::from_millis(timeout_ms), async move {
355            loop {
356                match rx.recv().await {
357                    Ok((m, params)) if m == method => return Ok(params),
358                    Ok(_) => continue,
359                    Err(broadcast::error::RecvError::Lagged(_)) => continue,
360                    Err(_) => return Err(CdpError::Protocol("event channel closed".into())),
361                }
362            }
363        })
364        .await
365        .map_err(|_| CdpError::Timeout)?
366    }
367
368    /// Enable a CDP domain (e.g. `"Page"`, `"Runtime"`, `"Network"`), required before
369    /// that domain's events start flowing or some of its commands work.
370    pub async fn enable_domain(&self, domain: &str) -> Result<()> {
371        self.send_command(&format!("{domain}.enable"), json!({}))
372            .await?;
373        Ok(())
374    }
375
376    /// Close the tab this client is attached to.
377    pub async fn close(&self) -> Result<()> {
378        // Ignore errors, connection drops immediately after the tab closes
379        let _ = self.send_command("Page.close", json!({})).await;
380        Ok(())
381    }
382}