1use std::fmt;
2use std::future::Future;
3use std::sync::Arc;
4use std::time::Duration;
5
6use futures_util::FutureExt;
7use futures_util::future::BoxFuture;
8use http::{HeaderMap, HeaderName, HeaderValue};
9use serde_json::Value;
10
11use crate::backoff::DEFAULT_JITTER;
12use crate::engineio::TlsConfig;
13use crate::handler::{Handler, Handlers};
14use crate::protocol::socketio::Packet;
15use crate::{Client, ConnectionState, Error, Event, Result, TransportType};
16
17pub(crate) type AuthFn = Arc<dyn Fn() -> BoxFuture<'static, Value> + Send + Sync>;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22#[non_exhaustive]
23pub enum Direction {
24 Incoming,
26 Outgoing,
28}
29
30pub(crate) type ParamsFn = Arc<dyn Fn() -> BoxFuture<'static, ConnectParams> + Send + Sync>;
31
32#[derive(Clone, Default)]
36pub struct ConnectParams {
37 pub(crate) query: Vec<(String, String)>,
38 pub(crate) headers: Vec<(String, String)>,
39}
40
41impl fmt::Debug for ConnectParams {
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43 let keys = |v: &[(String, String)]| v.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>();
44 f.debug_struct("ConnectParams")
45 .field("query_keys", &keys(&self.query))
46 .field("header_keys", &keys(&self.headers))
47 .finish()
48 }
49}
50
51impl ConnectParams {
52 pub fn new() -> Self {
54 ConnectParams::default()
55 }
56
57 pub fn query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
59 self.query.push((key.into(), value.into()));
60 self
61 }
62
63 pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
65 self.headers.push((key.into(), value.into()));
66 self
67 }
68}
69
70#[derive(Clone, Debug)]
72pub(crate) enum ProxyChoice {
73 Env,
74 Url(String),
75 Off,
76}
77
78pub(crate) type Inspector = Arc<dyn Fn(Direction, &Packet) + Send + Sync>;
79
80#[derive(Clone)]
82pub(crate) struct Config {
83 pub(crate) address: String,
84 pub(crate) path: String,
85 pub(crate) namespace: Option<String>,
86 pub(crate) query: Vec<(String, String)>,
87 pub(crate) headers: HeaderMap,
88 pub(crate) auth: Option<Value>,
89 pub(crate) auth_fn: Option<AuthFn>,
90 pub(crate) params_fn: Option<ParamsFn>,
91 pub(crate) proxy: ProxyChoice,
93 pub(crate) http: Option<crate::engineio::http::Http>,
95 #[cfg_attr(not(any(feature = "rustls", feature = "native-tls")), allow(dead_code))]
96 pub(crate) tls_config: Option<TlsConfig>,
97 pub(crate) transport: TransportType,
98 pub(crate) timeout: Duration,
99 pub(crate) reconnection: bool,
100 pub(crate) reconnection_attempts: Option<u32>,
101 pub(crate) reconnection_delay: Duration,
102 pub(crate) reconnection_delay_max: Duration,
103 pub(crate) randomization_factor: f64,
104 pub(crate) reconnect_on_disconnect: bool,
105 pub(crate) buffer_while_disconnected: bool,
106 pub(crate) redact_query: bool,
107 pub(crate) inspector: Option<Inspector>,
108}
109
110impl fmt::Debug for Config {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 f.debug_struct("Config")
113 .field("path", &self.path)
114 .field("namespace", &self.namespace)
115 .field(
116 "query_keys",
117 &self.query.iter().map(|(k, _)| k).collect::<Vec<_>>(),
118 )
119 .field("auth", &self.auth.as_ref().map(|_| "***"))
120 .field("transport", &self.transport)
121 .field("timeout", &self.timeout)
122 .field("reconnection", &self.reconnection)
123 .field("reconnection_attempts", &self.reconnection_attempts)
124 .field("reconnection_delay", &self.reconnection_delay)
125 .field("reconnection_delay_max", &self.reconnection_delay_max)
126 .field("randomization_factor", &self.randomization_factor)
127 .field("reconnect_on_disconnect", &self.reconnect_on_disconnect)
128 .field("buffer_while_disconnected", &self.buffer_while_disconnected)
129 .field("proxy", &!matches!(self.proxy, ProxyChoice::Env))
130 .finish_non_exhaustive()
131 }
132}
133
134pub struct ClientBuilder {
157 pub(crate) config: Config,
158 pub(crate) handlers: Handlers,
159 raw_headers: Vec<(String, String)>,
160}
161
162impl fmt::Debug for ClientBuilder {
163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 f.debug_struct("ClientBuilder")
165 .field("config", &self.config)
166 .field("handlers", &self.handlers)
167 .field(
168 "headers",
169 &self.raw_headers.iter().map(|(k, _)| k).collect::<Vec<_>>(),
170 )
171 .finish()
172 }
173}
174
175impl ClientBuilder {
176 pub fn new(address: impl Into<String>) -> Self {
181 ClientBuilder {
182 config: Config {
183 address: address.into(),
184 path: "/socket.io/".to_owned(),
185 namespace: None,
186 query: Vec::new(),
187 headers: HeaderMap::new(),
188 auth: None,
189 auth_fn: None,
190 params_fn: None,
191 proxy: ProxyChoice::Env,
192 http: None,
193 tls_config: None,
194 transport: TransportType::Any,
195 timeout: Duration::from_secs(20),
196 reconnection: true,
197 reconnection_attempts: None,
198 reconnection_delay: Duration::from_millis(1000),
199 reconnection_delay_max: Duration::from_millis(5000),
200 randomization_factor: DEFAULT_JITTER,
201 reconnect_on_disconnect: false,
202 buffer_while_disconnected: false,
203 redact_query: true,
204 inspector: None,
205 },
206 handlers: Handlers::default(),
207 raw_headers: Vec::new(),
208 }
209 }
210
211 pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
213 let mut nsp = namespace.into();
214 if !nsp.starts_with('/') {
215 nsp.insert(0, '/');
216 }
217 self.config.namespace = Some(nsp);
218 self
219 }
220
221 pub fn path(mut self, path: impl Into<String>) -> Self {
223 let mut path = path.into();
224 if !path.starts_with('/') {
225 path.insert(0, '/');
226 }
227 if !path.ends_with('/') {
228 path.push('/');
229 }
230 self.config.path = path;
231 self
232 }
233
234 pub fn query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
238 self.config.query.push((key.into(), value.into()));
239 self
240 }
241
242 pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
245 self.raw_headers.push((key.into(), value.into()));
246 self
247 }
248
249 pub fn auth(mut self, auth: impl Into<Value>) -> Self {
253 self.config.auth = Some(auth.into());
254 self
255 }
256
257 pub fn auth_with<F, Fut>(mut self, auth: F) -> Self
260 where
261 F: Fn() -> Fut + Send + Sync + 'static,
262 Fut: Future<Output = Value> + Send + 'static,
263 {
264 self.config.auth_fn = Some(Arc::new(move || auth().boxed()));
265 self
266 }
267
268 pub fn connect_params_with<F, Fut>(mut self, params: F) -> Self
272 where
273 F: Fn() -> Fut + Send + Sync + 'static,
274 Fut: Future<Output = ConnectParams> + Send + 'static,
275 {
276 self.config.params_fn = Some(Arc::new(move || params().boxed()));
277 self
278 }
279
280 #[cfg(any(feature = "rustls", feature = "native-tls"))]
283 #[cfg_attr(docsrs, doc(cfg(any(feature = "rustls", feature = "native-tls"))))]
284 pub fn tls_config(mut self, tls_config: impl Into<TlsConfig>) -> Self {
285 self.config.tls_config = Some(tls_config.into());
286 self
287 }
288
289 pub fn proxy(mut self, proxy: impl Into<String>) -> Self {
294 self.config.proxy = ProxyChoice::Url(proxy.into());
295 self
296 }
297
298 pub fn no_proxy(mut self) -> Self {
303 self.config.proxy = ProxyChoice::Off;
304 self
305 }
306
307 pub fn transport_type(mut self, transport: TransportType) -> Self {
310 self.config.transport = transport;
311 self
312 }
313
314 pub fn timeout(mut self, timeout: Duration) -> Self {
317 self.config.timeout = timeout;
318 self
319 }
320
321 pub fn reconnection(mut self, reconnection: bool) -> Self {
323 self.config.reconnection = reconnection;
324 self
325 }
326
327 pub fn reconnection_attempts(mut self, attempts: u32) -> Self {
331 self.config.reconnection_attempts = Some(attempts);
332 self
333 }
334
335 pub fn reconnection_delay(mut self, delay: Duration) -> Self {
339 self.config.reconnection_delay = delay;
340 self
341 }
342
343 pub fn reconnection_delay_max(mut self, delay: Duration) -> Self {
345 self.config.reconnection_delay_max = delay;
346 self
347 }
348
349 pub fn randomization_factor(mut self, factor: f64) -> Self {
352 self.config.randomization_factor = factor;
353 self
354 }
355
356 pub fn reconnect_on_disconnect(mut self, reconnect: bool) -> Self {
359 self.config.reconnect_on_disconnect = reconnect;
360 self
361 }
362
363 pub fn buffer_while_disconnected(mut self, buffer: bool) -> Self {
367 self.config.buffer_while_disconnected = buffer;
368 self
369 }
370
371 pub fn redact_query(mut self, redact: bool) -> Self {
374 self.config.redact_query = redact;
375 self
376 }
377
378 pub fn inspect_packets<F>(mut self, inspector: F) -> Self
381 where
382 F: Fn(Direction, &Packet) + Send + Sync + 'static,
383 {
384 self.config.inspector = Some(Arc::new(inspector));
385 self
386 }
387
388 pub fn on<M>(mut self, event: impl Into<String>, handler: impl Handler<Event, M>) -> Self {
390 self.handlers.on(event.into(), handler.into_boxed(), false);
391 self
392 }
393
394 pub fn once<M>(mut self, event: impl Into<String>, handler: impl Handler<Event, M>) -> Self {
396 self.handlers.on(event.into(), handler.into_boxed(), true);
397 self
398 }
399
400 pub fn on_any<M>(mut self, handler: impl Handler<Event, M>) -> Self {
402 self.handlers.on_any(handler.into_boxed());
403 self
404 }
405
406 pub fn on_state_change<M>(mut self, handler: impl Handler<ConnectionState, M>) -> Self {
408 self.handlers.on_state(handler.into_boxed());
409 self
410 }
411
412 pub fn engine_url(&self) -> Result<url::Url> {
417 Ok(crate::client::resolve(&self.config)?.0)
418 }
419
420 pub async fn connect(mut self) -> Result<Client> {
423 if self.config.auth.as_ref().is_some_and(|a| !a.is_object()) {
424 return Err(Error::InvalidAuth("the auth payload must be a JSON object"));
425 }
426 for (key, value) in std::mem::take(&mut self.raw_headers) {
427 let name = HeaderName::try_from(key.as_str())
428 .map_err(|_| Error::InvalidHeader(format!("bad header name {key:?}")))?;
429 let value = HeaderValue::try_from(value.as_str())
430 .map_err(|_| Error::InvalidHeader(format!("bad value for header {key:?}")))?;
431 self.config.headers.append(name, value);
432 }
433 use crate::engineio::http::ProxyMode;
434 let proxy = match &self.config.proxy {
435 ProxyChoice::Url(proxy) => {
436 ProxyMode::Explicit(url::Url::parse(proxy).map_err(|_| {
437 crate::engineio::Error::ProxyFailed("the proxy is not a valid URL".into())
438 })?)
439 }
440 ProxyChoice::Env => ProxyMode::Env,
441 ProxyChoice::Off => ProxyMode::Off,
442 };
443 self.config.http = Some(crate::engineio::http::Http::new(
444 self.config.tls_config.as_ref(),
445 proxy,
446 )?);
447 crate::client::connect(self.config, self.handlers).await
448 }
449}