Skip to main content

byteflow/transport/
mod.rs

1//! Reference host I/O for remote Atomic Hop frames — **not** a cluster protocol.
2//!
3//! Byteflow already defines [`encode_frame`] / [`decode_frame`] and
4//! [`Runtime::deliver_frame`]. This module adds a copy-friendly **length-prefixed
5//! wire envelope** and small TCP/UDP helpers with **bounded outbound queues**
6//! so a slow socket applies backpressure to [`DistributionBridge`] drains.
7//!
8//! The embedder still owns routing (`OutboundHop::node`), TLS, auth, and
9//! retries. See [`crate::docs::remote_transport`].
10
11pub mod router;
12
13use std::io::{Read, Write};
14use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream, UdpSocket};
15use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
16use std::sync::mpsc::{sync_channel, SyncSender};
17use std::sync::Arc;
18use std::thread::{self, JoinHandle};
19use std::time::{Duration, Instant};
20
21use crate::encode_frame;
22use crate::scheduler::{DistributionBridge, RemoteFrameError};
23
24fn transport_info(msg: impl std::fmt::Display) {
25    crate::log::info(format!("transport: {msg}"));
26}
27
28fn transport_debug(msg: impl std::fmt::Display) {
29    crate::log::debug(format!("transport: {msg}"));
30}
31
32/// Default cap on one length-prefixed payload (typical mailbox byte budget).
33pub const DEFAULT_MAX_WIRE_BYTES: u32 = 4 * 1024 * 1024;
34
35const WIRE_MAGIC: [u8; 4] = *b"BFT1";
36const WIRE_VERSION: u8 = 1;
37
38/// Why host transport refused or failed an operation.
39#[derive(Debug)]
40pub enum TransportError {
41    Io(std::io::Error),
42    Truncated,
43    BadMagic,
44    BadVersion,
45    FrameTooLarge {
46        len: u32,
47        max: u32,
48    },
49    TrailingData,
50    InvalidConfig(&'static str),
51    /// [`NodeRouter::resolve`] has no peer for this host-defined node id.
52    UnknownNode {
53        node: u64,
54    },
55    Deliver(RemoteFrameError),
56    ThreadJoin,
57}
58
59impl std::fmt::Display for TransportError {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        match self {
62            Self::Io(e) => write!(f, "transport io: {e}"),
63            Self::Truncated => f.write_str("transport frame truncated"),
64            Self::BadMagic => f.write_str("transport bad magic"),
65            Self::BadVersion => f.write_str("transport bad version"),
66            Self::FrameTooLarge { len, max } => {
67                write!(f, "transport frame {len} bytes exceeds max {max}")
68            }
69            Self::TrailingData => f.write_str("transport frame trailing data"),
70            Self::InvalidConfig(msg) => write!(f, "transport config: {msg}"),
71            Self::UnknownNode { node } => write!(f, "transport unknown node id {node}"),
72            Self::Deliver(e) => write!(f, "deliver_frame: {e}"),
73            Self::ThreadJoin => f.write_str("transport thread panicked"),
74        }
75    }
76}
77
78impl std::error::Error for TransportError {
79    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
80        match self {
81            Self::Io(e) => Some(e),
82            Self::Deliver(e) => Some(e),
83            _ => None,
84        }
85    }
86}
87
88fn check_max_wire(max_wire_bytes: u32) -> Result<(), TransportError> {
89    if max_wire_bytes == 0 {
90        return Err(TransportError::InvalidConfig(
91            "max_wire_bytes must be at least 1",
92        ));
93    }
94    Ok(())
95}
96
97impl From<std::io::Error> for TransportError {
98    fn from(e: std::io::Error) -> Self {
99        Self::Io(e)
100    }
101}
102
103/// Configuration for [`spawn_tcp_outbound`].
104#[derive(Clone, Debug)]
105pub struct TcpOutboundConfig {
106    /// Bounded queue between bridge drain and the TCP writer (backpressure).
107    pub queue_capacity: usize,
108    pub max_wire_bytes: u32,
109    /// How long [`DistributionBridge::recv_timeout`] waits when the queue is empty.
110    pub bridge_poll: Duration,
111    pub connect_timeout: Duration,
112}
113
114impl Default for TcpOutboundConfig {
115    fn default() -> Self {
116        Self {
117            queue_capacity: 256,
118            max_wire_bytes: DEFAULT_MAX_WIRE_BYTES,
119            bridge_poll: Duration::from_millis(50),
120            connect_timeout: Duration::from_secs(5),
121        }
122    }
123}
124
125/// Stops [`spawn_tcp_outbound`] and joins its worker threads.
126pub struct TcpOutboundHandle {
127    stop: Arc<AtomicBool>,
128    joins: Vec<JoinHandle<()>>,
129    wire_pending: Arc<AtomicUsize>,
130}
131
132impl TcpOutboundHandle {
133    /// Frames queued for the TCP writer but not yet written.
134    pub fn wire_pending(&self) -> usize {
135        self.wire_pending.load(Ordering::Acquire)
136    }
137
138    /// Poll until [`Self::wire_pending`] is zero or `timeout` elapses.
139    pub fn wait_wire_drained(&self, timeout: Duration) -> Result<(), TransportError> {
140        let deadline = Instant::now() + timeout;
141        while self.wire_pending.load(Ordering::Acquire) > 0 {
142            if Instant::now() >= deadline {
143                return Err(TransportError::InvalidConfig("wire queue drain timed out"));
144            }
145            thread::sleep(Duration::from_millis(5));
146        }
147        Ok(())
148    }
149
150    pub fn stop(self) -> Result<(), TransportError> {
151        self.stop.store(true, Ordering::Relaxed);
152        for join in self.joins {
153            join.join().map_err(|_| TransportError::ThreadJoin)?;
154        }
155        Ok(())
156    }
157}
158
159const SESSION_DRAIN: Duration = Duration::from_secs(5);
160
161/// Drains `bridge`, encodes each [`crate::OutboundHop`], and writes length-prefixed
162/// frames to `peer`. When the outbound queue is full, the pump **blocks**, so
163/// [`DistributionBridge`] fills and bytecode `SendRemote` eventually fails closed.
164///
165/// Same as [`spawn_tcp_outbound_routed`] with [`FixedPeerRouter`] (ignores hop node id).
166pub fn spawn_tcp_outbound(
167    bridge: Arc<DistributionBridge>,
168    peer: SocketAddr,
169    config: TcpOutboundConfig,
170) -> Result<TcpOutboundHandle, TransportError> {
171    spawn_tcp_outbound_routed(bridge, Arc::new(router::FixedPeerRouter(peer)), config)
172}
173
174/// Drains `bridge`, resolves each hop's [`OutboundHop::node`] through `router`, and
175/// writes length-prefixed frames to the matching TCP peer.
176///
177/// When routing or `encode_frame` fails, the pump stops fail-closed (same as the
178/// single-peer outbound). Unknown node ids surface as [`TransportError::UnknownNode`]
179/// on the pump thread via logs; the hop is not retried automatically.
180pub fn spawn_tcp_outbound_routed(
181    bridge: Arc<DistributionBridge>,
182    router: Arc<dyn router::NodeRouter>,
183    config: TcpOutboundConfig,
184) -> Result<TcpOutboundHandle, TransportError> {
185    check_max_wire(config.max_wire_bytes)?;
186    if config.queue_capacity == 0 {
187        return Err(TransportError::InvalidConfig(
188            "queue_capacity must be at least 1",
189        ));
190    }
191    let stop = Arc::new(AtomicBool::new(false));
192    let stop_writer = Arc::clone(&stop);
193    let stop_pump = Arc::clone(&stop);
194    let (wire_tx, wire_rx) = sync_channel(config.queue_capacity);
195    let wire_pending = Arc::new(AtomicUsize::new(0));
196    let pending_pump = Arc::clone(&wire_pending);
197    let pending_writer = Arc::clone(&wire_pending);
198    let max_wire = config.max_wire_bytes;
199    let connect_timeout = config.connect_timeout;
200
201    let writer = thread::Builder::new()
202        .name("byteflow-tcp-out".into())
203        .spawn(move || {
204            let _ = run_tcp_routed_writer(
205                connect_timeout,
206                max_wire,
207                wire_rx,
208                stop_writer,
209                pending_writer,
210            );
211        })
212        .map_err(TransportError::Io)?;
213
214    let bridge_poll = config.bridge_poll;
215    let pump = thread::Builder::new()
216        .name("byteflow-bridge-pump".into())
217        .spawn(move || {
218            pump_bridge_to_routed_channel(
219                &bridge,
220                router,
221                wire_tx,
222                bridge_poll,
223                stop_pump,
224                pending_pump,
225            );
226        })
227        .map_err(TransportError::Io)?;
228
229    Ok(TcpOutboundHandle {
230        stop,
231        joins: vec![pump, writer],
232        wire_pending,
233    })
234}
235
236fn pump_bridge_to_routed_channel(
237    bridge: &DistributionBridge,
238    router: Arc<dyn router::NodeRouter>,
239    wire_tx: SyncSender<(SocketAddr, Vec<u8>)>,
240    poll: Duration,
241    stop: Arc<AtomicBool>,
242    wire_pending: Arc<AtomicUsize>,
243) {
244    while !stop.load(Ordering::Relaxed) {
245        match bridge.recv_timeout(poll) {
246            Ok(Some(hop)) => {
247                let peer = match router::resolve_hop_peer(&hop, router.as_ref()) {
248                    Ok(p) => p,
249                    Err(e) => {
250                        transport_info(format!("node resolve failed; stopping outbound pump: {e}"));
251                        break;
252                    }
253                };
254                match encode_frame(&hop) {
255                    Ok(bytes) => match wire_tx.send((peer, bytes)) {
256                        Ok(()) => {
257                            wire_pending.fetch_add(1, Ordering::Release);
258                        }
259                        Err(_) => break,
260                    },
261                    Err(e) => {
262                        transport_info(format!("encode_frame failed; stopping outbound pump: {e}"));
263                        break;
264                    }
265                }
266            }
267            Ok(None) => {}
268            Err(e) => {
269                transport_info(format!("bridge recv failed: {e}"));
270                break;
271            }
272        }
273    }
274}
275
276fn run_tcp_routed_writer(
277    connect_timeout: Duration,
278    max_wire: u32,
279    wire_rx: std::sync::mpsc::Receiver<(SocketAddr, Vec<u8>)>,
280    stop: Arc<AtomicBool>,
281    wire_pending: Arc<AtomicUsize>,
282) -> Result<(), TransportError> {
283    let mut retry_frame: Option<(SocketAddr, Vec<u8>)> = None;
284    let mut stream: Option<TcpStream> = None;
285    let mut connected_peer: Option<SocketAddr> = None;
286
287    while !stop.load(Ordering::Relaxed) {
288        let (peer, bytes) = if let Some(frame) = retry_frame.take() {
289            frame
290        } else {
291            match wire_rx.recv_timeout(Duration::from_millis(200)) {
292                Ok(item) => item,
293                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
294                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => return Ok(()),
295            }
296        };
297
298        if connected_peer != Some(peer) || stream.is_none() {
299            stream = None;
300            connected_peer = None;
301            match TcpStream::connect_timeout(&peer, connect_timeout) {
302                Ok(s) => {
303                    if s.set_nodelay(true).is_ok() {
304                        connected_peer = Some(peer);
305                        stream = Some(s);
306                    } else {
307                        retry_frame = Some((peer, bytes));
308                        thread::sleep(Duration::from_millis(100));
309                        continue;
310                    }
311                }
312                Err(e) => {
313                    transport_debug(format!("connect {peer} failed: {e}"));
314                    retry_frame = Some((peer, bytes));
315                    thread::sleep(Duration::from_millis(100));
316                    continue;
317                }
318            }
319        }
320
321        let Some(active) = stream.as_mut() else {
322            retry_frame = Some((peer, bytes));
323            continue;
324        };
325
326        if let Err(e) = write_wire_frame(active, &bytes, max_wire) {
327            transport_info(format!("write to {peer} failed: {e}"));
328            retry_frame = Some((peer, bytes));
329            stream = None;
330            connected_peer = None;
331            continue;
332        }
333        wire_pending.fetch_sub(1, Ordering::Release);
334    }
335    Ok(())
336}
337
338/// Poll until [`DistributionBridge::try_recv`] returns `None` or `timeout` elapses.
339///
340/// Use after the sending runtime has finished bytecode work so the outbound
341/// pump can encode and queue wire frames before [`TcpOutboundHandle::stop`].
342pub fn wait_bridge_drained(
343    bridge: &DistributionBridge,
344    timeout: Duration,
345) -> Result<(), TransportError> {
346    let deadline = Instant::now() + timeout;
347    loop {
348        match bridge.try_recv() {
349            Ok(None) => return Ok(()),
350            Ok(Some(_)) => {}
351            Err(_) => {
352                return Err(TransportError::InvalidConfig(
353                    "distribution bridge unavailable",
354                ));
355            }
356        }
357        if Instant::now() >= deadline {
358            return Err(TransportError::InvalidConfig("bridge drain timed out"));
359        }
360        thread::sleep(Duration::from_millis(5));
361    }
362}
363
364/// Configuration for [`spawn_tcp_inbound`].
365#[derive(Clone, Debug)]
366pub struct TcpInboundConfig {
367    pub max_wire_bytes: u32,
368    /// Concurrent TCP session threads. `0` means no limit.
369    pub max_sessions: usize,
370}
371
372impl Default for TcpInboundConfig {
373    fn default() -> Self {
374        Self {
375            max_wire_bytes: DEFAULT_MAX_WIRE_BYTES,
376            max_sessions: 64,
377        }
378    }
379}
380
381/// Accepts TCP connections and delivers each wire frame through `deliver`.
382pub struct TcpInboundHandle {
383    stop: Arc<AtomicBool>,
384    join: JoinHandle<()>,
385    active_sessions: Arc<AtomicUsize>,
386}
387
388impl TcpInboundHandle {
389    pub fn stop(self) -> Result<(), TransportError> {
390        self.stop.store(true, Ordering::Relaxed);
391        self.join.join().map_err(|_| TransportError::ThreadJoin)?;
392        let deadline = Instant::now() + SESSION_DRAIN;
393        while self.active_sessions.load(Ordering::Acquire) > 0 {
394            if Instant::now() >= deadline {
395                return Err(TransportError::InvalidConfig(
396                    "inbound sessions did not finish",
397                ));
398            }
399            thread::sleep(Duration::from_millis(10));
400        }
401        Ok(())
402    }
403}
404
405pub fn spawn_tcp_inbound<F>(
406    listener: TcpListener,
407    deliver: Arc<F>,
408    config: TcpInboundConfig,
409) -> Result<TcpInboundHandle, TransportError>
410where
411    F: Fn(&[u8]) -> Result<(), RemoteFrameError> + Send + Sync + 'static,
412{
413    check_max_wire(config.max_wire_bytes)?;
414    let stop = Arc::new(AtomicBool::new(false));
415    let stop_accept = Arc::clone(&stop);
416    let active_sessions = Arc::new(AtomicUsize::new(0));
417    let sessions_accept = Arc::clone(&active_sessions);
418    let max_wire = config.max_wire_bytes;
419    let max_sessions = config.max_sessions;
420    let join = thread::Builder::new()
421        .name("byteflow-tcp-in".into())
422        .spawn(move || {
423            accept_inbound_loop(
424                listener,
425                deliver,
426                max_wire,
427                max_sessions,
428                stop_accept,
429                sessions_accept,
430            );
431        })
432        .map_err(TransportError::Io)?;
433    Ok(TcpInboundHandle {
434        stop,
435        join,
436        active_sessions,
437    })
438}
439
440fn accept_inbound_loop<F>(
441    listener: TcpListener,
442    deliver: Arc<F>,
443    max_wire: u32,
444    max_sessions: usize,
445    stop: Arc<AtomicBool>,
446    active_sessions: Arc<AtomicUsize>,
447) where
448    F: Fn(&[u8]) -> Result<(), RemoteFrameError> + Send + Sync + 'static,
449{
450    let _ = listener.set_nonblocking(true);
451    while !stop.load(Ordering::Relaxed) {
452        match listener.accept() {
453            Ok((stream, peer)) => {
454                let deliver = Arc::clone(&deliver);
455                let sessions = Arc::clone(&active_sessions);
456                let Ok(guard) = SessionGuard::try_start(sessions, max_sessions) else {
457                    transport_info(format!(
458                        "inbound session limit ({max_sessions}) reached; refusing {peer}"
459                    ));
460                    let _ = stream.shutdown(Shutdown::Both);
461                    continue;
462                };
463                if thread::Builder::new()
464                    .name("byteflow-tcp-session".into())
465                    .spawn(move || {
466                        let _guard = guard;
467                        if let Err(e) = serve_tcp_connection(stream, &*deliver, max_wire) {
468                            transport_info(format!("session from {peer} ended: {e}"));
469                        }
470                    })
471                    .is_err()
472                {
473                    transport_info("inbound session thread spawn failed");
474                    continue;
475                }
476            }
477            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
478                thread::sleep(Duration::from_millis(25));
479            }
480            Err(_) => thread::sleep(Duration::from_millis(50)),
481        }
482    }
483}
484
485struct SessionGuard(Arc<AtomicUsize>);
486
487impl SessionGuard {
488    fn try_start(active: Arc<AtomicUsize>, max_sessions: usize) -> Result<Self, ()> {
489        if max_sessions == 0 {
490            active.fetch_add(1, Ordering::Relaxed);
491            return Ok(Self(active));
492        }
493        loop {
494            let current = active.load(Ordering::Acquire);
495            if current >= max_sessions {
496                return Err(());
497            }
498            if active
499                .compare_exchange_weak(current, current + 1, Ordering::AcqRel, Ordering::Acquire)
500                .is_ok()
501            {
502                return Ok(Self(active));
503            }
504        }
505    }
506}
507
508impl Drop for SessionGuard {
509    fn drop(&mut self) {
510        self.0.fetch_sub(1, Ordering::Release);
511    }
512}
513
514fn serve_tcp_connection<F>(
515    mut stream: TcpStream,
516    deliver: &F,
517    max_wire: u32,
518) -> Result<(), TransportError>
519where
520    F: Fn(&[u8]) -> Result<(), RemoteFrameError>,
521{
522    loop {
523        let frame = match read_wire_frame(&mut stream, max_wire) {
524            Ok(f) => f,
525            Err(TransportError::Io(e))
526                if matches!(
527                    e.kind(),
528                    std::io::ErrorKind::UnexpectedEof | std::io::ErrorKind::ConnectionReset
529                ) =>
530            {
531                return Ok(());
532            }
533            Err(e) => return Err(e),
534        };
535        if let Err(e) = deliver(&frame) {
536            transport_info(format!("deliver_frame failed: {e}"));
537            return Err(TransportError::Deliver(e));
538        }
539    }
540}
541
542/// One datagram carries exactly one wire frame (`BFT1` header + BFH1 body).
543pub fn send_wire_frame_udp(
544    sock: &UdpSocket,
545    addr: SocketAddr,
546    bfh1_payload: &[u8],
547    max_wire_bytes: u32,
548) -> Result<(), TransportError> {
549    let wire = encode_wire_bytes(bfh1_payload, max_wire_bytes)?;
550    sock.send_to(&wire, addr)?;
551    Ok(())
552}
553
554/// Reads one datagram wire frame. Returns the inner BFH1 bytes and the sender.
555pub fn recv_wire_frame_udp(
556    sock: &UdpSocket,
557    buf: &mut [u8],
558    max_wire_bytes: u32,
559) -> Result<(Vec<u8>, SocketAddr), TransportError> {
560    let (n, from) = sock.recv_from(buf)?;
561    decode_wire_bytes(&buf[..n], max_wire_bytes).map(|inner| (inner.to_vec(), from))
562}
563
564/// Write `BFT1 | u8 ver | u32 le len | payload` where `payload` is an [`encode_frame`] blob.
565pub fn write_wire_frame(
566    writer: &mut impl Write,
567    bfh1_payload: &[u8],
568    max_wire_bytes: u32,
569) -> Result<(), TransportError> {
570    let wire = encode_wire_bytes(bfh1_payload, max_wire_bytes)?;
571    writer.write_all(&wire)?;
572    Ok(())
573}
574
575/// Read one length-prefixed frame and return the inner BFH1 bytes.
576pub fn read_wire_frame(
577    reader: &mut impl Read,
578    max_wire_bytes: u32,
579) -> Result<Vec<u8>, TransportError> {
580    let mut header = [0u8; 9];
581    read_exact(reader, &mut header)?;
582    let len = wire_payload_len(&header, max_wire_bytes)?;
583    if len == 0 {
584        return Err(TransportError::InvalidConfig("empty remote hop payload"));
585    }
586    let mut body = vec![0u8; len as usize];
587    read_exact(reader, &mut body)?;
588    Ok(body)
589}
590
591pub use router::{resolve_hop_peer, FixedPeerRouter, NodeRouter, StaticNodeRouter};
592
593fn encode_wire_bytes(bfh1_payload: &[u8], max_wire_bytes: u32) -> Result<Vec<u8>, TransportError> {
594    let len = u32::try_from(bfh1_payload.len()).map_err(|_| TransportError::FrameTooLarge {
595        len: u32::MAX,
596        max: max_wire_bytes,
597    })?;
598    if len > max_wire_bytes {
599        return Err(TransportError::FrameTooLarge {
600            len,
601            max: max_wire_bytes,
602        });
603    }
604    let mut out = Vec::with_capacity(9 + bfh1_payload.len());
605    out.extend_from_slice(&WIRE_MAGIC);
606    out.push(WIRE_VERSION);
607    out.extend_from_slice(&len.to_le_bytes());
608    out.extend_from_slice(bfh1_payload);
609    Ok(out)
610}
611
612fn decode_wire_bytes(wire: &[u8], max_wire_bytes: u32) -> Result<&[u8], TransportError> {
613    let len = wire_payload_len(wire, max_wire_bytes)?;
614    let body_start = 9usize;
615    let body_end = body_start
616        .checked_add(len as usize)
617        .ok_or(TransportError::Truncated)?;
618    if body_end > wire.len() {
619        return Err(TransportError::Truncated);
620    }
621    if body_end < wire.len() {
622        return Err(TransportError::TrailingData);
623    }
624    Ok(&wire[body_start..body_end])
625}
626
627fn wire_payload_len(header: &[u8], max_wire_bytes: u32) -> Result<u32, TransportError> {
628    if header.len() < 9 {
629        return Err(TransportError::Truncated);
630    }
631    if header[..4] != WIRE_MAGIC {
632        return Err(TransportError::BadMagic);
633    }
634    if header[4] != WIRE_VERSION {
635        return Err(TransportError::BadVersion);
636    }
637    let len = u32::from_le_bytes([header[5], header[6], header[7], header[8]]);
638    if len > max_wire_bytes {
639        return Err(TransportError::FrameTooLarge {
640            len,
641            max: max_wire_bytes,
642        });
643    }
644    Ok(len)
645}
646
647fn read_exact(reader: &mut impl Read, buf: &mut [u8]) -> Result<(), TransportError> {
648    reader.read_exact(buf)?;
649    Ok(())
650}
651
652#[cfg(test)]
653mod tests {
654    use std::io::Cursor;
655
656    use super::*;
657
658    #[test]
659    fn wire_round_trips_bfh1_payload() -> Result<(), TransportError> {
660        let inner = b"BFH1-payload-bytes".to_vec();
661        let mut buf = Vec::new();
662        write_wire_frame(&mut buf, &inner, DEFAULT_MAX_WIRE_BYTES)?;
663        let mut cursor = Cursor::new(buf);
664        let back = read_wire_frame(&mut cursor, DEFAULT_MAX_WIRE_BYTES)?;
665        if back != inner {
666            return Err(TransportError::InvalidConfig("round trip mismatch"));
667        }
668        Ok(())
669    }
670
671    #[test]
672    fn wire_rejects_oversized_length_prefix() {
673        let mut wire = Vec::new();
674        wire.extend_from_slice(&WIRE_MAGIC);
675        wire.push(WIRE_VERSION);
676        wire.extend_from_slice(&(DEFAULT_MAX_WIRE_BYTES + 1).to_le_bytes());
677        assert!(matches!(
678            decode_wire_bytes(&wire, DEFAULT_MAX_WIRE_BYTES),
679            Err(TransportError::FrameTooLarge { .. })
680        ));
681    }
682
683    #[test]
684    fn wire_rejects_trailing_bytes() -> Result<(), TransportError> {
685        let inner = b"hop";
686        let mut wire = encode_wire_bytes(inner, DEFAULT_MAX_WIRE_BYTES)?;
687        wire.push(0);
688        assert!(matches!(
689            decode_wire_bytes(&wire, DEFAULT_MAX_WIRE_BYTES),
690            Err(TransportError::TrailingData)
691        ));
692        Ok(())
693    }
694
695    #[test]
696    fn session_limit_rejects_when_full() {
697        let active = Arc::new(AtomicUsize::new(0));
698        let first = match SessionGuard::try_start(Arc::clone(&active), 1) {
699            Ok(guard) => guard,
700            Err(()) => panic!("first slot"),
701        };
702        assert!(SessionGuard::try_start(active, 1).is_err());
703        drop(first);
704    }
705}