use serde_json::Value;
use std::collections::HashMap;
use std::sync::{Arc as StdArc, Mutex as StdMutex};
use super::{
client_socket_ref::{ClientInner, ClientSocketRef},
socket_io_client::SocketIOClient,
};
use futures::future::BoxFuture;
pub type NsHandler<S> = Box<dyn Fn(ClientSocketRef<S>) -> BoxFuture<'static, ()> + Send + Sync>;
pub struct ClientApp<S> {
pub app_state: StdArc<S>,
pub ns_handlers: Vec<(String, NsHandler<S>)>,
pub auth: HashMap<String, Value>,
pub reconnect_interval_secs: Option<u64>,
pub retry_count: Option<usize>,
pub pong_timeout_secs: Option<u64>,
pub allow_upgrade: Option<bool>,
}
impl<S> ClientApp<S>
where
S: Send + Sync + 'static,
{
pub fn new(state: S) -> Self {
Self {
app_state: StdArc::new(state),
ns_handlers: Vec::new(),
auth: HashMap::new(),
reconnect_interval_secs: None,
retry_count: None,
pong_timeout_secs: None,
allow_upgrade: None,
}
}
pub fn ns<F, Fut>(&mut self, ns: &str, f: F)
where
F: Fn(ClientSocketRef<S>) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
let normalized_ns = normalize_ns(ns);
self.ns_handlers
.push((normalized_ns, Box::new(move |socket| Box::pin(f(socket)))));
}
pub fn set_auth(&mut self, ns: &str, auth: Value) {
let normalized_ns = normalize_ns(ns);
self.auth.insert(normalized_ns, auth);
}
pub async fn run(&mut self, url: &str) {
let primary_ns = self
.ns_handlers
.first()
.map(|(ns, _)| ns.clone())
.unwrap_or_else(|| "/".to_string());
let mut client = SocketIOClient::new(url);
client.set_namespace(&primary_ns);
if let Some(secs) = self.reconnect_interval_secs {
client.set_reconnect_interval(secs);
}
if let Some(count) = self.retry_count {
client.set_retry_count(count);
}
if let Some(secs) = self.pong_timeout_secs {
client.set_pong_timeout(secs);
}
if let Some(allow) = self.allow_upgrade {
client.set_allow_upgrade(allow);
}
for (ns, _) in &self.ns_handlers {
client.register_namespace(ns);
if let Some(auth) = self.auth.get(ns) {
client.set_auth(ns, auth.clone());
}
}
let inner = StdArc::new(ClientInner {
client: StdMutex::new(client),
app_state: self.app_state.clone(),
interval_tasks: StdMutex::new(HashMap::new()),
});
for (ns, handler) in &self.ns_handlers {
let socket_ref = ClientSocketRef::with_namespace(inner.clone(), ns.clone());
handler(socket_ref).await;
}
let mut client = {
let guard = inner.client.lock().unwrap();
guard.clone()
};
client.run_with_reconnect().await;
}
pub fn set_reconnect_interval(&mut self, secs: u64) {
self.reconnect_interval_secs = Some(secs);
}
pub fn set_retry_count(&mut self, count: usize) {
self.retry_count = Some(count);
}
pub fn set_pong_timeout(&mut self, secs: u64) {
self.pong_timeout_secs = Some(secs);
}
pub fn set_allow_upgrade(&mut self, allow: bool) {
self.allow_upgrade = Some(allow);
}
}
fn normalize_ns(ns: &str) -> String {
if ns.is_empty() || ns == "/" {
"/".to_string()
} else if ns.starts_with('/') {
ns.to_string()
} else {
format!("/{ns}")
}
}