Skip to main content

cdp_driver/
typed.rs

1//! Sending a CDP command as a type, and reading an event back as one.
2//!
3//! [`CdpClient::call`](crate::CdpClient::call) takes a method name and a
4//! `Serialize` beside a result type chosen by the caller, so nothing stops the
5//! three from disagreeing. The traits here tie them together: a generated
6//! parameters struct in [`crate::protocol`] knows its own method name and its
7//! own result type, and an event payload knows the event it belongs to.
8
9use serde::de::DeserializeOwned;
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12
13use crate::client::CdpClient;
14use crate::error::Result;
15use crate::session::{CdpSession, SessionEvent};
16
17/// The result of a command the protocol declares no return fields for.
18///
19/// Chrome answers such a command with an empty object, and older builds
20/// sometimes with nothing at all, so this accepts whatever arrives rather than
21/// turning a successful command into a decoding error.
22#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(from = "Value")]
24pub struct NoReturns {}
25
26/// A CDP command, carrying its own method name and result type.
27///
28/// Implemented by every `*Params` struct in [`crate::protocol`].
29pub trait Command: Serialize {
30    /// The protocol's name for the command, e.g. `"Page.navigate"`.
31    const METHOD: &'static str;
32
33    /// What the browser answers with, or [`NoReturns`] when it answers with
34    /// nothing.
35    type Returns: DeserializeOwned;
36}
37
38/// A CDP event, carrying the name it arrives under.
39///
40/// Implemented by every `*Event` struct in [`crate::protocol`].
41pub trait Event: DeserializeOwned {
42    /// The protocol's name for the event, e.g. `"Page.loadEventFired"`.
43    const METHOD: &'static str;
44}
45
46impl From<Value> for NoReturns {
47    fn from(_: Value) -> Self {
48        Self {}
49    }
50}
51
52/// Decode a raw `(method, params)` pair as `E`.
53///
54/// `None` means the pair is some other event, which is the common case when
55/// walking a subscription; `Some(Err(_))` means it was this event and its
56/// payload did not fit.
57///
58/// ```no_run
59/// # use cdp_driver::CdpClient;
60/// use cdp_driver::protocol::page::LoadEventFiredEvent;
61/// use cdp_driver::typed;
62///
63/// # async fn run(client: &CdpClient) -> cdp_driver::Result<()> {
64/// let mut events = client.subscribe_events();
65/// while let Ok((method, params)) = events.recv().await {
66///     if let Some(loaded) = typed::decode::<LoadEventFiredEvent>(&method, &params) {
67///         println!("loaded at {}", loaded?.timestamp);
68///         break;
69///     }
70/// }
71/// # Ok(())
72/// # }
73/// ```
74pub fn decode<E: Event>(method: &str, params: &Value) -> Option<Result<E>> {
75    if method != E::METHOD {
76        return None;
77    }
78    Some(E::deserialize(params).map_err(Into::into))
79}
80
81impl SessionEvent {
82    /// Decode this event as `E`, or `None` when it is a different event.
83    ///
84    /// Which session raised it is left to the caller to check, since an event
85    /// from a session and the same event from the connected target decode
86    /// identically.
87    pub fn decode<E: Event>(&self) -> Option<Result<E>> {
88        decode(&self.method, &self.params)
89    }
90}
91
92impl CdpSession<'_> {
93    /// Send a typed command in this session.
94    ///
95    /// The counterpart of [`CdpClient::send`], differing only in that the
96    /// command is addressed to this session rather than to the connected target.
97    pub async fn send<C: Command>(&self, params: C) -> Result<C::Returns> {
98        self.call(C::METHOD, params).await
99    }
100
101    /// Wait for the next `E` raised by this session, up to `timeout_ms`
102    /// milliseconds. Events from other sessions are ignored.
103    pub async fn wait_for<E: Event>(&self, timeout_ms: u64) -> Result<E> {
104        let params = self.wait_for_event(E::METHOD, timeout_ms).await?;
105        Ok(serde_json::from_value(params)?)
106    }
107}
108
109impl CdpClient {
110    /// Send a typed command and get back its declared result.
111    ///
112    /// The method name and the result type both come from the parameters, so a
113    /// command cannot be paired with the wrong result.
114    ///
115    /// ```no_run
116    /// # use cdp_driver::CdpClient;
117    /// use cdp_driver::protocol::page::NavigateParams;
118    ///
119    /// # async fn run(client: &CdpClient) -> cdp_driver::Result<()> {
120    /// let navigated = client
121    ///     .send(NavigateParams {
122    ///         url: "https://example.com".to_string(),
123    ///         ..Default::default()
124    ///     })
125    ///     .await?;
126    /// println!("{}", navigated.frame_id);
127    /// # Ok(())
128    /// # }
129    /// ```
130    pub async fn send<C: Command>(&self, params: C) -> Result<C::Returns> {
131        self.call(C::METHOD, params).await
132    }
133
134    /// Wait for the next `E` on the connected target, up to `timeout_ms`
135    /// milliseconds.
136    ///
137    /// The event's domain has to be enabled first, as with
138    /// [`wait_for_event`](Self::wait_for_event).
139    pub async fn wait_for<E: Event>(&self, timeout_ms: u64) -> Result<E> {
140        let params = self.wait_for_event(E::METHOD, timeout_ms).await?;
141        Ok(serde_json::from_value(params)?)
142    }
143}