cfxcore/pos/protocol/message/
block_retrieval_response.rs

1// Copyright 2019-2020 Conflux Foundation. All rights reserved.
2// TreeGraph is free software and distributed under Apache License 2.0.
3// See https://www.apache.org/licenses/LICENSE-2.0
4
5use crate::{
6    message::RequestId,
7    pos::protocol::{
8        message::block_retrieval::BlockRetrievalRpcRequest,
9        request_manager::AsAny,
10        sync_protocol::{Context, Handleable, RpcResponse},
11    },
12    sync::Error,
13};
14use consensus_types::block_retrieval::BlockRetrievalResponse;
15use serde::{Deserialize, Serialize};
16use std::any::Any;
17
18#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
19pub struct BlockRetrievalRpcResponse {
20    pub request_id: RequestId,
21    #[serde(bound(deserialize = "BlockRetrievalResponse: Deserialize<'de>"))]
22    pub response: BlockRetrievalResponse,
23}
24
25impl RpcResponse for BlockRetrievalRpcResponse {}
26
27impl AsAny for BlockRetrievalRpcResponse {
28    fn as_any(&self) -> &dyn Any { self }
29
30    fn as_any_mut(&mut self) -> &mut dyn Any { self }
31}
32
33impl Handleable for BlockRetrievalRpcResponse {
34    fn handle(self, ctx: &Context) -> Result<(), Error> {
35        let mut req = ctx.match_request(self.request_id)?;
36        // FIXME: There is a potential issue if downcast error happens.
37        match req.downcast_mut::<BlockRetrievalRpcRequest>(
38            ctx.io,
39            &ctx.manager.request_manager,
40        ) {
41            Ok(req) => {
42                let res_tx = req.response_tx.take();
43                if let Some(tx) = res_tx {
44                    if let Err(e) = tx.send(Ok(Box::new(self))) {
45                        bail!(Error::UnexpectedMessage(
46                            format!("{:?}", e).into()
47                        ))
48                    }
49                }
50            }
51            Err(e) => {
52                return Err(e);
53            }
54        }
55        Ok(())
56    }
57}