Skip to main content

rings_core/message/handlers/
connection.rs

1use async_trait::async_trait;
2
3use crate::dht::types::Chord;
4use crate::dht::Did;
5use crate::dht::PeerRingAction;
6use crate::dht::TopoInfo;
7use crate::error::Error;
8use crate::error::Result;
9use crate::message::effects::CoreEffect;
10use crate::message::types::ConnectNodeReport;
11use crate::message::types::ConnectNodeSend;
12use crate::message::types::FindSuccessorReport;
13use crate::message::types::FindSuccessorSend;
14use crate::message::types::Message;
15use crate::message::types::QueryForTopoInfoSend;
16use crate::message::FindSuccessorReportHandler;
17use crate::message::FindSuccessorThen;
18use crate::message::HandleMsg;
19use crate::message::MessageHandler;
20
21/// Correlated topology-report admission and bounded candidate processing.
22///
23/// The submodule owns the request-token checks and connection-plan state
24/// machine used by topology reports. Keeping that flow separate prevents the
25/// general connection dispatcher from mutating DHT topology before transport
26/// evidence is current.
27mod topology_view;
28
29use topology_view::connect_successor_hint;
30
31use crate::message::handlers::HandlerContext;
32
33/// `result` with the expected drop of a connect-signaling reply whose recorded path names a hop
34/// this node lost the link to (#947) logged at debug and absorbed: the initiator's pending
35/// timeout covers it, and it is no fault of this node.
36fn drop_unlinked_return(result: Result<()>, context: &'static str) -> Result<()> {
37    match result {
38        Err(Error::RelayPathHopUnlinked { hop }) => {
39            tracing::debug!(%hop, context, "connect signaling reply dropped: return hop unlinked");
40            Ok(())
41        }
42        other => other,
43    }
44}
45
46/// `result` of answering `peer`'s offer with the refusal of the peer's slot (#1152) logged at
47/// debug and absorbed: `AlreadyConnected` is the slot's answer, an admitted connection or a
48/// handshake with `peer` still under way (`Law (Crossing offer)`), so no reply is owed; that
49/// handshake settles the edge, or the peer's next offer does once it ends.
50fn absorb_refused_offer(result: Result<()>, peer: Did) -> Result<()> {
51    match result {
52        Err(Error::AlreadyConnected) => {
53            tracing::debug!(%peer, "CONNECT_NODE offer refused: a handshake with the peer holds the slot");
54            Ok(())
55        }
56        other => other,
57    }
58}
59
60/// QueryForTopoInfoSend is direct message
61#[cfg_attr(all(feature = "wasm", target_family = "wasm"), async_trait(?Send))]
62#[cfg_attr(not(all(feature = "wasm", target_family = "wasm")), async_trait)]
63impl HandleMsg<QueryForTopoInfoSend> for MessageHandler {
64    async fn handle(&self, context: &HandlerContext<'_>, msg: &QueryForTopoInfoSend) -> Result<()> {
65        let ctx = context.payload();
66        if ctx.should_forward_from(self.dht.did) {
67            return self
68                .run_effects([CoreEffect::forward_payload(ctx, None)])
69                .await;
70        }
71        let info: TopoInfo = TopoInfo::try_from(self.dht.as_ref())?;
72        if msg.targets(self.dht.did) {
73            self.run_effects([CoreEffect::send_report_message(
74                ctx,
75                Message::QueryForTopoInfoReport(msg.resp(info)),
76            )])
77            .await?
78        }
79        Ok(())
80    }
81}
82
83#[cfg_attr(all(feature = "wasm", target_family = "wasm"), async_trait(?Send))]
84#[cfg_attr(not(all(feature = "wasm", target_family = "wasm")), async_trait)]
85impl HandleMsg<ConnectNodeSend> for MessageHandler {
86    async fn handle(&self, context: &HandlerContext<'_>, msg: &ConnectNodeSend) -> Result<()> {
87        let ctx = context.payload();
88        if !self.transport.accepts_connection_offer(msg) {
89            tracing::warn!(
90                local = %self.dht.did,
91                tx_id = %ctx.transaction.tx_id,
92                origin = %ctx.transaction.origin(),
93                relay_destination = %ctx.relay.destination,
94                transaction_destination = %ctx.transaction.destination,
95                mode = ?msg.dht_protocol_mode,
96                "CONNECT_NODE offer rejected by DHT protocol mismatch"
97            );
98            return Ok(());
99        }
100
101        if ctx.should_forward_from(self.dht.did) {
102            tracing::trace!(
103                local = %self.dht.did,
104                tx_id = %ctx.transaction.tx_id,
105                origin = %ctx.transaction.origin(),
106                next_hop = %ctx.relay.next_hop,
107                relay_destination = %ctx.relay.destination,
108                transaction_destination = %ctx.transaction.destination,
109                handshake_bytes = msg.handshake.len(),
110                "CONNECT_NODE offer forward"
111            );
112            drop_unlinked_return(
113                self.run_effects([CoreEffect::forward_payload(ctx, None)])
114                    .await,
115                "CONNECT_NODE forward",
116            )
117        } else {
118            let peer = ctx.transaction.origin();
119            tracing::trace!(
120                local = %self.dht.did,
121                peer = %peer,
122                tx_id = %ctx.transaction.tx_id,
123                handshake_bytes = msg.handshake.len(),
124                "CONNECT_NODE offer answer start"
125            );
126            // The reply, an answer or a counter-offer, retraces the offer's path (#947); the
127            // answer waits on ICE gathering, so it is negotiated and sent apart from this inbound
128            // event (inbound locality).
129            let answered = self
130                .transport
131                .answer_signaled_offer(self.inner_callback(), ctx, msg)
132                .await;
133            match absorb_refused_offer(
134                drop_unlinked_return(answered, "CONNECT_NODE offer reply"),
135                peer,
136            ) {
137                Ok(()) => {
138                    tracing::trace!(
139                        local = %self.dht.did,
140                        peer = %peer,
141                        tx_id = %ctx.transaction.tx_id,
142                        "CONNECT_NODE offer reply complete"
143                    );
144                    Ok(())
145                }
146                Err(error) => {
147                    tracing::warn!(
148                        local = %self.dht.did,
149                        peer = %peer,
150                        tx_id = %ctx.transaction.tx_id,
151                        error = ?error,
152                        "CONNECT_NODE offer answer failed"
153                    );
154                    Err(error)
155                }
156            }
157        }
158    }
159}
160
161#[cfg_attr(all(feature = "wasm", target_family = "wasm"), async_trait(?Send))]
162#[cfg_attr(not(all(feature = "wasm", target_family = "wasm")), async_trait)]
163impl HandleMsg<ConnectNodeReport> for MessageHandler {
164    async fn handle(&self, context: &HandlerContext<'_>, msg: &ConnectNodeReport) -> Result<()> {
165        let ctx = context.payload();
166        if ctx.should_forward_from(self.dht.did) {
167            tracing::trace!(
168                local = %self.dht.did,
169                tx_id = %ctx.transaction.tx_id,
170                origin = %ctx.transaction.origin(),
171                next_hop = %ctx.relay.next_hop,
172                relay_destination = %ctx.relay.destination,
173                transaction_destination = %ctx.transaction.destination,
174                handshake_bytes = msg.handshake.len(),
175                "CONNECT_NODE answer forward"
176            );
177            drop_unlinked_return(
178                self.run_effects([CoreEffect::forward_payload(ctx, None)])
179                    .await,
180                "CONNECT_NODE forward",
181            )
182        } else {
183            let peer = ctx.transaction.origin();
184            tracing::trace!(
185                local = %self.dht.did,
186                peer = %peer,
187                tx_id = %ctx.transaction.tx_id,
188                handshake_bytes = msg.handshake.len(),
189                "CONNECT_NODE answer accept start"
190            );
191            // The answer applies only to the generation whose offer left under this
192            // transaction (#947); a late one, for an offer since released, touches nothing.
193            match self.transport.handle_signaled_report(ctx, msg).await {
194                Ok(true) => {
195                    tracing::trace!(
196                        local = %self.dht.did,
197                        peer = %peer,
198                        tx_id = %ctx.transaction.tx_id,
199                        "CONNECT_NODE answer accept complete"
200                    );
201                    Ok(())
202                }
203                Ok(false) => {
204                    tracing::debug!(
205                        local = %self.dht.did,
206                        peer = %peer,
207                        tx_id = %ctx.transaction.tx_id,
208                        "CONNECT_NODE answer for no pending offer dropped"
209                    );
210                    Ok(())
211                }
212                Err(error) => drop_unlinked_return(Err(error), "CONNECT_NODE answer").inspect_err(
213                    |logged_error| {
214                        tracing::warn!(
215                            local = %self.dht.did,
216                            peer = %peer,
217                            tx_id = %ctx.transaction.tx_id,
218                            error = ?logged_error,
219                            "CONNECT_NODE answer accept failed"
220                        );
221                    },
222                ),
223            }
224        }
225    }
226}
227
228impl MessageHandler {
229    /// Resolve `msg` against the local Chord topology, consulting passive 1-hop
230    /// bridge hints (`TopologyState::bridged`) only for query-level resolution:
231    /// - `Connect` and `FixFingerTable` reports require a directly connected
232    ///   topology peer (`head`) so bootstrap `ConnectNodeSend` and finger table
233    ///   updates do not target an unreachable bridged peer.
234    /// - Application lookups (`FindSuccessorReportHandler::None`) report the
235    ///   closest bridged peer in `[msg.did, head)` when `msg` accepts a local
236    ///   successor.
237    /// - Strict lookups (`msg.strict && msg.did != self.dht.did`) forward
238    ///   directly to `msg.did` when `msg.did` is already connected or
239    ///   referenced in local topology, or route via the bridge's connected
240    ///   `via` successor when `msg.did` is recorded in `state.bridged`.
241    pub(crate) fn find_successor_for_query(
242        &self,
243        msg: &FindSuccessorSend,
244    ) -> Result<PeerRingAction> {
245        if !msg.accepts_local_successor(self.dht.did) {
246            if self.transport.get_connection(msg.did).is_some() {
247                return Ok(PeerRingAction::Some(msg.did));
248            }
249            let state = self.dht.topology_state()?;
250            if state.references(msg.did) {
251                return Ok(PeerRingAction::Some(msg.did));
252            }
253            if let Some(via) = state.bridged.get(&msg.did).copied().filter(|&via| {
254                via != state.local
255                    && state.references(via)
256                    && self.transport.get_connection(via).is_some()
257            }) {
258                return Ok(PeerRingAction::RemoteAction(
259                    via,
260                    crate::dht::PeerRingRemoteAction::FindSuccessor(msg.did),
261                ));
262            }
263            return self.dht.find_successor(msg.did);
264        }
265
266        let action = self.dht.find_successor(msg.did)?;
267        let PeerRingAction::Some(head) = action else {
268            return Ok(action);
269        };
270        if head == self.dht.did || msg.did == self.dht.did {
271            return Ok(PeerRingAction::Some(head));
272        }
273        let state = self.dht.topology_state()?;
274        let target = crate::dht::topology::dist(state.local, msg.did);
275        let head_dist = crate::dht::topology::dist(state.local, head);
276        let bridged = state
277            .bridged
278            .iter()
279            .filter(|(&peer, &via)| {
280                peer != state.local
281                    && via != state.local
282                    && state.references(via)
283                    && self.transport.get_connection(via).is_some()
284                    && !state.references(peer)
285            })
286            .filter_map(|(&peer, &via)| {
287                let peer_dist = crate::dht::topology::dist(state.local, peer);
288                (target <= peer_dist && peer_dist < head_dist).then_some((peer_dist, peer, via))
289            })
290            .min_by(|(dist_a, _, _), (dist_b, _, _)| dist_a.cmp(dist_b))
291            .map(|(_, peer, via)| (peer, via));
292        let Some((bridged_peer, _via)) = bridged else {
293            return Ok(PeerRingAction::Some(head));
294        };
295        let FindSuccessorThen::Report(handler) = &msg.then;
296        match handler {
297            FindSuccessorReportHandler::None => Ok(PeerRingAction::Some(bridged_peer)),
298            FindSuccessorReportHandler::Connect { .. }
299            | FindSuccessorReportHandler::FixFingerTable { .. } => {
300                if self.transport.get_connection(bridged_peer).is_some() {
301                    Ok(PeerRingAction::Some(bridged_peer))
302                } else {
303                    Ok(PeerRingAction::Some(head))
304                }
305            }
306        }
307    }
308}
309
310#[cfg_attr(all(feature = "wasm", target_family = "wasm"), async_trait(?Send))]
311#[cfg_attr(not(all(feature = "wasm", target_family = "wasm")), async_trait)]
312impl HandleMsg<FindSuccessorSend> for MessageHandler {
313    async fn handle(&self, context: &HandlerContext<'_>, msg: &FindSuccessorSend) -> Result<()> {
314        let ctx = context.payload();
315        match self.find_successor_for_query(msg)? {
316            PeerRingAction::Some(did) => {
317                if msg.accepts_local_successor(self.dht.did) {
318                    match &msg.then {
319                        FindSuccessorThen::Report(handler) => {
320                            let did = match handler {
321                                FindSuccessorReportHandler::Connect { .. } => {
322                                    connect_successor_hint(
323                                        self.dht.as_ref(),
324                                        ctx.transaction.origin(),
325                                        did,
326                                    )?
327                                }
328                                FindSuccessorReportHandler::FixFingerTable { .. }
329                                    if did != self.dht.did
330                                        && self.transport.get_connection(did).is_none() =>
331                                {
332                                    self.dht
333                                        .successors()
334                                        .list()?
335                                        .into_iter()
336                                        .find(|succ| self.transport.get_connection(*succ).is_some())
337                                        .unwrap_or(did)
338                                }
339                                _ => did,
340                            };
341                            self.run_effects([CoreEffect::send_report_message(
342                                ctx,
343                                Message::FindSuccessorReport(FindSuccessorReport {
344                                    did,
345                                    handler: handler.clone(),
346                                }),
347                            )])
348                            .await
349                        }
350                    }
351                } else {
352                    self.run_effects([CoreEffect::reset_destination(ctx, did)])
353                        .await
354                }
355            }
356            PeerRingAction::RemoteAction(next, _) => {
357                self.run_effects([CoreEffect::reset_destination(ctx, next)])
358                    .await
359            }
360            act => Err(Error::unexpected_peer_ring_action(act)),
361        }
362    }
363}
364
365#[cfg_attr(all(feature = "wasm", target_family = "wasm"), async_trait(?Send))]
366#[cfg_attr(not(all(feature = "wasm", target_family = "wasm")), async_trait)]
367impl HandleMsg<FindSuccessorReport> for MessageHandler {
368    async fn handle(&self, context: &HandlerContext<'_>, msg: &FindSuccessorReport) -> Result<()> {
369        let ctx = context.payload();
370        let effect = if ctx.should_forward_from(self.dht.did) {
371            CoreEffect::forward_payload(ctx, None)
372        } else {
373            let reports_remote = msg.reports_remote_successor(self.dht.did);
374            match &msg.handler {
375                FindSuccessorReportHandler::FixFingerTable { request } => {
376                    CoreEffect::admit_finger_candidate(msg.did, *request, reports_remote)
377                }
378                FindSuccessorReportHandler::Connect { request_id } => {
379                    CoreEffect::claim_connect_candidate(msg.did, *request_id, reports_remote)
380                }
381                // An application lookup: resolve the handle the application awaits. A report no
382                // live lookup awaits is unsolicited and dropped here; the application never sees it.
383                FindSuccessorReportHandler::None => {
384                    CoreEffect::answer_application_lookup(ctx.transaction.tx_id, msg.did)
385                }
386            }
387        };
388        self.run_effects([effect]).await
389    }
390}
391
392#[cfg(not(all(feature = "wasm", target_family = "wasm")))]
393#[cfg(test)]
394mod test_connection;