Skip to main content

socketio_next/
builder.rs

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
17/// Called before every CONNECT for the auth payload (socket.io-client `auth` as a function).
18pub(crate) type AuthFn = Arc<dyn Fn() -> BoxFuture<'static, Value> + Send + Sync>;
19
20/// Which way a packet went, for [`ClientBuilder::inspect_packets`].
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22#[non_exhaustive]
23pub enum Direction {
24    /// From the server.
25    Incoming,
26    /// To the server.
27    Outgoing,
28}
29
30pub(crate) type ParamsFn = Arc<dyn Fn() -> BoxFuture<'static, ConnectParams> + Send + Sync>;
31
32/// Query parameters and headers computed for one connect attempt
33/// ([`ClientBuilder::connect_params_with`]). A key given here replaces the builder's value of
34/// the same key for that attempt.
35#[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    /// No parameters.
53    pub fn new() -> Self {
54        ConnectParams::default()
55    }
56
57    /// A query parameter for this attempt.
58    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    /// An HTTP header for this attempt.
64    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/// The proxy setting of a builder.
71#[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/// Everything the connection actor needs; fixed at `connect()`.
81#[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    /// The environment's proxy, an explicit one, or none.
92    pub(crate) proxy: ProxyChoice,
93    /// Built by `connect()`: one HTTP client (pool, cookies) for every attempt.
94    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
134/// Configures a [`Client`]. Defaults follow socket.io-client 4.8.
135///
136/// ```no_run
137/// use std::time::Duration;
138/// use socketio_next::{ClientBuilder, Event, Client};
139/// use serde_json::json;
140///
141/// # async fn run() -> socketio_next::Result<()> {
142/// let client = ClientBuilder::new("http://localhost:4200")
143///     .namespace("/admin")
144///     .query("token", "s3cr3t")
145///     .auth(json!({ "user": "me" }))
146///     .on("chat", |event: Event, _client: Client| async move {
147///         println!("chat: {:?}", event.payload());
148///     })
149///     .connect()
150///     .await?;
151/// client.emit("chat", "hello")?;
152/// let reply = client.emit_with_ack("sum", vec![json!(1), json!(2)], Duration::from_secs(5)).await?;
153/// client.disconnect().await?;
154/// # Ok(()) }
155/// ```
156pub 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    /// A builder for the server at `address` (`http`, `https`, `ws` or `wss`).
177    ///
178    /// Like socket.io-client, the URL path is the **namespace** (`http://host/admin` joins
179    /// `/admin`); the engine.io path is [`path`](Self::path) (default `/socket.io/`).
180    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    /// The namespace to join (overrides the URL path). A missing leading `/` is added.
212    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    /// The engine.io path on the server (socket.io-client `path`, default `/socket.io/`).
222    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    /// Adds a query parameter to every request (socket.io-client `query`). Values are
235    /// percent-encoded and, by default, shown as `***` in logs (see
236    /// [`redact_query`](Self::redact_query)).
237    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    /// Adds an HTTP header to every polling request and the websocket handshake
243    /// (socket.io-client `extraHeaders`). Fails at `connect()` when it is not valid HTTP.
244    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    /// The CONNECT payload (socket.io-client `auth` object), read by the server as
250    /// `socket.handshake.auth`. Must be a JSON object (`connect()` fails with
251    /// [`Error::InvalidAuth`] otherwise).
252    pub fn auth(mut self, auth: impl Into<Value>) -> Self {
253        self.config.auth = Some(auth.into());
254        self
255    }
256
257    /// Computes the CONNECT payload before every connect and reconnect (socket.io-client
258    /// `auth` as a function), e.g. to refresh a token. Overrides [`auth`](Self::auth).
259    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    /// Computes query parameters and headers before every connect and reconnect, e.g. a
269    /// signed timestamp or a fresh bearer token in `Authorization`. Runs inside the attempt's
270    /// timeout; a panic fails the attempt. Values replace the builder's ones of the same key.
271    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    /// TLS for `https`/`wss`: a [`TlsConfig`], a `rustls::ClientConfig` or a
281    /// `native_tls::TlsConnector`. Default: the backend's default roots.
282    #[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    /// Sends polling requests and the websocket through the HTTP proxy `proxy`
290    /// (`http://[user:password@]host:port`; the websocket goes through a `CONNECT` tunnel with
291    /// basic auth from the user info). Without it the environment is used: `HTTPS_PROXY` /
292    /// `HTTP_PROXY` / `ALL_PROXY` and `NO_PROXY`, for polling and websocket alike.
293    pub fn proxy(mut self, proxy: impl Into<String>) -> Self {
294        self.config.proxy = ProxyChoice::Url(proxy.into());
295        self
296    }
297
298    /// No proxy for any transport, whatever `HTTPS_PROXY` / `HTTP_PROXY` say (environment
299    /// proxies apply to `ws://` too; a proxy that refuses `CONNECT` to other ports than 443
300    /// would otherwise break websockets; with `TransportType::Any` the client then stays on
301    /// polling after the failed upgrade).
302    pub fn no_proxy(mut self) -> Self {
303        self.config.proxy = ProxyChoice::Off;
304        self
305    }
306
307    /// Which engine.io transports to use (default: polling, upgraded to websocket, polling when
308    /// the websocket fails).
309    pub fn transport_type(mut self, transport: TransportType) -> Self {
310        self.config.transport = transport;
311        self
312    }
313
314    /// Bound for one connect attempt: engine.io handshake, upgrade and namespace CONNECT
315    /// (socket.io-client `timeout`, default 20 s).
316    pub fn timeout(mut self, timeout: Duration) -> Self {
317        self.config.timeout = timeout;
318        self
319    }
320
321    /// Reconnect after a lost connection (socket.io-client `reconnection`, default on).
322    pub fn reconnection(mut self, reconnection: bool) -> Self {
323        self.config.reconnection = reconnection;
324        self
325    }
326
327    /// At most this many reconnect attempts per outage (socket.io-client
328    /// `reconnectionAttempts`, default unlimited). Then the client closes with
329    /// [`DisconnectReason::ReconnectFailed`](crate::DisconnectReason::ReconnectFailed).
330    pub fn reconnection_attempts(mut self, attempts: u32) -> Self {
331        self.config.reconnection_attempts = Some(attempts);
332        self
333    }
334
335    /// First reconnect delay (socket.io-client `reconnectionDelay`, default 1 s). Attempt `n`
336    /// waits `delay * 2^(n-1)`, randomised, capped by
337    /// [`reconnection_delay_max`](Self::reconnection_delay_max). The first attempt waits too.
338    pub fn reconnection_delay(mut self, delay: Duration) -> Self {
339        self.config.reconnection_delay = delay;
340        self
341    }
342
343    /// Longest reconnect delay (socket.io-client `reconnectionDelayMax`, default 5 s).
344    pub fn reconnection_delay_max(mut self, delay: Duration) -> Self {
345        self.config.reconnection_delay_max = delay;
346        self
347    }
348
349    /// Randomises each delay by up to ± this fraction (socket.io-client `randomizationFactor`,
350    /// default 0.5; 0 disables).
351    pub fn randomization_factor(mut self, factor: f64) -> Self {
352        self.config.randomization_factor = factor;
353        self
354    }
355
356    /// Also reconnect after the server disconnected the socket (socket.io-client does not;
357    /// default off).
358    pub fn reconnect_on_disconnect(mut self, reconnect: bool) -> Self {
359        self.config.reconnect_on_disconnect = reconnect;
360        self
361    }
362
363    /// Queue emits while disconnected and send them after the next connect, like
364    /// socket.io-client's `sendBuffer` (default off: `emit` fails fast with
365    /// [`Error::NotConnected`]). Pending acks keep their timeout.
366    pub fn buffer_while_disconnected(mut self, buffer: bool) -> Self {
367        self.config.buffer_while_disconnected = buffer;
368        self
369    }
370
371    /// Show query values as `***` in logs and `Debug` output (default on; the engine.io
372    /// parameters stay visible). Errors never contain the URL either way.
373    pub fn redact_query(mut self, redact: bool) -> Self {
374        self.config.redact_query = redact;
375        self
376    }
377
378    /// Sees every socket.io packet in and out, after decoding / before encoding. For debugging;
379    /// runs on the connection task, so keep it quick.
380    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    /// Handles `event` (see [`Handler`] for the closure forms).
389    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    /// Handles the next `event` only.
395    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    /// Handles every event (socket.io-client `onAny`), before the event's own handlers.
401    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    /// Sees every [`ConnectionState`] transition, in order with the events.
407    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    /// The engine.io URL `connect()` will use (before `connect_params_with`): the address with
413    /// its path replaced by [`path`](Self::path) (the URL's path is the namespace) and the
414    /// query added, normalized the way the connection normalizes it (`/v1/../x/` is `/x/`).
415    /// For checking where a connection goes, e.g. against an allow-list.
416    pub fn engine_url(&self) -> Result<url::Url> {
417        Ok(crate::client::resolve(&self.config)?.0)
418    }
419
420    /// Connects and joins the namespace. Resolves once the server answered CONNECT; fails with
421    /// the error of this first attempt (no retry: reconnects start after a connection existed).
422    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}