noxu-rep 3.2.0

Replication and high availability for Noxu DB
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
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
//! QUIC multiplexed transport for Noxu DB replication.
//!
//! Extends the single-stream [`QuicChannel`] with true QUIC stream
//! multiplexing: one QUIC connection carries four independent streams, one
//! per replication concern, plus unreliable datagrams for CBVLSN broadcasts.
//!
//! ## Feature flag
//!
//! Compiled only when the `quic` cargo feature is enabled.
//!
//! ## Stream layout
//!
//! | Stream | ID | Direction | Purpose                       |
//! |--------|----|-----------|-------------------------------|
//! | Heartbeat | 0 | Bidirectional | Elections and heartbeats   |
//! | Log       | 1 | M → R     | Log-entry shipping            |
//! | Ack       | 2 | R → M     | Commit acknowledgements       |
//! | Restore   | 3 | M → R     | Network restore file xfer     |
//!
//! ## Why separate streams matter
//!
//! QUIC enforces per-stream flow control.  On TCP, a large log-shipping burst
//! fills the socket send buffer and delays the next heartbeat packet — the
//! classic head-of-line blocking problem.  With separate QUIC streams, log
//! back-pressure on stream 1 has no effect on stream 0 heartbeats, so the
//! `PhiAccrualDetector` sees a tighter inter-arrival distribution and is less
//! prone to false elections.
//!
//! ## CBVLSN datagrams
//!
//! CBVLSN (Cluster-Based VLSN) heartbeat values are broadcast as 8-byte
//! unreliable QUIC datagrams (`RFC 9221`).  A lost datagram is immediately
//! superseded by the next broadcast (~10 ms later), so reliability is
//! unnecessary and the overhead of retransmission is avoided.
//!
//! ## Wire handshake
//!
//! On connection the client opens four bidirectional QUIC streams (in order
//! 0–3) and writes a 5-byte handshake on each:
//! `[NXMX: 4 bytes][stream_type: 1 byte]`.
//! The server accepts four streams and validates the magic + type.
//!
//! ## 0-RTT reconnect
//!
//! Because `QuicMultiplexedChannel::connect` stores the underlying `Endpoint`,
//! TLS session tickets from the initial connection are cached.  On master
//! failover, extract the endpoint via [`QuicMultiplexedChannel::take_endpoint`]
//! and call [`QuicMultiplexedChannel::connect_with_endpoint`]; Quinn uses the
//! cached session ticket and issues a 0-RTT / early-data reconnect, cutting
//! reconnect latency from ~3 RTT (TCP+TLS) to ~1 RTT.

use hashbrown::HashMap;
use std::net::{SocketAddr, ToSocketAddrs};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use bytes::Bytes;
use quinn::{Connection, Endpoint, ReadExactError, RecvStream, SendStream};
use tokio::runtime::Runtime;

use super::quic_channel::{default_server_config, insecure_client_config};
use crate::error::{RepError, Result};
use crate::net::channel::Channel;

// ---------------------------------------------------------------------------
// Wire protocol constants
// ---------------------------------------------------------------------------

/// Magic bytes identifying a multiplexed QUIC connection.
/// Distinguishes from single-stream [`QuicChannel`] (which uses `b"NXUR"`).
const MULTIPLEXED_MAGIC: &[u8; 4] = b"NXMX";

/// Stream type identifiers sent as the 5th byte of the per-stream handshake.
const STREAM_HEARTBEAT: u8 = 0;
const STREAM_LOG: u8 = 1;
const STREAM_ACK: u8 = 2;
const STREAM_RESTORE: u8 = 3;

/// Total number of streams opened per multiplexed connection.
const NUM_STREAMS: usize = 4;

// ---------------------------------------------------------------------------
// Transport config helpers
// ---------------------------------------------------------------------------

/// Build a `quinn::ServerConfig` with datagrams enabled (64 KiB receive
/// buffer).  Used by [`QuicMultiplexedChannelListener::bind`].
pub fn mux_server_config() -> Result<quinn::ServerConfig> {
    let mut cfg = default_server_config()?;
    let mut transport = quinn::TransportConfig::default();
    // Disable PMTUD: loopback MTU is fixed; MTUD asserts under netem
    // duplicate/corrupt injection (quinn-proto mtud.rs:88).
    transport.mtu_discovery_config(None);
    transport.datagram_receive_buffer_size(Some(64 * 1024));
    cfg.transport_config(Arc::new(transport));
    Ok(cfg)
}

/// Build a skip-verify `quinn::ClientConfig` with datagrams enabled.
/// Used by [`QuicMultiplexedChannel::connect`].
pub fn mux_insecure_client_config() -> quinn::ClientConfig {
    let mut cfg = insecure_client_config();
    let mut transport = quinn::TransportConfig::default();
    // Disable PMTUD: same reason as mux_server_config.
    transport.mtu_discovery_config(None);
    transport.datagram_receive_buffer_size(Some(64 * 1024));
    cfg.transport_config(Arc::new(transport));
    cfg
}

// ---------------------------------------------------------------------------
// QuicSubChannel  (one QUIC stream, implements Channel)
// ---------------------------------------------------------------------------

/// A [`Channel`] backed by a single QUIC bidirectional stream.
///
/// Wire framing: `[payload_len: u32 LE][payload bytes]`, identical to
/// [`TcpChannel`](super::channel::TcpChannel).
///
/// All four streams of a [`QuicMultiplexedChannel`] are `QuicSubChannel`
/// instances that share the same Tokio runtime.
pub(super) struct QuicSubChannel {
    pub(super) send: Arc<tokio::sync::Mutex<SendStream>>,
    recv: Arc<tokio::sync::Mutex<RecvStream>>,
    runtime: Arc<Runtime>,
    pub(super) open: AtomicBool,
}

impl QuicSubChannel {
    fn new(send: SendStream, recv: RecvStream, runtime: Arc<Runtime>) -> Self {
        Self {
            send: Arc::new(tokio::sync::Mutex::new(send)),
            recv: Arc::new(tokio::sync::Mutex::new(recv)),
            runtime,
            open: AtomicBool::new(true),
        }
    }
}

impl Channel for QuicSubChannel {
    fn send(&self, data: &[u8]) -> Result<()> {
        if !self.is_open() {
            return Err(RepError::ChannelClosed(
                "QuicSubChannel is closed".into(),
            ));
        }
        let len_prefix = (data.len() as u32).to_le_bytes();
        let payload = data.to_vec();
        // Rust 2024 edition: async block captures self.send by field (not all of self),
        // so borrowing self.runtime for block_on and self.send inside the future is fine.
        self.runtime.block_on(async {
            let mut stream = self.send.lock().await;
            stream
                .write_all(&len_prefix)
                .await
                .map_err(|e| RepError::NetworkError(e.to_string()))?;
            stream
                .write_all(&payload)
                .await
                .map_err(|e| RepError::NetworkError(e.to_string()))
        })
    }

    fn receive(&self, timeout: Duration) -> Result<Option<Vec<u8>>> {
        if !self.is_open() {
            return Err(RepError::ChannelClosed(
                "QuicSubChannel is closed".into(),
            ));
        }
        self.runtime.block_on(async {
            let mut stream = self.recv.lock().await;

            let mut len_buf = [0u8; 4];
            match tokio::time::timeout(timeout, stream.read_exact(&mut len_buf))
                .await
            {
                Err(_elapsed) => return Ok(None),
                Ok(Ok(_)) => {}
                Ok(Err(ReadExactError::FinishedEarly(_))) => {
                    return Err(RepError::ChannelClosed(
                        "QUIC stream closed by peer".into(),
                    ));
                }
                Ok(Err(ReadExactError::ReadError(e))) => {
                    return Err(RepError::NetworkError(e.to_string()));
                }
            }

            let payload_len = u32::from_le_bytes(len_buf) as usize;
            if payload_len > crate::net::channel::MAX_FRAME_PAYLOAD {
                return Err(RepError::ProtocolError(format!(
                    "frame payload too large: {} > {}",
                    payload_len,
                    crate::net::channel::MAX_FRAME_PAYLOAD
                )));
            }
            let mut payload = vec![0u8; payload_len];
            stream.read_exact(&mut payload).await.map_err(|e| match e {
                ReadExactError::FinishedEarly(_) => RepError::ChannelClosed(
                    "QUIC stream closed mid-payload".into(),
                ),
                ReadExactError::ReadError(re) => {
                    RepError::NetworkError(re.to_string())
                }
            })?;
            Ok(Some(payload))
        })
    }

    fn close(&self) -> Result<()> {
        if !self.open.swap(false, Ordering::SeqCst) {
            return Ok(());
        }
        self.runtime.block_on(async {
            let mut stream = self.send.lock().await;
            let _ = stream.finish();
            tokio::time::sleep(Duration::from_millis(50)).await;
        });
        Ok(())
    }

    fn is_open(&self) -> bool {
        self.open.load(Ordering::SeqCst)
    }
}

// ---------------------------------------------------------------------------
// ReplicationChannel trait
// ---------------------------------------------------------------------------

/// Stream-typed channel interface for Noxu replication over QUIC.
///
/// Provides per-concern stream accessors and CBVLSN datagram support.
/// Each stream operates independently under QUIC flow control: log-shipping
/// back-pressure on [`log_channel`] cannot delay heartbeats on
/// [`heartbeat_channel`].
///
/// [`log_channel`]: ReplicationChannel::log_channel
/// [`heartbeat_channel`]: ReplicationChannel::heartbeat_channel
pub trait ReplicationChannel: Send + Sync {
    /// Bidirectional stream for heartbeats and elections (stream 0).
    fn heartbeat_channel(&self) -> &dyn Channel;

    /// Stream for log shipping, master → replica (stream 1).
    fn log_channel(&self) -> &dyn Channel;

    /// Stream for ack / commit feedback, replica → master (stream 2).
    fn ack_channel(&self) -> &dyn Channel;

    /// Stream for network restore file transfer (stream 3).
    fn restore_channel(&self) -> &dyn Channel;

    /// Broadcast a CBVLSN value as an unreliable 8-byte datagram.
    ///
    /// Datagrams are fresh-only: a lost datagram is superseded by the next
    /// broadcast in ~10 ms, so reliability is unnecessary.  This is a
    /// non-blocking call; the QUIC stack enqueues the datagram immediately.
    fn send_vlsn_datagram(&self, vlsn: i64) -> Result<()>;

    /// Receive a CBVLSN datagram, blocking until one arrives or `timeout`
    /// expires.
    ///
    /// Returns `Ok(None)` on timeout.
    fn recv_vlsn_datagram(&self, timeout: Duration) -> Result<Option<i64>>;
}

// ---------------------------------------------------------------------------
// ReconnectToken
// ---------------------------------------------------------------------------

/// Token produced by [`QuicMultiplexedChannel::into_reconnect_token`] that
/// bundles the QUIC `Endpoint` and its Tokio `Runtime` for a subsequent
/// 0-RTT reconnect.
///
/// The `Runtime` **must** be kept alive alongside the `Endpoint`: Quinn's
/// endpoint background task runs on the runtime that created the endpoint, so
/// dropping the runtime invalidates the endpoint with "endpoint stopping".
pub struct ReconnectToken {
    /// The QUIC endpoint with cached TLS session tickets.
    pub endpoint: Endpoint,
    /// The Tokio runtime driving the endpoint's UDP socket background task.
    pub runtime: Arc<Runtime>,
}

// ---------------------------------------------------------------------------
// QuicMultiplexedChannel
// ---------------------------------------------------------------------------

/// A QUIC connection multiplexed into four independent per-concern streams
/// plus unreliable datagrams for CBVLSN broadcasts.
///
/// Obtain instances via:
/// - [`QuicMultiplexedChannel::connect`] — client side, insecure TLS
/// - [`QuicMultiplexedChannelListener::accept`] — server side
pub struct QuicMultiplexedChannel {
    /// Keep the client endpoint alive (None for server-accepted channels).
    endpoint: Option<Endpoint>,
    /// Named connection handle so we can call `send_datagram` / `read_datagram`.
    connection: Connection,
    heartbeat: QuicSubChannel,
    log: QuicSubChannel,
    ack: QuicSubChannel,
    restore: QuicSubChannel,
    runtime: Arc<Runtime>,
    open: AtomicBool,
}

impl QuicMultiplexedChannel {
    fn build_runtime() -> Result<Arc<Runtime>> {
        tokio::runtime::Builder::new_multi_thread()
            .worker_threads(2)
            .enable_all()
            .build()
            .map(Arc::new)
            .map_err(|e| RepError::NetworkError(format!("tokio: {e}")))
    }

    /// Connect to a multiplexed QUIC endpoint using insecure (skip-verify)
    /// TLS.  `server_name` must match the server's SNI (use `"localhost"` for
    /// the self-signed cert from [`mux_server_config`]).
    pub fn connect(addr: SocketAddr, server_name: &str) -> Result<Self> {
        let runtime = Self::build_runtime()?;
        Self::connect_inner(
            addr,
            server_name,
            mux_insecure_client_config(),
            runtime,
            None,
        )
    }

    /// Connect using a caller-supplied `ClientConfig`.
    pub fn connect_with_config(
        addr: SocketAddr,
        server_name: &str,
        client_cfg: quinn::ClientConfig,
    ) -> Result<Self> {
        let runtime = Self::build_runtime()?;
        Self::connect_inner(addr, server_name, client_cfg, runtime, None)
    }

    /// Connect by hostname (or IP string) and port with DNS resolution.
    ///
    /// Happy Eyeballs: IPv6 addresses are tried before IPv4. The first address
    /// that completes the QUIC handshake wins.
    pub fn connect_host(
        host: &str,
        port: u16,
        server_name: &str,
    ) -> Result<Self> {
        let addrs: Vec<SocketAddr> = (host, port)
            .to_socket_addrs()
            .map_err(|e| {
                RepError::NetworkError(format!(
                    "DNS resolution failed for {host}:{port}: {e}"
                ))
            })?
            .collect();

        if addrs.is_empty() {
            return Err(RepError::NetworkError(format!(
                "no addresses resolved for {host}:{port}"
            )));
        }

        // Happy Eyeballs: prefer IPv6.
        let mut sorted = addrs;
        sorted.sort_by_key(|a| if a.is_ipv6() { 0u8 } else { 1u8 });

        let mut last_err = None;
        for addr in &sorted {
            match Self::connect(*addr, server_name) {
                Ok(ch) => return Ok(ch),
                Err(e) => last_err = Some(e),
            }
        }
        Err(last_err.unwrap_or_else(|| {
            RepError::NetworkError(format!(
                "could not connect to {host}:{port}"
            ))
        }))
    }

    /// Reconnect using a [`ReconnectToken`] produced by
    /// [`into_reconnect_token`].
    ///
    /// The token's `Runtime` is reused so that the endpoint's UDP background
    /// task remains alive, and the endpoint's cached TLS session ticket enables
    /// a 0-RTT / early-data handshake.
    ///
    /// [`into_reconnect_token`]: QuicMultiplexedChannel::into_reconnect_token
    pub fn connect_with_token(
        token: ReconnectToken,
        addr: SocketAddr,
        server_name: &str,
    ) -> Result<Self> {
        Self::connect_inner(
            addr,
            server_name,
            mux_insecure_client_config(),
            token.runtime,
            Some(token.endpoint),
        )
    }

    /// Reconnect reusing an existing `Endpoint`.
    ///
    /// Because the `Endpoint` retains TLS session tickets from the previous
    /// connection, Quinn will use 0-RTT / early data when the server's session
    /// ticket has not yet expired — cutting reconnect latency to ~1 RTT.
    ///
    /// Obtain the endpoint from a prior channel with [`take_endpoint`].
    ///
    /// [`take_endpoint`]: QuicMultiplexedChannel::take_endpoint
    pub fn connect_with_endpoint(
        endpoint: Endpoint,
        addr: SocketAddr,
        server_name: &str,
    ) -> Result<Self> {
        let runtime = Self::build_runtime()?;
        Self::connect_inner(
            addr,
            server_name,
            mux_insecure_client_config(),
            runtime,
            Some(endpoint),
        )
    }

    fn connect_inner(
        addr: SocketAddr,
        server_name: &str,
        client_cfg: quinn::ClientConfig,
        runtime: Arc<Runtime>,
        existing_endpoint: Option<Endpoint>,
    ) -> Result<Self> {
        let server_name = server_name.to_string();

        // Block on all async QUIC setup; returns the endpoint, connection, and
        // a HashMap of (SendStream, RecvStream) keyed by stream type byte.
        let (endpoint, conn, mut stream_map): (
            Endpoint,
            Connection,
            HashMap<u8, (SendStream, RecvStream)>,
        ) = runtime.block_on(async move {
            let mut endpoint = match existing_endpoint {
                Some(ep) => ep,
                None => Endpoint::client(
                    "0.0.0.0:0".parse().expect("valid bind addr"),
                )
                .map_err(|e| RepError::NetworkError(e.to_string()))?,
            };
            endpoint.set_default_client_config(client_cfg);
            let conn = endpoint
                .connect(addr, &server_name)
                .map_err(|e| RepError::NetworkError(e.to_string()))?
                .await
                .map_err(|e| RepError::NetworkError(e.to_string()))?;

            // Open streams in canonical order: heartbeat, log, ack, restore.
            let stream_types =
                [STREAM_HEARTBEAT, STREAM_LOG, STREAM_ACK, STREAM_RESTORE];
            let mut map: HashMap<u8, (SendStream, RecvStream)> =
                HashMap::with_capacity(NUM_STREAMS);

            for stream_type in stream_types {
                let (mut send, recv) = conn
                    .open_bi()
                    .await
                    .map_err(|e| RepError::NetworkError(e.to_string()))?;
                // 5-byte handshake: magic (4) + stream type (1).
                // Sending data immediately forces a QUIC STREAM frame, making
                // the stream visible to the server's accept_bi().
                let mut handshake = [0u8; 5];
                handshake[..4].copy_from_slice(MULTIPLEXED_MAGIC);
                handshake[4] = stream_type;
                send.write_all(&handshake)
                    .await
                    .map_err(|e| RepError::NetworkError(e.to_string()))?;
                map.insert(stream_type, (send, recv));
            }

            Ok::<_, RepError>((endpoint, conn, map))
        })?;

        let (hb_s, hb_r) =
            stream_map.remove(&STREAM_HEARTBEAT).ok_or_else(|| {
                RepError::NetworkError("missing heartbeat stream".into())
            })?;
        let (log_s, log_r) =
            stream_map.remove(&STREAM_LOG).ok_or_else(|| {
                RepError::NetworkError("missing log stream".into())
            })?;
        let (ack_s, ack_r) =
            stream_map.remove(&STREAM_ACK).ok_or_else(|| {
                RepError::NetworkError("missing ack stream".into())
            })?;
        let (rst_s, rst_r) =
            stream_map.remove(&STREAM_RESTORE).ok_or_else(|| {
                RepError::NetworkError("missing restore stream".into())
            })?;

        let (hb_rt, log_rt, ack_rt, rst_rt) = (
            Arc::clone(&runtime),
            Arc::clone(&runtime),
            Arc::clone(&runtime),
            Arc::clone(&runtime),
        );

        Ok(Self {
            endpoint: Some(endpoint),
            connection: conn,
            heartbeat: QuicSubChannel::new(hb_s, hb_r, hb_rt),
            log: QuicSubChannel::new(log_s, log_r, log_rt),
            ack: QuicSubChannel::new(ack_s, ack_r, ack_rt),
            restore: QuicSubChannel::new(rst_s, rst_r, rst_rt),
            runtime,
            open: AtomicBool::new(true),
        })
    }

    /// Consume this channel and return a [`ReconnectToken`] for 0-RTT reconnect.
    ///
    /// The token bundles the QUIC `Endpoint` **and** its Tokio `Runtime`.
    /// Both must stay alive together: the runtime drives the endpoint's UDP
    /// socket background task, and dropping it would invalidate the endpoint
    /// with "endpoint stopping".
    ///
    /// Pass the token to [`connect_with_token`] to open a new multiplexed
    /// connection to the new master, reusing the cached TLS session ticket for
    /// 0-RTT / early-data.
    ///
    /// Returns `None` for server-accepted channels (the listener owns their
    /// endpoint).
    ///
    /// [`connect_with_token`]: QuicMultiplexedChannel::connect_with_token
    pub fn into_reconnect_token(mut self) -> Option<ReconnectToken> {
        let endpoint = self.endpoint.take()?;
        let runtime = Arc::clone(&self.runtime);
        Some(ReconnectToken { endpoint, runtime })
    }

    /// Returns `true` if the channel has not been closed.
    pub fn is_open(&self) -> bool {
        self.open.load(Ordering::SeqCst)
    }

    /// Close all four streams simultaneously.
    ///
    /// Sends a QUIC stream FIN on every stream and waits 50 ms for the
    /// background task to flush any buffered packets before the connection
    /// reference is dropped.
    pub fn close_all(&self) -> Result<()> {
        if !self.open.swap(false, Ordering::SeqCst) {
            return Ok(());
        }
        // Mark every sub-channel as closed so in-flight operations fail fast.
        self.heartbeat.open.store(false, Ordering::SeqCst);
        self.log.open.store(false, Ordering::SeqCst);
        self.ack.open.store(false, Ordering::SeqCst);
        self.restore.open.store(false, Ordering::SeqCst);

        // Rust 2024: async block captures each sub-channel's send field precisely.
        self.runtime.block_on(async {
            let _ = self.heartbeat.send.lock().await.finish();
            let _ = self.log.send.lock().await.finish();
            let _ = self.ack.send.lock().await.finish();
            let _ = self.restore.send.lock().await.finish();
            tokio::time::sleep(Duration::from_millis(50)).await;
        });
        Ok(())
    }
}

impl ReplicationChannel for QuicMultiplexedChannel {
    fn heartbeat_channel(&self) -> &dyn Channel {
        &self.heartbeat
    }

    fn log_channel(&self) -> &dyn Channel {
        &self.log
    }

    fn ack_channel(&self) -> &dyn Channel {
        &self.ack
    }

    fn restore_channel(&self) -> &dyn Channel {
        &self.restore
    }

    /// Enqueue a CBVLSN datagram on the connection.  Non-blocking; the QUIC
    /// stack sends the 8-byte datagram as soon as the congestion window allows.
    fn send_vlsn_datagram(&self, vlsn: i64) -> Result<()> {
        self.connection
            .send_datagram(Bytes::from(vlsn.to_le_bytes().to_vec()))
            .map_err(|e| RepError::NetworkError(format!("datagram send: {e}")))
    }

    fn recv_vlsn_datagram(&self, timeout: Duration) -> Result<Option<i64>> {
        self.runtime.block_on(async {
            match tokio::time::timeout(timeout, self.connection.read_datagram())
                .await
            {
                Err(_elapsed) => Ok(None),
                Ok(Ok(data)) => {
                    if data.len() != 8 {
                        return Err(RepError::NetworkError(format!(
                            "VLSN datagram: expected 8 bytes, got {}",
                            data.len()
                        )));
                    }
                    let bytes: [u8; 8] =
                        data[..8].try_into().expect("length checked above");
                    Ok(Some(i64::from_le_bytes(bytes)))
                }
                Ok(Err(e)) => {
                    Err(RepError::NetworkError(format!("datagram recv: {e}")))
                }
            }
        })
    }
}

impl Drop for QuicMultiplexedChannel {
    fn drop(&mut self) {
        if self.is_open() {
            let _ = self.close_all();
        }
    }
}

// ---------------------------------------------------------------------------
// QuicMultiplexedChannelListener
// ---------------------------------------------------------------------------

/// Accepts incoming multiplexed QUIC connections and returns
/// [`QuicMultiplexedChannel`] instances.
///
/// The server endpoint is configured with datagrams enabled so that CBVLSN
/// broadcasts sent by clients are not silently discarded.
pub struct QuicMultiplexedChannelListener {
    endpoint: Endpoint,
    runtime: Arc<Runtime>,
}

impl QuicMultiplexedChannelListener {
    /// Bind to `addr` using a self-signed certificate with datagrams enabled.
    pub fn bind(addr: SocketAddr) -> Result<Self> {
        let runtime = Arc::new(
            tokio::runtime::Builder::new_multi_thread()
                .worker_threads(2)
                .enable_all()
                .build()
                .map_err(|e| RepError::NetworkError(format!("tokio: {e}")))?,
        );
        let server_cfg = mux_server_config()?;
        let endpoint = runtime.block_on(async move {
            Endpoint::server(server_cfg, addr)
                .map_err(|e| RepError::NetworkError(e.to_string()))
        })?;
        Ok(Self { endpoint, runtime })
    }

    /// Bind using a caller-supplied `ServerConfig`.
    pub fn with_server_config(
        addr: SocketAddr,
        server_cfg: quinn::ServerConfig,
    ) -> Result<Self> {
        let runtime = Arc::new(
            tokio::runtime::Builder::new_multi_thread()
                .worker_threads(2)
                .enable_all()
                .build()
                .map_err(|e| RepError::NetworkError(format!("tokio: {e}")))?,
        );
        let endpoint = runtime.block_on(async move {
            Endpoint::server(server_cfg, addr)
                .map_err(|e| RepError::NetworkError(e.to_string()))
        })?;
        Ok(Self { endpoint, runtime })
    }

    /// Return the local address the listener is bound to.
    pub fn local_addr(&self) -> Result<SocketAddr> {
        self.endpoint
            .local_addr()
            .map_err(|e| RepError::NetworkError(e.to_string()))
    }

    /// Accept the next incoming multiplexed QUIC connection.
    ///
    /// Waits for the client to open four bidirectional streams and validates
    /// the 5-byte handshake on each stream before returning.
    pub fn accept(&self) -> Result<QuicMultiplexedChannel> {
        // Rust 2024: borrow self.endpoint and self.runtime as separate fields;
        // the runtime Arc is cloned once inside the future (not twice outside).
        self.runtime.block_on(async {
            let incoming = self.endpoint.accept().await.ok_or_else(|| {
                RepError::NetworkError("QUIC endpoint closed".into())
            })?;
            let conn = incoming
                .await
                .map_err(|e| RepError::NetworkError(e.to_string()))?;

            // Accept NUM_STREAMS streams; the client opens them in type order
            // but we key by the type byte from the handshake, so any ordering
            // is accepted safely.
            let mut stream_map: HashMap<u8, (SendStream, RecvStream)> =
                HashMap::with_capacity(NUM_STREAMS);

            for _ in 0..NUM_STREAMS {
                let (send, mut recv) = conn
                    .accept_bi()
                    .await
                    .map_err(|e| RepError::NetworkError(e.to_string()))?;

                let mut handshake = [0u8; 5];
                recv.read_exact(&mut handshake).await.map_err(|e| {
                    RepError::NetworkError(format!("mux handshake: {e}"))
                })?;

                if &handshake[..4] != MULTIPLEXED_MAGIC {
                    return Err(RepError::NetworkError(format!(
                        "invalid mux magic: {:02x?}",
                        &handshake[..4]
                    )));
                }
                let stream_type = handshake[4];
                if stream_map.contains_key(&stream_type) {
                    return Err(RepError::NetworkError(format!(
                        "duplicate stream type {stream_type}"
                    )));
                }
                stream_map.insert(stream_type, (send, recv));
            }

            let (hb_s, hb_r) =
                stream_map.remove(&STREAM_HEARTBEAT).ok_or_else(|| {
                    RepError::NetworkError("missing heartbeat stream".into())
                })?;
            let (log_s, log_r) =
                stream_map.remove(&STREAM_LOG).ok_or_else(|| {
                    RepError::NetworkError("missing log stream".into())
                })?;
            let (ack_s, ack_r) =
                stream_map.remove(&STREAM_ACK).ok_or_else(|| {
                    RepError::NetworkError("missing ack stream".into())
                })?;
            let (rst_s, rst_r) =
                stream_map.remove(&STREAM_RESTORE).ok_or_else(|| {
                    RepError::NetworkError("missing restore stream".into())
                })?;

            // One clone of the runtime Arc, distributed to each sub-channel and
            // to the channel itself (five Arc::clone total, down from six before).
            let rt = Arc::clone(&self.runtime);
            Ok(QuicMultiplexedChannel {
                endpoint: None, // server side: listener owns the endpoint
                connection: conn,
                heartbeat: QuicSubChannel::new(hb_s, hb_r, Arc::clone(&rt)),
                log: QuicSubChannel::new(log_s, log_r, Arc::clone(&rt)),
                ack: QuicSubChannel::new(ack_s, ack_r, Arc::clone(&rt)),
                restore: QuicSubChannel::new(rst_s, rst_r, Arc::clone(&rt)),
                runtime: rt,
                open: AtomicBool::new(true),
            })
        })
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    fn loopback_mux_listener() -> QuicMultiplexedChannelListener {
        QuicMultiplexedChannelListener::bind("127.0.0.1:0".parse().unwrap())
            .expect("bind mux QUIC listener")
    }

    // -----------------------------------------------------------------------
    // Basic connectivity
    // -----------------------------------------------------------------------

    #[test]
    fn test_mux_connect_and_close() {
        let listener = loopback_mux_listener();
        let addr = listener.local_addr().unwrap();

        let server_thread = std::thread::spawn(move || {
            let ch = listener.accept().unwrap();
            assert!(ch.is_open());
            // Server drops naturally, which calls close_all().
        });

        let client =
            QuicMultiplexedChannel::connect(addr, "localhost").unwrap();
        assert!(client.is_open());
        client.close_all().unwrap();
        assert!(!client.is_open());

        server_thread.join().unwrap();
    }

    // -----------------------------------------------------------------------
    // Per-stream send / receive
    // -----------------------------------------------------------------------

    #[test]
    fn test_mux_heartbeat_send_receive() {
        let listener = loopback_mux_listener();
        let addr = listener.local_addr().unwrap();

        let server_thread = std::thread::spawn(move || {
            let ch = listener.accept().unwrap();
            let msg =
                ch.heartbeat_channel().receive(Duration::from_secs(5)).unwrap();
            assert_eq!(msg, Some(b"hb-ping".to_vec()));
            ch.heartbeat_channel().send(b"hb-pong").unwrap();
        });

        let client =
            QuicMultiplexedChannel::connect(addr, "localhost").unwrap();
        client.heartbeat_channel().send(b"hb-ping").unwrap();
        let reply =
            client.heartbeat_channel().receive(Duration::from_secs(5)).unwrap();
        assert_eq!(reply, Some(b"hb-pong".to_vec()));

        server_thread.join().unwrap();
    }

    #[test]
    fn test_mux_log_send_receive() {
        let listener = loopback_mux_listener();
        let addr = listener.local_addr().unwrap();

        let server_thread = std::thread::spawn(move || {
            let ch = listener.accept().unwrap();
            let msg = ch.log_channel().receive(Duration::from_secs(5)).unwrap();
            assert_eq!(msg, Some(b"log-entry".to_vec()));
        });

        let client =
            QuicMultiplexedChannel::connect(addr, "localhost").unwrap();
        client.log_channel().send(b"log-entry").unwrap();

        server_thread.join().unwrap();
    }

    #[test]
    fn test_mux_ack_send_receive() {
        let listener = loopback_mux_listener();
        let addr = listener.local_addr().unwrap();

        let server_thread = std::thread::spawn(move || {
            let ch = listener.accept().unwrap();
            let msg = ch.ack_channel().receive(Duration::from_secs(5)).unwrap();
            assert_eq!(msg, Some(b"ack-42".to_vec()));
        });

        let client =
            QuicMultiplexedChannel::connect(addr, "localhost").unwrap();
        client.ack_channel().send(b"ack-42").unwrap();

        server_thread.join().unwrap();
    }

    #[test]
    fn test_mux_restore_send_receive() {
        let listener = loopback_mux_listener();
        let addr = listener.local_addr().unwrap();

        let server_thread = std::thread::spawn(move || {
            let ch = listener.accept().unwrap();
            let msg =
                ch.restore_channel().receive(Duration::from_secs(5)).unwrap();
            assert_eq!(msg, Some(b"restore-block".to_vec()));
        });

        let client =
            QuicMultiplexedChannel::connect(addr, "localhost").unwrap();
        client.restore_channel().send(b"restore-block").unwrap();

        server_thread.join().unwrap();
    }

    // -----------------------------------------------------------------------
    // Stream independence
    // -----------------------------------------------------------------------

    #[test]
    fn test_mux_all_streams_independent() {
        // Each of the four streams carries a distinct message.
        // None blocks any other — the QUIC stack routes them independently.
        let listener = loopback_mux_listener();
        let addr = listener.local_addr().unwrap();

        let server_thread = std::thread::spawn(move || {
            let ch = listener.accept().unwrap();
            let hb =
                ch.heartbeat_channel().receive(Duration::from_secs(5)).unwrap();
            let log = ch.log_channel().receive(Duration::from_secs(5)).unwrap();
            let ack = ch.ack_channel().receive(Duration::from_secs(5)).unwrap();
            let rst =
                ch.restore_channel().receive(Duration::from_secs(5)).unwrap();
            (hb, log, ack, rst)
        });

        let client =
            QuicMultiplexedChannel::connect(addr, "localhost").unwrap();
        client.heartbeat_channel().send(b"heartbeat").unwrap();
        client.log_channel().send(b"log").unwrap();
        client.ack_channel().send(b"ack").unwrap();
        client.restore_channel().send(b"restore").unwrap();

        let (hb, log, ack, rst) = server_thread.join().unwrap();
        assert_eq!(hb, Some(b"heartbeat".to_vec()));
        assert_eq!(log, Some(b"log".to_vec()));
        assert_eq!(ack, Some(b"ack".to_vec()));
        assert_eq!(rst, Some(b"restore".to_vec()));
    }

    #[test]
    fn test_mux_streams_dont_interfere() {
        // Send a large burst on the log stream; heartbeats on stream 0 must
        // still flow independently (QUIC per-stream flow control).
        let listener = loopback_mux_listener();
        let addr = listener.local_addr().unwrap();
        let large_payload: Vec<u8> = vec![0xABu8; 32 * 1024]; // 32 KiB

        let server_thread = std::thread::spawn(move || {
            let ch = listener.accept().unwrap();
            // Drain all log messages.
            for _ in 0..10 {
                ch.log_channel().receive(Duration::from_secs(5)).unwrap();
            }
            // Confirm heartbeat arrives promptly.
            let hb =
                ch.heartbeat_channel().receive(Duration::from_secs(5)).unwrap();
            assert_eq!(hb, Some(b"hb".to_vec()));
        });

        let client =
            QuicMultiplexedChannel::connect(addr, "localhost").unwrap();
        // Send 10 large log messages.
        for _ in 0..10 {
            client.log_channel().send(&large_payload).unwrap();
        }
        // Heartbeat sent after the log burst — must arrive independently.
        client.heartbeat_channel().send(b"hb").unwrap();

        server_thread.join().unwrap();
    }

    // -----------------------------------------------------------------------
    // CBVLSN datagrams
    // -----------------------------------------------------------------------

    #[test]
    fn test_mux_vlsn_datagram_roundtrip() {
        let listener = loopback_mux_listener();
        let addr = listener.local_addr().unwrap();

        let server_thread = std::thread::spawn(move || {
            let ch = listener.accept().unwrap();
            let vlsn = ch.recv_vlsn_datagram(Duration::from_secs(5)).unwrap();
            assert_eq!(vlsn, Some(42_i64));
        });

        let client =
            QuicMultiplexedChannel::connect(addr, "localhost").unwrap();
        client.send_vlsn_datagram(42).unwrap();

        server_thread.join().unwrap();
    }

    #[test]
    fn test_mux_vlsn_datagram_timeout() {
        let listener = loopback_mux_listener();
        let addr = listener.local_addr().unwrap();

        // Server accepts but never sends a datagram.
        let server_thread = std::thread::spawn(move || {
            listener.accept().unwrap()
            // channel held alive for the duration of the test
        });

        let client =
            QuicMultiplexedChannel::connect(addr, "localhost").unwrap();
        let result =
            client.recv_vlsn_datagram(Duration::from_millis(300)).unwrap();
        assert_eq!(result, None, "expected timeout → None");

        drop(server_thread.join().unwrap());
    }

    // -----------------------------------------------------------------------
    // Trait object usage
    // -----------------------------------------------------------------------

    #[test]
    fn test_mux_replication_channel_trait_object() {
        let listener = loopback_mux_listener();
        let addr = listener.local_addr().unwrap();

        let server_thread = std::thread::spawn(move || {
            let ch: Box<dyn ReplicationChannel> =
                Box::new(listener.accept().unwrap());
            let msg =
                ch.heartbeat_channel().receive(Duration::from_secs(5)).unwrap();
            assert_eq!(msg, Some(b"trait test".to_vec()));
        });

        let client: Box<dyn ReplicationChannel> = Box::new(
            QuicMultiplexedChannel::connect(addr, "localhost").unwrap(),
        );
        client.heartbeat_channel().send(b"trait test").unwrap();

        server_thread.join().unwrap();
    }

    // -----------------------------------------------------------------------
    // 0-RTT reconnect path (verifies endpoint is extractable and reusable)
    // -----------------------------------------------------------------------

    #[test]
    fn test_mux_reconnect_with_endpoint() {
        let listener = loopback_mux_listener();
        let addr = listener.local_addr().unwrap();

        // Server: accept two connections in sequence.
        let server_thread = std::thread::spawn(move || {
            let ch = listener.accept().unwrap();
            ch.heartbeat_channel().receive(Duration::from_secs(5)).unwrap();
            // Second connection on the same listener.
            let ch2 = listener.accept().unwrap();
            ch2.heartbeat_channel().receive(Duration::from_secs(5)).unwrap();
        });

        let first = QuicMultiplexedChannel::connect(addr, "localhost").unwrap();
        first.heartbeat_channel().send(b"first-conn").unwrap();

        // Consume `first` into a ReconnectToken — keeps the Runtime alive so
        // the endpoint's UDP background task is not cancelled on drop.
        let token = first.into_reconnect_token().unwrap();

        // Second connection reusing the endpoint + runtime — Quinn will use the
        // cached TLS session ticket for 0-RTT when the server supports it.
        let second = QuicMultiplexedChannel::connect_with_token(
            token,
            addr,
            "localhost",
        )
        .unwrap();
        second.heartbeat_channel().send(b"second-conn").unwrap();

        server_thread.join().unwrap();
    }

    // -----------------------------------------------------------------------
    // LOG-2 hardening
    // -----------------------------------------------------------------------

    /// Each multiplexed sub-channel must enforce the same payload bound as
    /// the single-stream `QuicChannel`.  We exercise the heartbeat
    /// sub-channel; the same `receive` implementation is shared by all
    /// four streams.
    #[test]
    fn test_quic_mux_rejects_oversize_frame() {
        let listener = loopback_mux_listener();
        let addr = listener.local_addr().unwrap();

        let server_thread = std::thread::spawn(move || {
            let ch = listener.accept().unwrap();
            let oversized =
                vec![0u8; crate::net::channel::MAX_FRAME_PAYLOAD + 1];
            // Send through the heartbeat stream.  The send may fail when
            // the client tears down the connection after rejecting the
            // header — that's expected.
            let _ = ch.heartbeat_channel().send(&oversized);
        });

        let client =
            QuicMultiplexedChannel::connect(addr, "localhost").unwrap();
        let result =
            client.heartbeat_channel().receive(Duration::from_secs(10));
        let _ = client.heartbeat_channel().close();
        let err = result.expect_err("oversize QUIC mux frame must be rejected");
        match err {
            RepError::ProtocolError(msg) => {
                assert!(
                    msg.contains("frame payload too large"),
                    "unexpected protocol-error message: {}",
                    msg
                );
            }
            other => panic!("expected ProtocolError, got {:?}", other),
        }
        let _ = server_thread.join();
    }
}