rings_node/extension/ext/protocol.rs
1//! The pure core of an extension: the [`Protocol`] trait authors implement, its typed
2//! step algebra ([`Transition`]), and the decode boundary ([`Wire`] → `Event`).
3//!
4//! An extension owns **its own** effect algebra (`Protocol::Effect`) — the core defines
5//! no global `Effect` enum. Effects are interpreted by the extension's own
6//! [`Interpret`](super::Interpret) shell, which is handed a namespace-scoped capability
7//! ([`Scope`](super::Scope)) — `send`/`inject` confined to its own namespace. This is what
8//! keeps the effect set from becoming a global command bus: a new extension brings its own
9//! effects and its own interpreter without ever touching the core.
10
11use rings_core::dht::Did;
12use rings_core::swarm::application::SwarmEvent;
13use rings_runtime::MaybeSendSync;
14
15/// The raw boundary input handed to [`Protocol::decode`]: an inbound message's authenticated
16/// sender, this node's own did, and the opaque payload bytes. `decode` turns this into the
17/// protocol's typed `Event` (or rejects it).
18///
19/// `from == me` marks a **self re-injected** message (a local command or an effect's result
20/// fed back into the router); any other `from` is a network message from an authenticated
21/// peer (a peer cannot forge `from`).
22pub struct Wire<'a> {
23 /// Authenticated sender of the message.
24 pub from: Did,
25 /// This node's own did (so `decode` can tell self-injection from a peer).
26 pub me: Did,
27 /// Opaque payload bytes; the protocol's own codec decides how to read them.
28 pub payload: &'a [u8],
29}
30
31/// The explicit result of a failed [`Protocol::decode`]: the input is malformed or not for
32/// this protocol. The router drops it (a defined no-op) instead of the pure step silently
33/// returning an unchanged state — so "valid no-op" and "undecodable input" are
34/// distinguishable.
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct Reject(pub String);
37
38/// Read-only state carrier passed *into* a step: the protocol's current state `S` plus
39/// read-only node facts. The state is borrowed; a step returns the next state in its
40/// [`Transition`] rather than mutating in place.
41pub struct Ctx<'a, S> {
42 /// This node's DID.
43 pub did: Did,
44 /// Current protocol state (read-only here).
45 pub state: &'a S,
46}
47
48/// The output of a step: the next state and the protocol's own effects to run.
49/// `Transition (S, E) ≅ (S, [E])` — the Writer-over-State pair, now parameterized by the
50/// protocol's private effect type `E`. `PartialEq`/`Eq` are derived (when `S`/`E` are) so
51/// tests can compare whole transitions.
52#[derive(Clone, Debug, PartialEq, Eq)]
53pub struct Transition<S, E> {
54 /// Next state.
55 pub state: S,
56 /// Effects to run, in order.
57 pub effects: Vec<E>,
58}
59
60impl<S, E> Transition<S, E> {
61 /// A pure transition with no effects: `pure s = (s, ε)`.
62 pub fn pure(state: S) -> Self {
63 Self {
64 state,
65 effects: Vec::new(),
66 }
67 }
68
69 /// A transition with effects.
70 pub fn with(state: S, effects: Vec<E>) -> Self {
71 Self { state, effects }
72 }
73}
74
75/// A protocol: a `namespace`, an initial state, a **decode boundary**, and a state
76/// transition that is pure **by contract**.
77///
78/// ```text
79/// init : → S
80/// decode : Wire ⇀ Event (partial: may Reject)
81/// step : (Ctx S, Event) → Transition (S, Effect)
82/// ```
83///
84/// `decode` is the single place raw bytes become a typed `Event`; a malformed/foreign
85/// message is an explicit [`Reject`], not a silent no-op in `step`. `step` is then total
86/// over well-typed events and pure: no IO, no clocks, no globals. All side effects are
87/// described as values of the protocol's **own** `Effect` type and performed by the
88/// extension's [`Interpret`](super::Interpret) shell.
89pub trait Protocol {
90 /// Protocol-private state, owned by the runtime and threaded through `step`.
91 type State;
92 /// The protocol's typed input, produced by [`decode`](Protocol::decode).
93 type Event: MaybeSendSync;
94 /// The protocol's **own** effect algebra (the core defines no global effect enum).
95 type Effect;
96
97 /// The namespace this protocol is registered and routed under.
98 fn namespace(&self) -> &str;
99
100 /// Initial state. `init : 1 → S`.
101 fn init(&self) -> Self::State;
102
103 /// Decode the boundary into a typed event, or [`Reject`] it. `decode : Wire ⇀ Event`.
104 fn decode(&self, wire: Wire<'_>) -> Result<Self::Event, Reject>;
105
106 /// Pure transition. `step : (Ctx S, Event) → Transition (S, Effect)`.
107 fn step(
108 &self,
109 ctx: Ctx<'_, Self::State>,
110 event: Self::Event,
111 ) -> Transition<Self::State, Self::Effect>;
112
113 /// Whether this protocol delegates its admission: it admits its own direct-edge traffic,
114 /// per sending neighbour, before its own processing and after core's admission (#888).
115 ///
116 /// Read once when the protocol is registered. For this namespace's traffic from the
117 /// authenticated neighbour that originated it, core then skips the per-origin message-count
118 /// limit; the per-origin byte bucket and the record bound still apply, and relayed or
119 /// foreign-origin traffic keeps the enforced limits. `false`, the default, delegates nothing.
120 ///
121 /// Delegation is trusted local configuration: a protocol that returns `true` must enforce
122 /// its own per-neighbour admission.
123 fn delegates_admission(&self) -> bool {
124 false
125 }
126
127 /// Whether this protocol delegates its replay (#1081): it acts on each of its payloads at
128 /// most once, by its own replay key, across connections, link generations, envelopes and
129 /// restarts of this node (Obligation R of durable-records).
130 ///
131 /// Read once when the protocol is registered. For this namespace's traffic from the
132 /// authenticated neighbour that originated it, core then admits each transaction in a
133 /// volatile replay window of the link it arrived on, instead of its durable window, and
134 /// writes nothing; relayed or foreign-origin traffic keeps the durable window. `false`, the
135 /// default, delegates nothing.
136 ///
137 /// Delegation is trusted local configuration: a protocol that returns `true` must keep R.
138 fn delegates_replay(&self) -> bool {
139 false
140 }
141
142 /// The event this protocol makes of `fact` about a link, or `None` when the protocol keeps
143 /// no state about links. `link_fact : LinkFact ⇀ Event`.
144 ///
145 /// A fact reaches the protocol in its namespace's queue, in order with the envelopes around
146 /// it, and is never dropped (#963, #966).
147 fn link_fact(&self, _fact: LinkFact) -> Option<Self::Event> {
148 None
149 }
150}
151
152/// A fact about this node's link to one peer, which the router delivers to a protocol beside
153/// its envelopes ([`Protocol::link_fact`]).
154#[derive(Clone, Copy, Debug, Eq, PartialEq)]
155pub enum LinkFact {
156 /// `peer`'s link generation was admitted: it is up until the `Retired(peer)` after it. Per
157 /// peer the queue carries `Admitted` and `Retired` alternately, in the order core decided
158 /// them, so a protocol keying state by admitted link (the onion data plane, #843) follows
159 /// core's links without reading them.
160 Admitted(Did),
161 /// `peer`'s link generation retired: nothing more crosses it (#963).
162 Retired(Did),
163 /// The namespace's queue (#966), or the core's application inbox (#969), dropped a message
164 /// from `peer`, an admitted peer, for want of room: the link stays up, but a message `peer`
165 /// sent over it was lost here. A drop by the core's inbox names no namespace, so every
166 /// namespace is told.
167 ///
168 /// Several drops before the protocol reads the fact are told once: at most one such fact per
169 /// peer waits in a namespace's queue.
170 Dropped(Did),
171}
172
173impl LinkFact {
174 /// The link fact `event` states, or `None` for an event about no link.
175 /// `of : SwarmEvent ⇀ LinkFact`, a bijection on the link events, `of(e).peer()` being the
176 /// peer `e` names.
177 pub const fn of(event: &SwarmEvent) -> Option<Self> {
178 match *event {
179 SwarmEvent::PeerAdmitted { peer } => Some(Self::Admitted(peer)),
180 SwarmEvent::PeerRetired { peer } => Some(Self::Retired(peer)),
181 SwarmEvent::MessageDropped { peer } => Some(Self::Dropped(peer)),
182 _ => None,
183 }
184 }
185
186 /// The peer at the other end of the link this fact is about.
187 pub const fn peer(self) -> Did {
188 match self {
189 Self::Admitted(peer) | Self::Retired(peer) | Self::Dropped(peer) => peer,
190 }
191 }
192}