Cleanup and remove unnecessary trait objects

This commit is contained in:
Vurich 2017-10-23 11:45:35 +02:00
parent 0e4375fc90
commit 384d15e24a
3 changed files with 187 additions and 150 deletions

View File

@ -3,8 +3,9 @@
extern crate futures; extern crate futures;
extern crate libp2p_transport as transport; extern crate libp2p_transport as transport;
use futures::{Future, IntoFuture, BoxFuture}; use futures::{Future, IntoFuture};
use transport::{ProtocolId, MultiAddr, Socket}; use transport::{ProtocolId, Socket};
use transport::multiaddr::Multiaddr;
/// Produces a future for each incoming `Socket`. /// Produces a future for each incoming `Socket`.
pub trait Handler<S: Socket> { pub trait Handler<S: Socket> {
@ -13,29 +14,34 @@ pub trait Handler<S: Socket> {
/// Handle the incoming socket, producing a future which should resolve /// Handle the incoming socket, producing a future which should resolve
/// when the handler is finished. /// when the handler is finished.
fn handle(&self, socket: S) -> Self::Future; fn handle(&self, socket: S) -> Self::Future;
fn boxed(self) -> BoxHandler<S> where fn boxed(self) -> BoxHandler<S>
where
Self: Sized + Send + 'static, Self: Sized + Send + 'static,
<Self::Future as IntoFuture>::Future: Send + 'static <Self::Future as IntoFuture>::Future: Send + 'static,
{ {
BoxHandler(Box::new(move |socket| BoxHandler(Box::new(move |socket| {
self.handle(socket).into_future().boxed() Box::new(self.handle(socket).into_future()) as _
)) }))
} }
} }
impl<S: Socket, F, U> Handler<S> for F impl<S: Socket, F, U> Handler<S> for F
where F: Fn(S) -> U, U: IntoFuture<Item=(), Error=()> where
F: Fn(S) -> U,
U: IntoFuture<Item = (), Error = ()>,
{ {
type Future = U; type Future = U;
fn handle(&self, socket: S) -> U { (self)(socket) } fn handle(&self, socket: S) -> U {
(self)(socket)
}
} }
/// A boxed handler. /// A boxed handler.
pub struct BoxHandler<S: Socket>(Box<Handler<S, Future=BoxFuture<(), ()>>>); pub struct BoxHandler<S: Socket>(Box<Handler<S, Future = Box<Future<Item = (), Error = ()>>>>);
impl<S: Socket> Handler<S> for BoxHandler<S> { impl<S: Socket> Handler<S> for BoxHandler<S> {
type Future = BoxFuture<(), ()>; type Future = Box<Future<Item = (), Error = ()>>;
fn handle(&self, socket: S) -> Self::Future { fn handle(&self, socket: S) -> Self::Future {
self.0.handle(socket) self.0.handle(socket)
@ -66,12 +72,14 @@ pub trait PeerStore {}
/// wraps an arbitrary event loop, and manages protocol IDs. /// wraps an arbitrary event loop, and manages protocol IDs.
pub trait Host { pub trait Host {
type Socket: Socket; type Socket: Socket;
type Mux: Mux<Socket = Self::Socket>;
type Multiaddrs: IntoIterator<Item = Multiaddr>;
/// Get a handle to the peer store. /// Get a handle to the peer store.
fn peer_store(&self) -> &PeerStore; fn peer_store(&self) -> &PeerStore;
/// Get a handle to the underlying muxer. /// Get a handle to the underlying muxer.
fn mux(&self) -> &Mux<Socket=Self::Socket>; fn mux(&self) -> &Self::Mux;
/// Set the socket handler for a given protocol id. /// Set the socket handler for a given protocol id.
fn set_handler(&self, proto: ProtocolId, handler: BoxHandler<Self::Socket>) { fn set_handler(&self, proto: ProtocolId, handler: BoxHandler<Self::Socket>) {
@ -84,5 +92,5 @@ pub trait Host {
} }
/// Addresses we're listening on. /// Addresses we're listening on.
fn listen_addrs(&self) -> Vec<MultiAddr>; fn listen_addrs(&self) -> Self::Multiaddrs;
} }

View File

@ -19,9 +19,7 @@ pub struct Tcp {
impl Tcp { impl Tcp {
pub fn new() -> Result<Tcp, IoError> { pub fn new() -> Result<Tcp, IoError> {
Ok(Tcp { Ok(Tcp { event_loop: Core::new()? })
event_loop: Core::new()?,
})
} }
} }
@ -39,10 +37,15 @@ impl Transport for Tcp {
/// Returns the address back if it isn't supported. /// Returns the address back if it isn't supported.
fn listen_on(&mut self, addr: Multiaddr) -> Result<Self::Listener, Multiaddr> { fn listen_on(&mut self, addr: Multiaddr) -> Result<Self::Listener, Multiaddr> {
if let Ok(socket_addr) = multiaddr_to_socketaddr(&addr) { if let Ok(socket_addr) = multiaddr_to_socketaddr(&addr) {
Ok(Box::new(futures::future::result(TcpListener::bind(&socket_addr, &self.event_loop.handle())).map(|listener| { Ok(Box::new(
futures::future::result(
TcpListener::bind(&socket_addr, &self.event_loop.handle()),
).map(|listener| {
// Pull out a stream of sockets for incoming connections // Pull out a stream of sockets for incoming connections
listener.incoming().map(|x| x.0) listener.incoming().map(|x| x.0)
}).flatten_stream())) })
.flatten_stream(),
))
} else { } else {
Err(addr) Err(addr)
} }
@ -63,23 +66,29 @@ impl Transport for Tcp {
// This type of logic should probably be moved into the multiaddr package // This type of logic should probably be moved into the multiaddr package
fn multiaddr_to_socketaddr(addr: &Multiaddr) -> Result<SocketAddr, &Multiaddr> { fn multiaddr_to_socketaddr(addr: &Multiaddr) -> Result<SocketAddr, &Multiaddr> {
let protocols = addr.protocol(); let protocols = addr.protocol();
// TODO: This is nonconforming (since a multiaddr could specify TCP first) but we can't fix that
// until multiaddrs-rs is improved.
match (protocols[0], protocols[1]) { match (protocols[0], protocols[1]) {
(Protocol::IP4, Protocol::TCP) => { (Protocol::IP4, Protocol::TCP) => {
let bs = addr.as_slice(); let bs = addr.as_slice();
Ok(SocketAddr::new( Ok(SocketAddr::new(
IpAddr::V4(Ipv4Addr::new(bs[1], bs[2], bs[3], bs[4])), IpAddr::V4(Ipv4Addr::new(bs[1], bs[2], bs[3], bs[4])),
(bs[6] as u16) << 8 | bs[7] as u16 (bs[6] as u16) << 8 | bs[7] as u16,
)) ))
}, }
(Protocol::IP6, Protocol::TCP) => { (Protocol::IP6, Protocol::TCP) => {
let bs = addr.as_slice(); let bs = addr.as_slice();
if let Ok(Some(s)) = Protocol::IP6.bytes_to_string(&bs[1..17]) { if let Ok(Some(s)) = Protocol::IP6.bytes_to_string(&bs[1..17]) {
if let Ok(ipv6addr) = s.parse() { if let Ok(ipv6addr) = s.parse() {
return Ok(SocketAddr::new(IpAddr::V6(ipv6addr), (bs[18] as u16) << 8 | bs[19] as u16)) return Ok(SocketAddr::new(
IpAddr::V6(ipv6addr),
(bs[18] as u16) << 8 | bs[19] as u16,
));
} }
} }
Err(addr) Err(addr)
}, }
_ => Err(addr), _ => Err(addr),
} }
} }
@ -97,23 +106,46 @@ mod tests {
#[test] #[test]
fn multiaddr_to_tcp_conversion() { fn multiaddr_to_tcp_conversion() {
use std::net::{Ipv6Addr}; use std::net::Ipv6Addr;
assert_eq!( assert_eq!(
multiaddr_to_socketaddr(&Multiaddr::new("/ip4/127.0.0.1/tcp/12345").unwrap()), multiaddr_to_socketaddr(&Multiaddr::new("/ip4/127.0.0.1/tcp/12345").unwrap()),
Ok(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 12345)) Ok(SocketAddr::new(
IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
12345,
))
); );
assert_eq!( assert_eq!(
multiaddr_to_socketaddr(&Multiaddr::new("/ip4/255.255.255.255/tcp/8080").unwrap()), multiaddr_to_socketaddr(&Multiaddr::new("/ip4/255.255.255.255/tcp/8080").unwrap()),
Ok(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(255, 255, 255, 255)), 8080)) Ok(SocketAddr::new(
IpAddr::V4(Ipv4Addr::new(255, 255, 255, 255)),
8080,
))
); );
assert_eq!( assert_eq!(
multiaddr_to_socketaddr(&Multiaddr::new("/ip6/::1/tcp/12345").unwrap()), multiaddr_to_socketaddr(&Multiaddr::new("/ip6/::1/tcp/12345").unwrap()),
Ok(SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 12345)) Ok(SocketAddr::new(
IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)),
12345,
))
); );
assert_eq!( assert_eq!(
multiaddr_to_socketaddr(&Multiaddr::new("/ip6/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/tcp/8080").unwrap()), multiaddr_to_socketaddr(&Multiaddr::new(
Ok(SocketAddr::new(IpAddr::V6(Ipv6Addr::new(65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535)), 8080)) "/ip6/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/tcp/8080",
).unwrap()),
Ok(SocketAddr::new(
IpAddr::V6(Ipv6Addr::new(
65535,
65535,
65535,
65535,
65535,
65535,
65535,
65535,
)),
8080,
))
); );
} }
@ -121,8 +153,6 @@ mod tests {
fn communicating_between_dialer_and_listener() { fn communicating_between_dialer_and_listener() {
use std::io::Write; use std::io::Write;
/// This thread is running the listener
/// while the main thread runs the dialer
std::thread::spawn(move || { std::thread::spawn(move || {
let addr = Multiaddr::new("/ip4/127.0.0.1/tcp/12345").unwrap(); let addr = Multiaddr::new("/ip4/127.0.0.1/tcp/12345").unwrap();
let mut tcp = Tcp::new().unwrap(); let mut tcp = Tcp::new().unwrap();
@ -130,11 +160,9 @@ mod tests {
let listener = tcp.listen_on(addr).unwrap().for_each(|sock| { let listener = tcp.listen_on(addr).unwrap().for_each(|sock| {
// Define what to do with the socket that just connected to us // Define what to do with the socket that just connected to us
// Which in this case is read 3 bytes // Which in this case is read 3 bytes
let handle_conn = tokio_io::io::read_exact(sock, [0; 3]).map(|(_, buf)| { let handle_conn = tokio_io::io::read_exact(sock, [0; 3])
assert_eq!(buf, [1,2,3]) .map(|(_, buf)| assert_eq!(buf, [1, 2, 3]))
}).map_err(|err| { .map_err(|err| panic!("IO error {:?}", err));
panic!("IO error {:?}", err)
});
// Spawn the future as a concurrent task // Spawn the future as a concurrent task
handle.spawn(handle_conn); handle.spawn(handle_conn);
@ -150,14 +178,12 @@ mod tests {
// Obtain a future socket through dialing // Obtain a future socket through dialing
let socket = tcp.dial(addr.clone()).unwrap(); let socket = tcp.dial(addr.clone()).unwrap();
// Define what to do with the socket once it's obtained // Define what to do with the socket once it's obtained
let action = socket.then(|sock| { let action = socket.then(|sock| match sock {
match sock {
Ok(mut s) => { Ok(mut s) => {
let written = s.write(&[0x1, 0x2, 0x3]).unwrap(); let written = s.write(&[0x1, 0x2, 0x3]).unwrap();
Ok(written) Ok(written)
} }
Err(x) => Err(x) Err(x) => Err(x),
}
}); });
// Execute the future in our event loop // Execute the future in our event loop
tcp.event_loop.run(action).unwrap(); tcp.event_loop.run(action).unwrap();

View File

@ -19,21 +19,24 @@ pub type PeerId = String;
/// A logical wire between us and a peer. We can read and write through this asynchronously. /// A logical wire between us and a peer. We can read and write through this asynchronously.
/// ///
/// You can have multiple `Socket`s between you and any given peer. /// You can have multiple `Socket`s between you and any given peer.
pub trait Socket: AsyncRead + AsyncWrite { pub trait Socket: AsyncRead + AsyncWrite + Sized {
type Conn: Conn<Socket = Self>;
/// Get the protocol ID this socket uses. /// Get the protocol ID this socket uses.
fn protocol_id(&self) -> ProtocolId; fn protocol_id(&self) -> ProtocolId;
/// Access the underlying connection. /// Access the underlying connection.
fn conn(&self) -> &Conn<Socket=Self>; fn conn(&self) -> &Self::Conn;
} }
/// A connection between you and a peer. /// A connection between you and a peer.
pub trait Conn { pub trait Conn {
/// The socket type this connection manages. /// The socket type this connection manages.
type Socket; type Socket;
type SocketFuture: IntoFuture<Item = Self::Socket, Error = IoError>;
/// Initiate a socket between you and the peer on the given protocol. /// Initiate a socket between you and the peer on the given protocol.
fn make_socket(&self, proto: ProtocolId) -> Box<Future<Item=Self::Socket, Error=IoError>>; fn make_socket(&self, proto: ProtocolId) -> Self::SocketFuture;
} }
/// A transport is a stream producing incoming connections. /// A transport is a stream producing incoming connections.