eioc 0.3.1

Async Engine.IO client implementation for Sioc
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! Engine.IO packet types.

use std::time::Duration;

use crate::error::PacketError;
use bytes::Bytes;
use bytestring::ByteString;
use serde::Deserialize;

/// Payload sent in the WebSocket upgrade probe ping and expected in the pong reply.
pub const PROBE: ByteString = ByteString::from_static("probe");

/// Content exchanged between the Socket.IO and Engine.IO layers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Message {
    /// A UTF-8 text payload.
    Text(ByteString),
    /// A raw binary payload.
    Binary(Bytes),
    /// Signals a clean connection close.
    Close,
}

impl std::fmt::Display for Message {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Text(s) => f.debug_tuple("Text").field(&format_args!("{s}")).finish(),
            Self::Binary(b) => f.debug_struct("Binary").field("len", &b.len()).finish(),
            Self::Close => f.write_str("Close"),
        }
    }
}

/// A wire-level frame exchanged with the transport layer.
///
/// [`Frame::Packet`] carries a fully-encoded Engine.IO text packet (e.g. `"4hello"`).
/// [`Frame::Binary`] carries a raw binary payload with no packet-type prefix.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Frame {
    /// A UTF-8 text frame (contains a complete Engine.IO packet).
    Packet(Packet),
    /// A raw binary frame.
    Binary(Bytes),
}

impl From<Packet> for Frame {
    fn from(packet: Packet) -> Self {
        Frame::Packet(packet)
    }
}

impl From<Bytes> for Frame {
    fn from(bytes: Bytes) -> Self {
        Frame::Binary(bytes)
    }
}

/// Data exchanged in the Engine.IO v4 handshake (the `open` packet payload).
///
/// # Wire format
///
/// ```json
/// {
///   "sid": "lv_VI97HAXpY6yYWAAAC",
///   "upgrades": ["websocket"],
///   "pingInterval": 25000,
///   "pingTimeout": 20000,
///   "maxPayload": 1000000
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Handshake {
    /// Session identifier; sent as the `sid` query parameter in all subsequent requests.
    pub sid: ByteString,

    /// Available transport upgrades (e.g. `["websocket"]`).
    pub upgrades: Vec<ByteString>,

    /// Server ping interval in milliseconds.
    #[serde(rename = "pingInterval")]
    pub ping_interval: u64,

    /// Server ping timeout in milliseconds.
    #[serde(rename = "pingTimeout")]
    pub ping_timeout: u64,

    /// Maximum bytes per chunk, used by the client to aggregate packets into payloads.
    #[serde(rename = "maxPayload")]
    pub max_payload: u64,
}

impl Handshake {
    /// Returns `true` if the server offered a WebSocket upgrade.
    pub fn can_upgrade_to_websocket(&self) -> bool {
        self.upgrades.iter().any(|u| u == "websocket")
    }

    /// Combined `pingInterval + pingTimeout` as a [`Duration`].
    pub fn ping_window(&self) -> Duration {
        Duration::from_millis(self.ping_interval + self.ping_timeout)
    }
}

/// A packet in the Engine.IO v4 protocol.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Packet {
    /// `0`: Handshake data from the server.
    Open(Handshake),
    /// `1`: The transport can be closed.
    Close,
    /// `2`: Heartbeat from the server (client must reply with [`Packet::Pong`]).
    Ping(ByteString),
    /// `3`: Heartbeat reply.
    Pong(ByteString),
    /// `4`: Application-level text data.
    Message(ByteString),
    /// `5`: Sent by the client to finalise a transport upgrade.
    Upgrade,
    /// `6`: Sent by the server to flush a pending long-poll GET during upgrade.
    Noop,
}

impl Packet {
    /// Appends the wire encoding of this packet to `buffer`.
    ///
    /// # Panics
    ///
    /// Panics if called on `Open` or `Noop`, which are server-only packets.
    pub fn write(&self, buffer: &mut String) {
        match self {
            Self::Open(..) => panic!("client should never encode an Open packet"),
            Self::Close => buffer.push('1'),
            Self::Ping(payload) => {
                buffer.reserve(1 + payload.len());
                buffer.push('2');
                buffer.push_str(payload);
            }
            Self::Pong(payload) => {
                buffer.reserve(1 + payload.len());
                buffer.push('3');
                buffer.push_str(payload);
            }
            Self::Message(payload) => {
                buffer.reserve(1 + payload.len());
                buffer.push('4');
                buffer.push_str(payload);
            }
            Self::Upgrade => buffer.push('5'),
            Self::Noop => panic!("client should never encode a Noop packet"),
        }
    }

    /// Encodes this packet into a [`String`].
    pub fn encode(&self) -> String {
        let mut buffer = String::new();
        self.write(&mut buffer);
        buffer
    }

    /// Decodes a single packet from a text frame.
    ///
    /// The first character is the packet-type digit (`'0'`..=`'6'`).
    ///
    /// # Errors
    ///
    /// Returns an error if the byte string is empty, has an unrecognised type ID, or the payload is malformed.
    pub fn decode(bytes: &ByteString) -> Result<Self, PacketError> {
        let mut chars = bytes.chars();

        let Some(id) = chars.next() else {
            return Err(PacketError::Empty);
        };

        let rest = chars.as_str();

        match id {
            '0' => Ok(Packet::Open(serde_json::from_str(rest)?)),
            '1' => {
                if rest.is_empty() {
                    Ok(Packet::Close)
                } else {
                    Err(PacketError::Payload {
                        id: '1',
                        payload: bytes.slice_ref(rest),
                    })
                }
            }
            '2' => Ok(Packet::Ping(bytes.slice_ref(rest))),
            '3' => Ok(Packet::Pong(bytes.slice_ref(rest))),
            '4' => Ok(Packet::Message(bytes.slice_ref(rest))),
            '5' => {
                if rest.is_empty() {
                    Ok(Packet::Upgrade)
                } else {
                    Err(PacketError::Payload {
                        id: '5',
                        payload: bytes.slice_ref(rest),
                    })
                }
            }
            '6' => {
                if rest.is_empty() {
                    Ok(Packet::Noop)
                } else {
                    Err(PacketError::Payload {
                        id: '6',
                        payload: bytes.slice_ref(rest),
                    })
                }
            }
            id => Err(PacketError::InvalidId { id })?,
        }
    }
}

impl std::fmt::Display for Packet {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Open(h) => f
                .debug_tuple("Open")
                .field(&format_args!("{}", h.sid))
                .finish(),
            Self::Close => f.write_str("Close"),
            Self::Ping(s) => f.debug_tuple("Ping").field(&format_args!("{s}")).finish(),
            Self::Pong(s) => f.debug_tuple("Pong").field(&format_args!("{s}")).finish(),
            Self::Message(s) => f
                .debug_tuple("Message")
                .field(&format_args!("{s}"))
                .finish(),
            Self::Upgrade => f.write_str("Upgrade"),
            Self::Noop => f.write_str("Noop"),
        }
    }
}

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

    fn bss(s: &'static str) -> ByteString {
        ByteString::from_static(s)
    }

    fn test_handshake() -> Handshake {
        Handshake {
            sid: "abc".into(),
            upgrades: vec!["websocket".into()],
            ping_interval: 25000,
            ping_timeout: 5000,
            max_payload: 1_000_000,
        }
    }

    #[test]
    fn handshake_missing_required_field_is_error() {
        let json = serde_json::json!({
            "sid": "test-456",
            "upgrades": [],
            "pingInterval": 25000,
            "pingTimeout": 20000
        });
        let bytes = ByteString::from(format!("0{json}"));
        assert!(Packet::decode(&bytes).is_err());
    }

    #[test]
    fn handshake_ping_window() {
        let hs = test_handshake();
        assert_eq!(hs.ping_window(), std::time::Duration::from_secs(30));
    }

    #[test]
    fn decode_invalid_packet_id() {
        assert!(matches!(
            Packet::decode(&bss("9")),
            Err(PacketError::InvalidId { id: '9' })
        ));
    }

    #[test]
    fn decode_empty_packet() {
        assert!(matches!(
            Packet::decode(&ByteString::new()),
            Err(PacketError::Empty)
        ));
    }

    #[test]
    fn decode_open() {
        let hs = test_handshake();
        let json = r#"{"sid":"abc","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000,"maxPayload":1000000}"#;
        let bytes = ByteString::from(format!("0{json}"));
        assert_eq!(Packet::decode(&bytes).unwrap(), Packet::Open(hs));
    }

    #[test]
    fn encode_decode_close_round_trip() {
        let encoded = Packet::Close.encode();
        assert_eq!(
            Packet::decode(&ByteString::from(encoded)).unwrap(),
            Packet::Close
        );
    }

    #[test]
    fn encode_decode_ping_round_trip() {
        let payload = bss("probe");
        let encoded = Packet::Ping(payload.clone()).encode();
        assert_eq!(
            Packet::decode(&ByteString::from(encoded)).unwrap(),
            Packet::Ping(payload)
        );
    }

    #[test]
    fn encode_decode_ping_empty_payload() {
        let encoded = Packet::Ping(ByteString::new()).encode();
        assert_eq!(
            Packet::decode(&ByteString::from(encoded)).unwrap(),
            Packet::Ping(ByteString::new())
        );
    }

    #[test]
    fn encode_decode_pong_round_trip() {
        let payload = bss("probe");
        let encoded = Packet::Pong(payload.clone()).encode();
        assert_eq!(
            Packet::decode(&ByteString::from(encoded)).unwrap(),
            Packet::Pong(payload)
        );
    }

    #[test]
    fn encode_decode_message_round_trip() {
        let text = bss("hello world");
        let encoded = Packet::Message(text.clone()).encode();
        assert_eq!(
            Packet::decode(&ByteString::from(encoded)).unwrap(),
            Packet::Message(text)
        );
    }

    #[test]
    fn encode_decode_upgrade_round_trip() {
        let encoded = Packet::Upgrade.encode();
        assert_eq!(
            Packet::decode(&ByteString::from(encoded)).unwrap(),
            Packet::Upgrade
        );
    }

    #[test]
    fn decode_noop() {
        assert_eq!(Packet::decode(&bss("6")).unwrap(), Packet::Noop);
    }

    #[test]
    fn handshake_can_upgrade_to_websocket_true() {
        let hs = test_handshake();
        assert!(hs.can_upgrade_to_websocket());
    }

    #[test]
    fn handshake_can_upgrade_to_websocket_false() {
        let hs = Handshake {
            sid: "x".into(),
            upgrades: vec![],
            ping_interval: 25000,
            ping_timeout: 5000,
            max_payload: 1_000_000,
        };
        assert!(!hs.can_upgrade_to_websocket());
    }

    #[test]
    fn decode_close_with_payload_is_error() {
        let bytes = bss("1extra");
        assert!(matches!(
            Packet::decode(&bytes),
            Err(crate::error::PacketError::Payload { id: '1', .. })
        ));
    }

    #[test]
    fn decode_upgrade_with_payload_is_error() {
        let bytes = bss("5extra");
        assert!(matches!(
            Packet::decode(&bytes),
            Err(crate::error::PacketError::Payload { id: '5', .. })
        ));
    }

    #[test]
    fn decode_noop_with_payload_is_error() {
        let bytes = bss("6extra");
        assert!(matches!(
            Packet::decode(&bytes),
            Err(crate::error::PacketError::Payload { id: '6', .. })
        ));
    }

    #[test]
    fn message_display_text() {
        let s = format!("{}", Message::Text(bss("hello")));
        assert!(s.contains("hello"));
    }

    #[test]
    fn message_display_binary() {
        let s = format!(
            "{}",
            Message::Binary(bytes::Bytes::from_static(b"\x01\x02"))
        );
        assert!(s.contains('2'));
    }

    #[test]
    fn message_display_close() {
        assert_eq!(format!("{}", Message::Close), "Close");
    }

    #[test]
    fn packet_display_variants() {
        let hs = test_handshake();
        assert!(format!("{}", Packet::Open(hs)).contains("Open"));
        assert_eq!(format!("{}", Packet::Close), "Close");
        assert!(format!("{}", Packet::Ping(bss("probe"))).contains("probe"));
        assert!(format!("{}", Packet::Pong(bss("probe"))).contains("probe"));
        assert!(format!("{}", Packet::Message(bss("hello"))).contains("hello"));
        assert_eq!(format!("{}", Packet::Upgrade), "Upgrade");
        assert_eq!(format!("{}", Packet::Noop), "Noop");
    }

    #[test]
    fn frame_from_conversions() {
        let frame: Frame = Packet::Close.into();
        assert!(matches!(frame, Frame::Packet(Packet::Close)));

        let frame: Frame = bytes::Bytes::from_static(b"\x01").into();
        assert!(matches!(frame, Frame::Binary(_)));
    }

    #[test]
    #[should_panic(expected = "client should never encode an Open packet")]
    fn encode_open_panics() {
        Packet::Open(test_handshake()).encode();
    }

    #[test]
    #[should_panic(expected = "client should never encode a Noop packet")]
    fn encode_noop_panics() {
        Packet::Noop.encode();
    }
}