wse 3.2.0

WebSocket engine for reactive user interfaces: topics with message recovery, presence, clustering without a broker, JWT, end-to-end encryption and signed messages.
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
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
//! The Python binding layer: the `RustWSEServer` class.
//!
//! This file holds everything Python sees: the class, its constructor
//! parameters and the single `#[pymethods]` block (PyO3 takes one per class
//! without its `multiple-pymethods` feature), with every signature, default and
//! docstring. Apart from the constructor and the short accessors, each method
//! delegates to an `*_impl` helper in a topic file.

mod callbacks;
mod cluster;
mod convert;
mod handler;
mod inbound;
mod lifecycle;
mod messaging;
mod metrics;
mod presence;
mod subscriptions;

use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;

use pyo3::exceptions::PyRuntimeError;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList};

use crate::server::{
    Config, JwtKeys, JwtSettings, PresenceSettings, Publisher, RecoverySettings, ServerCommand,
    SharedState,
};

// ---------------------------------------------------------------------------
// PyO3 class
// ---------------------------------------------------------------------------

/// The server object is shared by every Python thread that uses it: a drain
/// loop sits in `drain_inbound()` while other threads broadcast, and `stop()`
/// comes from yet another one. So every method takes `&self` (`frozen`) and the
/// few fields that change do so behind their own synchronization. A `&mut self`
/// method would fail with "Already borrowed" whenever another thread is inside
/// the object - with the GIL too, since `drain_inbound()` releases it while it
/// waits.
#[pyclass(frozen)]
pub struct RustWSEServer {
    host: String,
    port: u16,
    shared: Arc<SharedState>,
    /// Command channel into the running server, `None` while stopped. Loaded on
    /// every send and broadcast, replaced only by `start()` and `stop()`.
    cmd_tx: arc_swap::ArcSwapOption<Publisher>,
    /// The server thread while one exists. Its lock also serializes `start()`
    /// and `stop()` against each other.
    lifecycle: std::sync::Mutex<Option<thread::JoinHandle<()>>>,
    running: Arc<AtomicBool>,
    rt_handle: parking_lot::RwLock<Option<tokio::runtime::Handle>>,
    /// The runtime of a run stopped from one of its own callbacks, while its
    /// thread may still be ending: a start() waits for it, and one of its
    /// callbacks cannot.
    stopping: parking_lot::Mutex<Option<tokio::runtime::Id>>,
    /// Callback mode's callbacks (`set_callbacks()`), shared with the handler.
    callbacks: Arc<handler::PyCallbacks>,
}

/// The command sender of the running server, loaded from `RustWSEServer::cmd_tx`
/// without touching its reference count.
struct CommandTx(arc_swap::Guard<Option<Arc<Publisher>>>);

impl std::ops::Deref for CommandTx {
    type Target = Publisher;

    fn deref(&self) -> &Self::Target {
        self.0
            .as_deref()
            .expect("CommandTx is only built while a sender is stored")
    }
}

impl Drop for RustWSEServer {
    /// Dropped while running, without stop(): the server is told to stop and
    /// its thread ends by itself; nothing waits for it here.
    fn drop(&mut self) {
        if self.running.swap(false, Ordering::SeqCst) {
            // The run leaves the cluster as it ends.
            if let Some(tx) = self.cmd_tx.load_full() {
                let _ = tx.command(ServerCommand::Shutdown);
            }
        }
    }
}

// Parameter groups for RustWSEServer::new() -- keeps the PyO3 #[new] shim clean
struct ServerParams {
    max_connections: usize,
    max_inbound_queue_size: usize,
    max_inbound_queue_bytes: usize,
    allowed_origins: Option<Vec<String>>,
    client_subscriptions: bool,
    e2e_identity_key: Option<Vec<u8>>,
    e2e_legacy: bool,
    signing_key: Option<Vec<u8>>,
    signature_window: u64,
    bind_sessions: bool,
    max_message_size: usize,
    ping_interval: u64,
    idle_timeout: u64,
    max_outbound_queue_bytes: usize,
    max_subscriptions_per_connection: usize,
    rate_limit_capacity: f64,
    rate_limit_refill: f64,
}

struct JwtParams {
    jwt_secret: Option<Vec<u8>>,
    jwt_issuer: Option<String>,
    jwt_audience: Option<String>,
    jwt_cookie_name: Option<String>,
    jwt_previous_secret: Option<Vec<u8>>,
    jwt_key_id: Option<String>,
    jwt_algorithm: Option<String>,
    jwt_private_key: Option<Vec<u8>>,
}

struct RecoveryParams {
    recovery_enabled: bool,
    recovery_buffer_size: usize,
    recovery_ttl: u64,
    recovery_max_messages: usize,
    recovery_memory_budget: usize,
}

struct PresenceParams {
    presence_enabled: bool,
    presence_max_data_size: usize,
    presence_max_members: usize,
}

impl RustWSEServer {
    // Config's fields are set one by one, as from another crate.
    #[allow(clippy::field_reassign_with_default)]
    fn build(
        host: String,
        port: u16,
        srv: ServerParams,
        jwt: JwtParams,
        rec: RecoveryParams,
        pres: PresenceParams,
    ) -> PyResult<Self> {
        // Every jwt_* option needs jwt_secret: without it the server runs with
        // no authentication, and an issuer or audience set alone would only
        // look like protection.
        if jwt.jwt_secret.is_none() {
            let set: Vec<&str> = [
                ("jwt_issuer", jwt.jwt_issuer.is_some()),
                ("jwt_audience", jwt.jwt_audience.is_some()),
                ("jwt_previous_secret", jwt.jwt_previous_secret.is_some()),
                ("jwt_key_id", jwt.jwt_key_id.is_some()),
                ("jwt_algorithm", jwt.jwt_algorithm.is_some()),
                ("jwt_private_key", jwt.jwt_private_key.is_some()),
                ("jwt_cookie_name", jwt.jwt_cookie_name.is_some()),
            ]
            .into_iter()
            .filter_map(|(name, is_set)| is_set.then_some(name))
            .collect();
            if !set.is_empty() {
                return Err(pyo3::exceptions::PyValueError::new_err(format!(
                    "{} set without jwt_secret: the server would accept every connection \
                     unauthenticated. Pass jwt_secret (the HMAC secret, or the public key \
                     for the asymmetric algorithms) or drop these options.",
                    set.join(", ")
                )));
            }
        }
        let mut config = Config::default();
        config.max_connections = srv.max_connections;
        config.max_inbound_queue_size = srv.max_inbound_queue_size;
        config.max_inbound_queue_bytes = srv.max_inbound_queue_bytes;
        config.allowed_origins = srv.allowed_origins;
        config.client_subscriptions = srv.client_subscriptions;
        config.e2e_identity_key = srv.e2e_identity_key;
        config.e2e_legacy = srv.e2e_legacy;
        config.signing_key = srv.signing_key;
        config.signature_window = srv.signature_window;
        config.bind_sessions = srv.bind_sessions;
        config.max_message_size = srv.max_message_size;
        config.ping_interval = srv.ping_interval;
        config.idle_timeout = srv.idle_timeout;
        config.max_outbound_queue_bytes = srv.max_outbound_queue_bytes;
        config.max_subscriptions_per_connection = srv.max_subscriptions_per_connection;
        config.rate_limit_capacity = srv.rate_limit_capacity;
        config.rate_limit_refill = srv.rate_limit_refill;
        config.jwt = jwt.jwt_secret.map(|secret| {
            let mut settings = JwtSettings::new(secret);
            settings.algorithm = jwt.jwt_algorithm;
            settings.issuer = jwt.jwt_issuer;
            settings.audience = jwt.jwt_audience;
            settings.cookie_name = jwt.jwt_cookie_name;
            settings.previous_secret = jwt.jwt_previous_secret;
            settings.key_id = jwt.jwt_key_id;
            settings.private_key = jwt.jwt_private_key;
            settings
        });
        config.recovery = rec.recovery_enabled.then(|| {
            let mut settings = RecoverySettings::default();
            settings.buffer_size = rec.recovery_buffer_size;
            settings.ttl = rec.recovery_ttl;
            settings.max_messages = rec.recovery_max_messages;
            settings.memory_budget = rec.recovery_memory_budget;
            settings
        });
        config.presence = pres.presence_enabled.then(|| {
            let mut settings = PresenceSettings::default();
            settings.max_data_size = pres.presence_max_data_size;
            settings.max_members = pres.presence_max_members;
            settings
        });
        let shared = config
            .into_state()
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;
        Ok(Self {
            host,
            port,
            shared: Arc::new(shared),
            cmd_tx: arc_swap::ArcSwapOption::empty(),
            lifecycle: std::sync::Mutex::new(None),
            running: Arc::new(AtomicBool::new(false)),
            rt_handle: parking_lot::RwLock::new(None),
            stopping: parking_lot::Mutex::new(None),
            callbacks: Arc::default(),
        })
    }

    /// The command channel of the running server, or `RuntimeError("Not running")`.
    fn command_tx(&self) -> PyResult<CommandTx> {
        let guard = self.cmd_tx.load();
        if guard.is_none() {
            return Err(PyRuntimeError::new_err("Not running"));
        }
        Ok(CommandTx(guard))
    }

    /// The engine's API for this server, running or not.
    fn engine(&self) -> Publisher {
        Publisher::new(Arc::clone(&self.shared))
    }

    /// The tokio runtime of the server, once it has been started.
    fn runtime(&self) -> Option<tokio::runtime::Handle> {
        self.rt_handle.read().clone()
    }
}

#[pymethods]
impl RustWSEServer {
    /// Create a new WSE server instance.
    ///
    /// The server runs all transport in Rust (TCP, TLS, WS framing, JWT auth,
    /// compression, encryption, ping/pong). Python handles application logic
    /// via drain mode or callbacks.
    #[new]
    #[pyo3(signature = (host, port, max_connections = 1000, jwt_secret = None, jwt_issuer = None, jwt_audience = None, jwt_cookie_name = None, jwt_previous_secret = None, jwt_key_id = None, jwt_algorithm = None, jwt_private_key = None, max_inbound_queue_size = 131072, recovery_enabled = false, recovery_buffer_size = 128, recovery_ttl = 300, recovery_max_messages = 500, recovery_memory_budget = 268435456, presence_enabled = false, presence_max_data_size = 4096, presence_max_members = 0, rate_limit_capacity = 100_000.0, rate_limit_refill = 10_000.0, max_message_size = 1_048_576, ping_interval = 25, idle_timeout = 60, max_outbound_queue_bytes = 16_777_216, max_subscriptions_per_connection = 0, max_inbound_queue_bytes = 67_108_864, allowed_origins = None, client_subscriptions = false, e2e_identity_key = None, e2e_legacy = true, signing_key = None, signature_window = 30, bind_sessions = true))]
    #[expect(
        clippy::too_many_arguments,
        reason = "PyO3 __init__: 34 Python kwargs with defaults"
    )]
    fn new(
        host: String,
        port: u16,
        max_connections: usize,
        jwt_secret: Option<Vec<u8>>,
        jwt_issuer: Option<String>,
        jwt_audience: Option<String>,
        jwt_cookie_name: Option<String>,
        jwt_previous_secret: Option<Vec<u8>>,
        jwt_key_id: Option<String>,
        jwt_algorithm: Option<String>,
        jwt_private_key: Option<Vec<u8>>,
        max_inbound_queue_size: usize,
        recovery_enabled: bool,
        recovery_buffer_size: usize,
        recovery_ttl: u64,
        recovery_max_messages: usize,
        recovery_memory_budget: usize,
        presence_enabled: bool,
        presence_max_data_size: usize,
        presence_max_members: usize,
        rate_limit_capacity: f64,
        rate_limit_refill: f64,
        max_message_size: usize,
        ping_interval: u64,
        idle_timeout: u64,
        max_outbound_queue_bytes: usize,
        max_subscriptions_per_connection: usize,
        max_inbound_queue_bytes: usize,
        allowed_origins: Option<Vec<String>>,
        client_subscriptions: bool,
        e2e_identity_key: Option<Vec<u8>>,
        e2e_legacy: bool,
        signing_key: Option<Vec<u8>>,
        signature_window: u64,
        bind_sessions: bool,
    ) -> PyResult<Self> {
        Self::build(
            host,
            port,
            ServerParams {
                max_connections,
                max_inbound_queue_size,
                max_inbound_queue_bytes,
                allowed_origins,
                client_subscriptions,
                e2e_identity_key,
                e2e_legacy,
                signing_key,
                signature_window,
                bind_sessions,
                max_message_size,
                ping_interval,
                idle_timeout,
                max_outbound_queue_bytes,
                max_subscriptions_per_connection,
                rate_limit_capacity,
                rate_limit_refill,
            },
            JwtParams {
                jwt_secret,
                jwt_issuer,
                jwt_audience,
                jwt_cookie_name,
                jwt_previous_secret,
                jwt_key_id,
                jwt_algorithm,
                jwt_private_key,
            },
            RecoveryParams {
                recovery_enabled,
                recovery_buffer_size,
                recovery_ttl,
                recovery_max_messages,
                recovery_memory_budget,
            },
            PresenceParams {
                presence_enabled,
                presence_max_data_size,
                presence_max_members,
            },
        )
    }

    /// Register Python callbacks for connection events.
    ///
    /// - on_connect(conn_id, user_id) -- called when a client connects; the
    ///   user id the server validated, or without jwt_secret the Cookie header
    /// - on_message(conn_id, data) -- called when a message is received
    /// - on_disconnect(conn_id) -- called when a client disconnects
    /// - on_signed_message(conn_id, data) -- optional: a client's signed
    ///   message that passed every check, with its proof in
    ///   data["signature"]. Without it such messages go to on_message,
    ///   without the proof.
    ///
    /// The callbacks of one connection run one after another in the order of
    /// its events. Alternative to drain mode. Cannot be used together with
    /// enable_drain_mode().
    #[pyo3(signature = (on_connect, on_message, on_disconnect, on_signed_message = None))]
    fn set_callbacks(
        &self,
        py: Python<'_>,
        on_connect: Py<PyAny>,
        on_message: Py<PyAny>,
        on_disconnect: Py<PyAny>,
        on_signed_message: Option<Py<PyAny>>,
    ) -> PyResult<()> {
        self.set_callbacks_impl(py, on_connect, on_message, on_disconnect, on_signed_message)
    }

    /// The server's public key for the messages it signs: base64 of the
    /// uncompressed P-256 point, what clients pin to check them. None without
    /// signing_key.
    fn signing_public_key(&self) -> Option<String> {
        self.engine().signing_public_key()
    }

    /// A message signed with the server's signing_key, ready for send(),
    /// broadcast() and the rest: its type, payload and, for a topic message,
    /// the topic, which the signature covers. `to` names the one user it is
    /// for (the token's sub, or the user_id given to accept_connection):
    /// the signature covers it, and other users' clients drop the message.
    /// Sign once, send to any number of connections.
    #[pyo3(signature = (event_type, payload = None, topic = None, to = None))]
    fn sign(
        &self,
        event_type: &str,
        payload: Option<&Bound<'_, PyAny>>,
        topic: Option<&str>,
        to: Option<&str>,
    ) -> PyResult<String> {
        self.sign_impl(event_type, payload, topic, to)
    }

    /// Bind the public key a connection signs its messages with (base64 of
    /// the uncompressed P-256 point), or remove it (None). A key from the
    /// connection's token (`cnf` claim) is replaced. False when there is no
    /// such connection.
    fn set_client_key(&self, conn_id: &str, public_key: Option<&str>) -> PyResult<bool> {
        self.set_client_key_impl(conn_id, public_key)
    }

    /// Start the WebSocket server on a background thread.
    ///
    /// Binds to host:port, spawns a dedicated tokio runtime and begins
    /// accepting connections. Raises RuntimeError if already running and
    /// OSError if host:port cannot be bound.
    fn start(&self, py: Python<'_>) -> PyResult<()> {
        self.start_impl(py)
    }

    /// Enter graceful drain mode (lame duck).
    ///
    /// 1. Stops accepting new connections (upgrades get HTTP 503)
    /// 2. Notifies cluster peers via DRAIN frame
    /// 3. Closes every client with `close_code`; a client that does not
    ///    answer within 5 seconds is disconnected
    /// 4. Waits up to `timeout` seconds for clients to disconnect, then
    ///    drops the rest
    ///
    /// Returns how many connections had to be dropped at the timeout. Call
    /// `stop()` after `drain()` to fully shut down.
    #[pyo3(signature = (close_code = 4300, close_reason = "", timeout = 30))]
    fn drain(
        &self,
        py: Python<'_>,
        close_code: u16,
        close_reason: &str,
        timeout: u64,
    ) -> PyResult<usize> {
        self.drain_impl(py, close_code, close_reason, timeout)
    }

    /// True between drain() and the next start().
    fn is_draining(&self) -> bool {
        self.engine().is_draining()
    }

    /// `with RustWSEServer(...) as server:` starts the server (unless it
    /// runs already) and stops it at the end of the block.
    fn __enter__<'py>(slf: PyRef<'py, Self>, py: Python<'py>) -> PyResult<PyRef<'py, Self>> {
        if !slf.running.load(Ordering::SeqCst) {
            slf.start_impl(py)?;
        }
        Ok(slf)
    }

    /// Stops the server; an exception in the block is not swallowed.
    #[pyo3(signature = (exc_type = None, exc = None, traceback = None))]
    fn __exit__(
        &self,
        py: Python<'_>,
        exc_type: Option<&Bound<'_, PyAny>>,
        exc: Option<&Bound<'_, PyAny>>,
        traceback: Option<&Bound<'_, PyAny>>,
    ) -> PyResult<bool> {
        let _ = (exc_type, exc, traceback);
        self.stop_impl(py)?;
        Ok(false)
    }

    /// Stop the server and close all connections (close code 1001).
    ///
    /// Shuts down the cluster mesh, sends a Shutdown command, and joins
    /// the server thread. Safe to call if not running (returns Ok).
    ///
    /// Callable from any thread, also while other threads are inside the
    /// server (for example a drain loop waiting in `drain_inbound()`).
    fn stop(&self, py: Python<'_>) -> PyResult<()> {
        self.stop_impl(py)
    }

    // -- send methods -------------------------------------------------------

    /// Send a raw text frame to a single connection.
    fn send(&self, py: Python<'_>, conn_id: &str, data: &str) -> PyResult<()> {
        self.send_impl(py, conn_id, data)
    }

    /// Send a raw binary frame to a single connection.
    fn send_bytes(&self, py: Python<'_>, conn_id: &str, data: &[u8]) -> PyResult<()> {
        self.send_bytes_impl(py, conn_id, data)
    }

    /// Full outbound pipeline in Rust: PyDict -> envelope -> JSON -> compress -> send.
    /// Returns the size of the frame handed to the connection, 0 for an event
    /// id this connection already got. A connection whose outbound queue is
    /// over `max_outbound_queue_bytes` drops it.
    #[pyo3(signature = (conn_id, event, compression_threshold = 1024))]
    fn send_event(
        &self,
        py: Python<'_>,
        conn_id: &str,
        event: &Bound<'_, PyDict>,
        compression_threshold: usize,
    ) -> PyResult<usize> {
        self.send_event_impl(py, conn_id, event, compression_threshold)
    }

    /// Send a text frame to all connected clients (no topic filtering).
    fn broadcast_all(&self, py: Python<'_>, data: &str) -> PyResult<()> {
        self.broadcast_all_impl(py, data)
    }

    /// Send a binary frame to all connected clients.
    fn broadcast_all_bytes(&self, py: Python<'_>, data: &[u8]) -> PyResult<()> {
        self.broadcast_all_bytes_impl(py, data)
    }

    // -- query / management -------------------------------------------------

    /// Number of active connections (lock-free AtomicUsize read).
    fn get_connection_count(&self) -> usize {
        self.engine().connection_count()
    }

    /// List all active connection IDs, read without waiting for the server.
    fn get_connections(&self) -> Vec<String> {
        self.engine().connections()
    }

    /// Close a connection with code 1000. Its messages after that are not
    /// delivered, and a client that does not answer within 5 seconds is
    /// disconnected.
    fn disconnect(&self, conn_id: &str) -> PyResult<()> {
        self.command_tx()?
            .disconnect(conn_id)
            .map_err(messaging::py_error)
    }

    // -- users ----------------------------------------------------------------

    /// The connections of a user on this server (the token's `sub`, or the
    /// user_id given to accept_connection): every tab and device it has
    /// open here.
    fn get_user_connections(&self, user_id: &str) -> Vec<String> {
        self.engine().user_connections(user_id)
    }

    /// Send a text frame to every connection of a user on this server.
    /// Returns how many it went to.
    fn send_to_user(&self, py: Python<'_>, user_id: &str, data: &str) -> PyResult<usize> {
        self.send_to_user_impl(py, user_id, data)
    }

    /// `send_event` to every connection of a user on this server, each in
    /// its own format. Returns how many it went to.
    #[pyo3(signature = (user_id, event, compression_threshold = 1024))]
    fn send_event_to_user(
        &self,
        py: Python<'_>,
        user_id: &str,
        event: &Bound<'_, PyDict>,
        compression_threshold: usize,
    ) -> PyResult<usize> {
        self.send_event_to_user_impl(py, user_id, event, compression_threshold)
    }

    /// Close every connection of a user on this server (1000): a logout, a
    /// revoked session, a banned account. Returns how many it closed.
    fn disconnect_user(&self, user_id: &str) -> PyResult<usize> {
        self.command_tx()?
            .disconnect_user(user_id)
            .map_err(messaging::py_error)
    }

    /// Accept a connection the application authenticated itself (a server
    /// without `jwt_secret`): it gets server_ready, the message the clients
    /// wait for before they send anything, and `user_id` becomes its user
    /// for presence. Call it once per connection, after checking the
    /// cookies of its "connect" event. Returns False when the connection is
    /// gone. A server that validates tokens itself sends server_ready on its
    /// own and raises RuntimeError here.
    ///
    /// With client_key (base64 of the user's P-256 public key), the
    /// connection is bound to it: admitted once the client has proved the key
    /// inside its end-to-end session, refused (4401) when it proves another
    /// or none, so a cookie copied on the way opens nothing. RuntimeError for
    /// a connection without an end-to-end session.
    #[pyo3(signature = (conn_id, user_id, client_key = None))]
    fn accept_connection(
        &self,
        conn_id: &str,
        user_id: &str,
        client_key: Option<&str>,
    ) -> PyResult<bool> {
        self.accept_connection_impl(conn_id, user_id, client_key)
    }

    /// Return True if the server is running.
    fn is_running(&self) -> bool {
        self.running.load(Ordering::SeqCst)
    }

    // -- drain mode -----------------------------------------------------------

    /// Enable drain mode. Inbound events are queued instead of calling
    /// on_message/on_connect/on_disconnect callbacks. Call drain_inbound()
    /// from a Python thread to retrieve batches.
    fn enable_drain_mode(&self) {
        self.shared.drain_mode.store(true, Ordering::SeqCst);
    }

    /// Drain up to max_count inbound events. Blocks up to timeout_ms waiting
    /// for at least one event. Returns list of (event_type, conn_id, data) tuples.
    ///
    /// event_type: "connect" | "auth_connect" | "msg" | "raw" | "bin" |
    ///             "disconnect" | "presence_join" | "presence_leave"
    ///
    /// data: str (for "connect"=cookies, "auth_connect"=user_id, "raw"),
    ///       dict (for "msg", "presence_join", "presence_leave"),
    ///       bytes (for "bin"), None (for "disconnect")
    ///
    /// GIL is released while waiting on channel, acquired once for batch conversion.
    #[pyo3(signature = (max_count = 256, timeout_ms = 50))]
    fn drain_inbound(
        &self,
        py: Python<'_>,
        max_count: usize,
        timeout_ms: u64,
    ) -> PyResult<Py<PyList>> {
        self.drain_inbound_impl(py, max_count, timeout_ms)
    }

    /// Client messages dropped over `max_inbound_queue_size` or
    /// `max_inbound_queue_bytes`. Connect, disconnect and presence events are
    /// never dropped.
    fn inbound_dropped_count(&self) -> u64 {
        self.shared.inbound_dropped.load(Ordering::Relaxed)
    }

    /// Current number of events waiting in the inbound queue.
    fn inbound_queue_depth(&self) -> usize {
        self.shared.inbound_rx.len()
    }

    // -- Cluster Protocol -----------------------------------------------------

    /// Connect to cluster peers via TCP mesh protocol.
    ///
    /// Two modes: static peers (pass peer addresses directly) or seed-based
    /// discovery (pass seeds + cluster_addr for gossip).
    ///
    /// The links are TLS, always: from `cluster_secret` (at least 32 random
    /// bytes, the same on every node: a node without it cannot link), or
    /// from certificate files (`tls_cert`, `tls_key`, `tls_ca`). Left out,
    /// they come from WSE_CLUSTER_SECRET, or from WSE_CLUSTER_TLS_CERT/KEY/CA.
    ///
    /// Peers' links come in on `cluster_port` (bound on `cluster_host`,
    /// 0.0.0.0 by default; `::` is IPv6 and IPv4), or with `single_port=True`
    /// on the WebSocket port.
    /// One of the two is required.
    ///
    /// Addresses are `host:port`; an IPv6 address carries its zone by number
    /// (`[fe80::1%2]:9999`): one by an interface's name is a ValueError.
    ///
    /// Raises RuntimeError if cluster is already connected or if seeds
    /// is used without cluster_addr, ValueError for a missing or short
    /// secret or a missing or contradictory option, OSError if
    /// `cluster_port` cannot be bound.
    #[pyo3(signature = (peers, tls_cert=None, tls_key=None, tls_ca=None, cluster_port=None, seeds=None, cluster_addr=None, cluster_host=None, single_port=false, cluster_secret=None))]
    #[expect(
        clippy::too_many_arguments,
        reason = "PyO3 boundary: &self + 10 Python kwargs"
    )]
    fn connect_cluster(
        &self,
        peers: Vec<String>,
        tls_cert: Option<String>,
        tls_key: Option<String>,
        tls_ca: Option<String>,
        cluster_port: Option<u16>,
        seeds: Option<Vec<String>>,
        cluster_addr: Option<String>,
        cluster_host: Option<String>,
        single_port: bool,
        cluster_secret: Option<&Bound<'_, PyAny>>,
    ) -> PyResult<()> {
        self.connect_cluster_inner(
            peers,
            (tls_cert, tls_key, tls_ca),
            (cluster_port, cluster_host, single_port),
            (seeds, cluster_addr),
            cluster_secret,
        )
    }

    /// Return True if at least one cluster peer is connected.
    fn cluster_connected(&self) -> bool {
        self.shared
            .cluster_metrics
            .connected_peers
            .load(Ordering::Relaxed)
            > 0
    }

    /// Number of connected cluster peers.
    fn cluster_peers_count(&self) -> u64 {
        self.shared
            .cluster_metrics
            .connected_peers
            .load(Ordering::Relaxed)
    }

    /// Sign a token for user `sub` with this server's configuration: its
    /// algorithm and key (the HMAC secret, or `jwt_private_key` for the
    /// asymmetric algorithms), `jwt_key_id`, and its issuer and audience when
    /// set. Valid for `ttl` seconds; `claims` adds or overrides others.
    /// Raises RuntimeError on a server without jwt_secret, or with an
    /// asymmetric algorithm but no jwt_private_key.
    #[pyo3(signature = (sub, ttl = 900, claims = None))]
    fn issue_token(
        &self,
        sub: &str,
        ttl: u64,
        claims: Option<&Bound<'_, PyDict>>,
    ) -> PyResult<String> {
        let claims = match claims {
            Some(claims) => match crate::jwt_py::pydict_to_json(claims)? {
                serde_json::Value::Object(claims) => claims,
                _ => serde_json::Map::new(),
            },
            None => serde_json::Map::new(),
        };
        self.engine()
            .issue_token(sub, std::time::Duration::from_secs(ttl), claims)
            .map_err(messaging::py_error)
    }

    /// The public key clients pin for end-to-end encryption: base64 of the
    /// uncompressed P-256 point of `e2e_identity_key`, None without one.
    fn e2e_identity_public_key(&self) -> Option<String> {
        use base64::Engine;
        self.shared
            .e2e_identity
            .as_ref()
            .map(|k| base64::engine::general_purpose::STANDARD.encode(k.public_key()))
    }

    /// Replace the JWT verification keys without a restart, for a key
    /// rotation: `jwt_secret` (the HMAC secret, or the public key of the
    /// asymmetric algorithms) and optionally `jwt_previous_secret`, accepted
    /// too while tokens signed with it are still out. The algorithm, issuer,
    /// audience and cookie name stay. Open connections are not affected; new
    /// ones are checked with the new keys. With an asymmetric algorithm and a
    /// new public key, a server that issues tokens needs the new
    /// `jwt_private_key` too. Raises RuntimeError on a server without
    /// jwt_secret, ValueError for a key that does not fit.
    #[pyo3(signature = (jwt_secret, jwt_previous_secret = None, jwt_key_id = None, jwt_private_key = None))]
    fn reload_jwt_keys(
        &self,
        jwt_secret: Vec<u8>,
        jwt_previous_secret: Option<Vec<u8>>,
        jwt_key_id: Option<String>,
        jwt_private_key: Option<Vec<u8>>,
    ) -> PyResult<()> {
        let mut keys = JwtKeys::new(jwt_secret);
        keys.previous_secret = jwt_previous_secret;
        keys.key_id = jwt_key_id;
        keys.private_key = jwt_private_key;
        self.engine()
            .reload_jwt_keys(keys)
            .map_err(messaging::py_error)
    }

    /// Hot-reload cluster TLS certificates without restarting the server.
    /// New connections will use the updated certs; in-flight handshakes
    /// complete with the previous config (TlsAcceptor/TlsConnector use Arc internally).
    #[pyo3(signature = (cert_path, key_path, ca_path))]
    fn reload_cluster_tls(
        &self,
        cert_path: String,
        key_path: String,
        ca_path: String,
    ) -> PyResult<()> {
        self.reload_cluster_tls_impl(cert_path, key_path, ca_path)
    }

    /// List connected cluster peers with address, instance_id, capabilities,
    /// and connected_at timestamp. Returns a list of dicts.
    fn cluster_info(&self, py: Python<'_>) -> PyResult<Py<PyList>> {
        self.cluster_info_impl(py)
    }

    // -- Topic authorization --------------------------------------------------

    /// Set topic ACL for a connection programmatically (for non-JWT auth).
    ///
    /// - allow: list of glob patterns; left out, every topic not denied is
    ///   allowed, and an empty list allows none (as in the JWT claim)
    /// - deny: list of glob patterns (deny takes precedence over allow)
    ///
    /// Returns False (and stores nothing) when the connection is gone.
    #[pyo3(signature = (conn_id, allow = None, deny = None))]
    fn set_topic_acl(
        &self,
        conn_id: &str,
        allow: Option<Vec<String>>,
        deny: Option<Vec<String>>,
    ) -> bool {
        self.set_topic_acl_impl(conn_id, allow, deny)
    }

    // -- Topic subscriptions --------------------------------------------------

    /// Subscribe a connection to topics.
    ///
    /// Optionally set initial presence data (requires presence_enabled=True).
    /// If queue_group is set, the connection joins a named group for
    /// round-robin dispatch instead of standard fan-out.
    ///
    /// Returns the topics it took: not those its topic ACL denies, invalid
    /// names (empty, over 256 bytes, control characters), patterns past 16
    /// per connection, or what exceeds max_subscriptions_per_connection.
    #[pyo3(signature = (conn_id, topics, presence_data = None, queue_group = None))]
    fn subscribe_connection(
        &self,
        py: Python<'_>,
        conn_id: &str,
        topics: Vec<String>,
        presence_data: Option<&Bound<'_, PyDict>>,
        queue_group: Option<String>,
    ) -> PyResult<Vec<String>> {
        self.subscribe_connection_impl(py, conn_id, topics, presence_data, queue_group)
    }

    /// Subscribe with message recovery support.
    ///
    /// Returns a dict with per-topic recovery status:
    /// {recovered: bool, topics: {topic: {epoch, offset, recoverable, recovered,
    /// count, subscribed}}}
    ///
    /// When recover=True, replays missed messages from the recovery buffer,
    /// before anything sent to the connection afterwards. `positions` maps
    /// each topic to its own {"epoch": "<8 hex>", "offset": n}, the shape the
    /// clients send in `p.recovery`; a single `epoch` and `offset` apply to
    /// every topic. `offset` in the result is the last offset the client has
    /// (or may take as had): when nothing was recovered, everything after it
    /// reaches the connection live. A replay cut short by the outbound budget
    /// reports recovered=False and the last offset it queued.
    #[pyo3(signature = (conn_id, topics, recover = false, epoch = None, offset = None, positions = None))]
    #[expect(
        clippy::too_many_arguments,
        reason = "PyO3 boundary: &self + 7 Python arguments"
    )]
    fn subscribe_with_recovery(
        &self,
        py: Python<'_>,
        conn_id: &str,
        topics: Vec<String>,
        recover: bool,
        epoch: Option<String>,
        offset: Option<u64>,
        positions: Option<&Bound<'_, PyDict>>,
    ) -> PyResult<Py<PyDict>> {
        self.subscribe_with_recovery_impl(py, conn_id, topics, recover, epoch, offset, positions)
    }

    /// Unsubscribe a connection from topics.
    /// If topics is None, unsubscribe from all topics.
    #[pyo3(signature = (conn_id, topics = None))]
    fn unsubscribe_connection(&self, conn_id: &str, topics: Option<Vec<String>>) -> PyResult<()> {
        self.unsubscribe_connection_impl(conn_id, topics)
    }

    /// Fan-out to topic subscribers locally.
    fn broadcast_local(&self, py: Python<'_>, topic: &str, data: &str) -> PyResult<()> {
        self.broadcast_local_impl(py, topic, data)
    }

    /// Fan-out locally + cluster PUBLISH for multi-instance coordination.
    fn broadcast(&self, py: Python<'_>, topic: &str, data: &str) -> PyResult<()> {
        self.broadcast_impl(py, topic, data)
    }

    /// Number of fan-out subscribers on a topic (excludes queue group members).
    fn get_topic_subscriber_count(&self, topic: &str) -> usize {
        self.engine().topic_subscriber_count(topic)
    }

    /// Get queue group info for a topic. Returns dict of group_name -> member_count.
    fn get_queue_group_info(&self, py: Python<'_>, topic: &str) -> PyResult<Py<PyDict>> {
        self.get_queue_group_info_impl(py, topic)
    }

    /// Full server health snapshot as a dict.
    ///
    /// Keys: connections, inbound_queue_depth, inbound_dropped,
    /// cluster_connected, cluster_peer_count, cluster_messages_sent/delivered/dropped,
    /// cluster_bytes_sent/received, cluster_reconnect_count, cluster_dlq_size,
    /// uptime_secs, recovery_enabled/topic_count/total_bytes,
    /// presence_enabled/topics/total_users.
    fn health_snapshot(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
        self.health_snapshot_impl(py)
    }

    /// Return Prometheus exposition format metrics string.
    ///
    /// Includes gauges (connections, queue depth, uptime, drops),
    /// per-topic counters (top 50 by volume), cluster metrics,
    /// and optional recovery/presence gauges.
    fn prometheus_metrics(&self) -> String {
        self.prometheus_metrics_impl()
    }

    /// Drain and return dead-letter-queue entries from failed cluster sends.
    ///
    /// Each entry is a dict with keys: topic, payload, peer_addr, error.
    /// Entries are consumed (not peeked) -- calling twice returns different results.
    fn get_cluster_dlq_entries(&self, py: Python<'_>) -> PyResult<Py<PyList>> {
        self.get_cluster_dlq_entries_impl(py)
    }

    /// Get all members currently present in a topic.
    /// Returns dict: {user_id: {"data": {...}, "connections": N}}
    fn presence(&self, py: Python<'_>, topic: &str) -> PyResult<Py<PyDict>> {
        self.presence_impl(py, topic)
    }

    /// Get lightweight presence counters for a topic (O(1), no iteration).
    /// Returns dict: {"num_users": N, "num_connections": M}
    fn presence_stats(&self, py: Python<'_>, topic: &str) -> PyResult<Py<PyDict>> {
        self.presence_stats_impl(py, topic)
    }

    /// Update presence data for a connection across all its presence topics.
    #[pyo3(signature = (conn_id, data))]
    fn update_presence(&self, conn_id: &str, data: &Bound<'_, PyDict>) -> PyResult<()> {
        self.update_presence_impl(conn_id, data)
    }
}