Skip to main content

nexo_cdp/
client.rs

1use std::sync::atomic::{AtomicU64, Ordering};
2use std::sync::Arc;
3use std::time::Duration;
4
5use anyhow::anyhow;
6use dashmap::DashMap;
7use futures::{SinkExt, StreamExt};
8use serde_json::{json, Value};
9use tokio::sync::{broadcast, mpsc, oneshot};
10use tokio_tungstenite::connect_async;
11use tokio_tungstenite::tungstenite::Message;
12use tokio_util::sync::CancellationToken;
13
14struct CdpRequest {
15    id: u64,
16    method: String,
17    params: Value,
18    session_id: Option<String>,
19}
20
21/// A CDP notification (no `id` field) received from Chrome.
22/// Forwarded via a broadcast channel so multiple subscribers can observe it.
23#[derive(Debug, Clone)]
24pub struct CdpEvent {
25    pub method: String,
26    pub params: Value,
27    pub session_id: Option<String>,
28}
29
30type PendingMap = Arc<DashMap<u64, oneshot::Sender<anyhow::Result<Value>>>>;
31
32#[derive(Clone)]
33pub struct CdpClient {
34    tx: mpsc::Sender<CdpRequest>,
35    pending: PendingMap,
36    events: broadcast::Sender<CdpEvent>,
37    next_id: Arc<AtomicU64>,
38    shutdown: CancellationToken,
39}
40
41impl CdpClient {
42    /// Connect to a raw CDP WebSocket URL (ws://...).
43    pub async fn connect(ws_url: &str) -> anyhow::Result<Self> {
44        let (ws_stream, _) = connect_async(ws_url)
45            .await
46            .map_err(|e| anyhow!("CDP WebSocket connect failed: {e}"))?;
47
48        let (mut sink, mut stream) = ws_stream.split();
49        let (tx, mut rx) = mpsc::channel::<CdpRequest>(64);
50        let pending: PendingMap = Arc::new(DashMap::new());
51        let (events_tx, _) = broadcast::channel::<CdpEvent>(256);
52        let shutdown = CancellationToken::new();
53
54        // Writer task
55        let pending_w = Arc::clone(&pending);
56        let shutdown_w = shutdown.clone();
57        tokio::spawn(async move {
58            loop {
59                tokio::select! {
60                    req = rx.recv() => {
61                        let Some(req) = req else { break };
62                        let mut msg = json!({
63                            "id": req.id,
64                            "method": req.method,
65                            "params": req.params,
66                        });
67                        if let Some(sid) = req.session_id {
68                            msg["sessionId"] = json!(sid);
69                        }
70                        if sink.send(Message::Text(msg.to_string())).await.is_err() {
71                            // Socket is gone — fail every caller waiting
72                            // on a response so they unblock immediately
73                            // rather than sitting until their timeout.
74                            // (The earlier iter/retain no-ops here were
75                            // unused drafts — removed.)
76                            let ids: Vec<u64> = pending_w.iter().map(|e| *e.key()).collect();
77                            for id in ids {
78                                if let Some((_, sender)) = pending_w.remove(&id) {
79                                    let _ = sender.send(Err(anyhow!("CDP connection lost")));
80                                }
81                            }
82                            break;
83                        }
84                    }
85                    _ = shutdown_w.cancelled() => {
86                        let _ = sink.close().await;
87                        break;
88                    }
89                }
90            }
91        });
92
93        // Reader task
94        let pending_r = Arc::clone(&pending);
95        let events_r = events_tx.clone();
96        let shutdown_r = shutdown.clone();
97        tokio::spawn(async move {
98            loop {
99                tokio::select! {
100                    msg = stream.next() => {
101                        let Some(Ok(msg)) = msg else {
102                            // Reject all pending on disconnect
103                            let ids: Vec<u64> = pending_r.iter().map(|e| *e.key()).collect();
104                            for id in ids {
105                                if let Some((_, s)) = pending_r.remove(&id) {
106                                    let _ = s.send(Err(anyhow!("CDP socket closed")));
107                                }
108                            }
109                            break;
110                        };
111                        let text = match msg {
112                            Message::Text(t) => t.to_string(),
113                            Message::Binary(b) => String::from_utf8_lossy(&b).to_string(),
114                            Message::Close(_) => {
115                                let ids: Vec<u64> = pending_r.iter().map(|e| *e.key()).collect();
116                                for id in ids {
117                                    if let Some((_, s)) = pending_r.remove(&id) {
118                                        let _ = s.send(Err(anyhow!("CDP socket closed")));
119                                    }
120                                }
121                                break;
122                            }
123                            _ => continue,
124                        };
125                        let Ok(parsed) = serde_json::from_str::<Value>(&text) else { continue };
126
127                        // Messages with an `id` are responses to requests.
128                        if let Some(id) = parsed.get("id").and_then(|v| v.as_u64()) {
129                            let Some((_, sender)) = pending_r.remove(&id) else { continue };
130                            if let Some(err) = parsed.get("error") {
131                                let msg = err.get("message")
132                                    .and_then(|m| m.as_str())
133                                    .unwrap_or("CDP error");
134                                let _ = sender.send(Err(anyhow!("{msg}")));
135                            } else {
136                                let result = parsed.get("result").cloned().unwrap_or(Value::Null);
137                                let _ = sender.send(Ok(result));
138                            }
139                            continue;
140                        }
141
142                        // Otherwise it's an event notification (no `id`, has `method`).
143                        if let Some(method) = parsed.get("method").and_then(|v| v.as_str()) {
144                            let params = parsed.get("params").cloned().unwrap_or(Value::Null);
145                            let session_id = parsed
146                                .get("sessionId")
147                                .and_then(|v| v.as_str())
148                                .map(|s| s.to_string());
149                            // Ignore send errors — no subscribers is fine.
150                            let _ = events_r.send(CdpEvent {
151                                method: method.to_string(),
152                                params,
153                                session_id,
154                            });
155                        }
156                    }
157                    _ = shutdown_r.cancelled() => break,
158                }
159            }
160        });
161
162        Ok(Self {
163            tx,
164            pending,
165            events: events_tx,
166            next_id: Arc::new(AtomicU64::new(1)),
167            shutdown,
168        })
169    }
170
171    /// Subscribe to every CDP event. Caller filters by `method` / `session_id`.
172    pub fn subscribe_events(&self) -> broadcast::Receiver<CdpEvent> {
173        self.events.subscribe()
174    }
175
176    /// Subscribe to events scoped to a specific `session_id`. Events for other
177    /// sessions are discarded by a filter task to keep the receiver simple.
178    pub fn subscribe_session_events(&self, session_id: &str) -> broadcast::Receiver<CdpEvent> {
179        let session_id = session_id.to_string();
180        let mut upstream = self.events.subscribe();
181        let (downstream_tx, downstream_rx) = broadcast::channel::<CdpEvent>(64);
182        let shutdown = self.shutdown.clone();
183        tokio::spawn(async move {
184            loop {
185                tokio::select! {
186                    // Respect client shutdown so these filter tasks
187                    // don't outlive the CdpClient and leak into the
188                    // runtime when many sessions come and go.
189                    _ = shutdown.cancelled() => break,
190                    recv = upstream.recv() => match recv {
191                        Ok(ev) if ev.session_id.as_deref() == Some(&session_id) => {
192                            if downstream_tx.send(ev).is_err() {
193                                break; // no subscribers left
194                            }
195                        }
196                        Ok(_) => continue,
197                        Err(broadcast::error::RecvError::Lagged(_)) => continue,
198                        Err(broadcast::error::RecvError::Closed) => break,
199                    }
200                }
201            }
202        });
203        downstream_rx
204    }
205
206    /// Discover WS URL from a CDP HTTP endpoint (http://127.0.0.1:9222).
207    pub async fn discover_ws_url(http_url: &str, timeout_ms: u64) -> anyhow::Result<String> {
208        let client = reqwest::Client::builder()
209            .timeout(Duration::from_millis(timeout_ms))
210            .build()?;
211        let url = format!("{}/json/version", http_url.trim_end_matches('/'));
212        // Chrome DevTools HTTP endpoint requires Host: localhost.
213        let resp: Value = client
214            .get(&url)
215            .header(reqwest::header::HOST, "localhost")
216            .send()
217            .await?
218            .json()
219            .await?;
220        let ws = resp
221            .get("webSocketDebuggerUrl")
222            .and_then(|v| v.as_str())
223            .ok_or_else(|| anyhow!("no webSocketDebuggerUrl in /json/version response"))?;
224        // Chrome echoes the Host header back in webSocketDebuggerUrl (e.g. ws://localhost/...),
225        // which loses the real port. Rewrite authority to match the cdp_url we were given.
226        Ok(rewrite_ws_authority(ws, http_url))
227    }
228
229    pub async fn send(&self, method: &str, params: Value) -> anyhow::Result<Value> {
230        self.send_with_session(method, params, None).await
231    }
232
233    /// Default per-call timeout. Covers most CDP roundtrips (navigate,
234    /// querySelector, eval). Long-running operations should use
235    /// `send_with_timeout` explicitly.
236    const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
237
238    pub async fn send_with_session(
239        &self,
240        method: &str,
241        params: Value,
242        session_id: Option<String>,
243    ) -> anyhow::Result<Value> {
244        self.send_with_timeout(method, params, session_id, Self::DEFAULT_TIMEOUT)
245            .await
246    }
247
248    /// Like `send_with_session` but with a caller-specified timeout.
249    /// Without an upper bound a CDP request waiting on a crashed tab
250    /// would hang forever — every other client in this workspace caps
251    /// its waits, so browser gets the same treatment.
252    pub async fn send_with_timeout(
253        &self,
254        method: &str,
255        params: Value,
256        session_id: Option<String>,
257        timeout: Duration,
258    ) -> anyhow::Result<Value> {
259        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
260        let (tx, rx) = oneshot::channel();
261        self.pending.insert(id, tx);
262
263        if self
264            .tx
265            .send(CdpRequest {
266                id,
267                method: method.to_string(),
268                params,
269                session_id,
270            })
271            .await
272            .is_err()
273        {
274            // Writer gone — reclaim the slot so a late drain doesn't
275            // double-fire, then surface a clean error.
276            self.pending.remove(&id);
277            return Err(anyhow!("CDP client channel closed"));
278        }
279
280        match tokio::time::timeout(timeout, rx).await {
281            Ok(Ok(result)) => result,
282            Ok(Err(_)) => Err(anyhow!("CDP response channel dropped")),
283            Err(_) => {
284                // Timed out — remove the pending slot so a late
285                // response doesn't find (and try to use) a stale
286                // sender that's already dropped. Caller sees a clean
287                // timeout error identical in shape to the other
288                // clients in the workspace.
289                self.pending.remove(&id);
290                Err(anyhow!(
291                    "CDP request `{method}` timed out after {}ms",
292                    timeout.as_millis()
293                ))
294            }
295        }
296    }
297
298    pub fn close(&self) {
299        self.shutdown.cancel();
300    }
301}
302
303impl Drop for CdpClient {
304    fn drop(&mut self) {
305        self.shutdown.cancel();
306    }
307}
308
309// Re-export reqwest for use inside the crate
310use reqwest;
311
312/// Replace the authority (host:port) of a ws:// or wss:// URL with the authority
313/// from an http:// or https:// base. Preserves scheme and path of the WS URL.
314/// Chrome returns webSocketDebuggerUrl echoing the Host header, which drops the
315/// real port when Host was spoofed — this rewrites it back to the reachable endpoint.
316fn rewrite_ws_authority(ws_url: &str, http_base: &str) -> String {
317    let authority = http_base
318        .trim_end_matches('/')
319        .trim_start_matches("https://")
320        .trim_start_matches("http://");
321    let (ws_scheme, rest) = if let Some(r) = ws_url.strip_prefix("ws://") {
322        ("ws://", r)
323    } else if let Some(r) = ws_url.strip_prefix("wss://") {
324        ("wss://", r)
325    } else {
326        return ws_url.to_string();
327    };
328    let path = rest.find('/').map(|i| &rest[i..]).unwrap_or("");
329    format!("{ws_scheme}{authority}{path}")
330}
331
332#[cfg(test)]
333mod tests {
334    use super::rewrite_ws_authority;
335
336    #[test]
337    fn rewrites_host_and_port() {
338        let out = rewrite_ws_authority("ws://localhost/devtools/browser/abc", "http://chrome:9222");
339        assert_eq!(out, "ws://chrome:9222/devtools/browser/abc");
340    }
341
342    #[test]
343    fn preserves_existing_port() {
344        let out = rewrite_ws_authority(
345            "ws://localhost:1234/devtools/browser/xyz",
346            "http://127.0.0.1:9222/",
347        );
348        assert_eq!(out, "ws://127.0.0.1:9222/devtools/browser/xyz");
349    }
350
351    #[test]
352    fn handles_wss() {
353        let out = rewrite_ws_authority(
354            "wss://localhost/devtools/page/1",
355            "https://remote.example:443",
356        );
357        assert_eq!(out, "wss://remote.example:443/devtools/page/1");
358    }
359
360    #[tokio::test]
361    async fn send_with_timeout_reports_timeout_cleanly() {
362        // Drive the client without a real Chrome: stub a writer task
363        // that silently eats requests and never replies. `send_with_
364        // timeout` must return an Err that mentions "timed out" (and
365        // not hang the test runner).
366        use super::CdpClient;
367        use dashmap::DashMap;
368        use std::sync::atomic::AtomicU64;
369        use std::sync::Arc as StdArc;
370        use tokio::sync::{broadcast, mpsc};
371        use tokio_util::sync::CancellationToken;
372
373        let (tx, mut rx) = mpsc::channel::<super::CdpRequest>(8);
374        let (events_tx, _) = broadcast::channel(4);
375        let shutdown = CancellationToken::new();
376        let shutdown_c = shutdown.clone();
377        tokio::spawn(async move {
378            tokio::select! {
379                _ = shutdown_c.cancelled() => {}
380                _ = async { while let Some(_req) = rx.recv().await {} } => {}
381            }
382        });
383        // Reconstruct a private-like CdpClient via the same fields.
384        // We can't use CdpClient::connect without a server, so the
385        // struct has to be buildable here. It is — all fields are
386        // internal and this test lives in the same module.
387        let client = CdpClient {
388            tx,
389            pending: StdArc::new(DashMap::new()),
390            events: events_tx,
391            next_id: StdArc::new(AtomicU64::new(1)),
392            shutdown,
393        };
394        let err = client
395            .send_with_timeout(
396                "Test.hang",
397                serde_json::json!({}),
398                None,
399                std::time::Duration::from_millis(50),
400            )
401            .await
402            .unwrap_err();
403        let s = err.to_string();
404        assert!(
405            s.contains("timed out"),
406            "error must mention timeout; got: {s}"
407        );
408        // Pending entry must be removed — a late response arriving now
409        // shouldn't find a sender waiting, otherwise we'd leak.
410        assert!(client.pending.is_empty(), "pending slot must be reclaimed");
411    }
412}