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
use base64::{engine::general_purpose, Engine};
use serde::{de::Error, Deserialize, Serialize};

use crate::sid_generator::Sid;
use crate::socket::DisconnectReason;
use crate::{config::EngineIoConfig, service::TransportType};

/// A Packet type to use when sending data to the client from the public API
///
/// This is a subset of the Packet enum, which is used internally
#[derive(Debug)]
pub enum SendPacket {
    Message(String),
    Binary(Vec<u8>),
    Close(DisconnectReason),
}

/// A Packet type to use when receiving and sending data from the client
#[derive(Debug, PartialEq, PartialOrd)]
pub enum Packet {
    /// Open packet used to initiate a connection
    Open(OpenPacket),
    /// Close packet used to close a connection
    Close,
    /// Ping packet used to check if the connection is still alive
    /// The client never sends this packet, it is only used by the server
    Ping,
    /// Pong packet used to respond to a Ping packet
    /// The server never sends this packet, it is only used by the client
    Pong,

    /// Special Ping packet used to initiate a connection
    PingUpgrade,
    /// Special Pong packet used to respond to a PingUpgrade packet and upgrade the connection
    PongUpgrade,

    /// Message packet used to send a message to the client
    Message(String),
    /// Upgrade packet to upgrade the connection from polling to websocket
    Upgrade,

    /// Noop packet used to send something to a opened polling connection so it gracefully closes to allow the client to upgrade to websocket
    Noop,

    /// Binary packet used to send binary data to the client
    /// Converts to a String using base64 encoding when using polling connection
    /// Or to a websocket binary frame when using websocket connection
    ///
    /// When receiving, it is only used with polling connection, websocket use binary frame
    Binary(Vec<u8>), // Not part of the protocol, used internally

    /// Binary packet used to send binary data to the client
    /// Converts to a String using base64 encoding when using polling connection
    /// Or to a websocket binary frame when using websocket connection
    ///
    /// When receiving, it is only used with polling connection, websocket use binary frame
    ///
    /// This is a special packet, excepionally specific to the V3 protocol.
    BinaryV3(Vec<u8>), // Not part of the protocol, used internally
}

impl Packet {
    /// Check if the packet is a binary packet
    pub fn is_binary(&self) -> bool {
        matches!(self, Packet::Binary(_) | Packet::BinaryV3(_))
    }
}

/// Serialize a [Packet] to a [String] according to the Engine.IO protocol
impl TryInto<String> for Packet {
    type Error = crate::errors::Error;
    fn try_into(self) -> Result<String, Self::Error> {
        let res = match self {
            Packet::Open(open) => {
                "0".to_string() + &serde_json::to_string(&open).map_err(Self::Error::from)?
            }
            Packet::Close => "1".to_string(),
            Packet::Ping => "2".to_string(),
            Packet::Pong => "3".to_string(),
            Packet::PingUpgrade => "2probe".to_string(),
            Packet::PongUpgrade => "3probe".to_string(),
            Packet::Message(msg) => "4".to_string() + &msg,
            Packet::Upgrade => "5".to_string(),
            Packet::Noop => "6".to_string(),
            Packet::Binary(data) => "b".to_string() + &general_purpose::STANDARD.encode(data),
            Packet::BinaryV3(data) => "b4".to_string() + &general_purpose::STANDARD.encode(data),
        };
        Ok(res)
    }
}
/// Deserialize a [Packet] from a [String] according to the Engine.IO protocol
impl TryFrom<&str> for Packet {
    type Error = crate::errors::Error;
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let mut chars = value.chars();
        let packet_type = chars
            .next()
            .ok_or_else(|| serde_json::Error::custom("Packet type not found in packet string"))?;
        let packet_data = chars.as_str();
        let is_upgrade = packet_data.starts_with("probe");
        let res = match packet_type {
            '0' => Packet::Open(serde_json::from_str(packet_data)?),
            '1' => Packet::Close,
            '2' => {
                if is_upgrade {
                    Packet::PingUpgrade
                } else {
                    Packet::Ping
                }
            }
            '3' => {
                if is_upgrade {
                    Packet::PongUpgrade
                } else {
                    Packet::Pong
                }
            }
            '4' => Packet::Message(packet_data.to_string()),
            '5' => Packet::Upgrade,
            '6' => Packet::Noop,
            'b' if value.starts_with("b4") => {
                Packet::BinaryV3(general_purpose::STANDARD.decode(packet_data[1..].as_bytes())?)
            }
            'b' => Packet::Binary(general_purpose::STANDARD.decode(packet_data.as_bytes())?),
            c => Err(serde_json::Error::custom(
                "Invalid packet type ".to_string() + &c.to_string(),
            ))?,
        };
        Ok(res)
    }
}

impl TryFrom<String> for Packet {
    type Error = crate::errors::Error;
    fn try_from(value: String) -> Result<Self, Self::Error> {
        Packet::try_from(value.as_str())
    }
}

/// Convert a [`SendPacket`] (used in the public API) to an internal [`Packet`]
impl From<SendPacket> for Packet {
    fn from(value: SendPacket) -> Packet {
        match value {
            SendPacket::Message(msg) => Packet::Message(msg),
            SendPacket::Binary(data) => Packet::Binary(data),
            SendPacket::Close(_) => Packet::Close,
        }
    }
}

/// An OpenPacket is used to initiate a connection
#[derive(Debug, Serialize, Deserialize, PartialEq, PartialOrd)]
#[serde(rename_all = "camelCase")]
pub struct OpenPacket {
    sid: String,
    upgrades: Vec<String>,
    ping_interval: u64,
    ping_timeout: u64,
    max_payload: u64,
}

impl OpenPacket {
    /// Create a new [OpenPacket]
    /// If the current transport is polling, the server will always allow the client to upgrade to websocket
    pub fn new(transport: TransportType, sid: Sid, config: &EngineIoConfig) -> Self {
        let upgrades = if transport == TransportType::Polling {
            vec!["websocket".to_string()]
        } else {
            vec![]
        };
        OpenPacket {
            sid: sid.to_string(),
            upgrades,
            ping_interval: config.ping_interval.as_millis() as u64,
            ping_timeout: config.ping_timeout.as_millis() as u64,
            max_payload: config.max_payload,
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::config::EngineIoConfig;

    use super::*;
    use std::convert::TryInto;

    #[test]
    fn test_open_packet() {
        let packet = Packet::Open(OpenPacket::new(
            TransportType::Polling,
            1i64.into(),
            &EngineIoConfig::default(),
        ));
        let packet_str: String = packet.try_into().unwrap();
        assert_eq!(packet_str, "0{\"sid\":\"AAAAAAAAAAE\",\"upgrades\":[\"websocket\"],\"pingInterval\":25000,\"pingTimeout\":20000,\"maxPayload\":100000}");
    }

    #[test]
    fn test_open_packet_deserialize() {
        let packet_str = "0{\"sid\":\"1\",\"upgrades\":[\"websocket\"],\"pingInterval\":25000,\"pingTimeout\":20000,\"maxPayload\":100000}";
        let packet = Packet::try_from(packet_str.to_string()).unwrap();
        assert_eq!(
            packet,
            Packet::Open(OpenPacket {
                sid: "1".to_string(),
                upgrades: vec!["websocket".to_string()],
                ping_interval: 25000,
                ping_timeout: 20000,
                max_payload: 1e5 as u64,
            })
        );
    }

    #[test]
    fn test_message_packet() {
        let packet = Packet::Message("hello".to_string());
        let packet_str: String = packet.try_into().unwrap();
        assert_eq!(packet_str, "4hello");
    }

    #[test]
    fn test_message_packet_deserialize() {
        let packet_str = "4hello".to_string();
        let packet: Packet = packet_str.try_into().unwrap();
        assert_eq!(packet, Packet::Message("hello".to_string()));
    }

    #[test]
    fn test_binary_packet() {
        let packet = Packet::Binary(vec![1, 2, 3]);
        let packet_str: String = packet.try_into().unwrap();
        assert_eq!(packet_str, "bAQID");
    }

    #[test]
    fn test_binary_packet_deserialize() {
        let packet_str = "bAQID".to_string();
        let packet: Packet = packet_str.try_into().unwrap();
        assert_eq!(packet, Packet::Binary(vec![1, 2, 3]));
    }

    #[test]
    fn test_binary_packet_v3() {
        let packet = Packet::BinaryV3(vec![1, 2, 3]);
        let packet_str: String = packet.try_into().unwrap();
        assert_eq!(packet_str, "b4AQID");
    }

    #[test]
    fn test_binary_packet_v3_deserialize() {
        let packet_str = "b4AQID".to_string();
        let packet: Packet = packet_str.try_into().unwrap();
        assert_eq!(packet, Packet::BinaryV3(vec![1, 2, 3]));
    }

    #[test]
    fn test_send_packet_into_packet() {
        let packet = SendPacket::Message("hello".to_string());
        let packet: Packet = packet.into();
        assert_eq!(packet, Packet::Message("hello".to_string()));

        let packet = SendPacket::Binary(vec![1, 2, 3]);
        let packet: Packet = packet.into();
        assert_eq!(packet, Packet::Binary(vec![1, 2, 3]));
    }
}