rings-node 0.39.0

Rings is a browser-native, structured peer-to-peer network: browser tabs and native daemons find each other by DID and talk over WebRTC, routed by a Chord DHT.
//! Transport relay — one abstraction for TCP, HTTP and (future) UDP.
//!
//! # Why these are *not* three protocols
//!
//! The rings overlay (DHT + swarm + backend envelopes) provides an **authenticated,
//! bidirectional message channel between two DIDs** — call it the *virtual circuit*. It is
//! best effort: a full application inbox or namespace queue drops a message, counted, and a
//! frame held on an unresolved delegation reference may be overtaken by later frames of its
//! stream. A relay that promises a reliable byte stream therefore sequences its frames and
//! resets the stream on a loss it cannot repair (see [`Frame::Data`]). TCP / HTTP / UDP
//! "services" are all the **same thing**: a *relay* that maps a local I/O resource (a
//! socket) onto that virtual circuit. They differ only in the shape of the local resource,
//! along three axes:
//!
//! ```text
//!   axis                     TCP                 HTTP                    UDP
//!   ----------------------   -----------------   ---------------------   ------------------
//!   session cardinality      ω (endless stream)  1  (one req/resp,       0  (no session,
//!                                                    affine: Req ⊸ Resp)     datagrams)
//!   framing                  byte stream         HTTP messages           datagrams
//!   lifecycle                open → data* → close open → 1×req → 1×resp   none
//!                                                  → close
//!   ordering / reliability   ordered, reliable   ordered, reliable       unordered, lossy
//!                                                                         (semantics chosen
//!                                                                          when tunnelled)
//! ```
//!
//! Categorically they are one structure at three points of a single "session
//! cardinality" axis:
//!
//! - **TCP** = a bidirectional byte **stream** — the cofree stream / a long-lived
//!   process; cardinality **ω**.
//! - **HTTP** = the **affine** degeneration of TCP: exactly one exchange
//!   `Request ⊸ Response` (a use-once session); cardinality **1**.
//! - **UDP** = the **0-session** degeneration: `Datagram → [Datagram]`, a discrete
//!   transducer with no lifecycle; cardinality **0**.
//!
//! So adding UDP later is not a fourth subsystem — it is this axis taken to 0.
//!
//! # How it sits on the effect base (`backend::ext`)
//!
//! Pure/effect separation is preserved:
//!
//! - The **interpreter owns the live resources** (the `TcpStream` / `UdpSocket`), keyed
//!   by [`RelaySessionId`], in a resource table. These are non-purifiable OS handles and so
//!   live only in the imperative shell — never in a protocol's state.
//! - A protocol's **pure `step`** holds only session *metadata* (which `RelaySessionId` maps
//!   to which peer/service, framing state, counters) — never a live socket.
//! - Generic transport **effects** (run by the interpreter): stream ops
//!   `Connect` / `Write` / `Close`; datagram ops `Bind` / `SendTo`.
//! - Local reads / accepts **re-inject** [`Frame`]s as events (the event trace of the
//!   effect monad): the read task feeds `Data` / `Close` / `Datagram` back through the
//!   router → `step` → an `Effect::Send` over the virtual circuit.
//!
//! TCP / HTTP / UDP are then thin instances over this one relay: TCP uses the stream
//! ops with an ω session; HTTP adds "one request → one response → close" session logic
//! (expressible purely in `step`); UDP uses only the datagram ops with no session.

// The relay's imperative resource tables are private to the relay interpreter — not a public
// API. Reachable in-crate by the relay extension only.
pub(crate) mod engine;

use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;

use bytes::Bytes;
use rings_core::dht::Did;
use serde::Deserialize;
use serde::Serialize;

/// Maximum silence before an abandoned local socket/flow is reclaimed.
pub(crate) const RELAY_IDLE_TIMEOUT: Duration = Duration::from_secs(5 * 60);

/// Allocate one counter value without ever wrapping back to a live ABA-equivalent value.
pub(crate) fn allocate_non_reusing(counter: &AtomicU64) -> Option<u64> {
    counter
        .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
            value.checked_add(1)
        })
        .ok()
}

/// Identifier assigned by the opener to a relayed stream or datagram flow (a virtual circuit
/// ↔ local socket pairing). This relay identifier is distinct from delegated-signing identity.
///
/// TCP uses it for a connection; UDP uses it for a *flow* (a NAT-like mapping that
/// routes responses back to the right local client) — see [`TransportKind`].
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
pub struct RelaySessionId(pub u64);

/// Which end **opened** a relay session, from the perspective of the node holding the key.
///
/// Necessary because two nodes that simultaneously open a tunnel to each other both mint
/// `RelaySessionId(0)`: without an initiator, "the session I opened to peer B" and "the session B
/// opened to me" would collide on `(peer=B, namespace, session=0)`, and a wire `Data(0)`
/// would be ambiguous. The initiator splits the id space into two halves per `(peer,
/// namespace)`.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
pub enum Initiator {
    /// This node opened the session (a client tunnel).
    Local,
    /// The peer opened the session (this node is the server).
    Remote,
}

/// Result of applying one ordered peer-to-local transport effect without
/// waiting for backend backpressure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum EffectEnqueue {
    /// The effect was accepted by the current backend generation.
    Enqueued,
    /// The requested backend slot is already owned by a live generation; the
    /// duplicate effect is a no-op and pure state must preserve the session.
    AlreadyPresent,
    /// No backend generation exists; pure state must simply forget the key.
    Missing,
    /// The current backend generation failed or saturated; pure state must
    /// forget it and notify the peer with `Close`.
    Failed,
}

/// Result of trying to reserve one unique backend slot.
pub(crate) enum SlotRegistration<T> {
    /// The vacant slot was reserved and produced its backend-specific resource.
    Registered(T),
    /// A live backend generation already owns the slot and remains authoritative.
    AlreadyPresent,
    /// The slot could not be reserved because an internal resource failed.
    Failed,
}

/// A relay session's full identity — the unit used to key live sessions and to address
/// transport effects.
///
/// A bare [`RelaySessionId`] is **not** a valid address: the id on the wire is assigned by the
/// opener, so two ends can both pick `RelaySessionId(0)`. The key scopes a session by `(peer,
/// namespace, session, initiator)`, where `peer` is the **authenticated** other end
/// (`event.from`, the verified signer) and `initiator` records which end opened it. Because a
/// peer cannot forge `event.from`, it can only ever address sessions whose `peer` is itself
/// (owner rejection); and `initiator` keeps a peer's session distinct from one of ours that
/// happened to get the same id (bidirectional-open safety).
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct SessionKey {
    /// The authenticated remote end of the session (`event.from` for inbound frames).
    pub peer: Did,
    /// The transport namespace the session lives under (e.g. `tcp`, `udp`).
    pub namespace: String,
    /// The opener-assigned session id, unique only within `(peer, namespace, initiator)`.
    pub session: RelaySessionId,
    /// Which end opened the session (disambiguates colliding ids on simultaneous open).
    pub initiator: Initiator,
}

impl SessionKey {
    /// Build a delegatee key from its parts.
    pub fn new(
        peer: Did,
        namespace: impl Into<String>,
        session: RelaySessionId,
        initiator: Initiator,
    ) -> Self {
        Self {
            peer,
            namespace: namespace.into(),
            session,
            initiator,
        }
    }
}

/// Which local socket a relay session is backed by.
///
/// Both kinds share the same [`Frame`] vocabulary (`Open`/`Data`/`Close`); only the
/// socket differs. UDP is *flow*-based rather than truly sessionless because a relayed
/// datagram still needs a return path to the originating local client, so each flow
/// carries a [`RelaySessionId`] just like a TCP connection. `Data` preserves message
/// boundaries (one datagram per frame) for UDP.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum TransportKind {
    /// Connection-oriented byte stream.
    Tcp,
    /// Datagram flow (per-flow socket; message boundaries preserved per `Data`).
    Udp,
}

/// The relay's overlay wire message — the payload carried under a transport namespace.
///
/// One vocabulary for both kinds (TCP connections and UDP flows), differing only in how the
/// bytes travel:
///
/// ```text
///   TCP   Open(session, service) → Data(session, seq, bytes)* → Shutdown(session, sent)
///                                                                     → Close(session)
///   UDP   Open(session, service) → Datagram(session, bytes)*        → Close(session)
/// ```
///
/// Law (no silent gap). A TCP direction's `Data` frames carry `seq = 0, 1, 2, …` and its
/// `Shutdown` carries the number `sent` of them. The receiver writes bytes to its local socket
/// in `seq` order only, reordering at most [`REORDER_WINDOW`] frames ahead, so the local
/// stream is always a prefix of what the peer sent. A frame missing for [`REORDER_DEADLINE`] is
/// past the delivery bounds of its path, and one more than the window behind can never arrive
/// (the replay window refuses it), so either way the receiver resets the session: the peer gets
/// `Close`, and the local socket an abortive close. A `Shutdown` is applied only once every one
/// of its `sent` frames was written, so a lost last frame is a reset, never a clean end of
/// stream.
///
/// [`REORDER_WINDOW`]: rings_core::message::REORDER_WINDOW
/// [`REORDER_DEADLINE`]: rings_core::message::REORDER_DEADLINE
///
/// `Open` is always sent by the session's opener. `Data`/`Shutdown`/`Close` flow in both
/// directions over the *same* opener-assigned id, so they carry `from_opener` — whether the
/// **sender** of this frame opened the session. The receiver flips it to recover its own
/// [`Initiator`], so a peer's session never collides with one of ours sharing the same id.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Frame {
    /// Open a session/flow to a named local service (always sent by the opener).
    Open {
        /// Relay session identifier (assigned by the opener).
        session: RelaySessionId,
        /// Local service name to connect to.
        service: String,
    },
    /// A segment of a TCP session's byte stream, in its direction's `seq` order.
    Data {
        /// Relay session the bytes belong to.
        session: RelaySessionId,
        /// Whether the sender of this frame opened the session.
        from_opener: bool,
        /// The segment's position in its direction: the sender's count of earlier `Data`.
        seq: u64,
        /// Payload bytes.
        bytes: Bytes,
    },
    /// One datagram of a UDP flow; datagrams carry no order and may be lost.
    Datagram {
        /// Relay flow the datagram belongs to.
        session: RelaySessionId,
        /// Whether the sender of this frame opened the flow.
        from_opener: bool,
        /// The datagram.
        bytes: Bytes,
    },
    /// Half-close: the sender has no more `Data` this direction (a TCP FIN). The receiver shuts
    /// down its local write side once all `sent` segments are written, and keeps the reverse
    /// direction open. Ignored by UDP (datagram flows have no half-close).
    Shutdown {
        /// Relay session being half-closed.
        session: RelaySessionId,
        /// Whether the sender of this frame opened the session.
        from_opener: bool,
        /// How many `Data` frames the sender sent this direction.
        sent: u64,
    },
    /// Close a session/flow (full teardown, both directions).
    Close {
        /// Relay session to close.
        session: RelaySessionId,
        /// Whether the sender of this frame opened the session.
        from_opener: bool,
    },
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_non_reusing_allocator_is_total_at_exhaustion() {
        let counter = AtomicU64::new(u64::MAX - 1);
        assert_eq!(allocate_non_reusing(&counter), Some(u64::MAX - 1));
        assert_eq!(allocate_non_reusing(&counter), None);
        assert_eq!(counter.load(Ordering::Relaxed), u64::MAX);
    }
}