use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use serde_json::Value;
use tokio::runtime::{Handle, Runtime};
#[cfg(any(feature = "rustls", feature = "native-tls"))]
use crate::engineio::TlsConfig;
use crate::handler::ListenerId;
use crate::{
ConnectionState, Direction, Event, LinkInfo, Payload, Result, TransportType, protocol,
};
struct RuntimeOwner(Option<Runtime>);
impl Drop for RuntimeOwner {
fn drop(&mut self) {
if let Some(runtime) = self.0.take() {
runtime.shutdown_background();
}
}
}
pub struct ClientBuilder {
inner: crate::ClientBuilder,
runtime: Arc<RuntimeOwner>,
handle: Handle,
}
impl fmt::Debug for ClientBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ClientBuilder")
.field("inner", &self.inner)
.finish_non_exhaustive()
}
}
macro_rules! delegate {
($($(#[$meta:meta])* fn $name:ident($($arg:ident: $ty:ty),*);)*) => {$(
$(#[$meta])*
pub fn $name(self, $($arg: $ty),*) -> Self {
ClientBuilder { inner: self.inner.$name($($arg),*), ..self }
}
)*};
}
impl ClientBuilder {
pub fn new(address: impl Into<String>) -> Self {
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.thread_name("socketio-next")
.enable_all()
.build()
.expect("start the socketio-next runtime");
let handle = runtime.handle().clone();
ClientBuilder {
inner: crate::ClientBuilder::new(address),
runtime: Arc::new(RuntimeOwner(Some(runtime))),
handle,
}
}
delegate! {
fn namespace(namespace: impl Into<String>);
fn path(path: impl Into<String>);
fn query(key: impl Into<String>, value: impl Into<String>);
fn header(key: impl Into<String>, value: impl Into<String>);
fn auth(auth: impl Into<Value>);
fn transport_type(transport: TransportType);
fn timeout(timeout: Duration);
fn reconnection(reconnection: bool);
fn reconnection_attempts(attempts: u32);
fn reconnection_delay(delay: Duration);
fn reconnection_delay_max(delay: Duration);
fn randomization_factor(factor: f64);
fn reconnect_on_disconnect(reconnect: bool);
fn buffer_while_disconnected(buffer: bool);
fn redact_query(redact: bool);
fn proxy(proxy: impl Into<String>);
fn no_proxy();
}
pub fn engine_url(&self) -> Result<url::Url> {
self.inner.engine_url()
}
pub fn connect_params_with<F>(self, params: F) -> Self
where
F: Fn() -> crate::ConnectParams + Send + Sync + 'static,
{
let params = Arc::new(params);
let inner = self.inner.connect_params_with(move || {
let params = Arc::clone(¶ms);
async move {
match tokio::task::spawn_blocking(move || params()).await {
Ok(value) => value,
Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()),
Err(_) => {
std::panic::resume_unwind(Box::new("connect_params_with was cancelled"))
}
}
}
});
ClientBuilder { inner, ..self }
}
#[cfg(any(feature = "rustls", feature = "native-tls"))]
pub fn tls_config(self, tls_config: impl Into<TlsConfig>) -> Self {
ClientBuilder {
inner: self.inner.tls_config(tls_config),
..self
}
}
pub fn auth_with<F>(self, auth: F) -> Self
where
F: Fn() -> Value + Send + Sync + 'static,
{
let auth = Arc::new(auth);
let inner = self.inner.auth_with(move || {
let auth = Arc::clone(&auth);
async move {
match tokio::task::spawn_blocking(move || auth()).await {
Ok(value) => value,
Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()),
Err(_) => std::panic::resume_unwind(Box::new("auth_with was cancelled")),
}
}
});
ClientBuilder { inner, ..self }
}
pub fn inspect_packets<F>(self, inspector: F) -> Self
where
F: Fn(Direction, &protocol::socketio::Packet) + Send + Sync + 'static,
{
ClientBuilder {
inner: self.inner.inspect_packets(inspector),
..self
}
}
pub fn on<F>(self, event: impl Into<String>, handler: F) -> Self
where
F: Fn(Event, Client) + Send + Sync + 'static,
{
let handle = self.handle.clone();
ClientBuilder {
inner: self.inner.on(event, wrap(handle, handler)),
..self
}
}
pub fn once<F>(self, event: impl Into<String>, handler: F) -> Self
where
F: Fn(Event, Client) + Send + Sync + 'static,
{
let handle = self.handle.clone();
ClientBuilder {
inner: self.inner.once(event, wrap(handle, handler)),
..self
}
}
pub fn on_any<F>(self, handler: F) -> Self
where
F: Fn(Event, Client) + Send + Sync + 'static,
{
let handle = self.handle.clone();
ClientBuilder {
inner: self.inner.on_any(wrap(handle, handler)),
..self
}
}
pub fn on_state_change<F>(self, handler: F) -> Self
where
F: Fn(ConnectionState, Client) + Send + Sync + 'static,
{
let handle = self.handle.clone();
ClientBuilder {
inner: self.inner.on_state_change(wrap(handle, handler)),
..self
}
}
pub fn connect(self) -> Result<Client> {
let inner = self.handle.block_on(self.inner.connect())?;
Ok(Client {
inner,
handle: self.handle,
_runtime: Some(self.runtime),
})
}
}
fn wrap<A, F>(handle: Handle, handler: F) -> impl Fn(A, crate::Client) + Send + Sync + 'static
where
A: Send + 'static,
F: Fn(A, Client) + Send + Sync + 'static,
{
move |arg, inner| {
handler(
arg,
Client {
inner,
handle: handle.clone(),
_runtime: None,
},
)
}
}
#[derive(Clone)]
pub struct Client {
inner: crate::Client,
handle: Handle,
_runtime: Option<Arc<RuntimeOwner>>,
}
impl fmt::Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Client").field(&self.inner).finish()
}
}
impl Drop for Client {
fn drop(&mut self) {
let last = self
._runtime
.as_ref()
.is_some_and(|runtime| Arc::strong_count(runtime) == 1);
if last && Handle::try_current().is_err() && !self.inner.state().is_closed() {
let inner = self.inner.clone();
self.handle.block_on(async move {
let _ = tokio::time::timeout(Duration::from_secs(3), inner.disconnect()).await;
});
}
}
}
impl Client {
pub fn as_async(&self) -> &crate::Client {
&self.inner
}
pub fn emit(&self, event: impl AsRef<str>, data: impl Into<Payload>) -> Result<()> {
self.inner.emit(event, data)
}
pub fn emit_with_ack(
&self,
event: impl AsRef<str>,
data: impl Into<Payload>,
timeout: Duration,
) -> Result<Payload> {
self.handle
.block_on(self.inner.emit_with_ack(event, data, timeout))
}
pub fn disconnect(&self) -> Result<()> {
self.handle.block_on(self.inner.disconnect())
}
pub fn reconnect(&self) -> Result<()> {
self.handle.block_on(self.inner.reconnect())
}
pub fn on<F>(&self, event: impl Into<String>, handler: F) -> ListenerId
where
F: Fn(Event, Client) + Send + Sync + 'static,
{
self.inner.on(event, wrap(self.handle.clone(), handler))
}
pub fn once<F>(&self, event: impl Into<String>, handler: F) -> ListenerId
where
F: Fn(Event, Client) + Send + Sync + 'static,
{
self.inner.once(event, wrap(self.handle.clone(), handler))
}
pub fn on_any<F>(&self, handler: F) -> ListenerId
where
F: Fn(Event, Client) + Send + Sync + 'static,
{
self.inner.on_any(wrap(self.handle.clone(), handler))
}
pub fn on_state_change<F>(&self, handler: F) -> ListenerId
where
F: Fn(ConnectionState, Client) + Send + Sync + 'static,
{
self.inner
.on_state_change(wrap(self.handle.clone(), handler))
}
pub fn off(&self, event: &str) -> usize {
self.inner.off(event)
}
pub fn off_any(&self) -> usize {
self.inner.off_any()
}
pub fn off_listener(&self, id: ListenerId) -> bool {
self.inner.off_listener(id)
}
pub fn listener_count(&self, event: &str) -> usize {
self.inner.listener_count(event)
}
pub fn state(&self) -> ConnectionState {
self.inner.state()
}
pub fn wait_for(
&self,
predicate: impl Fn(&ConnectionState) -> bool,
timeout: Duration,
) -> ConnectionState {
self.handle.block_on(async {
tokio::time::timeout(timeout, self.inner.wait_for(predicate))
.await
.unwrap_or_else(|_| self.inner.state())
})
}
pub fn connected(&self) -> bool {
self.inner.connected()
}
pub fn id(&self) -> Option<String> {
self.inner.id()
}
pub fn recovered(&self) -> bool {
self.inner.recovered()
}
pub fn namespace(&self) -> &str {
self.inner.namespace()
}
pub fn link_info(&self) -> LinkInfo {
self.inner.link_info()
}
}