Skip to main content

hopr_protocol_session/socket/
state.rs

1use hopr_utils::network_types::crossfire_sink::CrossfireSink;
2
3use crate::{
4    errors::SessionError,
5    processing::types::FrameInspector,
6    protocol::{FrameAcknowledgements, FrameId, Segment, SegmentId, SegmentRequest, SeqIndicator, SessionMessage},
7};
8
9/// Components the `SessionSocket` exposes to a [`SocketState`].
10///
11/// This is the primary communication interface between the state and the socket.
12pub struct SocketComponents<const C: usize> {
13    /// Allows inspecting incomplete frames that are currently held by the socket.
14    ///
15    /// Some states might strictly require a frame inspector and may therefore
16    /// return an error in [`SocketState::run`] if not present.
17    pub inspector: Option<FrameInspector>,
18    /// Allows emitting control messages to the socket.
19    ///
20    /// It is a regular `SessionMessage` injected into the downstream.
21    /// Strict-capacity bounded channel — capacity never inflates regardless of clone count.
22    pub ctl_tx: CrossfireSink<SessionMessage<C>>,
23}
24
25/// Abstraction of the `SessionSocket` state.
26pub trait SocketState<const C: usize>: Send {
27    /// Gets ID of this Session.
28    fn session_id(&self) -> &str;
29
30    /// Starts the necessary processes inside the state.
31    /// Should be idempotent if called multiple times.
32    fn run(&mut self, components: SocketComponents<C>) -> Result<(), SessionError>;
33
34    /// Stops processes inside the state for the given direction.
35    fn stop(&mut self) -> Result<(), SessionError>;
36
37    /// Called when the Socket receives a new segment from Downstream.
38    /// When the error is returned, the incoming segment is not passed Upstream.
39    fn incoming_segment(&mut self, id: &SegmentId, ind: SeqIndicator) -> Result<(), SessionError>;
40
41    /// Called when [segment retransmission request](SegmentRequest) is received from Downstream.
42    fn incoming_retransmission_request(&mut self, request: SegmentRequest<C>) -> Result<(), SessionError>;
43
44    /// Called when an [acknowledgement of frames](FrameAcknowledgements) is received from Downstream.
45    fn incoming_acknowledged_frames(&mut self, ack: FrameAcknowledgements<C>) -> Result<(), SessionError>;
46
47    /// Called when a complete Frame has been finalized from segments received from Downstream.
48    fn frame_complete(&mut self, id: FrameId) -> Result<(), SessionError>;
49
50    /// Called when a complete Frame emitted to Upstream in-sequence.
51    fn frame_emitted(&mut self, id: FrameId) -> Result<(), SessionError>;
52
53    /// Called when a frame could not be completed from the segments received from Downstream.
54    fn frame_discarded(&mut self, id: FrameId) -> Result<(), SessionError>;
55
56    /// Called when a segment of a Frame was sent to the Downstream.
57    fn segment_sent(&mut self, segment: &Segment) -> Result<(), SessionError>;
58
59    /// Convenience method to dispatch a `SessionMessage` to one of the available handlers.
60    fn incoming_message(&mut self, message: &SessionMessage<C>) -> Result<(), SessionError> {
61        match &message {
62            SessionMessage::Segment(s) => self.incoming_segment(&s.id(), s.seq_flags),
63            SessionMessage::Request(r) => self.incoming_retransmission_request(r.clone()),
64            SessionMessage::Acknowledge(a) => self.incoming_acknowledged_frames(a.clone()),
65        }
66    }
67}
68
69/// Represents a stateless Session socket.
70///
71/// Does nothing by default, only logs warnings and events for tracing.
72#[derive(Clone)]
73pub struct Stateless<const C: usize>(String);
74
75impl<const C: usize> Stateless<C> {
76    pub(crate) fn new<I: std::fmt::Display>(session_id: I) -> Self {
77        Self(session_id.to_string())
78    }
79}
80
81impl<const C: usize> SocketState<C> for Stateless<C> {
82    fn session_id(&self) -> &str {
83        &self.0
84    }
85
86    fn run(&mut self, _: SocketComponents<C>) -> Result<(), SessionError> {
87        Ok(())
88    }
89
90    fn stop(&mut self) -> Result<(), SessionError> {
91        Ok(())
92    }
93
94    fn incoming_segment(&mut self, _: &SegmentId, _: SeqIndicator) -> Result<(), SessionError> {
95        Ok(())
96    }
97
98    fn incoming_retransmission_request(&mut self, _: SegmentRequest<C>) -> Result<(), SessionError> {
99        Ok(())
100    }
101
102    fn incoming_acknowledged_frames(&mut self, _: FrameAcknowledgements<C>) -> Result<(), SessionError> {
103        Ok(())
104    }
105
106    fn frame_complete(&mut self, _: FrameId) -> Result<(), SessionError> {
107        Ok(())
108    }
109
110    fn frame_emitted(&mut self, _: FrameId) -> Result<(), SessionError> {
111        Ok(())
112    }
113
114    fn frame_discarded(&mut self, _: FrameId) -> Result<(), SessionError> {
115        Ok(())
116    }
117
118    fn segment_sent(&mut self, _: &Segment) -> Result<(), SessionError> {
119        Ok(())
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use std::{collections::HashSet, time::Duration};
126
127    use anyhow::Context;
128    use futures::{AsyncReadExt, AsyncWriteExt};
129    use futures_time::future::FutureExt;
130
131    use super::*;
132    #[cfg(feature = "telemetry")]
133    use crate::socket::telemetry::NoopTracker;
134    use crate::{
135        MAX_SESSION_MTU, SessionSocket, SessionSocketConfig, session_frame_size, session_socket_mtu,
136        utils::test::{FaultyNetworkConfig, setup_alice_bob},
137    };
138
139    /// The production frame size over this module's deliberately small segment MTU.
140    const FRAME_SIZE: usize = session_frame_size::<MTU>(MAX_SESSION_MTU, (SeqIndicator::MAX + 1) as usize);
141
142    const MTU: usize = 1000;
143
144    mockall::mock! {
145        SockState {}
146        impl SocketState<MTU> for SockState {
147            fn session_id(&self) -> &str;
148            fn run(&mut self, components: SocketComponents<MTU>) -> Result<(), SessionError>;
149            fn stop(&mut self) -> Result<(), SessionError>;
150            fn incoming_segment(&mut self, id: &SegmentId, ind: SeqIndicator) -> Result<(), SessionError>;
151            fn incoming_retransmission_request(&mut self, request: SegmentRequest<MTU>) -> Result<(), SessionError>;
152            fn incoming_acknowledged_frames(&mut self, ack: FrameAcknowledgements<MTU>) -> Result<(), SessionError>;
153            fn frame_complete(&mut self, id: FrameId) -> Result<(), SessionError>;
154            fn frame_emitted(&mut self, id: FrameId) -> Result<(), SessionError>;
155            fn frame_discarded(&mut self, id: FrameId) -> Result<(), SessionError>;
156            fn segment_sent(&mut self, segment: &Segment) -> Result<(), SessionError>;
157        }
158    }
159
160    #[derive(Clone)]
161    struct CloneableMockState<'a>(std::sync::Arc<std::sync::Mutex<MockSockState>>, &'a str);
162
163    impl<'a> CloneableMockState<'a> {
164        pub fn new(state: MockSockState, id: &'a str) -> Self {
165            Self(std::sync::Arc::new(std::sync::Mutex::new(state)), id)
166        }
167    }
168
169    impl SocketState<MTU> for CloneableMockState<'_> {
170        fn session_id(&self) -> &str {
171            let _ = self.0.lock().unwrap().session_id();
172            self.1
173        }
174
175        fn run(&mut self, components: SocketComponents<MTU>) -> Result<(), SessionError> {
176            tracing::debug!(id = self.1, "run called");
177            self.0.lock().unwrap().run(components)
178        }
179
180        fn stop(&mut self) -> Result<(), SessionError> {
181            tracing::debug!(id = self.1, "stop called");
182            self.0.lock().unwrap().stop()
183        }
184
185        fn incoming_segment(&mut self, id: &SegmentId, ind: SeqIndicator) -> Result<(), SessionError> {
186            tracing::debug!(id = self.1, "incoming_segment called");
187            self.0.lock().unwrap().incoming_segment(id, ind)
188        }
189
190        fn incoming_retransmission_request(&mut self, request: SegmentRequest<MTU>) -> Result<(), SessionError> {
191            tracing::debug!(id = self.1, "incoming_retransmission_request called");
192            self.0.lock().unwrap().incoming_retransmission_request(request)
193        }
194
195        fn incoming_acknowledged_frames(&mut self, ack: FrameAcknowledgements<MTU>) -> Result<(), SessionError> {
196            tracing::debug!(id = self.1, "incoming_acknowledged_frames called");
197            self.0.lock().unwrap().incoming_acknowledged_frames(ack)
198        }
199
200        fn frame_complete(&mut self, id: FrameId) -> Result<(), SessionError> {
201            tracing::debug!(id = self.1, "frame_complete called");
202            self.0.lock().unwrap().frame_complete(id)
203        }
204
205        fn frame_emitted(&mut self, id: FrameId) -> Result<(), SessionError> {
206            tracing::debug!(id = self.1, "frame_received called");
207            self.0.lock().unwrap().frame_emitted(id)
208        }
209
210        fn frame_discarded(&mut self, id: FrameId) -> Result<(), SessionError> {
211            tracing::debug!(id = self.1, "frame_discarded called");
212            self.0.lock().unwrap().frame_discarded(id)
213        }
214
215        fn segment_sent(&mut self, segment: &Segment) -> Result<(), SessionError> {
216            tracing::debug!(id = self.1, "segment_sent called");
217            self.0.lock().unwrap().segment_sent(segment)
218        }
219    }
220
221    #[test_log::test(tokio::test)]
222    async fn session_socket_must_correctly_dispatch_segment_and_frame_state_events() -> anyhow::Result<()> {
223        const NUM_FRAMES: usize = 2;
224
225        const NUM_SEGMENTS: usize = NUM_FRAMES * FRAME_SIZE.div_ceil(session_socket_mtu::<MTU>());
226
227        let mut alice_seq = mockall::Sequence::new();
228        let mut alice_state = MockSockState::new();
229        alice_state.expect_session_id().return_const("alice".into());
230
231        alice_state
232            .expect_run()
233            .once()
234            .in_sequence(&mut alice_seq)
235            .return_once(|_| Ok::<_, SessionError>(()));
236        alice_state
237            .expect_segment_sent()
238            .times(NUM_SEGMENTS)
239            .in_sequence(&mut alice_seq)
240            .returning(|_| Ok::<_, SessionError>(()));
241        alice_state
242            .expect_stop()
243            .once()
244            .in_sequence(&mut alice_seq)
245            .return_once(|| Ok::<_, SessionError>(()));
246        alice_state
247            .expect_segment_sent() // terminating segment
248            .once()
249            .in_sequence(&mut alice_seq)
250            .return_once(|_| Ok::<_, SessionError>(()));
251        // PinnedDrop on SessionSocket calls state.stop() again on drop.
252        alice_state
253            .expect_stop()
254            .once()
255            .in_sequence(&mut alice_seq)
256            .return_once(|| Ok::<_, SessionError>(()));
257
258        let mut bob_seq = mockall::Sequence::new();
259        let mut bob_state = MockSockState::new();
260        bob_state.expect_session_id().return_const("bob".into());
261
262        bob_state
263            .expect_run()
264            .once()
265            .in_sequence(&mut bob_seq)
266            .return_once(|_| Ok::<_, SessionError>(()));
267        bob_state
268            .expect_incoming_segment()
269            .times(NUM_SEGMENTS - 1)
270            .in_sequence(&mut bob_seq)
271            .returning(|_, _| Ok::<_, SessionError>(()));
272        bob_state
273            .expect_frame_complete()
274            .once()
275            .in_sequence(&mut bob_seq)
276            .with(mockall::predicate::eq(2))
277            .returning(|_| Ok::<_, SessionError>(()));
278        bob_state
279            .expect_frame_discarded()
280            .once()
281            .in_sequence(&mut bob_seq)
282            .with(mockall::predicate::eq(1))
283            .returning(|_| Ok::<_, SessionError>(()));
284        bob_state
285            .expect_frame_emitted()
286            .once()
287            .in_sequence(&mut bob_seq)
288            .with(mockall::predicate::eq(2))
289            .returning(|_| Ok::<_, SessionError>(()));
290        bob_state
291            .expect_stop()
292            .once()
293            .in_sequence(&mut bob_seq)
294            .return_once(|| Ok::<_, SessionError>(()));
295        bob_state
296            .expect_segment_sent() // terminating segment
297            .once()
298            .in_sequence(&mut bob_seq)
299            .return_once(|_| Ok::<_, SessionError>(()));
300        // PinnedDrop on SessionSocket calls state.stop() again on drop.
301        bob_state
302            .expect_stop()
303            .once()
304            .in_sequence(&mut bob_seq)
305            .return_once(|| Ok::<_, SessionError>(()));
306
307        let (alice, bob) = setup_alice_bob::<MTU>(
308            FaultyNetworkConfig {
309                avg_delay: Duration::from_millis(10),
310                ids_to_drop: HashSet::from_iter([0_usize]),
311                ..Default::default()
312            },
313            None,
314            None,
315        );
316
317        let cfg = SessionSocketConfig {
318            frame_size: FRAME_SIZE,
319            frame_timeout: Duration::from_millis(55),
320            ..Default::default()
321        };
322
323        let mut alice_socket = SessionSocket::new(
324            alice,
325            CloneableMockState::new(alice_state, "alice"),
326            cfg,
327            None,
328            #[cfg(feature = "telemetry")]
329            NoopTracker,
330        )?;
331        let mut bob_socket = SessionSocket::new(
332            bob,
333            CloneableMockState::new(bob_state, "bob"),
334            cfg,
335            None,
336            #[cfg(feature = "telemetry")]
337            NoopTracker,
338        )?;
339
340        let alice_sent_data = hopr_types::crypto_random::random_bytes::<{ NUM_FRAMES * FRAME_SIZE }>();
341        alice_socket
342            .write_all(&alice_sent_data)
343            .timeout(futures_time::time::Duration::from_secs(2))
344            .await
345            .context("write_all timeout")??;
346        alice_socket.flush().await?;
347
348        // One entire frame is discarded
349        let mut bob_recv_data = [0u8; (NUM_FRAMES - 1) * FRAME_SIZE];
350        bob_socket
351            .read_exact(&mut bob_recv_data)
352            .timeout(futures_time::time::Duration::from_secs(2))
353            .await
354            .context("read_exact timeout")??;
355
356        tracing::debug!("stopping");
357        alice_socket.close().await?;
358        bob_socket.close().await?;
359
360        Ok(())
361    }
362}