Skip to main content

zetta_transport/
lib.rs

1//! # ZettaTransport
2//!
3//! ZettaTransport is an experimental, encrypted, multiplexed transport protocol over UDP.
4//! It provides reliable ordered streams, unreliable datagrams, Tokio asynchronous I/O,
5//! congestion control, flow control, path validation, and path-MTU discovery.
6//!
7//! > **Experimental software:** this crate implements a custom protocol, not QUIC. It has not
8//! > received an independent security audit and is not intended for production or
9//! > mission-critical deployments. Prefer a standards-based QUIC implementation when
10//! > interoperability or production assurance is required.
11//!
12//! ## Start here
13//!
14//! Most applications use these types:
15//!
16//! - [`ZtEndpoint`](transport::endpoint::ZtEndpoint) owns a UDP socket and creates connections.
17//! - [`ZtConnectionHandle`](stream::ZtConnectionHandle) opens/accepts streams and sends datagrams.
18//! - [`ZtStream`](stream::ZtStream) is a reliable ordered byte stream implementing
19//!   [`tokio::io::AsyncRead`] and [`tokio::io::AsyncWrite`].
20//! - [`ZtConfig`](config::ZtConfig) controls timeouts, limits, MTU discovery, security, and
21//!   congestion control.
22//! - [`ZtError`](error::ZtError) exposes typed transport failures.
23//!
24//! Add the crate and the Tokio runtime to your project:
25//!
26//! ```toml
27//! [dependencies]
28//! zetta-transport = "0.1.26"
29//! tokio = { version = "1", features = ["full"] }
30//! bytes = "1"
31//! ```
32//!
33//! ## Echo server
34//!
35//! The endpoint is reference-counted. Each accepted connection owns its incoming stream queue,
36//! and every accepted stream can be processed in its own task.
37//!
38//! ```no_run
39//! use tokio::io::{AsyncReadExt, AsyncWriteExt};
40//! use zetta_transport::transport::endpoint::ZtEndpoint;
41//!
42//! #[tokio::main]
43//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
44//!     let endpoint = ZtEndpoint::bind("0.0.0.0:4433", None).await?;
45//!     println!("listening on {}", endpoint.local_addr()?);
46//!
47//!     while let Some(mut connection) = endpoint.accept().await {
48//!         tokio::spawn(async move {
49//!             while let Some(mut stream) = connection.accept_stream().await {
50//!                 tokio::spawn(async move {
51//!                     let mut buffer = [0_u8; 16 * 1024];
52//!                     loop {
53//!                         let read = match stream.read(&mut buffer).await {
54//!                             Ok(0) | Err(_) => break,
55//!                             Ok(read) => read,
56//!                         };
57//!                         if stream.write_all(&buffer[..read]).await.is_err() {
58//!                             break;
59//!                         }
60//!                     }
61//!                 });
62//!             }
63//!         });
64//!     }
65//!     Ok(())
66//! }
67//! ```
68//!
69//! ## Client
70//!
71//! ```no_run
72//! use tokio::io::{AsyncReadExt, AsyncWriteExt};
73//! use zetta_transport::transport::endpoint::ZtEndpoint;
74//!
75//! #[tokio::main]
76//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
77//!     let endpoint = ZtEndpoint::bind("0.0.0.0:0", None).await?;
78//!     let connection = endpoint.connect("127.0.0.1:4433".parse()?).await?;
79//!     let mut stream = connection.open_stream().await?;
80//!
81//!     stream.write_all(b"hello").await?;
82//!     stream.flush().await?;
83//!
84//!     let mut reply = [0_u8; 5];
85//!     stream.read_exact(&mut reply).await?;
86//!     assert_eq!(&reply, b"hello");
87//!     Ok(())
88//! }
89//! ```
90//!
91//! ## Streams and datagrams
92//!
93//! [`stream::ZtConnectionHandle::open_stream`] creates a bidirectional stream. Use
94//! [`stream::ZtConnectionHandle::open_stream_with_type`] for a send-only stream. A receive-only
95//! stream is created locally when the peer opens a send-only stream; it cannot be opened directly.
96//! Dropping or calling [`stream::ZtStream::close`] gracefully finishes a stream. Use
97//! [`stream::ZtStream::reset`] to terminate it with an application error code.
98//!
99//! Datagrams are encrypted and congestion-controlled but are not ordered or retransmitted. They
100//! are appropriate only when losing an individual message is acceptable.
101//!
102//! ## Preserving close reasons
103//!
104//! Convenience receive methods return `Option` and collapse termination into `None`. Applications
105//! that need the exact cause should use [`stream::ZtStream::recv_result`],
106//! [`stream::ZtConnectionHandle::accept_stream_result`], and
107//! [`stream::ZtConnectionHandle::recv_datagram_result`]. These methods preserve peer reset codes,
108//! peer connection-close reasons, and idle timeouts.
109//!
110//! ## Authentication
111//!
112//! Every endpoint creates an Ed25519 identity at bind time and uses ephemeral X25519 keys for each
113//! connection. By default, cryptographic identity proves handshake integrity but is not tied to a
114//! trusted name. Experiments that need peer authentication should install a verifier with
115//! [`transport::endpoint::ZtEndpoint::set_peer_key_verifier`] and may additionally configure a
116//! shared 32-byte PSK through [`config::ZtConfig::psk`]. Endpoint identities are currently
117//! ephemeral unless the application pins and redistributes the exposed public key itself.
118//!
119//! ## Protocol compatibility
120//!
121//! Version 0.1.26 speaks ZettaTransport wire protocol version 2. Version 2 is intentionally not
122//! wire-compatible with earlier crate releases: it signs transport parameters, transmits stream
123//! direction on the wire, and includes a final byte offset in graceful stream closure.
124//!
125//! See the crate modules below for the complete API and the repository's `DOCUMENTATION.md` for
126//! packet/frame layout and protocol internals.
127
128#![warn(missing_docs)]
129
130/// Endpoint configuration and validation.
131pub mod config;
132pub(crate) mod crypto;
133/// Public error and result types.
134pub mod error;
135pub(crate) mod protocol;
136/// Connection telemetry snapshots.
137pub mod stats;
138/// Connection and stream application APIs.
139pub mod stream;
140/// Endpoint construction, stream direction, and congestion-control selection.
141pub mod transport;
142
143#[cfg(any(test, feature = "testing"))]
144/// Deterministic endpoint-scoped network fault injection for tests.
145pub mod simulation;
146
147/// Narrow test-only entry points used by the out-of-process fuzz targets.
148#[cfg(any(test, feature = "testing"))]
149pub mod fuzzing {
150    /// Decodes a complete frame corpus, guaranteeing forward progress even for malformed input.
151    pub fn decode_frames(data: &[u8]) {
152        let mut bytes = bytes::Bytes::copy_from_slice(data);
153        while !bytes.is_empty() {
154            let before = bytes.len();
155            if crate::protocol::frame::Frame::decode(&mut bytes).is_err() {
156                break;
157            }
158            if bytes.len() >= before {
159                break;
160            }
161        }
162    }
163}