Skip to main content

socketio_next/
client.rs

1use std::cell::Cell;
2use std::fmt;
3use std::panic::AssertUnwindSafe;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Arc, Mutex, PoisonError, Weak};
6use std::time::Duration;
7
8use futures_util::FutureExt;
9use tokio::sync::{mpsc, oneshot, watch};
10use tokio::task::JoinHandle;
11
12use crate::actor::{Actor, Command, Dispatch};
13use crate::builder::Config;
14use crate::handler::{Handler, Handlers, ListenerId};
15use crate::protocol::socketio::{Packet, is_reserved_event};
16use crate::state::LinkInfo;
17use crate::{ConnectionState, Error, Event, Payload, Result};
18
19tokio::task_local! {
20    /// Set while the event task runs a handler.
21    static IN_HANDLER_TASK: ();
22}
23
24thread_local! {
25    /// Set while a blocking-pool thread runs a sync handler.
26    pub(crate) static IN_HANDLER_THREAD: Cell<bool> = const { Cell::new(false) };
27}
28
29fn in_handler() -> bool {
30    IN_HANDLER_TASK.try_with(|_| ()).is_ok() || IN_HANDLER_THREAD.with(Cell::get)
31}
32
33/// How long `disconnect()` waits for running handlers before it mutes the rest.
34const HANDLER_DRAIN: Duration = Duration::from_secs(5);
35
36pub(crate) struct Inner {
37    /// The running actor's command queue (replaced by `reconnect()`).
38    cmd: Mutex<mpsc::UnboundedSender<Command>>,
39    /// Dropped with the last handle (or replaced): tells the actor to stop.
40    _shutdown: Mutex<oneshot::Sender<()>>,
41    state: watch::Receiver<ConnectionState>,
42    state_tx: watch::Sender<ConnectionState>,
43    config: Config,
44    url: url::Url,
45    /// One `reconnect()` at a time.
46    restart: tokio::sync::Mutex<()>,
47    /// Counts `disconnect()` calls. Held while an actor is started or a disconnect takes the
48    /// running one, so a disconnect wins over a concurrent `reconnect()`.
49    lifecycle: Mutex<u64>,
50    handlers: Mutex<Handlers>,
51    shared: Arc<Shared>,
52    nsp: Arc<str>,
53    buffer_while_disconnected: bool,
54    actor: Mutex<Option<JoinHandle<()>>>,
55    dispatcher: Mutex<Option<JoinHandle<()>>>,
56}
57
58/// State the actor writes and the handles read.
59#[derive(Debug, Default)]
60pub(crate) struct Shared {
61    pub(crate) connected: AtomicBool,
62    pub(crate) closed: AtomicBool,
63    /// No handler runs once set (after `disconnect()` returned).
64    pub(crate) muted: AtomicBool,
65    pub(crate) link: Mutex<LinkInfo>,
66}
67
68impl Shared {
69    pub(crate) fn link(&self) -> std::sync::MutexGuard<'_, LinkInfo> {
70        self.link.lock().unwrap_or_else(PoisonError::into_inner)
71    }
72}
73
74/// A connected socket.io client (one namespace). Cheap to clone; all clones are one client.
75///
76/// Dropping the last clone closes the connection. Handlers get a clone for the duration of
77/// the call.
78#[derive(Clone)]
79pub struct Client {
80    inner: Arc<Inner>,
81}
82
83impl fmt::Debug for Client {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        f.debug_struct("Client")
86            .field("nsp", &self.inner.nsp)
87            .field("state", &*self.inner.state.borrow())
88            .finish_non_exhaustive()
89    }
90}
91
92pub(crate) async fn connect(config: Config, handlers: Handlers) -> Result<Client> {
93    let (cmd_tx, _) = mpsc::unbounded_channel();
94    let (shutdown_tx, _) = oneshot::channel();
95    let (state_tx, state_rx) = watch::channel(ConnectionState::Connecting { attempt: 0 });
96    let (url, nsp) = resolve(&config)?;
97    let inner = Arc::new(Inner {
98        cmd: Mutex::new(cmd_tx),
99        _shutdown: Mutex::new(shutdown_tx),
100        state: state_rx,
101        state_tx,
102        handlers: Mutex::new(handlers),
103        shared: Arc::new(Shared::default()),
104        nsp: nsp.into(),
105        buffer_while_disconnected: config.buffer_while_disconnected,
106        config,
107        url,
108        restart: tokio::sync::Mutex::new(()),
109        lifecycle: Mutex::new(0),
110        actor: Mutex::default(),
111        dispatcher: Mutex::default(),
112    });
113    let ready = start(&inner);
114    match ready.await {
115        Ok(Ok(())) => Ok(Client { inner }),
116        Ok(Err(err)) => Err(err),
117        Err(_) => Err(Error::Closed),
118    }
119}
120
121/// Spawns the event task and the connection task for `inner`; the receiver resolves with the
122/// first connect attempt.
123fn start(inner: &Arc<Inner>) -> oneshot::Receiver<Result<()>> {
124    let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
125    let (shutdown_tx, shutdown_rx) = oneshot::channel();
126    let (dispatch_tx, dispatch_rx) = mpsc::unbounded_channel();
127    let (ready_tx, ready_rx) = oneshot::channel();
128    inner
129        .state_tx
130        .send_replace(ConnectionState::Connecting { attempt: 0 });
131    let shared = Arc::clone(&inner.shared);
132    shared.closed.store(false, Ordering::Release);
133    shared.muted.store(false, Ordering::Release);
134    *inner.cmd.lock().unwrap_or_else(PoisonError::into_inner) = cmd_tx.clone();
135    *inner
136        ._shutdown
137        .lock()
138        .unwrap_or_else(PoisonError::into_inner) = shutdown_tx;
139
140    let dispatcher = tokio::spawn(dispatch(dispatch_rx, Arc::downgrade(inner)));
141    let panic_state = inner.state_tx.clone();
142    let actor = Actor::new(
143        inner.config.clone(),
144        inner.url.clone(),
145        Arc::clone(&inner.nsp),
146        cmd_rx,
147        cmd_tx,
148        shutdown_rx,
149        inner.state_tx.clone(),
150        dispatch_tx,
151        Arc::clone(&shared),
152    );
153    // A bug in the connection task must not leave the state at `Connected` forever.
154    let actor = tokio::spawn(async move {
155        if AssertUnwindSafe(actor.run(ready_tx))
156            .catch_unwind()
157            .await
158            .is_err()
159        {
160            tracing::error!("the socket.io connection task panicked; the client is closed");
161            shared.connected.store(false, Ordering::Release);
162            shared.closed.store(true, Ordering::Release);
163            panic_state.send_replace(ConnectionState::Closed {
164                reason: crate::DisconnectReason::TransportError,
165                error: None,
166            });
167        }
168    });
169    *inner.actor.lock().unwrap_or_else(PoisonError::into_inner) = Some(actor);
170    *inner
171        .dispatcher
172        .lock()
173        .unwrap_or_else(PoisonError::into_inner) = Some(dispatcher);
174    ready_rx
175}
176
177/// The engine.io URL and the namespace: like socket.io-client, the URL path is the namespace
178/// unless one is set explicitly; the engine.io path comes from the builder.
179pub(crate) fn resolve(config: &Config) -> Result<(url::Url, String)> {
180    let mut url = url::Url::parse(&config.address)?;
181    let url_nsp = match url.path() {
182        "" | "/" => None,
183        path => Some(percent_decode(path)),
184    };
185    let nsp = config
186        .namespace
187        .clone()
188        .or(url_nsp)
189        .unwrap_or_else(|| "/".to_owned());
190    url.set_path(&config.path);
191    if !config.query.is_empty() {
192        url.query_pairs_mut().extend_pairs(&config.query);
193    }
194    Ok((url, nsp))
195}
196
197/// `%XX` escapes of a URL path back to UTF-8 (the namespace is compared as text).
198fn percent_decode(path: &str) -> String {
199    let bytes = path.as_bytes();
200    let mut out = Vec::with_capacity(bytes.len());
201    let mut i = 0;
202    while i < bytes.len() {
203        let hex = |b: u8| (b as char).to_digit(16);
204        if bytes[i] == b'%' && i + 2 < bytes.len() {
205            if let (Some(h), Some(l)) = (hex(bytes[i + 1]), hex(bytes[i + 2])) {
206                out.push((h * 16 + l) as u8);
207                i += 3;
208                continue;
209            }
210        }
211        out.push(bytes[i]);
212        i += 1;
213    }
214    String::from_utf8_lossy(&out).into_owned()
215}
216
217/// Runs handlers one at a time, in order. Holds only a weak reference, so it never keeps the
218/// client alive.
219///
220/// ponytail: the queue is unbounded (like socket.io-client's event emitter); a server that
221/// floods events faster than slow handlers finish grows memory. Add a bound if that matters.
222async fn dispatch(mut rx: mpsc::UnboundedReceiver<Dispatch>, inner: Weak<Inner>) {
223    while let Some(item) = rx.recv().await {
224        let Some(strong) = inner.upgrade() else {
225            break;
226        };
227        if strong.shared.muted.load(Ordering::Acquire) {
228            continue;
229        }
230        let client = Client {
231            inner: Arc::clone(&strong),
232        };
233        drop(strong);
234        match item {
235            Dispatch::Event(event) => {
236                let handlers = client.handlers().take_for_event(event.name());
237                for handler in handlers {
238                    if client.inner.shared.muted.load(Ordering::Acquire) {
239                        break;
240                    }
241                    run(handler(event.clone(), client.clone())).await;
242                }
243            }
244            Dispatch::State(state) => {
245                let handlers = client.handlers().state_handlers();
246                for handler in handlers {
247                    if client.inner.shared.muted.load(Ordering::Acquire) {
248                        break;
249                    }
250                    run(handler(state.clone(), client.clone())).await;
251                }
252            }
253        }
254    }
255}
256
257/// One handler call; a panic is logged and does not stop the event task.
258async fn run(fut: futures_util::future::BoxFuture<'static, ()>) {
259    if IN_HANDLER_TASK
260        .scope((), AssertUnwindSafe(fut).catch_unwind())
261        .await
262        .is_err()
263    {
264        tracing::error!("an event handler panicked");
265    }
266}
267
268impl Client {
269    fn cmd(&self) -> mpsc::UnboundedSender<Command> {
270        self.inner
271            .cmd
272            .lock()
273            .unwrap_or_else(PoisonError::into_inner)
274            .clone()
275    }
276
277    /// Connects again after the client closed (a `ConnectRejected`, `ReconnectFailed`, a
278    /// server disconnect without `reconnect_on_disconnect`, or `disconnect()`), with the same
279    /// handlers and options; `auth_with` and `connect_params_with` run again, so a new token
280    /// can be handed in first. Resolves like `connect()`: once the server accepted the
281    /// namespace, or with the error of that attempt (the client then stays closed). A no-op
282    /// while the client is not closed. Must not be called from one of its handlers.
283    pub async fn reconnect(&self) -> Result<()> {
284        let _guard = self.inner.restart.lock().await;
285        let seen = *self.lifecycle();
286        if !self.state().is_closed() {
287            return Ok(());
288        }
289        // the previous tasks end on their own once closed; wait so none outlives the restart
290        let actor = self
291            .inner
292            .actor
293            .lock()
294            .unwrap_or_else(PoisonError::into_inner)
295            .take();
296        if let Some(actor) = actor {
297            let _ = actor.await;
298        }
299        let dispatcher = self
300            .inner
301            .dispatcher
302            .lock()
303            .unwrap_or_else(PoisonError::into_inner)
304            .take();
305        if let Some(dispatcher) = dispatcher {
306            if tokio::time::timeout(HANDLER_DRAIN, &mut Box::pin(dispatcher))
307                .await
308                .is_err()
309            {
310                tracing::warn!(
311                    "handlers still running after {HANDLER_DRAIN:?}; reconnecting anyway"
312                );
313            }
314        }
315        #[cfg(test)]
316        tests::reconnect_pause(&self.inner.nsp).await;
317        let ready = {
318            let lifecycle = self.lifecycle();
319            // a disconnect() since this call began wins: the client stays closed
320            if *lifecycle != seen {
321                return Err(Error::Closed);
322            }
323            start(&self.inner)
324        };
325        match ready.await {
326            Ok(result) => result,
327            Err(_) => Err(Error::Closed),
328        }
329    }
330
331    fn lifecycle(&self) -> std::sync::MutexGuard<'_, u64> {
332        self.inner
333            .lifecycle
334            .lock()
335            .unwrap_or_else(PoisonError::into_inner)
336    }
337
338    fn handlers(&self) -> std::sync::MutexGuard<'_, Handlers> {
339        self.inner
340            .handlers
341            .lock()
342            .unwrap_or_else(PoisonError::into_inner)
343    }
344
345    fn event_packet(&self, event: &str, data: Payload) -> Result<Packet> {
346        if is_reserved_event(event) {
347            return Err(Error::ReservedEvent(event.to_owned()));
348        }
349        Ok(Packet::new_event(data, event, &self.inner.nsp, None)?)
350    }
351
352    fn check_open(&self) -> Result<()> {
353        let shared = &self.inner.shared;
354        if shared.closed.load(Ordering::Acquire) {
355            return Err(Error::Closed);
356        }
357        if !self.inner.buffer_while_disconnected && !shared.connected.load(Ordering::Acquire) {
358            return Err(Error::NotConnected);
359        }
360        Ok(())
361    }
362
363    /// Sends `event` with `data` ([`Payload`], `serde_json::Value`, a string, bytes, `()` for
364    /// no arguments). Never blocks: the packet is queued for the connection task.
365    ///
366    /// Fails with [`Error::NotConnected`] while disconnected (unless
367    /// `buffer_while_disconnected`), [`Error::Closed`] after the client closed, and
368    /// [`Error::ReservedEvent`] for `connect`, `disconnect`, ...
369    pub fn emit(&self, event: impl AsRef<str>, data: impl Into<Payload>) -> Result<()> {
370        let packet = self.event_packet(event.as_ref(), data.into())?;
371        self.check_open()?;
372        self.cmd()
373            .send(Command::Emit { packet, ack: None })
374            .map_err(|_| Error::Closed)
375    }
376
377    /// Sends `event` and waits for the server's ack (socket.io-client
378    /// `socket.timeout(ms).emitWithAck(...)`). Resolves with the ack's arguments, or fails with
379    /// [`Error::AckTimeout`] after `timeout`, [`Error::Disconnected`] when the connection drops
380    /// first. Dropping the future forgets the ack.
381    pub async fn emit_with_ack(
382        &self,
383        event: impl AsRef<str>,
384        data: impl Into<Payload>,
385        timeout: Duration,
386    ) -> Result<Payload> {
387        let packet = self.event_packet(event.as_ref(), data.into())?;
388        self.check_open()?;
389        let (tx, rx) = oneshot::channel();
390        self.cmd()
391            .send(Command::Emit {
392                packet,
393                ack: Some((tx, timeout)),
394            })
395            .map_err(|_| Error::Closed)?;
396        rx.await.map_err(|_| Error::Closed)?
397    }
398
399    /// Adds a handler for `event`; returns its id for [`off_listener`](Self::off_listener).
400    pub fn on<M>(&self, event: impl Into<String>, handler: impl Handler<Event, M>) -> ListenerId {
401        self.handlers()
402            .on(event.into(), handler.into_boxed(), false)
403    }
404
405    /// Adds a handler for the next `event` only.
406    pub fn once<M>(&self, event: impl Into<String>, handler: impl Handler<Event, M>) -> ListenerId {
407        self.handlers().on(event.into(), handler.into_boxed(), true)
408    }
409
410    /// Adds a handler for every event (socket.io-client `onAny`).
411    pub fn on_any<M>(&self, handler: impl Handler<Event, M>) -> ListenerId {
412        self.handlers().on_any(handler.into_boxed())
413    }
414
415    /// Adds a handler for every [`ConnectionState`] transition.
416    pub fn on_state_change<M>(&self, handler: impl Handler<ConnectionState, M>) -> ListenerId {
417        self.handlers().on_state(handler.into_boxed())
418    }
419
420    /// Removes every handler of `event`; returns how many.
421    pub fn off(&self, event: &str) -> usize {
422        self.handlers().off(event)
423    }
424
425    /// Removes every catch-all handler; returns how many.
426    pub fn off_any(&self) -> usize {
427        self.handlers().off_any()
428    }
429
430    /// Removes one handler; `false` when it was gone already (a `once` handler that ran).
431    pub fn off_listener(&self, id: ListenerId) -> bool {
432        self.handlers().off_listener(id)
433    }
434
435    /// Number of handlers of `event` (socket.io-client `listeners(event).length`).
436    pub fn listener_count(&self, event: &str) -> usize {
437        self.handlers().listener_count(event)
438    }
439
440    /// The current state.
441    pub fn state(&self) -> ConnectionState {
442        self.inner.state.borrow().clone()
443    }
444
445    /// A watch of the state: `changed().await` wakes on transitions (a slow reader sees the
446    /// latest; use [`on_state_change`](Self::on_state_change) to see every one).
447    pub fn state_watch(&self) -> watch::Receiver<ConnectionState> {
448        self.inner.state.clone()
449    }
450
451    /// Waits until the state matches `predicate` (or the client closed).
452    pub async fn wait_for(&self, predicate: impl Fn(&ConnectionState) -> bool) -> ConnectionState {
453        let mut watch = self.inner.state.clone();
454        loop {
455            let state = watch.borrow_and_update().clone();
456            if predicate(&state) || state.is_closed() {
457                return state;
458            }
459            if watch.changed().await.is_err() {
460                return watch.borrow().clone();
461            }
462        }
463    }
464
465    /// The namespace is joined right now.
466    pub fn connected(&self) -> bool {
467        self.inner.shared.connected.load(Ordering::Acquire)
468    }
469
470    /// The socket id while connected (`socket.id`).
471    pub fn id(&self) -> Option<String> {
472        self.inner.shared.link().sid.clone()
473    }
474
475    /// The namespace of this client.
476    pub fn namespace(&self) -> &str {
477        &self.inner.nsp
478    }
479
480    /// The last connect restored the session (connection state recovery, `socket.recovered`).
481    pub fn recovered(&self) -> bool {
482        matches!(
483            self.state(),
484            ConnectionState::Connected {
485                recovered: true,
486                ..
487            }
488        )
489    }
490
491    /// A snapshot of the link: transport, sids, heartbeat, last packet, attempts.
492    pub fn link_info(&self) -> LinkInfo {
493        self.inner.shared.link().clone()
494    }
495
496    /// Leaves the namespace (DISCONNECT packet), closes the connection and stops reconnecting.
497    ///
498    /// Bounded: the goodbye (queued packets, DISCONNECT, engine.io close) gets at most 2 s on a
499    /// dead link. Events already received are still handled; handlers get up to 5 s in total,
500    /// then the event task is stopped. When it returns no handler starts any more. Safe to call
501    /// from inside a handler (it then does not wait for the handlers; the event task ends after
502    /// the running handler).
503    pub async fn disconnect(&self) -> Result<()> {
504        // The actor this call stops, its command queue and event task, taken together: a
505        // concurrent `reconnect()` either started its actor before (it is stopped here) or
506        // sees the count change and does not start one.
507        let (cmd, actor, dispatcher) = {
508            let mut lifecycle = self.lifecycle();
509            *lifecycle += 1;
510            let actor = self
511                .inner
512                .actor
513                .lock()
514                .unwrap_or_else(PoisonError::into_inner)
515                .take();
516            let dispatcher = if in_handler() {
517                None
518            } else {
519                self.inner
520                    .dispatcher
521                    .lock()
522                    .unwrap_or_else(PoisonError::into_inner)
523                    .take()
524            };
525            (self.cmd(), actor, dispatcher)
526        };
527        let (tx, rx) = oneshot::channel();
528        if cmd.send(Command::Disconnect { done: tx }).is_ok() {
529            let _ = rx.await;
530        }
531        if let Some(actor) = actor {
532            let _ = actor.await;
533        }
534        {
535            if let Some(mut dispatcher) = dispatcher {
536                if tokio::time::timeout(HANDLER_DRAIN, &mut dispatcher)
537                    .await
538                    .is_err()
539                {
540                    // a handler is stuck: stop the event task so nothing else starts
541                    tracing::warn!(
542                        "handlers still running after {HANDLER_DRAIN:?}; event task stopped"
543                    );
544                    dispatcher.abort();
545                    let _ = dispatcher.await;
546                }
547            }
548        }
549        self.inner.shared.muted.store(true, Ordering::Release);
550        Ok(())
551    }
552}
553
554impl Drop for Inner {
555    fn drop(&mut self) {
556        // The actor stops when `_shutdown` drops right after this; nothing may run any more.
557        self.shared.muted.store(true, Ordering::Release);
558    }
559}
560
561#[cfg(test)]
562mod tests {
563    use super::*;
564    use std::sync::OnceLock;
565    use tokio::sync::Notify;
566
567    /// (namespace, reached, go): `reconnect()` of a client of that namespace (only: other
568    /// tests reconnect in parallel) waits between its awaits and the start.
569    type Pause = (String, Arc<Notify>, Arc<Notify>);
570    static PAUSE: OnceLock<Mutex<Option<Pause>>> = OnceLock::new();
571
572    pub(super) async fn reconnect_pause(nsp: &str) {
573        let pause = PAUSE.get_or_init(Mutex::default).lock().unwrap().clone();
574        if let Some((target, reached, go)) = pause {
575            if target == nsp {
576                reached.notify_one();
577                go.notified().await;
578            }
579        }
580    }
581
582    async fn closed_client(url: String) -> Client {
583        let client = crate::ClientBuilder::new(url).connect().await.unwrap();
584        client.emit("server_disconnect", ()).unwrap();
585        client.wait_for(ConnectionState::is_closed).await;
586        client
587    }
588
589    /// Case A: `disconnect()` while `reconnect()` waits for the old tasks: the client must
590    /// stay closed (it was revived before).
591    #[tokio::test(flavor = "multi_thread")]
592    async fn disconnect_during_reconnect_wins() {
593        tokio::time::timeout(std::time::Duration::from_secs(90), async move {
594            let client = closed_client(socketio_next_testing::socket_io_server()).await;
595            let (reached, go) = (Arc::new(Notify::new()), Arc::new(Notify::new()));
596            *PAUSE.get_or_init(Mutex::default).lock().unwrap() =
597                Some(("/".into(), Arc::clone(&reached), Arc::clone(&go)));
598            let reconnecting = {
599                let client = client.clone();
600                tokio::spawn(async move { client.reconnect().await })
601            };
602            reached.notified().await;
603            *PAUSE.get().unwrap().lock().unwrap() = None;
604            client.disconnect().await.unwrap();
605            go.notify_one();
606            let result = tokio::time::timeout(Duration::from_secs(5), reconnecting)
607                .await
608                .unwrap()
609                .unwrap();
610            assert!(matches!(result, Err(Error::Closed)), "{result:?}");
611            tokio::time::sleep(Duration::from_millis(300)).await;
612            assert!(client.state().is_closed() && !client.connected());
613        })
614        .await
615        .expect("test `disconnect_during_reconnect_wins` timed out")
616    }
617
618    /// Case B: `disconnect()` while the restarted connection task is connecting (a namespace
619    /// that answers CONNECT after 200 ms) returns promptly and leaves the client closed.
620    #[tokio::test(flavor = "multi_thread")]
621    async fn disconnect_during_a_reconnect_attempt_returns() {
622        tokio::time::timeout(std::time::Duration::from_secs(90), async move {
623            let client = closed_client(format!(
624                "{}/slow",
625                socketio_next_testing::socket_io_server()
626            ))
627            .await;
628            let reconnecting = {
629                let client = client.clone();
630                tokio::spawn(async move { client.reconnect().await })
631            };
632            tokio::time::sleep(Duration::from_millis(50)).await;
633            tokio::time::timeout(Duration::from_secs(5), client.disconnect())
634                .await
635                .expect("disconnect did not hang")
636                .unwrap();
637            let _ = tokio::time::timeout(Duration::from_secs(5), reconnecting)
638                .await
639                .unwrap();
640            tokio::time::sleep(Duration::from_millis(300)).await;
641            assert!(
642                client.state().is_closed() && !client.connected(),
643                "{:?}",
644                client.state()
645            );
646        })
647        .await
648        .expect("test `disconnect_during_a_reconnect_attempt_returns` timed out")
649    }
650
651    #[test]
652    fn percent_decode_paths() {
653        assert_eq!(super::percent_decode("/%C3%A4dmin"), "/ädmin");
654        assert_eq!(super::percent_decode("/a%2"), "/a%2");
655        assert_eq!(super::percent_decode("/plain"), "/plain");
656    }
657}