rings_node/extension/transport/mod.rs
1//! Transport relay — one abstraction for TCP, HTTP and (future) UDP.
2//!
3//! # Why these are *not* three protocols
4//!
5//! The rings overlay (DHT + swarm + backend envelopes) provides an **authenticated,
6//! bidirectional message channel between two DIDs** — call it the *virtual circuit*. It is
7//! best effort: a full application inbox or namespace queue drops a message, counted, and a
8//! frame held on an unresolved delegation reference may be overtaken by later frames of its
9//! stream. A relay that promises a reliable byte stream therefore sequences its frames and
10//! resets the stream on a loss it cannot repair (see [`Frame::Data`]). TCP / HTTP / UDP
11//! "services" are all the **same thing**: a *relay* that maps a local I/O resource (a
12//! socket) onto that virtual circuit. They differ only in the shape of the local resource,
13//! along three axes:
14//!
15//! ```text
16//! axis TCP HTTP UDP
17//! ---------------------- ----------------- --------------------- ------------------
18//! session cardinality ω (endless stream) 1 (one req/resp, 0 (no session,
19//! affine: Req ⊸ Resp) datagrams)
20//! framing byte stream HTTP messages datagrams
21//! lifecycle open → data* → close open → 1×req → 1×resp none
22//! → close
23//! ordering / reliability ordered, reliable ordered, reliable unordered, lossy
24//! (semantics chosen
25//! when tunnelled)
26//! ```
27//!
28//! Categorically they are one structure at three points of a single "session
29//! cardinality" axis:
30//!
31//! - **TCP** = a bidirectional byte **stream** — the cofree stream / a long-lived
32//! process; cardinality **ω**.
33//! - **HTTP** = the **affine** degeneration of TCP: exactly one exchange
34//! `Request ⊸ Response` (a use-once session); cardinality **1**.
35//! - **UDP** = the **0-session** degeneration: `Datagram → [Datagram]`, a discrete
36//! transducer with no lifecycle; cardinality **0**.
37//!
38//! So adding UDP later is not a fourth subsystem — it is this axis taken to 0.
39//!
40//! # How it sits on the effect base (`backend::ext`)
41//!
42//! Pure/effect separation is preserved:
43//!
44//! - The **interpreter owns the live resources** (the `TcpStream` / `UdpSocket`), keyed
45//! by [`RelaySessionId`], in a resource table. These are non-purifiable OS handles and so
46//! live only in the imperative shell — never in a protocol's state.
47//! - A protocol's **pure `step`** holds only session *metadata* (which `RelaySessionId` maps
48//! to which peer/service, framing state, counters) — never a live socket.
49//! - Generic transport **effects** (run by the interpreter): stream ops
50//! `Connect` / `Write` / `Close`; datagram ops `Bind` / `SendTo`.
51//! - Local reads / accepts **re-inject** [`Frame`]s as events (the event trace of the
52//! effect monad): the read task feeds `Data` / `Close` / `Datagram` back through the
53//! router → `step` → an `Effect::Send` over the virtual circuit.
54//!
55//! TCP / HTTP / UDP are then thin instances over this one relay: TCP uses the stream
56//! ops with an ω session; HTTP adds "one request → one response → close" session logic
57//! (expressible purely in `step`); UDP uses only the datagram ops with no session.
58
59// The relay's imperative resource tables are private to the relay interpreter — not a public
60// API. Reachable in-crate by the relay extension only.
61pub(crate) mod engine;
62
63use std::sync::atomic::AtomicU64;
64use std::sync::atomic::Ordering;
65use std::time::Duration;
66
67use bytes::Bytes;
68use rings_core::dht::Did;
69use serde::Deserialize;
70use serde::Serialize;
71
72/// Maximum silence before an abandoned local socket/flow is reclaimed.
73pub(crate) const RELAY_IDLE_TIMEOUT: Duration = Duration::from_secs(5 * 60);
74
75/// Allocate one counter value without ever wrapping back to a live ABA-equivalent value.
76pub(crate) fn allocate_non_reusing(counter: &AtomicU64) -> Option<u64> {
77 counter
78 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
79 value.checked_add(1)
80 })
81 .ok()
82}
83
84/// Identifier assigned by the opener to a relayed stream or datagram flow (a virtual circuit
85/// ↔ local socket pairing). This relay identifier is distinct from delegated-signing identity.
86///
87/// TCP uses it for a connection; UDP uses it for a *flow* (a NAT-like mapping that
88/// routes responses back to the right local client) — see [`TransportKind`].
89#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
90pub struct RelaySessionId(pub u64);
91
92/// Which end **opened** a relay session, from the perspective of the node holding the key.
93///
94/// Necessary because two nodes that simultaneously open a tunnel to each other both mint
95/// `RelaySessionId(0)`: without an initiator, "the session I opened to peer B" and "the session B
96/// opened to me" would collide on `(peer=B, namespace, session=0)`, and a wire `Data(0)`
97/// would be ambiguous. The initiator splits the id space into two halves per `(peer,
98/// namespace)`.
99#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
100pub enum Initiator {
101 /// This node opened the session (a client tunnel).
102 Local,
103 /// The peer opened the session (this node is the server).
104 Remote,
105}
106
107/// Result of applying one ordered peer-to-local transport effect without
108/// waiting for backend backpressure.
109#[derive(Clone, Copy, Debug, Eq, PartialEq)]
110pub(crate) enum EffectEnqueue {
111 /// The effect was accepted by the current backend generation.
112 Enqueued,
113 /// The requested backend slot is already owned by a live generation; the
114 /// duplicate effect is a no-op and pure state must preserve the session.
115 AlreadyPresent,
116 /// No backend generation exists; pure state must simply forget the key.
117 Missing,
118 /// The current backend generation failed or saturated; pure state must
119 /// forget it and notify the peer with `Close`.
120 Failed,
121}
122
123/// Result of trying to reserve one unique backend slot.
124pub(crate) enum SlotRegistration<T> {
125 /// The vacant slot was reserved and produced its backend-specific resource.
126 Registered(T),
127 /// A live backend generation already owns the slot and remains authoritative.
128 AlreadyPresent,
129 /// The slot could not be reserved because an internal resource failed.
130 Failed,
131}
132
133/// A relay session's full identity — the unit used to key live sessions and to address
134/// transport effects.
135///
136/// A bare [`RelaySessionId`] is **not** a valid address: the id on the wire is assigned by the
137/// opener, so two ends can both pick `RelaySessionId(0)`. The key scopes a session by `(peer,
138/// namespace, session, initiator)`, where `peer` is the **authenticated** other end
139/// (`event.from`, the verified signer) and `initiator` records which end opened it. Because a
140/// peer cannot forge `event.from`, it can only ever address sessions whose `peer` is itself
141/// (owner rejection); and `initiator` keeps a peer's session distinct from one of ours that
142/// happened to get the same id (bidirectional-open safety).
143#[derive(Clone, PartialEq, Eq, Hash, Debug)]
144pub struct SessionKey {
145 /// The authenticated remote end of the session (`event.from` for inbound frames).
146 pub peer: Did,
147 /// The transport namespace the session lives under (e.g. `tcp`, `udp`).
148 pub namespace: String,
149 /// The opener-assigned session id, unique only within `(peer, namespace, initiator)`.
150 pub session: RelaySessionId,
151 /// Which end opened the session (disambiguates colliding ids on simultaneous open).
152 pub initiator: Initiator,
153}
154
155impl SessionKey {
156 /// Build a delegatee key from its parts.
157 pub fn new(
158 peer: Did,
159 namespace: impl Into<String>,
160 session: RelaySessionId,
161 initiator: Initiator,
162 ) -> Self {
163 Self {
164 peer,
165 namespace: namespace.into(),
166 session,
167 initiator,
168 }
169 }
170}
171
172/// Which local socket a relay session is backed by.
173///
174/// Both kinds share the same [`Frame`] vocabulary (`Open`/`Data`/`Close`); only the
175/// socket differs. UDP is *flow*-based rather than truly sessionless because a relayed
176/// datagram still needs a return path to the originating local client, so each flow
177/// carries a [`RelaySessionId`] just like a TCP connection. `Data` preserves message
178/// boundaries (one datagram per frame) for UDP.
179#[derive(Clone, Copy, PartialEq, Eq, Debug)]
180pub enum TransportKind {
181 /// Connection-oriented byte stream.
182 Tcp,
183 /// Datagram flow (per-flow socket; message boundaries preserved per `Data`).
184 Udp,
185}
186
187/// The relay's overlay wire message — the payload carried under a transport namespace.
188///
189/// One vocabulary for both kinds (TCP connections and UDP flows), differing only in how the
190/// bytes travel:
191///
192/// ```text
193/// TCP Open(session, service) → Data(session, seq, bytes)* → Shutdown(session, sent)
194/// → Close(session)
195/// UDP Open(session, service) → Datagram(session, bytes)* → Close(session)
196/// ```
197///
198/// Law (no silent gap). A TCP direction's `Data` frames carry `seq = 0, 1, 2, …` and its
199/// `Shutdown` carries the number `sent` of them. The receiver writes bytes to its local socket
200/// in `seq` order only, reordering at most [`REORDER_WINDOW`] frames ahead, so the local
201/// stream is always a prefix of what the peer sent. A frame missing for [`REORDER_DEADLINE`] is
202/// past the delivery bounds of its path, and one more than the window behind can never arrive
203/// (the replay window refuses it), so either way the receiver resets the session: the peer gets
204/// `Close`, and the local socket an abortive close. A `Shutdown` is applied only once every one
205/// of its `sent` frames was written, so a lost last frame is a reset, never a clean end of
206/// stream.
207///
208/// [`REORDER_WINDOW`]: rings_core::message::REORDER_WINDOW
209/// [`REORDER_DEADLINE`]: rings_core::message::REORDER_DEADLINE
210///
211/// `Open` is always sent by the session's opener. `Data`/`Shutdown`/`Close` flow in both
212/// directions over the *same* opener-assigned id, so they carry `from_opener` — whether the
213/// **sender** of this frame opened the session. The receiver flips it to recover its own
214/// [`Initiator`], so a peer's session never collides with one of ours sharing the same id.
215#[derive(Clone, Debug, Serialize, Deserialize)]
216pub enum Frame {
217 /// Open a session/flow to a named local service (always sent by the opener).
218 Open {
219 /// Relay session identifier (assigned by the opener).
220 session: RelaySessionId,
221 /// Local service name to connect to.
222 service: String,
223 },
224 /// A segment of a TCP session's byte stream, in its direction's `seq` order.
225 Data {
226 /// Relay session the bytes belong to.
227 session: RelaySessionId,
228 /// Whether the sender of this frame opened the session.
229 from_opener: bool,
230 /// The segment's position in its direction: the sender's count of earlier `Data`.
231 seq: u64,
232 /// Payload bytes.
233 bytes: Bytes,
234 },
235 /// One datagram of a UDP flow; datagrams carry no order and may be lost.
236 Datagram {
237 /// Relay flow the datagram belongs to.
238 session: RelaySessionId,
239 /// Whether the sender of this frame opened the flow.
240 from_opener: bool,
241 /// The datagram.
242 bytes: Bytes,
243 },
244 /// Half-close: the sender has no more `Data` this direction (a TCP FIN). The receiver shuts
245 /// down its local write side once all `sent` segments are written, and keeps the reverse
246 /// direction open. Ignored by UDP (datagram flows have no half-close).
247 Shutdown {
248 /// Relay session being half-closed.
249 session: RelaySessionId,
250 /// Whether the sender of this frame opened the session.
251 from_opener: bool,
252 /// How many `Data` frames the sender sent this direction.
253 sent: u64,
254 },
255 /// Close a session/flow (full teardown, both directions).
256 Close {
257 /// Relay session to close.
258 session: RelaySessionId,
259 /// Whether the sender of this frame opened the session.
260 from_opener: bool,
261 },
262}
263
264#[cfg(test)]
265mod tests {
266 use super::*;
267
268 #[test]
269 fn test_non_reusing_allocator_is_total_at_exhaustion() {
270 let counter = AtomicU64::new(u64::MAX - 1);
271 assert_eq!(allocate_non_reusing(&counter), Some(u64::MAX - 1));
272 assert_eq!(allocate_non_reusing(&counter), None);
273 assert_eq!(counter.load(Ordering::Relaxed), u64::MAX);
274 }
275}