rings-node 1.0.0-pre.8

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.
Documentation
//! The pure core of an extension: the [`Protocol`] trait authors implement, its typed
//! step algebra ([`Transition`]), and the decode boundary ([`Wire`] → `Event`).
//!
//! An extension owns **its own** effect algebra (`Protocol::Effect`) — the core defines
//! no global `Effect` enum. Effects are interpreted by the extension's own
//! [`Interpret`](super::Interpret) shell, which is handed a namespace-scoped capability
//! ([`Scope`](super::Scope)) — `send`/`inject` confined to its own namespace. This is what
//! keeps the effect set from becoming a global command bus: a new extension brings its own
//! effects and its own interpreter without ever touching the core.

use rings_core::dht::Did;
use rings_core::swarm::application::SwarmEvent;
use rings_runtime::MaybeSendSync;

/// The raw boundary input handed to [`Protocol::decode`]: an inbound message's authenticated
/// sender, this node's own did, and the opaque payload bytes. `decode` turns this into the
/// protocol's typed `Event` (or rejects it).
///
/// `from == me` marks a **self re-injected** message (a local command or an effect's result
/// fed back into the router); any other `from` is a network message from an authenticated
/// peer (a peer cannot forge `from`).
pub struct Wire<'a> {
    /// Authenticated sender of the message.
    pub from: Did,
    /// This node's own did (so `decode` can tell self-injection from a peer).
    pub me: Did,
    /// Opaque payload bytes; the protocol's own codec decides how to read them.
    pub payload: &'a [u8],
}

/// The explicit result of a failed [`Protocol::decode`]: the input is malformed or not for
/// this protocol. The router drops it (a defined no-op) instead of the pure step silently
/// returning an unchanged state — so "valid no-op" and "undecodable input" are
/// distinguishable.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Reject(pub String);

/// Read-only state carrier passed *into* a step: the protocol's current state `S` plus
/// read-only node facts. The state is borrowed; a step returns the next state in its
/// [`Transition`] rather than mutating in place.
pub struct Ctx<'a, S> {
    /// This node's DID.
    pub did: Did,
    /// Current protocol state (read-only here).
    pub state: &'a S,
}

/// The output of a step: the next state and the protocol's own effects to run.
/// `Transition (S, E) ≅ (S, [E])` — the Writer-over-State pair, now parameterized by the
/// protocol's private effect type `E`. `PartialEq`/`Eq` are derived (when `S`/`E` are) so
/// tests can compare whole transitions.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Transition<S, E> {
    /// Next state.
    pub state: S,
    /// Effects to run, in order.
    pub effects: Vec<E>,
}

impl<S, E> Transition<S, E> {
    /// A pure transition with no effects: `pure s = (s, ε)`.
    pub fn pure(state: S) -> Self {
        Self {
            state,
            effects: Vec::new(),
        }
    }

    /// A transition with effects.
    pub fn with(state: S, effects: Vec<E>) -> Self {
        Self { state, effects }
    }
}

/// A protocol: a `namespace`, an initial state, a **decode boundary**, and a state
/// transition that is pure **by contract**.
///
/// ```text
///   init   :              → S
///   decode : Wire        ⇀ Event            (partial: may Reject)
///   step   : (Ctx S, Event) → Transition (S, Effect)
/// ```
///
/// `decode` is the single place raw bytes become a typed `Event`; a malformed/foreign
/// message is an explicit [`Reject`], not a silent no-op in `step`. `step` is then total
/// over well-typed events and pure: no IO, no clocks, no globals. All side effects are
/// described as values of the protocol's **own** `Effect` type and performed by the
/// extension's [`Interpret`](super::Interpret) shell.
pub trait Protocol {
    /// Protocol-private state, owned by the runtime and threaded through `step`.
    type State;
    /// The protocol's typed input, produced by [`decode`](Protocol::decode).
    type Event: MaybeSendSync;
    /// The protocol's **own** effect algebra (the core defines no global effect enum).
    type Effect;

    /// The namespace this protocol is registered and routed under.
    fn namespace(&self) -> &str;

    /// Initial state. `init : 1 → S`.
    fn init(&self) -> Self::State;

    /// Decode the boundary into a typed event, or [`Reject`] it. `decode : Wire ⇀ Event`.
    fn decode(&self, wire: Wire<'_>) -> Result<Self::Event, Reject>;

    /// Pure transition. `step : (Ctx S, Event) → Transition (S, Effect)`.
    fn step(
        &self,
        ctx: Ctx<'_, Self::State>,
        event: Self::Event,
    ) -> Transition<Self::State, Self::Effect>;

    /// Whether this protocol delegates its admission: it admits its own direct-edge traffic,
    /// per sending neighbour, before its own processing and after core's admission (#888).
    ///
    /// Read once when the protocol is registered. For this namespace's traffic from the
    /// authenticated neighbour that originated it, core then skips the per-origin message-count
    /// limit; the per-origin byte bucket and the record bound still apply, and relayed or
    /// foreign-origin traffic keeps the enforced limits. `false`, the default, delegates nothing.
    ///
    /// Delegation is trusted local configuration: a protocol that returns `true` must enforce
    /// its own per-neighbour admission.
    fn delegates_admission(&self) -> bool {
        false
    }

    /// Whether this protocol delegates its replay (#1081): it acts on each of its payloads at
    /// most once, by its own replay key, across connections, link generations, envelopes and
    /// restarts of this node (Obligation R of durable-records).
    ///
    /// Read once when the protocol is registered. For this namespace's traffic from the
    /// authenticated neighbour that originated it, core then admits each transaction in a
    /// volatile replay window of the link it arrived on, instead of its durable window, and
    /// writes nothing; relayed or foreign-origin traffic keeps the durable window. `false`, the
    /// default, delegates nothing.
    ///
    /// Delegation is trusted local configuration: a protocol that returns `true` must keep R.
    fn delegates_replay(&self) -> bool {
        false
    }

    /// The event this protocol makes of `fact` about a link, or `None` when the protocol keeps
    /// no state about links. `link_fact : LinkFact ⇀ Event`.
    ///
    /// A fact reaches the protocol in its namespace's queue, in order with the envelopes around
    /// it, and is never dropped (#963, #966).
    fn link_fact(&self, _fact: LinkFact) -> Option<Self::Event> {
        None
    }
}

/// A fact about this node's link to one peer, which the router delivers to a protocol beside
/// its envelopes ([`Protocol::link_fact`]).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LinkFact {
    /// `peer`'s link generation was admitted: it is up until the `Retired(peer)` after it. Per
    /// peer the queue carries `Admitted` and `Retired` alternately, in the order core decided
    /// them, so a protocol keying state by admitted link (the onion data plane, #843) follows
    /// core's links without reading them.
    Admitted(Did),
    /// `peer`'s link generation retired: nothing more crosses it (#963).
    Retired(Did),
    /// The namespace's queue (#966), or the core's application inbox (#969), dropped a message
    /// from `peer`, an admitted peer, for want of room: the link stays up, but a message `peer`
    /// sent over it was lost here. A drop by the core's inbox names no namespace, so every
    /// namespace is told.
    ///
    /// Several drops before the protocol reads the fact are told once: at most one such fact per
    /// peer waits in a namespace's queue.
    Dropped(Did),
}

impl LinkFact {
    /// The link fact `event` states, or `None` for an event about no link.
    /// `of : SwarmEvent ⇀ LinkFact`, a bijection on the link events, `of(e).peer()` being the
    /// peer `e` names.
    pub const fn of(event: &SwarmEvent) -> Option<Self> {
        match *event {
            SwarmEvent::PeerAdmitted { peer } => Some(Self::Admitted(peer)),
            SwarmEvent::PeerRetired { peer } => Some(Self::Retired(peer)),
            SwarmEvent::MessageDropped { peer } => Some(Self::Dropped(peer)),
            _ => None,
        }
    }

    /// The peer at the other end of the link this fact is about.
    pub const fn peer(self) -> Did {
        match self {
            Self::Admitted(peer) | Self::Retired(peer) | Self::Dropped(peer) => peer,
        }
    }
}