Skip to main content

hopr_protocol_session/protocol/
messages.rs

1//! Contains definitions of Session protocol messages.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use bitvec::{BitArr, field::BitField, prelude::Msb0};
6
7use crate::{
8    errors::SessionError,
9    protocol::{FrameId, SegmentId, SeqNum, SessionMessage},
10};
11
12/// Holds the Segment Retransmission Request message.
13///
14/// That is an ordered map of frame IDs and a bitmap of missing segments in each frame.
15/// The bitmap can cover up a request for up to [`SegmentRequest::MAX_ENTRIES`] segments.
16#[derive(Debug, Clone, PartialEq, Eq, Default)]
17pub struct SegmentRequest<const C: usize>(pub(super) BTreeMap<FrameId, SeqNum>);
18
19/// Bitmap of segments missing in a frame.
20///
21/// Represented by `u8`, it can cover up to 8 segments per frame.
22/// If a bit is set, the segment is *missing* from the frame.
23pub type MissingSegmentsBitmap = BitArr!(for 1, in SeqNum, Msb0);
24
25impl<const C: usize> SegmentRequest<C> {
26    /// Size of a single segment retransmission request entry.
27    pub const ENTRY_SIZE: usize = size_of::<FrameId>() + size_of::<SeqNum>();
28    /// Maximum number of segment retransmission entries.
29    pub const MAX_ENTRIES: usize = Self::SIZE / Self::ENTRY_SIZE;
30    /// Maximum number of missing segments per frame.
31    pub const MAX_MISSING_SEGMENTS_PER_FRAME: usize = SeqNum::BITS as usize;
32    /// Size of the message.
33    pub const SIZE: usize = C - SessionMessage::<C>::HEADER_SIZE;
34
35    /// Returns the total number of segments to retransmit for all frames in this request.
36    pub fn len(&self) -> usize {
37        self.0
38            .values()
39            .take(Self::MAX_ENTRIES)
40            .map(|e| e.count_ones() as usize)
41            .sum()
42    }
43
44    /// Returns true if there are no segments to retransmit in this request.
45    pub fn is_empty(&self) -> bool {
46        self.0.iter().take(Self::MAX_ENTRIES).all(|(_, e)| e.count_ones() == 0)
47    }
48
49    /// Iterates the frame IDs named by this request, in ascending order.
50    ///
51    /// Bounded to [`Self::MAX_ENTRIES`] entries, like [`Self::len`] and [`Self::is_empty`].
52    ///
53    /// Exists so a handler can decide admission per frame *before* [`IntoIterator`] materialises one
54    /// [`SegmentId`] per requested bit — up to `MAX_ENTRIES * MAX_MISSING_SEGMENTS_PER_FRAME` ids for a
55    /// full request, which a throttled request must not pay for.
56    pub fn frames(&self) -> impl Iterator<Item = FrameId> + '_ {
57        self.0.keys().take(Self::MAX_ENTRIES).copied()
58    }
59}
60
61impl<const C: usize> IntoIterator for SegmentRequest<C> {
62    type IntoIter = std::vec::IntoIter<Self::Item>;
63    type Item = SegmentId;
64
65    // An ordered iterator of missing segments in the form of SegmentId tuples.
66    fn into_iter(self) -> Self::IntoIter {
67        let seq_size = SeqNum::BITS as usize;
68        let mut ret = Vec::with_capacity(seq_size * self.0.len());
69        for (frame_id, missing) in self.0 {
70            ret.extend(
71                MissingSegmentsBitmap::from([missing])
72                    .iter_ones()
73                    .map(|i| SegmentId(frame_id, i as SeqNum)),
74            );
75        }
76        ret.into_iter()
77    }
78}
79
80// From FrameIds and bitmap of missing segments per frame
81impl<const C: usize> FromIterator<(FrameId, MissingSegmentsBitmap)> for SegmentRequest<C> {
82    fn from_iter<T: IntoIterator<Item = (FrameId, MissingSegmentsBitmap)>>(iter: T) -> Self {
83        Self(
84            iter.into_iter()
85                .map(|(fid, missing_segments)| (fid, missing_segments.load()))
86                .collect(),
87        )
88    }
89}
90
91impl<const C: usize> TryFrom<&[u8]> for SegmentRequest<C> {
92    type Error = SessionError;
93
94    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
95        if value.len() == Self::SIZE {
96            let mut ret = Self::default();
97            for (frame_id, missing) in value
98                .chunks_exact(Self::ENTRY_SIZE)
99                .map(|c| c.split_at(size_of::<FrameId>()))
100            {
101                let frame_id = FrameId::from_be_bytes(frame_id.try_into().map_err(|_| SessionError::ParseError)?);
102                if frame_id > 0 {
103                    ret.0.insert(
104                        frame_id,
105                        SeqNum::from_be_bytes(missing.try_into().map_err(|_| SessionError::ParseError)?),
106                    );
107                }
108            }
109            Ok(ret)
110        } else {
111            Err(SessionError::ParseError)
112        }
113    }
114}
115
116impl<const C: usize> From<SegmentRequest<C>> for Vec<u8> {
117    fn from(value: SegmentRequest<C>) -> Self {
118        let mut ret = vec![0u8; SegmentRequest::<C>::SIZE];
119        let mut offset = 0;
120        for (frame_id, seq_num) in value.0 {
121            if offset + size_of::<FrameId>() + size_of::<SeqNum>() <= SegmentRequest::<C>::SIZE {
122                ret[offset..offset + size_of::<FrameId>()].copy_from_slice(&frame_id.to_be_bytes());
123                offset += size_of::<FrameId>();
124                ret[offset..offset + size_of::<SeqNum>()].copy_from_slice(&seq_num.to_be_bytes());
125                offset += size_of::<SeqNum>();
126            } else {
127                break;
128            }
129        }
130        ret
131    }
132}
133
134/// Holds the Frame Acknowledgement message.
135/// This carries an ordered set of up to [`FrameAcknowledgements::MAX_ACK_FRAMES`] [frame IDs](FrameId)
136/// that has been acknowledged by the counterparty.
137#[derive(Debug, Clone, PartialEq, Eq, Default)]
138pub struct FrameAcknowledgements<const C: usize>(pub(super) BTreeSet<FrameId>);
139
140impl<const C: usize> FrameAcknowledgements<C> {
141    /// Maximum number of [`FrameIds`](FrameId) that can be accommodated.
142    pub const MAX_ACK_FRAMES: usize = Self::SIZE / size_of::<FrameId>();
143    /// Size of the message.
144    pub const SIZE: usize = C - SessionMessage::<C>::HEADER_SIZE;
145
146    /// Pushes the frame ID.
147    /// Returns true if the value has been pushed or false it the container is full or already
148    /// contains that value.
149    #[inline]
150    pub fn push(&mut self, frame_id: FrameId) -> bool {
151        !self.is_full() && self.0.insert(frame_id)
152    }
153
154    /// Number of acknowledged frame IDs in this instance.
155    #[inline]
156    pub fn len(&self) -> usize {
157        self.0.len()
158    }
159
160    /// Returns true if there are no frame IDs in this instance.
161    pub fn is_empty(&self) -> bool {
162        self.0.is_empty()
163    }
164
165    /// Indicates whether the [maximum number of frame IDs](FrameAcknowledgements::MAX_ACK_FRAMES)
166    /// has been reached.
167    #[inline]
168    pub fn is_full(&self) -> bool {
169        self.0.len() == Self::MAX_ACK_FRAMES
170    }
171
172    /// Creates a vector of [`FrameAcknowledgements`] from the given iterator
173    /// of acknowledged [`FrameIds`](FrameId).
174    pub fn new_multiple<T: IntoIterator<Item = FrameId>>(items: T) -> Vec<Self> {
175        let mut out = Vec::with_capacity(2);
176        let mut frame_ack = Self::default();
177        for frame_id in items {
178            if frame_ack.is_full() {
179                out.push(frame_ack);
180                frame_ack = Self::default();
181            }
182
183            frame_ack.push(frame_id);
184        }
185        out.push(frame_ack);
186        out
187    }
188}
189
190impl<const C: usize> TryFrom<Vec<FrameId>> for FrameAcknowledgements<C> {
191    type Error = SessionError;
192
193    fn try_from(value: Vec<FrameId>) -> Result<Self, Self::Error> {
194        if value.len() <= Self::MAX_ACK_FRAMES {
195            value
196                .into_iter()
197                .map(|v| {
198                    if v > 0 {
199                        Ok(v)
200                    } else {
201                        Err(SessionError::InvalidFrameId)
202                    }
203                })
204                .collect::<Result<BTreeSet<_>, _>>()
205                .map(Self)
206        } else {
207            Err(SessionError::DataTooLong)
208        }
209    }
210}
211
212impl<const C: usize> IntoIterator for FrameAcknowledgements<C> {
213    type IntoIter = std::collections::btree_set::IntoIter<Self::Item>;
214    type Item = FrameId;
215
216    fn into_iter(self) -> Self::IntoIter {
217        self.0.into_iter()
218    }
219}
220
221impl<'a, const C: usize> TryFrom<&'a [u8]> for FrameAcknowledgements<C> {
222    type Error = SessionError;
223
224    fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
225        if value.len() == Self::SIZE {
226            Ok(Self(
227                // chunks_exact discards the remainder bytes
228                value
229                    .chunks_exact(size_of::<FrameId>())
230                    .map(|v| FrameId::from_be_bytes(v.try_into().unwrap()))
231                    .filter(|f| *f > 0)
232                    .collect(),
233            ))
234        } else {
235            Err(SessionError::ParseError)
236        }
237    }
238}
239
240impl<const C: usize> From<FrameAcknowledgements<C>> for Vec<u8> {
241    fn from(value: FrameAcknowledgements<C>) -> Self {
242        value
243            .0
244            .iter()
245            .flat_map(|v| v.to_be_bytes())
246            .chain(std::iter::repeat(0_u8))
247            .take(FrameAcknowledgements::<C>::SIZE)
248            .collect::<Vec<_>>()
249    }
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255
256    #[test]
257    fn test_frame_acks_multiple_single() {
258        let mut acks = FrameAcknowledgements::<1024>::new_multiple(vec![1, 2, 3]);
259        assert_eq!(acks.len(), 1);
260
261        let ids = acks.remove(0).into_iter().collect::<Vec<_>>();
262        assert_eq!(ids, vec![1, 2, 3]);
263    }
264
265    #[test]
266    fn test_frame_acks_multiple_many() {
267        const MAX: usize = FrameAcknowledgements::<1024>::MAX_ACK_FRAMES;
268
269        let expected = (0..(2 * MAX + 2) as FrameId).collect::<Vec<_>>();
270        let acks = FrameAcknowledgements::<1024>::new_multiple(expected.clone());
271
272        let chunk_lengths: Vec<_> = acks.iter().map(|a| a.len()).collect();
273        assert_eq!(chunk_lengths, [MAX, MAX, 2]);
274
275        let actual = acks.into_iter().flat_map(|a| a.into_iter()).collect::<Vec<_>>();
276        assert_eq!(expected, actual);
277    }
278
279    #[test]
280    fn test_missing_segments_in_segment_request() {
281        let frame_1_missing: MissingSegmentsBitmap = [0b00000000_u8].into();
282        let frame_2_missing: MissingSegmentsBitmap = [0b00100000_u8].into();
283        let frame_3_missing: MissingSegmentsBitmap = [0b00111001_u8].into();
284        let frame_4_missing: MissingSegmentsBitmap = [0b11111111_u8].into();
285
286        let req = SegmentRequest::<1000>::from_iter([
287            (4, frame_4_missing),
288            (1, frame_1_missing),
289            (3, frame_3_missing),
290            (2, frame_2_missing),
291        ]);
292
293        // Iterator of SegmentIds is guaranteed to be sorted
294        let missing = req.into_iter().collect::<Vec<SegmentId>>();
295        let expected = [
296            SegmentId(2, 2),
297            SegmentId(3, 2),
298            SegmentId(3, 3),
299            SegmentId(3, 4),
300            SegmentId(3, 7),
301            SegmentId(4, 0),
302            SegmentId(4, 1),
303            SegmentId(4, 2),
304            SegmentId(4, 3),
305            SegmentId(4, 4),
306            SegmentId(4, 5),
307            SegmentId(4, 6),
308            SegmentId(4, 7),
309        ];
310        assert_eq!(missing, expected);
311    }
312}