Skip to main content

claw_transport/
lib.rs

1#![deny(missing_docs)]
2//! Async byte-stream transport trait with pluggable TLS backends.
3//!
4//! Provides a [`Transport`] trait that abstracts over byte-stream
5//! connections (TLS, plain TCP, WebSocket tunnels, etc.).
6//!
7//! No `Send` bound is required, making this compatible with single-threaded
8//! runtimes like WASM.
9//!
10//! # Features
11//!
12//! - `wasm` — `wasm::TlsStream`: TLS via epoxy-tls JS bridge (for browser/WASM).
13//!   Connects through a Wisp proxy over WebSocket.
14//! - `native` — `native::TlsStream`: TLS via tokio + rustls (for native apps).
15//!   Direct TCP+TLS connection.
16
17#[cfg(feature = "wasm")]
18pub mod wasm;
19
20#[cfg(feature = "native")]
21pub mod native;
22
23/// Async byte-stream transport.
24///
25/// The transport must already be connected when passed to a protocol client.
26/// Connection setup (TLS handshake, etc.) is the caller's responsibility.
27///
28/// Uses native `async fn` in trait (Rust 1.75+) without `Send` bounds,
29/// for WASM single-threaded runtime compatibility.
30///
31/// # Contract
32///
33/// - [`send`](Transport::send) writes all provided bytes or returns an error.
34/// - [`recv`](Transport::recv) blocks until data is available. An empty `Vec`
35///   indicates a timeout; connection closure should return an error.
36/// - [`is_connected`](Transport::is_connected) returns `true` if the transport
37///   believes the connection is alive. A `true` return does not guarantee the
38///   next `send`/`recv` will succeed.
39#[allow(async_fn_in_trait)]
40pub trait Transport {
41    /// The error type for transport operations.
42    type Error: std::fmt::Display;
43
44    /// Send all bytes to the remote peer.
45    ///
46    /// Returns `Ok(())` when all data has been written, or an error
47    /// if the write fails.
48    async fn send(&mut self, data: &[u8]) -> Result<(), Self::Error>;
49
50    /// Receive data from the remote peer.
51    ///
52    /// Blocks until at least some data is available. Returns the received
53    /// bytes. An empty `Vec` indicates a timeout (no data within the
54    /// implementation's timeout window). Connection closure or I/O errors
55    /// should be reported as `Err`, not as an empty `Vec`.
56    async fn recv(&mut self) -> Result<Vec<u8>, Self::Error>;
57
58    /// Check if the transport believes the connection is still alive.
59    ///
60    /// This is a best-effort check. A return value of `true` does not
61    /// guarantee that the next `send` or `recv` will succeed.
62    fn is_connected(&self) -> bool;
63}