1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
pub mod client;
pub mod server;

use std::io::Result;

use crate::ids;

/// AppSender sends application (Vm) level messages.
///
/// ref. <https://pkg.go.dev/github.com/ava-labs/avalanchego/snow/engine/common#AppSender>
#[tonic::async_trait]
pub trait AppSender: Send + Sync + CloneBox {
    async fn send_app_request(
        &self,
        node_ids: ids::node::Set,
        request_id: u32,
        request: Vec<u8>,
    ) -> Result<()>;
    async fn send_app_response(
        &self,
        node_if: ids::node::Id,
        request_id: u32,
        response: Vec<u8>,
    ) -> Result<()>;
    async fn send_app_gossip(&self, msg: Vec<u8>) -> Result<()>;
    async fn send_app_gossip_specific(&self, node_ids: ids::node::Set, msg: Vec<u8>) -> Result<()>;
    async fn send_cross_chain_app_request(
        &self,
        chain_id: ids::Id,
        request_id: u32,
        app_request_bytes: Vec<u8>,
    ) -> Result<()>;
    async fn send_cross_chain_app_response(
        &self,
        chain_id: ids::Id,
        request_id: u32,
        app_response_bytes: Vec<u8>,
    ) -> Result<()>;
}

pub trait CloneBox {
    fn clone_box(&self) -> Box<dyn AppSender + Send + Sync>;
}

impl<T> CloneBox for T
where
    T: 'static + AppSender + Clone + Send + Sync,
{
    fn clone_box(&self) -> Box<dyn AppSender + Send + Sync> {
        Box::new(self.clone())
    }
}

impl Clone for Box<dyn AppSender + Send + Sync> {
    fn clone(&self) -> Box<dyn AppSender + Send + Sync> {
        self.clone_box()
    }
}

#[tokio::test]
async fn clone_box_test() {
    use crate::subnet::rpc::snow::engine::common::appsender::client::AppSenderClient;
    use tokio::net::TcpListener;
    use tonic::transport::Channel;

    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let client_conn = Channel::builder(format!("http://{}", addr).parse().unwrap())
        .connect()
        .await
        .unwrap();
    let _app_sender = AppSenderClient::new(client_conn).clone();
}