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::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 [`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`.
416pub struct TcpInboundHandle {
417    stop: Arc<AtomicBool>,
418    join: JoinHandle<()>,
419    active_sessions: Arc<AtomicUsize>,
420    registry: Arc<SessionRegistry>,
421}
422
423impl TcpInboundHandle {
424    /// Signal stop, **shutdown every live session socket**, join the accept
425    /// thread, then wait for session threads to exit (≤ [`SESSION_DRAIN`]).
426    pub fn stop(self) -> Result<(), TransportError> {
427        self.stop.store(true, Ordering::Relaxed);
428        self.registry.shutdown_all();
429        self.join.join().map_err(|_| TransportError::ThreadJoin)?;
430        let deadline = Instant::now() + SESSION_DRAIN;
431        while self.active_sessions.load(Ordering::Acquire) > 0 {
432            if Instant::now() >= deadline {
433                return Err(TransportError::InvalidConfig(
434                    "inbound sessions did not finish",
435                ));
436            }
437            thread::sleep(Duration::from_millis(10));
438        }
439        Ok(())
440    }
441}
442
443pub fn spawn_tcp_inbound<F>(
444    listener: TcpListener,
445    deliver: Arc<F>,
446    config: TcpInboundConfig,
447) -> Result<TcpInboundHandle, TransportError>
448where
449    F: Fn(&[u8]) -> Result<(), RemoteFrameError> + Send + Sync + 'static,
450{
451    check_max_wire(config.max_wire_bytes)?;
452    let stop = Arc::new(AtomicBool::new(false));
453    let stop_accept = Arc::clone(&stop);
454    let active_sessions = Arc::new(AtomicUsize::new(0));
455    let sessions_accept = Arc::clone(&active_sessions);
456    let registry = Arc::new(SessionRegistry::new());
457    let registry_accept = Arc::clone(&registry);
458    let max_wire = config.max_wire_bytes;
459    let max_sessions = config.max_sessions;
460    let read_timeout = config.read_timeout;
461    let write_timeout = config.write_timeout;
462    let join = thread::Builder::new()
463        .name("byteflow-tcp-in".into())
464        .spawn(move || {
465            accept_inbound_loop(
466                listener,
467                deliver,
468                InboundLoopState {
469                    max_wire,
470                    max_sessions,
471                    read_timeout,
472                    write_timeout,
473                    stop: stop_accept,
474                    active_sessions: sessions_accept,
475                    registry: registry_accept,
476                },
477            );
478        })
479        .map_err(TransportError::Io)?;
480    Ok(TcpInboundHandle {
481        stop,
482        join,
483        active_sessions,
484        registry,
485    })
486}
487
488struct InboundLoopState {
489    max_wire: u32,
490    max_sessions: usize,
491    read_timeout: Option<Duration>,
492    write_timeout: Option<Duration>,
493    stop: Arc<AtomicBool>,
494    active_sessions: Arc<AtomicUsize>,
495    registry: Arc<SessionRegistry>,
496}
497
498fn accept_inbound_loop<F>(listener: TcpListener, deliver: Arc<F>, state: InboundLoopState)
499where
500    F: Fn(&[u8]) -> Result<(), RemoteFrameError> + Send + Sync + 'static,
501{
502    let InboundLoopState {
503        max_wire,
504        max_sessions,
505        read_timeout,
506        write_timeout,
507        stop,
508        active_sessions,
509        registry,
510    } = state;
511    let _ = listener.set_nonblocking(true);
512    while !stop.load(Ordering::Relaxed) {
513        match listener.accept() {
514            Ok((stream, peer)) => {
515                let deliver = Arc::clone(&deliver);
516                let sessions = Arc::clone(&active_sessions);
517                let registry = Arc::clone(&registry);
518                let stop_session = Arc::clone(&stop);
519                let Ok(guard) = SessionGuard::try_start(sessions, max_sessions) else {
520                    transport_info(format!(
521                        "inbound session limit ({max_sessions}) reached; refusing {peer}"
522                    ));
523                    let _ = stream.shutdown(Shutdown::Both);
524                    continue;
525                };
526                if apply_socket_timeouts(&stream, read_timeout, write_timeout).is_err() {
527                    transport_info(format!("inbound {peer}: set socket timeouts failed"));
528                    let _ = stream.shutdown(Shutdown::Both);
529                    continue;
530                }
531                let Some(session_id) = registry.register(&stream) else {
532                    transport_info(format!("inbound {peer}: session registry failed"));
533                    let _ = stream.shutdown(Shutdown::Both);
534                    continue;
535                };
536                let registry_session = Arc::clone(&registry);
537                if thread::Builder::new()
538                    .name("byteflow-tcp-session".into())
539                    .spawn(move || {
540                        let _guard = guard;
541                        let _reg = SessionRegistration {
542                            id: session_id,
543                            registry: registry_session,
544                        };
545                        if let Err(e) =
546                            serve_tcp_connection(stream, &*deliver, max_wire, stop_session)
547                        {
548                            transport_info(format!("session from {peer} ended: {e}"));
549                        }
550                    })
551                    .is_err()
552                {
553                    registry.unregister(session_id);
554                    transport_info("inbound session thread spawn failed");
555                    continue;
556                }
557            }
558            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
559                thread::sleep(Duration::from_millis(25));
560            }
561            Err(_) => thread::sleep(Duration::from_millis(50)),
562        }
563    }
564}
565
566/// Cloned peer sockets so [`TcpInboundHandle::stop`] can unblock `read_exact`.
567struct SessionRegistry {
568    next_id: AtomicUsize,
569    sockets: Mutex<HashMap<usize, TcpStream>>,
570}
571
572impl SessionRegistry {
573    fn new() -> Self {
574        Self {
575            next_id: AtomicUsize::new(1),
576            sockets: Mutex::new(HashMap::new()),
577        }
578    }
579
580    fn register(&self, stream: &TcpStream) -> Option<usize> {
581        let clone = stream.try_clone().ok()?;
582        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
583        self.sockets.lock().ok()?.insert(id, clone);
584        Some(id)
585    }
586
587    fn unregister(&self, id: usize) {
588        if let Ok(mut g) = self.sockets.lock() {
589            g.remove(&id);
590        }
591    }
592
593    fn shutdown_all(&self) {
594        let Ok(mut g) = self.sockets.lock() else {
595            return;
596        };
597        for (_, sock) in g.drain() {
598            let _ = sock.shutdown(Shutdown::Both);
599        }
600    }
601}
602
603struct SessionRegistration {
604    id: usize,
605    registry: Arc<SessionRegistry>,
606}
607
608impl Drop for SessionRegistration {
609    fn drop(&mut self) {
610        self.registry.unregister(self.id);
611    }
612}
613
614struct SessionGuard(Arc<AtomicUsize>);
615
616impl SessionGuard {
617    fn try_start(active: Arc<AtomicUsize>, max_sessions: usize) -> Result<Self, ()> {
618        if max_sessions == 0 {
619            active.fetch_add(1, Ordering::Relaxed);
620            return Ok(Self(active));
621        }
622        loop {
623            let current = active.load(Ordering::Acquire);
624            if current >= max_sessions {
625                return Err(());
626            }
627            if active
628                .compare_exchange_weak(current, current + 1, Ordering::AcqRel, Ordering::Acquire)
629                .is_ok()
630            {
631                return Ok(Self(active));
632            }
633        }
634    }
635}
636
637impl Drop for SessionGuard {
638    fn drop(&mut self) {
639        self.0.fetch_sub(1, Ordering::Release);
640    }
641}
642
643fn serve_tcp_connection<F>(
644    mut stream: TcpStream,
645    deliver: &F,
646    max_wire: u32,
647    stop: Arc<AtomicBool>,
648) -> Result<(), TransportError>
649where
650    F: Fn(&[u8]) -> Result<(), RemoteFrameError>,
651{
652    while !stop.load(Ordering::Relaxed) {
653        let frame = match read_wire_frame(&mut stream, max_wire) {
654            Ok(f) => f,
655            Err(TransportError::Io(e))
656                if matches!(
657                    e.kind(),
658                    std::io::ErrorKind::UnexpectedEof
659                        | std::io::ErrorKind::ConnectionReset
660                        | std::io::ErrorKind::ConnectionAborted
661                        | std::io::ErrorKind::TimedOut
662                        | std::io::ErrorKind::WouldBlock
663                ) =>
664            {
665                return Ok(());
666            }
667            Err(e) => return Err(e),
668        };
669        if stop.load(Ordering::Relaxed) {
670            return Ok(());
671        }
672        if let Err(e) = deliver(&frame) {
673            transport_info(format!("deliver_frame failed: {e}"));
674            return Err(TransportError::Deliver(e));
675        }
676    }
677    Ok(())
678}
679
680/// One datagram carries exactly one wire frame (`BFT1` header + BFH1 body).
681pub fn send_wire_frame_udp(
682    sock: &UdpSocket,
683    addr: SocketAddr,
684    bfh1_payload: &[u8],
685    max_wire_bytes: u32,
686) -> Result<(), TransportError> {
687    let wire = encode_wire_bytes(bfh1_payload, max_wire_bytes)?;
688    sock.send_to(&wire, addr)?;
689    Ok(())
690}
691
692/// Reads one datagram wire frame. Returns the inner BFH1 bytes and the sender.
693pub fn recv_wire_frame_udp(
694    sock: &UdpSocket,
695    buf: &mut [u8],
696    max_wire_bytes: u32,
697) -> Result<(Vec<u8>, SocketAddr), TransportError> {
698    let (n, from) = sock.recv_from(buf)?;
699    decode_wire_bytes(&buf[..n], max_wire_bytes).map(|inner| (inner.to_vec(), from))
700}
701
702/// Write `BFT1 | u8 ver | u32 le len | payload` where `payload` is an [`encode_frame`] blob.
703pub fn write_wire_frame(
704    writer: &mut impl Write,
705    bfh1_payload: &[u8],
706    max_wire_bytes: u32,
707) -> Result<(), TransportError> {
708    let wire = encode_wire_bytes(bfh1_payload, max_wire_bytes)?;
709    writer.write_all(&wire)?;
710    Ok(())
711}
712
713/// Read one length-prefixed frame and return the inner BFH1 bytes.
714pub fn read_wire_frame(
715    reader: &mut impl Read,
716    max_wire_bytes: u32,
717) -> Result<Vec<u8>, TransportError> {
718    let mut header = [0u8; 9];
719    read_exact(reader, &mut header)?;
720    let len = wire_payload_len(&header, max_wire_bytes)?;
721    if len == 0 {
722        return Err(TransportError::InvalidConfig("empty remote hop payload"));
723    }
724    let mut body = vec![0u8; len as usize];
725    read_exact(reader, &mut body)?;
726    Ok(body)
727}
728
729pub use router::{resolve_hop_peer, FixedPeerRouter, NodeRouter, StaticNodeRouter};
730
731fn encode_wire_bytes(bfh1_payload: &[u8], max_wire_bytes: u32) -> Result<Vec<u8>, TransportError> {
732    let len = u32::try_from(bfh1_payload.len()).map_err(|_| TransportError::FrameTooLarge {
733        len: u32::MAX,
734        max: max_wire_bytes,
735    })?;
736    if len > max_wire_bytes {
737        return Err(TransportError::FrameTooLarge {
738            len,
739            max: max_wire_bytes,
740        });
741    }
742    let mut out = Vec::with_capacity(9 + bfh1_payload.len());
743    out.extend_from_slice(&WIRE_MAGIC);
744    out.push(WIRE_VERSION);
745    out.extend_from_slice(&len.to_le_bytes());
746    out.extend_from_slice(bfh1_payload);
747    Ok(out)
748}
749
750fn decode_wire_bytes(wire: &[u8], max_wire_bytes: u32) -> Result<&[u8], TransportError> {
751    let len = wire_payload_len(wire, max_wire_bytes)?;
752    let body_start = 9usize;
753    let body_end = body_start
754        .checked_add(len as usize)
755        .ok_or(TransportError::Truncated)?;
756    if body_end > wire.len() {
757        return Err(TransportError::Truncated);
758    }
759    if body_end < wire.len() {
760        return Err(TransportError::TrailingData);
761    }
762    Ok(&wire[body_start..body_end])
763}
764
765fn wire_payload_len(header: &[u8], max_wire_bytes: u32) -> Result<u32, TransportError> {
766    if header.len() < 9 {
767        return Err(TransportError::Truncated);
768    }
769    if header[..4] != WIRE_MAGIC {
770        return Err(TransportError::BadMagic);
771    }
772    if header[4] != WIRE_VERSION {
773        return Err(TransportError::BadVersion);
774    }
775    let len = u32::from_le_bytes([header[5], header[6], header[7], header[8]]);
776    if len > max_wire_bytes {
777        return Err(TransportError::FrameTooLarge {
778            len,
779            max: max_wire_bytes,
780        });
781    }
782    Ok(len)
783}
784
785fn read_exact(reader: &mut impl Read, buf: &mut [u8]) -> Result<(), TransportError> {
786    reader.read_exact(buf)?;
787    Ok(())
788}
789
790#[cfg(test)]
791mod tests {
792    use std::io::Cursor;
793
794    use super::*;
795
796    #[test]
797    fn wire_round_trips_bfh1_payload() -> Result<(), TransportError> {
798        let inner = b"BFH1-payload-bytes".to_vec();
799        let mut buf = Vec::new();
800        write_wire_frame(&mut buf, &inner, DEFAULT_MAX_WIRE_BYTES)?;
801        let mut cursor = Cursor::new(buf);
802        let back = read_wire_frame(&mut cursor, DEFAULT_MAX_WIRE_BYTES)?;
803        if back != inner {
804            return Err(TransportError::InvalidConfig("round trip mismatch"));
805        }
806        Ok(())
807    }
808
809    #[test]
810    fn wire_rejects_oversized_length_prefix() {
811        let mut wire = Vec::new();
812        wire.extend_from_slice(&WIRE_MAGIC);
813        wire.push(WIRE_VERSION);
814        wire.extend_from_slice(&(DEFAULT_MAX_WIRE_BYTES + 1).to_le_bytes());
815        assert!(matches!(
816            decode_wire_bytes(&wire, DEFAULT_MAX_WIRE_BYTES),
817            Err(TransportError::FrameTooLarge { .. })
818        ));
819    }
820
821    #[test]
822    fn wire_rejects_trailing_bytes() -> Result<(), TransportError> {
823        let inner = b"hop";
824        let mut wire = encode_wire_bytes(inner, DEFAULT_MAX_WIRE_BYTES)?;
825        wire.push(0);
826        assert!(matches!(
827            decode_wire_bytes(&wire, DEFAULT_MAX_WIRE_BYTES),
828            Err(TransportError::TrailingData)
829        ));
830        Ok(())
831    }
832
833    #[test]
834    fn session_limit_rejects_when_full() {
835        let active = Arc::new(AtomicUsize::new(0));
836        let first = match SessionGuard::try_start(Arc::clone(&active), 1) {
837            Ok(guard) => guard,
838            Err(()) => panic!("first slot"),
839        };
840        assert!(SessionGuard::try_start(active, 1).is_err());
841        drop(first);
842    }
843}