socketio-next 0.2.0

Socket.IO v4 / Engine.IO v4 client with socket.io-client 4.8 parity: async (tokio) and blocking, rustls or native-tls
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
use std::future::Future;
use std::time::Duration;

use bytes::Bytes;
use futures_util::{Stream, StreamExt};
use http::HeaderMap;
use url::Url;

use crate::engineio::callback::{Callbacks, boxed};
use crate::engineio::error::Result;
use crate::engineio::http::Http;
use crate::engineio::socket::Socket as InnerSocket;
use crate::engineio::tls::{self, TlsConfig};
use crate::engineio::transport::Frame;
use crate::engineio::transports::{PollingTransport, WebsocketTransport};
use crate::engineio::{
    Client, DEFAULT_TIMEOUT, ENGINE_IO_VERSION, Error, HandshakePacket, Packet, PacketId,
};
use crate::protocol::engineio::Batch;

/// Configures and opens an engine.io [`Client`].
///
/// `build*` performs the handshake; [`Client::connect`] then starts the session.
#[derive(Clone)]
pub struct ClientBuilder {
    url: Url,
    tls_config: Option<TlsConfig>,
    headers: Option<HeaderMap>,
    timeout: Duration,
    handshake: Option<HandshakePacket>,
    /// Packets the handshake response carried after the open packet (python-engineio sends
    /// what the server's connect handler emitted in the same body).
    pending: Vec<Packet>,
    callbacks: Callbacks,
    /// Shared by every transport this builder opens (built on first use).
    http: Option<Http>,
}

impl std::fmt::Debug for ClientBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // query values and header values may be secrets
        f.debug_struct("ClientBuilder")
            .field("url", &crate::redact::url(&self.url, true))
            .field(
                "headers",
                &self
                    .headers
                    .iter()
                    .flat_map(|h| h.keys())
                    .map(|k| k.as_str())
                    .collect::<Vec<_>>(),
            )
            .field("tls_config", &self.tls_config)
            .field("timeout", &self.timeout)
            .field("handshake", &self.handshake.is_some())
            .field("callbacks", &self.callbacks)
            .finish()
    }
}

/// Query keys engine.io itself sets.
const RESERVED_QUERY: [&str; 5] = ["EIO", "transport", "sid", "t", "b64"];

impl ClientBuilder {
    /// A builder for `url`. `EIO=4` is added to the query; an empty path becomes `/engine.io/`.
    /// The engine.io parameters (`EIO`, `transport`, `sid`, `t`, `b64`) are the client's own: a
    /// caller's values for them are dropped, as engine.io-client overrides them.
    pub fn new(url: Url) -> Self {
        let mut url = url;
        let user: Vec<(String, String)> = url
            .query_pairs()
            .filter(|(k, _)| !RESERVED_QUERY.contains(&k.as_ref()))
            .map(|(k, v)| (k.into_owned(), v.into_owned()))
            .collect();
        url.set_query(None);
        url.query_pairs_mut()
            .extend_pairs(user)
            .append_pair("EIO", &ENGINE_IO_VERSION.to_string());
        if url.path() == "/" {
            url.set_path("/engine.io/");
        }
        ClientBuilder {
            url,
            headers: None,
            tls_config: None,
            timeout: DEFAULT_TIMEOUT,
            handshake: None,
            pending: Vec::new(),
            callbacks: Callbacks::default(),
            http: None,
        }
    }

    /// The HTTP client (pool, cookie jar) and proxy of the socket.io client.
    pub(crate) fn http(mut self, http: Http) -> Self {
        self.http = Some(http);
        self
    }

    fn http_settings(&mut self) -> Result<Http> {
        if self.http.is_none() {
            self.http = Some(Http::new(
                self.tls_config.as_ref(),
                crate::engineio::http::ProxyMode::Env,
            )?);
        }
        Ok(self.http.clone().expect("set above"))
    }

    /// TLS configuration for `https`/`wss` (default: the backend's default roots).
    #[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.tls_config = Some(tls_config.into());
        self
    }

    /// HTTP headers for every polling request and the websocket handshake.
    pub fn headers(mut self, headers: HeaderMap) -> Self {
        self.headers = Some(headers);
        self
    }

    /// Bound for the handshake and the websocket connect (default 20 s).
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Called when the session closes (server close packet or [`Client::disconnect`]).
    pub fn on_close<F, Fut>(mut self, callback: F) -> Self
    where
        F: Fn(()) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.callbacks.on_close = Some(boxed(callback));
        self
    }

    /// Called with the data of every message packet.
    pub fn on_data<F, Fut>(mut self, callback: F) -> Self
    where
        F: Fn(Bytes) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.callbacks.on_data = Some(boxed(callback));
        self
    }

    /// Called with the text of every send error.
    pub fn on_error<F, Fut>(mut self, callback: F) -> Self
    where
        F: Fn(String) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.callbacks.on_error = Some(boxed(callback));
        self
    }

    /// Called when [`Client::connect`] opens the session.
    pub fn on_open<F, Fut>(mut self, callback: F) -> Self
    where
        F: Fn(()) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.callbacks.on_open = Some(boxed(callback));
        self
    }

    /// Called with every received packet.
    pub fn on_packet<F, Fut>(mut self, callback: F) -> Self
    where
        F: Fn(Packet) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.callbacks.on_packet = Some(boxed(callback));
        self
    }

    /// Reads the open packet from `transport` and adds the sid to the URL.
    async fn handshake_with_transport<T, I>(&mut self, transport: &mut T) -> Result<()>
    where
        T: Stream<Item = Result<I>> + Unpin,
        I: Into<Frame>,
    {
        if self.handshake.is_some() {
            return Ok(());
        }
        let first = transport.next().await.ok_or_else(|| {
            Error::InvalidHandshake("the connection closed before the open packet".into())
        })??;
        let handshake = match first.into() {
            Frame::Text(bytes) => {
                let (handshake, pending) = parse_handshake(bytes)?;
                self.pending = pending;
                handshake
            }
            Frame::Binary(_) => {
                return Err(Error::InvalidHandshake(
                    "binary frame instead of the open packet".into(),
                ));
            }
        };
        self.url
            .query_pairs_mut()
            .append_pair("sid", &handshake.sid);
        tracing::debug!(
            sid = %handshake.sid,
            upgrades = ?handshake.upgrades,
            ping_interval_ms = handshake.ping_interval,
            ping_timeout_ms = handshake.ping_timeout,
            max_payload = handshake.max_payload,
            "engine.io handshake"
        );
        self.handshake = Some(handshake);
        Ok(())
    }

    async fn handshake(&mut self) -> Result<()> {
        if self.handshake.is_some() {
            return Ok(());
        }
        tls::check_scheme(&self.url)?;
        let http = self.http_settings()?;
        let mut transport = PollingTransport::with_client(
            self.url.clone(),
            &http,
            self.headers.clone().unwrap_or_default(),
            Some(self.timeout),
        )?;
        self.handshake_with_transport(&mut transport).await
    }

    /// Polling handshake, then a websocket upgrade when the server offers one; when the upgrade
    /// fails (a proxy that drops `Upgrade:`), the session stays on polling, like
    /// engine.io-client.
    pub async fn build(mut self) -> Result<Client> {
        self.handshake().await?;
        if self.websocket_upgrade() {
            match self.clone().build_websocket_with_upgrade().await {
                Ok(client) => return Ok(client),
                Err(err) => {
                    tracing::debug!(error = %err, "websocket upgrade failed, staying on polling");
                }
            }
        }
        self.build_polling().await
    }

    /// Polling only.
    pub async fn build_polling(mut self) -> Result<Client> {
        self.handshake().await?;
        let handshake = self
            .handshake
            .take()
            .ok_or(Error::InvalidHandshake("missing".into()))?;

        // A long-poll GET is answered at least once per ping interval; a request still open after
        // the ping deadline belongs to a dead connection.
        let request_timeout = Duration::from_millis(
            handshake
                .ping_interval
                .saturating_add(handshake.ping_timeout),
        );
        let http = self.http_settings()?;
        let transport = PollingTransport::with_client(
            self.url,
            &http,
            self.headers.unwrap_or_default(),
            Some(request_timeout),
        )?;
        tracing::debug!(transport = "polling", "engine.io transport chosen");
        Ok(Client::new(InnerSocket::new(
            transport.into(),
            handshake,
            self.callbacks,
            self.pending,
        )))
    }

    /// Polling handshake, then the websocket upgrade; fails when the server offers none.
    pub async fn build_websocket_with_upgrade(mut self) -> Result<Client> {
        self.handshake().await?;
        if self.websocket_upgrade() {
            self.build_websocket().await
        } else {
            Err(Error::UpgradeUnavailable)
        }
    }

    /// Websocket only: the handshake runs over the websocket, or (after a polling handshake)
    /// the upgrade probe does. Bounded by the timeout: a blackholed websocket (a proxy that
    /// accepts TCP and drops the upgrade) would otherwise hang and `build_with_fallback` would
    /// never fall back to polling.
    pub async fn build_websocket(mut self) -> Result<Client> {
        let timeout = self.timeout;
        let connect = async move {
            let http = self.http_settings()?;
            let headers = http.with_cookies(&self.headers.clone().unwrap_or_default(), &self.url);
            let mut transport = WebsocketTransport::connect(
                self.url.clone(),
                self.tls_config.clone(),
                Some(headers),
                http.ws_route(&self.url)?,
            )
            .await?;
            if self.handshake.is_some() {
                transport.upgrade().await?;
                tracing::debug!(transport = "websocket", "engine.io upgraded");
            } else {
                self.handshake_with_transport(&mut transport).await?;
                tracing::debug!(transport = "websocket", "engine.io transport chosen");
            }
            let handshake = self
                .handshake
                .ok_or(Error::InvalidHandshake("missing".into()))?;
            Ok(Client::new(InnerSocket::new(
                transport.into(),
                handshake,
                self.callbacks,
                self.pending,
            )))
        };
        tokio::time::timeout(timeout, connect)
            .await
            .map_err(|_| Error::Timeout(timeout))?
    }

    /// Polling handshake, then the websocket upgrade within half the timeout; when the upgrade
    /// fails (blocked or blackholed websocket) the session stays on polling with the same sid,
    /// as engine.io-client does after a failed probe.
    pub async fn build_with_fallback(mut self) -> Result<Client> {
        self.handshake().await?;
        if self.websocket_upgrade() {
            let mut upgrade = self.clone();
            upgrade.timeout = self.timeout / 2;
            match upgrade.build_websocket().await {
                Ok(client) => return Ok(client),
                Err(err) => {
                    tracing::debug!(error = %err, "websocket upgrade failed, staying on polling");
                }
            }
        }
        self.build_polling().await
    }

    fn websocket_upgrade(&self) -> bool {
        self.handshake.as_ref().is_some_and(|handshake| {
            handshake
                .upgrades
                .iter()
                .any(|upgrade| upgrade.eq_ignore_ascii_case("websocket"))
        })
    }
}

/// The open packet: `0{"sid":..}`, and the packets a polling handshake body carried after it
/// (decoded as a payload, as engine.io-client does). Anything else (an Engine.IO v3
/// `96:0{..}` length-prefixed payload, a proxy error page) is an invalid handshake with a hint.
fn parse_handshake(body: Bytes) -> Result<(HandshakePacket, Vec<Packet>)> {
    let (bytes, rest) = match body.iter().position(|&b| b == Batch::SEPARATOR as u8) {
        Some(at) => (body.slice(..at), Some(body.slice(at + 1..))),
        None => (body.clone(), None),
    };
    let hint = || {
        let head = String::from_utf8_lossy(&bytes[..bytes.len().min(32)]).into_owned();
        let v3 = head
            .split_once(':')
            .is_some_and(|(len, _)| len.bytes().all(|b| b.is_ascii_digit()));
        if v3 {
            format!(
                "{head:?}: looks like an Engine.IO v3 server (socket.io 2.x); this client needs v4 (socket.io 3+)"
            )
        } else {
            format!("expected an open packet `0{{...}}`, got {head:?}")
        }
    };
    let packet = Packet::try_from(bytes.clone()).map_err(|_| Error::InvalidHandshake(hint()))?;
    if packet.packet_id != PacketId::Open {
        return Err(Error::InvalidHandshake(hint()));
    }
    let handshake =
        HandshakePacket::try_from(packet).map_err(|e| Error::InvalidHandshake(e.to_string()))?;
    let pending = match rest {
        Some(rest) => Batch::try_from(rest)?.into_iter().collect(),
        None => Vec::new(),
    };
    Ok((handshake, pending))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn handshake_errors_explain() {
        let err = parse_handshake(Bytes::from_static(b"96:0{\"sid\":\"x\"}")).unwrap_err();
        assert!(err.to_string().contains("Engine.IO v3"), "{err}");
        let err = parse_handshake(Bytes::from_static(b"<html>")).unwrap_err();
        assert!(err.to_string().contains("expected an open packet"), "{err}");
        let ok = parse_handshake(Bytes::from_static(
            b"0{\"sid\":\"a\",\"upgrades\":[\"websocket\"],\"pingInterval\":25000,\"pingTimeout\":20000,\"maxPayload\":1000000}",
        ))
        .unwrap();
        assert_eq!(
            (ok.0.sid.as_str(), ok.0.max_payload),
            ("a", Some(1_000_000))
        );
        assert!(ok.1.is_empty());
        // python-engineio: what the connect handler sent comes in the handshake body
        let (open, rest) = parse_handshake(Bytes::from_static(
            b"0{\"sid\":\"a\",\"upgrades\":[],\"pingInterval\":25000,\"pingTimeout\":20000}\x1e4hello\x1ebAQI=",
        ))
        .unwrap();
        assert_eq!(open.sid, "a");
        assert_eq!(
            rest,
            [
                Packet::new(PacketId::Message, Bytes::from_static(b"hello")),
                Packet::new(PacketId::MessageBinary, Bytes::from_static(&[1, 2])),
            ]
        );
    }
}