Simplify handling of upgrade information. (#761)

This commit is contained in:
Toralf Wittner 2018-12-11 15:13:10 +01:00 committed by GitHub
parent 2dce4294a0
commit a152e18821
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
25 changed files with 346 additions and 377 deletions

View File

@ -18,7 +18,7 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use crate::{muxing::{Shutdown, StreamMuxer}, Multiaddr}; use crate::{muxing::{Shutdown, StreamMuxer}, Multiaddr, ProtocolName};
use futures::prelude::*; use futures::prelude::*;
use std::{fmt, io::{Error as IoError, Read, Write}}; use std::{fmt, io::{Error as IoError, Read, Write}};
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
@ -342,3 +342,14 @@ where
} }
} }
#[derive(Debug, Clone)]
pub enum EitherName<A, B> { A(A), B(B) }
impl<A: ProtocolName, B: ProtocolName> ProtocolName for EitherName<A, B> {
fn protocol_name(&self) -> &[u8] {
match self {
EitherName::A(a) => a.protocol_name(),
EitherName::B(b) => b.protocol_name()
}
}
}

View File

@ -111,7 +111,7 @@ pub use self::protocols_handler::{ProtocolsHandler, ProtocolsHandlerEvent};
pub use self::public_key::PublicKey; pub use self::public_key::PublicKey;
pub use self::swarm::Swarm; pub use self::swarm::Swarm;
pub use self::transport::Transport; pub use self::transport::Transport;
pub use self::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo, UpgradeError}; pub use self::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo, UpgradeError, ProtocolName};
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Endpoint { pub enum Endpoint {

View File

@ -19,7 +19,7 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use crate::{ use crate::{
Transport, Multiaddr, PublicKey, PeerId, InboundUpgrade, OutboundUpgrade, UpgradeInfo, Transport, Multiaddr, PublicKey, PeerId, InboundUpgrade, OutboundUpgrade, UpgradeInfo, ProtocolName,
muxing::StreamMuxer, muxing::StreamMuxer,
nodes::{ nodes::{
handled_node::NodeHandler, handled_node::NodeHandler,
@ -104,13 +104,15 @@ where TBehaviour: NetworkBehaviour<TTopology>,
<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutEvent: Send + 'static, <TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutEvent: Send + 'static,
<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundOpenInfo: Send + 'static, // TODO: shouldn't be necessary <TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundOpenInfo: Send + 'static, // TODO: shouldn't be necessary
<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol: InboundUpgrade<Substream<TMuxer>> + Send + 'static, <TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol: InboundUpgrade<Substream<TMuxer>> + Send + 'static,
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as UpgradeInfo>::NamesIter: Send + 'static, <<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as UpgradeInfo>::Info: Send + 'static,
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as UpgradeInfo>::UpgradeId: Send + 'static, <<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as UpgradeInfo>::InfoIter: Send + 'static,
<<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as UpgradeInfo>::InfoIter as IntoIterator>::IntoIter: Send + 'static,
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as InboundUpgrade<Substream<TMuxer>>>::Error: fmt::Debug + Send + 'static, <<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as InboundUpgrade<Substream<TMuxer>>>::Error: fmt::Debug + Send + 'static,
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as InboundUpgrade<Substream<TMuxer>>>::Future: Send + 'static, <<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as InboundUpgrade<Substream<TMuxer>>>::Future: Send + 'static,
<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol: OutboundUpgrade<Substream<TMuxer>> + Send + 'static, <TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol: OutboundUpgrade<Substream<TMuxer>> + Send + 'static,
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as UpgradeInfo>::NamesIter: Send + 'static, <<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as UpgradeInfo>::Info: Send + 'static,
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as UpgradeInfo>::UpgradeId: Send + 'static, <<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as UpgradeInfo>::InfoIter: Send + 'static,
<<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as UpgradeInfo>::InfoIter as IntoIterator>::IntoIter: Send + 'static,
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as OutboundUpgrade<Substream<TMuxer>>>::Future: Send + 'static, <<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as OutboundUpgrade<Substream<TMuxer>>>::Future: Send + 'static,
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as OutboundUpgrade<Substream<TMuxer>>>::Error: fmt::Debug + Send + 'static, <<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as OutboundUpgrade<Substream<TMuxer>>>::Error: fmt::Debug + Send + 'static,
<NodeHandlerWrapper<TBehaviour::ProtocolsHandler> as NodeHandler>::OutboundOpenInfo: Send + 'static, // TODO: shouldn't be necessary <NodeHandlerWrapper<TBehaviour::ProtocolsHandler> as NodeHandler>::OutboundOpenInfo: Send + 'static, // TODO: shouldn't be necessary
@ -122,8 +124,9 @@ where TBehaviour: NetworkBehaviour<TTopology>,
let supported_protocols = behaviour let supported_protocols = behaviour
.new_handler() .new_handler()
.listen_protocol() .listen_protocol()
.protocol_names() .protocol_info()
.map(|(name, _)| name.to_vec()) .into_iter()
.map(|info| info.protocol_name().to_vec())
.collect(); .collect();
let local_peer_id = local_public_key.clone().into_peer_id(); let local_peer_id = local_public_key.clone().into_peer_id();
@ -222,13 +225,15 @@ where TBehaviour: NetworkBehaviour<TTopology>,
<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol: InboundUpgrade<Substream<TMuxer>> + Send + 'static, <TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol: InboundUpgrade<Substream<TMuxer>> + Send + 'static,
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as InboundUpgrade<Substream<TMuxer>>>::Future: Send + 'static, <<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as InboundUpgrade<Substream<TMuxer>>>::Future: Send + 'static,
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as InboundUpgrade<Substream<TMuxer>>>::Error: fmt::Debug + Send + 'static, <<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as InboundUpgrade<Substream<TMuxer>>>::Error: fmt::Debug + Send + 'static,
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as UpgradeInfo>::NamesIter: Send + 'static, <<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as UpgradeInfo>::Info: Send + 'static,
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as UpgradeInfo>::UpgradeId: Send + 'static, <<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as UpgradeInfo>::InfoIter: Send + 'static,
<<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as UpgradeInfo>::InfoIter as IntoIterator>::IntoIter: Send + 'static,
<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol: OutboundUpgrade<Substream<TMuxer>> + Send + 'static, <TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol: OutboundUpgrade<Substream<TMuxer>> + Send + 'static,
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as OutboundUpgrade<Substream<TMuxer>>>::Future: Send + 'static, <<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as OutboundUpgrade<Substream<TMuxer>>>::Future: Send + 'static,
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as OutboundUpgrade<Substream<TMuxer>>>::Error: fmt::Debug + Send + 'static, <<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as OutboundUpgrade<Substream<TMuxer>>>::Error: fmt::Debug + Send + 'static,
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as UpgradeInfo>::NamesIter: Send + 'static, <<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as UpgradeInfo>::Info: Send + 'static,
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as UpgradeInfo>::UpgradeId: Send + 'static, <<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as UpgradeInfo>::InfoIter: Send + 'static,
<<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as UpgradeInfo>::InfoIter as IntoIterator>::IntoIter: Send + 'static,
<NodeHandlerWrapper<TBehaviour::ProtocolsHandler> as NodeHandler>::OutboundOpenInfo: Send + 'static, // TODO: shouldn't be necessary <NodeHandlerWrapper<TBehaviour::ProtocolsHandler> as NodeHandler>::OutboundOpenInfo: Send + 'static, // TODO: shouldn't be necessary
TTopology: Topology, TTopology: Topology,
{ {
@ -392,7 +397,7 @@ impl<'a, TTopology> PollParameters<'a, TTopology> {
/// Returns the public key of the local node. /// Returns the public key of the local node.
#[inline] #[inline]
pub fn local_public_key(&self) -> &PublicKey { pub fn local_public_key(&self) -> &PublicKey {
self.local_public_key self.local_public_key
} }

View File

@ -18,9 +18,8 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use bytes::Bytes;
use crate::nodes::ConnectedPoint; use crate::nodes::ConnectedPoint;
use crate::upgrade::{UpgradeInfo, InboundUpgrade, OutboundUpgrade, UpgradeError}; use crate::upgrade::{UpgradeInfo, InboundUpgrade, OutboundUpgrade, UpgradeError, ProtocolName};
use futures::{future::Either, prelude::*}; use futures::{future::Either, prelude::*};
use multistream_select::{self, DialerSelectFuture, ListenerSelectFuture}; use multistream_select::{self, DialerSelectFuture, ListenerSelectFuture};
use std::mem; use std::mem;
@ -46,7 +45,8 @@ where
C: AsyncRead + AsyncWrite, C: AsyncRead + AsyncWrite,
U: InboundUpgrade<C>, U: InboundUpgrade<C>,
{ {
let future = multistream_select::listener_select_proto(conn, UpgradeIntoProtocolsIterWrap(up)); let iter = UpgradeInfoIterWrap(up);
let future = multistream_select::listener_select_proto(conn, iter);
InboundUpgradeApply { InboundUpgradeApply {
inner: InboundUpgradeApplyState::Init { future } inner: InboundUpgradeApplyState::Init { future }
} }
@ -58,7 +58,7 @@ where
C: AsyncRead + AsyncWrite, C: AsyncRead + AsyncWrite,
U: OutboundUpgrade<C> U: OutboundUpgrade<C>
{ {
let iter = ProtocolNames(up.protocol_names()); let iter = up.protocol_info().into_iter().map(NameWrap as fn(_) -> NameWrap<_>);
let future = multistream_select::dialer_select_proto(conn, iter); let future = multistream_select::dialer_select_proto(conn, iter);
OutboundUpgradeApply { OutboundUpgradeApply {
inner: OutboundUpgradeApplyState::Init { future, upgrade: up } inner: OutboundUpgradeApplyState::Init { future, upgrade: up }
@ -80,7 +80,7 @@ where
U: InboundUpgrade<C> U: InboundUpgrade<C>
{ {
Init { Init {
future: ListenerSelectFuture<C, UpgradeIntoProtocolsIterWrap<U>, U::UpgradeId>, future: ListenerSelectFuture<C, UpgradeInfoIterWrap<U>, NameWrap<U::Info>>,
}, },
Upgrade { Upgrade {
future: U::Future future: U::Future
@ -100,7 +100,7 @@ where
loop { loop {
match mem::replace(&mut self.inner, InboundUpgradeApplyState::Undefined) { match mem::replace(&mut self.inner, InboundUpgradeApplyState::Undefined) {
InboundUpgradeApplyState::Init { mut future } => { InboundUpgradeApplyState::Init { mut future } => {
let (upgrade_id, connection, upgrade) = match future.poll()? { let (info, connection, upgrade) = match future.poll()? {
Async::Ready(x) => x, Async::Ready(x) => x,
Async::NotReady => { Async::NotReady => {
self.inner = InboundUpgradeApplyState::Init { future }; self.inner = InboundUpgradeApplyState::Init { future };
@ -108,7 +108,7 @@ where
} }
}; };
self.inner = InboundUpgradeApplyState::Upgrade { self.inner = InboundUpgradeApplyState::Upgrade {
future: upgrade.0.upgrade_inbound(connection, upgrade_id) future: upgrade.0.upgrade_inbound(connection, info.0)
}; };
} }
InboundUpgradeApplyState::Upgrade { mut future } => { InboundUpgradeApplyState::Upgrade { mut future } => {
@ -149,7 +149,7 @@ where
U: OutboundUpgrade<C> U: OutboundUpgrade<C>
{ {
Init { Init {
future: DialerSelectFuture<C, ProtocolNames<U::NamesIter>, U::UpgradeId>, future: DialerSelectFuture<C, NameWrapIter<<U::InfoIter as IntoIterator>::IntoIter>>,
upgrade: U upgrade: U
}, },
Upgrade { Upgrade {
@ -170,7 +170,7 @@ where
loop { loop {
match mem::replace(&mut self.inner, OutboundUpgradeApplyState::Undefined) { match mem::replace(&mut self.inner, OutboundUpgradeApplyState::Undefined) {
OutboundUpgradeApplyState::Init { mut future, upgrade } => { OutboundUpgradeApplyState::Init { mut future, upgrade } => {
let (upgrade_id, connection) = match future.poll()? { let (info, connection) = match future.poll()? {
Async::Ready(x) => x, Async::Ready(x) => x,
Async::NotReady => { Async::NotReady => {
self.inner = OutboundUpgradeApplyState::Init { future, upgrade }; self.inner = OutboundUpgradeApplyState::Init { future, upgrade };
@ -178,7 +178,7 @@ where
} }
}; };
self.inner = OutboundUpgradeApplyState::Upgrade { self.inner = OutboundUpgradeApplyState::Upgrade {
future: upgrade.upgrade_outbound(connection, upgrade_id) future: upgrade.upgrade_outbound(connection, info.0)
}; };
} }
OutboundUpgradeApplyState::Upgrade { mut future } => { OutboundUpgradeApplyState::Upgrade { mut future } => {
@ -205,37 +205,29 @@ where
} }
/// Wraps around a `UpgradeInfo` and satisfies the requirement of `listener_select_proto`. /// Wraps around a `UpgradeInfo` and satisfies the requirement of `listener_select_proto`.
struct UpgradeIntoProtocolsIterWrap<U>(U); struct UpgradeInfoIterWrap<U>(U);
impl<'a, U> IntoIterator for &'a UpgradeIntoProtocolsIterWrap<U> impl<'a, U> IntoIterator for &'a UpgradeInfoIterWrap<U>
where U: UpgradeInfo
{
type Item = (Bytes, fn(&Bytes, &Bytes) -> bool, U::UpgradeId);
type IntoIter = ProtocolNames<U::NamesIter>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
ProtocolNames(self.0.protocol_names())
}
}
/// Iterator adapter which adds equality matching predicates to items.
/// Used in `NegotiationFuture`.
#[derive(Clone)]
pub struct ProtocolNames<I>(I);
impl<I, Id> Iterator for ProtocolNames<I>
where where
I: Iterator<Item=(Bytes, Id)> U: UpgradeInfo
{ {
type Item = (Bytes, fn(&Bytes, &Bytes) -> bool, Id); type Item = NameWrap<U::Info>;
type IntoIter = NameWrapIter<<U::InfoIter as IntoIterator>::IntoIter>;
fn next(&mut self) -> Option<Self::Item> { fn into_iter(self) -> Self::IntoIter {
let f = <Bytes as PartialEq>::eq as fn(&Bytes, &Bytes) -> bool; self.0.protocol_info().into_iter().map(NameWrap)
self.0.next().map(|(b, id)| (b, f, id))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
} }
} }
type NameWrapIter<I> =
std::iter::Map<I, fn(<I as Iterator>::Item) -> NameWrap<<I as Iterator>::Item>>;
/// Wrapper type to expose an `AsRef<[u8]>` impl for all types implementing `ProtocolName`.
struct NameWrap<N>(N);
impl<N: ProtocolName> AsRef<[u8]> for NameWrap<N> {
fn as_ref(&self) -> &[u8] {
self.0.protocol_name()
}
}

View File

@ -18,11 +18,10 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use bytes::Bytes;
use crate::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}; use crate::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo};
use futures::future; use futures::future;
use std::iter; use std::iter;
use void::{unreachable, Void}; use void::Void;
/// Dummy implementation of `UpgradeInfo`/`InboundUpgrade`/`OutboundUpgrade` that doesn't support /// Dummy implementation of `UpgradeInfo`/`InboundUpgrade`/`OutboundUpgrade` that doesn't support
/// any protocol. /// any protocol.
@ -30,10 +29,10 @@ use void::{unreachable, Void};
pub struct DeniedUpgrade; pub struct DeniedUpgrade;
impl UpgradeInfo for DeniedUpgrade { impl UpgradeInfo for DeniedUpgrade {
type UpgradeId = Void; type Info = &'static [u8];
type NamesIter = iter::Empty<(Bytes, Self::UpgradeId)>; type InfoIter = iter::Empty<Self::Info>;
fn protocol_names(&self) -> Self::NamesIter { fn protocol_info(&self) -> Self::InfoIter {
iter::empty() iter::empty()
} }
} }
@ -43,8 +42,8 @@ impl<C> InboundUpgrade<C> for DeniedUpgrade {
type Error = Void; type Error = Void;
type Future = future::Empty<Self::Output, Self::Error>; type Future = future::Empty<Self::Output, Self::Error>;
fn upgrade_inbound(self, _: C, id: Self::UpgradeId) -> Self::Future { fn upgrade_inbound(self, _: C, _: Self::Info) -> Self::Future {
unreachable(id) future::empty()
} }
} }
@ -53,8 +52,8 @@ impl<C> OutboundUpgrade<C> for DeniedUpgrade {
type Error = Void; type Error = Void;
type Future = future::Empty<Self::Output, Self::Error>; type Future = future::Empty<Self::Output, Self::Error>;
fn upgrade_outbound(self, _: C, id: Self::UpgradeId) -> Self::Future { fn upgrade_outbound(self, _: C, _: Self::Info) -> Self::Future {
unreachable(id) future::empty()
} }
} }

View File

@ -18,10 +18,8 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use bytes::Bytes;
use futures::future::Either;
use crate::{ use crate::{
either::{EitherOutput, EitherError, EitherFuture2}, either::{EitherOutput, EitherError, EitherFuture2, EitherName},
upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo} upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}
}; };
@ -34,13 +32,16 @@ where
A: UpgradeInfo, A: UpgradeInfo,
B: UpgradeInfo B: UpgradeInfo
{ {
type UpgradeId = Either<A::UpgradeId, B::UpgradeId>; type Info = EitherName<A::Info, B::Info>;
type NamesIter = EitherIter<A::NamesIter, B::NamesIter>; type InfoIter = EitherIter<
<A::InfoIter as IntoIterator>::IntoIter,
<B::InfoIter as IntoIterator>::IntoIter
>;
fn protocol_names(&self) -> Self::NamesIter { fn protocol_info(&self) -> Self::InfoIter {
match self { match self {
EitherUpgrade::A(a) => EitherIter::A(a.protocol_names()), EitherUpgrade::A(a) => EitherIter::A(a.protocol_info().into_iter()),
EitherUpgrade::B(b) => EitherIter::B(b.protocol_names()) EitherUpgrade::B(b) => EitherIter::B(b.protocol_info().into_iter())
} }
} }
} }
@ -54,10 +55,10 @@ where
type Error = EitherError<EA, EB>; type Error = EitherError<EA, EB>;
type Future = EitherFuture2<A::Future, B::Future>; type Future = EitherFuture2<A::Future, B::Future>;
fn upgrade_inbound(self, sock: C, id: Self::UpgradeId) -> Self::Future { fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
match (self, id) { match (self, info) {
(EitherUpgrade::A(a), Either::A(id)) => EitherFuture2::A(a.upgrade_inbound(sock, id)), (EitherUpgrade::A(a), EitherName::A(info)) => EitherFuture2::A(a.upgrade_inbound(sock, info)),
(EitherUpgrade::B(b), Either::B(id)) => EitherFuture2::B(b.upgrade_inbound(sock, id)), (EitherUpgrade::B(b), EitherName::B(info)) => EitherFuture2::B(b.upgrade_inbound(sock, info)),
_ => panic!("Invalid invocation of EitherUpgrade::upgrade_inbound") _ => panic!("Invalid invocation of EitherUpgrade::upgrade_inbound")
} }
} }
@ -72,10 +73,10 @@ where
type Error = EitherError<EA, EB>; type Error = EitherError<EA, EB>;
type Future = EitherFuture2<A::Future, B::Future>; type Future = EitherFuture2<A::Future, B::Future>;
fn upgrade_outbound(self, sock: C, id: Self::UpgradeId) -> Self::Future { fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
match (self, id) { match (self, info) {
(EitherUpgrade::A(a), Either::A(id)) => EitherFuture2::A(a.upgrade_outbound(sock, id)), (EitherUpgrade::A(a), EitherName::A(info)) => EitherFuture2::A(a.upgrade_outbound(sock, info)),
(EitherUpgrade::B(b), Either::B(id)) => EitherFuture2::B(b.upgrade_outbound(sock, id)), (EitherUpgrade::B(b), EitherName::B(info)) => EitherFuture2::B(b.upgrade_outbound(sock, info)),
_ => panic!("Invalid invocation of EitherUpgrade::upgrade_outbound") _ => panic!("Invalid invocation of EitherUpgrade::upgrade_outbound")
} }
} }
@ -85,17 +86,17 @@ where
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum EitherIter<A, B> { A(A), B(B) } pub enum EitherIter<A, B> { A(A), B(B) }
impl<A, B, AId, BId> Iterator for EitherIter<A, B> impl<A, B> Iterator for EitherIter<A, B>
where where
A: Iterator<Item = (Bytes, AId)>, A: Iterator,
B: Iterator<Item = (Bytes, BId)>, B: Iterator
{ {
type Item = (Bytes, Either<AId, BId>); type Item = EitherName<A::Item, B::Item>;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
match self { match self {
EitherIter::A(a) => a.next().map(|(name, id)| (name, Either::A(id))), EitherIter::A(a) => a.next().map(EitherName::A),
EitherIter::B(b) => b.next().map(|(name, id)| (name, Either::B(id))) EitherIter::B(b) => b.next().map(EitherName::B)
} }
} }

View File

@ -35,11 +35,11 @@ impl<U, F> UpgradeInfo for MapInboundUpgrade<U, F>
where where
U: UpgradeInfo U: UpgradeInfo
{ {
type UpgradeId = U::UpgradeId; type Info = U::Info;
type NamesIter = U::NamesIter; type InfoIter = U::InfoIter;
fn protocol_names(&self) -> Self::NamesIter { fn protocol_info(&self) -> Self::InfoIter {
self.upgrade.protocol_names() self.upgrade.protocol_info()
} }
} }
@ -52,9 +52,9 @@ where
type Error = U::Error; type Error = U::Error;
type Future = MapFuture<U::Future, F>; type Future = MapFuture<U::Future, F>;
fn upgrade_inbound(self, sock: C, id: Self::UpgradeId) -> Self::Future { fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
MapFuture { MapFuture {
inner: self.upgrade.upgrade_inbound(sock, id), inner: self.upgrade.upgrade_inbound(sock, info),
map: Some(self.fun) map: Some(self.fun)
} }
} }
@ -68,8 +68,8 @@ where
type Error = U::Error; type Error = U::Error;
type Future = U::Future; type Future = U::Future;
fn upgrade_outbound(self, sock: C, id: Self::UpgradeId) -> Self::Future { fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
self.upgrade.upgrade_outbound(sock, id) self.upgrade.upgrade_outbound(sock, info)
} }
} }
@ -87,11 +87,11 @@ impl<U, F> UpgradeInfo for MapOutboundUpgrade<U, F>
where where
U: UpgradeInfo U: UpgradeInfo
{ {
type UpgradeId = U::UpgradeId; type Info = U::Info;
type NamesIter = U::NamesIter; type InfoIter = U::InfoIter;
fn protocol_names(&self) -> Self::NamesIter { fn protocol_info(&self) -> Self::InfoIter {
self.upgrade.protocol_names() self.upgrade.protocol_info()
} }
} }
@ -103,8 +103,8 @@ where
type Error = U::Error; type Error = U::Error;
type Future = U::Future; type Future = U::Future;
fn upgrade_inbound(self, sock: C, id: Self::UpgradeId) -> Self::Future { fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
self.upgrade.upgrade_inbound(sock, id) self.upgrade.upgrade_inbound(sock, info)
} }
} }
@ -117,9 +117,9 @@ where
type Error = U::Error; type Error = U::Error;
type Future = MapFuture<U::Future, F>; type Future = MapFuture<U::Future, F>;
fn upgrade_outbound(self, sock: C, id: Self::UpgradeId) -> Self::Future { fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
MapFuture { MapFuture {
inner: self.upgrade.upgrade_outbound(sock, id), inner: self.upgrade.upgrade_outbound(sock, info),
map: Some(self.fun) map: Some(self.fun)
} }
} }
@ -139,11 +139,11 @@ impl<U, F> UpgradeInfo for MapInboundUpgradeErr<U, F>
where where
U: UpgradeInfo U: UpgradeInfo
{ {
type UpgradeId = U::UpgradeId; type Info = U::Info;
type NamesIter = U::NamesIter; type InfoIter = U::InfoIter;
fn protocol_names(&self) -> Self::NamesIter { fn protocol_info(&self) -> Self::InfoIter {
self.upgrade.protocol_names() self.upgrade.protocol_info()
} }
} }
@ -156,9 +156,9 @@ where
type Error = T; type Error = T;
type Future = MapErrFuture<U::Future, F>; type Future = MapErrFuture<U::Future, F>;
fn upgrade_inbound(self, sock: C, id: Self::UpgradeId) -> Self::Future { fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
MapErrFuture { MapErrFuture {
fut: self.upgrade.upgrade_inbound(sock, id), fut: self.upgrade.upgrade_inbound(sock, info),
fun: Some(self.fun) fun: Some(self.fun)
} }
} }
@ -172,8 +172,8 @@ where
type Error = U::Error; type Error = U::Error;
type Future = U::Future; type Future = U::Future;
fn upgrade_outbound(self, sock: C, id: Self::UpgradeId) -> Self::Future { fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
self.upgrade.upgrade_outbound(sock, id) self.upgrade.upgrade_outbound(sock, info)
} }
} }
@ -191,11 +191,11 @@ impl<U, F> UpgradeInfo for MapOutboundUpgradeErr<U, F>
where where
U: UpgradeInfo U: UpgradeInfo
{ {
type UpgradeId = U::UpgradeId; type Info = U::Info;
type NamesIter = U::NamesIter; type InfoIter = U::InfoIter;
fn protocol_names(&self) -> Self::NamesIter { fn protocol_info(&self) -> Self::InfoIter {
self.upgrade.protocol_names() self.upgrade.protocol_info()
} }
} }
@ -208,9 +208,9 @@ where
type Error = T; type Error = T;
type Future = MapErrFuture<U::Future, F>; type Future = MapErrFuture<U::Future, F>;
fn upgrade_outbound(self, sock: C, id: Self::UpgradeId) -> Self::Future { fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
MapErrFuture { MapErrFuture {
fut: self.upgrade.upgrade_outbound(sock, id), fut: self.upgrade.upgrade_outbound(sock, info),
fun: Some(self.fun) fun: Some(self.fun)
} }
} }
@ -224,8 +224,8 @@ where
type Error = U::Error; type Error = U::Error;
type Future = U::Future; type Future = U::Future;
fn upgrade_inbound(self, sock: C, id: Self::UpgradeId) -> Self::Future { fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
self.upgrade.upgrade_inbound(sock, id) self.upgrade.upgrade_inbound(sock, info)
} }
} }

View File

@ -36,7 +36,7 @@
//! //!
//! An upgrade is performed in two steps: //! An upgrade is performed in two steps:
//! //!
//! - A protocol negotiation step. The `UpgradeInfo::protocol_names` method is called to determine //! - A protocol negotiation step. The `UpgradeInfo::protocol_info` method is called to determine
//! which protocols are supported by the trait implementation. The `multistream-select` protocol //! which protocols are supported by the trait implementation. The `multistream-select` protocol
//! is used in order to agree on which protocol to use amongst the ones supported. //! is used in order to agree on which protocol to use amongst the ones supported.
//! //!
@ -64,7 +64,6 @@ mod error;
mod map; mod map;
mod select; mod select;
use bytes::Bytes;
use futures::future::Future; use futures::future::Future;
pub use self::{ pub use self::{
@ -76,18 +75,28 @@ pub use self::{
select::SelectUpgrade select::SelectUpgrade
}; };
/// Types serving as protocol names.
pub trait ProtocolName {
/// The protocol name as bytes.
fn protocol_name(&self) -> &[u8];
}
impl<T: AsRef<[u8]>> ProtocolName for T {
fn protocol_name(&self) -> &[u8] {
self.as_ref()
}
}
/// Common trait for upgrades that can be applied on inbound substreams, outbound substreams, /// Common trait for upgrades that can be applied on inbound substreams, outbound substreams,
/// or both. /// or both.
pub trait UpgradeInfo { pub trait UpgradeInfo {
/// Opaque type representing a negotiable protocol. /// Opaque type representing a negotiable protocol.
type UpgradeId; type Info: ProtocolName;
/// Iterator returned by `protocol_names`. /// Iterator returned by `protocol_info`.
type NamesIter: Iterator<Item = (Bytes, Self::UpgradeId)>; type InfoIter: IntoIterator<Item = Self::Info>;
/// Returns the list of protocols that are supported. Used during the negotiation process. /// Returns the list of protocols that are supported. Used during the negotiation process.
/// fn protocol_info(&self) -> Self::InfoIter;
/// Each item returned by the iterator is a pair of a protocol name and an opaque identifier.
fn protocol_names(&self) -> Self::NamesIter;
} }
/// Possible upgrade on an inbound connection or substream. /// Possible upgrade on an inbound connection or substream.
@ -102,8 +111,8 @@ pub trait InboundUpgrade<C>: UpgradeInfo {
/// After we have determined that the remote supports one of the protocols we support, this /// After we have determined that the remote supports one of the protocols we support, this
/// method is called to start the handshake. /// method is called to start the handshake.
/// ///
/// The `id` is the identifier of the protocol, as produced by `protocol_names()`. /// The `info` is the identifier of the protocol, as produced by `protocol_info`.
fn upgrade_inbound(self, socket: C, id: Self::UpgradeId) -> Self::Future; fn upgrade_inbound(self, socket: C, info: Self::Info) -> Self::Future;
} }
/// Extension trait for `InboundUpgrade`. Automatically implemented on all types that implement /// Extension trait for `InboundUpgrade`. Automatically implemented on all types that implement
@ -142,8 +151,8 @@ pub trait OutboundUpgrade<C>: UpgradeInfo {
/// After we have determined that the remote supports one of the protocols we support, this /// After we have determined that the remote supports one of the protocols we support, this
/// method is called to start the handshake. /// method is called to start the handshake.
/// ///
/// The `id` is the identifier of the protocol, as produced by `protocol_names()`. /// The `info` is the identifier of the protocol, as produced by `protocol_info`.
fn upgrade_outbound(self, socket: C, id: Self::UpgradeId) -> Self::Future; fn upgrade_outbound(self, socket: C, info: Self::Info) -> Self::Future;
} }
/// Extention trait for `OutboundUpgrade`. Automatically implemented on all types that implement /// Extention trait for `OutboundUpgrade`. Automatically implemented on all types that implement

View File

@ -18,10 +18,8 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use bytes::Bytes;
use futures::future::Either;
use crate::{ use crate::{
either::{EitherOutput, EitherError, EitherFuture2}, either::{EitherOutput, EitherError, EitherFuture2, EitherName},
upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo} upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}
}; };
@ -46,11 +44,14 @@ where
A: UpgradeInfo, A: UpgradeInfo,
B: UpgradeInfo B: UpgradeInfo
{ {
type UpgradeId = Either<A::UpgradeId, B::UpgradeId>; type Info = EitherName<A::Info, B::Info>;
type NamesIter = NamesIterChain<A::NamesIter, B::NamesIter>; type InfoIter = InfoIterChain<
<A::InfoIter as IntoIterator>::IntoIter,
<B::InfoIter as IntoIterator>::IntoIter
>;
fn protocol_names(&self) -> Self::NamesIter { fn protocol_info(&self) -> Self::InfoIter {
NamesIterChain(self.0.protocol_names(), self.1.protocol_names()) InfoIterChain(self.0.protocol_info().into_iter(), self.1.protocol_info().into_iter())
} }
} }
@ -63,10 +64,10 @@ where
type Error = EitherError<EA, EB>; type Error = EitherError<EA, EB>;
type Future = EitherFuture2<A::Future, B::Future>; type Future = EitherFuture2<A::Future, B::Future>;
fn upgrade_inbound(self, sock: C, id: Self::UpgradeId) -> Self::Future { fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
match id { match info {
Either::A(id) => EitherFuture2::A(self.0.upgrade_inbound(sock, id)), EitherName::A(info) => EitherFuture2::A(self.0.upgrade_inbound(sock, info)),
Either::B(id) => EitherFuture2::B(self.1.upgrade_inbound(sock, id)) EitherName::B(info) => EitherFuture2::B(self.1.upgrade_inbound(sock, info))
} }
} }
} }
@ -80,31 +81,31 @@ where
type Error = EitherError<EA, EB>; type Error = EitherError<EA, EB>;
type Future = EitherFuture2<A::Future, B::Future>; type Future = EitherFuture2<A::Future, B::Future>;
fn upgrade_outbound(self, sock: C, id: Self::UpgradeId) -> Self::Future { fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
match id { match info {
Either::A(id) => EitherFuture2::A(self.0.upgrade_outbound(sock, id)), EitherName::A(info) => EitherFuture2::A(self.0.upgrade_outbound(sock, info)),
Either::B(id) => EitherFuture2::B(self.1.upgrade_outbound(sock, id)) EitherName::B(info) => EitherFuture2::B(self.1.upgrade_outbound(sock, info))
} }
} }
} }
/// Iterator that combines the protocol names of twp upgrades. /// Iterator that combines the protocol names of twp upgrades.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct NamesIterChain<A, B>(A, B); pub struct InfoIterChain<A, B>(A, B);
impl<A, B, AId, BId> Iterator for NamesIterChain<A, B> impl<A, B> Iterator for InfoIterChain<A, B>
where where
A: Iterator<Item = (Bytes, AId)>, A: Iterator,
B: Iterator<Item = (Bytes, BId)>, B: Iterator
{ {
type Item = (Bytes, Either<AId, BId>); type Item = EitherName<A::Item, B::Item>;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
if let Some((name, id)) = self.0.next() { if let Some(info) = self.0.next() {
return Some((name, Either::A(id))) return Some(EitherName::A(info))
} }
if let Some((name, id)) = self.1.next() { if let Some(info) = self.1.next() {
return Some((name, Either::B(id))) return Some(EitherName::B(info))
} }
None None
} }

View File

@ -31,8 +31,7 @@ use crate::ProtocolChoiceError;
/// Future, returned by `dialer_select_proto`, which selects a protocol and dialer /// Future, returned by `dialer_select_proto`, which selects a protocol and dialer
/// either sequentially of by considering all protocols in parallel. /// either sequentially of by considering all protocols in parallel.
pub type DialerSelectFuture<R, I, P> = pub type DialerSelectFuture<R, I> = Either<DialerSelectSeq<R, I>, DialerSelectPar<R, I>>;
Either<DialerSelectSeq<R, IgnoreMatchFn<I>, P>, DialerSelectPar<R, I, P>>;
/// Helps selecting a protocol amongst the ones supported. /// Helps selecting a protocol amongst the ones supported.
/// ///
@ -46,48 +45,30 @@ pub type DialerSelectFuture<R, I, P> =
/// success, the function returns the identifier (of type `P`), plus the socket which now uses that /// success, the function returns the identifier (of type `P`), plus the socket which now uses that
/// chosen protocol. /// chosen protocol.
#[inline] #[inline]
pub fn dialer_select_proto<R, I, M, P>(inner: R, protocols: I) -> DialerSelectFuture<R, I, P> pub fn dialer_select_proto<R, I>(inner: R, protocols: I) -> DialerSelectFuture<R, I::IntoIter>
where where
R: AsyncRead + AsyncWrite, R: AsyncRead + AsyncWrite,
I: Iterator<Item=(Bytes, M, P)>, I: IntoIterator,
M: FnMut(&Bytes, &Bytes) -> bool, I::Item: AsRef<[u8]>
{ {
let iter = protocols.into_iter();
// We choose between the "serial" and "parallel" strategies based on the number of protocols. // We choose between the "serial" and "parallel" strategies based on the number of protocols.
if protocols.size_hint().1.map(|n| n <= 3).unwrap_or(false) { if iter.size_hint().1.map(|n| n <= 3).unwrap_or(false) {
Either::A(dialer_select_proto_serial(inner, IgnoreMatchFn(protocols))) Either::A(dialer_select_proto_serial(inner, iter))
} else { } else {
Either::B(dialer_select_proto_parallel(inner, protocols)) Either::B(dialer_select_proto_parallel(inner, iter))
} }
} }
/// Iterator, which ignores match predicates of the iterator it wraps.
pub struct IgnoreMatchFn<I>(I);
impl<I, M, P> Iterator for IgnoreMatchFn<I>
where
I: Iterator<Item=(Bytes, M, P)>
{
type Item = (Bytes, P);
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|(b, _, p)| (b, p))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// Helps selecting a protocol amongst the ones supported. /// Helps selecting a protocol amongst the ones supported.
/// ///
/// Same as `dialer_select_proto`. Tries protocols one by one. The iterator doesn't need to produce /// Same as `dialer_select_proto`. Tries protocols one by one. The iterator doesn't need to produce
/// match functions, because it's not needed. /// match functions, because it's not needed.
pub fn dialer_select_proto_serial<R, I, P>(inner: R, protocols: I,) -> DialerSelectSeq<R, I, P> pub fn dialer_select_proto_serial<R, I>(inner: R, protocols: I,) -> DialerSelectSeq<R, I>
where where
R: AsyncRead + AsyncWrite, R: AsyncRead + AsyncWrite,
I: Iterator<Item = (Bytes, P)>, I: Iterator,
I::Item: AsRef<[u8]>
{ {
DialerSelectSeq { DialerSelectSeq {
inner: DialerSelectSeqState::AwaitDialer { dialer_fut: Dialer::new(inner), protocols } inner: DialerSelectSeqState::AwaitDialer { dialer_fut: Dialer::new(inner), protocols }
@ -97,11 +78,11 @@ where
/// Future, returned by `dialer_select_proto_serial` which selects a protocol /// Future, returned by `dialer_select_proto_serial` which selects a protocol
/// and dialer sequentially. /// and dialer sequentially.
pub struct DialerSelectSeq<R: AsyncRead + AsyncWrite, I, P> { pub struct DialerSelectSeq<R: AsyncRead + AsyncWrite, I: Iterator> {
inner: DialerSelectSeqState<R, I, P> inner: DialerSelectSeqState<R, I>
} }
enum DialerSelectSeqState<R: AsyncRead + AsyncWrite, I, P> { enum DialerSelectSeqState<R: AsyncRead + AsyncWrite, I: Iterator> {
AwaitDialer { AwaitDialer {
dialer_fut: DialerFuture<R>, dialer_fut: DialerFuture<R>,
protocols: I protocols: I
@ -112,25 +93,24 @@ enum DialerSelectSeqState<R: AsyncRead + AsyncWrite, I, P> {
}, },
SendProtocol { SendProtocol {
sender: sink::Send<Dialer<R>>, sender: sink::Send<Dialer<R>>,
proto_name: Bytes, proto_name: I::Item,
proto_value: P,
protocols: I protocols: I
}, },
AwaitProtocol { AwaitProtocol {
stream: StreamFuture<Dialer<R>>, stream: StreamFuture<Dialer<R>>,
proto_name: Bytes, proto_name: I::Item,
proto_value: P,
protocols: I protocols: I
}, },
Undefined Undefined
} }
impl<R, I, P> Future for DialerSelectSeq<R, I, P> impl<R, I> Future for DialerSelectSeq<R, I>
where where
I: Iterator<Item=(Bytes, P)>, I: Iterator,
I::Item: AsRef<[u8]>,
R: AsyncRead + AsyncWrite, R: AsyncRead + AsyncWrite,
{ {
type Item = (P, R); type Item = (I::Item, R);
type Error = ProtocolChoiceError; type Error = ProtocolChoiceError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
@ -147,28 +127,26 @@ where
self.inner = DialerSelectSeqState::NextProtocol { dialer, protocols } self.inner = DialerSelectSeqState::NextProtocol { dialer, protocols }
} }
DialerSelectSeqState::NextProtocol { dialer, mut protocols } => { DialerSelectSeqState::NextProtocol { dialer, mut protocols } => {
let (proto_name, proto_value) = let proto_name =
protocols.next().ok_or(ProtocolChoiceError::NoProtocolFound)?; protocols.next().ok_or(ProtocolChoiceError::NoProtocolFound)?;
let req = DialerToListenerMessage::ProtocolRequest { let req = DialerToListenerMessage::ProtocolRequest {
name: proto_name.clone() name: Bytes::from(proto_name.as_ref())
}; };
trace!("sending {:?}", req); trace!("sending {:?}", req);
let sender = dialer.send(req); let sender = dialer.send(req);
self.inner = DialerSelectSeqState::SendProtocol { self.inner = DialerSelectSeqState::SendProtocol {
sender, sender,
proto_name, proto_name,
proto_value,
protocols protocols
} }
} }
DialerSelectSeqState::SendProtocol { mut sender, proto_name, proto_value, protocols } => { DialerSelectSeqState::SendProtocol { mut sender, proto_name, protocols } => {
let dialer = match sender.poll()? { let dialer = match sender.poll()? {
Async::Ready(d) => d, Async::Ready(d) => d,
Async::NotReady => { Async::NotReady => {
self.inner = DialerSelectSeqState::SendProtocol { self.inner = DialerSelectSeqState::SendProtocol {
sender, sender,
proto_name, proto_name,
proto_value,
protocols protocols
}; };
return Ok(Async::NotReady) return Ok(Async::NotReady)
@ -178,18 +156,16 @@ where
self.inner = DialerSelectSeqState::AwaitProtocol { self.inner = DialerSelectSeqState::AwaitProtocol {
stream, stream,
proto_name, proto_name,
proto_value,
protocols protocols
}; };
} }
DialerSelectSeqState::AwaitProtocol { mut stream, proto_name, proto_value, protocols } => { DialerSelectSeqState::AwaitProtocol { mut stream, proto_name, protocols } => {
let (m, r) = match stream.poll() { let (m, r) = match stream.poll() {
Ok(Async::Ready(x)) => x, Ok(Async::Ready(x)) => x,
Ok(Async::NotReady) => { Ok(Async::NotReady) => {
self.inner = DialerSelectSeqState::AwaitProtocol { self.inner = DialerSelectSeqState::AwaitProtocol {
stream, stream,
proto_name, proto_name,
proto_value,
protocols protocols
}; };
return Ok(Async::NotReady) return Ok(Async::NotReady)
@ -198,8 +174,10 @@ where
}; };
trace!("received {:?}", m); trace!("received {:?}", m);
match m.ok_or(ProtocolChoiceError::UnexpectedMessage)? { match m.ok_or(ProtocolChoiceError::UnexpectedMessage)? {
ListenerToDialerMessage::ProtocolAck { ref name } if name == &proto_name => { ListenerToDialerMessage::ProtocolAck { ref name }
return Ok(Async::Ready((proto_value, r.into_inner()))) if name.as_ref() == proto_name.as_ref() =>
{
return Ok(Async::Ready((proto_name, r.into_inner())))
}, },
ListenerToDialerMessage::NotAvailable => { ListenerToDialerMessage::NotAvailable => {
self.inner = DialerSelectSeqState::NextProtocol { dialer: r, protocols } self.inner = DialerSelectSeqState::NextProtocol { dialer: r, protocols }
@ -219,11 +197,11 @@ where
/// ///
/// Same as `dialer_select_proto`. Queries the list of supported protocols from the remote, then /// Same as `dialer_select_proto`. Queries the list of supported protocols from the remote, then
/// chooses the most appropriate one. /// chooses the most appropriate one.
pub fn dialer_select_proto_parallel<R, I, M, P>(inner: R, protocols: I) -> DialerSelectPar<R, I, P> pub fn dialer_select_proto_parallel<R, I>(inner: R, protocols: I) -> DialerSelectPar<R, I>
where where
R: AsyncRead + AsyncWrite, I: Iterator,
I: Iterator<Item = (Bytes, M, P)>, I::Item: AsRef<[u8]>,
M: FnMut(&Bytes, &Bytes) -> bool, R: AsyncRead + AsyncWrite
{ {
DialerSelectPar { DialerSelectPar {
inner: DialerSelectParState::AwaitDialer { dialer_fut: Dialer::new(inner), protocols } inner: DialerSelectParState::AwaitDialer { dialer_fut: Dialer::new(inner), protocols }
@ -234,11 +212,11 @@ where
/// Future, returned by `dialer_select_proto_parallel`, which selects a protocol and dialer in /// Future, returned by `dialer_select_proto_parallel`, which selects a protocol and dialer in
/// parellel, by first requesting the liste of protocols supported by the remote endpoint and /// parellel, by first requesting the liste of protocols supported by the remote endpoint and
/// then selecting the most appropriate one by applying a match predicate to the result. /// then selecting the most appropriate one by applying a match predicate to the result.
pub struct DialerSelectPar<R: AsyncRead + AsyncWrite, I, P> { pub struct DialerSelectPar<R: AsyncRead + AsyncWrite, I: Iterator> {
inner: DialerSelectParState<R, I, P> inner: DialerSelectParState<R, I>
} }
enum DialerSelectParState<R: AsyncRead + AsyncWrite, I, P> { enum DialerSelectParState<R: AsyncRead + AsyncWrite, I: Iterator> {
AwaitDialer { AwaitDialer {
dialer_fut: DialerFuture<R>, dialer_fut: DialerFuture<R>,
protocols: I protocols: I
@ -253,24 +231,22 @@ enum DialerSelectParState<R: AsyncRead + AsyncWrite, I, P> {
}, },
SendProtocol { SendProtocol {
sender: sink::Send<Dialer<R>>, sender: sink::Send<Dialer<R>>,
proto_name: Bytes, proto_name: I::Item
proto_val: P
}, },
AwaitProtocol { AwaitProtocol {
stream: StreamFuture<Dialer<R>>, stream: StreamFuture<Dialer<R>>,
proto_name: Bytes, proto_name: I::Item
proto_val: P
}, },
Undefined Undefined
} }
impl<R, I, M, P> Future for DialerSelectPar<R, I, P> impl<R, I> Future for DialerSelectPar<R, I>
where where
I: Iterator<Item=(Bytes, M, P)>, I: Iterator,
M: FnMut(&Bytes, &Bytes) -> bool, I::Item: AsRef<[u8]>,
R: AsyncRead + AsyncWrite, R: AsyncRead + AsyncWrite,
{ {
type Item = (P, R); type Item = (I::Item, R);
type Error = ProtocolChoiceError; type Error = ProtocolChoiceError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
@ -314,10 +290,10 @@ where
_ => return Err(ProtocolChoiceError::UnexpectedMessage), _ => return Err(ProtocolChoiceError::UnexpectedMessage),
}; };
let mut found = None; let mut found = None;
for (local_name, mut match_fn, ident) in protocols { for local_name in protocols {
for remote_name in &list { for remote_name in &list {
if match_fn(remote_name, &local_name) { if remote_name.as_ref() == local_name.as_ref() {
found = Some((remote_name.clone(), ident)); found = Some(local_name);
break; break;
} }
} }
@ -325,21 +301,20 @@ where
break; break;
} }
} }
let (proto_name, proto_val) = found.ok_or(ProtocolChoiceError::NoProtocolFound)?; let proto_name = found.ok_or(ProtocolChoiceError::NoProtocolFound)?;
trace!("sending {:?}", proto_name); trace!("sending {:?}", proto_name.as_ref());
let sender = d.send(DialerToListenerMessage::ProtocolRequest { let sender = d.send(DialerToListenerMessage::ProtocolRequest {
name: proto_name.clone(), name: Bytes::from(proto_name.as_ref())
}); });
self.inner = DialerSelectParState::SendProtocol { sender, proto_name, proto_val }; self.inner = DialerSelectParState::SendProtocol { sender, proto_name };
} }
DialerSelectParState::SendProtocol { mut sender, proto_name, proto_val } => { DialerSelectParState::SendProtocol { mut sender, proto_name } => {
let dialer = match sender.poll()? { let dialer = match sender.poll()? {
Async::Ready(d) => d, Async::Ready(d) => d,
Async::NotReady => { Async::NotReady => {
self.inner = DialerSelectParState::SendProtocol { self.inner = DialerSelectParState::SendProtocol {
sender, sender,
proto_name, proto_name
proto_val
}; };
return Ok(Async::NotReady) return Ok(Async::NotReady)
} }
@ -347,18 +322,16 @@ where
let stream = dialer.into_future(); let stream = dialer.into_future();
self.inner = DialerSelectParState::AwaitProtocol { self.inner = DialerSelectParState::AwaitProtocol {
stream, stream,
proto_name, proto_name
proto_val
}; };
} }
DialerSelectParState::AwaitProtocol { mut stream, proto_name, proto_val } => { DialerSelectParState::AwaitProtocol { mut stream, proto_name } => {
let (m, r) = match stream.poll() { let (m, r) = match stream.poll() {
Ok(Async::Ready(x)) => x, Ok(Async::Ready(x)) => x,
Ok(Async::NotReady) => { Ok(Async::NotReady) => {
self.inner = DialerSelectParState::AwaitProtocol { self.inner = DialerSelectParState::AwaitProtocol {
stream, stream,
proto_name, proto_name
proto_val
}; };
return Ok(Async::NotReady) return Ok(Async::NotReady)
} }
@ -366,8 +339,10 @@ where
}; };
trace!("received {:?}", m); trace!("received {:?}", m);
match m { match m {
Some(ListenerToDialerMessage::ProtocolAck { ref name }) if name == &proto_name => { Some(ListenerToDialerMessage::ProtocolAck { ref name })
return Ok(Async::Ready((proto_val, r.into_inner()))) if name.as_ref() == proto_name.as_ref() =>
{
return Ok(Async::Ready((proto_name, r.into_inner())))
} }
_ => return Err(ProtocolChoiceError::UnexpectedMessage) _ => return Err(ProtocolChoiceError::UnexpectedMessage)
} }

View File

@ -55,17 +55,12 @@
//! let client = TcpStream::connect(&"127.0.0.1:10333".parse().unwrap()) //! let client = TcpStream::connect(&"127.0.0.1:10333".parse().unwrap())
//! .from_err() //! .from_err()
//! .and_then(move |connec| { //! .and_then(move |connec| {
//! let protos = vec![ //! let protos = vec![b"/echo/1.0.0", b"/echo/2.5.0"];
//! (Bytes::from("/echo/1.0.0"), <Bytes as PartialEq>::eq, MyProto::Echo),
//! (Bytes::from("/hello/2.5.0"), <Bytes as PartialEq>::eq, MyProto::Hello),
//! ]
//! .into_iter();
//! dialer_select_proto(connec, protos).map(|r| r.0) //! dialer_select_proto(connec, protos).map(|r| r.0)
//! }); //! });
//! //!
//! let mut rt = Runtime::new().unwrap(); //! let mut rt = Runtime::new().unwrap();
//! let negotiated_protocol: MyProto = rt.block_on(client) //! let negotiated_protocol = rt.block_on(client).expect("failed to find a protocol");
//! .expect("failed to find a protocol");
//! println!("negotiated: {:?}", negotiated_protocol); //! println!("negotiated: {:?}", negotiated_protocol);
//! # } //! # }
//! ``` //! ```

View File

@ -43,23 +43,32 @@ use crate::ProtocolChoiceError;
/// ///
/// On success, returns the socket and the identifier of the chosen protocol (of type `P`). The /// On success, returns the socket and the identifier of the chosen protocol (of type `P`). The
/// socket now uses this protocol. /// socket now uses this protocol.
pub fn listener_select_proto<R, I, M, P>(inner: R, protocols: I) -> ListenerSelectFuture<R, I, P> pub fn listener_select_proto<R, I, X>(inner: R, protocols: I) -> ListenerSelectFuture<R, I, X>
where where
R: AsyncRead + AsyncWrite, R: AsyncRead + AsyncWrite,
for<'r> &'r I: IntoIterator<Item = (Bytes, M, P)>, for<'r> &'r I: IntoIterator<Item = X>,
M: FnMut(&Bytes, &Bytes) -> bool, X: AsRef<[u8]>
{ {
ListenerSelectFuture { ListenerSelectFuture {
inner: ListenerSelectState::AwaitListener { listener_fut: Listener::new(inner), protocols } inner: ListenerSelectState::AwaitListener {
listener_fut: Listener::new(inner),
protocols: protocols
}
} }
} }
/// Future, returned by `listener_select_proto` which selects a protocol among the ones supported. /// Future, returned by `listener_select_proto` which selects a protocol among the ones supported.
pub struct ListenerSelectFuture<R: AsyncRead + AsyncWrite, I, P> { pub struct ListenerSelectFuture<R: AsyncRead + AsyncWrite, I, X>
inner: ListenerSelectState<R, I, P> where
for<'a> &'a I: IntoIterator<Item = X>
{
inner: ListenerSelectState<R, I, X>
} }
enum ListenerSelectState<R: AsyncRead + AsyncWrite, I, P> { enum ListenerSelectState<R: AsyncRead + AsyncWrite, I, X>
where
for<'a> &'a I: IntoIterator<Item = X>
{
AwaitListener { AwaitListener {
listener_fut: ListenerFuture<R>, listener_fut: ListenerFuture<R>,
protocols: I protocols: I
@ -71,18 +80,18 @@ enum ListenerSelectState<R: AsyncRead + AsyncWrite, I, P> {
Outgoing { Outgoing {
sender: sink::Send<Listener<R>>, sender: sink::Send<Listener<R>>,
protocols: I, protocols: I,
outcome: Option<P> outcome: Option<X>
}, },
Undefined Undefined
} }
impl<R, I, M, P> Future for ListenerSelectFuture<R, I, P> impl<R, I, X> Future for ListenerSelectFuture<R, I, X>
where where
for<'r> &'r I: IntoIterator<Item=(Bytes, M, P)>, for<'a> &'a I: IntoIterator<Item = X>,
M: FnMut(&Bytes, &Bytes) -> bool,
R: AsyncRead + AsyncWrite, R: AsyncRead + AsyncWrite,
X: AsRef<[u8]>
{ {
type Item = (P, R, I); type Item = (X, R, I);
type Error = ProtocolChoiceError; type Error = ProtocolChoiceError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
@ -111,7 +120,7 @@ where
match msg { match msg {
Some(DialerToListenerMessage::ProtocolsListRequest) => { Some(DialerToListenerMessage::ProtocolsListRequest) => {
let msg = ListenerToDialerMessage::ProtocolsListResponse { let msg = ListenerToDialerMessage::ProtocolsListResponse {
list: protocols.into_iter().map(|(p, _, _)| p).collect(), list: protocols.into_iter().map(|x| Bytes::from(x.as_ref())).collect(),
}; };
trace!("protocols list response: {:?}", msg); trace!("protocols list response: {:?}", msg);
let sender = listener.send(msg); let sender = listener.send(msg);
@ -124,10 +133,10 @@ where
Some(DialerToListenerMessage::ProtocolRequest { name }) => { Some(DialerToListenerMessage::ProtocolRequest { name }) => {
let mut outcome = None; let mut outcome = None;
let mut send_back = ListenerToDialerMessage::NotAvailable; let mut send_back = ListenerToDialerMessage::NotAvailable;
for (supported, mut matches, value) in &protocols { for supported in &protocols {
if matches(&name, &supported) { if name.as_ref() == supported.as_ref() {
send_back = ListenerToDialerMessage::ProtocolAck {name: name.clone()}; send_back = ListenerToDialerMessage::ProtocolAck {name: name.clone()};
outcome = Some(value); outcome = Some(supported);
break; break;
} }
} }

View File

@ -95,27 +95,21 @@ fn select_proto_basic() {
.map(|s| s.0.unwrap()) .map(|s| s.0.unwrap())
.map_err(|(e, _)| e.into()) .map_err(|(e, _)| e.into())
.and_then(move |connec| { .and_then(move |connec| {
let protos = vec![ let protos = vec![b"/proto1", b"/proto2"];
(Bytes::from("/proto1"), <Bytes as PartialEq>::eq, 0),
(Bytes::from("/proto2"), <Bytes as PartialEq>::eq, 1),
];
listener_select_proto(connec, VecRefIntoIter(protos)).map(|r| r.0) listener_select_proto(connec, VecRefIntoIter(protos)).map(|r| r.0)
}); });
let client = TcpStream::connect(&listener_addr) let client = TcpStream::connect(&listener_addr)
.from_err() .from_err()
.and_then(move |connec| { .and_then(move |connec| {
let protos = vec![ let protos = vec![b"/proto3", b"/proto2"];
(Bytes::from("/proto3"), <Bytes as PartialEq>::eq, 2),
(Bytes::from("/proto2"), <Bytes as PartialEq>::eq, 3),
].into_iter();
dialer_select_proto(connec, protos).map(|r| r.0) dialer_select_proto(connec, protos).map(|r| r.0)
}); });
let mut rt = Runtime::new().unwrap(); let mut rt = Runtime::new().unwrap();
let (dialer_chosen, listener_chosen) = let (dialer_chosen, listener_chosen) =
rt.block_on(client.join(server)).unwrap(); rt.block_on(client.join(server)).unwrap();
assert_eq!(dialer_chosen, 3); assert_eq!(dialer_chosen, b"/proto2");
assert_eq!(listener_chosen, 1); assert_eq!(listener_chosen, b"/proto2");
} }
#[test] #[test]
@ -129,20 +123,14 @@ fn no_protocol_found() {
.map(|s| s.0.unwrap()) .map(|s| s.0.unwrap())
.map_err(|(e, _)| e.into()) .map_err(|(e, _)| e.into())
.and_then(move |connec| { .and_then(move |connec| {
let protos = vec![ let protos = vec![b"/proto1", b"/proto2"];
(Bytes::from("/proto1"), <Bytes as PartialEq>::eq, 1),
(Bytes::from("/proto2"), <Bytes as PartialEq>::eq, 2),
];
listener_select_proto(connec, VecRefIntoIter(protos)).map(|r| r.0) listener_select_proto(connec, VecRefIntoIter(protos)).map(|r| r.0)
}); });
let client = TcpStream::connect(&listener_addr) let client = TcpStream::connect(&listener_addr)
.from_err() .from_err()
.and_then(move |connec| { .and_then(move |connec| {
let protos = vec![ let protos = vec![b"/proto3", b"/proto4"];
(Bytes::from("/proto3"), <Bytes as PartialEq>::eq, 3),
(Bytes::from("/proto4"), <Bytes as PartialEq>::eq, 4),
].into_iter();
dialer_select_proto(connec, protos).map(|r| r.0) dialer_select_proto(connec, protos).map(|r| r.0)
}); });
let mut rt = Runtime::new().unwrap(); let mut rt = Runtime::new().unwrap();
@ -163,28 +151,22 @@ fn select_proto_parallel() {
.map(|s| s.0.unwrap()) .map(|s| s.0.unwrap())
.map_err(|(e, _)| e.into()) .map_err(|(e, _)| e.into())
.and_then(move |connec| { .and_then(move |connec| {
let protos = vec![ let protos = vec![b"/proto1", b"/proto2"];
(Bytes::from("/proto1"), <Bytes as PartialEq>::eq, 0),
(Bytes::from("/proto2"), <Bytes as PartialEq>::eq, 1),
];
listener_select_proto(connec, VecRefIntoIter(protos)).map(|r| r.0) listener_select_proto(connec, VecRefIntoIter(protos)).map(|r| r.0)
}); });
let client = TcpStream::connect(&listener_addr) let client = TcpStream::connect(&listener_addr)
.from_err() .from_err()
.and_then(move |connec| { .and_then(move |connec| {
let protos = vec![ let protos = vec![b"/proto3", b"/proto2"];
(Bytes::from("/proto3"), <Bytes as PartialEq>::eq, 2), dialer_select_proto_parallel(connec, protos.into_iter()).map(|r| r.0)
(Bytes::from("/proto2"), <Bytes as PartialEq>::eq, 3),
].into_iter();
dialer_select_proto_parallel(connec, protos).map(|r| r.0)
}); });
let mut rt = Runtime::new().unwrap(); let mut rt = Runtime::new().unwrap();
let (dialer_chosen, listener_chosen) = let (dialer_chosen, listener_chosen) =
rt.block_on(client.join(server)).unwrap(); rt.block_on(client.join(server)).unwrap();
assert_eq!(dialer_chosen, 3); assert_eq!(dialer_chosen, b"/proto2");
assert_eq!(listener_chosen, 1); assert_eq!(listener_chosen, b"/proto2");
} }
#[test] #[test]
@ -198,23 +180,20 @@ fn select_proto_serial() {
.map(|s| s.0.unwrap()) .map(|s| s.0.unwrap())
.map_err(|(e, _)| e.into()) .map_err(|(e, _)| e.into())
.and_then(move |connec| { .and_then(move |connec| {
let protos = vec![ let protos = vec![b"/proto1", b"/proto2"];
(Bytes::from("/proto1"), <Bytes as PartialEq>::eq, 0),
(Bytes::from("/proto2"), <Bytes as PartialEq>::eq, 1),
];
listener_select_proto(connec, VecRefIntoIter(protos)).map(|r| r.0) listener_select_proto(connec, VecRefIntoIter(protos)).map(|r| r.0)
}); });
let client = TcpStream::connect(&listener_addr) let client = TcpStream::connect(&listener_addr)
.from_err() .from_err()
.and_then(move |connec| { .and_then(move |connec| {
let protos = vec![(Bytes::from("/proto3"), 2), (Bytes::from("/proto2"), 3)].into_iter(); let protos = vec![b"/proto3", b"/proto2"];
dialer_select_proto_serial(connec, protos).map(|r| r.0) dialer_select_proto_serial(connec, protos.into_iter()).map(|r| r.0)
}); });
let mut rt = Runtime::new().unwrap(); let mut rt = Runtime::new().unwrap();
let (dialer_chosen, listener_chosen) = let (dialer_chosen, listener_chosen) =
rt.block_on(client.join(server)).unwrap(); rt.block_on(client.join(server)).unwrap();
assert_eq!(dialer_chosen, 3); assert_eq!(dialer_chosen, b"/proto2");
assert_eq!(listener_chosen, 1); assert_eq!(listener_chosen, b"/proto2");
} }

View File

@ -148,12 +148,12 @@ pub enum MaxBufferBehaviour {
} }
impl UpgradeInfo for MplexConfig { impl UpgradeInfo for MplexConfig {
type UpgradeId = (); type Info = &'static [u8];
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>; type InfoIter = iter::Once<Self::Info>;
#[inline] #[inline]
fn protocol_names(&self) -> Self::NamesIter { fn protocol_info(&self) -> Self::InfoIter {
iter::once((Bytes::from("/mplex/6.7.0"), ())) iter::once(b"/mplex/6.7.0")
} }
} }
@ -165,7 +165,7 @@ where
type Error = IoError; type Error = IoError;
type Future = future::FutureResult<Self::Output, IoError>; type Future = future::FutureResult<Self::Output, IoError>;
fn upgrade_inbound(self, socket: C, _: Self::UpgradeId) -> Self::Future { fn upgrade_inbound(self, socket: C, _: Self::Info) -> Self::Future {
future::ok(self.upgrade(socket, Endpoint::Listener)) future::ok(self.upgrade(socket, Endpoint::Listener))
} }
} }
@ -178,7 +178,7 @@ where
type Error = IoError; type Error = IoError;
type Future = future::FutureResult<Self::Output, IoError>; type Future = future::FutureResult<Self::Output, IoError>;
fn upgrade_outbound(self, socket: C, _: Self::UpgradeId) -> Self::Future { fn upgrade_outbound(self, socket: C, _: Self::Info) -> Self::Future {
future::ok(self.upgrade(socket, Endpoint::Dialer)) future::ok(self.upgrade(socket, Endpoint::Dialer))
} }
} }

View File

@ -9,7 +9,6 @@ keywords = ["peer-to-peer", "libp2p", "networking"]
categories = ["network-programming", "asynchronous"] categories = ["network-programming", "asynchronous"]
[dependencies] [dependencies]
bytes = "0.4"
futures = "0.1" futures = "0.1"
libp2p-core = { version = "0.1.0", path = "../../core" } libp2p-core = { version = "0.1.0", path = "../../core" }
log = "0.4" log = "0.4"

View File

@ -21,7 +21,6 @@
//! Implements the Yamux multiplexing protocol for libp2p, see also the //! Implements the Yamux multiplexing protocol for libp2p, see also the
//! [specification](https://github.com/hashicorp/yamux/blob/master/spec.md). //! [specification](https://github.com/hashicorp/yamux/blob/master/spec.md).
extern crate bytes;
extern crate futures; extern crate futures;
#[macro_use] #[macro_use]
extern crate log; extern crate log;
@ -29,7 +28,6 @@ extern crate libp2p_core;
extern crate tokio_io; extern crate tokio_io;
extern crate yamux; extern crate yamux;
use bytes::Bytes;
use futures::{future::{self, FutureResult}, prelude::*}; use futures::{future::{self, FutureResult}, prelude::*};
use libp2p_core::{muxing::Shutdown, upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}}; use libp2p_core::{muxing::Shutdown, upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}};
use std::{io, iter}; use std::{io, iter};
@ -136,11 +134,11 @@ impl Default for Config {
} }
impl UpgradeInfo for Config { impl UpgradeInfo for Config {
type UpgradeId = (); type Info = &'static [u8];
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>; type InfoIter = iter::Once<Self::Info>;
fn protocol_names(&self) -> Self::NamesIter { fn protocol_info(&self) -> Self::InfoIter {
iter::once((Bytes::from("/yamux/1.0.0"), ())) iter::once(b"/yamux/1.0.0")
} }
} }
@ -152,7 +150,7 @@ where
type Error = io::Error; type Error = io::Error;
type Future = FutureResult<Yamux<C>, io::Error>; type Future = FutureResult<Yamux<C>, io::Error>;
fn upgrade_inbound(self, i: C, _: Self::UpgradeId) -> Self::Future { fn upgrade_inbound(self, i: C, _: Self::Info) -> Self::Future {
future::ok(Yamux::new(i, self.0, yamux::Mode::Server)) future::ok(Yamux::new(i, self.0, yamux::Mode::Server))
} }
} }
@ -165,7 +163,7 @@ where
type Error = io::Error; type Error = io::Error;
type Future = FutureResult<Yamux<C>, io::Error>; type Future = FutureResult<Yamux<C>, io::Error>;
fn upgrade_outbound(self, i: C, _: Self::UpgradeId) -> Self::Future { fn upgrade_outbound(self, i: C, _: Self::Info) -> Self::Future {
future::ok(Yamux::new(i, self.0, yamux::Mode::Client)) future::ok(Yamux::new(i, self.0, yamux::Mode::Client))
} }
} }

View File

@ -18,7 +18,7 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use bytes::{BufMut, Bytes, BytesMut}; use bytes::{BufMut, BytesMut};
use crate::rpc_proto; use crate::rpc_proto;
use futures::future; use futures::future;
use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo, PeerId}; use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo, PeerId};
@ -42,12 +42,12 @@ impl FloodsubConfig {
} }
impl UpgradeInfo for FloodsubConfig { impl UpgradeInfo for FloodsubConfig {
type UpgradeId = (); type Info = &'static [u8];
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>; type InfoIter = iter::Once<Self::Info>;
#[inline] #[inline]
fn protocol_names(&self) -> Self::NamesIter { fn protocol_info(&self) -> Self::InfoIter {
iter::once(("/floodsub/1.0.0".into(), ())) iter::once(b"/floodsub/1.0.0")
} }
} }
@ -60,7 +60,7 @@ where
type Future = future::FutureResult<Self::Output, Self::Error>; type Future = future::FutureResult<Self::Output, Self::Error>;
#[inline] #[inline]
fn upgrade_inbound(self, socket: TSocket, _: Self::UpgradeId) -> Self::Future { fn upgrade_inbound(self, socket: TSocket, _: Self::Info) -> Self::Future {
future::ok(Framed::new(socket, FloodsubCodec { length_prefix: Default::default() })) future::ok(Framed::new(socket, FloodsubCodec { length_prefix: Default::default() }))
} }
} }
@ -74,7 +74,7 @@ where
type Future = future::FutureResult<Self::Output, Self::Error>; type Future = future::FutureResult<Self::Output, Self::Error>;
#[inline] #[inline]
fn upgrade_outbound(self, socket: TSocket, _: Self::UpgradeId) -> Self::Future { fn upgrade_outbound(self, socket: TSocket, _: Self::Info) -> Self::Future {
future::ok(Framed::new(socket, FloodsubCodec { length_prefix: Default::default() })) future::ok(Framed::new(socket, FloodsubCodec { length_prefix: Default::default() }))
} }
} }

View File

@ -18,7 +18,7 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use bytes::{Bytes, BytesMut}; use bytes::BytesMut;
use futures::{future::{self, FutureResult}, Async, AsyncSink, Future, Poll, Sink, Stream}; use futures::{future::{self, FutureResult}, Async, AsyncSink, Future, Poll, Sink, Stream};
use libp2p_core::{ use libp2p_core::{
Multiaddr, PublicKey, Multiaddr, PublicKey,
@ -134,12 +134,11 @@ pub struct IdentifyInfo {
} }
impl UpgradeInfo for IdentifyProtocolConfig { impl UpgradeInfo for IdentifyProtocolConfig {
type UpgradeId = (); type Info = &'static [u8];
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>; type InfoIter = iter::Once<Self::Info>;
#[inline] fn protocol_info(&self) -> Self::InfoIter {
fn protocol_names(&self) -> Self::NamesIter { iter::once(b"/ipfs/id/1.0.0")
iter::once((Bytes::from("/ipfs/id/1.0.0"), ()))
} }
} }
@ -151,7 +150,7 @@ where
type Error = IoError; type Error = IoError;
type Future = FutureResult<Self::Output, IoError>; type Future = FutureResult<Self::Output, IoError>;
fn upgrade_inbound(self, socket: C, _: ()) -> Self::Future { fn upgrade_inbound(self, socket: C, _: Self::Info) -> Self::Future {
trace!("Upgrading inbound connection"); trace!("Upgrading inbound connection");
let socket = Framed::new(socket, codec::UviBytes::default()); let socket = Framed::new(socket, codec::UviBytes::default());
let sender = IdentifySender { inner: socket }; let sender = IdentifySender { inner: socket };
@ -167,7 +166,7 @@ where
type Error = IoError; type Error = IoError;
type Future = IdentifyOutboundFuture<C>; type Future = IdentifyOutboundFuture<C>;
fn upgrade_outbound(self, socket: C, _: ()) -> Self::Future { fn upgrade_outbound(self, socket: C, _: Self::Info) -> Self::Future {
IdentifyOutboundFuture { IdentifyOutboundFuture {
inner: Framed::new(socket, codec::UviBytes::<BytesMut>::default()), inner: Framed::new(socket, codec::UviBytes::<BytesMut>::default()),
} }

View File

@ -26,7 +26,7 @@
//! The `Stream` component is used to poll the underlying transport, and the `Sink` component is //! The `Stream` component is used to poll the underlying transport, and the `Sink` component is
//! used to send messages. //! used to send messages.
use bytes::{Bytes, BytesMut}; use bytes::BytesMut;
use futures::{future, sink, stream, Sink, Stream}; use futures::{future, sink, stream, Sink, Stream};
use libp2p_core::{InboundUpgrade, Multiaddr, OutboundUpgrade, PeerId, UpgradeInfo}; use libp2p_core::{InboundUpgrade, Multiaddr, OutboundUpgrade, PeerId, UpgradeInfo};
use multihash::Multihash; use multihash::Multihash;
@ -136,12 +136,12 @@ impl Into<protobuf_structs::dht::Message_Peer> for KadPeer {
pub struct KademliaProtocolConfig; pub struct KademliaProtocolConfig;
impl UpgradeInfo for KademliaProtocolConfig { impl UpgradeInfo for KademliaProtocolConfig {
type NamesIter = iter::Once<(Bytes, ())>; type Info = &'static [u8];
type UpgradeId = (); type InfoIter = iter::Once<Self::Info>;
#[inline] #[inline]
fn protocol_names(&self) -> Self::NamesIter { fn protocol_info(&self) -> Self::InfoIter {
iter::once(("/ipfs/kad/1.0.0".into(), ())) iter::once(b"/ipfs/kad/1.0.0")
} }
} }
@ -154,7 +154,7 @@ where
type Error = IoError; type Error = IoError;
#[inline] #[inline]
fn upgrade_inbound(self, incoming: C, _: ()) -> Self::Future { fn upgrade_inbound(self, incoming: C, _: Self::Info) -> Self::Future {
future::ok( future::ok(
Framed::new(incoming, codec::UviBytes::default()) Framed::new(incoming, codec::UviBytes::default())
.from_err::<IoError>() .from_err::<IoError>()
@ -180,7 +180,7 @@ where
type Error = IoError; type Error = IoError;
#[inline] #[inline]
fn upgrade_outbound(self, incoming: C, _: ()) -> Self::Future { fn upgrade_outbound(self, incoming: C, _: Self::Info) -> Self::Future {
future::ok( future::ok(
Framed::new(incoming, codec::UviBytes::default()) Framed::new(incoming, codec::UviBytes::default())
.from_err::<IoError>() .from_err::<IoError>()

View File

@ -46,11 +46,11 @@ impl Observed {
} }
impl UpgradeInfo for Observed { impl UpgradeInfo for Observed {
type UpgradeId = (); type Info = &'static [u8];
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>; type InfoIter = iter::Once<Self::Info>;
fn protocol_names(&self) -> Self::NamesIter { fn protocol_info(&self) -> Self::InfoIter {
iter::once((Bytes::from("/paritytech/observed-address/0.1.0"), ())) iter::once(b"/paritytech/observed-address/0.1.0")
} }
} }
@ -62,7 +62,7 @@ where
type Error = io::Error; type Error = io::Error;
type Future = Box<dyn Future<Item=Self::Output, Error=Self::Error> + Send>; type Future = Box<dyn Future<Item=Self::Output, Error=Self::Error> + Send>;
fn upgrade_inbound(self, conn: C, _: ()) -> Self::Future { fn upgrade_inbound(self, conn: C, _: Self::Info) -> Self::Future {
let io = FramedWrite::new(conn, UviBytes::default()); let io = FramedWrite::new(conn, UviBytes::default());
Box::new(future::ok(Sender { io })) Box::new(future::ok(Sender { io }))
} }
@ -76,7 +76,7 @@ where
type Error = io::Error; type Error = io::Error;
type Future = Box<dyn Future<Item=Self::Output, Error=Self::Error> + Send>; type Future = Box<dyn Future<Item=Self::Output, Error=Self::Error> + Send>;
fn upgrade_outbound(self, conn: C, _: ()) -> Self::Future { fn upgrade_outbound(self, conn: C, _: Self::Info) -> Self::Future {
let io = FramedRead::new(conn, UviBytes::default()); let io = FramedRead::new(conn, UviBytes::default());
let future = io.into_future() let future = io.into_future()
.map_err(|(e, _): (io::Error, FramedRead<C, UviBytes>)| e) .map_err(|(e, _): (io::Error, FramedRead<C, UviBytes>)| e)
@ -126,14 +126,14 @@ mod tests {
.into_future() .into_future()
.map_err(|(e, _)| e.into()) .map_err(|(e, _)| e.into())
.and_then(move |(conn, _)| { .and_then(move |(conn, _)| {
Observed::new().upgrade_inbound(conn.unwrap(), ()) Observed::new().upgrade_inbound(conn.unwrap(), b"/paritytech/observed-address/0.1.0")
}) })
.and_then(move |sender| sender.send_address(observed_addr1)); .and_then(move |sender| sender.send_address(observed_addr1));
let client = TcpStream::connect(&server_addr) let client = TcpStream::connect(&server_addr)
.map_err(|e| e.into()) .map_err(|e| e.into())
.and_then(|conn| { .and_then(|conn| {
Observed::new().upgrade_outbound(conn, ()) Observed::new().upgrade_outbound(conn, b"/paritytech/observed-address/0.1.0")
}) })
.map(move |addr| { .map(move |addr| {
eprintln!("{} {}", addr, observed_addr2); eprintln!("{} {}", addr, observed_addr2);

View File

@ -44,11 +44,11 @@ impl<TUserData> Default for Ping<TUserData> {
} }
impl<TUserData> UpgradeInfo for Ping<TUserData> { impl<TUserData> UpgradeInfo for Ping<TUserData> {
type UpgradeId = (); type Info = &'static [u8];
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>; type InfoIter = iter::Once<Self::Info>;
fn protocol_names(&self) -> Self::NamesIter { fn protocol_info(&self) -> Self::InfoIter {
iter::once(("/ipfs/ping/1.0.0".into(), ())) iter::once(b"/ipfs/ping/1.0.0")
} }
} }
@ -61,7 +61,7 @@ where
type Future = FutureResult<Self::Output, Self::Error>; type Future = FutureResult<Self::Output, Self::Error>;
#[inline] #[inline]
fn upgrade_inbound(self, socket: TSocket, _: Self::UpgradeId) -> Self::Future { fn upgrade_inbound(self, socket: TSocket, _: Self::Info) -> Self::Future {
let listener = PingListener { let listener = PingListener {
inner: Framed::new(socket, Codec), inner: Framed::new(socket, Codec),
state: PingListenerState::Listening, state: PingListenerState::Listening,
@ -79,7 +79,7 @@ where
type Future = FutureResult<Self::Output, Self::Error>; type Future = FutureResult<Self::Output, Self::Error>;
#[inline] #[inline]
fn upgrade_outbound(self, socket: TSocket, _: Self::UpgradeId) -> Self::Future { fn upgrade_outbound(self, socket: TSocket, _: Self::Info) -> Self::Future {
let dialer = PingDialer { let dialer = PingDialer {
inner: Framed::new(socket, Codec), inner: Framed::new(socket, Codec),
need_writer_flush: false, need_writer_flush: false,
@ -341,14 +341,14 @@ mod tests {
.into_future() .into_future()
.map_err(|(e, _)| e.into()) .map_err(|(e, _)| e.into())
.and_then(|(c, _)| { .and_then(|(c, _)| {
Ping::<()>::default().upgrade_inbound(c.unwrap(), ()) Ping::<()>::default().upgrade_inbound(c.unwrap(), b"/ipfs/ping/1.0.0")
}) })
.flatten(); .flatten();
let client = TcpStream::connect(&listener_addr) let client = TcpStream::connect(&listener_addr)
.map_err(|e| e.into()) .map_err(|e| e.into())
.and_then(|c| { .and_then(|c| {
Ping::<()>::default().upgrade_outbound(c, ()) Ping::<()>::default().upgrade_outbound(c, b"/ipfs/ping/1.0.0")
}) })
.and_then(|mut pinger| { .and_then(|mut pinger| {
pinger.ping(()); pinger.ping(());
@ -371,14 +371,14 @@ mod tests {
.into_future() .into_future()
.map_err(|(e, _)| e.into()) .map_err(|(e, _)| e.into())
.and_then(|(c, _)| { .and_then(|(c, _)| {
Ping::<u32>::default().upgrade_inbound(c.unwrap(), ()) Ping::<u32>::default().upgrade_inbound(c.unwrap(), b"/ipfs/ping/1.0.0")
}) })
.flatten(); .flatten();
let client = TcpStream::connect(&listener_addr) let client = TcpStream::connect(&listener_addr)
.map_err(|e| e.into()) .map_err(|e| e.into())
.and_then(|c| { .and_then(|c| {
Ping::<u32>::default().upgrade_outbound(c, ()) Ping::<u32>::default().upgrade_outbound(c, b"/ipfs/ping/1.0.0")
}) })
.and_then(|mut pinger| { .and_then(|mut pinger| {
for n in 0..20 { for n in 0..20 {

View File

@ -9,7 +9,6 @@ keywords = ["peer-to-peer", "libp2p", "networking"]
categories = ["network-programming", "asynchronous"] categories = ["network-programming", "asynchronous"]
[dependencies] [dependencies]
bytes = "0.4"
futures = "0.1" futures = "0.1"
libp2p-core = { version = "0.1.0", path = "../../core" } libp2p-core = { version = "0.1.0", path = "../../core" }
void = "1" void = "1"

View File

@ -18,12 +18,10 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
extern crate bytes;
extern crate futures; extern crate futures;
extern crate libp2p_core; extern crate libp2p_core;
extern crate void; extern crate void;
use bytes::Bytes;
use futures::future::{self, FutureResult}; use futures::future::{self, FutureResult};
use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}; use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo};
use std::iter; use std::iter;
@ -33,11 +31,11 @@ use void::Void;
pub struct PlainTextConfig; pub struct PlainTextConfig;
impl UpgradeInfo for PlainTextConfig { impl UpgradeInfo for PlainTextConfig {
type UpgradeId = (); type Info = &'static [u8];
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>; type InfoIter = iter::Once<Self::Info>;
fn protocol_names(&self) -> Self::NamesIter { fn protocol_info(&self) -> Self::InfoIter {
iter::once((Bytes::from("/plaintext/1.0.0"), ())) iter::once(b"/plaintext/1.0.0")
} }
} }
@ -46,7 +44,7 @@ impl<C> InboundUpgrade<C> for PlainTextConfig {
type Error = Void; type Error = Void;
type Future = FutureResult<C, Self::Error>; type Future = FutureResult<C, Self::Error>;
fn upgrade_inbound(self, i: C, _: Self::UpgradeId) -> Self::Future { fn upgrade_inbound(self, i: C, _: Self::Info) -> Self::Future {
future::ok(i) future::ok(i)
} }
} }
@ -56,7 +54,7 @@ impl<C> OutboundUpgrade<C> for PlainTextConfig {
type Error = Void; type Error = Void;
type Future = FutureResult<C, Self::Error>; type Future = FutureResult<C, Self::Error>;
fn upgrade_outbound(self, i: C, _: Self::UpgradeId) -> Self::Future { fn upgrade_outbound(self, i: C, _: Self::Info) -> Self::Future {
future::ok(i) future::ok(i)
} }
} }

View File

@ -116,7 +116,7 @@ pub use self::error::SecioError;
#[cfg(feature = "secp256k1")] #[cfg(feature = "secp256k1")]
use asn1_der::{traits::FromDerEncoded, traits::FromDerObject, DerObject}; use asn1_der::{traits::FromDerEncoded, traits::FromDerObject, DerObject};
use bytes::{Bytes, BytesMut}; use bytes::BytesMut;
use ed25519_dalek::Keypair as Ed25519KeyPair; use ed25519_dalek::Keypair as Ed25519KeyPair;
use futures::stream::MapErr as StreamMapErr; use futures::stream::MapErr as StreamMapErr;
use futures::{Future, Poll, Sink, StartSend, Stream}; use futures::{Future, Poll, Sink, StartSend, Stream};
@ -193,7 +193,7 @@ impl SecioConfig {
self self
} }
fn handshake<T>(self, socket: T, _: ()) -> impl Future<Item=SecioOutput<T>, Error=SecioError> fn handshake<T>(self, socket: T) -> impl Future<Item=SecioOutput<T>, Error=SecioError>
where where
T: AsyncRead + AsyncWrite + Send + 'static T: AsyncRead + AsyncWrite + Send + 'static
{ {
@ -371,11 +371,11 @@ where
} }
impl UpgradeInfo for SecioConfig { impl UpgradeInfo for SecioConfig {
type UpgradeId = (); type Info = &'static [u8];
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>; type InfoIter = iter::Once<Self::Info>;
fn protocol_names(&self) -> Self::NamesIter { fn protocol_info(&self) -> Self::InfoIter {
iter::once(("/secio/1.0.0".into(), ())) iter::once(b"/secio/1.0.0")
} }
} }
@ -387,8 +387,8 @@ where
type Error = SecioError; type Error = SecioError;
type Future = Box<dyn Future<Item = Self::Output, Error = Self::Error> + Send>; type Future = Box<dyn Future<Item = Self::Output, Error = Self::Error> + Send>;
fn upgrade_inbound(self, socket: T, id: Self::UpgradeId) -> Self::Future { fn upgrade_inbound(self, socket: T, _: Self::Info) -> Self::Future {
Box::new(self.handshake(socket, id)) Box::new(self.handshake(socket))
} }
} }
@ -400,8 +400,8 @@ where
type Error = SecioError; type Error = SecioError;
type Future = Box<dyn Future<Item = Self::Output, Error = Self::Error> + Send>; type Future = Box<dyn Future<Item = Self::Output, Error = Self::Error> + Send>;
fn upgrade_outbound(self, socket: T, id: Self::UpgradeId) -> Self::Future { fn upgrade_outbound(self, socket: T, _: Self::Info) -> Self::Future {
Box::new(self.handshake(socket, id)) Box::new(self.handshake(socket))
} }
} }

View File

@ -27,7 +27,7 @@ use tokio_io::{AsyncRead, AsyncWrite};
/// Implementation of `ConnectionUpgrade`. Convenient to use with small protocols. /// Implementation of `ConnectionUpgrade`. Convenient to use with small protocols.
#[derive(Debug)] #[derive(Debug)]
pub struct SimpleProtocol<F> { pub struct SimpleProtocol<F> {
name: Bytes, info: Bytes,
// Note: we put the closure `F` in an `Arc` because Rust closures aren't automatically clonable // Note: we put the closure `F` in an `Arc` because Rust closures aren't automatically clonable
// yet. // yet.
upgrade: Arc<F>, upgrade: Arc<F>,
@ -36,12 +36,12 @@ pub struct SimpleProtocol<F> {
impl<F> SimpleProtocol<F> { impl<F> SimpleProtocol<F> {
/// Builds a `SimpleProtocol`. /// Builds a `SimpleProtocol`.
#[inline] #[inline]
pub fn new<N>(name: N, upgrade: F) -> SimpleProtocol<F> pub fn new<N>(info: N, upgrade: F) -> SimpleProtocol<F>
where where
N: Into<Bytes>, N: Into<Bytes>,
{ {
SimpleProtocol { SimpleProtocol {
name: name.into(), info: info.into(),
upgrade: Arc::new(upgrade), upgrade: Arc::new(upgrade),
} }
} }
@ -51,19 +51,19 @@ impl<F> Clone for SimpleProtocol<F> {
#[inline] #[inline]
fn clone(&self) -> Self { fn clone(&self) -> Self {
SimpleProtocol { SimpleProtocol {
name: self.name.clone(), info: self.info.clone(),
upgrade: self.upgrade.clone(), upgrade: self.upgrade.clone(),
} }
} }
} }
impl<F> UpgradeInfo for SimpleProtocol<F> { impl<F> UpgradeInfo for SimpleProtocol<F> {
type UpgradeId = (); type Info = Bytes;
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>; type InfoIter = iter::Once<Self::Info>;
#[inline] #[inline]
fn protocol_names(&self) -> Self::NamesIter { fn protocol_info(&self) -> Self::InfoIter {
iter::once((self.name.clone(), ())) iter::once(self.info.clone())
} }
} }
@ -78,7 +78,7 @@ where
type Future = FromErr<O::Future, IoError>; type Future = FromErr<O::Future, IoError>;
#[inline] #[inline]
fn upgrade_inbound(self, socket: C, _: Self::UpgradeId) -> Self::Future { fn upgrade_inbound(self, socket: C, _: Self::Info) -> Self::Future {
let upgrade = &self.upgrade; let upgrade = &self.upgrade;
upgrade(socket).into_future().from_err() upgrade(socket).into_future().from_err()
} }
@ -95,7 +95,7 @@ where
type Future = FromErr<O::Future, IoError>; type Future = FromErr<O::Future, IoError>;
#[inline] #[inline]
fn upgrade_outbound(self, socket: C, _: Self::UpgradeId) -> Self::Future { fn upgrade_outbound(self, socket: C, _: Self::Info) -> Self::Future {
let upgrade = &self.upgrade; let upgrade = &self.upgrade;
upgrade(socket).into_future().from_err() upgrade(socket).into_future().from_err()
} }