Skip to main content

hopr_protocol_session/
lib.rs

1//! Contains implementation of a `Session` message protocol.
2//!
3//! The implementation in this crate follows
4//! the HOPR [`RFC-0007`](https://github.com/hoprnet/rfc/tree/main/rfcs/RFC-0007-session-protocol).
5//!
6//! # What is `Session` protocol?
7//! `Session` protocol is a simple protocol for unreliable networks that implements
8//! basic TCP-like features, such as segmentation, retransmission and acknowledgement.
9//!
10//! The goal of this protocol is to establish a read-write session between two parties,
11//! where one is a message sender and the other one is the receiver. The messages are called
12//! *frames* which are split and are delivered as *segments* from the sender to the recipient.
13//! The session has some reliability guarantees given by the retransmission and acknowledgement
14//! capabilities of individual segments.
15//!
16//! The [`UnreliableSocket`] acts as an unreliable Session protocol socket, taking care only of
17//! segmentation, reassembly and sequencing.
18//!
19//! The [`ReliableSocket`] has (in addition to segmentation, reassembly and sequencing) an
20//! internal state that allows acknowledging frames, retransmit unacknowledged frames and/or
21//! requesting of missing frame segments. It therefore offers data some delivery guarantees
22//! up to the pre-defined frame expiration time.
23//!
24//! The above sockets can be constructed on top of any transport that implements
25//! [`futures::io::AsyncRead`] and [`futures::io::AsyncWrite`],
26//! also using the [extension](SessionSocketExt) methods.
27//!
28//! ## Overview of the crate
29//! - Protocol messages are defined in the `protocol` submodule.
30//! - Socket-like Session interface is defined in `socket` submodule.
31//! - Frames and segments are defined in the `frames` module.
32//! - Segmentation, reassembly and sequencing are defined in the `processing` submodule.
33
34/// Contains errors thrown from this module.
35pub mod errors;
36/// Client/ENTRY-side send-window flow control (AIMD send window over the honest delivery clock).
37pub mod flow_control;
38#[allow(dead_code)]
39mod processing;
40mod protocol;
41mod socket;
42pub(crate) mod utils;
43
44pub use processing::types::FrameInspector;
45pub use protocol::{FrameAcknowledgements, FrameId, Segment, SegmentId, SegmentRequest, SeqIndicator};
46#[cfg(feature = "telemetry")]
47pub use socket::telemetry::{NoopTracker, SessionMessageDiscriminants, SessionTelemetryTracker};
48pub use socket::{
49    SessionSocket, SessionSocketConfig,
50    ack_state::{AcknowledgementMode, AcknowledgementState, AcknowledgementStateConfig},
51    loss_signal::FrameLossSignal,
52    state::{SocketComponents, SocketState, Stateless},
53};
54
55// Enable exports of additional Session protocol types
56#[cfg(feature = "session-types")]
57pub mod types {
58    pub use super::protocol::*;
59}
60
61/// Represents a stateless (and therefore unreliable) socket.
62pub type UnreliableSocket<const C: usize> = SessionSocket<C, Stateless<C>>;
63
64/// Represents a socket with reliable delivery.
65pub type ReliableSocket<const C: usize> = SessionSocket<C, AcknowledgementState<C>>;
66
67const fn min(a: usize, b: usize) -> usize {
68    if a < b { a } else { b }
69}
70
71/// Maximum Session MTU even if the HOPR packet allows for more.
72///
73/// Based on GnosisVPN (gnosis_vpn-lib/src/wireguard.rs:9) with a 1420-byte WG tunnel MTU, whose padding is capped at
74/// that MTU, plus a 16-byte transport header and a 16-byte authentication tag.
75pub const MAX_SESSION_MTU: usize = 1452;
76
77/// Computes the Session Socket MTU, given the MTU `C` of the underlying socket.
78pub const fn session_socket_mtu<const C: usize>() -> usize {
79    min(MAX_SESSION_MTU, C - protocol::SessionMessage::<C>::SEGMENT_OVERHEAD)
80}
81
82/// Clamps a requested `frame_size` between one and `max_segments` segment payloads.
83///
84/// Preserves frame boundaries within these limits: UDP forwarding turns each reconstructed frame
85/// into a datagram, so rounding down could split a datagram that fits the requested frame size.
86pub const fn session_frame_size<const C: usize>(frame_size: usize, max_segments: usize) -> usize {
87    let segment = session_socket_mtu::<C>();
88    let frame_size = min(frame_size, segment.saturating_mul(max_segments));
89    if frame_size < segment { segment } else { frame_size }
90}
91
92/// Adaptors for [`futures::io::AsyncRead`] + [`futures::io::AsyncWrite`] transport to use Session protocol.
93///
94/// Use `compat` first when the underlying transport is Tokio-based.
95pub trait SessionSocketExt: futures::io::AsyncRead + futures::io::AsyncWrite + Send + Unpin {
96    /// Runs a [reliable](ReliableSocket) Session protocol on self.
97    fn reliable_session<const MTU: usize>(
98        self,
99        ack: AcknowledgementState<MTU>,
100        cfg: SessionSocketConfig,
101    ) -> errors::Result<ReliableSocket<MTU>>
102    where
103        Self: Sized + 'static,
104    {
105        #[cfg(feature = "telemetry")]
106        {
107            SessionSocket::new(self, ack, cfg, None, NoopTracker)
108        }
109        #[cfg(not(feature = "telemetry"))]
110        {
111            SessionSocket::new(self, ack, cfg, None)
112        }
113    }
114
115    /// Runs [unreliable](UnreliableSocket) Session protocol on self.
116    fn unreliable_session<const MTU: usize>(
117        self,
118        id: &str,
119        cfg: SessionSocketConfig,
120    ) -> errors::Result<UnreliableSocket<MTU>>
121    where
122        Self: Sized + 'static,
123    {
124        #[cfg(feature = "telemetry")]
125        {
126            SessionSocket::new_stateless(id, self, cfg, None, NoopTracker)
127        }
128        #[cfg(not(feature = "telemetry"))]
129        {
130            SessionSocket::new_stateless(id, self, cfg, None)
131        }
132    }
133}
134
135impl<T: ?Sized> SessionSocketExt for T where T: futures::io::AsyncRead + futures::io::AsyncWrite + Send + Unpin {}