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