1use std::future::Future;
2use std::time::Duration;
3
4use bytes::Bytes;
5use futures_util::{Stream, StreamExt};
6use http::HeaderMap;
7use url::Url;
8
9use crate::engineio::callback::{Callbacks, boxed};
10use crate::engineio::error::Result;
11use crate::engineio::http::Http;
12use crate::engineio::socket::Socket as InnerSocket;
13use crate::engineio::tls::{self, TlsConfig};
14use crate::engineio::transport::Frame;
15use crate::engineio::transports::{PollingTransport, WebsocketTransport};
16use crate::engineio::{
17 Client, DEFAULT_TIMEOUT, ENGINE_IO_VERSION, Error, HandshakePacket, Packet, PacketId,
18};
19use crate::protocol::engineio::Batch;
20
21#[derive(Clone)]
25pub struct ClientBuilder {
26 url: Url,
27 tls_config: Option<TlsConfig>,
28 headers: Option<HeaderMap>,
29 timeout: Duration,
30 handshake: Option<HandshakePacket>,
31 pending: Vec<Packet>,
34 callbacks: Callbacks,
35 http: Option<Http>,
37}
38
39impl std::fmt::Debug for ClientBuilder {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 f.debug_struct("ClientBuilder")
43 .field("url", &crate::redact::url(&self.url, true))
44 .field(
45 "headers",
46 &self
47 .headers
48 .iter()
49 .flat_map(|h| h.keys())
50 .map(|k| k.as_str())
51 .collect::<Vec<_>>(),
52 )
53 .field("tls_config", &self.tls_config)
54 .field("timeout", &self.timeout)
55 .field("handshake", &self.handshake.is_some())
56 .field("callbacks", &self.callbacks)
57 .finish()
58 }
59}
60
61const RESERVED_QUERY: [&str; 5] = ["EIO", "transport", "sid", "t", "b64"];
63
64impl ClientBuilder {
65 pub fn new(url: Url) -> Self {
69 let mut url = url;
70 let user: Vec<(String, String)> = url
71 .query_pairs()
72 .filter(|(k, _)| !RESERVED_QUERY.contains(&k.as_ref()))
73 .map(|(k, v)| (k.into_owned(), v.into_owned()))
74 .collect();
75 url.set_query(None);
76 url.query_pairs_mut()
77 .extend_pairs(user)
78 .append_pair("EIO", &ENGINE_IO_VERSION.to_string());
79 if url.path() == "/" {
80 url.set_path("/engine.io/");
81 }
82 ClientBuilder {
83 url,
84 headers: None,
85 tls_config: None,
86 timeout: DEFAULT_TIMEOUT,
87 handshake: None,
88 pending: Vec::new(),
89 callbacks: Callbacks::default(),
90 http: None,
91 }
92 }
93
94 pub(crate) fn http(mut self, http: Http) -> Self {
96 self.http = Some(http);
97 self
98 }
99
100 fn http_settings(&mut self) -> Result<Http> {
101 if self.http.is_none() {
102 self.http = Some(Http::new(
103 self.tls_config.as_ref(),
104 crate::engineio::http::ProxyMode::Env,
105 )?);
106 }
107 Ok(self.http.clone().expect("set above"))
108 }
109
110 #[cfg(any(feature = "rustls", feature = "native-tls"))]
112 #[cfg_attr(docsrs, doc(cfg(any(feature = "rustls", feature = "native-tls"))))]
113 pub fn tls_config(mut self, tls_config: impl Into<TlsConfig>) -> Self {
114 self.tls_config = Some(tls_config.into());
115 self
116 }
117
118 pub fn headers(mut self, headers: HeaderMap) -> Self {
120 self.headers = Some(headers);
121 self
122 }
123
124 pub fn timeout(mut self, timeout: Duration) -> Self {
126 self.timeout = timeout;
127 self
128 }
129
130 pub fn on_close<F, Fut>(mut self, callback: F) -> Self
132 where
133 F: Fn(()) -> Fut + Send + Sync + 'static,
134 Fut: Future<Output = ()> + Send + 'static,
135 {
136 self.callbacks.on_close = Some(boxed(callback));
137 self
138 }
139
140 pub fn on_data<F, Fut>(mut self, callback: F) -> Self
142 where
143 F: Fn(Bytes) -> Fut + Send + Sync + 'static,
144 Fut: Future<Output = ()> + Send + 'static,
145 {
146 self.callbacks.on_data = Some(boxed(callback));
147 self
148 }
149
150 pub fn on_error<F, Fut>(mut self, callback: F) -> Self
152 where
153 F: Fn(String) -> Fut + Send + Sync + 'static,
154 Fut: Future<Output = ()> + Send + 'static,
155 {
156 self.callbacks.on_error = Some(boxed(callback));
157 self
158 }
159
160 pub fn on_open<F, Fut>(mut self, callback: F) -> Self
162 where
163 F: Fn(()) -> Fut + Send + Sync + 'static,
164 Fut: Future<Output = ()> + Send + 'static,
165 {
166 self.callbacks.on_open = Some(boxed(callback));
167 self
168 }
169
170 pub fn on_packet<F, Fut>(mut self, callback: F) -> Self
172 where
173 F: Fn(Packet) -> Fut + Send + Sync + 'static,
174 Fut: Future<Output = ()> + Send + 'static,
175 {
176 self.callbacks.on_packet = Some(boxed(callback));
177 self
178 }
179
180 async fn handshake_with_transport<T, I>(&mut self, transport: &mut T) -> Result<()>
182 where
183 T: Stream<Item = Result<I>> + Unpin,
184 I: Into<Frame>,
185 {
186 if self.handshake.is_some() {
187 return Ok(());
188 }
189 let first = transport.next().await.ok_or_else(|| {
190 Error::InvalidHandshake("the connection closed before the open packet".into())
191 })??;
192 let handshake = match first.into() {
193 Frame::Text(bytes) => {
194 let (handshake, pending) = parse_handshake(bytes)?;
195 self.pending = pending;
196 handshake
197 }
198 Frame::Binary(_) => {
199 return Err(Error::InvalidHandshake(
200 "binary frame instead of the open packet".into(),
201 ));
202 }
203 };
204 self.url
205 .query_pairs_mut()
206 .append_pair("sid", &handshake.sid);
207 tracing::debug!(
208 sid = %handshake.sid,
209 upgrades = ?handshake.upgrades,
210 ping_interval_ms = handshake.ping_interval,
211 ping_timeout_ms = handshake.ping_timeout,
212 max_payload = handshake.max_payload,
213 "engine.io handshake"
214 );
215 self.handshake = Some(handshake);
216 Ok(())
217 }
218
219 async fn handshake(&mut self) -> Result<()> {
220 if self.handshake.is_some() {
221 return Ok(());
222 }
223 tls::check_scheme(&self.url)?;
224 let http = self.http_settings()?;
225 let mut transport = PollingTransport::with_client(
226 self.url.clone(),
227 &http,
228 self.headers.clone().unwrap_or_default(),
229 Some(self.timeout),
230 )?;
231 self.handshake_with_transport(&mut transport).await
232 }
233
234 pub async fn build(mut self) -> Result<Client> {
238 self.handshake().await?;
239 if self.websocket_upgrade() {
240 match self.clone().build_websocket_with_upgrade().await {
241 Ok(client) => return Ok(client),
242 Err(err) => {
243 tracing::debug!(error = %err, "websocket upgrade failed, staying on polling");
244 }
245 }
246 }
247 self.build_polling().await
248 }
249
250 pub async fn build_polling(mut self) -> Result<Client> {
252 self.handshake().await?;
253 let handshake = self
254 .handshake
255 .take()
256 .ok_or(Error::InvalidHandshake("missing".into()))?;
257
258 let request_timeout = Duration::from_millis(
261 handshake
262 .ping_interval
263 .saturating_add(handshake.ping_timeout),
264 );
265 let http = self.http_settings()?;
266 let transport = PollingTransport::with_client(
267 self.url,
268 &http,
269 self.headers.unwrap_or_default(),
270 Some(request_timeout),
271 )?;
272 tracing::debug!(transport = "polling", "engine.io transport chosen");
273 Ok(Client::new(InnerSocket::new(
274 transport.into(),
275 handshake,
276 self.callbacks,
277 self.pending,
278 )))
279 }
280
281 pub async fn build_websocket_with_upgrade(mut self) -> Result<Client> {
283 self.handshake().await?;
284 if self.websocket_upgrade() {
285 self.build_websocket().await
286 } else {
287 Err(Error::UpgradeUnavailable)
288 }
289 }
290
291 pub async fn build_websocket(mut self) -> Result<Client> {
296 let timeout = self.timeout;
297 let connect = async move {
298 let http = self.http_settings()?;
299 let headers = http.with_cookies(&self.headers.clone().unwrap_or_default(), &self.url);
300 let mut transport = WebsocketTransport::connect(
301 self.url.clone(),
302 self.tls_config.clone(),
303 Some(headers),
304 http.ws_route(&self.url)?,
305 )
306 .await?;
307 if self.handshake.is_some() {
308 transport.upgrade().await?;
309 tracing::debug!(transport = "websocket", "engine.io upgraded");
310 } else {
311 self.handshake_with_transport(&mut transport).await?;
312 tracing::debug!(transport = "websocket", "engine.io transport chosen");
313 }
314 let handshake = self
315 .handshake
316 .ok_or(Error::InvalidHandshake("missing".into()))?;
317 Ok(Client::new(InnerSocket::new(
318 transport.into(),
319 handshake,
320 self.callbacks,
321 self.pending,
322 )))
323 };
324 tokio::time::timeout(timeout, connect)
325 .await
326 .map_err(|_| Error::Timeout(timeout))?
327 }
328
329 pub async fn build_with_fallback(mut self) -> Result<Client> {
333 self.handshake().await?;
334 if self.websocket_upgrade() {
335 let mut upgrade = self.clone();
336 upgrade.timeout = self.timeout / 2;
337 match upgrade.build_websocket().await {
338 Ok(client) => return Ok(client),
339 Err(err) => {
340 tracing::debug!(error = %err, "websocket upgrade failed, staying on polling");
341 }
342 }
343 }
344 self.build_polling().await
345 }
346
347 fn websocket_upgrade(&self) -> bool {
348 self.handshake.as_ref().is_some_and(|handshake| {
349 handshake
350 .upgrades
351 .iter()
352 .any(|upgrade| upgrade.eq_ignore_ascii_case("websocket"))
353 })
354 }
355}
356
357fn parse_handshake(body: Bytes) -> Result<(HandshakePacket, Vec<Packet>)> {
361 let (bytes, rest) = match body.iter().position(|&b| b == Batch::SEPARATOR as u8) {
362 Some(at) => (body.slice(..at), Some(body.slice(at + 1..))),
363 None => (body.clone(), None),
364 };
365 let hint = || {
366 let head = String::from_utf8_lossy(&bytes[..bytes.len().min(32)]).into_owned();
367 let v3 = head
368 .split_once(':')
369 .is_some_and(|(len, _)| len.bytes().all(|b| b.is_ascii_digit()));
370 if v3 {
371 format!(
372 "{head:?}: looks like an Engine.IO v3 server (socket.io 2.x); this client needs v4 (socket.io 3+)"
373 )
374 } else {
375 format!("expected an open packet `0{{...}}`, got {head:?}")
376 }
377 };
378 let packet = Packet::try_from(bytes.clone()).map_err(|_| Error::InvalidHandshake(hint()))?;
379 if packet.packet_id != PacketId::Open {
380 return Err(Error::InvalidHandshake(hint()));
381 }
382 let handshake =
383 HandshakePacket::try_from(packet).map_err(|e| Error::InvalidHandshake(e.to_string()))?;
384 let pending = match rest {
385 Some(rest) => Batch::try_from(rest)?.into_iter().collect(),
386 None => Vec::new(),
387 };
388 Ok((handshake, pending))
389}
390
391#[cfg(test)]
392mod tests {
393 use super::*;
394
395 #[test]
396 fn handshake_errors_explain() {
397 let err = parse_handshake(Bytes::from_static(b"96:0{\"sid\":\"x\"}")).unwrap_err();
398 assert!(err.to_string().contains("Engine.IO v3"), "{err}");
399 let err = parse_handshake(Bytes::from_static(b"<html>")).unwrap_err();
400 assert!(err.to_string().contains("expected an open packet"), "{err}");
401 let ok = parse_handshake(Bytes::from_static(
402 b"0{\"sid\":\"a\",\"upgrades\":[\"websocket\"],\"pingInterval\":25000,\"pingTimeout\":20000,\"maxPayload\":1000000}",
403 ))
404 .unwrap();
405 assert_eq!(
406 (ok.0.sid.as_str(), ok.0.max_payload),
407 ("a", Some(1_000_000))
408 );
409 assert!(ok.1.is_empty());
410 let (open, rest) = parse_handshake(Bytes::from_static(
412 b"0{\"sid\":\"a\",\"upgrades\":[],\"pingInterval\":25000,\"pingTimeout\":20000}\x1e4hello\x1ebAQI=",
413 ))
414 .unwrap();
415 assert_eq!(open.sid, "a");
416 assert_eq!(
417 rest,
418 [
419 Packet::new(PacketId::Message, Bytes::from_static(b"hello")),
420 Packet::new(PacketId::MessageBinary, Bytes::from_static(&[1, 2])),
421 ]
422 );
423 }
424}