Skip to main content

rings_core/message/handlers/
mod.rs

1#![deny(missing_docs)]
2//! This module implemented message handler of rings network.
3
4use std::sync::Arc;
5
6use async_trait::async_trait;
7
8use super::effects::core_actor_steps;
9use super::effects::lower_dht_action_with_id;
10use super::effects::yield_core_actor_step;
11use super::effects::CoreEffect;
12use super::effects::CoreEffectInterpreter;
13use super::MessagePayload;
14use super::Principal;
15use crate::dht::topology::TopologyRemoval;
16use crate::dht::Did;
17use crate::dht::PeerRing;
18use crate::dht::PeerRingAction;
19use crate::error::Error;
20use crate::error::Result;
21use crate::swarm::callback::SwarmTransportCallback;
22use crate::swarm::transport::PendingConnectionAttempt;
23use crate::swarm::transport::SwarmTransport;
24use crate::utils::Clock;
25use crate::utils::SYSTEM_CLOCK;
26
27/// Operator and Handler for Connection
28pub mod connection;
29/// Operator and Handler for CustomMessage
30pub mod custom;
31/// Operator and Handler for E2E encrypted messages
32pub mod e2e;
33/// Relay inbox: holding messages for offline peers and draining one's own inbox.
34pub(crate) mod inbox;
35/// Handlers of relay custody: holder announcements and inbox fetches.
36mod relay_holder;
37/// Chain repair of relay carriers: one digest-set offer per chain neighbour and pass.
38pub(crate) mod relay_repair;
39/// Chain replication of relay holds: each member forwarding a hold to its next member.
40pub(crate) mod relay_replica;
41mod service_receipt;
42/// Operator and handler for DHT stabilization
43pub mod stabilization;
44/// Operator and Handler for Storage
45pub mod storage;
46/// Shared message-handler handle.
47///
48/// Clone law: cloning duplicates `Arc` handles to the same transport and DHT state. It never
49/// forks protocol state or transfers ownership.
50#[derive(Clone)]
51pub struct MessageHandler {
52    transport: Arc<SwarmTransport>,
53    dht: Arc<PeerRing>,
54}
55
56/// One payload as the logical stage hands it to a handler: the payload, the principal that
57/// delivered it to this node (load-bounds paper, Law 1), which every table a handler grows is
58/// charged to, and the injected [`Clock`] capability used by time-sensitive protocol decisions.
59#[derive(Clone, Copy, Debug)]
60pub struct HandlerContext<'a> {
61    /// The payload.
62    payload: &'a MessagePayload,
63    /// The edge that delivered it, or this node for a payload out of its own stores.
64    introducer: Principal,
65    /// Injected clock capability read by handler decisions.
66    clock: &'a dyn Clock,
67}
68
69/// Alias for [`HandlerContext`].
70pub type HandlerCtx<'a> = HandlerContext<'a>;
71
72impl<'a> HandlerContext<'a> {
73    /// `payload`, delivered by `introducer`, using the default [`SystemClock`](crate::utils::SystemClock).
74    pub const fn new(payload: &'a MessagePayload, introducer: Principal) -> Self {
75        Self {
76            payload,
77            introducer,
78            clock: &SYSTEM_CLOCK,
79        }
80    }
81
82    /// `payload`, delivered by `introducer`, reading protocol time from `clock`.
83    pub fn new_with_clock(
84        payload: &'a MessagePayload,
85        introducer: Principal,
86        clock: &'a dyn Clock,
87    ) -> Self {
88        Self {
89            payload,
90            introducer,
91            clock,
92        }
93    }
94
95    /// Return a copy of this context bound to `clock`.
96    pub fn with_clock(mut self, clock: &'a dyn Clock) -> Self {
97        self.clock = clock;
98        self
99    }
100
101    /// The principal that delivered the payload: a node-local accounting index, meaningless
102    /// outside this node.
103    pub(crate) const fn introducer(&self) -> Principal {
104        self.introducer
105    }
106
107    /// The payload.
108    pub const fn payload(&self) -> &'a MessagePayload {
109        self.payload
110    }
111
112    /// The injected [`Clock`] capability for this handler invocation.
113    pub fn clock(&self) -> &'a dyn Clock {
114        self.clock
115    }
116
117    /// Read the current Unix epoch timestamp in milliseconds from this context's [`Clock`].
118    pub fn now_ms(&self) -> u128 {
119        self.clock.now_ms()
120    }
121
122    /// Read the current Unix epoch timestamp in milliseconds as `i64` from this context's
123    /// [`Clock`].
124    pub fn now_ms_i64(&self) -> i64 {
125        self.clock.now_ms_i64()
126    }
127
128    /// Test builds: `payload` as delivered on no slot.
129    #[cfg(all(test, not(target_family = "wasm")))]
130    pub(crate) fn unbound_for_test(payload: &'a MessagePayload) -> Self {
131        Self::new(payload, Principal::Unbound)
132    }
133
134    /// Test builds: `payload` as delivered on no slot with an explicit `clock`.
135    #[cfg(all(test, not(target_family = "wasm")))]
136    #[allow(dead_code)]
137    pub(crate) fn unbound_with_clock_for_test(
138        payload: &'a MessagePayload,
139        clock: &'a dyn Clock,
140    ) -> Self {
141        Self::new_with_clock(payload, Principal::Unbound, clock)
142    }
143}
144
145/// Generic trait for handle message ,inspired by Actor-Model.
146#[cfg_attr(all(feature = "wasm", target_family = "wasm"), async_trait(?Send))]
147#[cfg_attr(not(all(feature = "wasm", target_family = "wasm")), async_trait)]
148pub trait HandleMsg<T> {
149    /// Message handler.
150    async fn handle(&self, context: &HandlerContext<'_>, msg: &T) -> Result<()>;
151}
152
153impl MessageHandler {
154    /// Create a new MessageHandler instance.
155    pub fn new(transport: Arc<SwarmTransport>) -> Self {
156        let dht = transport.dht.clone();
157        Self { transport, dht }
158    }
159
160    /// Build the callback handle passed into a newly created transport connection.
161    fn inner_callback(&self) -> SwarmTransportCallback {
162        SwarmTransportCallback::new(self.transport.clone())
163    }
164
165    /// Interpret already-lowered core effects against this handler's transport.
166    pub(crate) async fn run_effects<'payload>(
167        &self,
168        effects: impl IntoIterator<Item = CoreEffect<'payload>>,
169    ) -> Result<()> {
170        CoreEffectInterpreter::new(&self.transport)
171            .run_all(effects)
172            .await
173    }
174
175    /// Idempotently establish a DHT-driven transport connection.
176    ///
177    /// Self and already-connected peers are no-ops. `AlreadyConnected` is treated
178    /// as success so concurrent DHT actions racing through `MultiActions` do not
179    /// fail the whole handler.
180    pub(crate) async fn connect_dht_peer(&self, peer: Did) -> Result<()> {
181        self.run_effects([CoreEffect::connect_dht_peer(peer)]).await
182    }
183
184    pub(crate) async fn join_dht(&self, peer: Did) -> Result<()> {
185        // Default HMCC/Zave join path: maps to the JoinThenSync operation in
186        // the CorrectChord spec (see tests/default/test_dht_convergence.rs).
187        let Some(dht_ev) = self.transport.join_routable_peer(peer)? else {
188            return Err(Error::SwarmMissDidInTable(peer));
189        };
190        // The local join has completed. Follow-up convergence messages are
191        // best-effort: a peer can churn before these sends complete, and that
192        // must not suppress the application-level Connected event.
193        if let Err(e) = self.handle_dht_events(&dht_ev).await {
194            tracing::warn!("Failed to handle dht events while joining {peer}: {e:?}");
195        }
196        Ok(())
197    }
198
199    pub(crate) async fn admit_dht_attempt(
200        &self,
201        attempt: PendingConnectionAttempt,
202    ) -> Result<bool> {
203        let Some(dht_ev) = self.transport.commit_connection_admission(attempt)? else {
204            return Ok(false);
205        };
206        // Local topology and lifecycle state are committed together. Remote
207        // convergence remains best-effort because the peer may churn immediately.
208        if let Err(error) = self.handle_dht_events(&dht_ev).await {
209            tracing::warn!(
210                peer = %attempt.peer(),
211                generation = attempt.generation(),
212                error = ?error,
213                "failed to handle DHT events after connection admission"
214            );
215        }
216        Ok(true)
217    }
218
219    pub(crate) async fn leave_dht_attempt(&self, attempt: PendingConnectionAttempt) -> Result<()> {
220        let removal = match self.transport.disconnect_attempt(attempt).await? {
221            Some(removal) => Some(removal),
222            None => self.transport.remove_retired_attempt_topology(attempt)?,
223        };
224        // An admitted peer may outlive every slot that referenced it; only a
225        // removal that vacates a slot changes the placement view.
226        if removal.is_some_and(TopologyRemoval::storage_repair_due) {
227            self.transport.request_storage_repair();
228        }
229        Ok(())
230    }
231
232    #[cfg(all(test, not(all(feature = "wasm", target_family = "wasm"))))]
233    pub(crate) async fn leave_dht(&self, peer: Did) -> Result<()> {
234        if self.dht.remove(peer)?.storage_repair_due() {
235            self.transport.request_storage_repair();
236        }
237        Ok(())
238    }
239
240    /// Flatten a nested DHT action into its transport effects without executing them.
241    fn collect_dht_effects(
242        &self,
243        act: &PeerRingAction,
244        effects: &mut Vec<CoreEffect<'static>>,
245    ) -> Result<()> {
246        match act {
247            PeerRingAction::MultiActions(acts) => {
248                for act in acts {
249                    self.collect_dht_effects(act, effects)?;
250                }
251                Ok(())
252            }
253            act => {
254                if let Some(effect) = lower_dht_action_with_id(
255                    act,
256                    |did| self.transport.get_connection(did).is_some(),
257                    || self.transport.rng().next_uuid(),
258                )? {
259                    effects.push(effect);
260                }
261                Ok(())
262            }
263        }
264    }
265
266    /// Run connection effects first in local quality order, then all other effects.
267    ///
268    /// Multi-action DHT updates can contain several peers competing for pending
269    /// connection capacity. Splitting the phases makes that contention use the
270    /// same quality policy as direct connection plans while preserving the
271    /// original order of non-connection effects.
272    async fn run_prioritized_dht_effects(&self, effects: Vec<CoreEffect<'static>>) -> Result<()> {
273        // Peers in this list may allocate scarce pending-connection slots.
274        let mut connection_peers = Vec::new();
275        // Everything else stays in original effect order and runs after the
276        // connection phase has yielded between attempts.
277        let mut other_effects = Vec::new();
278        for effect in effects {
279            match effect {
280                CoreEffect::ConnectDhtPeer { peer } => {
281                    connection_peers.push(peer);
282                }
283                effect => other_effects.push(effect),
284            }
285        }
286
287        // Ordering is evaluated once for the batch so the later awaits do not
288        // reshuffle peers as measurements change.
289        let ordered_peers = self
290            .transport
291            .order_dht_candidates_by_quality(connection_peers)
292            .await;
293        for (peer, has_next) in core_actor_steps(ordered_peers) {
294            if let Err(e) = self.connect_dht_peer(peer).await {
295                tracing::error!("Failed on handle multi connection action: {e:?}");
296            }
297            if has_next || !other_effects.is_empty() {
298                yield_core_actor_step().await;
299            }
300        }
301
302        for (effect, has_next) in core_actor_steps(other_effects) {
303            if let Err(e) = self.run_effects([effect]).await {
304                tracing::error!("Failed on handle multi action: {e:?}");
305            }
306            if has_next {
307                yield_core_actor_step().await;
308            }
309        }
310
311        Ok(())
312    }
313
314    /// Lower and execute follow-up effects emitted by a DHT state transition.
315    pub(crate) async fn handle_dht_events(&self, act: &PeerRingAction) -> Result<()> {
316        if matches!(act, PeerRingAction::MultiActions(_)) {
317            let mut effects = Vec::new();
318            self.collect_dht_effects(act, &mut effects)?;
319            self.run_prioritized_dht_effects(effects).await
320        } else {
321            let effects = lower_dht_action_with_id(
322                act,
323                |did| self.transport.get_connection(did).is_some(),
324                || self.transport.rng().next_uuid(),
325            )?;
326            self.run_effects(effects).await
327        }
328    }
329}
330
331#[cfg(all(test, not(all(feature = "wasm", target_family = "wasm"))))]
332mod test_capabilities;