Skip to main content

byteflow/transport/
mod.rs

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