truffle_core/transport/mod.rs
1//! Layer 4: Transport — Protocol-specific connection management.
2//!
3//! This module defines three transport trait families:
4//!
5//! - [`StreamTransport`] + [`FramedStream`]: Persistent, framed, bidirectional
6//! connections used for messaging, pub/sub, and signaling. Implemented by
7//! [`WebSocketTransport`](websocket::WebSocketTransport).
8//!
9//! - [`RawTransport`] + [`RawListener`]: Raw byte streams used for file transfer,
10//! TCP proxy, and HTTP. Implemented by [`TcpTransport`](tcp::TcpTransport).
11//!
12//! - [`DatagramTransport`] + [`DatagramSocket`]: Unreliable datagrams for
13//! real-time video/audio and game state. Stubs only in this phase.
14//!
15//! # Layer rules
16//!
17//! - Layer 4 does NOT know about peers, sessions, or envelopes
18//! - Layer 4 works with [`PeerAddr`](crate::network::PeerAddr) (IP + hostname),
19//! not peer IDs
20//! - All transports delegate raw networking to Layer 3's [`NetworkProvider`]
21//! - The [`FramedStream`] trait is what Layer 5 (Session) will consume
22
23pub mod tcp;
24pub mod udp;
25pub mod quic;
26pub mod quic_socket;
27pub mod websocket;
28
29#[cfg(test)]
30mod tests;
31
32use std::time::Duration;
33
34use tokio::net::TcpStream;
35
36use crate::network::PeerAddr;
37
38// ---------------------------------------------------------------------------
39// Transport traits
40// ---------------------------------------------------------------------------
41
42/// A persistent, framed, bidirectional connection.
43///
44/// Used for: messaging, pub/sub, signaling.
45/// Implementations: WebSocket, QUIC streams (future).
46///
47/// The transport takes an `Arc<dyn NetworkProvider>` at construction time and
48/// uses Layer 3 to establish raw TCP connections before performing protocol
49/// upgrades (e.g., WebSocket handshake).
50#[allow(async_fn_in_trait)]
51pub trait StreamTransport: Send + Sync {
52 /// The framed stream type produced by this transport.
53 type Stream: FramedStream;
54
55 /// Connect to a peer address and return a framed bidirectional stream.
56 ///
57 /// The implementation should:
58 /// 1. Dial the peer via Layer 3 (`NetworkProvider::dial_tcp`)
59 /// 2. Perform any protocol upgrade (e.g., WebSocket handshake)
60 /// 3. Exchange a transport-level handshake message
61 /// 4. Return the resulting framed stream
62 async fn connect(&self, addr: &PeerAddr) -> Result<Self::Stream, TransportError>;
63
64 /// Start listening for incoming framed connections.
65 ///
66 /// Returns a [`StreamListener`] that yields framed streams as peers connect.
67 async fn listen(&self) -> Result<StreamListener<Self::Stream>, TransportError>;
68}
69
70/// A framed bidirectional stream (message-oriented, not byte-oriented).
71///
72/// Each `send()` call transmits one discrete message; each `recv()` call
73/// returns one discrete message. The transport handles framing internally
74/// (e.g., WebSocket frames, length-prefixed frames).
75///
76/// This is the primary interface that Layer 5 (Session) uses to exchange
77/// data with peers.
78#[allow(async_fn_in_trait)]
79pub trait FramedStream: Send + Sync + 'static {
80 /// Send a binary message to the peer.
81 async fn send(&mut self, data: &[u8]) -> Result<(), TransportError>;
82
83 /// Receive the next binary message from the peer.
84 ///
85 /// Returns `Ok(None)` when the stream is cleanly closed by the remote side.
86 async fn recv(&mut self) -> Result<Option<Vec<u8>>, TransportError>;
87
88 /// Gracefully close the stream.
89 async fn close(&mut self) -> Result<(), TransportError>;
90
91 /// The remote peer's address as a human-readable string.
92 fn peer_addr(&self) -> String;
93}
94
95/// A raw byte stream transport (not framed).
96///
97/// Used for: file transfer, TCP proxy, HTTP forwarding.
98/// Implementations: TCP, QUIC unidirectional streams (future).
99///
100/// Returns plain `TcpStream`s that Layer 7 applications use directly
101/// for byte-oriented I/O.
102#[allow(async_fn_in_trait)]
103pub trait RawTransport: Send + Sync {
104 /// Open a raw byte stream to a peer on the given port.
105 ///
106 /// Delegates to `NetworkProvider::dial_tcp` and returns the resulting
107 /// `TcpStream` without any protocol upgrade.
108 async fn open(&self, addr: &PeerAddr, port: u16) -> Result<TcpStream, TransportError>;
109
110 /// Listen for incoming raw byte streams on a port.
111 ///
112 /// Returns a [`RawListener`] that yields `TcpStream`s as peers connect.
113 async fn listen(&self, port: u16) -> Result<RawListener, TransportError>;
114}
115
116/// Unreliable datagram transport.
117///
118/// Used for: real-time video/audio, game state synchronization.
119/// Implementations: UDP, QUIC datagrams (future).
120///
121/// When backed by a [`NetworkProvider`](crate::network::NetworkProvider) that
122/// supports UDP (e.g., `TailscaleProvider`), the transport delegates to
123/// `NetworkProvider::bind_udp` and wraps the returned [`NetworkUdpSocket`]
124/// in a [`DatagramSocket`].
125#[allow(async_fn_in_trait)]
126pub trait DatagramTransport: Send + Sync {
127 /// Bind a datagram socket to a peer address.
128 ///
129 /// Returns a [`DatagramSocket`] that can send and receive datagrams.
130 async fn bind(&self, port: u16) -> Result<DatagramSocket, TransportError>;
131}
132
133// ---------------------------------------------------------------------------
134// Supporting types
135// ---------------------------------------------------------------------------
136
137/// A listener that yields framed streams as peers connect.
138///
139/// Wraps a `tokio::sync::mpsc::Receiver` internally. Call [`accept()`](Self::accept)
140/// in a loop to handle incoming connections.
141pub struct StreamListener<S: FramedStream> {
142 /// Receiver for incoming framed streams.
143 rx: tokio::sync::mpsc::Receiver<S>,
144 /// Port this listener is bound to.
145 pub port: u16,
146}
147
148impl<S: FramedStream> StreamListener<S> {
149 /// Create a new stream listener from a receiver and port.
150 pub fn new(rx: tokio::sync::mpsc::Receiver<S>, port: u16) -> Self {
151 Self { rx, port }
152 }
153
154 /// Accept the next incoming framed stream.
155 ///
156 /// Returns `None` when the listener has been shut down.
157 pub async fn accept(&mut self) -> Option<S> {
158 self.rx.recv().await
159 }
160}
161
162/// A listener that yields raw TCP streams as peers connect.
163///
164/// Wraps a `tokio::sync::mpsc::Receiver` internally. Call [`accept()`](Self::accept)
165/// in a loop to handle incoming connections.
166pub struct RawListener {
167 /// Receiver for incoming connections.
168 rx: tokio::sync::mpsc::Receiver<RawIncoming>,
169 /// Port this listener is bound to.
170 pub port: u16,
171}
172
173impl RawListener {
174 /// Create a new raw listener from a receiver and port.
175 pub fn new(rx: tokio::sync::mpsc::Receiver<RawIncoming>, port: u16) -> Self {
176 Self { rx, port }
177 }
178
179 /// Accept the next incoming raw connection.
180 ///
181 /// Returns `None` when the listener has been shut down.
182 pub async fn accept(&mut self) -> Option<RawIncoming> {
183 self.rx.recv().await
184 }
185}
186
187/// An incoming raw TCP connection with metadata.
188pub struct RawIncoming {
189 /// The raw TCP stream.
190 pub stream: TcpStream,
191 /// Remote address of the connecting peer.
192 pub remote_addr: String,
193}
194
195/// A datagram socket for sending and receiving unreliable packets.
196///
197/// Supports two modes:
198/// - **Direct**: Wraps a `tokio::net::UdpSocket` for loopback/LAN use.
199/// - **Network**: Wraps a [`NetworkUdpSocket`](crate::network::NetworkUdpSocket)
200/// for Tailscale relay-based UDP.
201pub enum DatagramSocket {
202 /// A direct UDP socket (loopback / LAN).
203 Direct {
204 /// The underlying UDP socket.
205 socket: tokio::net::UdpSocket,
206 },
207 /// A network-relayed UDP socket (Tailscale tsnet).
208 Network {
209 /// The network UDP socket with address-framed relay.
210 socket: crate::network::NetworkUdpSocket,
211 },
212}
213
214impl DatagramSocket {
215 /// Create a direct datagram socket from a tokio UdpSocket.
216 pub fn direct(socket: tokio::net::UdpSocket) -> Self {
217 Self::Direct { socket }
218 }
219
220 /// Create a network-relayed datagram socket from a NetworkUdpSocket.
221 pub fn network(socket: crate::network::NetworkUdpSocket) -> Self {
222 Self::Network { socket }
223 }
224
225 /// Send a datagram to the specified address.
226 pub async fn send_to(&self, data: &[u8], addr: &str) -> Result<usize, TransportError> {
227 match self {
228 Self::Direct { socket } => {
229 socket.send_to(data, addr).await.map_err(TransportError::Io)
230 }
231 Self::Network { socket } => {
232 let sock_addr: std::net::SocketAddr = addr.parse().map_err(|e| {
233 TransportError::ConnectFailed(format!("invalid address '{addr}': {e}"))
234 })?;
235 socket
236 .send_to(data, sock_addr)
237 .await
238 .map_err(|e| TransportError::Io(std::io::Error::new(std::io::ErrorKind::Other, e.to_string())))
239 }
240 }
241 }
242
243 /// Receive a datagram, returning the data and sender address.
244 pub async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, String), TransportError> {
245 match self {
246 Self::Direct { socket } => {
247 let (n, addr) = socket.recv_from(buf).await.map_err(TransportError::Io)?;
248 Ok((n, addr.to_string()))
249 }
250 Self::Network { socket } => {
251 let (n, addr) = socket
252 .recv_from(buf)
253 .await
254 .map_err(|e| TransportError::Io(std::io::Error::new(std::io::ErrorKind::Other, e.to_string())))?;
255 Ok((n, addr.to_string()))
256 }
257 }
258 }
259
260 /// Return the local address this socket is bound to.
261 pub fn local_addr(&self) -> Result<std::net::SocketAddr, TransportError> {
262 match self {
263 Self::Direct { socket } => socket.local_addr().map_err(TransportError::Io),
264 Self::Network { socket } => socket
265 .local_addr()
266 .map_err(|e| TransportError::Io(std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))),
267 }
268 }
269}
270
271// ---------------------------------------------------------------------------
272// Handshake types (used by WebSocketTransport)
273// ---------------------------------------------------------------------------
274
275/// Transport-level handshake message exchanged during connection setup.
276///
277/// This is a Layer 4 concern — it identifies the transport endpoint,
278/// not the application. Layer 5 (Session) will use this to associate
279/// the connection with a known peer.
280#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
281pub struct Handshake {
282 /// Identifier of the connecting peer (e.g., Tailscale stable node ID).
283 pub peer_id: String,
284 /// Capabilities supported by this peer (e.g., ["ws", "binary", "compress"]).
285 pub capabilities: Vec<String>,
286 /// Protocol version for compatibility negotiation.
287 pub protocol_version: u32,
288}
289
290/// Current transport protocol version.
291pub const PROTOCOL_VERSION: u32 = 1;
292
293// ---------------------------------------------------------------------------
294// Configuration
295// ---------------------------------------------------------------------------
296
297// Re-export transport configurations from submodules.
298pub use quic::QuicConfig;
299pub use udp::UdpConfig;
300
301/// Configuration for WebSocket transport.
302#[derive(Debug, Clone)]
303pub struct WsConfig {
304 /// Port to listen on for incoming WebSocket connections.
305 pub port: u16,
306 /// Interval between ping frames sent to the peer.
307 pub ping_interval: Duration,
308 /// Maximum time to wait for a pong response before considering
309 /// the connection dead.
310 pub pong_timeout: Duration,
311 /// Maximum WebSocket message size in bytes.
312 pub max_message_size: usize,
313}
314
315impl Default for WsConfig {
316 fn default() -> Self {
317 Self {
318 port: 9417,
319 ping_interval: Duration::from_secs(10),
320 pong_timeout: Duration::from_secs(30),
321 max_message_size: 16 * 1024 * 1024, // 16 MiB
322 }
323 }
324}
325
326// ---------------------------------------------------------------------------
327// Shared helpers
328// ---------------------------------------------------------------------------
329
330/// Resolve the best dial address from a [`PeerAddr`].
331///
332/// Prefers IP address (most reliable for Tailscale), falls back to DNS name,
333/// then hostname.
334pub(crate) fn resolve_dial_addr(addr: &PeerAddr) -> String {
335 if let Some(ip) = &addr.ip {
336 ip.to_string()
337 } else if let Some(dns) = &addr.dns_name {
338 dns.clone()
339 } else {
340 addr.hostname.clone()
341 }
342}
343
344// ---------------------------------------------------------------------------
345// Errors
346// ---------------------------------------------------------------------------
347
348/// Errors from Layer 4 transport operations.
349#[derive(Debug, thiserror::Error)]
350pub enum TransportError {
351 /// The requested transport or feature is not implemented.
352 #[error("not implemented: {0}")]
353 NotImplemented(String),
354
355 /// Failed to connect to the peer.
356 #[error("connect failed: {0}")]
357 ConnectFailed(String),
358
359 /// Failed to start listening.
360 #[error("listen failed: {0}")]
361 ListenFailed(String),
362
363 /// The transport-level handshake failed.
364 #[error("handshake failed: {0}")]
365 HandshakeFailed(String),
366
367 /// Protocol version mismatch between peers.
368 #[error("protocol version mismatch: local={local}, remote={remote}")]
369 VersionMismatch {
370 /// Local protocol version.
371 local: u32,
372 /// Remote protocol version.
373 remote: u32,
374 },
375
376 /// The connection was closed unexpectedly.
377 #[error("connection closed: {0}")]
378 ConnectionClosed(String),
379
380 /// A send or receive operation timed out.
381 #[error("timeout: {0}")]
382 Timeout(String),
383
384 /// Heartbeat (ping/pong) failure — the peer stopped responding.
385 #[error("heartbeat timeout after {0:?}")]
386 HeartbeatTimeout(Duration),
387
388 /// WebSocket protocol error.
389 #[error("websocket error: {0}")]
390 WebSocket(String),
391
392 /// I/O error from the underlying stream.
393 #[error("io error: {0}")]
394 Io(#[from] std::io::Error),
395
396 /// Serialization/deserialization error (e.g., handshake JSON).
397 #[error("serialization error: {0}")]
398 Serialize(String),
399
400 /// Error from Layer 3 (network).
401 #[error("network error: {0}")]
402 Network(#[from] crate::network::NetworkError),
403}