use crate::error::Result;
use crate::server::connection::ConnectionLike;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::sync::Arc;
#[derive(Clone)]
pub struct Channel {
guid: Arc<str>,
connection: Arc<dyn ConnectionLike>,
}
impl Channel {
pub fn new(guid: Arc<str>, connection: Arc<dyn ConnectionLike>) -> Self {
Self { guid, connection }
}
pub async fn send<P: Serialize, R: DeserializeOwned>(
&self,
method: &str,
params: P,
) -> Result<R> {
let params_value = serde_json::to_value(params)?;
let response = self
.connection
.send_message(&self.guid, method, params_value)
.await?;
serde_json::from_value(response).map_err(Into::into)
}
pub async fn send_no_params<R: DeserializeOwned>(&self, method: &str) -> Result<R> {
self.send(method, Value::Null).await
}
pub async fn send_no_result<P: Serialize>(&self, method: &str, params: P) -> Result<()> {
let _: Value = self.send(method, params).await?;
Ok(())
}
pub(crate) async fn notify<P: Serialize>(&self, method: &str, params: P) {
if let Err(e) = self.send_no_result(method, params).await {
tracing::warn!("{} failed: {}", method, e);
}
}
pub async fn update_subscription(&self, event: &str, enabled: bool) -> Result<()> {
self.send_no_result(
"updateSubscription",
serde_json::json!({
"event": event,
"enabled": enabled,
}),
)
.await
}
pub fn guid(&self) -> &str {
&self.guid
}
}