use serde::Serialize;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::{Arc as StdArc, Mutex as StdMutex};
use std::time::Duration;
use tokio::task::JoinHandle;
use super::{
extractor::Extractor,
socket_io_client::{IncomingEvent, SocketIOClient, SYS_CONNECT, SYS_CONNECT_ERROR,
SYS_DISCONNECT, SYS_ERROR, SYS_CLOSED, SYS_RECONNECT_ATTEMPT, SYS_RECONNECT},
};
pub struct ClientInner<S> {
pub client: StdMutex<SocketIOClient>,
pub app_state: StdArc<S>,
pub interval_tasks: StdMutex<HashMap<String, JoinHandle<()>>>,
}
pub struct ClientSocketRef<S> {
pub inner: StdArc<ClientInner<S>>,
pub namespace: String,
}
impl<S> Clone for ClientSocketRef<S> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
namespace: self.namespace.clone(),
}
}
}
impl<S> ClientSocketRef<S>
where
S: Send + Sync + 'static,
{
pub fn new(inner: StdArc<ClientInner<S>>) -> Self {
let ns = {
let c = inner.client.lock().unwrap();
c.namespace.clone()
};
Self {
inner,
namespace: ns,
}
}
pub fn with_namespace(inner: StdArc<ClientInner<S>>, ns: String) -> Self {
Self { inner, namespace: ns }
}
pub fn id(&self) -> String {
"client".into()
}
pub fn namespace(&self) -> String {
self.namespace.clone()
}
pub fn transport(&self) -> super::socket_io_client::TransportMode {
self.clone_client().transport()
}
pub async fn emit<T: Serialize>(
&self,
event: &str,
data: T,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let client = self.clone_client();
client.emit_ns(&self.namespace, event, data).await
}
pub async fn emit_with_ack<T: Serialize>(
&self,
event: &str,
data: T,
timeout: Duration,
) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
let client = self.clone_client();
client
.emit_with_ack_ns(&self.namespace, event, data, timeout)
.await
}
pub async fn emit_binary(
&self,
event: &str,
args: Vec<Value>,
attachments: Vec<Vec<u8>>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let client = self.clone_client();
client
.emit_binary_ns(&self.namespace, event, args, attachments)
.await
}
pub async fn emit_binary_with_ack(
&self,
event: &str,
args: Vec<Value>,
attachments: Vec<Vec<u8>>,
timeout: Duration,
) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
let client = self.clone_client();
client
.emit_binary_with_ack_ns(&self.namespace, event, args, attachments, timeout)
.await
}
pub async fn emit_args(
&self,
event: &str,
args: Vec<Value>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let client = self.clone_client();
client.emit_args_ns(&self.namespace, event, args).await
}
pub async fn disconnect(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let client = self.clone_client();
client.disconnect_ns(&self.namespace).await
}
pub async fn join(&self, room: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
self.emit("join", serde_json::json!({"room": room})).await
}
pub async fn leave(&self, room: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
self.emit("leave", serde_json::json!({"room": room})).await
}
fn clone_client(&self) -> SocketIOClient {
let guard = self.inner.client.lock().unwrap();
guard.clone()
}
pub fn on<E1, E2, E3, H, Fut>(&self, event: &str, handler: H)
where
E1: Extractor<S> + Send + 'static,
E2: Extractor<S> + Send + 'static,
E3: Extractor<S> + Send + 'static,
H: Fn(E1, E2, E3) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
let handler = StdArc::new(handler);
self.register(event, move |socket, evt| {
let handler = handler.clone();
Box::pin(async move {
let e1 = E1::extract(&socket, &evt);
let e2 = E2::extract(&socket, &evt);
let e3 = E3::extract(&socket, &evt);
handler(e1, e2, e3).await;
})
});
}
pub fn on_connect<E1, E2, H, Fut>(&self, handler: H)
where
E1: Extractor<S> + Send + 'static,
E2: Extractor<S> + Send + 'static,
H: Fn(E1, E2) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
self.register_sys_2(SYS_CONNECT, handler);
}
pub fn on_disconnect<E1, E2, H, Fut>(&self, handler: H)
where
E1: Extractor<S> + Send + 'static,
E2: Extractor<S> + Send + 'static,
H: Fn(E1, E2) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
self.register_sys_2(SYS_DISCONNECT, handler);
}
pub fn on_closed<E1, E2, H, Fut>(&self, handler: H)
where
E1: Extractor<S> + Send + 'static,
E2: Extractor<S> + Send + 'static,
H: Fn(E1, E2) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
self.register_sys_2(SYS_CLOSED, handler);
}
pub fn on_error<E1, E2, H, Fut>(&self, handler: H)
where
E1: Extractor<S> + Send + 'static,
E2: Extractor<S> + Send + 'static,
H: Fn(E1, E2, String) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
let handler = StdArc::new(handler);
self.register(SYS_ERROR, move |socket, evt| {
let handler = handler.clone();
Box::pin(async move {
let e1 = E1::extract(&socket, &evt);
let e2 = E2::extract(&socket, &evt);
let err = match &evt.data {
Value::String(s) => s.clone(),
other => other.to_string(),
};
handler(e1, e2, err).await;
})
});
}
pub fn on_connect_error<E1, E2, H, Fut>(&self, handler: H)
where
E1: Extractor<S> + Send + 'static,
E2: Extractor<S> + Send + 'static,
H: Fn(E1, E2, Value) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
let handler = StdArc::new(handler);
self.register(SYS_CONNECT_ERROR, move |socket, evt| {
let handler = handler.clone();
Box::pin(async move {
let e1 = E1::extract(&socket, &evt);
let e2 = E2::extract(&socket, &evt);
handler(e1, e2, evt.data.clone()).await;
})
});
}
pub fn on_reconnect_attempt<E1, E2, H, Fut>(&self, handler: H)
where
E1: Extractor<S> + Send + 'static,
E2: Extractor<S> + Send + 'static,
H: Fn(E1, E2, u64) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
let handler = StdArc::new(handler);
self.register(SYS_RECONNECT_ATTEMPT, move |socket, evt| {
let handler = handler.clone();
Box::pin(async move {
let e1 = E1::extract(&socket, &evt);
let e2 = E2::extract(&socket, &evt);
let attempts = evt.data.as_u64().unwrap_or(0);
handler(e1, e2, attempts).await;
})
});
}
pub fn on_reconnect<E1, E2, H, Fut>(&self, handler: H)
where
E1: Extractor<S> + Send + 'static,
E2: Extractor<S> + Send + 'static,
H: Fn(E1, E2, u64) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
let handler = StdArc::new(handler);
self.register(SYS_RECONNECT, move |socket, evt| {
let handler = handler.clone();
Box::pin(async move {
let e1 = E1::extract(&socket, &evt);
let e2 = E2::extract(&socket, &evt);
let attempts = evt.data.as_u64().unwrap_or(0);
handler(e1, e2, attempts).await;
})
});
}
fn register_sys_2<E1, E2, H, Fut>(&self, sys_event: &str, handler: H)
where
E1: Extractor<S> + Send + 'static,
E2: Extractor<S> + Send + 'static,
H: Fn(E1, E2) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
let handler = StdArc::new(handler);
self.register(sys_event, move |socket, evt| {
let handler = handler.clone();
Box::pin(async move {
let e1 = E1::extract(&socket, &evt);
let e2 = E2::extract(&socket, &evt);
handler(e1, e2).await;
})
});
}
fn register<F>(&self, event: &str, wrap: F)
where
F: Fn(ClientSocketRef<S>, IncomingEvent) -> futures::future::BoxFuture<'static, ()>
+ Send
+ Sync
+ 'static,
{
let inner = self.inner.clone();
let ns = self.namespace.clone();
let wrap = StdArc::new(wrap);
let mut client = inner.client.lock().unwrap();
let inner_for_cb = inner.clone();
let ns_for_cb = ns.clone();
client.on_ns(&ns, event, move |evt: IncomingEvent| {
let socket = ClientSocketRef::with_namespace(inner_for_cb.clone(), ns_for_cb.clone());
(wrap)(socket, evt)
});
}
pub fn run_interval<E1, E2, H, Fut>(
&self,
loop_name: &str,
interval: Duration,
count: usize,
handler: H,
) where
E1: Extractor<S> + Send + 'static,
E2: Extractor<S> + Send + 'static,
H: Fn(String, Duration, usize, E1, E2) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = ()> + Send + 'static,
{
let handler = StdArc::new(handler);
let name = loop_name.to_string();
let h_connect = handler.clone();
let name_connect = name.clone();
self.register(SYS_CONNECT, move |socket, _evt| {
let handler = h_connect.clone();
let name = name_connect.clone();
let interval_cloned = interval;
let count_cloned = count;
Box::pin(async move {
let inner = socket.inner.clone();
let socket_for_task = socket.clone();
let name_for_cb = name.clone();
let h = tokio::spawn(async move {
let mut executed: usize = 0;
loop {
if count_cloned != 0 && executed >= count_cloned {
break;
}
let e1 = E1::extract(
&socket_for_task,
&IncomingEvent {
data: Value::Null,
ack_id: None,
namespace: socket_for_task.namespace.clone(),
},
);
let e2 = E2::extract(
&socket_for_task,
&IncomingEvent {
data: Value::Null,
ack_id: None,
namespace: socket_for_task.namespace.clone(),
},
);
handler(name_for_cb.clone(), interval_cloned, count_cloned, e1, e2)
.await;
tokio::time::sleep(interval_cloned).await;
executed += 1;
}
});
let mut tasks = inner.interval_tasks.lock().unwrap();
if let Some(prev) = tasks.remove(&name) {
prev.abort();
}
tasks.insert(name, h);
})
});
let name_disconnect = name.clone();
self.register(SYS_DISCONNECT, move |socket, _evt| {
let inner = socket.inner.clone();
let name = name_disconnect.clone();
Box::pin(async move {
let mut tasks = inner.interval_tasks.lock().unwrap();
if let Some(h) = tasks.remove(&name) {
h.abort();
}
})
});
}
}