Skip to main content

nimiq_network_interface/request/
mod.rs

1use std::{fmt, sync::Arc, time::Duration};
2
3use futures::{stream::BoxStream, Future, StreamExt};
4use nimiq_serde::{Deserialize, DeserializeError, Serialize};
5use thiserror::Error;
6
7/// The default time it takes to refill the whole request budget of a peer, see
8/// [`RequestCommon::TIME_WINDOW`].
9pub const DEFAULT_MAX_REQUEST_RESPONSE_TIME_WINDOW: Duration = Duration::from_secs(10);
10
11use crate::network::Network;
12
13#[derive(Copy, Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
14pub struct RequestType(pub u16);
15
16impl fmt::Display for RequestType {
17    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
18        write!(
19            f,
20            "{}{}",
21            self.type_id(),
22            if self.requires_response() { 'r' } else { 'm' },
23        )
24    }
25}
26
27impl RequestType {
28    const fn new(type_id: u16, requires_response: bool) -> Self {
29        Self((type_id << 1) | requires_response as u16)
30    }
31    pub fn from_request<R: RequestCommon>() -> Self {
32        Self::new(R::TYPE_ID, R::Kind::EXPECT_RESPONSE)
33    }
34    pub const fn request(type_id: u16) -> Self {
35        Self::new(type_id, true)
36    }
37    pub const fn message(type_id: u16) -> Self {
38        Self::new(type_id, false)
39    }
40    pub const fn type_id(self) -> u16 {
41        self.0 >> 1
42    }
43    pub const fn requires_response(self) -> bool {
44        self.0 & 1 != 0
45    }
46}
47
48/// Error enumeration for requests
49#[derive(Clone, Debug, Error, Eq, PartialEq)]
50pub enum RequestError {
51    /// Outbound request error
52    #[error("Outbound error: {0}")]
53    OutboundRequest(#[from] OutboundRequestError),
54    /// Inbound request error
55    #[error("Inbound error: {0}")]
56    InboundRequest(#[from] InboundRequestError),
57}
58
59#[derive(Clone, Debug, Error, Eq, PartialEq)]
60pub enum OutboundRequestError {
61    /// The connection closed before a response was received.
62    ///
63    /// It is not known whether the request may have been
64    /// received (and processed) by the remote peer.
65    #[error("Connection to peer is closed")]
66    ConnectionClosed,
67    /// The request could not be sent because a dialing attempt failed.
68    #[error("Dial attempt failed")]
69    DialFailure,
70    /// No receiver was found for this request and no response could be transmitted
71    #[error("No receiver for request")]
72    NoReceiver,
73    /// Error sending this request
74    #[error("Couldn't send request")]
75    SendError,
76    /// Sender future has already been dropped
77    #[error("Sender future is already dropped")]
78    SenderFutureDropped,
79    /// Request failed to be serialized
80    #[error("Failed to serialized request")]
81    SerializationError,
82    /// Timeout waiting for the response of this request.
83    /// In this case a receiver was registered for responding these requests
84    /// but the response never arrived before the timeout was hit.
85    #[error("Request timed out")]
86    Timeout,
87    /// The remote supports none of the requested protocols.
88    #[error("Remote doesn't support requested protocol")]
89    UnsupportedProtocols,
90    /// No response after asking a couple of peers.
91    #[error("No response after asking a couple of peers")]
92    NoResponse,
93    /// Error that doesn't match any of the other error causes
94    #[error("Other: {0}")]
95    Other(String),
96}
97
98#[repr(u8)]
99#[derive(Clone, Copy, Debug, Error, Eq, PartialEq, Serialize, Deserialize)]
100pub enum InboundRequestError {
101    /// Response failed to be deserialized
102    #[error("Response failed to be deserialized")]
103    DeSerializationError = 1,
104    /// No receiver was found for this incoming request
105    #[error("No receiver for request")]
106    NoReceiver = 2,
107    /// Sender future has already been dropped
108    #[error("Sender future is already dropped")]
109    SenderFutureDropped = 3,
110    /// The request timed out before a response could have been sent.
111    #[error("Request timed out")]
112    Timeout = 4,
113    /// The request exceeded the maximum defined rate limit for its request type.
114    #[error("Request exceeds the maximum rate limit")]
115    ExceedsRateLimit = 5,
116}
117
118pub trait RequestKind {
119    const EXPECT_RESPONSE: bool;
120}
121
122pub struct RequestMarker;
123pub struct MessageMarker;
124
125impl RequestKind for RequestMarker {
126    const EXPECT_RESPONSE: bool = true;
127}
128impl RequestKind for MessageMarker {
129    const EXPECT_RESPONSE: bool = false;
130}
131
132pub trait RequestCommon:
133    Serialize + Deserialize + Send + Sync + Unpin + fmt::Debug + 'static
134{
135    type Kind: RequestKind;
136    const TYPE_ID: u16;
137    type Response: Deserialize + Serialize + Send;
138    /// The maximum number of requests of this type a peer can send in a burst. Implementations
139    /// treat the budget as a token bucket that refills one request every
140    /// `TIME_WINDOW / MAX_REQUESTS`, so this is also the number of requests a peer can make per
141    /// [`TIME_WINDOW`](Self::TIME_WINDOW) on average. A request that finds the bucket empty is
142    /// answered with [`InboundRequestError::ExceedsRateLimit`]. Must be at least one.
143    const MAX_REQUESTS: u32;
144    /// The time it takes to refill the whole budget of [`MAX_REQUESTS`](Self::MAX_REQUESTS).
145    /// Must be at least a nanosecond per request, so it cannot be zero.
146    const TIME_WINDOW: Duration = DEFAULT_MAX_REQUEST_RESPONSE_TIME_WINDOW;
147
148    /// Returns the type name of the given request type `T`.
149    /// This only works for
150    ///   - non-generic types
151    ///   - generic types with a single level of nesting, in which case the name of
152    ///     the type parameter is returned
153    fn type_name<T>() -> &'static str {
154        let name = std::any::type_name::<T>();
155        let name = match name.rfind("::") {
156            Some(index) => &name[index + 2..],
157            None => name,
158        };
159        match name.rfind(">") {
160            Some(index) => &name[..index],
161            None => name,
162        }
163    }
164}
165
166pub trait RequestSerialize: RequestCommon {
167    /// Serializes a request.
168    /// A serialized request is composed of:
169    /// - A variable sized integer for the Type ID of the request
170    /// - Serialized content of the inner type.
171    fn serialize_request(&self) -> Vec<u8> {
172        let mut data = Vec::with_capacity(self.serialized_request_size());
173        RequestType::from_request::<Self>()
174            .serialize_to_writer(&mut data)
175            .unwrap();
176        Serialize::serialize_to_writer(self, &mut data).unwrap();
177        data
178    }
179
180    /// Computes the size in bytes of a serialized request.
181    /// A serialized request is composed of:
182    /// - A 2 bytes (u16) for the Type ID of the request
183    /// - Serialized content of the inner type.
184    fn serialized_request_size(&self) -> usize {
185        let mut size = 0;
186        size += RequestType::from_request::<Self>().0.serialized_size();
187        size += self.serialized_size();
188        size
189    }
190
191    /// Deserializes a request
192    /// A serialized request is composed of:
193    /// - A variable sized integer for the Type ID of the request
194    /// - Serialized content of the inner type.
195    fn deserialize_request(buffer: &[u8]) -> Result<Self, DeserializeError> {
196        // Check for correct type.
197        let (ty, message_buf) = u16::deserialize_take(buffer)?;
198        if ty != RequestType::from_request::<Self>().0 {
199            return Err(DeserializeError::bad_enum());
200        }
201        Self::deserialize_from_vec(message_buf)
202    }
203}
204
205impl<T: RequestCommon> RequestSerialize for T {}
206
207pub trait Request: RequestCommon<Kind = RequestMarker> {}
208pub trait Message: RequestCommon<Kind = MessageMarker, Response = ()> {}
209
210impl<T: RequestCommon<Kind = RequestMarker>> Request for T {}
211impl<T: RequestCommon<Kind = MessageMarker, Response = ()>> Message for T {}
212
213pub fn peek_type(buffer: &[u8]) -> Result<RequestType, DeserializeError> {
214    let ty = u16::deserialize_from_vec(buffer)?;
215    Ok(RequestType(ty))
216}
217
218/// This trait defines the behaviour when receiving a message and how to generate the response.
219pub trait Handle<N: Network, T>: Request {
220    fn handle(&self, peer_id: N::PeerId, context: &T) -> <Self as RequestCommon>::Response;
221}
222
223/// This trait defines the behaviour when receiving a message
224pub trait MessageHandle<N: Network, T> {
225    fn message_handle(&self, peer_id: N::PeerId, context: &T);
226}
227
228const MAX_CONCURRENT_HANDLERS: usize = 64;
229
230pub fn request_handler<T: Send + Sync + Clone + 'static, Req: Handle<N, T>, N: Network>(
231    network: &Arc<N>,
232    stream: BoxStream<'static, (Req, N::RequestId, N::PeerId)>,
233    req_environment: &T,
234) -> impl Future<Output = ()> + use<T, Req, N> {
235    let req_environment = req_environment.clone();
236    let network = Arc::clone(network);
237    async move {
238        stream
239            .for_each_concurrent(MAX_CONCURRENT_HANDLERS, |(msg, request_id, peer_id)| {
240                let network = Arc::clone(&network);
241                let req_environment = req_environment.clone();
242                async move {
243                    // Try to send the response. If it fails, it usually means that the peer has
244                    // disconnected, so we silently ignore any errors here.
245                    network
246                        .respond::<Req>(request_id, msg.handle(peer_id, &req_environment))
247                        .await
248                        .ok();
249                }
250            })
251            .await
252    }
253}
254
255/// Handler that takes care of sending messages to a network, similar to a request except that we don't expect an answer.
256pub fn message_handler<
257    T: Send + Sync + Clone + 'static,
258    Msg: MessageHandle<N, T> + Message,
259    N: Network,
260>(
261    _network: &Arc<N>,
262    stream: BoxStream<'static, (Msg, N::PeerId)>,
263    req_environment: &T,
264) -> impl Future<Output = ()> {
265    let req_environment = req_environment.clone();
266    async move {
267        stream
268            .for_each_concurrent(MAX_CONCURRENT_HANDLERS, |(msg, peer_id)| {
269                let req_environment = req_environment.clone();
270                async move {
271                    // Messages do not have a response (so the response is ignored)
272                    msg.message_handle(peer_id, &req_environment);
273                }
274            })
275            .await
276    }
277}