Skip to main content

rings_core/message/handlers/
custom.rs

1use async_trait::async_trait;
2
3use crate::dht::Did;
4use crate::error::Result;
5use crate::message::effects::CoreEffect;
6use crate::message::handlers::HandlerContext;
7use crate::message::types::CustomMessage;
8use crate::message::HandleMsg;
9use crate::message::MessageHandler;
10use crate::message::MessagePayload;
11
12/// How this node stands to a message's destination.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub(crate) enum Reachability {
15    /// The destination can be reached, or is somebody else's to reach: forward.
16    Reachable,
17    /// This node is responsible for the destination's position and it has no connection: hold.
18    Offline,
19}
20
21/// The effect an application message requires at `local`.
22///
23/// Post: a message for `local` needs no effect; a message for a destination this node is
24/// responsible for but cannot reach is held in that destination's relay inbox; every other
25/// message is forwarded one hop further along its Chord route.
26pub(crate) fn custom_message_effects<'payload>(
27    local: Did,
28    ctx: &'payload MessagePayload,
29    destination: Reachability,
30    now_ms: u128,
31) -> Option<CoreEffect<'payload>> {
32    if !ctx.should_forward_from(local) {
33        None
34    } else {
35        Some(match destination {
36            Reachability::Offline => CoreEffect::hold_for_offline_destination_at(ctx, now_ms),
37            Reachability::Reachable => CoreEffect::forward_payload(ctx, None),
38        })
39    }
40}
41
42#[cfg_attr(all(feature = "wasm", target_family = "wasm"), async_trait(?Send))]
43#[cfg_attr(not(all(feature = "wasm", target_family = "wasm")), async_trait)]
44impl HandleMsg<CustomMessage> for MessageHandler {
45    async fn handle(&self, context: &HandlerContext<'_>, _: &CustomMessage) -> Result<()> {
46        let ctx = context.payload();
47        let destination = self.destination_reachability(ctx.transaction.destination)?;
48        self.run_effects(custom_message_effects(
49            self.dht.did,
50            ctx,
51            destination,
52            context.now_ms(),
53        ))
54        .await
55    }
56}
57
58#[cfg(not(all(feature = "wasm", target_family = "wasm")))]
59#[cfg(test)]
60mod tests {
61    use super::*;
62    use crate::delegation::DelegateeKey;
63    use crate::ecc::SecretKey;
64    use crate::error::Error;
65    use crate::message::HopBudget;
66    use crate::message::Message;
67    use crate::message::MessagePayload;
68    use crate::message::MessageSigner;
69    use crate::tests::default::assert_no_more_msg;
70    use crate::tests::default::prepare_node;
71    use crate::tests::default::wait_for_msgs;
72    use crate::tests::default::Node;
73    use crate::tests::manually_establish_connection;
74    use crate::tests::TEST_NETWORK_ID;
75
76    /// An application payload from a stranger, addressed through `relay` to `destination`.
77    fn payload_through(
78        relay: &Node,
79        destination: &Node,
80        hop_budget: HopBudget,
81    ) -> Result<(MessagePayload, CustomMessage)> {
82        let origin = DelegateeKey::new_with_seckey(&SecretKey::random())?;
83        let message = CustomMessage(b"through".to_vec());
84        let mut payload = MessagePayload::new_send(
85            Message::CustomMessage(message.clone()),
86            MessageSigner::new(&origin, TEST_NETWORK_ID),
87            relay.did(),
88            destination.did(),
89        )?;
90        payload.relay.hop_budget = hop_budget;
91        Ok((payload, message))
92    }
93
94    /// A hop drops a payload whose carrier has no forward left, with the typed error, and the
95    /// destination never sees it; the same payload with one forward left is forwarded and
96    /// arrives with its budget spent.
97    #[tokio::test]
98    async fn test_forwarding_observes_the_hop_budget() -> Result<()> {
99        let relay = prepare_node(SecretKey::random()).await;
100        let destination = prepare_node(SecretKey::random()).await;
101        manually_establish_connection(&relay.swarm, &destination.swarm).await;
102        wait_for_msgs([&relay, &destination]).await;
103        assert_no_more_msg([&relay, &destination]).await;
104        let handler = MessageHandler::new(relay.swarm.transport.clone());
105
106        let (exhausted, message) = payload_through(&relay, &destination, HopBudget::EXHAUSTED)?;
107        assert!(matches!(
108            handler
109                .handle(&HandlerContext::unbound_for_test(&exhausted), &message)
110                .await,
111            Err(Error::RelayHopBudgetExhausted)
112        ));
113        assert_no_more_msg([&destination]).await;
114
115        let last_forward = HopBudget::try_from(1)?;
116        let (forwardable, message) = payload_through(&relay, &destination, last_forward)?;
117        handler
118            .handle(&HandlerContext::unbound_for_test(&forwardable), &message)
119            .await?;
120        let received = destination
121            .listen_once()
122            .await
123            .ok_or_else(|| Error::InvalidMessage("forwarded payload not delivered".to_string()))?;
124
125        assert_eq!(received.transaction, forwardable.transaction);
126        assert_eq!(received.relay.next_hop, destination.did());
127        assert_eq!(received.relay.destination, destination.did());
128        assert_eq!(received.relay.hop_budget, HopBudget::EXHAUSTED);
129        Ok(())
130    }
131}