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