use std::fmt;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use futures_util::FutureExt;
use futures_util::future::BoxFuture;
use http::{HeaderMap, HeaderName, HeaderValue};
use serde_json::Value;
use crate::backoff::DEFAULT_JITTER;
use crate::engineio::TlsConfig;
use crate::handler::{Handler, Handlers};
use crate::protocol::socketio::Packet;
use crate::{Client, ConnectionState, Error, Event, Result, TransportType};
pub(crate) type AuthFn = Arc<dyn Fn() -> BoxFuture<'static, Value> + Send + Sync>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Direction {
Incoming,
Outgoing,
}
pub(crate) type ParamsFn = Arc<dyn Fn() -> BoxFuture<'static, ConnectParams> + Send + Sync>;
#[derive(Clone, Default)]
pub struct ConnectParams {
pub(crate) query: Vec<(String, String)>,
pub(crate) headers: Vec<(String, String)>,
}
impl fmt::Debug for ConnectParams {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let keys = |v: &[(String, String)]| v.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>();
f.debug_struct("ConnectParams")
.field("query_keys", &keys(&self.query))
.field("header_keys", &keys(&self.headers))
.finish()
}
}
impl ConnectParams {
pub fn new() -> Self {
ConnectParams::default()
}
pub fn query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.query.push((key.into(), value.into()));
self
}
pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((key.into(), value.into()));
self
}
}
#[derive(Clone, Debug)]
pub(crate) enum ProxyChoice {
Env,
Url(String),
Off,
}
pub(crate) type Inspector = Arc<dyn Fn(Direction, &Packet) + Send + Sync>;
#[derive(Clone)]
pub(crate) struct Config {
pub(crate) address: String,
pub(crate) path: String,
pub(crate) namespace: Option<String>,
pub(crate) query: Vec<(String, String)>,
pub(crate) headers: HeaderMap,
pub(crate) auth: Option<Value>,
pub(crate) auth_fn: Option<AuthFn>,
pub(crate) params_fn: Option<ParamsFn>,
pub(crate) proxy: ProxyChoice,
pub(crate) http: Option<crate::engineio::http::Http>,
#[cfg_attr(not(any(feature = "rustls", feature = "native-tls")), allow(dead_code))]
pub(crate) tls_config: Option<TlsConfig>,
pub(crate) transport: TransportType,
pub(crate) timeout: Duration,
pub(crate) reconnection: bool,
pub(crate) reconnection_attempts: Option<u32>,
pub(crate) reconnection_delay: Duration,
pub(crate) reconnection_delay_max: Duration,
pub(crate) randomization_factor: f64,
pub(crate) reconnect_on_disconnect: bool,
pub(crate) buffer_while_disconnected: bool,
pub(crate) redact_query: bool,
pub(crate) inspector: Option<Inspector>,
}
impl fmt::Debug for Config {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Config")
.field("path", &self.path)
.field("namespace", &self.namespace)
.field(
"query_keys",
&self.query.iter().map(|(k, _)| k).collect::<Vec<_>>(),
)
.field("auth", &self.auth.as_ref().map(|_| "***"))
.field("transport", &self.transport)
.field("timeout", &self.timeout)
.field("reconnection", &self.reconnection)
.field("reconnection_attempts", &self.reconnection_attempts)
.field("reconnection_delay", &self.reconnection_delay)
.field("reconnection_delay_max", &self.reconnection_delay_max)
.field("randomization_factor", &self.randomization_factor)
.field("reconnect_on_disconnect", &self.reconnect_on_disconnect)
.field("buffer_while_disconnected", &self.buffer_while_disconnected)
.field("proxy", &!matches!(self.proxy, ProxyChoice::Env))
.finish_non_exhaustive()
}
}
pub struct ClientBuilder {
pub(crate) config: Config,
pub(crate) handlers: Handlers,
raw_headers: Vec<(String, String)>,
}
impl fmt::Debug for ClientBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ClientBuilder")
.field("config", &self.config)
.field("handlers", &self.handlers)
.field(
"headers",
&self.raw_headers.iter().map(|(k, _)| k).collect::<Vec<_>>(),
)
.finish()
}
}
impl ClientBuilder {
pub fn new(address: impl Into<String>) -> Self {
ClientBuilder {
config: Config {
address: address.into(),
path: "/socket.io/".to_owned(),
namespace: None,
query: Vec::new(),
headers: HeaderMap::new(),
auth: None,
auth_fn: None,
params_fn: None,
proxy: ProxyChoice::Env,
http: None,
tls_config: None,
transport: TransportType::Any,
timeout: Duration::from_secs(20),
reconnection: true,
reconnection_attempts: None,
reconnection_delay: Duration::from_millis(1000),
reconnection_delay_max: Duration::from_millis(5000),
randomization_factor: DEFAULT_JITTER,
reconnect_on_disconnect: false,
buffer_while_disconnected: false,
redact_query: true,
inspector: None,
},
handlers: Handlers::default(),
raw_headers: Vec::new(),
}
}
pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
let mut nsp = namespace.into();
if !nsp.starts_with('/') {
nsp.insert(0, '/');
}
self.config.namespace = Some(nsp);
self
}
pub fn path(mut self, path: impl Into<String>) -> Self {
let mut path = path.into();
if !path.starts_with('/') {
path.insert(0, '/');
}
if !path.ends_with('/') {
path.push('/');
}
self.config.path = path;
self
}
pub fn query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.config.query.push((key.into(), value.into()));
self
}
pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.raw_headers.push((key.into(), value.into()));
self
}
pub fn auth(mut self, auth: impl Into<Value>) -> Self {
self.config.auth = Some(auth.into());
self
}
pub fn auth_with<F, Fut>(mut self, auth: F) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Value> + Send + 'static,
{
self.config.auth_fn = Some(Arc::new(move || auth().boxed()));
self
}
pub fn connect_params_with<F, Fut>(mut self, params: F) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = ConnectParams> + Send + 'static,
{
self.config.params_fn = Some(Arc::new(move || params().boxed()));
self
}
#[cfg(any(feature = "rustls", feature = "native-tls"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "rustls", feature = "native-tls"))))]
pub fn tls_config(mut self, tls_config: impl Into<TlsConfig>) -> Self {
self.config.tls_config = Some(tls_config.into());
self
}
pub fn proxy(mut self, proxy: impl Into<String>) -> Self {
self.config.proxy = ProxyChoice::Url(proxy.into());
self
}
pub fn no_proxy(mut self) -> Self {
self.config.proxy = ProxyChoice::Off;
self
}
pub fn transport_type(mut self, transport: TransportType) -> Self {
self.config.transport = transport;
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.config.timeout = timeout;
self
}
pub fn reconnection(mut self, reconnection: bool) -> Self {
self.config.reconnection = reconnection;
self
}
pub fn reconnection_attempts(mut self, attempts: u32) -> Self {
self.config.reconnection_attempts = Some(attempts);
self
}
pub fn reconnection_delay(mut self, delay: Duration) -> Self {
self.config.reconnection_delay = delay;
self
}
pub fn reconnection_delay_max(mut self, delay: Duration) -> Self {
self.config.reconnection_delay_max = delay;
self
}
pub fn randomization_factor(mut self, factor: f64) -> Self {
self.config.randomization_factor = factor;
self
}
pub fn reconnect_on_disconnect(mut self, reconnect: bool) -> Self {
self.config.reconnect_on_disconnect = reconnect;
self
}
pub fn buffer_while_disconnected(mut self, buffer: bool) -> Self {
self.config.buffer_while_disconnected = buffer;
self
}
pub fn redact_query(mut self, redact: bool) -> Self {
self.config.redact_query = redact;
self
}
pub fn inspect_packets<F>(mut self, inspector: F) -> Self
where
F: Fn(Direction, &Packet) + Send + Sync + 'static,
{
self.config.inspector = Some(Arc::new(inspector));
self
}
pub fn on<M>(mut self, event: impl Into<String>, handler: impl Handler<Event, M>) -> Self {
self.handlers.on(event.into(), handler.into_boxed(), false);
self
}
pub fn once<M>(mut self, event: impl Into<String>, handler: impl Handler<Event, M>) -> Self {
self.handlers.on(event.into(), handler.into_boxed(), true);
self
}
pub fn on_any<M>(mut self, handler: impl Handler<Event, M>) -> Self {
self.handlers.on_any(handler.into_boxed());
self
}
pub fn on_state_change<M>(mut self, handler: impl Handler<ConnectionState, M>) -> Self {
self.handlers.on_state(handler.into_boxed());
self
}
pub fn engine_url(&self) -> Result<url::Url> {
Ok(crate::client::resolve(&self.config)?.0)
}
pub async fn connect(mut self) -> Result<Client> {
if self.config.auth.as_ref().is_some_and(|a| !a.is_object()) {
return Err(Error::InvalidAuth("the auth payload must be a JSON object"));
}
for (key, value) in std::mem::take(&mut self.raw_headers) {
let name = HeaderName::try_from(key.as_str())
.map_err(|_| Error::InvalidHeader(format!("bad header name {key:?}")))?;
let value = HeaderValue::try_from(value.as_str())
.map_err(|_| Error::InvalidHeader(format!("bad value for header {key:?}")))?;
self.config.headers.append(name, value);
}
use crate::engineio::http::ProxyMode;
let proxy = match &self.config.proxy {
ProxyChoice::Url(proxy) => {
ProxyMode::Explicit(url::Url::parse(proxy).map_err(|_| {
crate::engineio::Error::ProxyFailed("the proxy is not a valid URL".into())
})?)
}
ProxyChoice::Env => ProxyMode::Env,
ProxyChoice::Off => ProxyMode::Off,
};
self.config.http = Some(crate::engineio::http::Http::new(
self.config.tls_config.as_ref(),
proxy,
)?);
crate::client::connect(self.config, self.handlers).await
}
}