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
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
mod handler;
mod protocol;

pub use protocol::RPCProtocol;

use futures::prelude::*;
use tokio::io::{AsyncRead, AsyncWrite};
use libp2p::{Multiaddr, PeerId};
use libp2p::core::ConnectedPoint;
use libp2p::swarm::{
	protocols_handler::ProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction,
	PollParameters,
};
use core::marker::PhantomData;

pub type RequestId = usize;

#[derive(Debug)]
pub enum RPCError {
	Codec,
	StreamTimeout,
	Custom(String),
}

impl std::fmt::Display for RPCError {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		write!(f, "{:?}", self)
	}
}

impl std::error::Error for RPCError { }

impl<T> From<tokio::timer::timeout::Error<T>> for RPCError {
    fn from(err: tokio::timer::timeout::Error<T>) -> Self {
        if err.is_elapsed() {
            RPCError::StreamTimeout
        } else {
            RPCError::Custom("Stream timer failed".into())
        }
    }
}

pub trait RPCRequest {
	fn is_goodbye(&self) -> bool;
	fn expect_response(&self) -> bool;
}

pub enum RPCEvent<Req, Res> {
	Request(RequestId, Req),
	Response(RequestId, Res),
	Error(RequestId, RPCError),
}

impl<Req, Res> RPCEvent<Req, Res> {
	pub fn id(&self) -> RequestId {
		match self {
			RPCEvent::Request(id, _) => *id,
			RPCEvent::Response(id, _) => *id,
			RPCEvent::Error(id, _) => *id,
		}
	}
}

pub enum RPCMessage<Req, Res> {
	Event(PeerId, RPCEvent<Req, Res>),
	PeerDialed(PeerId),
	PeerDisconnected(PeerId),
}

pub struct RPC<P: RPCProtocol, TSubstream> {
	events: Vec<NetworkBehaviourAction<RPCEvent<P::Request, P::Response>,
									   RPCMessage<P::Request, P::Response>>>,
	_marker: PhantomData<TSubstream>,
}

impl<P: RPCProtocol, TSubstream> RPC<P, TSubstream> {
	pub fn new() -> Self {
        RPC {
            events: Vec::new(),
            _marker: PhantomData,
        }
    }

    /// Submits an RPC request.
    ///
    /// The peer must be connected for this to succeed.
    pub fn send_rpc(&mut self, peer_id: PeerId, rpc_event: RPCEvent<P::Request, P::Response>) {
        self.events.push(NetworkBehaviourAction::SendEvent {
            peer_id,
            event: rpc_event,
        });
    }
}

impl<P, TSubstream> NetworkBehaviour for RPC<P, TSubstream> where
	P: RPCProtocol + Default + Clone,
	TSubstream: AsyncRead + AsyncWrite,
{
	type ProtocolsHandler = crate::handler::RPCHandler<P, TSubstream>;
    type OutEvent = RPCMessage<P::Request, P::Response>;

    fn new_handler(&mut self) -> Self::ProtocolsHandler {
        Default::default()
    }

    // handled by discovery
    fn addresses_of_peer(&mut self, _peer_id: &PeerId) -> Vec<Multiaddr> {
        Vec::new()
    }

    fn inject_connected(&mut self, peer_id: PeerId, connected_point: ConnectedPoint) {
        // if initialised the connection, report this upwards to send the HELLO request
        if let ConnectedPoint::Dialer { .. } = connected_point {
            self.events.push(NetworkBehaviourAction::GenerateEvent(
                RPCMessage::PeerDialed(peer_id),
            ));
        }
    }

    fn inject_disconnected(&mut self, peer_id: &PeerId, _: ConnectedPoint) {
        // inform the rpc handler that the peer has disconnected
        self.events.push(NetworkBehaviourAction::GenerateEvent(
            RPCMessage::PeerDisconnected(peer_id.clone()),
        ));
    }

    fn inject_node_event(
        &mut self,
        source: PeerId,
        event: <Self::ProtocolsHandler as ProtocolsHandler>::OutEvent,
    ) {
        // send the event to the user
        self.events
            .push(NetworkBehaviourAction::GenerateEvent(RPCMessage::Event(
                source, event,
            )));
    }

    fn poll(
        &mut self,
        _: &mut impl PollParameters,
    ) -> Async<
        NetworkBehaviourAction<
            <Self::ProtocolsHandler as ProtocolsHandler>::InEvent,
            Self::OutEvent,
        >,
    > {
        if !self.events.is_empty() {
            return Async::Ready(self.events.remove(0));
        }
        Async::NotReady
    }
}