socketio-next 0.2.1

Socket.IO v4 / Engine.IO v4 client with socket.io-client 4.8 parity: async (tokio) and blocking, rustls or native-tls
Documentation
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! The client without async: the same [`crate::Client`] driven by a private tokio runtime
//! (one worker thread), with blocking methods and plain-closure handlers.
//!
//! ```no_run
//! use std::time::Duration;
//! use socketio_next::blocking::{Client, ClientBuilder};
//! use socketio_next::Event;
//!
//! let client = ClientBuilder::new("http://localhost:3000")
//!     .on("news", |event: Event, client: Client| {
//!         println!("news: {:?}", event.payload());
//!         client.emit("thanks", ()).ok();
//!     })
//!     .connect()?;
//! let reply = client.emit_with_ack("ping", (), Duration::from_secs(5))?;
//! client.disconnect()?;
//! # Ok::<(), socketio_next::Error>(())
//! ```
//!
//! The blocking methods must not be called from inside an async runtime (tokio panics on a
//! nested `block_on`); handlers run on blocking threads, where they are fine.

use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use serde_json::Value;
use tokio::runtime::{Handle, Runtime};

#[cfg(any(feature = "rustls", feature = "native-tls"))]
use crate::engineio::TlsConfig;
use crate::handler::ListenerId;
use crate::{
    ConnectionState, Direction, Event, LinkInfo, Payload, Result, TransportType, protocol,
};

/// Owns the runtime; shuts it down without blocking (safe from any thread).
struct RuntimeOwner(Option<Runtime>);

impl Drop for RuntimeOwner {
    fn drop(&mut self) {
        if let Some(runtime) = self.0.take() {
            runtime.shutdown_background();
        }
    }
}

/// Builder of the blocking [`Client`]; the options of [`crate::ClientBuilder`].
pub struct ClientBuilder {
    inner: crate::ClientBuilder,
    runtime: Arc<RuntimeOwner>,
    handle: Handle,
}

impl fmt::Debug for ClientBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ClientBuilder")
            .field("inner", &self.inner)
            .finish_non_exhaustive()
    }
}

macro_rules! delegate {
    ($($(#[$meta:meta])* fn $name:ident($($arg:ident: $ty:ty),*);)*) => {$(
        $(#[$meta])*
        pub fn $name(self, $($arg: $ty),*) -> Self {
            ClientBuilder { inner: self.inner.$name($($arg),*), ..self }
        }
    )*};
}

impl ClientBuilder {
    /// A builder for `address` (see [`crate::ClientBuilder::new`]). Starts the runtime thread.
    ///
    /// # Panics
    /// When the OS refuses to start a thread.
    pub fn new(address: impl Into<String>) -> Self {
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(1)
            .thread_name("socketio-next")
            .enable_all()
            .build()
            .expect("start the socketio-next runtime");
        let handle = runtime.handle().clone();
        ClientBuilder {
            inner: crate::ClientBuilder::new(address),
            runtime: Arc::new(RuntimeOwner(Some(runtime))),
            handle,
        }
    }

    delegate! {
        /// See [`crate::ClientBuilder::namespace`].
        fn namespace(namespace: impl Into<String>);
        /// See [`crate::ClientBuilder::path`].
        fn path(path: impl Into<String>);
        /// See [`crate::ClientBuilder::query`].
        fn query(key: impl Into<String>, value: impl Into<String>);
        /// See [`crate::ClientBuilder::header`].
        fn header(key: impl Into<String>, value: impl Into<String>);
        /// See [`crate::ClientBuilder::auth`].
        fn auth(auth: impl Into<Value>);
        /// See [`crate::ClientBuilder::transport_type`].
        fn transport_type(transport: TransportType);
        /// See [`crate::ClientBuilder::timeout`].
        fn timeout(timeout: Duration);
        /// See [`crate::ClientBuilder::reconnection`].
        fn reconnection(reconnection: bool);
        /// See [`crate::ClientBuilder::reconnection_attempts`].
        fn reconnection_attempts(attempts: u32);
        /// See [`crate::ClientBuilder::reconnection_delay`].
        fn reconnection_delay(delay: Duration);
        /// See [`crate::ClientBuilder::reconnection_delay_max`].
        fn reconnection_delay_max(delay: Duration);
        /// See [`crate::ClientBuilder::randomization_factor`].
        fn randomization_factor(factor: f64);
        /// See [`crate::ClientBuilder::reconnect_on_disconnect`].
        fn reconnect_on_disconnect(reconnect: bool);
        /// See [`crate::ClientBuilder::buffer_while_disconnected`].
        fn buffer_while_disconnected(buffer: bool);
        /// See [`crate::ClientBuilder::redact_query`].
        fn redact_query(redact: bool);
        /// See [`crate::ClientBuilder::proxy`].
        fn proxy(proxy: impl Into<String>);
        /// See [`crate::ClientBuilder::no_proxy`].
        fn no_proxy();
    }

    /// See [`crate::ClientBuilder::engine_url`].
    pub fn engine_url(&self) -> Result<url::Url> {
        self.inner.engine_url()
    }

    /// See [`crate::ClientBuilder::connect_params_with`]; `params` runs on a blocking thread
    /// before every connect attempt.
    pub fn connect_params_with<F>(self, params: F) -> Self
    where
        F: Fn() -> crate::ConnectParams + Send + Sync + 'static,
    {
        let params = Arc::new(params);
        let inner = self.inner.connect_params_with(move || {
            let params = Arc::clone(&params);
            async move {
                // a panic stays a panic: the attempt fails with "connect_params_with panicked"
                match tokio::task::spawn_blocking(move || params()).await {
                    Ok(value) => value,
                    Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()),
                    Err(_) => {
                        std::panic::resume_unwind(Box::new("connect_params_with was cancelled"))
                    }
                }
            }
        });
        ClientBuilder { inner, ..self }
    }

    /// See [`crate::ClientBuilder::tls_config`].
    #[cfg(any(feature = "rustls", feature = "native-tls"))]
    pub fn tls_config(self, tls_config: impl Into<TlsConfig>) -> Self {
        ClientBuilder {
            inner: self.inner.tls_config(tls_config),
            ..self
        }
    }

    /// See [`crate::ClientBuilder::auth_with`]; `auth` runs on a blocking thread.
    pub fn auth_with<F>(self, auth: F) -> Self
    where
        F: Fn() -> Value + Send + Sync + 'static,
    {
        let auth = Arc::new(auth);
        let inner = self.inner.auth_with(move || {
            let auth = Arc::clone(&auth);
            async move {
                // a panic stays a panic: the attempt fails with "auth_with panicked"
                match tokio::task::spawn_blocking(move || auth()).await {
                    Ok(value) => value,
                    Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()),
                    Err(_) => std::panic::resume_unwind(Box::new("auth_with was cancelled")),
                }
            }
        });
        ClientBuilder { inner, ..self }
    }

    /// See [`crate::ClientBuilder::inspect_packets`].
    pub fn inspect_packets<F>(self, inspector: F) -> Self
    where
        F: Fn(Direction, &protocol::socketio::Packet) + Send + Sync + 'static,
    {
        ClientBuilder {
            inner: self.inner.inspect_packets(inspector),
            ..self
        }
    }

    /// Handles `event` (on a blocking thread, in arrival order).
    pub fn on<F>(self, event: impl Into<String>, handler: F) -> Self
    where
        F: Fn(Event, Client) + Send + Sync + 'static,
    {
        let handle = self.handle.clone();
        ClientBuilder {
            inner: self.inner.on(event, wrap(handle, handler)),
            ..self
        }
    }

    /// Handles the next `event` only.
    pub fn once<F>(self, event: impl Into<String>, handler: F) -> Self
    where
        F: Fn(Event, Client) + Send + Sync + 'static,
    {
        let handle = self.handle.clone();
        ClientBuilder {
            inner: self.inner.once(event, wrap(handle, handler)),
            ..self
        }
    }

    /// Handles every event.
    pub fn on_any<F>(self, handler: F) -> Self
    where
        F: Fn(Event, Client) + Send + Sync + 'static,
    {
        let handle = self.handle.clone();
        ClientBuilder {
            inner: self.inner.on_any(wrap(handle, handler)),
            ..self
        }
    }

    /// Sees every state transition.
    pub fn on_state_change<F>(self, handler: F) -> Self
    where
        F: Fn(ConnectionState, Client) + Send + Sync + 'static,
    {
        let handle = self.handle.clone();
        ClientBuilder {
            inner: self.inner.on_state_change(wrap(handle, handler)),
            ..self
        }
    }

    /// Connects (see [`crate::ClientBuilder::connect`]), blocking until CONNECT or failure.
    pub fn connect(self) -> Result<Client> {
        let inner = self.handle.block_on(self.inner.connect())?;
        Ok(Client {
            inner,
            handle: self.handle,
            _runtime: Some(self.runtime),
        })
    }
}

fn wrap<A, F>(handle: Handle, handler: F) -> impl Fn(A, crate::Client) + Send + Sync + 'static
where
    A: Send + 'static,
    F: Fn(A, Client) + Send + Sync + 'static,
{
    move |arg, inner| {
        handler(
            arg,
            Client {
                inner,
                handle: handle.clone(),
                _runtime: None,
            },
        )
    }
}

/// The blocking client. Cheap to clone; dropping the last clone the user holds disconnects
/// (bounded, as [`Client::disconnect`]) and stops the runtime. The clients handed to handlers
/// are for the duration of the call; do not keep them after the last user handle is gone.
#[derive(Clone)]
pub struct Client {
    inner: crate::Client,
    handle: Handle,
    _runtime: Option<Arc<RuntimeOwner>>,
}

impl fmt::Debug for Client {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Client").field(&self.inner).finish()
    }
}

impl Drop for Client {
    fn drop(&mut self) {
        // The last user handle: say goodbye before the runtime goes (not possible from inside
        // an async context, where the drop just closes the connection).
        let last = self
            ._runtime
            .as_ref()
            .is_some_and(|runtime| Arc::strong_count(runtime) == 1);
        if last && Handle::try_current().is_err() && !self.inner.state().is_closed() {
            let inner = self.inner.clone();
            self.handle.block_on(async move {
                let _ = tokio::time::timeout(Duration::from_secs(3), inner.disconnect()).await;
            });
        }
    }
}

impl Client {
    /// The async client behind this one.
    pub fn as_async(&self) -> &crate::Client {
        &self.inner
    }

    /// See [`crate::Client::emit`] (never blocks).
    pub fn emit(&self, event: impl AsRef<str>, data: impl Into<Payload>) -> Result<()> {
        self.inner.emit(event, data)
    }

    /// See [`crate::Client::emit_with_ack`]; blocks until the ack, the timeout or the loss.
    pub fn emit_with_ack(
        &self,
        event: impl AsRef<str>,
        data: impl Into<Payload>,
        timeout: Duration,
    ) -> Result<Payload> {
        self.handle
            .block_on(self.inner.emit_with_ack(event, data, timeout))
    }

    /// See [`crate::Client::disconnect`]; blocks (bounded).
    pub fn disconnect(&self) -> Result<()> {
        self.handle.block_on(self.inner.disconnect())
    }

    /// See [`crate::Client::reconnect`]; blocks until the attempt ends.
    pub fn reconnect(&self) -> Result<()> {
        self.handle.block_on(self.inner.reconnect())
    }

    /// Adds a handler for `event`.
    pub fn on<F>(&self, event: impl Into<String>, handler: F) -> ListenerId
    where
        F: Fn(Event, Client) + Send + Sync + 'static,
    {
        self.inner.on(event, wrap(self.handle.clone(), handler))
    }

    /// Adds a handler for the next `event`.
    pub fn once<F>(&self, event: impl Into<String>, handler: F) -> ListenerId
    where
        F: Fn(Event, Client) + Send + Sync + 'static,
    {
        self.inner.once(event, wrap(self.handle.clone(), handler))
    }

    /// Adds a handler for every event.
    pub fn on_any<F>(&self, handler: F) -> ListenerId
    where
        F: Fn(Event, Client) + Send + Sync + 'static,
    {
        self.inner.on_any(wrap(self.handle.clone(), handler))
    }

    /// Adds a handler for every state transition.
    pub fn on_state_change<F>(&self, handler: F) -> ListenerId
    where
        F: Fn(ConnectionState, Client) + Send + Sync + 'static,
    {
        self.inner
            .on_state_change(wrap(self.handle.clone(), handler))
    }

    /// Removes every handler of `event`.
    pub fn off(&self, event: &str) -> usize {
        self.inner.off(event)
    }

    /// Removes every catch-all handler.
    pub fn off_any(&self) -> usize {
        self.inner.off_any()
    }

    /// Removes one handler.
    pub fn off_listener(&self, id: ListenerId) -> bool {
        self.inner.off_listener(id)
    }

    /// Number of handlers of `event`.
    pub fn listener_count(&self, event: &str) -> usize {
        self.inner.listener_count(event)
    }

    /// The current state.
    pub fn state(&self) -> ConnectionState {
        self.inner.state()
    }

    /// Blocks until the state matches `predicate`, the client closed, or `timeout` passed;
    /// returns the state then.
    pub fn wait_for(
        &self,
        predicate: impl Fn(&ConnectionState) -> bool,
        timeout: Duration,
    ) -> ConnectionState {
        self.handle.block_on(async {
            tokio::time::timeout(timeout, self.inner.wait_for(predicate))
                .await
                .unwrap_or_else(|_| self.inner.state())
        })
    }

    /// The namespace is joined right now.
    pub fn connected(&self) -> bool {
        self.inner.connected()
    }

    /// The socket id while connected.
    pub fn id(&self) -> Option<String> {
        self.inner.id()
    }

    /// The last connect restored the session (connection state recovery).
    pub fn recovered(&self) -> bool {
        self.inner.recovered()
    }

    /// The namespace.
    pub fn namespace(&self) -> &str {
        self.inner.namespace()
    }

    /// A snapshot of the link.
    pub fn link_info(&self) -> LinkInfo {
        self.inner.link_info()
    }
}