Skip to main content

ab_networking/protocols/request_response/handlers/
piece_by_index.rs

1//! Helper for incoming piece requests.
2//!
3//! Request handler can be created with [`PieceByIndexRequestHandler`].
4
5#[cfg(test)]
6mod tests;
7
8use crate::protocols::request_response::handlers::generic_request_handler::{
9    GenericRequest, GenericRequestHandler, encode_to_buffer,
10};
11use crate::protocols::request_response::handlers::{decode_piece, encode_piece};
12use crate::protocols::request_response::request_response_factory::ResponsePayload;
13use ab_aligned_buffer::SharedAlignedBuffer;
14use ab_aligned_buffer::alignment::Align1;
15use ab_core_primitives::pieces::{Piece, PieceIndex};
16use parity_scale_codec::{Decode, DecodeAll, Encode};
17use std::sync::Arc;
18
19/// Piece-by-index request
20#[derive(Debug, Clone, Eq, PartialEq, Encode, Decode)]
21pub struct PieceByIndexRequest {
22    /// Request key - piece index
23    pub piece_index: PieceIndex,
24    /// Additional pieces that requester is interested in if they are cached locally
25    // TODO: Use `Arc<[PieceIndex]>` once
26    //  https://github.com/paritytech/parity-scale-codec/issues/633 is resolved
27    pub cached_pieces: Arc<Vec<PieceIndex>>,
28}
29
30impl GenericRequest for PieceByIndexRequest {
31    const PROTOCOL_NAME: &'static str = "/subspace/piece-by-index/0.1.0";
32    const LOG_TARGET: &'static str = "piece-by-index-request-response-handler";
33    type Response = PieceByIndexResponse;
34
35    /// Piece is not copied into the payload
36    fn encode_response(response: &Self::Response) -> Option<ResponsePayload> {
37        let PieceByIndexResponse {
38            piece,
39            cached_pieces,
40        } = response;
41
42        let mut payload = ResponsePayload::default();
43        if let Some(piece) = piece {
44            // `Some` variant of `Option`
45            encode_piece(&mut payload, &1u8, piece)?;
46        } else {
47            payload.push(encode_to_buffer(&None::<Piece>)?);
48        }
49        payload.push(encode_to_buffer(cached_pieces)?);
50
51        Some(payload)
52    }
53
54    /// Piece references the payload without copying it
55    fn decode_response(
56        payload: SharedAlignedBuffer<Align1>,
57    ) -> Result<Self::Response, parity_scale_codec::Error> {
58        let mut input = payload.as_slice();
59        let piece = match u8::decode(&mut input)? {
60            0 => None,
61            1 => Some(decode_piece(&payload, &mut input)?),
62            _ => {
63                return Err("Invalid `Option<Piece>` variant".into());
64            }
65        };
66        // This is the last field, so it must consume the rest of the payload
67        let cached_pieces = Vec::decode_all(&mut input)?;
68
69        Ok(PieceByIndexResponse {
70            piece,
71            cached_pieces,
72        })
73    }
74}
75
76impl PieceByIndexRequest {
77    /// Max number of cached pieces to accept per request, equals to the number of source shards in
78    /// a sector and fits nicely into a single TCP packet
79    pub const RECOMMENDED_LIMIT: usize = 128;
80}
81
82/// Piece-by-index response, may be cached piece or stored in one of the farms
83#[derive(Debug, PartialEq, Eq, Clone, Encode, Decode)]
84pub struct PieceByIndexResponse {
85    /// Piece, if found
86    pub piece: Option<Piece>,
87    /// Additional pieces that requester is interested in and are cached locally, order from
88    /// request is not preserved
89    pub cached_pieces: Vec<PieceIndex>,
90}
91
92/// Piece-by-index request handler
93pub type PieceByIndexRequestHandler = GenericRequestHandler<PieceByIndexRequest>;