use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tokio::sync::broadcast;
use crate::client::CdpClient;
use crate::error::{CdpError, Result};
use crate::methods::target::{ATTACH_TO_TARGET, DETACH_FROM_TARGET};
const FLAT_SESSIONS: bool = true;
#[derive(Debug, Clone)]
pub struct SessionEvent {
pub session_id: Option<String>,
pub method: String,
pub params: Value,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Attached {
session_id: String,
}
pub struct CdpSession<'a> {
client: &'a CdpClient,
session_id: String,
}
impl<'a> CdpSession<'a> {
pub fn id(&self) -> &str {
&self.session_id
}
pub async fn call_raw(&self, method: &str, params: Value) -> Result<Value> {
self.client
.send_command_on(Some(&self.session_id), method, params)
.await
}
pub async fn call<P: Serialize, R: DeserializeOwned>(
&self,
method: &str,
params: P,
) -> Result<R> {
let result = self.call_raw(method, serde_json::to_value(params)?).await?;
Ok(serde_json::from_value(result)?)
}
pub async fn enable_domain(&self, domain: &str) -> Result<()> {
self.call_raw(&format!("{domain}.enable"), json!({}))
.await?;
Ok(())
}
pub async fn wait_for_event(&self, method: &str, timeout_ms: u64) -> Result<Value> {
let mut rx = self.client.subscribe_session_events();
let session_id = self.session_id.clone();
tokio::time::timeout(std::time::Duration::from_millis(timeout_ms), async move {
loop {
match rx.recv().await {
Ok(event)
if event.method == method
&& event.session_id.as_deref() == Some(session_id.as_str()) =>
{
return Ok(event.params);
}
Ok(_) => continue,
Err(broadcast::error::RecvError::Lagged(_)) => continue,
Err(_) => return Err(CdpError::Protocol("event channel closed".into())),
}
}
})
.await
.map_err(|_| CdpError::Timeout)?
}
pub async fn detach(self) -> Result<()> {
self.client
.call_raw(DETACH_FROM_TARGET, json!({ "sessionId": self.session_id }))
.await?;
Ok(())
}
}
impl CdpClient {
pub fn session(&self, session_id: impl Into<String>) -> CdpSession<'_> {
CdpSession {
client: self,
session_id: session_id.into(),
}
}
pub async fn attach_to_target(&self, target_id: &str) -> Result<CdpSession<'_>> {
let attached: Attached = self
.call(
ATTACH_TO_TARGET,
json!({ "targetId": target_id, "flatten": FLAT_SESSIONS }),
)
.await?;
Ok(self.session(attached.session_id))
}
}