Skip to main content

ab_networking/protocols/request_response/handlers/
generic_request_handler.rs

1//! Generic request-response handler, typically is used with a type implementing [`GenericRequest`]
2//! to significantly reduce boilerplate when implementing [`RequestHandler`].
3
4#[cfg(test)]
5mod tests;
6
7use crate::protocols::request_response::request_response_factory::{
8    IncomingRequest, OutgoingResponse, ProtocolConfig, RequestHandler, ResponsePayload,
9};
10use ab_aligned_buffer::alignment::Align1;
11use ab_aligned_buffer::{OwnedAlignedBuffer, SharedAlignedBuffer};
12use async_trait::async_trait;
13use futures::channel::mpsc;
14use futures::prelude::*;
15use libp2p::PeerId;
16use parity_scale_codec::{Decode, DecodeAll, Encode, Output};
17use std::fmt;
18use std::pin::Pin;
19use std::sync::Arc;
20use tracing::{debug, trace};
21
22/// Could be changed after the production feedback.
23const REQUESTS_BUFFER_SIZE: usize = 50;
24
25/// SCALE codec output that writes into an aligned buffer
26struct BufferOutput {
27    buffer: OwnedAlignedBuffer<Align1>,
28    failed: bool,
29}
30
31impl Output for BufferOutput {
32    #[inline]
33    fn write(&mut self, bytes: &[u8]) {
34        if self.buffer.append(bytes).is_err() {
35            self.failed = true;
36        }
37    }
38}
39
40/// Encode a value with SCALE codec into a new buffer.
41///
42/// Returns `None` if the encoding is larger than [`OwnedAlignedBuffer::MAX_CAPACITY`] or allocation
43/// fails.
44pub fn encode_to_buffer<T>(value: &T) -> Option<SharedAlignedBuffer<Align1>>
45where
46    T: Encode + ?Sized,
47{
48    #[cfg_attr(
49        target_pointer_width = "64",
50        expect(
51            clippy::unnecessary_min_or_max,
52            reason = "`MAX_CAPACITY` is `u32::MAX` where `usize` is 64-bit"
53        )
54    )]
55    let capacity = u32::try_from(value.size_hint())
56        .unwrap_or(u32::MAX)
57        .min(OwnedAlignedBuffer::<Align1>::MAX_CAPACITY);
58    let mut output = BufferOutput {
59        buffer: OwnedAlignedBuffer::try_with_capacity(capacity).ok()?,
60        failed: false,
61    };
62    value.encode_to(&mut output);
63
64    (!output.failed).then(|| output.buffer.into_shared())
65}
66
67/// Generic request with associated response
68pub trait GenericRequest: Encode + Decode + Send + Sync + 'static {
69    /// Defines request-response protocol name.
70    const PROTOCOL_NAME: &'static str;
71    /// Specifies log-parameters for tracing.
72    const LOG_TARGET: &'static str;
73    /// Response type that corresponds to this request
74    type Response: Encode + Decode + Send + Sync + 'static;
75
76    /// Encode a response into a payload, which must be decodable with [`Self::decode_response()`].
77    ///
78    /// The default implementation encodes the response with SCALE codec, responses that contain
79    /// large buffers can be encoded the same way without copying them into the payload instead.
80    ///
81    /// Returns `None` if the response is too large.
82    #[inline]
83    fn encode_response(response: &Self::Response) -> Option<ResponsePayload> {
84        encode_to_buffer(response).map(ResponsePayload::from)
85    }
86
87    /// Decode a response received from a remote peer, the whole payload must be consumed.
88    ///
89    /// The default implementation decodes the response with SCALE codec, responses that contain
90    /// large buffers can reference them in the payload without copying them instead.
91    #[inline]
92    fn decode_response(
93        payload: SharedAlignedBuffer<Align1>,
94    ) -> Result<Self::Response, parity_scale_codec::Error> {
95        Self::Response::decode_all(&mut payload.as_slice())
96    }
97}
98
99type RequestHandlerFn<Request> = Arc<
100    dyn (Fn(
101            PeerId,
102            Request,
103        )
104            -> Pin<Box<dyn Future<Output = Option<<Request as GenericRequest>::Response>> + Send>>)
105        + Send
106        + Sync
107        + 'static,
108>;
109
110/// Defines generic request-response protocol handler.
111pub struct GenericRequestHandler<Request>
112where
113    Request: GenericRequest,
114{
115    request_receiver: mpsc::Receiver<IncomingRequest>,
116    request_handler: RequestHandlerFn<Request>,
117    protocol_config: ProtocolConfig,
118}
119
120impl<Request> fmt::Debug for GenericRequestHandler<Request>
121where
122    Request: GenericRequest,
123{
124    #[inline]
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        f.debug_struct("GenericRequestHandler")
127            .field("protocol_name", &Request::PROTOCOL_NAME)
128            .finish_non_exhaustive()
129    }
130}
131
132impl<Request> GenericRequestHandler<Request>
133where
134    Request: GenericRequest,
135{
136    /// Creates new [`GenericRequestHandler`] by given handler.
137    pub fn create<RH, Fut>(request_handler: RH) -> Box<dyn RequestHandler>
138    where
139        RH: (Fn(PeerId, Request) -> Fut) + Send + Sync + 'static,
140        Fut: Future<Output = Option<Request::Response>> + Send + 'static,
141    {
142        let (request_sender, request_receiver) = mpsc::channel(REQUESTS_BUFFER_SIZE);
143
144        let mut protocol_config = ProtocolConfig::new(Request::PROTOCOL_NAME);
145        protocol_config.inbound_queue = Some(request_sender);
146
147        Box::new(Self {
148            request_receiver,
149            request_handler: Arc::new(move |peer_id, request| {
150                Box::pin(request_handler(peer_id, request))
151            }),
152            protocol_config,
153        })
154    }
155
156    /// Invokes external protocol handler.
157    async fn handle_request(
158        &self,
159        peer: PeerId,
160        payload: Vec<u8>,
161    ) -> Result<ResponsePayload, RequestHandlerError> {
162        trace!(%peer, protocol=Request::LOG_TARGET, "Handling request...");
163        let request = Request::decode_all(&mut payload.as_slice())
164            .map_err(|_error| RequestHandlerError::InvalidRequestFormat)?;
165        let response = (self.request_handler)(peer, request)
166            .await
167            .ok_or(RequestHandlerError::NoResponse)?;
168
169        Request::encode_response(&response).ok_or(RequestHandlerError::ResponseTooLarge)
170    }
171}
172
173#[async_trait]
174impl<Request> RequestHandler for GenericRequestHandler<Request>
175where
176    Request: GenericRequest,
177{
178    /// Run [`RequestHandler`].
179    async fn run(&mut self) {
180        while let Some(request) = self.request_receiver.next().await {
181            let IncomingRequest {
182                peer,
183                payload,
184                pending_response,
185            } = request;
186
187            match self.handle_request(peer, payload).await {
188                Ok(response_data) => {
189                    let response = OutgoingResponse {
190                        result: Ok(response_data),
191                        sent_feedback: None,
192                    };
193
194                    if pending_response.send(response).is_ok() {
195                        trace!(target = Request::LOG_TARGET, %peer, "Handled request");
196                    } else {
197                        debug!(
198                            target = Request::LOG_TARGET,
199                            protocol = Request::PROTOCOL_NAME,
200                            %peer,
201                            "Failed to handle request: {}",
202                            RequestHandlerError::SendResponse
203                        );
204                    }
205                }
206                Err(e) => {
207                    debug!(
208                        target = Request::LOG_TARGET,
209                        protocol = Request::PROTOCOL_NAME,
210                        %e,
211                        "Failed to handle request.",
212                    );
213
214                    let response = OutgoingResponse {
215                        result: Err(()),
216                        sent_feedback: None,
217                    };
218
219                    if pending_response.send(response).is_err() {
220                        debug!(
221                            target = Request::LOG_TARGET,
222                            protocol = Request::PROTOCOL_NAME,
223                            %peer,
224                            "Failed to handle request: {}", RequestHandlerError::SendResponse
225                        );
226                    }
227                }
228            }
229        }
230    }
231
232    fn protocol_config(&self) -> ProtocolConfig {
233        self.protocol_config.clone()
234    }
235
236    fn protocol_name(&self) -> &'static str {
237        Request::PROTOCOL_NAME
238    }
239
240    fn clone_box(&self) -> Box<dyn RequestHandler> {
241        let (request_sender, request_receiver) = mpsc::channel(REQUESTS_BUFFER_SIZE);
242
243        let mut protocol_config = ProtocolConfig::new(Request::PROTOCOL_NAME);
244        protocol_config.inbound_queue = Some(request_sender);
245
246        Box::new(Self {
247            request_receiver,
248            request_handler: Arc::clone(&self.request_handler),
249            protocol_config,
250        })
251    }
252}
253
254#[derive(Debug, thiserror::Error)]
255enum RequestHandlerError {
256    #[error("Failed to send response.")]
257    SendResponse,
258
259    #[error("Incorrect request format.")]
260    InvalidRequestFormat,
261
262    #[error("No response.")]
263    NoResponse,
264
265    #[error("Response is too large.")]
266    ResponseTooLarge,
267}