1use 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
26const DEFAULT_COMMAND_TIMEOUT_MS: u64 = 30_000;
29
30const EVENT_BACKLOG: usize = 256;
32
33const CONNECTION_CLOSED: &str = "connection closed";
35
36type PendingMap = Arc<Mutex<HashMap<u64, oneshot::Sender<Result<Value>>>>>;
37
38type Events = broadcast::Sender<(String, Value)>;
39
40fn 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
50fn 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
64async 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
72fn 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
82async 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
94async 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
101async 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
114async 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
133pub 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 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 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 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 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 self.pending.lock().await.remove(&id);
218 Err(CdpError::Timeout)
219 }
220 }
221 }
222
223 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 pub async fn call_raw(&self, method: &str, params: Value) -> Result<Value> {
264 self.send_command(method, params).await
265 }
266
267 pub fn subscribe_events(&self) -> broadcast::Receiver<(String, Value)> {
273 self.events_tx.subscribe()
274 }
275
276 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 pub async fn enable_domain(&self, domain: &str) -> Result<()> {
296 self.send_command(&format!("{domain}.enable"), json!({}))
297 .await?;
298 Ok(())
299 }
300
301 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 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 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 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 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 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 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 pub async fn close(&self) -> Result<()> {
397 let _ = self.send_command("Page.close", json!({})).await;
399 Ok(())
400 }
401
402 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 pub async fn screenshot_to_file(&self, path: &str) -> Result<()> {
415 tokio::fs::write(path, self.screenshot().await?).await?;
416 Ok(())
417 }
418
419 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 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 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 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 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 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 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 pub async fn create_tab(host: &str, port: u16, url: Option<&str>) -> Result<Target> {
500 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}