Skip to main content

socketio_next/
client.rs

1use std::cell::Cell;
2use std::fmt;
3use std::panic::AssertUnwindSafe;
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::sync::{Arc, Mutex, PoisonError, Weak};
6use std::time::Duration;
7
8use futures_util::FutureExt;
9use tokio::sync::{mpsc, oneshot, watch};
10
11use crate::actor::{Actor, Command, Cut, Dispatch, Link};
12use crate::builder::Config;
13use crate::handler::{Handler, Handlers, ListenerId};
14use crate::protocol::socketio::{Packet, is_reserved_event};
15use crate::state::LinkInfo;
16use crate::{ConnectionState, Error, Event, Payload, Result};
17
18tokio::task_local! {
19    /// The client (its [`Client::key`]) whose handler the event task is running.
20    static IN_HANDLER_TASK: usize;
21}
22
23thread_local! {
24    /// The client whose sync handler this blocking-pool thread is running (0: none).
25    pub(crate) static IN_HANDLER_THREAD: Cell<usize> = const { Cell::new(0) };
26}
27
28/// How long `disconnect()` waits for the handlers of what was received before it returns.
29const HANDLER_DRAIN: Duration = Duration::from_secs(5);
30
31/// What the handles of one client share. The connection task owns the client's life (its
32/// sessions, the state, the link snapshot); the handles reach it through `cmd`.
33pub(crate) struct Inner {
34    /// The connection task's commands, for the client's whole life.
35    cmd: mpsc::UnboundedSender<Command>,
36    /// Dropped with the last handle: tells the connection task to stop.
37    _shutdown: oneshot::Sender<()>,
38    state: watch::Receiver<ConnectionState>,
39    link: Link,
40    handlers: Mutex<Handlers>,
41    nsp: Arc<str>,
42    buffer_while_disconnected: bool,
43}
44
45/// A connected socket.io client (one namespace). Cheap to clone; all clones are one client.
46///
47/// Dropping the last clone closes the connection. Handlers get a clone for the duration of
48/// the call. A handler that keeps a `Client` of its own (captured in the closure) keeps the
49/// client alive for good, since the client owns its handlers: capture a [`WeakClient`]
50/// ([`downgrade`](Self::downgrade)) instead.
51#[derive(Clone)]
52pub struct Client {
53    inner: Arc<Inner>,
54}
55
56/// A [`Client`] that does not keep the connection open: for handlers and other places that
57/// the client itself (directly or not) owns. [`upgrade`](Self::upgrade) gives the client back
58/// while a `Client` exists elsewhere.
59#[derive(Clone)]
60pub struct WeakClient {
61    inner: Weak<Inner>,
62}
63
64impl WeakClient {
65    /// The client, unless every `Client` was dropped (the connection is closed then).
66    pub fn upgrade(&self) -> Option<Client> {
67        self.inner.upgrade().map(|inner| Client { inner })
68    }
69}
70
71impl fmt::Debug for WeakClient {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.debug_struct("WeakClient")
74            .field("alive", &(self.inner.strong_count() > 0))
75            .finish()
76    }
77}
78
79impl fmt::Debug for Client {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        f.debug_struct("Client")
82            .field("nsp", &self.inner.nsp)
83            .field("state", &*self.inner.state.borrow())
84            .finish_non_exhaustive()
85    }
86}
87
88/// Starts the connection task and the event task; resolves with the first connect attempt.
89pub(crate) async fn connect(config: Config, handlers: Handlers) -> Result<Client> {
90    let (url, nsp) = resolve(&config)?;
91    let nsp: Arc<str> = nsp.into();
92    let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
93    let (shutdown_tx, shutdown_rx) = oneshot::channel();
94    let (dispatch_tx, dispatch_rx) = mpsc::unbounded_channel();
95    let (ready_tx, ready_rx) = oneshot::channel();
96    let (state_tx, state_rx) = watch::channel(ConnectionState::Connecting { attempt: 0 });
97    let link = Link::default();
98    let cut: Cut = Arc::new(AtomicU64::new(0));
99    let inner = Arc::new(Inner {
100        cmd: cmd_tx.clone(),
101        _shutdown: shutdown_tx,
102        state: state_rx,
103        link: link.clone(),
104        handlers: Mutex::new(handlers),
105        nsp: Arc::clone(&nsp),
106        buffer_while_disconnected: config.buffer_while_disconnected,
107    });
108    tokio::spawn(dispatch(
109        dispatch_rx,
110        Arc::downgrade(&inner),
111        Arc::clone(&cut),
112    ));
113    let panic_state = state_tx.clone();
114    let panic_dispatch = dispatch_tx.clone();
115    let actor = Actor::new(
116        config,
117        url,
118        nsp,
119        cmd_rx,
120        cmd_tx,
121        shutdown_rx,
122        state_tx,
123        dispatch_tx,
124        link,
125        cut,
126    );
127    // A bug in the connection task must not leave the state at `Connected` forever.
128    tokio::spawn(async move {
129        if AssertUnwindSafe(actor.run(ready_tx))
130            .catch_unwind()
131            .await
132            .is_err()
133        {
134            tracing::error!("the socket.io connection task panicked; the client is closed");
135            let closed = ConnectionState::Closed {
136                reason: crate::DisconnectReason::TransportError,
137                error: None,
138            };
139            panic_state.send_replace(closed.clone());
140            let _ = panic_dispatch.send(Dispatch::State(closed));
141        }
142    });
143    match ready_rx.await {
144        Ok(Ok(())) => Ok(Client { inner }),
145        Ok(Err(err)) => Err(err),
146        Err(_) => Err(Error::Closed),
147    }
148}
149
150/// The engine.io URL and the namespace: like socket.io-client, the URL path is the namespace
151/// unless one is set explicitly; the engine.io path comes from the builder.
152pub(crate) fn resolve(config: &Config) -> Result<(url::Url, String)> {
153    let mut url = url::Url::parse(&config.address)?;
154    let url_nsp = match url.path() {
155        "" | "/" => None,
156        path => Some(percent_decode(path)),
157    };
158    let nsp = config
159        .namespace
160        .clone()
161        .or(url_nsp)
162        .unwrap_or_else(|| "/".to_owned());
163    url.set_path(&config.path);
164    if !config.query.is_empty() {
165        url.query_pairs_mut().extend_pairs(&config.query);
166    }
167    Ok((url, nsp))
168}
169
170/// `%XX` escapes of a URL path back to UTF-8 (the namespace is compared as text).
171fn percent_decode(path: &str) -> String {
172    let bytes = path.as_bytes();
173    let mut out = Vec::with_capacity(bytes.len());
174    let mut i = 0;
175    while i < bytes.len() {
176        let hex = |b: u8| (b as char).to_digit(16);
177        if bytes[i] == b'%' && i + 2 < bytes.len() {
178            if let (Some(h), Some(l)) = (hex(bytes[i + 1]), hex(bytes[i + 2])) {
179                out.push((h * 16 + l) as u8);
180                i += 3;
181                continue;
182            }
183        }
184        out.push(bytes[i]);
185        i += 1;
186    }
187    String::from_utf8_lossy(&out).into_owned()
188}
189
190/// Runs handlers one at a time, in order, for the client's whole life (one task across
191/// reconnects). Holds only a weak reference, so it never keeps the client alive.
192///
193/// ponytail: the queue is unbounded (like socket.io-client's event emitter); a server that
194/// floods events faster than slow handlers finish grows memory. Add a bound if that matters.
195async fn dispatch(mut rx: mpsc::UnboundedReceiver<Dispatch>, inner: Weak<Inner>, cut: Cut) {
196    while let Some(item) = rx.recv().await {
197        let Some(strong) = inner.upgrade() else {
198            break;
199        };
200        let client = Client { inner: strong };
201        let key = client.key();
202        match item {
203            Dispatch::Event { session, event } => {
204                let handlers = client.handlers().take_for_event(event.name());
205                for handler in handlers {
206                    // a disconnect() since the event arrived: no more handlers for it
207                    if session < cut.load(Ordering::Acquire) {
208                        break;
209                    }
210                    run(key, || handler(event.clone(), client.clone())).await;
211                }
212            }
213            Dispatch::State(state) => {
214                let handlers = client.handlers().state_handlers();
215                for handler in handlers {
216                    run(key, || handler(state.clone(), client.clone())).await;
217                }
218            }
219            Dispatch::Fence(reached) => {
220                let _ = reached.send(());
221            }
222        }
223    }
224}
225
226/// One handler call of client `key`; a panic is logged and does not stop the event task. The
227/// call itself is inside the guard too: an async handler's closure body runs while its future
228/// is built.
229async fn run(key: usize, call: impl FnOnce() -> futures_util::future::BoxFuture<'static, ()>) {
230    let guarded = async move {
231        let fut = std::panic::catch_unwind(AssertUnwindSafe(call)).map_err(|_| ())?;
232        AssertUnwindSafe(fut).catch_unwind().await.map_err(|_| ())
233    };
234    if IN_HANDLER_TASK.scope(key, guarded).await.is_err() {
235        tracing::error!("an event handler panicked");
236    }
237}
238
239impl Client {
240    /// A handle that does not keep the client alive.
241    pub fn downgrade(&self) -> WeakClient {
242        WeakClient {
243            inner: Arc::downgrade(&self.inner),
244        }
245    }
246
247    /// Identifies this client among others (handlers of client A may drive client B).
248    pub(crate) fn key(&self) -> usize {
249        Arc::as_ptr(&self.inner) as usize
250    }
251
252    /// Called from one of this client's own handlers.
253    fn in_own_handler(&self) -> bool {
254        let key = self.key();
255        IN_HANDLER_TASK.try_with(|k| *k == key).unwrap_or(false)
256            || IN_HANDLER_THREAD.with(Cell::get) == key
257    }
258
259    /// Connects again after the client closed (a `ConnectRejected`, `ReconnectFailed`, a
260    /// server disconnect without `reconnect_on_disconnect`, or `disconnect()`), with the same
261    /// handlers and options; `auth_with` and `connect_params_with` run again, so a new token
262    /// can be handed in first. Resolves like `connect()`: once the server accepted the
263    /// namespace, or with the error of that attempt (the client then stays closed). A no-op
264    /// while the client is not closed. `reconnect()` and `disconnect()` take effect in the
265    /// order they are called.
266    pub async fn reconnect(&self) -> Result<()> {
267        let (ready, rx) = oneshot::channel();
268        self.inner
269            .cmd
270            .send(Command::Reconnect { ready })
271            .map_err(|_| Error::Closed)?;
272        rx.await.map_err(|_| Error::Closed)?
273    }
274
275    fn handlers(&self) -> std::sync::MutexGuard<'_, Handlers> {
276        self.inner
277            .handlers
278            .lock()
279            .unwrap_or_else(PoisonError::into_inner)
280    }
281
282    fn event_packet(&self, event: &str, data: Payload) -> Result<Packet> {
283        if is_reserved_event(event) {
284            return Err(Error::ReservedEvent(event.to_owned()));
285        }
286        Ok(Packet::new_event(data, event, &self.inner.nsp, None)?)
287    }
288
289    fn check_open(&self) -> Result<()> {
290        match &*self.inner.state.borrow() {
291            ConnectionState::Closed { .. } => Err(Error::Closed),
292            ConnectionState::Connected { .. } => Ok(()),
293            _ if self.inner.buffer_while_disconnected => Ok(()),
294            _ => Err(Error::NotConnected),
295        }
296    }
297
298    /// Sends `event` with `data` ([`Payload`], `serde_json::Value`, a string, bytes, `()` for
299    /// no arguments). Never blocks: the packet is queued for the connection task.
300    ///
301    /// Fails with [`Error::NotConnected`] while disconnected (unless
302    /// `buffer_while_disconnected`), [`Error::Closed`] after the client closed, and
303    /// [`Error::ReservedEvent`] for `connect`, `disconnect`, ...
304    pub fn emit(&self, event: impl AsRef<str>, data: impl Into<Payload>) -> Result<()> {
305        let packet = self.event_packet(event.as_ref(), data.into())?;
306        self.check_open()?;
307        self.inner
308            .cmd
309            .send(Command::Emit { packet, ack: None })
310            .map_err(|_| Error::Closed)
311    }
312
313    /// Sends `event` and waits for the server's ack (socket.io-client
314    /// `socket.timeout(ms).emitWithAck(...)`). Resolves with the ack's arguments, or fails with
315    /// [`Error::AckTimeout`] after `timeout`, [`Error::Disconnected`] when the connection drops
316    /// first. Dropping the future forgets the ack.
317    pub async fn emit_with_ack(
318        &self,
319        event: impl AsRef<str>,
320        data: impl Into<Payload>,
321        timeout: Duration,
322    ) -> Result<Payload> {
323        let packet = self.event_packet(event.as_ref(), data.into())?;
324        self.check_open()?;
325        let (tx, rx) = oneshot::channel();
326        self.inner
327            .cmd
328            .send(Command::Emit {
329                packet,
330                ack: Some((tx, timeout)),
331            })
332            .map_err(|_| Error::Closed)?;
333        rx.await.map_err(|_| Error::Closed)?
334    }
335
336    /// Adds a handler for `event`; returns its id for [`off_listener`](Self::off_listener).
337    pub fn on<M>(&self, event: impl Into<String>, handler: impl Handler<Event, M>) -> ListenerId {
338        self.handlers()
339            .on(event.into(), handler.into_boxed(), false)
340    }
341
342    /// Adds a handler for the next `event` only.
343    pub fn once<M>(&self, event: impl Into<String>, handler: impl Handler<Event, M>) -> ListenerId {
344        self.handlers().on(event.into(), handler.into_boxed(), true)
345    }
346
347    /// Adds a handler for every event (socket.io-client `onAny`).
348    pub fn on_any<M>(&self, handler: impl Handler<Event, M>) -> ListenerId {
349        self.handlers().on_any(handler.into_boxed())
350    }
351
352    /// Adds a handler for every [`ConnectionState`] transition.
353    pub fn on_state_change<M>(&self, handler: impl Handler<ConnectionState, M>) -> ListenerId {
354        self.handlers().on_state(handler.into_boxed())
355    }
356
357    /// Removes every handler of `event`; returns how many.
358    pub fn off(&self, event: &str) -> usize {
359        self.handlers().off(event)
360    }
361
362    /// Removes every catch-all handler; returns how many.
363    pub fn off_any(&self) -> usize {
364        self.handlers().off_any()
365    }
366
367    /// Removes one handler; `false` when it was gone already (a `once` handler that ran).
368    pub fn off_listener(&self, id: ListenerId) -> bool {
369        self.handlers().off_listener(id)
370    }
371
372    /// Number of handlers of `event` (socket.io-client `listeners(event).length`).
373    pub fn listener_count(&self, event: &str) -> usize {
374        self.handlers().listener_count(event)
375    }
376
377    /// The current state.
378    pub fn state(&self) -> ConnectionState {
379        self.inner.state.borrow().clone()
380    }
381
382    /// A watch of the state: `changed().await` wakes on transitions (a slow reader sees the
383    /// latest; use [`on_state_change`](Self::on_state_change) to see every one).
384    pub fn state_watch(&self) -> watch::Receiver<ConnectionState> {
385        self.inner.state.clone()
386    }
387
388    /// Waits until the state matches `predicate` (or the client closed).
389    pub async fn wait_for(&self, predicate: impl Fn(&ConnectionState) -> bool) -> ConnectionState {
390        let mut watch = self.inner.state.clone();
391        loop {
392            let state = watch.borrow_and_update().clone();
393            if predicate(&state) || state.is_closed() {
394                return state;
395            }
396            if watch.changed().await.is_err() {
397                return watch.borrow().clone();
398            }
399        }
400    }
401
402    /// The namespace is joined right now.
403    pub fn connected(&self) -> bool {
404        self.inner.state.borrow().is_connected()
405    }
406
407    /// The socket id while connected (`socket.id`).
408    pub fn id(&self) -> Option<String> {
409        match &*self.inner.state.borrow() {
410            ConnectionState::Connected { sid, .. } => Some(sid.clone()),
411            _ => None,
412        }
413    }
414
415    /// The namespace of this client.
416    pub fn namespace(&self) -> &str {
417        &self.inner.nsp
418    }
419
420    /// The last connect restored the session (connection state recovery, `socket.recovered`).
421    pub fn recovered(&self) -> bool {
422        matches!(
423            self.state(),
424            ConnectionState::Connected {
425                recovered: true,
426                ..
427            }
428        )
429    }
430
431    /// A snapshot of the link: transport, sids, heartbeat, last packet, attempts.
432    pub fn link_info(&self) -> LinkInfo {
433        self.inner.link.get().clone()
434    }
435
436    /// Leaves the namespace (DISCONNECT packet), closes the connection and stops reconnecting.
437    ///
438    /// Bounded: the goodbye (queued packets, DISCONNECT, engine.io close) gets at most 2 s on a
439    /// dead link. No event handler starts for events received from now on (like
440    /// socket.io-client, which stops emitting events once disconnected); the `Closed` state
441    /// still reaches `on_state_change`. It waits up to 5 s for the handlers already running or
442    /// queued before it. Safe to call from inside one of the client's handlers: it then does not
443    /// wait for them.
444    pub async fn disconnect(&self) -> Result<()> {
445        let (done, rx) = oneshot::channel();
446        if self.inner.cmd.send(Command::Disconnect { done }).is_err() {
447            return Ok(()); // the connection task is gone: closed already
448        }
449        let Ok(fence) = rx.await else {
450            return Ok(());
451        };
452        if !self.in_own_handler() && tokio::time::timeout(HANDLER_DRAIN, fence).await.is_err() {
453            tracing::warn!("handlers still running {HANDLER_DRAIN:?} after disconnect()");
454        }
455        Ok(())
456    }
457}
458
459#[cfg(test)]
460mod tests {
461    #[test]
462    fn percent_decode_paths() {
463        assert_eq!(super::percent_decode("/%C3%A4dmin"), "/ädmin");
464        assert_eq!(super::percent_decode("/a%2"), "/a%2");
465        assert_eq!(super::percent_decode("/plain"), "/plain");
466    }
467}