socketio-next 0.1.0

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
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
use std::cell::Cell;
use std::fmt;
use std::panic::AssertUnwindSafe;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError, Weak};
use std::time::Duration;

use futures_util::FutureExt;
use tokio::sync::{mpsc, oneshot, watch};
use tokio::task::JoinHandle;

use crate::actor::{Actor, Command, Dispatch};
use crate::builder::Config;
use crate::handler::{Handler, Handlers, ListenerId};
use crate::protocol::socketio::{Packet, is_reserved_event};
use crate::state::LinkInfo;
use crate::{ConnectionState, Error, Event, Payload, Result};

tokio::task_local! {
    /// Set while the event task runs a handler.
    static IN_HANDLER_TASK: ();
}

thread_local! {
    /// Set while a blocking-pool thread runs a sync handler.
    pub(crate) static IN_HANDLER_THREAD: Cell<bool> = const { Cell::new(false) };
}

fn in_handler() -> bool {
    IN_HANDLER_TASK.try_with(|_| ()).is_ok() || IN_HANDLER_THREAD.with(Cell::get)
}

/// How long `disconnect()` waits for running handlers before it mutes the rest.
const HANDLER_DRAIN: Duration = Duration::from_secs(5);

pub(crate) struct Inner {
    /// The running actor's command queue (replaced by `reconnect()`).
    cmd: Mutex<mpsc::UnboundedSender<Command>>,
    /// Dropped with the last handle (or replaced): tells the actor to stop.
    _shutdown: Mutex<oneshot::Sender<()>>,
    state: watch::Receiver<ConnectionState>,
    state_tx: watch::Sender<ConnectionState>,
    config: Config,
    url: url::Url,
    /// One `reconnect()` at a time.
    restart: tokio::sync::Mutex<()>,
    /// Counts `disconnect()` calls. Held while an actor is started or a disconnect takes the
    /// running one, so a disconnect wins over a concurrent `reconnect()`.
    lifecycle: Mutex<u64>,
    handlers: Mutex<Handlers>,
    shared: Arc<Shared>,
    nsp: Arc<str>,
    buffer_while_disconnected: bool,
    actor: Mutex<Option<JoinHandle<()>>>,
    dispatcher: Mutex<Option<JoinHandle<()>>>,
}

/// State the actor writes and the handles read.
#[derive(Debug, Default)]
pub(crate) struct Shared {
    pub(crate) connected: AtomicBool,
    pub(crate) closed: AtomicBool,
    /// No handler runs once set (after `disconnect()` returned).
    pub(crate) muted: AtomicBool,
    pub(crate) link: Mutex<LinkInfo>,
}

impl Shared {
    pub(crate) fn link(&self) -> std::sync::MutexGuard<'_, LinkInfo> {
        self.link.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// A connected socket.io client (one namespace). Cheap to clone; all clones are one client.
///
/// Dropping the last clone closes the connection. Handlers get a clone for the duration of
/// the call.
#[derive(Clone)]
pub struct Client {
    inner: Arc<Inner>,
}

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

pub(crate) async fn connect(config: Config, handlers: Handlers) -> Result<Client> {
    let (cmd_tx, _) = mpsc::unbounded_channel();
    let (shutdown_tx, _) = oneshot::channel();
    let (state_tx, state_rx) = watch::channel(ConnectionState::Connecting { attempt: 0 });
    let (url, nsp) = resolve(&config)?;
    let inner = Arc::new(Inner {
        cmd: Mutex::new(cmd_tx),
        _shutdown: Mutex::new(shutdown_tx),
        state: state_rx,
        state_tx,
        handlers: Mutex::new(handlers),
        shared: Arc::new(Shared::default()),
        nsp: nsp.into(),
        buffer_while_disconnected: config.buffer_while_disconnected,
        config,
        url,
        restart: tokio::sync::Mutex::new(()),
        lifecycle: Mutex::new(0),
        actor: Mutex::default(),
        dispatcher: Mutex::default(),
    });
    let ready = start(&inner);
    match ready.await {
        Ok(Ok(())) => Ok(Client { inner }),
        Ok(Err(err)) => Err(err),
        Err(_) => Err(Error::Closed),
    }
}

/// Spawns the event task and the connection task for `inner`; the receiver resolves with the
/// first connect attempt.
fn start(inner: &Arc<Inner>) -> oneshot::Receiver<Result<()>> {
    let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
    let (shutdown_tx, shutdown_rx) = oneshot::channel();
    let (dispatch_tx, dispatch_rx) = mpsc::unbounded_channel();
    let (ready_tx, ready_rx) = oneshot::channel();
    inner
        .state_tx
        .send_replace(ConnectionState::Connecting { attempt: 0 });
    let shared = Arc::clone(&inner.shared);
    shared.closed.store(false, Ordering::Release);
    shared.muted.store(false, Ordering::Release);
    *inner.cmd.lock().unwrap_or_else(PoisonError::into_inner) = cmd_tx.clone();
    *inner
        ._shutdown
        .lock()
        .unwrap_or_else(PoisonError::into_inner) = shutdown_tx;

    let dispatcher = tokio::spawn(dispatch(dispatch_rx, Arc::downgrade(inner)));
    let panic_state = inner.state_tx.clone();
    let actor = Actor::new(
        inner.config.clone(),
        inner.url.clone(),
        Arc::clone(&inner.nsp),
        cmd_rx,
        cmd_tx,
        shutdown_rx,
        inner.state_tx.clone(),
        dispatch_tx,
        Arc::clone(&shared),
    );
    // A bug in the connection task must not leave the state at `Connected` forever.
    let actor = tokio::spawn(async move {
        if AssertUnwindSafe(actor.run(ready_tx))
            .catch_unwind()
            .await
            .is_err()
        {
            tracing::error!("the socket.io connection task panicked; the client is closed");
            shared.connected.store(false, Ordering::Release);
            shared.closed.store(true, Ordering::Release);
            panic_state.send_replace(ConnectionState::Closed {
                reason: crate::DisconnectReason::TransportError,
                error: None,
            });
        }
    });
    *inner.actor.lock().unwrap_or_else(PoisonError::into_inner) = Some(actor);
    *inner
        .dispatcher
        .lock()
        .unwrap_or_else(PoisonError::into_inner) = Some(dispatcher);
    ready_rx
}

/// The engine.io URL and the namespace: like socket.io-client, the URL path is the namespace
/// unless one is set explicitly; the engine.io path comes from the builder.
pub(crate) fn resolve(config: &Config) -> Result<(url::Url, String)> {
    let mut url = url::Url::parse(&config.address)?;
    let url_nsp = match url.path() {
        "" | "/" => None,
        path => Some(percent_decode(path)),
    };
    let nsp = config
        .namespace
        .clone()
        .or(url_nsp)
        .unwrap_or_else(|| "/".to_owned());
    url.set_path(&config.path);
    if !config.query.is_empty() {
        url.query_pairs_mut().extend_pairs(&config.query);
    }
    Ok((url, nsp))
}

/// `%XX` escapes of a URL path back to UTF-8 (the namespace is compared as text).
fn percent_decode(path: &str) -> String {
    let bytes = path.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        let hex = |b: u8| (b as char).to_digit(16);
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            if let (Some(h), Some(l)) = (hex(bytes[i + 1]), hex(bytes[i + 2])) {
                out.push((h * 16 + l) as u8);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Runs handlers one at a time, in order. Holds only a weak reference, so it never keeps the
/// client alive.
///
/// ponytail: the queue is unbounded (like socket.io-client's event emitter); a server that
/// floods events faster than slow handlers finish grows memory. Add a bound if that matters.
async fn dispatch(mut rx: mpsc::UnboundedReceiver<Dispatch>, inner: Weak<Inner>) {
    while let Some(item) = rx.recv().await {
        let Some(strong) = inner.upgrade() else {
            break;
        };
        if strong.shared.muted.load(Ordering::Acquire) {
            continue;
        }
        let client = Client {
            inner: Arc::clone(&strong),
        };
        drop(strong);
        match item {
            Dispatch::Event(event) => {
                let handlers = client.handlers().take_for_event(event.name());
                for handler in handlers {
                    if client.inner.shared.muted.load(Ordering::Acquire) {
                        break;
                    }
                    run(handler(event.clone(), client.clone())).await;
                }
            }
            Dispatch::State(state) => {
                let handlers = client.handlers().state_handlers();
                for handler in handlers {
                    if client.inner.shared.muted.load(Ordering::Acquire) {
                        break;
                    }
                    run(handler(state.clone(), client.clone())).await;
                }
            }
        }
    }
}

/// One handler call; a panic is logged and does not stop the event task.
async fn run(fut: futures_util::future::BoxFuture<'static, ()>) {
    if IN_HANDLER_TASK
        .scope((), AssertUnwindSafe(fut).catch_unwind())
        .await
        .is_err()
    {
        tracing::error!("an event handler panicked");
    }
}

impl Client {
    fn cmd(&self) -> mpsc::UnboundedSender<Command> {
        self.inner
            .cmd
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }

    /// Connects again after the client closed (a `ConnectRejected`, `ReconnectFailed`, a
    /// server disconnect without `reconnect_on_disconnect`, or `disconnect()`), with the same
    /// handlers and options; `auth_with` and `connect_params_with` run again, so a new token
    /// can be handed in first. Resolves like `connect()`: once the server accepted the
    /// namespace, or with the error of that attempt (the client then stays closed). A no-op
    /// while the client is not closed. Must not be called from one of its handlers.
    pub async fn reconnect(&self) -> Result<()> {
        let _guard = self.inner.restart.lock().await;
        let seen = *self.lifecycle();
        if !self.state().is_closed() {
            return Ok(());
        }
        // the previous tasks end on their own once closed; wait so none outlives the restart
        let actor = self
            .inner
            .actor
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take();
        if let Some(actor) = actor {
            let _ = actor.await;
        }
        let dispatcher = self
            .inner
            .dispatcher
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take();
        if let Some(dispatcher) = dispatcher {
            if tokio::time::timeout(HANDLER_DRAIN, &mut Box::pin(dispatcher))
                .await
                .is_err()
            {
                tracing::warn!(
                    "handlers still running after {HANDLER_DRAIN:?}; reconnecting anyway"
                );
            }
        }
        #[cfg(test)]
        tests::reconnect_pause(&self.inner.nsp).await;
        let ready = {
            let lifecycle = self.lifecycle();
            // a disconnect() since this call began wins: the client stays closed
            if *lifecycle != seen {
                return Err(Error::Closed);
            }
            start(&self.inner)
        };
        match ready.await {
            Ok(result) => result,
            Err(_) => Err(Error::Closed),
        }
    }

    fn lifecycle(&self) -> std::sync::MutexGuard<'_, u64> {
        self.inner
            .lifecycle
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
    }

    fn handlers(&self) -> std::sync::MutexGuard<'_, Handlers> {
        self.inner
            .handlers
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
    }

    fn event_packet(&self, event: &str, data: Payload) -> Result<Packet> {
        if is_reserved_event(event) {
            return Err(Error::ReservedEvent(event.to_owned()));
        }
        Ok(Packet::new_event(data, event, &self.inner.nsp, None)?)
    }

    fn check_open(&self) -> Result<()> {
        let shared = &self.inner.shared;
        if shared.closed.load(Ordering::Acquire) {
            return Err(Error::Closed);
        }
        if !self.inner.buffer_while_disconnected && !shared.connected.load(Ordering::Acquire) {
            return Err(Error::NotConnected);
        }
        Ok(())
    }

    /// Sends `event` with `data` ([`Payload`], `serde_json::Value`, a string, bytes, `()` for
    /// no arguments). Never blocks: the packet is queued for the connection task.
    ///
    /// Fails with [`Error::NotConnected`] while disconnected (unless
    /// `buffer_while_disconnected`), [`Error::Closed`] after the client closed, and
    /// [`Error::ReservedEvent`] for `connect`, `disconnect`, ...
    pub fn emit(&self, event: impl AsRef<str>, data: impl Into<Payload>) -> Result<()> {
        let packet = self.event_packet(event.as_ref(), data.into())?;
        self.check_open()?;
        self.cmd()
            .send(Command::Emit { packet, ack: None })
            .map_err(|_| Error::Closed)
    }

    /// Sends `event` and waits for the server's ack (socket.io-client
    /// `socket.timeout(ms).emitWithAck(...)`). Resolves with the ack's arguments, or fails with
    /// [`Error::AckTimeout`] after `timeout`, [`Error::Disconnected`] when the connection drops
    /// first. Dropping the future forgets the ack.
    pub async fn emit_with_ack(
        &self,
        event: impl AsRef<str>,
        data: impl Into<Payload>,
        timeout: Duration,
    ) -> Result<Payload> {
        let packet = self.event_packet(event.as_ref(), data.into())?;
        self.check_open()?;
        let (tx, rx) = oneshot::channel();
        self.cmd()
            .send(Command::Emit {
                packet,
                ack: Some((tx, timeout)),
            })
            .map_err(|_| Error::Closed)?;
        rx.await.map_err(|_| Error::Closed)?
    }

    /// Adds a handler for `event`; returns its id for [`off_listener`](Self::off_listener).
    pub fn on<M>(&self, event: impl Into<String>, handler: impl Handler<Event, M>) -> ListenerId {
        self.handlers()
            .on(event.into(), handler.into_boxed(), false)
    }

    /// Adds a handler for the next `event` only.
    pub fn once<M>(&self, event: impl Into<String>, handler: impl Handler<Event, M>) -> ListenerId {
        self.handlers().on(event.into(), handler.into_boxed(), true)
    }

    /// Adds a handler for every event (socket.io-client `onAny`).
    pub fn on_any<M>(&self, handler: impl Handler<Event, M>) -> ListenerId {
        self.handlers().on_any(handler.into_boxed())
    }

    /// Adds a handler for every [`ConnectionState`] transition.
    pub fn on_state_change<M>(&self, handler: impl Handler<ConnectionState, M>) -> ListenerId {
        self.handlers().on_state(handler.into_boxed())
    }

    /// Removes every handler of `event`; returns how many.
    pub fn off(&self, event: &str) -> usize {
        self.handlers().off(event)
    }

    /// Removes every catch-all handler; returns how many.
    pub fn off_any(&self) -> usize {
        self.handlers().off_any()
    }

    /// Removes one handler; `false` when it was gone already (a `once` handler that ran).
    pub fn off_listener(&self, id: ListenerId) -> bool {
        self.handlers().off_listener(id)
    }

    /// Number of handlers of `event` (socket.io-client `listeners(event).length`).
    pub fn listener_count(&self, event: &str) -> usize {
        self.handlers().listener_count(event)
    }

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

    /// A watch of the state: `changed().await` wakes on transitions (a slow reader sees the
    /// latest; use [`on_state_change`](Self::on_state_change) to see every one).
    pub fn state_watch(&self) -> watch::Receiver<ConnectionState> {
        self.inner.state.clone()
    }

    /// Waits until the state matches `predicate` (or the client closed).
    pub async fn wait_for(&self, predicate: impl Fn(&ConnectionState) -> bool) -> ConnectionState {
        let mut watch = self.inner.state.clone();
        loop {
            let state = watch.borrow_and_update().clone();
            if predicate(&state) || state.is_closed() {
                return state;
            }
            if watch.changed().await.is_err() {
                return watch.borrow().clone();
            }
        }
    }

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

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

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

    /// The last connect restored the session (connection state recovery, `socket.recovered`).
    pub fn recovered(&self) -> bool {
        matches!(
            self.state(),
            ConnectionState::Connected {
                recovered: true,
                ..
            }
        )
    }

    /// A snapshot of the link: transport, sids, heartbeat, last packet, attempts.
    pub fn link_info(&self) -> LinkInfo {
        self.inner.shared.link().clone()
    }

    /// Leaves the namespace (DISCONNECT packet), closes the connection and stops reconnecting.
    ///
    /// Bounded: the goodbye (queued packets, DISCONNECT, engine.io close) gets at most 2 s on a
    /// dead link. Events already received are still handled; handlers get up to 5 s in total,
    /// then the event task is stopped. When it returns no handler starts any more. Safe to call
    /// from inside a handler (it then does not wait for the handlers; the event task ends after
    /// the running handler).
    pub async fn disconnect(&self) -> Result<()> {
        // The actor this call stops, its command queue and event task, taken together: a
        // concurrent `reconnect()` either started its actor before (it is stopped here) or
        // sees the count change and does not start one.
        let (cmd, actor, dispatcher) = {
            let mut lifecycle = self.lifecycle();
            *lifecycle += 1;
            let actor = self
                .inner
                .actor
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .take();
            let dispatcher = if in_handler() {
                None
            } else {
                self.inner
                    .dispatcher
                    .lock()
                    .unwrap_or_else(PoisonError::into_inner)
                    .take()
            };
            (self.cmd(), actor, dispatcher)
        };
        let (tx, rx) = oneshot::channel();
        if cmd.send(Command::Disconnect { done: tx }).is_ok() {
            let _ = rx.await;
        }
        if let Some(actor) = actor {
            let _ = actor.await;
        }
        {
            if let Some(mut dispatcher) = dispatcher {
                if tokio::time::timeout(HANDLER_DRAIN, &mut dispatcher)
                    .await
                    .is_err()
                {
                    // a handler is stuck: stop the event task so nothing else starts
                    tracing::warn!(
                        "handlers still running after {HANDLER_DRAIN:?}; event task stopped"
                    );
                    dispatcher.abort();
                    let _ = dispatcher.await;
                }
            }
        }
        self.inner.shared.muted.store(true, Ordering::Release);
        Ok(())
    }
}

impl Drop for Inner {
    fn drop(&mut self) {
        // The actor stops when `_shutdown` drops right after this; nothing may run any more.
        self.shared.muted.store(true, Ordering::Release);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::OnceLock;
    use tokio::sync::Notify;

    /// (namespace, reached, go): `reconnect()` of a client of that namespace (only: other
    /// tests reconnect in parallel) waits between its awaits and the start.
    type Pause = (String, Arc<Notify>, Arc<Notify>);
    static PAUSE: OnceLock<Mutex<Option<Pause>>> = OnceLock::new();

    pub(super) async fn reconnect_pause(nsp: &str) {
        let pause = PAUSE.get_or_init(Mutex::default).lock().unwrap().clone();
        if let Some((target, reached, go)) = pause {
            if target == nsp {
                reached.notify_one();
                go.notified().await;
            }
        }
    }

    async fn closed_client(url: String) -> Client {
        let client = crate::ClientBuilder::new(url).connect().await.unwrap();
        client.emit("server_disconnect", ()).unwrap();
        client.wait_for(ConnectionState::is_closed).await;
        client
    }

    /// Case A: `disconnect()` while `reconnect()` waits for the old tasks: the client must
    /// stay closed (it was revived before).
    #[tokio::test(flavor = "multi_thread")]
    async fn disconnect_during_reconnect_wins() {
        tokio::time::timeout(std::time::Duration::from_secs(90), async move {
            let client = closed_client(socketio_next_testing::socket_io_server()).await;
            let (reached, go) = (Arc::new(Notify::new()), Arc::new(Notify::new()));
            *PAUSE.get_or_init(Mutex::default).lock().unwrap() =
                Some(("/".into(), Arc::clone(&reached), Arc::clone(&go)));
            let reconnecting = {
                let client = client.clone();
                tokio::spawn(async move { client.reconnect().await })
            };
            reached.notified().await;
            *PAUSE.get().unwrap().lock().unwrap() = None;
            client.disconnect().await.unwrap();
            go.notify_one();
            let result = tokio::time::timeout(Duration::from_secs(5), reconnecting)
                .await
                .unwrap()
                .unwrap();
            assert!(matches!(result, Err(Error::Closed)), "{result:?}");
            tokio::time::sleep(Duration::from_millis(300)).await;
            assert!(client.state().is_closed() && !client.connected());
        })
        .await
        .expect("test `disconnect_during_reconnect_wins` timed out")
    }

    /// Case B: `disconnect()` while the restarted connection task is connecting (a namespace
    /// that answers CONNECT after 200 ms) returns promptly and leaves the client closed.
    #[tokio::test(flavor = "multi_thread")]
    async fn disconnect_during_a_reconnect_attempt_returns() {
        tokio::time::timeout(std::time::Duration::from_secs(90), async move {
            let client = closed_client(format!(
                "{}/slow",
                socketio_next_testing::socket_io_server()
            ))
            .await;
            let reconnecting = {
                let client = client.clone();
                tokio::spawn(async move { client.reconnect().await })
            };
            tokio::time::sleep(Duration::from_millis(50)).await;
            tokio::time::timeout(Duration::from_secs(5), client.disconnect())
                .await
                .expect("disconnect did not hang")
                .unwrap();
            let _ = tokio::time::timeout(Duration::from_secs(5), reconnecting)
                .await
                .unwrap();
            tokio::time::sleep(Duration::from_millis(300)).await;
            assert!(
                client.state().is_closed() && !client.connected(),
                "{:?}",
                client.state()
            );
        })
        .await
        .expect("test `disconnect_during_a_reconnect_attempt_returns` timed out")
    }

    #[test]
    fn percent_decode_paths() {
        assert_eq!(super::percent_decode("/%C3%A4dmin"), "/ädmin");
        assert_eq!(super::percent_decode("/a%2"), "/a%2");
        assert_eq!(super::percent_decode("/plain"), "/plain");
    }
}