Skip to main content

gthings_cdp/
connection.rs

1use crate::error::{CdpError, Result};
2use futures_util::{SinkExt, StreamExt};
3use serde_json::Value;
4use std::collections::HashMap;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::time::Duration;
7use tokio::sync::{broadcast, mpsc, oneshot};
8use tokio::task::JoinHandle;
9use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};
10
11#[cfg(target_os = "macos")]
12use crate::browser::dismiss_allow_debugging_dialog;
13use tokio_tungstenite::tungstenite::Message;
14use tracing;
15
16static NEXT_CDP_ID: AtomicU64 = AtomicU64::new(1);
17
18/// A CDP event received from the browser (no "id" field, has "method" field).
19#[derive(Debug, Clone)]
20pub struct CdpEvent {
21    pub method: String,
22    pub params: Value,
23    pub session_id: Option<String>,
24}
25
26/// Internal bookkeeping for an in-flight CDP command.
27struct PendingCall {
28    method: String,
29    tx: oneshot::Sender<Result<Value>>,
30}
31
32type PendingMap = HashMap<u64, PendingCall>;
33
34/// Internal messages sent from `Connection::call` to the background I/O task.
35enum InternalMessage {
36    Call {
37        id: u64,
38        method: String,
39        params: Value,
40        session_id: Option<String>,
41        tx: oneshot::Sender<Result<Value>>,
42    },
43}
44
45/// Event-driven CDP WebSocket connection.
46///
47/// Spawns a background task that multiplexes outgoing CDP commands and
48/// incoming messages (responses → oneshot dispatch, events → broadcast).
49pub struct Connection {
50    write: mpsc::UnboundedSender<InternalMessage>,
51    events: broadcast::Sender<CdpEvent>,
52    #[allow(dead_code)]
53    handle: JoinHandle<()>,
54}
55
56impl std::fmt::Debug for Connection {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        f.debug_struct("Connection").finish_non_exhaustive()
59    }
60}
61
62impl Connection {
63    /// Connect to a CDP WebSocket endpoint.
64    pub async fn connect(ws_url: &str) -> Result<Self> {
65        // Start connecting in background
66        let ws_url_owned = ws_url.to_owned();
67        let connect_fut = tokio::spawn(async move {
68            connect_async(&ws_url_owned).await
69        });
70
71        // Wait 600ms, then dismiss the Dia dialog (if on macOS).
72        // The dialog appears during the WebSocket handshake, so we must
73        // dismiss it *while* the connection is still in progress.
74        #[cfg(target_os = "macos")]
75        {
76            tokio::time::sleep(Duration::from_millis(600)).await;
77            dismiss_allow_debugging_dialog();
78        }
79
80        // Await the connection
81        let (ws_stream, _) = connect_fut
82            .await
83            .map_err(|e| CdpError::ConnectionFailed {
84                detail: format!("task join: {e}"),
85            })?
86            .map_err(|e| CdpError::ConnectionFailed {
87                detail: format!("WebSocket connect to {ws_url} failed: {e}"),
88            })?;
89
90        let (write_tx, write_rx) = mpsc::unbounded_channel::<InternalMessage>();
91        let (events_tx, _) = broadcast::channel::<CdpEvent>(256);
92        let pending: PendingMap = HashMap::new();
93
94        let (ws_writer, ws_reader) = ws_stream.split();
95        let events_clone = events_tx.clone();
96
97        let handle = tokio::spawn(async move {
98            Self::run(write_rx, ws_writer, ws_reader, pending, events_clone).await;
99        });
100
101        Ok(Connection {
102            write: write_tx,
103            events: events_tx,
104            handle,
105        })
106    }
107
108    /// Background I/O loop: processes outgoing commands and incoming WebSocket messages.
109    async fn run(
110        mut write_rx: mpsc::UnboundedReceiver<InternalMessage>,
111        mut ws_writer: futures_util::stream::SplitSink<
112            WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>,
113            Message,
114        >,
115        mut ws_reader: futures_util::stream::SplitStream<
116            WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>,
117        >,
118        mut pending: PendingMap,
119        events: broadcast::Sender<CdpEvent>,
120    ) {
121        loop {
122            tokio::select! {
123                // Outgoing CDP commands from Connection::call
124                msg = write_rx.recv() => {
125                    match msg {
126                        Some(InternalMessage::Call { id, method, params, session_id, tx }) => {
127                            let cmd = if let Some(ref sid) = session_id {
128                                serde_json::json!({
129                                    "id": id,
130                                    "method": method,
131                                    "params": params,
132                                    "sessionId": sid,
133                                })
134                            } else {
135                                serde_json::json!({
136                                    "id": id,
137                                    "method": method,
138                                    "params": params,
139                                })
140                            };
141                            let text = match serde_json::to_string(&cmd) {
142                                Ok(t) => t,
143                                Err(e) => {
144                                    tracing::warn!("Failed to serialize CDP command: {e}");
145                                    let _ = tx.send(Err(CdpError::Json(e)));
146                                    continue;
147                                }
148                            };
149                            // Store pending before sending to avoid race
150                            pending.insert(id, PendingCall { method, tx });
151                            if let Err(e) = ws_writer.send(Message::Text(text)).await {
152                                tracing::warn!("WS send error: {e}");
153                                if let Some(pc) = pending.remove(&id) {
154                                    let _ = pc.tx.send(Err(CdpError::ConnectionFailed {
155                                        detail: format!("WebSocket send failed: {e}"),
156                                    }));
157                                }
158                                break;
159                            }
160                        }
161                        None => break,
162                    }
163                }
164                // Incoming WebSocket messages
165                msg = ws_reader.next() => {
166                    match msg {
167                        Some(Ok(Message::Text(text))) => {
168                            if let Ok(value) = serde_json::from_str::<Value>(&text) {
169                                Self::dispatch_message(value, &mut pending, &events).await;
170                            }
171                        }
172                        Some(Ok(Message::Close(frame))) => {
173                            tracing::debug!("CDP WebSocket closed: {frame:?}");
174                            break;
175                        }
176                        Some(Ok(Message::Binary(_))) => {
177                            // Binary frames not expected from CDP
178                        }
179                        Some(Err(e)) => {
180                            tracing::warn!("CDP WebSocket read error: {e}");
181                            break;
182                        }
183                        None => {
184                            tracing::debug!("CDP WebSocket stream ended");
185                            break;
186                        }
187                        _ => {}
188                    }
189                }
190            }
191        }
192
193        // Clean up all pending calls when the loop exits
194        for (_, pc) in pending.drain() {
195            let _ = pc.tx.send(Err(CdpError::ConnectionFailed {
196                detail: "WebSocket connection closed".into(),
197            }));
198        }
199    }
200
201    /// Route an incoming JSON message: either a response (has "id") or an event (has "method").
202    async fn dispatch_message(
203        value: Value,
204        pending: &mut PendingMap,
205        events: &broadcast::Sender<CdpEvent>,
206    ) {
207        if let Some(id) = value.get("id").and_then(|v| v.as_u64()) {
208            // Command response — route to the waiting oneshot
209            if let Some(pc) = pending.remove(&id) {
210                let result = if let Some(err) = value.get("error") {
211                    let detail = err
212                        .get("message")
213                        .and_then(|v| v.as_str())
214                        .unwrap_or("unknown error")
215                        .to_string();
216                    Err(CdpError::CdpCallFailed {
217                        method: pc.method,
218                        detail,
219                    })
220                } else {
221                    Ok(value.get("result").cloned().unwrap_or(Value::Null))
222                };
223                let _ = pc.tx.send(result);
224            }
225        } else if let Some(method) = value.get("method").and_then(|v| v.as_str()) {
226            // CDP event — broadcast to subscribers
227            let session_id = value
228                .get("sessionId")
229                .and_then(|v| v.as_str())
230                .map(String::from);
231            let evt = CdpEvent {
232                method: method.to_string(),
233                params: value.get("params").cloned().unwrap_or(Value::Null),
234                session_id,
235            };
236            let _ = events.send(evt);
237        }
238    }
239
240    /// Send a CDP command and wait for the response.
241    ///
242    /// If `session_id` is `Some`, the command is sent as a Target-scoped message;
243    /// if `None`, it is sent as a Browser-level message.
244    pub async fn call(
245        &self,
246        method: &str,
247        params: Value,
248        session_id: Option<&str>,
249    ) -> Result<Value> {
250        let id = NEXT_CDP_ID.fetch_add(1, Ordering::Relaxed);
251        let (tx, rx) = oneshot::channel();
252
253        let msg = InternalMessage::Call {
254            id,
255            method: method.to_string(),
256            params,
257            session_id: session_id.map(String::from),
258            tx,
259        };
260
261        self.write.send(msg).map_err(|_| CdpError::ConnectionFailed {
262            detail: "background I/O task has terminated".into(),
263        })?;
264
265        tokio::time::timeout(Duration::from_secs(30), rx)
266            .await
267            .map_err(|_| CdpError::CdpCallFailed {
268                method: method.to_string(),
269                detail: "timeout waiting for response".into(),
270            })? // -> Result<Result<Value, CdpError>, RecvError>
271            .map_err(|_| CdpError::CdpCallFailed {
272                method: method.to_string(),
273                detail: "oneshot channel closed".into(),
274            })? // -> Result<Value, CdpError>
275    }
276
277    /// Subscribe to all CDP events broadcast from the browser.
278    pub fn event_rx(&self) -> broadcast::Receiver<CdpEvent> {
279        self.events.subscribe()
280    }
281
282    /// Disconnect cleanly. Closes the command channel and waits for the
283    /// background I/O task to finish.
284    pub async fn close(self) {
285        let Self {
286            write,
287            events: _,
288            handle,
289        } = self;
290        drop(write); // Signals the background loop to exit
291        let _ = handle.await;
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use serde_json::json;
298
299    #[test]
300    fn test_cdp_response_parsing() {
301        let response = json!({"id": 1, "result": {"value": "hello"}});
302        assert_eq!(response["id"].as_u64(), Some(1));
303        assert!(response.get("error").is_none());
304        assert_eq!(response["result"]["value"].as_str(), Some("hello"));
305    }
306
307    #[test]
308    fn test_cdp_error_response() {
309        let response =
310            json!({"id": 2, "error": {"code": -32000, "message": "Cannot find context"}});
311        assert!(response.get("error").is_some());
312        assert_eq!(
313            response["error"]["message"].as_str(),
314            Some("Cannot find context")
315        );
316    }
317
318    #[test]
319    fn test_cdp_event_has_no_id() {
320        let event = json!({"method": "Page.frameStartedLoading", "params": {"frameId": "123"}});
321        assert!(event.get("id").is_none());
322        assert!(event.get("method").is_some());
323        assert!(event.get("params").is_some());
324    }
325
326    #[test]
327    fn test_cdp_event_with_session_id() {
328        let event = json!({
329            "method": "Runtime.consoleAPICalled",
330            "params": {},
331            "sessionId": "session-123"
332        });
333        assert!(event.get("id").is_none());
334        assert_eq!(event["sessionId"].as_str(), Some("session-123"));
335    }
336}