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    }
124
125    /// See [`crate::ClientBuilder::tls_config`].
126    #[cfg(any(feature = "rustls", feature = "native-tls"))]
127    pub fn tls_config(self, tls_config: impl Into<TlsConfig>) -> Self {
128        ClientBuilder {
129            inner: self.inner.tls_config(tls_config),
130            ..self
131        }
132    }
133
134    /// See [`crate::ClientBuilder::auth_with`]; `auth` runs on a blocking thread.
135    pub fn auth_with<F>(self, auth: F) -> Self
136    where
137        F: Fn() -> Value + Send + Sync + 'static,
138    {
139        let auth = Arc::new(auth);
140        let inner = self.inner.auth_with(move || {
141            let auth = Arc::clone(&auth);
142            async move {
143                tokio::task::spawn_blocking(move || auth())
144                    .await
145                    .unwrap_or(Value::Null)
146            }
147        });
148        ClientBuilder { inner, ..self }
149    }
150
151    /// See [`crate::ClientBuilder::inspect_packets`].
152    pub fn inspect_packets<F>(self, inspector: F) -> Self
153    where
154        F: Fn(Direction, &protocol::socketio::Packet) + Send + Sync + 'static,
155    {
156        ClientBuilder {
157            inner: self.inner.inspect_packets(inspector),
158            ..self
159        }
160    }
161
162    /// Handles `event` (on a blocking thread, in arrival order).
163    pub fn on<F>(self, event: impl Into<String>, handler: F) -> Self
164    where
165        F: Fn(Event, Client) + Send + Sync + 'static,
166    {
167        let handle = self.handle.clone();
168        ClientBuilder {
169            inner: self.inner.on(event, wrap(handle, handler)),
170            ..self
171        }
172    }
173
174    /// Handles the next `event` only.
175    pub fn once<F>(self, event: impl Into<String>, handler: F) -> Self
176    where
177        F: Fn(Event, Client) + Send + Sync + 'static,
178    {
179        let handle = self.handle.clone();
180        ClientBuilder {
181            inner: self.inner.once(event, wrap(handle, handler)),
182            ..self
183        }
184    }
185
186    /// Handles every event.
187    pub fn on_any<F>(self, handler: F) -> Self
188    where
189        F: Fn(Event, Client) + Send + Sync + 'static,
190    {
191        let handle = self.handle.clone();
192        ClientBuilder {
193            inner: self.inner.on_any(wrap(handle, handler)),
194            ..self
195        }
196    }
197
198    /// Sees every state transition.
199    pub fn on_state_change<F>(self, handler: F) -> Self
200    where
201        F: Fn(ConnectionState, Client) + Send + Sync + 'static,
202    {
203        let handle = self.handle.clone();
204        ClientBuilder {
205            inner: self.inner.on_state_change(wrap(handle, handler)),
206            ..self
207        }
208    }
209
210    /// Connects (see [`crate::ClientBuilder::connect`]), blocking until CONNECT or failure.
211    pub fn connect(self) -> Result<Client> {
212        let inner = self.handle.block_on(self.inner.connect())?;
213        Ok(Client {
214            inner,
215            handle: self.handle,
216            _runtime: Some(self.runtime),
217        })
218    }
219}
220
221fn wrap<A, F>(handle: Handle, handler: F) -> impl Fn(A, crate::Client) + Send + Sync + 'static
222where
223    A: Send + 'static,
224    F: Fn(A, Client) + Send + Sync + 'static,
225{
226    move |arg, inner| {
227        handler(
228            arg,
229            Client {
230                inner,
231                handle: handle.clone(),
232                _runtime: None,
233            },
234        )
235    }
236}
237
238/// The blocking client. Cheap to clone; dropping the last clone the user holds disconnects
239/// (bounded, as [`Client::disconnect`]) and stops the runtime. The clients handed to handlers
240/// are for the duration of the call; do not keep them after the last user handle is gone.
241#[derive(Clone)]
242pub struct Client {
243    inner: crate::Client,
244    handle: Handle,
245    _runtime: Option<Arc<RuntimeOwner>>,
246}
247
248impl fmt::Debug for Client {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        f.debug_tuple("Client").field(&self.inner).finish()
251    }
252}
253
254impl Drop for Client {
255    fn drop(&mut self) {
256        // The last user handle: say goodbye before the runtime goes (not possible from inside
257        // an async context, where the drop just closes the connection).
258        let last = self
259            ._runtime
260            .as_ref()
261            .is_some_and(|runtime| Arc::strong_count(runtime) == 1);
262        if last && Handle::try_current().is_err() && !self.inner.state().is_closed() {
263            let inner = self.inner.clone();
264            self.handle.block_on(async move {
265                let _ = tokio::time::timeout(Duration::from_secs(3), inner.disconnect()).await;
266            });
267        }
268    }
269}
270
271impl Client {
272    /// The async client behind this one.
273    pub fn as_async(&self) -> &crate::Client {
274        &self.inner
275    }
276
277    /// See [`crate::Client::emit`] (never blocks).
278    pub fn emit(&self, event: impl AsRef<str>, data: impl Into<Payload>) -> Result<()> {
279        self.inner.emit(event, data)
280    }
281
282    /// See [`crate::Client::emit_with_ack`]; blocks until the ack, the timeout or the loss.
283    pub fn emit_with_ack(
284        &self,
285        event: impl AsRef<str>,
286        data: impl Into<Payload>,
287        timeout: Duration,
288    ) -> Result<Payload> {
289        self.handle
290            .block_on(self.inner.emit_with_ack(event, data, timeout))
291    }
292
293    /// See [`crate::Client::disconnect`]; blocks (bounded).
294    pub fn disconnect(&self) -> Result<()> {
295        self.handle.block_on(self.inner.disconnect())
296    }
297
298    /// See [`crate::Client::reconnect`]; blocks until the attempt ends.
299    pub fn reconnect(&self) -> Result<()> {
300        self.handle.block_on(self.inner.reconnect())
301    }
302
303    /// Adds a handler for `event`.
304    pub fn on<F>(&self, event: impl Into<String>, handler: F) -> ListenerId
305    where
306        F: Fn(Event, Client) + Send + Sync + 'static,
307    {
308        self.inner.on(event, wrap(self.handle.clone(), handler))
309    }
310
311    /// Adds a handler for the next `event`.
312    pub fn once<F>(&self, event: impl Into<String>, handler: F) -> ListenerId
313    where
314        F: Fn(Event, Client) + Send + Sync + 'static,
315    {
316        self.inner.once(event, wrap(self.handle.clone(), handler))
317    }
318
319    /// Removes every handler of `event`.
320    pub fn off(&self, event: &str) -> usize {
321        self.inner.off(event)
322    }
323
324    /// Removes one handler.
325    pub fn off_listener(&self, id: ListenerId) -> bool {
326        self.inner.off_listener(id)
327    }
328
329    /// Number of handlers of `event`.
330    pub fn listener_count(&self, event: &str) -> usize {
331        self.inner.listener_count(event)
332    }
333
334    /// The current state.
335    pub fn state(&self) -> ConnectionState {
336        self.inner.state()
337    }
338
339    /// Blocks until the state matches `predicate`, the client closed, or `timeout` passed;
340    /// returns the state then.
341    pub fn wait_for(
342        &self,
343        predicate: impl Fn(&ConnectionState) -> bool,
344        timeout: Duration,
345    ) -> ConnectionState {
346        self.handle.block_on(async {
347            tokio::time::timeout(timeout, self.inner.wait_for(predicate))
348                .await
349                .unwrap_or_else(|_| self.inner.state())
350        })
351    }
352
353    /// The namespace is joined right now.
354    pub fn connected(&self) -> bool {
355        self.inner.connected()
356    }
357
358    /// The socket id while connected.
359    pub fn id(&self) -> Option<String> {
360        self.inner.id()
361    }
362
363    /// The namespace.
364    pub fn namespace(&self) -> &str {
365        self.inner.namespace()
366    }
367
368    /// A snapshot of the link.
369    pub fn link_info(&self) -> LinkInfo {
370        self.inner.link_info()
371    }
372}