use actix_codec::Framed;
use actix_http::Uri;
use async_stomp::{Message, ToServer};
use awc::{BoxedSocket, error::HttpError, ws::Codec};
use tokio::sync::mpsc::{self, Receiver, Sender, error::SendError};
use crate::{WStompConfig, stomp_handler::stomp_handler_task, wstomp_event::WStompEvent};
pub type WStompSender = Sender<Message<ToServer>>;
pub type WStompReceiver = Receiver<WStompEvent>;
pub struct WStompClient {
tx: WStompSender,
rx: WStompReceiver,
}
impl WStompClient {
pub fn builder<U>(url: U) -> WStompConfig<U>
where
Uri: TryFrom<U>,
<Uri as TryFrom<U>>::Error: Into<HttpError>,
{
WStompConfig::new(url)
}
pub fn from_framed(ws_framed: Framed<BoxedSocket, Codec>) -> Self {
let (app_tx, app_rx) = mpsc::channel::<Message<ToServer>>(100);
let (stomp_tx, stomp_rx) = mpsc::channel::<WStompEvent>(100);
actix_rt::spawn(stomp_handler_task(ws_framed, app_rx, stomp_tx));
Self {
tx: app_tx,
rx: stomp_rx,
}
}
pub async fn recv(&mut self) -> Option<WStompEvent> {
self.rx.recv().await
}
pub async fn send(&self, value: Message<ToServer>) -> Result<(), SendError<Message<ToServer>>> {
self.tx.send(value).await
}
pub fn into_split(self) -> (WStompReceiver, WStompSender) {
(self.rx, self.tx)
}
}