Skip to main content

socketio_next/engineio/
client.rs

1use std::fmt::Debug;
2use std::pin::Pin;
3
4use futures_util::{Stream, StreamExt};
5use tokio::time::Instant;
6
7use crate::engineio::error::Result;
8use crate::engineio::generator::{StreamGenerator, end_after_error};
9use crate::engineio::socket::Socket as InnerSocket;
10use crate::engineio::{HandshakePacket, Packet, TransportKind};
11
12/// An engine.io client: a [`Stream`] of received packets plus `emit`.
13///
14/// Clones share one session (no need for an `Arc`): emit from any clone, but read the stream
15/// from one task at a time; two tasks polling concurrently would steal each other's wakeups.
16#[derive(Clone)]
17pub struct Client {
18    socket: InnerSocket,
19    generator: StreamGenerator<Packet>,
20}
21
22impl Client {
23    pub(crate) fn new(socket: InnerSocket) -> Self {
24        Client {
25            socket: socket.clone(),
26            generator: StreamGenerator::new(Self::stream(socket)),
27        }
28    }
29
30    #[cfg(test)]
31    pub(crate) fn socket(&self) -> &InnerSocket {
32        &self.socket
33    }
34
35    /// Closes the session (same as [`disconnect`](Self::disconnect)).
36    pub async fn close(&self) -> Result<()> {
37        self.socket.disconnect().await
38    }
39
40    /// Starts the session after `build*`: the heartbeat deadline runs from here.
41    pub async fn connect(&self) -> Result<()> {
42        self.socket.connect();
43        Ok(())
44    }
45
46    /// Sends a close packet (best effort) and closes the session; the stream then ends.
47    pub async fn disconnect(&self) -> Result<()> {
48        self.socket.disconnect().await
49    }
50
51    /// Sends one packet.
52    pub async fn emit(&self, packet: Packet) -> Result<()> {
53        self.socket.emit(packet).await
54    }
55
56    /// Sends several packets in order: batched into as few polling requests as `maxPayload`
57    /// allows, or one websocket frame each.
58    pub async fn emit_all(&self, packets: Vec<Packet>) -> Result<()> {
59        self.socket.emit_all(packets).await
60    }
61
62    /// Whether the session is open.
63    pub fn is_connected(&self) -> bool {
64        self.socket.is_connected()
65    }
66
67    /// The server's handshake: sid, upgrades, ping interval / timeout, max payload.
68    pub fn handshake(&self) -> &HandshakePacket {
69        self.socket.handshake()
70    }
71
72    /// The transport of this session.
73    pub fn transport(&self) -> TransportKind {
74        self.socket.transport().kind()
75    }
76
77    /// When the last ping arrived (the session start before the first one).
78    pub fn last_ping(&self) -> Instant {
79        self.socket.last_ping()
80    }
81
82    fn stream(socket: InnerSocket) -> Pin<Box<dyn Stream<Item = Result<Packet>> + 'static + Send>> {
83        // Each packet is handled (pong, close, callbacks) before it is passed on; a failed
84        // handling ends the stream like a transport error.
85        let handled = socket.as_stream().then(move |item| {
86            let socket = socket.clone();
87            async move {
88                let packet: Packet = item?;
89                socket.handle_incoming_packet(packet.clone()).await?;
90                Ok(packet)
91            }
92        });
93        end_after_error(handled.boxed()).boxed()
94    }
95}
96
97impl Stream for Client {
98    type Item = Result<Packet>;
99
100    fn poll_next(
101        mut self: Pin<&mut Self>,
102        cx: &mut std::task::Context<'_>,
103    ) -> std::task::Poll<Option<Self::Item>> {
104        self.generator.poll_next_unpin(cx)
105    }
106}
107
108impl Debug for Client {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        f.debug_struct("Client")
111            .field("socket", &self.socket)
112            .finish()
113    }
114}
115
116#[cfg(test)]
117mod test {
118
119    use super::*;
120    use crate::engineio::ClientBuilder;
121    use futures_util::StreamExt;
122    use url::Url;
123
124    /// Reads until `deadline`; `Some(err)` for an error, `None` when it stayed healthy.
125    async fn watch(
126        socket: &mut Client,
127        deadline: std::time::Duration,
128    ) -> Option<crate::engineio::Error> {
129        let end = tokio::time::Instant::now() + deadline;
130        loop {
131            match tokio::time::timeout_at(end, socket.next()).await {
132                Err(_) => return None,
133                Ok(Some(Err(err))) => return Some(err),
134                Ok(Some(Ok(_))) => continue,
135                Ok(None) => return Some(crate::engineio::Error::NotConnected),
136            }
137        }
138    }
139
140    /// A system sleep on a dead link: the monotonic timer has most of pingInterval +
141    /// pingTimeout (45 s here) to go, the wall clock says the deadline passed. The probe gets
142    /// no answer and the link is declared dead after pingTimeout (20 s), not 45 s.
143    #[tokio::test]
144    async fn a_sleep_on_a_dead_link_is_a_ping_timeout_after_ping_timeout() -> Result<()> {
145        tokio::time::timeout(std::time::Duration::from_secs(90), async move {
146            let tcp = socketio_next_testing::Proxy::start(&socketio_next_testing::host_port(
147                crate::engineio::test::engine_io_server()?.as_str(),
148            ))
149            .await;
150            let mut socket = builder(Url::parse(&tcp.url())?).build_polling().await?;
151            socket.connect().await?;
152            // the link is dead: open connections stall, new ones are refused
153            tcp.refuse(true);
154            tcp.freeze();
155            let started = std::time::Instant::now();
156            socket
157                .socket
158                .shift_wall_clock(std::time::Duration::from_secs(3600), true);
159            let err = watch(&mut socket, std::time::Duration::from_secs(30)).await;
160            assert!(
161                matches!(err, Some(crate::engineio::Error::PingTimeout)),
162                "{err:?}"
163            );
164            let took = started.elapsed();
165            assert!(
166                took >= std::time::Duration::from_secs(19),
167                "probed first: {took:?}"
168            );
169            assert!(took < std::time::Duration::from_secs(25), "{took:?}");
170            tcp.cut();
171            Ok(())
172        })
173        .await
174        .expect("test `a_sleep_on_a_dead_link_is_a_ping_timeout_after_ping_timeout` timed out")
175    }
176
177    /// A forward clock step (NTP on a gateway without RTC) on a live link: the probe is
178    /// answered (a noop POST, or a websocket ping), nothing closes. On the fast-ping server
179    /// (pingInterval 300 ms, pingTimeout 200 ms), stepped right after a ping: the next ping is
180    /// ~300 ms away, so without the probe the 200 ms grace would end the link.
181    #[tokio::test]
182    async fn a_forward_clock_step_on_a_live_link_keeps_it() -> Result<()> {
183        tokio::time::timeout(std::time::Duration::from_secs(90), async move {
184            let mut url = Url::parse(&socketio_next_testing::fast_ping_server())?;
185            url.set_path("/socket.io/");
186            for websocket in [false, true] {
187                let mut socket = if websocket {
188                    builder(url.clone()).build_websocket().await?
189                } else {
190                    builder(url.clone()).build_polling().await?
191                };
192                socket.connect().await?;
193                // a ping arrived: the clock is stepped right after it
194                loop {
195                    let packet =
196                        tokio::time::timeout(std::time::Duration::from_secs(5), socket.next())
197                            .await
198                            .expect("a ping")
199                            .expect("open")?;
200                    if packet.packet_id == crate::engineio::PacketId::Ping {
201                        break;
202                    }
203                }
204                socket
205                    .socket
206                    .shift_wall_clock(std::time::Duration::from_secs(3600), true);
207                // longer than pingTimeout (200), shorter than pingInterval (300)
208                let err = watch(&mut socket, std::time::Duration::from_millis(260)).await;
209                assert!(err.is_none(), "websocket={websocket}: {err:?}");
210                assert!(socket.is_connected());
211                socket.disconnect().await?;
212            }
213            Ok(())
214        })
215        .await
216        .expect("test `a_forward_clock_step_on_a_live_link_keeps_it` timed out")
217    }
218
219    /// A backward step changes nothing.
220    #[tokio::test]
221    async fn a_backward_clock_step_has_no_effect() -> Result<()> {
222        tokio::time::timeout(std::time::Duration::from_secs(90), async move {
223            let url = crate::engineio::test::engine_io_server()?;
224            let mut socket = builder(url).build_polling().await?;
225            socket.connect().await?;
226            socket
227                .socket
228                .shift_wall_clock(std::time::Duration::from_secs(3600), false);
229            assert!(
230                watch(&mut socket, std::time::Duration::from_secs(1))
231                    .await
232                    .is_none()
233            );
234            socket.disconnect().await?;
235            Ok(())
236        })
237        .await
238        .expect("test `a_backward_clock_step_has_no_effect` timed out")
239    }
240
241    fn builder(url: Url) -> ClientBuilder {
242        ClientBuilder::new(url)
243            .on_open(|_| async {
244                println!("Open event!");
245            })
246            .on_packet(|packet| async move {
247                println!("Received packet: {:?}", packet);
248            })
249            .on_data(|data| async move {
250                println!("Received data: {:?}", std::str::from_utf8(&data));
251            })
252            .on_close(|_| async {
253                println!("Close event!");
254            })
255            .on_error(|error| async move {
256                println!("Error {}", error);
257            })
258    }
259}