Skip to main content

socketio_next/engineio/
builder.rs

1use std::future::Future;
2use std::time::Duration;
3
4use bytes::Bytes;
5use futures_util::{Stream, StreamExt};
6use http::HeaderMap;
7use url::Url;
8
9use crate::engineio::callback::{Callbacks, boxed};
10use crate::engineio::error::Result;
11use crate::engineio::http::Http;
12use crate::engineio::socket::Socket as InnerSocket;
13use crate::engineio::tls::{self, TlsConfig};
14use crate::engineio::transport::Frame;
15use crate::engineio::transports::{PollingTransport, WebsocketTransport};
16use crate::engineio::{
17    Client, DEFAULT_TIMEOUT, ENGINE_IO_VERSION, Error, HandshakePacket, Packet, PacketId,
18};
19
20/// Configures and opens an engine.io [`Client`].
21///
22/// `build*` performs the handshake; [`Client::connect`] then starts the session.
23#[derive(Clone)]
24pub struct ClientBuilder {
25    url: Url,
26    tls_config: Option<TlsConfig>,
27    headers: Option<HeaderMap>,
28    timeout: Duration,
29    handshake: Option<HandshakePacket>,
30    callbacks: Callbacks,
31    /// Shared by every transport this builder opens (built on first use).
32    http: Option<Http>,
33}
34
35impl std::fmt::Debug for ClientBuilder {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        // query values and header values may be secrets
38        f.debug_struct("ClientBuilder")
39            .field("url", &crate::redact::url(&self.url, true))
40            .field(
41                "headers",
42                &self
43                    .headers
44                    .iter()
45                    .flat_map(|h| h.keys())
46                    .map(|k| k.as_str())
47                    .collect::<Vec<_>>(),
48            )
49            .field("tls_config", &self.tls_config)
50            .field("timeout", &self.timeout)
51            .field("handshake", &self.handshake.is_some())
52            .field("callbacks", &self.callbacks)
53            .finish()
54    }
55}
56
57impl ClientBuilder {
58    /// A builder for `url`. `EIO=4` is added to the query; an empty path becomes `/engine.io/`.
59    pub fn new(url: Url) -> Self {
60        let mut url = url;
61        url.query_pairs_mut()
62            .append_pair("EIO", &ENGINE_IO_VERSION.to_string());
63        if url.path() == "/" {
64            url.set_path("/engine.io/");
65        }
66        ClientBuilder {
67            url,
68            headers: None,
69            tls_config: None,
70            timeout: DEFAULT_TIMEOUT,
71            handshake: None,
72            callbacks: Callbacks::default(),
73            http: None,
74        }
75    }
76
77    /// The HTTP client (pool, cookie jar) and proxy of the socket.io client.
78    pub(crate) fn http(mut self, http: Http) -> Self {
79        self.http = Some(http);
80        self
81    }
82
83    fn http_settings(&mut self) -> Result<Http> {
84        if self.http.is_none() {
85            self.http = Some(Http::new(
86                self.tls_config.as_ref(),
87                crate::engineio::http::ProxyMode::Env,
88            )?);
89        }
90        Ok(self.http.clone().expect("set above"))
91    }
92
93    /// TLS configuration for `https`/`wss` (default: the backend's default roots).
94    #[cfg(any(feature = "rustls", feature = "native-tls"))]
95    #[cfg_attr(docsrs, doc(cfg(any(feature = "rustls", feature = "native-tls"))))]
96    pub fn tls_config(mut self, tls_config: impl Into<TlsConfig>) -> Self {
97        self.tls_config = Some(tls_config.into());
98        self
99    }
100
101    /// HTTP headers for every polling request and the websocket handshake.
102    pub fn headers(mut self, headers: HeaderMap) -> Self {
103        self.headers = Some(headers);
104        self
105    }
106
107    /// Bound for the handshake and the websocket connect (default 20 s).
108    pub fn timeout(mut self, timeout: Duration) -> Self {
109        self.timeout = timeout;
110        self
111    }
112
113    /// Called when the session closes (server close packet or [`Client::disconnect`]).
114    pub fn on_close<F, Fut>(mut self, callback: F) -> Self
115    where
116        F: Fn(()) -> Fut + Send + Sync + 'static,
117        Fut: Future<Output = ()> + Send + 'static,
118    {
119        self.callbacks.on_close = Some(boxed(callback));
120        self
121    }
122
123    /// Called with the data of every message packet.
124    pub fn on_data<F, Fut>(mut self, callback: F) -> Self
125    where
126        F: Fn(Bytes) -> Fut + Send + Sync + 'static,
127        Fut: Future<Output = ()> + Send + 'static,
128    {
129        self.callbacks.on_data = Some(boxed(callback));
130        self
131    }
132
133    /// Called with the text of every send error.
134    pub fn on_error<F, Fut>(mut self, callback: F) -> Self
135    where
136        F: Fn(String) -> Fut + Send + Sync + 'static,
137        Fut: Future<Output = ()> + Send + 'static,
138    {
139        self.callbacks.on_error = Some(boxed(callback));
140        self
141    }
142
143    /// Called when [`Client::connect`] opens the session.
144    pub fn on_open<F, Fut>(mut self, callback: F) -> Self
145    where
146        F: Fn(()) -> Fut + Send + Sync + 'static,
147        Fut: Future<Output = ()> + Send + 'static,
148    {
149        self.callbacks.on_open = Some(boxed(callback));
150        self
151    }
152
153    /// Called with every received packet.
154    pub fn on_packet<F, Fut>(mut self, callback: F) -> Self
155    where
156        F: Fn(Packet) -> Fut + Send + Sync + 'static,
157        Fut: Future<Output = ()> + Send + 'static,
158    {
159        self.callbacks.on_packet = Some(boxed(callback));
160        self
161    }
162
163    /// Reads the open packet from `transport` and adds the sid to the URL.
164    async fn handshake_with_transport<T, I>(&mut self, transport: &mut T) -> Result<()>
165    where
166        T: Stream<Item = Result<I>> + Unpin,
167        I: Into<Frame>,
168    {
169        if self.handshake.is_some() {
170            return Ok(());
171        }
172        let first = transport.next().await.ok_or_else(|| {
173            Error::InvalidHandshake("the connection closed before the open packet".into())
174        })??;
175        let handshake = match first.into() {
176            Frame::Text(bytes) => parse_handshake(bytes)?,
177            Frame::Binary(_) => {
178                return Err(Error::InvalidHandshake(
179                    "binary frame instead of the open packet".into(),
180                ));
181            }
182        };
183        self.url
184            .query_pairs_mut()
185            .append_pair("sid", &handshake.sid);
186        tracing::debug!(
187            sid = %handshake.sid,
188            upgrades = ?handshake.upgrades,
189            ping_interval_ms = handshake.ping_interval,
190            ping_timeout_ms = handshake.ping_timeout,
191            max_payload = handshake.max_payload,
192            "engine.io handshake"
193        );
194        self.handshake = Some(handshake);
195        Ok(())
196    }
197
198    async fn handshake(&mut self) -> Result<()> {
199        if self.handshake.is_some() {
200            return Ok(());
201        }
202        tls::check_scheme(&self.url)?;
203        let http = self.http_settings()?;
204        let mut transport = PollingTransport::with_client(
205            self.url.clone(),
206            &http,
207            self.headers.clone().unwrap_or_default(),
208            Some(self.timeout),
209        )?;
210        self.handshake_with_transport(&mut transport).await
211    }
212
213    /// Polling handshake, then a websocket upgrade when the server offers one.
214    pub async fn build(mut self) -> Result<Client> {
215        self.handshake().await?;
216        if self.websocket_upgrade() {
217            self.build_websocket_with_upgrade().await
218        } else {
219            self.build_polling().await
220        }
221    }
222
223    /// Polling only.
224    pub async fn build_polling(mut self) -> Result<Client> {
225        self.handshake().await?;
226        let handshake = self
227            .handshake
228            .take()
229            .ok_or(Error::InvalidHandshake("missing".into()))?;
230
231        // A long-poll GET is answered at least once per ping interval; a request still open after
232        // the ping deadline belongs to a dead connection.
233        let request_timeout = Duration::from_millis(
234            handshake
235                .ping_interval
236                .saturating_add(handshake.ping_timeout),
237        );
238        let http = self.http_settings()?;
239        let transport = PollingTransport::with_client(
240            self.url,
241            &http,
242            self.headers.unwrap_or_default(),
243            Some(request_timeout),
244        )?;
245        tracing::debug!(transport = "polling", "engine.io transport chosen");
246        Ok(Client::new(InnerSocket::new(
247            transport.into(),
248            handshake,
249            self.callbacks,
250        )))
251    }
252
253    /// Polling handshake, then the websocket upgrade; fails when the server offers none.
254    pub async fn build_websocket_with_upgrade(mut self) -> Result<Client> {
255        self.handshake().await?;
256        if self.websocket_upgrade() {
257            self.build_websocket().await
258        } else {
259            Err(Error::UpgradeUnavailable)
260        }
261    }
262
263    /// Websocket only: the handshake runs over the websocket, or (after a polling handshake)
264    /// the upgrade probe does. Bounded by the timeout: a blackholed websocket (a proxy that
265    /// accepts TCP and drops the upgrade) would otherwise hang and `build_with_fallback` would
266    /// never fall back to polling.
267    pub async fn build_websocket(mut self) -> Result<Client> {
268        let timeout = self.timeout;
269        let connect = async move {
270            let http = self.http_settings()?;
271            let headers = http.with_cookies(&self.headers.clone().unwrap_or_default(), &self.url);
272            let mut transport = WebsocketTransport::connect(
273                self.url.clone(),
274                self.tls_config.clone(),
275                Some(headers),
276                http.ws_route(&self.url)?,
277            )
278            .await?;
279            if self.handshake.is_some() {
280                transport.upgrade().await?;
281                tracing::debug!(transport = "websocket", "engine.io upgraded");
282            } else {
283                self.handshake_with_transport(&mut transport).await?;
284                tracing::debug!(transport = "websocket", "engine.io transport chosen");
285            }
286            let handshake = self
287                .handshake
288                .ok_or(Error::InvalidHandshake("missing".into()))?;
289            Ok(Client::new(InnerSocket::new(
290                transport.into(),
291                handshake,
292                self.callbacks,
293            )))
294        };
295        tokio::time::timeout(timeout, connect)
296            .await
297            .map_err(|_| Error::Timeout(timeout))?
298    }
299
300    /// Polling handshake, then the websocket upgrade within half the timeout; when the upgrade
301    /// fails (blocked or blackholed websocket) the session stays on polling with the same sid,
302    /// as engine.io-client does after a failed probe.
303    pub async fn build_with_fallback(mut self) -> Result<Client> {
304        self.handshake().await?;
305        if self.websocket_upgrade() {
306            let mut upgrade = self.clone();
307            upgrade.timeout = self.timeout / 2;
308            match upgrade.build_websocket().await {
309                Ok(client) => return Ok(client),
310                Err(err) => {
311                    tracing::debug!(error = %err, "websocket upgrade failed, staying on polling");
312                }
313            }
314        }
315        self.build_polling().await
316    }
317
318    fn websocket_upgrade(&self) -> bool {
319        self.handshake.as_ref().is_some_and(|handshake| {
320            handshake
321                .upgrades
322                .iter()
323                .any(|upgrade| upgrade.eq_ignore_ascii_case("websocket"))
324        })
325    }
326}
327
328/// The open packet: `0{"sid":..}`. Anything else (an Engine.IO v3 `96:0{..}` length-prefixed
329/// payload, a proxy error page) is an invalid handshake with a hint.
330fn parse_handshake(bytes: Bytes) -> Result<HandshakePacket> {
331    let hint = || {
332        let head = String::from_utf8_lossy(&bytes[..bytes.len().min(32)]).into_owned();
333        let v3 = head
334            .split_once(':')
335            .is_some_and(|(len, _)| len.bytes().all(|b| b.is_ascii_digit()));
336        if v3 {
337            format!(
338                "{head:?}: looks like an Engine.IO v3 server (socket.io 2.x); this client needs v4 (socket.io 3+)"
339            )
340        } else {
341            format!("expected an open packet `0{{...}}`, got {head:?}")
342        }
343    };
344    let packet = Packet::try_from(bytes.clone()).map_err(|_| Error::InvalidHandshake(hint()))?;
345    if packet.packet_id != PacketId::Open {
346        return Err(Error::InvalidHandshake(hint()));
347    }
348    HandshakePacket::try_from(packet).map_err(|e| Error::InvalidHandshake(e.to_string()))
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354
355    #[test]
356    fn handshake_errors_explain() {
357        let err = parse_handshake(Bytes::from_static(b"96:0{\"sid\":\"x\"}")).unwrap_err();
358        assert!(err.to_string().contains("Engine.IO v3"), "{err}");
359        let err = parse_handshake(Bytes::from_static(b"<html>")).unwrap_err();
360        assert!(err.to_string().contains("expected an open packet"), "{err}");
361        let ok = parse_handshake(Bytes::from_static(
362            b"0{\"sid\":\"a\",\"upgrades\":[\"websocket\"],\"pingInterval\":25000,\"pingTimeout\":20000,\"maxPayload\":1000000}",
363        ))
364        .unwrap();
365        assert_eq!((ok.sid.as_str(), ok.max_payload), ("a", Some(1_000_000)));
366    }
367}