Skip to main content

cdp_driver/
session.rs

1//! Flat CDP sessions: addressing commands and attributing events to a target
2//! other than the one the connection was opened to.
3//!
4//! Attaching to a target yields a session id. A command carrying that id beside
5//! its `id` runs in that target, and an event raised there comes back carrying it
6//! too. Everything rides the one WebSocket [`CdpClient`] already owns, so an
7//! out-of-process iframe, a service worker, or a second tab is reachable without
8//! a second connection.
9
10use serde::de::DeserializeOwned;
11use serde::{Deserialize, Serialize};
12use serde_json::{Value, json};
13use tokio::sync::broadcast;
14
15use crate::client::CdpClient;
16use crate::error::{CdpError, Result};
17use crate::methods::target::{ATTACH_TO_TARGET, DETACH_FROM_TARGET};
18
19/// Ask for sessions multiplexed onto the connection we already have. The other
20/// arrangement, tunnelling each frame through `Target.sendMessageToTarget`, is
21/// deprecated in CDP and is deliberately not implemented here.
22const FLAT_SESSIONS: bool = true;
23
24/// One CDP event, and which target raised it.
25#[derive(Debug, Clone)]
26pub struct SessionEvent {
27    /// The session the event came from, or `None` for the target the client is
28    /// connected to directly.
29    pub session_id: Option<String>,
30    /// The CDP event name, e.g. `"Page.loadEventFired"`.
31    pub method: String,
32    /// The event's parameters, or [`Value::Null`] for an event that carries none.
33    pub params: Value,
34}
35
36/// What `Target.attachToTarget` answers with.
37#[derive(Debug, Deserialize)]
38#[serde(rename_all = "camelCase")]
39struct Attached {
40    session_id: String,
41}
42
43/// A handle for driving one attached target over the client's connection.
44///
45/// Borrowed from the client on purpose: a session cannot outlive the connection
46/// it is multiplexed onto. To hold one past that borrow, keep the session id and
47/// rebuild the handle with [`CdpClient::session`].
48pub struct CdpSession<'a> {
49    client: &'a CdpClient,
50    session_id: String,
51}
52
53impl<'a> CdpSession<'a> {
54    /// The session id CDP assigned when the target was attached.
55    pub fn id(&self) -> &str {
56        &self.session_id
57    }
58
59    /// Send any CDP command in this session and return its raw `result` object.
60    ///
61    /// The counterpart of [`CdpClient::call_raw`], differing only in that the
62    /// command is addressed to this session rather than to the connected target.
63    pub async fn call_raw(&self, method: &str, params: Value) -> Result<Value> {
64        self.client
65            .send_command_on(Some(&self.session_id), method, params)
66            .await
67    }
68
69    /// Send any CDP command in this session and deserialize its result into `R`.
70    ///
71    /// ```no_run
72    /// # use cdp_driver::CdpClient;
73    /// # use serde_json::{json, Value};
74    /// # async fn run(client: &CdpClient) -> cdp_driver::Result<()> {
75    /// let session = client.attach_to_target("A1B2C3").await?;
76    /// let _: Value = session
77    ///     .call("Page.navigate", json!({ "url": "https://example.com" }))
78    ///     .await?;
79    /// # Ok(())
80    /// # }
81    /// ```
82    pub async fn call<P: Serialize, R: DeserializeOwned>(
83        &self,
84        method: &str,
85        params: P,
86    ) -> Result<R> {
87        let result = self.call_raw(method, serde_json::to_value(params)?).await?;
88        Ok(serde_json::from_value(result)?)
89    }
90
91    /// Enable a CDP domain in this session, required before that target's events
92    /// for the domain start flowing.
93    pub async fn enable_domain(&self, domain: &str) -> Result<()> {
94        self.call_raw(&format!("{domain}.enable"), json!({}))
95            .await?;
96        Ok(())
97    }
98
99    /// Wait for the next event named `method` raised by this session, up to
100    /// `timeout_ms` milliseconds. Events from other sessions and from the connected
101    /// target are ignored.
102    pub async fn wait_for_event(&self, method: &str, timeout_ms: u64) -> Result<Value> {
103        let mut rx = self.client.subscribe_session_events();
104        let session_id = self.session_id.clone();
105        tokio::time::timeout(std::time::Duration::from_millis(timeout_ms), async move {
106            loop {
107                match rx.recv().await {
108                    Ok(event)
109                        if event.method == method
110                            && event.session_id.as_deref() == Some(session_id.as_str()) =>
111                    {
112                        return Ok(event.params);
113                    }
114                    Ok(_) => continue,
115                    Err(broadcast::error::RecvError::Lagged(_)) => continue,
116                    Err(_) => return Err(CdpError::Protocol("event channel closed".into())),
117                }
118            }
119        })
120        .await
121        .map_err(|_| CdpError::Timeout)?
122    }
123
124    /// Detach from the target, ending this session.
125    ///
126    /// The connection itself is untouched: the client and any other session on it
127    /// keep working. Consumes the handle, since its session id is spent.
128    pub async fn detach(self) -> Result<()> {
129        self.client
130            .call_raw(DETACH_FROM_TARGET, json!({ "sessionId": self.session_id }))
131            .await?;
132        Ok(())
133    }
134}
135
136impl CdpClient {
137    /// Address commands to a session id obtained elsewhere, e.g. from a
138    /// `Target.attachedToTarget` event raised by `setAutoAttach`.
139    ///
140    /// Nothing is sent, and the id is not checked; commands simply fail with the
141    /// browser's own error if no such session exists.
142    pub fn session(&self, session_id: impl Into<String>) -> CdpSession<'_> {
143        CdpSession {
144            client: self,
145            session_id: session_id.into(),
146        }
147    }
148
149    /// Attach to `target_id` and return a handle for driving it.
150    ///
151    /// The session shares this client's connection, its message ids, and its
152    /// command timeout. Find target ids with `Target.getTargets`, or create one
153    /// with `Target.createTarget`, through [`call`](CdpClient::call).
154    ///
155    /// ```no_run
156    /// # use cdp_driver::CdpClient;
157    /// # use serde_json::{json, Value};
158    /// # async fn run(client: &CdpClient) -> cdp_driver::Result<()> {
159    /// let session = client.attach_to_target("A1B2C3").await?;
160    /// let _: Value = session.call("Runtime.enable", json!({})).await?;
161    /// session.detach().await?;
162    /// # Ok(())
163    /// # }
164    /// ```
165    pub async fn attach_to_target(&self, target_id: &str) -> Result<CdpSession<'_>> {
166        let attached: Attached = self
167            .call(
168                ATTACH_TO_TARGET,
169                json!({ "targetId": target_id, "flatten": FLAT_SESSIONS }),
170            )
171            .await?;
172        Ok(self.session(attached.session_id))
173    }
174}