moosicbox_server 0.2.0

MoosicBox server package
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
//! WebSocket server implementation for managing client connections.
//!
//! This module provides a multi-room WebSocket server that manages client connections, message
//! routing, and player action dispatching. It supports multiple profiles and integrates with
//! the `MoosicBox` player system.

use std::{
    collections::{BTreeMap, BTreeSet},
    io,
    sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    },
};

use moosicbox_async_service::async_trait;
use moosicbox_ws::{
    PlayerAction, WebsocketContext, WebsocketDisconnectError, WebsocketMessageError,
    WebsocketSendError, WebsocketSender,
};
use serde_json::Value;
use strum_macros::AsRefStr;
use switchy_async::sync::{RwLock, mpsc, oneshot};
use switchy_database::{config::ConfigDatabase, profiles::PROFILES};
use tokio_util::sync::CancellationToken;

use crate::ws::{ConnId, Msg, RoomId};

#[async_trait]
impl WebsocketSender for WsServer {
    async fn send(&self, connection_id: &str, data: &str) -> Result<(), WebsocketSendError> {
        let id = connection_id.parse::<ConnId>().unwrap();
        log::debug!("Sending to {id}");
        self.send_message_to(id, data.to_string());
        for sender in &self.senders {
            sender.send(connection_id, data).await?;
        }
        Ok(())
    }

    async fn send_all(&self, data: &str) -> Result<(), WebsocketSendError> {
        self.send_system_message("main", 0, data.to_string());
        for sender in &self.senders {
            sender.send_all(data).await?;
        }
        Ok(())
    }

    async fn send_all_except(
        &self,
        connection_id: &str,
        data: &str,
    ) -> Result<(), WebsocketSendError> {
        self.send_system_message(
            "main",
            connection_id.parse::<ConnId>().unwrap(),
            data.to_string(),
        );
        for sender in &self.senders {
            sender.send_all_except(connection_id, data).await?;
        }
        Ok(())
    }

    async fn ping(&self) -> Result<(), WebsocketSendError> {
        self.ping_system();
        for sender in &self.senders {
            sender.ping().await?;
        }
        Ok(())
    }
}

/// A command received by the [`WsServer`].
#[derive(Debug, AsRefStr)]
pub enum Command {
    /// Adds a player action to be broadcast to connected clients.
    #[cfg(feature = "player")]
    AddPlayerAction {
        /// Player ID.
        id: u64,
        /// The player action to broadcast.
        action: PlayerAction,
    },

    /// Registers a new WebSocket connection.
    Connect {
        /// Profile name for this connection.
        profile: String,
        /// Channel sender for messages to this connection.
        conn_tx: mpsc::Sender<Msg>,
        /// Channel to send back the assigned connection ID.
        res_tx: oneshot::Sender<ConnId>,
    },

    /// Removes a WebSocket connection.
    Disconnect {
        /// Connection ID to disconnect.
        conn: ConnId,
    },

    /// Sends a message to a specific connection.
    Send {
        /// Message to send.
        msg: Msg,
        /// Target connection ID.
        conn: ConnId,
        /// Channel to signal completion.
        res_tx: oneshot::Sender<()>,
    },

    /// Broadcasts a message to all connections.
    Broadcast {
        /// Message to broadcast.
        msg: Msg,
        /// Channel to signal completion.
        res_tx: oneshot::Sender<()>,
    },

    /// Broadcasts a message to all connections except one.
    BroadcastExcept {
        /// Message to broadcast.
        msg: Msg,
        /// Connection ID to exclude from the broadcast.
        conn: ConnId,
        /// Channel to signal completion.
        res_tx: oneshot::Sender<()>,
    },

    /// Processes an incoming message from a connection.
    Message {
        /// The received message.
        msg: Msg,
        /// Connection ID that sent the message.
        conn: ConnId,
        /// Channel to signal completion.
        res_tx: oneshot::Sender<()>,
    },
}

impl std::fmt::Display for Command {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_ref())
    }
}

/// Represents an active WebSocket connection.
///
/// Contains the profile name and message sender channel for a connected client.
#[derive(Debug, Clone)]
struct Connection {
    /// The profile name this connection is using.
    profile: String,
    /// Channel for sending messages to this connection.
    sender: mpsc::Sender<Msg>,
}

/// A multi-room ws server.
///
/// Contains the logic of how connections ws with each other plus room management.
///
/// Call and spawn [`run`](Self::run) to start processing commands.
#[allow(clippy::module_name_repetitions)]
#[derive(Debug)]
pub struct WsServer {
    /// Map of connection IDs to their message receivers.
    connections: BTreeMap<ConnId, Connection>,

    config_db: ConfigDatabase,

    /// Map of room name to participant IDs in that room.
    rooms: BTreeMap<RoomId, BTreeSet<ConnId>>,

    /// Map of profiles to participant IDs using that profile.
    #[allow(unused)]
    profiles: BTreeMap<String, BTreeSet<ConnId>>,

    /// Tracks total number of historical connections established.
    visitor_count: Arc<AtomicUsize>,

    /// Command receiver.
    cmd_rx: flume::Receiver<Command>,

    senders: Vec<Box<dyn WebsocketSender>>,

    player_actions: Vec<(u64, PlayerAction)>,

    token: CancellationToken,
}

impl WsServer {
    /// Creates a new WebSocket server instance with the given configuration database.
    ///
    /// This function initializes a WebSocket server with a default "main" room and profile-specific
    /// rooms for all registered profiles. It returns both the server instance and a handle for
    /// sending commands to the server.
    ///
    /// # Returns
    ///
    /// A tuple containing:
    /// * [`WsServer`] - The server instance that should be run via [`run`](WsServer::run)
    /// * [`WsServerHandle`] - A handle for sending commands to the server
    #[must_use]
    pub fn new(config_db: ConfigDatabase) -> (Self, WsServerHandle) {
        // create empty server
        let mut rooms = BTreeMap::new();

        // create default room
        rooms.insert("main".to_owned(), BTreeSet::new());

        let mut profiles = BTreeMap::new();

        for profile in PROFILES.names() {
            profiles.insert(profile, BTreeSet::new());
        }

        let (cmd_tx, cmd_rx) = flume::unbounded();
        let token = CancellationToken::new();
        let handle = WsServerHandle {
            cmd_tx,
            token: token.clone(),
        };

        (
            Self {
                connections: BTreeMap::new(),
                config_db,
                rooms,
                profiles,
                visitor_count: Arc::new(AtomicUsize::new(0)),
                cmd_rx,
                senders: vec![],
                player_actions: vec![],
                token,
            },
            handle,
        )
    }

    /// Registers a player action callback for a specific player ID.
    ///
    /// Player actions are invoked when playback commands are received from connected clients
    /// for the associated player.
    #[cfg(feature = "player")]
    pub fn add_player_action(&mut self, id: u64, action: PlayerAction) {
        self.player_actions.push((id, action));
    }

    /// Adds an additional WebSocket sender for message forwarding.
    ///
    /// This is used to forward messages through the tunnel connection when the `tunnel`
    /// feature is enabled.
    #[cfg(feature = "tunnel")]
    pub fn add_sender(&mut self, sender: Box<dyn WebsocketSender>) {
        self.senders.push(sender);
    }

    #[allow(clippy::unused_self)]
    fn ping_system(&self) {
        log::trace!("ping_system: pong");
    }

    /// Send message to users in a room.
    ///
    /// `skip` is used to prevent messages triggered by a connection also being received by it.
    fn send_system_message(&self, room: &str, skip: ConnId, msg: impl Into<String>) {
        if let Some(sessions) = self.rooms.get(room) {
            let msg = msg.into();

            for conn_id in sessions {
                if *conn_id != skip
                    && let Some(Connection { sender, .. }) = self.connections.get(conn_id)
                {
                    // errors if client disconnected abruptly and hasn't been timed-out yet
                    let _ = sender.send(msg.clone());
                }
            }
        }
    }

    /// Send message directly to the user.
    fn send_message_to(&self, id: ConnId, msg: impl Into<String>) {
        if let Some(Connection { sender, .. }) = self.connections.get(&id) {
            // errors if client disconnected abruptly and hasn't been timed-out yet
            let _ = sender.send(msg.into());
        }
    }

    async fn on_message(
        &self,
        id: ConnId,
        msg: impl Into<String> + Send,
    ) -> Result<(), WebsocketMessageError> {
        let connection_id = id.to_string();
        let profile = self.connections.get(&id).unwrap().profile.clone();
        log::trace!(
            "on_message connection_id={connection_id} player_actions.len={}",
            self.player_actions.len()
        );
        let context = WebsocketContext {
            connection_id,
            profile: Some(profile),
            player_actions: self.player_actions.clone(),
        };
        let payload = msg.into();
        let body = serde_json::from_str::<Value>(&payload)
            .map_err(|e| WebsocketMessageError::InvalidPayload(payload, e.to_string()))?;

        moosicbox_ws::process_message(&self.config_db, body, context, self).await?;

        Ok(())
    }

    /// Register new session and assign unique ID to this session
    fn connect(&mut self, profile: String, tx: mpsc::Sender<Msg>) -> ConnId {
        log::debug!("Someone joined");

        // register session with random connection ID
        let id = switchy_random::rng().next_u64();
        self.connections.insert(
            id,
            Connection {
                profile: profile.clone(),
                sender: tx,
            },
        );

        // auto join session to main room
        self.rooms.entry("main".to_owned()).or_default().insert(id);

        let count = self.visitor_count.fetch_add(1, Ordering::SeqCst);
        log::debug!("Visitor count: {}", count + 1);

        let connection_id = id.to_string();
        let context = WebsocketContext {
            connection_id,
            profile: Some(profile),
            player_actions: self.player_actions.clone(),
        };

        let _ = moosicbox_ws::connect(self, &context);

        // send id back
        id
    }

    /// Unregister connection from room map and invoke ws api disconnect.
    async fn disconnect(&mut self, conn_id: ConnId) -> Result<(), WebsocketDisconnectError> {
        log::debug!("Someone disconnected {conn_id}");
        let count = self.visitor_count.fetch_sub(1, Ordering::SeqCst);
        log::debug!("Visitor count: {}", count - 1);

        // remove sender
        if self.connections.remove(&conn_id).is_some() {
            // remove session from all rooms
            for sessions in self.rooms.values_mut() {
                sessions.remove(&conn_id);
            }
        }

        let connection_id = conn_id.to_string();
        let context = WebsocketContext {
            connection_id,
            profile: None,
            player_actions: self.player_actions.clone(),
        };

        moosicbox_ws::disconnect(&self.config_db, self, &context).await?;

        Ok(())
    }

    #[allow(clippy::cognitive_complexity)]
    async fn process_command(ctx: Arc<RwLock<Self>>, cmd: Command) -> io::Result<()> {
        let cmd_str = cmd.to_string();

        if log::log_enabled!(log::Level::Trace) {
            log::trace!("process_command: cmd={cmd:?}");
        } else {
            log::debug!("process_command: cmd={cmd_str}");
        }

        match cmd {
            #[cfg(feature = "player")]
            Command::AddPlayerAction { id, action } => {
                ctx.write().await.add_player_action(id, action);
                log::debug!("Added a player action with id={id}");
            }

            Command::Connect {
                profile,
                conn_tx,
                res_tx,
            } => {
                let conn_id = ctx.write().await.connect(profile, conn_tx);
                res_tx
                    .send(conn_id)
                    .map_err(|e| std::io::Error::other(format!("Failed to send: {e:?}")))?;
            }

            Command::Disconnect { conn } => {
                let response = ctx.write().await.disconnect(conn).await;
                if let Err(error) = response {
                    moosicbox_assert::die_or_error!(
                        "Failed to disconnect connection {conn}: {:?}",
                        error
                    );
                }
            }

            Command::Send { msg, conn, res_tx } => {
                let response = ctx.read().await.send(&conn.to_string(), &msg).await;
                if let Err(error) = response {
                    moosicbox_assert::die_or_error!(
                        "Failed to send message to {conn} {msg:?}: {error:?}",
                    );
                }
                let _ = res_tx.send(());
            }

            Command::Broadcast { msg, res_tx } => {
                let response = ctx.read().await.send_all(&msg).await;
                if let Err(error) = response {
                    moosicbox_assert::die_or_error!(
                        "Failed to broadcast message {msg:?}: {error:?}",
                    );
                }
                let _ = res_tx.send(());
            }

            Command::BroadcastExcept { msg, conn, res_tx } => {
                let response = ctx
                    .read()
                    .await
                    .send_all_except(&conn.to_string(), &msg)
                    .await;
                if let Err(error) = response {
                    moosicbox_assert::die_or_error!(
                        "Failed to broadcast message {msg:?}: {error:?}",
                    );
                }
                let _ = res_tx.send(());
            }

            Command::Message { conn, msg, res_tx } => {
                let response = ctx.read().await.on_message(conn, msg.clone()).await;
                if let Err(error) = response {
                    if log::log_enabled!(log::Level::Debug) {
                        moosicbox_assert::die_or_error!(
                            "Failed to process message from {}: {msg:?}: {error:?}",
                            conn
                        );
                    } else {
                        moosicbox_assert::die_or_error!(
                            "Failed to process message from {}: {msg:?}: {error:?} ({:?})",
                            conn,
                            msg
                        );
                    }
                }
                let _ = res_tx.send(());
            }
        }

        log::debug!("process_command: Finished processing cmd {cmd_str}");

        Ok(())
    }

    /// Runs the WebSocket server message processing loop.
    ///
    /// This function consumes the server instance and processes commands until the server
    /// is shut down via the cancellation token. Each command is processed in a separate
    /// spawned task for concurrent handling.
    ///
    /// # Errors
    ///
    /// * If an I/O error occurs during command processing
    pub async fn run(self) -> io::Result<()> {
        let token = self.token.clone();
        let cmd_rx = self.cmd_rx.clone();
        let ctx = Arc::new(RwLock::new(self));
        while let Ok(Ok(cmd)) = switchy_async::select!(
            () = token.cancelled() => {
                log::debug!("WsServer was cancelled");
                Err(std::io::Error::new(std::io::ErrorKind::Interrupted, "Cancelled"))
            }
            cmd = cmd_rx.recv_async() => { Ok(cmd) }
        ) {
            log::trace!("Received WsServer command {cmd}");
            switchy_async::runtime::Handle::current().spawn_with_name(
                "server: WsServer process_command",
                Self::process_command(ctx.clone(), cmd),
            );
        }

        log::debug!("Stopped WsServer");

        Ok(())
    }
}

/// Handle and command sender for ws server.
///
/// Reduces boilerplate of setting up response channels in `WebSocket` handlers.
#[derive(Debug, Clone)]
pub struct WsServerHandle {
    cmd_tx: flume::Sender<Command>,
    token: CancellationToken,
}

#[async_trait]
impl WebsocketSender for WsServerHandle {
    async fn send(&self, connection_id: &str, data: &str) -> Result<(), WebsocketSendError> {
        let id = connection_id.parse::<ConnId>().unwrap();
        self.send(id, data.to_string()).await;
        Ok(())
    }

    async fn send_all(&self, data: &str) -> Result<(), WebsocketSendError> {
        if log::log_enabled!(log::Level::Trace) {
            log::trace!("Broadcasting message to all: {data}");
        } else {
            log::debug!("Broadcasting message to all");
        }
        self.broadcast(data.to_string()).await;
        Ok(())
    }

    async fn send_all_except(
        &self,
        connection_id: &str,
        data: &str,
    ) -> Result<(), WebsocketSendError> {
        if log::log_enabled!(log::Level::Trace) {
            log::trace!("Broadcasting message to all except {connection_id}: {data}");
        } else {
            log::debug!("Broadcasting message to all except {connection_id}");
        }
        self.broadcast_except(connection_id.parse::<ConnId>().unwrap(), data.to_string())
            .await;
        Ok(())
    }

    async fn ping(&self) -> Result<(), WebsocketSendError> {
        self.ping()
            .await
            .map_err(|e| WebsocketSendError::Unknown(e.to_string()))?;
        Ok(())
    }
}

impl WsServerHandle {
    /// Registers a player action callback for a specific player ID.
    ///
    /// Sends a command to the WebSocket server to register the player action, which will
    /// be invoked when playback commands are received for the specified player.
    #[cfg(feature = "player")]
    pub async fn add_player_action(&self, player_id: u64, action: PlayerAction) {
        log::trace!("Sending AddPlayerAction command id={player_id}");

        if let Err(e) = self
            .cmd_tx
            .send_async(Command::AddPlayerAction {
                id: player_id,
                action,
            })
            .await
        {
            moosicbox_assert::die_or_error!("Failed to send command: {e:?}");
        }
    }

    /// Register client message sender and obtain connection ID.
    ///
    /// # Panics
    ///
    /// * If the response channel from the WebSocket server is closed unexpectedly
    pub async fn connect(&self, profile: String, conn_tx: mpsc::Sender<String>) -> ConnId {
        log::trace!("Sending Connect command");

        let (res_tx, res_rx) = oneshot::channel();

        switchy_async::runtime::Handle::current().spawn_with_name("ws server connect", {
            let cmd_tx = self.cmd_tx.clone();
            async move {
                if let Err(e) = cmd_tx
                    .send_async(Command::Connect {
                        profile,
                        conn_tx,
                        res_tx,
                    })
                    .await
                {
                    moosicbox_assert::die_or_error!("Failed to send command: {e:?}");
                }
            }
        });

        res_rx.await.unwrap_or_else(|e| {
            moosicbox_assert::die_or_panic!("Failed to recv response from ws server: {e:?}")
        })
    }

    /// Sends a message to a specific connection.
    ///
    /// The message is sent asynchronously through the command channel and the function
    /// awaits confirmation of delivery to the WebSocket server's internal queue.
    pub async fn send(&self, conn: ConnId, msg: impl Into<String> + Send) {
        log::trace!("Sending Send command");
        let (res_tx, res_rx) = oneshot::channel();

        switchy_async::runtime::Handle::current().spawn_with_name("ws server send", {
            let cmd_tx = self.cmd_tx.clone();
            let msg = msg.into();
            async move {
                if let Err(e) = cmd_tx.send_async(Command::Send { msg, conn, res_tx }).await {
                    moosicbox_assert::die_or_error!("Failed to send command: {e:?}");
                }
            }
        });

        res_rx.await.unwrap_or_else(|e| {
            moosicbox_assert::die_or_error!("Failed to recv response from ws server: {e:?}");
        });
    }

    /// Broadcasts a message to all connected WebSocket clients.
    ///
    /// The message is sent asynchronously through the command channel and delivered to
    /// all active connections in the main room.
    pub async fn broadcast(&self, msg: impl Into<String> + Send) {
        log::trace!("Sending Broadcast command");
        let (res_tx, res_rx) = oneshot::channel();

        switchy_async::runtime::Handle::current().spawn_with_name("ws server broadcast", {
            let cmd_tx = self.cmd_tx.clone();
            let msg = msg.into();
            async move {
                if let Err(e) = cmd_tx.send_async(Command::Broadcast { msg, res_tx }).await {
                    moosicbox_assert::die_or_error!("Failed to send command: {e:?}");
                }
            }
        });

        res_rx.await.unwrap_or_else(|e| {
            moosicbox_assert::die_or_error!("Failed to recv response from ws server: {e:?}");
        });
    }

    /// Broadcasts a message to all connected WebSocket clients except the specified connection.
    ///
    /// This is useful for avoiding echo when the originating connection should not receive
    /// its own broadcast message.
    pub async fn broadcast_except(&self, conn: ConnId, msg: impl Into<String> + Send) {
        log::trace!("Sending BroadcastExcept command");
        let (res_tx, res_rx) = oneshot::channel();

        switchy_async::runtime::Handle::current().spawn_with_name("ws server broadcast_except", {
            let cmd_tx = self.cmd_tx.clone();
            let msg = msg.into();
            async move {
                if let Err(e) = cmd_tx
                    .send_async(Command::BroadcastExcept { msg, conn, res_tx })
                    .await
                {
                    moosicbox_assert::die_or_error!("Failed to send command: {e:?}");
                }
            }
        });

        res_rx.await.unwrap_or_else(|e| {
            moosicbox_assert::die_or_error!("Failed to recv response from ws server: {e:?}");
        });
    }

    /// Broadcast message to current room.
    pub async fn send_message(&self, conn: ConnId, msg: impl Into<String> + Send) {
        log::trace!("Sending Message command");
        let (res_tx, res_rx) = oneshot::channel();

        switchy_async::runtime::Handle::current().spawn_with_name("ws server send_message", {
            let cmd_tx = self.cmd_tx.clone();
            let msg = msg.into();
            async move {
                if let Err(e) = cmd_tx
                    .send_async(Command::Message { msg, conn, res_tx })
                    .await
                {
                    moosicbox_assert::die_or_error!("Failed to send command: {e:?}");
                }
            }
        });

        res_rx.await.unwrap_or_else(|e| {
            moosicbox_assert::die_or_error!("Failed to recv response from ws server: {e:?}");
        });
    }

    /// Unregister message sender and broadcast disconnection message to current room.
    pub async fn disconnect(&self, conn: ConnId) {
        log::trace!("Sending Disconnect command");

        if let Err(e) = self.cmd_tx.send_async(Command::Disconnect { conn }).await {
            moosicbox_assert::die_or_error!("Failed to send command: {e:?}");
        }
    }

    /// Shuts down the WebSocket server by cancelling its processing loop.
    ///
    /// After shutdown, the server will stop accepting new commands and connections.
    pub fn shutdown(&self) {
        self.token.cancel();
    }
}