use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use crate::client::{Authenticated, Client};
use crate::error::Result;
use super::client::WebSocket;
use super::events::WsEvent;
use super::subscription::Subscription;
pub type BoxedEventHandler =
Arc<dyn Fn(WsEvent) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;
pub struct WebSocketBuilder<'a> {
pub(crate) client: &'a Client<Authenticated>,
pub(crate) event_handler: Option<BoxedEventHandler>,
pub(crate) subscriptions: Vec<Subscription>,
pub(crate) auto_reconnect: bool,
pub(crate) reconnect_delay: Duration,
}
impl<'a> WebSocketBuilder<'a> {
pub(crate) fn new(client: &'a Client<Authenticated>) -> Self {
Self {
client,
event_handler: None,
subscriptions: Vec::new(),
auto_reconnect: true,
reconnect_delay: Duration::from_secs(5),
}
}
pub fn on_event<F, Fut>(mut self, handler: F) -> Self
where
F: Fn(WsEvent) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
self.event_handler = Some(Arc::new(move |event| {
Box::pin(handler(event)) as Pin<Box<dyn Future<Output = ()> + Send>>
}));
self
}
pub fn subscribe(mut self, subscription: Subscription) -> Self {
self.subscriptions.push(subscription);
self
}
pub fn auto_reconnect(mut self, enabled: bool) -> Self {
self.auto_reconnect = enabled;
self
}
pub fn reconnect_delay(mut self, delay: Duration) -> Self {
self.reconnect_delay = delay;
self
}
pub async fn connect(self) -> Result<WebSocket> {
WebSocket::connect(self).await
}
}
impl Client<Authenticated> {
#[cfg(feature = "websocket")]
pub fn websocket(&self) -> WebSocketBuilder<'_> {
WebSocketBuilder::new(self)
}
}