Skip to main content

socketio_next/
blocking.rs

1//! The client without async: the same [`crate::Client`] driven by a private tokio runtime
2//! (one worker thread), with blocking methods and plain-closure handlers.
3//!
4//! ```no_run
5//! use std::time::Duration;
6//! use socketio_next::blocking::{Client, ClientBuilder};
7//! use socketio_next::Event;
8//!
9//! let client = ClientBuilder::new("http://localhost:3000")
10//!     .on("news", |event: Event, client: Client| {
11//!         println!("news: {:?}", event.payload());
12//!         client.emit("thanks", ()).ok();
13//!     })
14//!     .connect()?;
15//! let reply = client.emit_with_ack("ping", (), Duration::from_secs(5))?;
16//! client.disconnect()?;
17//! # Ok::<(), socketio_next::Error>(())
18//! ```
19//!
20//! The blocking methods must not be called from inside an async runtime (tokio panics on a
21//! nested `block_on`); handlers run on blocking threads, where they are fine.
22
23use std::fmt;
24use std::sync::Arc;
25use std::time::Duration;
26
27use serde_json::Value;
28use tokio::runtime::{Handle, Runtime};
29
30#[cfg(any(feature = "rustls", feature = "native-tls"))]
31use crate::engineio::TlsConfig;
32use crate::handler::ListenerId;
33use crate::{
34    ConnectionState, Direction, Event, LinkInfo, Payload, Result, TransportType, protocol,
35};
36
37/// Owns the runtime; shuts it down without blocking (safe from any thread).
38struct RuntimeOwner(Option<Runtime>);
39
40impl Drop for RuntimeOwner {
41    fn drop(&mut self) {
42        if let Some(runtime) = self.0.take() {
43            runtime.shutdown_background();
44        }
45    }
46}
47
48/// Builder of the blocking [`Client`]; the options of [`crate::ClientBuilder`].
49pub struct ClientBuilder {
50    inner: crate::ClientBuilder,
51    runtime: Arc<RuntimeOwner>,
52    handle: Handle,
53}
54
55impl fmt::Debug for ClientBuilder {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        f.debug_struct("ClientBuilder")
58            .field("inner", &self.inner)
59            .finish_non_exhaustive()
60    }
61}
62
63macro_rules! delegate {
64    ($($(#[$meta:meta])* fn $name:ident($($arg:ident: $ty:ty),*);)*) => {$(
65        $(#[$meta])*
66        pub fn $name(self, $($arg: $ty),*) -> Self {
67            ClientBuilder { inner: self.inner.$name($($arg),*), ..self }
68        }
69    )*};
70}
71
72impl ClientBuilder {
73    /// A builder for `address` (see [`crate::ClientBuilder::new`]). Starts the runtime thread.
74    ///
75    /// # Panics
76    /// When the OS refuses to start a thread.
77    pub fn new(address: impl Into<String>) -> Self {
78        let runtime = tokio::runtime::Builder::new_multi_thread()
79            .worker_threads(1)
80            .thread_name("socketio-next")
81            .enable_all()
82            .build()
83            .expect("start the socketio-next runtime");
84        let handle = runtime.handle().clone();
85        ClientBuilder {
86            inner: crate::ClientBuilder::new(address),
87            runtime: Arc::new(RuntimeOwner(Some(runtime))),
88            handle,
89        }
90    }
91
92    delegate! {
93        /// See [`crate::ClientBuilder::namespace`].
94        fn namespace(namespace: impl Into<String>);
95        /// See [`crate::ClientBuilder::path`].
96        fn path(path: impl Into<String>);
97        /// See [`crate::ClientBuilder::query`].
98        fn query(key: impl Into<String>, value: impl Into<String>);
99        /// See [`crate::ClientBuilder::header`].
100        fn header(key: impl Into<String>, value: impl Into<String>);
101        /// See [`crate::ClientBuilder::auth`].
102        fn auth(auth: impl Into<Value>);
103        /// See [`crate::ClientBuilder::transport_type`].
104        fn transport_type(transport: TransportType);
105        /// See [`crate::ClientBuilder::timeout`].
106        fn timeout(timeout: Duration);
107        /// See [`crate::ClientBuilder::reconnection`].
108        fn reconnection(reconnection: bool);
109        /// See [`crate::ClientBuilder::reconnection_attempts`].
110        fn reconnection_attempts(attempts: u32);
111        /// See [`crate::ClientBuilder::reconnection_delay`].
112        fn reconnection_delay(delay: Duration);
113        /// See [`crate::ClientBuilder::reconnection_delay_max`].
114        fn reconnection_delay_max(delay: Duration);
115        /// See [`crate::ClientBuilder::randomization_factor`].
116        fn randomization_factor(factor: f64);
117        /// See [`crate::ClientBuilder::reconnect_on_disconnect`].
118        fn reconnect_on_disconnect(reconnect: bool);
119        /// See [`crate::ClientBuilder::buffer_while_disconnected`].
120        fn buffer_while_disconnected(buffer: bool);
121        /// See [`crate::ClientBuilder::redact_query`].
122        fn redact_query(redact: bool);
123        /// See [`crate::ClientBuilder::proxy`].
124        fn proxy(proxy: impl Into<String>);
125        /// See [`crate::ClientBuilder::no_proxy`].
126        fn no_proxy();
127    }
128
129    /// See [`crate::ClientBuilder::engine_url`].
130    pub fn engine_url(&self) -> Result<url::Url> {
131        self.inner.engine_url()
132    }
133
134    /// See [`crate::ClientBuilder::connect_params_with`]; `params` runs on a blocking thread
135    /// before every connect attempt.
136    pub fn connect_params_with<F>(self, params: F) -> Self
137    where
138        F: Fn() -> crate::ConnectParams + Send + Sync + 'static,
139    {
140        let params = Arc::new(params);
141        let inner = self.inner.connect_params_with(move || {
142            let params = Arc::clone(&params);
143            async move {
144                // a panic stays a panic: the attempt fails with "connect_params_with panicked"
145                match tokio::task::spawn_blocking(move || params()).await {
146                    Ok(value) => value,
147                    Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()),
148                    Err(_) => {
149                        std::panic::resume_unwind(Box::new("connect_params_with was cancelled"))
150                    }
151                }
152            }
153        });
154        ClientBuilder { inner, ..self }
155    }
156
157    /// See [`crate::ClientBuilder::tls_config`].
158    #[cfg(any(feature = "rustls", feature = "native-tls"))]
159    pub fn tls_config(self, tls_config: impl Into<TlsConfig>) -> Self {
160        ClientBuilder {
161            inner: self.inner.tls_config(tls_config),
162            ..self
163        }
164    }
165
166    /// See [`crate::ClientBuilder::auth_with`]; `auth` runs on a blocking thread.
167    pub fn auth_with<F>(self, auth: F) -> Self
168    where
169        F: Fn() -> Value + Send + Sync + 'static,
170    {
171        let auth = Arc::new(auth);
172        let inner = self.inner.auth_with(move || {
173            let auth = Arc::clone(&auth);
174            async move {
175                // a panic stays a panic: the attempt fails with "auth_with panicked"
176                match tokio::task::spawn_blocking(move || auth()).await {
177                    Ok(value) => value,
178                    Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()),
179                    Err(_) => std::panic::resume_unwind(Box::new("auth_with was cancelled")),
180                }
181            }
182        });
183        ClientBuilder { inner, ..self }
184    }
185
186    /// See [`crate::ClientBuilder::inspect_packets`].
187    pub fn inspect_packets<F>(self, inspector: F) -> Self
188    where
189        F: Fn(Direction, &protocol::socketio::Packet) + Send + Sync + 'static,
190    {
191        ClientBuilder {
192            inner: self.inner.inspect_packets(inspector),
193            ..self
194        }
195    }
196
197    /// Handles `event` (on a blocking thread, in arrival order).
198    pub fn on<F>(self, event: impl Into<String>, handler: F) -> Self
199    where
200        F: Fn(Event, Client) + Send + Sync + 'static,
201    {
202        let handle = self.handle.clone();
203        ClientBuilder {
204            inner: self.inner.on(event, wrap(handle, handler)),
205            ..self
206        }
207    }
208
209    /// Handles the next `event` only.
210    pub fn once<F>(self, event: impl Into<String>, handler: F) -> Self
211    where
212        F: Fn(Event, Client) + Send + Sync + 'static,
213    {
214        let handle = self.handle.clone();
215        ClientBuilder {
216            inner: self.inner.once(event, wrap(handle, handler)),
217            ..self
218        }
219    }
220
221    /// Handles every event.
222    pub fn on_any<F>(self, handler: F) -> Self
223    where
224        F: Fn(Event, Client) + Send + Sync + 'static,
225    {
226        let handle = self.handle.clone();
227        ClientBuilder {
228            inner: self.inner.on_any(wrap(handle, handler)),
229            ..self
230        }
231    }
232
233    /// Sees every state transition.
234    pub fn on_state_change<F>(self, handler: F) -> Self
235    where
236        F: Fn(ConnectionState, Client) + Send + Sync + 'static,
237    {
238        let handle = self.handle.clone();
239        ClientBuilder {
240            inner: self.inner.on_state_change(wrap(handle, handler)),
241            ..self
242        }
243    }
244
245    /// Connects (see [`crate::ClientBuilder::connect`]), blocking until CONNECT or failure.
246    pub fn connect(self) -> Result<Client> {
247        let inner = self.handle.block_on(self.inner.connect())?;
248        Ok(Client {
249            inner,
250            handle: self.handle,
251            _runtime: Some(self.runtime),
252        })
253    }
254}
255
256fn wrap<A, F>(handle: Handle, handler: F) -> impl Fn(A, crate::Client) + Send + Sync + 'static
257where
258    A: Send + 'static,
259    F: Fn(A, Client) + Send + Sync + 'static,
260{
261    move |arg, inner| {
262        handler(
263            arg,
264            Client {
265                inner,
266                handle: handle.clone(),
267                _runtime: None,
268            },
269        )
270    }
271}
272
273/// The blocking client. Cheap to clone; dropping the last clone the user holds disconnects
274/// (bounded, as [`Client::disconnect`]) and stops the runtime. The clients handed to handlers
275/// are for the duration of the call; do not keep them after the last user handle is gone.
276#[derive(Clone)]
277pub struct Client {
278    inner: crate::Client,
279    handle: Handle,
280    _runtime: Option<Arc<RuntimeOwner>>,
281}
282
283impl fmt::Debug for Client {
284    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285        f.debug_tuple("Client").field(&self.inner).finish()
286    }
287}
288
289impl Drop for Client {
290    fn drop(&mut self) {
291        // The last user handle: say goodbye before the runtime goes (not possible from inside
292        // an async context, where the drop just closes the connection).
293        let last = self
294            ._runtime
295            .as_ref()
296            .is_some_and(|runtime| Arc::strong_count(runtime) == 1);
297        if last && Handle::try_current().is_err() && !self.inner.state().is_closed() {
298            let inner = self.inner.clone();
299            self.handle.block_on(async move {
300                let _ = tokio::time::timeout(Duration::from_secs(3), inner.disconnect()).await;
301            });
302        }
303    }
304}
305
306impl Client {
307    /// The async client behind this one.
308    pub fn as_async(&self) -> &crate::Client {
309        &self.inner
310    }
311
312    /// See [`crate::Client::emit`] (never blocks).
313    pub fn emit(&self, event: impl AsRef<str>, data: impl Into<Payload>) -> Result<()> {
314        self.inner.emit(event, data)
315    }
316
317    /// See [`crate::Client::emit_with_ack`]; blocks until the ack, the timeout or the loss.
318    pub fn emit_with_ack(
319        &self,
320        event: impl AsRef<str>,
321        data: impl Into<Payload>,
322        timeout: Duration,
323    ) -> Result<Payload> {
324        self.handle
325            .block_on(self.inner.emit_with_ack(event, data, timeout))
326    }
327
328    /// See [`crate::Client::disconnect`]; blocks (bounded).
329    pub fn disconnect(&self) -> Result<()> {
330        self.handle.block_on(self.inner.disconnect())
331    }
332
333    /// See [`crate::Client::reconnect`]; blocks until the attempt ends.
334    pub fn reconnect(&self) -> Result<()> {
335        self.handle.block_on(self.inner.reconnect())
336    }
337
338    /// Adds a handler for `event`.
339    pub fn on<F>(&self, event: impl Into<String>, handler: F) -> ListenerId
340    where
341        F: Fn(Event, Client) + Send + Sync + 'static,
342    {
343        self.inner.on(event, wrap(self.handle.clone(), handler))
344    }
345
346    /// Adds a handler for the next `event`.
347    pub fn once<F>(&self, event: impl Into<String>, handler: F) -> ListenerId
348    where
349        F: Fn(Event, Client) + Send + Sync + 'static,
350    {
351        self.inner.once(event, wrap(self.handle.clone(), handler))
352    }
353
354    /// Adds a handler for every event.
355    pub fn on_any<F>(&self, handler: F) -> ListenerId
356    where
357        F: Fn(Event, Client) + Send + Sync + 'static,
358    {
359        self.inner.on_any(wrap(self.handle.clone(), handler))
360    }
361
362    /// Adds a handler for every state transition.
363    pub fn on_state_change<F>(&self, handler: F) -> ListenerId
364    where
365        F: Fn(ConnectionState, Client) + Send + Sync + 'static,
366    {
367        self.inner
368            .on_state_change(wrap(self.handle.clone(), handler))
369    }
370
371    /// Removes every handler of `event`.
372    pub fn off(&self, event: &str) -> usize {
373        self.inner.off(event)
374    }
375
376    /// Removes every catch-all handler.
377    pub fn off_any(&self) -> usize {
378        self.inner.off_any()
379    }
380
381    /// Removes one handler.
382    pub fn off_listener(&self, id: ListenerId) -> bool {
383        self.inner.off_listener(id)
384    }
385
386    /// Number of handlers of `event`.
387    pub fn listener_count(&self, event: &str) -> usize {
388        self.inner.listener_count(event)
389    }
390
391    /// The current state.
392    pub fn state(&self) -> ConnectionState {
393        self.inner.state()
394    }
395
396    /// Blocks until the state matches `predicate`, the client closed, or `timeout` passed;
397    /// returns the state then.
398    pub fn wait_for(
399        &self,
400        predicate: impl Fn(&ConnectionState) -> bool,
401        timeout: Duration,
402    ) -> ConnectionState {
403        self.handle.block_on(async {
404            tokio::time::timeout(timeout, self.inner.wait_for(predicate))
405                .await
406                .unwrap_or_else(|_| self.inner.state())
407        })
408    }
409
410    /// The namespace is joined right now.
411    pub fn connected(&self) -> bool {
412        self.inner.connected()
413    }
414
415    /// The socket id while connected.
416    pub fn id(&self) -> Option<String> {
417        self.inner.id()
418    }
419
420    /// The last connect restored the session (connection state recovery).
421    pub fn recovered(&self) -> bool {
422        self.inner.recovered()
423    }
424
425    /// The namespace.
426    pub fn namespace(&self) -> &str {
427        self.inner.namespace()
428    }
429
430    /// A snapshot of the link.
431    pub fn link_info(&self) -> LinkInfo {
432        self.inner.link_info()
433    }
434}