engineioxide 0.17.3

Engine IO server implementation as a Tower Service.
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
//! ## Encoder for http payloads
//!
//! There is 3 different encoders:
//! * engine.io v4 encoder
//! * engine.io v3 encoder:
//!    * string encoder (used when there is no binary packet or when the client does not support binary)
//!    * binary encoder (used when there are binary packets and the client supports binary)
//!

use tokio::sync::MutexGuard;

use crate::{
    errors::Error, packet::Packet, peekable::PeekableReceiver, socket::PacketBuf,
    transport::polling::payload::Payload,
};

/// Try to immediately poll a new packet buf from the rx channel and check that the new packet can be added to the payload
///
/// Manually close the channel if the packet is a close packet
/// It will allow to notify the [`Socket`](crate::socket::Socket) that the session is closed
///
/// ## Arguments
/// * `rx` - The channel to poll
/// * `payload_len` - The current payload length
/// * `max_payload` - The maximum payload length
/// * `b64` - If binary packets should be encoded in base64
fn try_recv_packet(
    rx: &mut MutexGuard<'_, PeekableReceiver<PacketBuf>>,
    payload_len: usize,
    max_payload: u64,
    b64: bool,
) -> Option<PacketBuf> {
    if let Some(packets) = rx.peek() {
        let size = packets.iter().map(|p| p.get_size_hint(b64)).sum::<usize>();
        if (payload_len + size) as u64 > max_payload {
            #[cfg(feature = "tracing")]
            tracing::debug!("payload too big, stopping encoding for this payload");
            return None;
        }
    }

    let packets = rx.try_recv().ok();

    if Some(&Packet::Close) == packets.as_ref().and_then(|p| p.first()) {
        #[cfg(feature = "tracing")]
        tracing::debug!("Received close packet, closing channel");
        rx.try_recv().ok();
        rx.close();
    }

    #[cfg(feature = "tracing")]
    tracing::debug!("sending packet: {:?}", packets);
    packets
}

/// Same as [`try_recv_packet`]
/// but wait for a new packet if there is no packet in the buffer
async fn recv_packet(
    rx: &mut MutexGuard<'_, PeekableReceiver<PacketBuf>>,
) -> Result<PacketBuf, Error> {
    let packet = rx.recv().await.ok_or(Error::Aborted)?;
    if Some(&Packet::Close) == packet.first() {
        #[cfg(feature = "tracing")]
        tracing::debug!("Received close packet, closing channel");
        rx.close();
    }

    #[cfg(feature = "tracing")]
    tracing::debug!("sending packet: {:?}", packet);
    Ok(packet)
}

/// Encode multiple packets into a string payload according to the
/// [engine.io v4 protocol](https://socket.io/fr/docs/v4/engine-io-protocol/#http-long-polling-1)
pub async fn v4_encoder(
    mut rx: MutexGuard<'_, PeekableReceiver<PacketBuf>>,
    max_payload: u64,
) -> Result<Payload, Error> {
    use crate::transport::polling::payload::PACKET_SEPARATOR_V4;

    #[cfg(feature = "tracing")]
    tracing::debug!("encoding payload with v4 encoder");
    let mut data: String = String::new();

    // Send all packets in the buffer
    const PUNCTUATION_LEN: usize = 1;
    while let Some(packets) =
        try_recv_packet(&mut rx, data.len() + PUNCTUATION_LEN, max_payload, true)
    {
        for packet in packets {
            let packet: String = packet.into();

            if !data.is_empty() {
                data.push(std::char::from_u32(PACKET_SEPARATOR_V4 as u32).unwrap());
            }
            data.push_str(&packet);
        }
    }

    // If there is no packet in the buffer, wait for the next packet
    if data.is_empty() {
        let packets = recv_packet(&mut rx).await?;
        for packet in packets {
            let packet: String = packet.into();
            data.push_str(&packet);
        }
    }

    Ok(Payload::new(data.into(), false))
}

/// Encode one packet into a *binary* payload according to the
/// [engine.io v3 protocol](https://github.com/socketio/engine.io-protocol/tree/v3#payload)
#[cfg(feature = "v3")]
pub fn v3_bin_packet_encoder(packet: Packet, data: &mut bytes::BytesMut) {
    use crate::transport::polling::payload::BINARY_PACKET_SEPARATOR_V3;
    use bytes::BufMut;

    let mut itoa = itoa::Buffer::new();
    match packet {
        Packet::BinaryV3(bin) => {
            let len = itoa.format(bin.len() + 1);
            let len_len = len.len(); // len is guaranteed to be ascii

            data.reserve(1 + len_len + 2 + bin.len());

            data.put_u8(0x1); // 1 = binary
            for char in len.chars() {
                data.put_u8(char as u8 - 48);
            }
            data.put_u8(BINARY_PACKET_SEPARATOR_V3); // separator
            data.put_u8(0x04); // message packet type
            data.extend_from_slice(&bin); // raw data
        }
        packet => {
            let packet: String = packet.into();
            let len = itoa.format(packet.len());
            let len_len = len.len(); // len is guaranteed to be ascii

            data.reserve(1 + len_len + 1 + packet.len());

            data.put_u8(0x0); // 0 = string
            for char in len.chars() {
                data.put_u8(char as u8 - 48);
            }
            data.put_u8(BINARY_PACKET_SEPARATOR_V3); // separator
            data.extend_from_slice(packet.as_bytes()); // packet
        }
    };
}

/// Encode one packet into a *string* payload according to the
/// [engine.io v3 protocol](https://github.com/socketio/engine.io-protocol/tree/v3#payload)
#[cfg(feature = "v3")]
pub fn v3_string_packet_encoder(packet: Packet, data: &mut bytes::BytesMut) {
    use crate::transport::polling::payload::STRING_PACKET_SEPARATOR_V3;
    use bytes::BufMut;
    let packet: String = packet.into();
    let packet = format!(
        "{}{}{}",
        packet.chars().count(),
        STRING_PACKET_SEPARATOR_V3 as char,
        packet
    );
    data.put_slice(packet.as_bytes());
}

/// Encode multiple packet packet into a *string* payload if there is no binary packet or into a *binary* payload if there are binary packets
/// according to the [engine.io v3 protocol](https://github.com/socketio/engine.io-protocol/tree/v3#payload)
#[cfg(feature = "v3")]
pub async fn v3_binary_encoder(
    mut rx: MutexGuard<'_, PeekableReceiver<PacketBuf>>,
    max_payload: u64,
) -> Result<Payload, Error> {
    let mut data = bytes::BytesMut::new();
    let mut packet_buffer: Vec<Packet> = Vec::new();

    // estimated size of the `packet_buffer` in bytes
    let mut estimated_size: usize = 0;
    // number of digits of the max packet size, used to approximate the payload size
    let max_packet_size_len = max_payload.checked_ilog10().unwrap_or(0) as usize + 1;

    #[cfg(feature = "tracing")]
    tracing::debug!("encoding payload with v3 binary encoder");
    // buffer all packets to find if there is binary packets
    let mut has_binary = false;

    while let Some(packets) = try_recv_packet(&mut rx, estimated_size, max_payload, false) {
        for packet in packets {
            if packet.is_binary() {
                has_binary = true;
            }

            const PUNCTUATION_LEN: usize = 2;
            estimated_size += packet.get_size_hint(false) + max_packet_size_len + PUNCTUATION_LEN;

            packet_buffer.push(packet);
        }
    }

    if has_binary {
        for packet in packet_buffer {
            v3_bin_packet_encoder(packet, &mut data);
        }
    } else {
        for packet in packet_buffer {
            v3_string_packet_encoder(packet, &mut data);
        }
    }

    // If there is no packet in the buffer, wait for the next packet
    if data.is_empty() {
        let packets = recv_packet(&mut rx).await?;
        for packet in packets {
            match packet {
                Packet::BinaryV3(_) | Packet::Binary(_) => {
                    v3_bin_packet_encoder(packet, &mut data);
                    has_binary = true;
                }
                packet => {
                    v3_string_packet_encoder(packet, &mut data);
                }
            };
        }
    }

    #[cfg(feature = "tracing")]
    tracing::debug!("sending packet: {:?}", &data);
    Ok(Payload::new(data.freeze(), has_binary))
}

/// Encode multiple packet packet into a *string* payload according to the
/// [engine.io v3 protocol](https://github.com/socketio/engine.io-protocol/tree/v3#payload)
#[cfg(feature = "v3")]
pub async fn v3_string_encoder(
    mut rx: MutexGuard<'_, PeekableReceiver<PacketBuf>>,
    max_payload: u64,
) -> Result<Payload, Error> {
    let mut data = bytes::BytesMut::new();

    #[cfg(feature = "tracing")]
    tracing::debug!("encoding payload with v3 string encoder");

    const PUNCTUATION_LEN: usize = 2;
    // number of digits of the max packet size, used to approximate the payload size
    let max_packet_size_len = max_payload.checked_ilog10().unwrap_or(0) as usize + 1;
    // Current size of the payload
    let current_size = data.len() + PUNCTUATION_LEN + max_packet_size_len;
    while let Some(packets) = try_recv_packet(&mut rx, current_size, max_payload, true) {
        for packet in packets {
            v3_string_packet_encoder(packet, &mut data);
        }
    }

    // If there is no packet in the buffer, wait for the next packet
    if data.is_empty() {
        let packets = recv_packet(&mut rx).await?;
        for packet in packets {
            v3_string_packet_encoder(packet, &mut data);
        }
    }

    Ok(Payload::new(data.freeze(), false))
}

#[cfg(test)]
mod tests {
    use bytes::Bytes;
    use tokio::sync::Mutex;

    use PacketBuf;

    use super::*;
    const MAX_PAYLOAD: u64 = 100_000;

    #[tokio::test]
    async fn encode_v4_payload() {
        const PAYLOAD: &str = "4hello€\x1ebAQIDBA==\x1e4hello€";
        let (tx, rx) = tokio::sync::mpsc::channel::<PacketBuf>(10);
        let rx = Mutex::new(PeekableReceiver::new(rx));
        let rx = rx.lock().await;
        tx.try_send(smallvec::smallvec![Packet::Message("hello€".into())])
            .unwrap();
        tx.try_send(smallvec::smallvec![Packet::Binary(Bytes::from_static(&[
            1, 2, 3, 4
        ]))])
        .unwrap();
        tx.try_send(smallvec::smallvec![Packet::Message("hello€".into())])
            .unwrap();
        let Payload { data, .. } = v4_encoder(rx, MAX_PAYLOAD).await.unwrap();
        assert_eq!(data, PAYLOAD.as_bytes());
    }

    #[tokio::test]
    async fn max_payload_v4() {
        const MAX_PAYLOAD: u64 = 10;
        let (tx, rx) = tokio::sync::mpsc::channel::<PacketBuf>(10);
        let mutex = Mutex::new(PeekableReceiver::new(rx));
        tx.try_send(smallvec::smallvec![Packet::Message("hello€".into())])
            .unwrap();
        tx.try_send(smallvec::smallvec![Packet::Binary(Bytes::from_static(&[
            1, 2, 3, 4
        ]))])
        .unwrap();
        tx.try_send(smallvec::smallvec![Packet::Message("hello€".into())])
            .unwrap();
        tx.try_send(smallvec::smallvec![Packet::Message("hello€".into())])
            .unwrap();
        {
            let rx = mutex.lock().await;
            let Payload { data, .. } = v4_encoder(rx, MAX_PAYLOAD).await.unwrap();
            assert_eq!(data, "4hello€".as_bytes());
        }
        {
            let rx = mutex.lock().await;
            let Payload { data, .. } = v4_encoder(rx, MAX_PAYLOAD + 10).await.unwrap();
            assert_eq!(data, "bAQIDBA==\x1e4hello€".as_bytes());
        }
        {
            let rx = mutex.lock().await;
            let Payload { data, .. } = v4_encoder(rx, MAX_PAYLOAD + 10).await.unwrap();
            assert_eq!(data, "4hello€".as_bytes());
        }
    }

    #[cfg(feature = "v3")]
    #[tokio::test]
    async fn encode_v3b64_payload() {
        const PAYLOAD: &str = "7:4hello€10:b4AQIDBA==7:4hello€";
        let (tx, rx) = tokio::sync::mpsc::channel::<PacketBuf>(10);
        let mutex = Mutex::new(PeekableReceiver::new(rx));
        let rx = mutex.lock().await;

        tx.try_send(smallvec::smallvec![Packet::Message("hello€".into())])
            .unwrap();
        tx.try_send(smallvec::smallvec![Packet::BinaryV3(Bytes::from_static(
            &[1, 2, 3, 4]
        ))])
        .unwrap();
        tx.try_send(smallvec::smallvec![Packet::Message("hello€".into())])
            .unwrap();
        let Payload {
            data, has_binary, ..
        } = v3_string_encoder(rx, MAX_PAYLOAD).await.unwrap();
        assert_eq!(data, PAYLOAD.as_bytes());
        assert!(!has_binary);
    }

    #[cfg(feature = "v3")]
    #[tokio::test]
    async fn max_payload_v3_b64() {
        const MAX_PAYLOAD: u64 = 10;

        let (tx, rx) = tokio::sync::mpsc::channel::<PacketBuf>(10);
        let mutex = Mutex::new(PeekableReceiver::new(rx));
        tx.try_send(smallvec::smallvec![Packet::Message("hello€".into())])
            .unwrap();
        tx.try_send(smallvec::smallvec![Packet::BinaryV3(Bytes::from_static(
            &[1, 2, 3, 4]
        ))])
        .unwrap();
        tx.try_send(smallvec::smallvec![Packet::Message("hello€".into())])
            .unwrap();
        tx.try_send(smallvec::smallvec![Packet::Message("hello€".into())])
            .unwrap();
        {
            let rx = mutex.lock().await;
            let Payload { data, .. } = v3_string_encoder(rx, MAX_PAYLOAD).await.unwrap();
            assert_eq!(data, "7:4hello€".as_bytes());
        }
        {
            let rx = mutex.lock().await;
            let Payload { data, .. } = v3_string_encoder(rx, MAX_PAYLOAD + 10).await.unwrap();
            assert_eq!(data, "10:b4AQIDBA==7:4hello€7:4hello€".as_bytes());
        }
    }

    #[cfg(feature = "v3")]
    #[tokio::test]
    async fn encode_v3binary_payload() {
        const PAYLOAD: [u8; 20] = [
            0, 9, 255, 52, 104, 101, 108, 108, 111, 226, 130, 172, 1, 5, 255, 4, 1, 2, 3, 4,
        ];
        let (tx, rx) = tokio::sync::mpsc::channel::<PacketBuf>(10);
        let mutex = Mutex::new(PeekableReceiver::new(rx));
        let rx = mutex.lock().await;

        tx.try_send(smallvec::smallvec![Packet::Message("hello€".into())])
            .unwrap();
        tx.try_send(smallvec::smallvec![Packet::BinaryV3(Bytes::from_static(
            &[1, 2, 3, 4]
        ))])
        .unwrap();
        let Payload {
            data, has_binary, ..
        } = v3_binary_encoder(rx, MAX_PAYLOAD).await.unwrap();
        assert_eq!(*data, PAYLOAD);
        assert!(has_binary);
    }

    #[cfg(feature = "v3")]
    #[tokio::test]
    async fn max_payload_v3_binary() {
        const MAX_PAYLOAD: u64 = 25;

        const PAYLOAD: [u8; 23] = [
            0, 1, 1, 255, 52, 104, 101, 108, 108, 111, 111, 111, 226, 130, 172, 1, 5, 255, 4, 1, 2,
            3, 4,
        ];
        let (tx, rx) = tokio::sync::mpsc::channel::<PacketBuf>(10);
        let mutex = Mutex::new(PeekableReceiver::new(rx));
        tx.try_send(smallvec::smallvec![Packet::Message("hellooo€".into())])
            .unwrap();
        tx.try_send(smallvec::smallvec![Packet::BinaryV3(Bytes::from_static(
            &[1, 2, 3, 4]
        ))])
        .unwrap();
        tx.try_send(smallvec::smallvec![Packet::Message("hello€".into())])
            .unwrap();
        tx.try_send(smallvec::smallvec![Packet::Message("hello€".into())])
            .unwrap();
        {
            let rx = mutex.lock().await;
            let Payload { data, .. } = v3_binary_encoder(rx, MAX_PAYLOAD).await.unwrap();
            assert_eq!(*data, PAYLOAD);
        }
        {
            let rx = mutex.lock().await;
            let Payload { data, .. } = v3_binary_encoder(rx, MAX_PAYLOAD).await.unwrap();
            assert_eq!(data, "7:4hello€7:4hello€".as_bytes());
        }
    }
}