socketioxide 0.18.3

Socket IO server implementation in rust as a Tower Service.
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! [`ConnectHandler`] trait and implementations, used to handle the connect event.
//! It has a flexible axum-like API, you can put any arguments as long as it implements the [`FromConnectParts`] trait.
//!
//! You can also implement the [`FromConnectParts`] trait for your own types.
//! See the [`extract`](crate::extract) module doc for more details on available extractors.
//!
//! Handlers _must_ be async.
//!
//! # Middlewares
//! [`ConnectHandlers`](ConnectHandler) can have middlewares, they are called before the connection
//! of the socket to the namespace and therefore before the handler.
//!
//! <div class="warning">
//!     Because the socket is not yet connected to the namespace,
//!     you can't send messages to it from the middleware.
//! </div>
//!
//! Middlewares must be async and can be chained.
//! They are defined with the [`ConnectMiddleware`] trait which is automatically implemented for any
//! closure with up to 16 arguments with the following signature:
//! * `async FnOnce(*args) -> Result<(), E> where E: Display`
//!
//! Arguments must implement the [`FromConnectParts`] trait in the exact same way than handlers.
//!
//! ## Example with async closures
//! ```rust
//! # use socketioxide::SocketIo;
//! # use socketioxide::extract::*;
//! let (svc, io) = SocketIo::new_svc();
//! // Here the handler is async and extract the current socket and the auth payload
//! io.ns("/", async |io: SocketIo, s: SocketRef, TryData(auth): TryData<String>| {
//!     println!("Socket connected on / namespace with id and auth data: {} {:?}", s.id, auth);
//! });
//! // Here the handler is async and only extract the current socket.
//! // The auth payload won't be deserialized and will be dropped
//! io.ns("/async_nsp", async |s: SocketRef| {
//!     println!("Socket connected on /async_nsp namespace with id: {}", s.id);
//! });
//! ```
//!
//! ## Example with async non anonymous functions
//! ```rust
//! # use socketioxide::SocketIo;
//! # use socketioxide::extract::*;
//! async fn handler(s: SocketRef, TryData(auth): TryData<String>) {
//!     tokio::time::sleep(std::time::Duration::from_secs(1)).await;
//!     println!("Socket connected on {} namespace with id and auth data: {} {:?}", s.ns(), s.id, auth);
//! }
//!
//! let (svc, io) = SocketIo::new_svc();
//!
//! // You can reuse the same handler for multiple namespaces
//! io.ns("/", handler);
//! io.ns("/admin", handler);
//! ```
//!
//! ## Example with middlewares
//!
//! ```rust
//! # use socketioxide::handler::ConnectHandler;
//! # use socketioxide::extract::*;
//! # use socketioxide::SocketIo;
//! async fn handler(s: SocketRef) {
//!     println!("socket connected on / namespace with id: {}", s.id);
//! }
//!
//! #[derive(Debug)]
//! struct AuthError;
//! impl std::fmt::Display for AuthError {
//!     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
//!         write!(f, "AuthError")
//!     }
//! }
//! impl std::error::Error for AuthError {}
//!
//! async fn middleware(s: SocketRef, Data(token): Data<String>) -> Result<(), AuthError> {
//!     println!("second middleware called");
//!     if token != "secret" {
//!         Err(AuthError)
//!     } else {
//!         Ok(())
//!     }
//! }
//!
//! async fn other_middleware(s: SocketRef) -> Result<(), AuthError> {
//!     println!("first middleware called");
//!     if s.req_parts().uri.query().map(|q| q.contains("secret")).unwrap_or_default() {
//!         Err(AuthError)
//!     } else {
//!         Ok(())
//!     }
//! }
//!
//! let (_, io) = SocketIo::new_layer();
//! io.ns("/", handler.with(middleware).with(other_middleware));
//! ```

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use crate::{adapter::Adapter, socket::Socket};
use socketioxide_core::Value;

use super::MakeErasedHandler;

/// A Type Erased [`ConnectHandler`] so it can be stored in a HashMap
pub(crate) type BoxedConnectHandler<A> = Box<dyn ErasedConnectHandler<A>>;

type MiddlewareRes = Result<(), Box<dyn std::fmt::Display + Send>>;
type MiddlewareResFut<'a> = Pin<Box<dyn Future<Output = MiddlewareRes> + Send + 'a>>;

pub(crate) trait ErasedConnectHandler<A: Adapter>: Send + Sync + 'static {
    fn call(&self, s: Arc<Socket<A>>, auth: Option<Value>);
    fn call_middleware<'a>(
        &'a self,
        s: Arc<Socket<A>>,
        auth: &'a Option<Value>,
    ) -> MiddlewareResFut<'a>;

    fn boxed_clone(&self) -> BoxedConnectHandler<A>;
}

/// A trait used to extract the arguments from the connect event.
/// The `Result` associated type is used to return an error if the extraction fails,
/// in this case the [`ConnectHandler`] is not called.
///
/// * See the [`connect`](super::connect) module doc for more details on connect handler.
/// * See the [`extract`](crate::extract) module doc for more details on available extractors.
#[diagnostic::on_unimplemented(
    note = "Function argument is not a valid socketio extractor.
See `https://docs.rs/socketioxide/latest/socketioxide/extract/index.html` for details",
    label = "Invalid extractor"
)]
pub trait FromConnectParts<A: Adapter>: Sized {
    /// The error type returned by the extractor
    type Error: std::error::Error + Send + 'static;

    /// Extract the arguments from the connect event.
    /// If it fails, the handler is not called
    fn from_connect_parts(s: &Arc<Socket<A>>, auth: &Option<Value>) -> Result<Self, Self::Error>;
}

/// Define a middleware for the connect event.
/// It is implemented for closures with up to 16 arguments.
/// They must implement the [`FromConnectParts`] trait and return `Result<(), E> where E: Display`.
///
/// * See the [`connect`](super::connect) module doc for more details on connect middlewares.
/// * See the [`extract`](crate::extract) module doc for more details on available extractors.
#[diagnostic::on_unimplemented(
    note = "This function is not a ConnectMiddleware. Check that:
* It is a clonable async `FnOnce` that returns `Result<(), E> where E: Display`.
* All its arguments are valid connect extractors.
* If you use a custom adapter, it must be generic over the adapter type.
See `https://docs.rs/socketioxide/latest/socketioxide/extract/index.html` for details.\n",
    label = "Invalid ConnectMiddleware"
)]
pub trait ConnectMiddleware<A: Adapter, T>: Sized + Clone + Send + Sync + 'static {
    /// Call the middleware with the given arguments.
    fn call<'a>(
        &'a self,
        s: Arc<Socket<A>>,
        auth: &'a Option<Value>,
    ) -> impl Future<Output = MiddlewareRes> + Send;

    #[doc(hidden)]
    fn phantom(&self) -> std::marker::PhantomData<(A, T)> {
        std::marker::PhantomData
    }
}

/// Define a handler for the connect event.
/// It is implemented for closures with up to 16 arguments. They must implement the [`FromConnectParts`] trait.
///
/// * See the [`connect`](super::connect) module doc for more details on connect handler.
/// * See the [`extract`](crate::extract) module doc for more details on available extractors.
#[diagnostic::on_unimplemented(
    note = "This function is not a ConnectHandler. Check that:
* It is a clonable async `FnOnce` that returns nothing.
* All its arguments are valid connect extractors.
* If you use a custom adapter, it must be generic over the adapter type.
See `https://docs.rs/socketioxide/latest/socketioxide/extract/index.html` for details.\n",
    label = "Invalid ConnectHandler"
)]
pub trait ConnectHandler<A: Adapter, T>: Sized + Clone + Send + Sync + 'static {
    /// Call the handler with the given arguments.
    fn call(&self, s: Arc<Socket<A>>, auth: Option<Value>);

    /// Call the middleware with the given arguments.
    fn call_middleware<'a>(
        &'a self,
        _: Arc<Socket<A>>,
        _: &'a Option<Value>,
    ) -> MiddlewareResFut<'a> {
        Box::pin(async move { Ok(()) })
    }

    /// Wraps this [`ConnectHandler`] with a new [`ConnectMiddleware`].
    /// The new provided middleware will be called before the current one.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use socketioxide::handler::ConnectHandler;
    /// # use socketioxide::extract::*;
    /// # use socketioxide::SocketIo;
    /// async fn handler(s: SocketRef) {
    ///     println!("socket connected on / namespace with id: {}", s.id);
    /// }
    ///
    /// #[derive(Debug)]
    /// struct AuthError;
    /// impl std::fmt::Display for AuthError {
    ///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    ///         write!(f, "AuthError")
    ///     }
    /// }
    /// impl std::error::Error for AuthError {}
    ///
    /// async fn middleware(s: SocketRef, Data(token): Data<String>) -> Result<(), AuthError> {
    ///     println!("second middleware called");
    ///     if token != "secret" {
    ///         Err(AuthError)
    ///     } else {
    ///         Ok(())
    ///     }
    /// }
    ///
    /// async fn other_middleware(s: SocketRef) -> Result<(), AuthError> {
    ///     println!("first middleware called");
    ///     if s.req_parts().uri.query().map(|q| q.contains("secret")).unwrap_or_default() {
    ///         Err(AuthError)
    ///     } else {
    ///         Ok(())
    ///     }
    /// }
    ///
    /// let (_, io) = SocketIo::new_layer();
    /// io.ns("/", handler.with(middleware).with(other_middleware));
    /// ```
    fn with<M, T1>(self, middleware: M) -> impl ConnectHandler<A, T>
    where
        M: ConnectMiddleware<A, T1> + Send + Sync + 'static,
        T: Send + Sync + 'static,
        T1: Send + Sync + 'static,
    {
        LayeredConnectHandler {
            handler: self,
            middleware,
            phantom: std::marker::PhantomData,
        }
    }

    #[doc(hidden)]
    fn phantom(&self) -> std::marker::PhantomData<T> {
        std::marker::PhantomData
    }
}
struct LayeredConnectHandler<A, H, M, T, T1> {
    handler: H,
    middleware: M,
    phantom: std::marker::PhantomData<(A, T, T1)>,
}
struct ConnectMiddlewareLayer<M, N, T, T1> {
    middleware: M,
    next: N,
    phantom: std::marker::PhantomData<(T, T1)>,
}

impl<A: Adapter, T, H> MakeErasedHandler<H, A, T>
where
    H: ConnectHandler<A, T> + Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    pub fn new_ns_boxed(inner: H) -> Box<dyn ErasedConnectHandler<A>> {
        Box::new(MakeErasedHandler::new(inner))
    }
}

impl<A: Adapter, T, H> ErasedConnectHandler<A> for MakeErasedHandler<H, A, T>
where
    H: ConnectHandler<A, T> + Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    #[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip(self, s), fields(id = ?s.id)))]
    fn call(&self, s: Arc<Socket<A>>, auth: Option<Value>) {
        self.handler.call(s, auth);
    }

    fn call_middleware<'a>(
        &'a self,
        s: Arc<Socket<A>>,
        auth: &'a Option<Value>,
    ) -> MiddlewareResFut<'a> {
        self.handler.call_middleware(s, auth)
    }

    fn boxed_clone(&self) -> BoxedConnectHandler<A> {
        Box::new(self.clone())
    }
}

#[diagnostic::do_not_recommend]
impl<A, H, M, T, T1> ConnectHandler<A, T> for LayeredConnectHandler<A, H, M, T, T1>
where
    A: Adapter,
    H: ConnectHandler<A, T> + Send + Sync + 'static,
    M: ConnectMiddleware<A, T1> + Send + Sync + 'static,
    T: Send + Sync + 'static,
    T1: Send + Sync + 'static,
{
    fn call(&self, s: Arc<Socket<A>>, auth: Option<Value>) {
        self.handler.call(s, auth);
    }

    fn call_middleware<'a>(
        &'a self,
        s: Arc<Socket<A>>,
        auth: &'a Option<Value>,
    ) -> MiddlewareResFut<'a> {
        Box::pin(async move { self.middleware.call(s, auth).await })
    }

    fn with<M2, T2>(self, next: M2) -> impl ConnectHandler<A, T>
    where
        M2: ConnectMiddleware<A, T2> + Send + Sync + 'static,
        T2: Send + Sync + 'static,
    {
        LayeredConnectHandler {
            handler: self.handler,
            middleware: ConnectMiddlewareLayer {
                middleware: next,
                next: self.middleware,
                phantom: std::marker::PhantomData,
            },
            phantom: std::marker::PhantomData,
        }
    }
}

#[diagnostic::do_not_recommend]
impl<A, H, N, T, T1> ConnectMiddleware<A, T1> for LayeredConnectHandler<A, H, N, T, T1>
where
    A: Adapter,
    H: ConnectHandler<A, T> + Send + Sync + 'static,
    N: ConnectMiddleware<A, T1> + Send + Sync + 'static,
    T: Send + Sync + 'static,
    T1: Send + Sync + 'static,
{
    async fn call<'a>(&'a self, s: Arc<Socket<A>>, auth: &'a Option<Value>) -> MiddlewareRes {
        self.middleware.call(s, auth).await
    }
}
impl<A, H, N, T, T1> Clone for LayeredConnectHandler<A, H, N, T, T1>
where
    H: Clone,
    N: Clone,
{
    fn clone(&self) -> Self {
        Self {
            handler: self.handler.clone(),
            middleware: self.middleware.clone(),
            phantom: self.phantom,
        }
    }
}
impl<M, N, T, T1> Clone for ConnectMiddlewareLayer<M, N, T, T1>
where
    M: Clone,
    N: Clone,
{
    fn clone(&self) -> Self {
        Self {
            middleware: self.middleware.clone(),
            next: self.next.clone(),
            phantom: self.phantom,
        }
    }
}

#[diagnostic::do_not_recommend]
impl<A, M, N, T, T1> ConnectMiddleware<A, T> for ConnectMiddlewareLayer<M, N, T, T1>
where
    A: Adapter,
    M: ConnectMiddleware<A, T> + Send + Sync + 'static,
    N: ConnectMiddleware<A, T1> + Send + Sync + 'static,
    T: Send + Sync + 'static,
    T1: Send + Sync + 'static,
{
    async fn call<'a>(&'a self, s: Arc<Socket<A>>, auth: &'a Option<Value>) -> MiddlewareRes {
        self.middleware.call(s.clone(), auth).await?;
        self.next.call(s, auth).await
    }
}

macro_rules! impl_handler_async {
    (
        [$($ty:ident),*]
    ) => {
        #[allow(non_snake_case, unused)]
        #[diagnostic::do_not_recommend]
        impl<A, F, Fut, $($ty,)*> ConnectHandler<A, ($($ty,)*)> for F
        where
            F: FnOnce($($ty,)*) -> Fut + Send + Sync + Clone + 'static,
            Fut: Future<Output = ()> + Send + 'static,
            A: Adapter,
            $( $ty: FromConnectParts<A> + Send, )*
        {
            fn call(&self, s: Arc<Socket<A>>, auth: Option<Value>) {
                $(
                    let $ty = match $ty::from_connect_parts(&s, &auth) {
                        Ok(v) => v,
                        Err(_e) => {
                            #[cfg(feature = "tracing")]
                            tracing::error!("Error while extracting data: {}", _e);
                            return;
                        },
                    };
                )*

                let fut = (self.clone())($($ty,)*);
                tokio::spawn(fut);
            }
        }
    };
}

macro_rules! impl_middleware_async {
    (
        [$($ty:ident),*]
    ) => {
        #[allow(non_snake_case, unused)]
        #[diagnostic::do_not_recommend]
        impl<A, F, Fut, E, $($ty,)*> ConnectMiddleware<A, ($($ty,)*)> for F
        where
            F: FnOnce($($ty,)*) -> Fut + Send + Sync + Clone + 'static,
            Fut: Future<Output = Result<(), E>> + Send + 'static,
            A: Adapter,
            E: std::fmt::Display + Send + 'static,
            $( $ty: FromConnectParts<A> + Send, )*
        {
            async fn call<'a>(
                &'a self,
                s: Arc<Socket<A>>,
                auth: &'a Option<Value>,
            ) -> MiddlewareRes {
                $(
                    let $ty = match $ty::from_connect_parts(&s, auth) {
                        Ok(v) => v,
                        Err(e) => {
                            #[cfg(feature = "tracing")]
                            tracing::error!("Error while extracting data: {}", e);
                            return Err(Box::new(e) as _);
                        },
                    };
                )*

                let res = (self.clone())($($ty,)*).await;
                if let Err(e) = res {
                    #[cfg(feature = "tracing")]
                    tracing::trace!("middleware returned error: {}", e);
                    Err(Box::new(e) as _)
                } else {
                    Ok(())
                }
            }
        }
    };
}

#[rustfmt::skip]
macro_rules! all_the_tuples {
    ($name:ident) => {
        $name!([]);
        $name!([T1]);
        $name!([T1, T2]);
        $name!([T1, T2, T3]);
        $name!([T1, T2, T3, T4]);
        $name!([T1, T2, T3, T4, T5]);
        $name!([T1, T2, T3, T4, T5, T6]);
        $name!([T1, T2, T3, T4, T5, T6, T7]);
        $name!([T1, T2, T3, T4, T5, T6, T7, T8]);
        $name!([T1, T2, T3, T4, T5, T6, T7, T8, T9]);
        $name!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]);
        $name!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11]);
        $name!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12]);
        $name!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13]);
        $name!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14]);
        $name!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15]);
        $name!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16]);
    };
}

all_the_tuples!(impl_handler_async);
all_the_tuples!(impl_middleware_async);