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