mirror of
https://github.com/fluencelabs/rust-libp2p
synced 2025-04-25 11:02:12 +00:00
Simplify handling of upgrade information. (#761)
This commit is contained in:
parent
2dce4294a0
commit
a152e18821
@ -18,7 +18,7 @@
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
// DEALINGS IN THE SOFTWARE.
|
||||
|
||||
use crate::{muxing::{Shutdown, StreamMuxer}, Multiaddr};
|
||||
use crate::{muxing::{Shutdown, StreamMuxer}, Multiaddr, ProtocolName};
|
||||
use futures::prelude::*;
|
||||
use std::{fmt, io::{Error as IoError, Read, Write}};
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -111,7 +111,7 @@ pub use self::protocols_handler::{ProtocolsHandler, ProtocolsHandlerEvent};
|
||||
pub use self::public_key::PublicKey;
|
||||
pub use self::swarm::Swarm;
|
||||
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)]
|
||||
pub enum Endpoint {
|
||||
|
@ -19,7 +19,7 @@
|
||||
// DEALINGS IN THE SOFTWARE.
|
||||
|
||||
use crate::{
|
||||
Transport, Multiaddr, PublicKey, PeerId, InboundUpgrade, OutboundUpgrade, UpgradeInfo,
|
||||
Transport, Multiaddr, PublicKey, PeerId, InboundUpgrade, OutboundUpgrade, UpgradeInfo, ProtocolName,
|
||||
muxing::StreamMuxer,
|
||||
nodes::{
|
||||
handled_node::NodeHandler,
|
||||
@ -104,13 +104,15 @@ where TBehaviour: NetworkBehaviour<TTopology>,
|
||||
<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutEvent: Send + 'static,
|
||||
<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 as UpgradeInfo>::NamesIter: Send + 'static,
|
||||
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as UpgradeInfo>::UpgradeId: Send + 'static,
|
||||
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as UpgradeInfo>::Info: 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>>>::Future: 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>::UpgradeId: Send + 'static,
|
||||
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as UpgradeInfo>::Info: 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>>>::Error: fmt::Debug + Send + 'static,
|
||||
<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
|
||||
.new_handler()
|
||||
.listen_protocol()
|
||||
.protocol_names()
|
||||
.map(|(name, _)| name.to_vec())
|
||||
.protocol_info()
|
||||
.into_iter()
|
||||
.map(|info| info.protocol_name().to_vec())
|
||||
.collect();
|
||||
|
||||
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 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 UpgradeInfo>::NamesIter: Send + 'static,
|
||||
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as UpgradeInfo>::UpgradeId: Send + 'static,
|
||||
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::InboundProtocol as UpgradeInfo>::Info: 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 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 UpgradeInfo>::NamesIter: Send + 'static,
|
||||
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as UpgradeInfo>::UpgradeId: Send + 'static,
|
||||
<<TBehaviour::ProtocolsHandler as ProtocolsHandler>::OutboundProtocol as UpgradeInfo>::Info: 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
|
||||
TTopology: Topology,
|
||||
{
|
||||
|
@ -18,9 +18,8 @@
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
// DEALINGS IN THE SOFTWARE.
|
||||
|
||||
use bytes::Bytes;
|
||||
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 multistream_select::{self, DialerSelectFuture, ListenerSelectFuture};
|
||||
use std::mem;
|
||||
@ -46,7 +45,8 @@ where
|
||||
C: AsyncRead + AsyncWrite,
|
||||
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 {
|
||||
inner: InboundUpgradeApplyState::Init { future }
|
||||
}
|
||||
@ -58,7 +58,7 @@ where
|
||||
C: AsyncRead + AsyncWrite,
|
||||
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);
|
||||
OutboundUpgradeApply {
|
||||
inner: OutboundUpgradeApplyState::Init { future, upgrade: up }
|
||||
@ -80,7 +80,7 @@ where
|
||||
U: InboundUpgrade<C>
|
||||
{
|
||||
Init {
|
||||
future: ListenerSelectFuture<C, UpgradeIntoProtocolsIterWrap<U>, U::UpgradeId>,
|
||||
future: ListenerSelectFuture<C, UpgradeInfoIterWrap<U>, NameWrap<U::Info>>,
|
||||
},
|
||||
Upgrade {
|
||||
future: U::Future
|
||||
@ -100,7 +100,7 @@ where
|
||||
loop {
|
||||
match mem::replace(&mut self.inner, InboundUpgradeApplyState::Undefined) {
|
||||
InboundUpgradeApplyState::Init { mut future } => {
|
||||
let (upgrade_id, connection, upgrade) = match future.poll()? {
|
||||
let (info, connection, upgrade) = match future.poll()? {
|
||||
Async::Ready(x) => x,
|
||||
Async::NotReady => {
|
||||
self.inner = InboundUpgradeApplyState::Init { future };
|
||||
@ -108,7 +108,7 @@ where
|
||||
}
|
||||
};
|
||||
self.inner = InboundUpgradeApplyState::Upgrade {
|
||||
future: upgrade.0.upgrade_inbound(connection, upgrade_id)
|
||||
future: upgrade.0.upgrade_inbound(connection, info.0)
|
||||
};
|
||||
}
|
||||
InboundUpgradeApplyState::Upgrade { mut future } => {
|
||||
@ -149,7 +149,7 @@ where
|
||||
U: OutboundUpgrade<C>
|
||||
{
|
||||
Init {
|
||||
future: DialerSelectFuture<C, ProtocolNames<U::NamesIter>, U::UpgradeId>,
|
||||
future: DialerSelectFuture<C, NameWrapIter<<U::InfoIter as IntoIterator>::IntoIter>>,
|
||||
upgrade: U
|
||||
},
|
||||
Upgrade {
|
||||
@ -170,7 +170,7 @@ where
|
||||
loop {
|
||||
match mem::replace(&mut self.inner, OutboundUpgradeApplyState::Undefined) {
|
||||
OutboundUpgradeApplyState::Init { mut future, upgrade } => {
|
||||
let (upgrade_id, connection) = match future.poll()? {
|
||||
let (info, connection) = match future.poll()? {
|
||||
Async::Ready(x) => x,
|
||||
Async::NotReady => {
|
||||
self.inner = OutboundUpgradeApplyState::Init { future, upgrade };
|
||||
@ -178,7 +178,7 @@ where
|
||||
}
|
||||
};
|
||||
self.inner = OutboundUpgradeApplyState::Upgrade {
|
||||
future: upgrade.upgrade_outbound(connection, upgrade_id)
|
||||
future: upgrade.upgrade_outbound(connection, info.0)
|
||||
};
|
||||
}
|
||||
OutboundUpgradeApplyState::Upgrade { mut future } => {
|
||||
@ -205,37 +205,29 @@ where
|
||||
}
|
||||
|
||||
/// 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>
|
||||
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>
|
||||
impl<'a, U> IntoIterator for &'a UpgradeInfoIterWrap<U>
|
||||
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> {
|
||||
let f = <Bytes as PartialEq>::eq as fn(&Bytes, &Bytes) -> bool;
|
||||
self.0.next().map(|(b, id)| (b, f, id))
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.0.size_hint()
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.0.protocol_info().into_iter().map(NameWrap)
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -18,11 +18,10 @@
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
// DEALINGS IN THE SOFTWARE.
|
||||
|
||||
use bytes::Bytes;
|
||||
use crate::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo};
|
||||
use futures::future;
|
||||
use std::iter;
|
||||
use void::{unreachable, Void};
|
||||
use void::Void;
|
||||
|
||||
/// Dummy implementation of `UpgradeInfo`/`InboundUpgrade`/`OutboundUpgrade` that doesn't support
|
||||
/// any protocol.
|
||||
@ -30,10 +29,10 @@ use void::{unreachable, Void};
|
||||
pub struct DeniedUpgrade;
|
||||
|
||||
impl UpgradeInfo for DeniedUpgrade {
|
||||
type UpgradeId = Void;
|
||||
type NamesIter = iter::Empty<(Bytes, Self::UpgradeId)>;
|
||||
type Info = &'static [u8];
|
||||
type InfoIter = iter::Empty<Self::Info>;
|
||||
|
||||
fn protocol_names(&self) -> Self::NamesIter {
|
||||
fn protocol_info(&self) -> Self::InfoIter {
|
||||
iter::empty()
|
||||
}
|
||||
}
|
||||
@ -43,8 +42,8 @@ impl<C> InboundUpgrade<C> for DeniedUpgrade {
|
||||
type Error = Void;
|
||||
type Future = future::Empty<Self::Output, Self::Error>;
|
||||
|
||||
fn upgrade_inbound(self, _: C, id: Self::UpgradeId) -> Self::Future {
|
||||
unreachable(id)
|
||||
fn upgrade_inbound(self, _: C, _: Self::Info) -> Self::Future {
|
||||
future::empty()
|
||||
}
|
||||
}
|
||||
|
||||
@ -53,8 +52,8 @@ impl<C> OutboundUpgrade<C> for DeniedUpgrade {
|
||||
type Error = Void;
|
||||
type Future = future::Empty<Self::Output, Self::Error>;
|
||||
|
||||
fn upgrade_outbound(self, _: C, id: Self::UpgradeId) -> Self::Future {
|
||||
unreachable(id)
|
||||
fn upgrade_outbound(self, _: C, _: Self::Info) -> Self::Future {
|
||||
future::empty()
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -18,10 +18,8 @@
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
// DEALINGS IN THE SOFTWARE.
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures::future::Either;
|
||||
use crate::{
|
||||
either::{EitherOutput, EitherError, EitherFuture2},
|
||||
either::{EitherOutput, EitherError, EitherFuture2, EitherName},
|
||||
upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}
|
||||
};
|
||||
|
||||
@ -34,13 +32,16 @@ where
|
||||
A: UpgradeInfo,
|
||||
B: UpgradeInfo
|
||||
{
|
||||
type UpgradeId = Either<A::UpgradeId, B::UpgradeId>;
|
||||
type NamesIter = EitherIter<A::NamesIter, B::NamesIter>;
|
||||
type Info = EitherName<A::Info, B::Info>;
|
||||
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 {
|
||||
EitherUpgrade::A(a) => EitherIter::A(a.protocol_names()),
|
||||
EitherUpgrade::B(b) => EitherIter::B(b.protocol_names())
|
||||
EitherUpgrade::A(a) => EitherIter::A(a.protocol_info().into_iter()),
|
||||
EitherUpgrade::B(b) => EitherIter::B(b.protocol_info().into_iter())
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -54,10 +55,10 @@ where
|
||||
type Error = EitherError<EA, EB>;
|
||||
type Future = EitherFuture2<A::Future, B::Future>;
|
||||
|
||||
fn upgrade_inbound(self, sock: C, id: Self::UpgradeId) -> Self::Future {
|
||||
match (self, id) {
|
||||
(EitherUpgrade::A(a), Either::A(id)) => EitherFuture2::A(a.upgrade_inbound(sock, id)),
|
||||
(EitherUpgrade::B(b), Either::B(id)) => EitherFuture2::B(b.upgrade_inbound(sock, id)),
|
||||
fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
|
||||
match (self, info) {
|
||||
(EitherUpgrade::A(a), EitherName::A(info)) => EitherFuture2::A(a.upgrade_inbound(sock, info)),
|
||||
(EitherUpgrade::B(b), EitherName::B(info)) => EitherFuture2::B(b.upgrade_inbound(sock, info)),
|
||||
_ => panic!("Invalid invocation of EitherUpgrade::upgrade_inbound")
|
||||
}
|
||||
}
|
||||
@ -72,10 +73,10 @@ where
|
||||
type Error = EitherError<EA, EB>;
|
||||
type Future = EitherFuture2<A::Future, B::Future>;
|
||||
|
||||
fn upgrade_outbound(self, sock: C, id: Self::UpgradeId) -> Self::Future {
|
||||
match (self, id) {
|
||||
(EitherUpgrade::A(a), Either::A(id)) => EitherFuture2::A(a.upgrade_outbound(sock, id)),
|
||||
(EitherUpgrade::B(b), Either::B(id)) => EitherFuture2::B(b.upgrade_outbound(sock, id)),
|
||||
fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
|
||||
match (self, info) {
|
||||
(EitherUpgrade::A(a), EitherName::A(info)) => EitherFuture2::A(a.upgrade_outbound(sock, info)),
|
||||
(EitherUpgrade::B(b), EitherName::B(info)) => EitherFuture2::B(b.upgrade_outbound(sock, info)),
|
||||
_ => panic!("Invalid invocation of EitherUpgrade::upgrade_outbound")
|
||||
}
|
||||
}
|
||||
@ -85,17 +86,17 @@ where
|
||||
#[derive(Debug, Clone)]
|
||||
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
|
||||
A: Iterator<Item = (Bytes, AId)>,
|
||||
B: Iterator<Item = (Bytes, BId)>,
|
||||
A: Iterator,
|
||||
B: Iterator
|
||||
{
|
||||
type Item = (Bytes, Either<AId, BId>);
|
||||
type Item = EitherName<A::Item, B::Item>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
match self {
|
||||
EitherIter::A(a) => a.next().map(|(name, id)| (name, Either::A(id))),
|
||||
EitherIter::B(b) => b.next().map(|(name, id)| (name, Either::B(id)))
|
||||
EitherIter::A(a) => a.next().map(EitherName::A),
|
||||
EitherIter::B(b) => b.next().map(EitherName::B)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -35,11 +35,11 @@ impl<U, F> UpgradeInfo for MapInboundUpgrade<U, F>
|
||||
where
|
||||
U: UpgradeInfo
|
||||
{
|
||||
type UpgradeId = U::UpgradeId;
|
||||
type NamesIter = U::NamesIter;
|
||||
type Info = U::Info;
|
||||
type InfoIter = U::InfoIter;
|
||||
|
||||
fn protocol_names(&self) -> Self::NamesIter {
|
||||
self.upgrade.protocol_names()
|
||||
fn protocol_info(&self) -> Self::InfoIter {
|
||||
self.upgrade.protocol_info()
|
||||
}
|
||||
}
|
||||
|
||||
@ -52,9 +52,9 @@ where
|
||||
type Error = U::Error;
|
||||
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 {
|
||||
inner: self.upgrade.upgrade_inbound(sock, id),
|
||||
inner: self.upgrade.upgrade_inbound(sock, info),
|
||||
map: Some(self.fun)
|
||||
}
|
||||
}
|
||||
@ -68,8 +68,8 @@ where
|
||||
type Error = U::Error;
|
||||
type Future = U::Future;
|
||||
|
||||
fn upgrade_outbound(self, sock: C, id: Self::UpgradeId) -> Self::Future {
|
||||
self.upgrade.upgrade_outbound(sock, id)
|
||||
fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
|
||||
self.upgrade.upgrade_outbound(sock, info)
|
||||
}
|
||||
}
|
||||
|
||||
@ -87,11 +87,11 @@ impl<U, F> UpgradeInfo for MapOutboundUpgrade<U, F>
|
||||
where
|
||||
U: UpgradeInfo
|
||||
{
|
||||
type UpgradeId = U::UpgradeId;
|
||||
type NamesIter = U::NamesIter;
|
||||
type Info = U::Info;
|
||||
type InfoIter = U::InfoIter;
|
||||
|
||||
fn protocol_names(&self) -> Self::NamesIter {
|
||||
self.upgrade.protocol_names()
|
||||
fn protocol_info(&self) -> Self::InfoIter {
|
||||
self.upgrade.protocol_info()
|
||||
}
|
||||
}
|
||||
|
||||
@ -103,8 +103,8 @@ where
|
||||
type Error = U::Error;
|
||||
type Future = U::Future;
|
||||
|
||||
fn upgrade_inbound(self, sock: C, id: Self::UpgradeId) -> Self::Future {
|
||||
self.upgrade.upgrade_inbound(sock, id)
|
||||
fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
|
||||
self.upgrade.upgrade_inbound(sock, info)
|
||||
}
|
||||
}
|
||||
|
||||
@ -117,9 +117,9 @@ where
|
||||
type Error = U::Error;
|
||||
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 {
|
||||
inner: self.upgrade.upgrade_outbound(sock, id),
|
||||
inner: self.upgrade.upgrade_outbound(sock, info),
|
||||
map: Some(self.fun)
|
||||
}
|
||||
}
|
||||
@ -139,11 +139,11 @@ impl<U, F> UpgradeInfo for MapInboundUpgradeErr<U, F>
|
||||
where
|
||||
U: UpgradeInfo
|
||||
{
|
||||
type UpgradeId = U::UpgradeId;
|
||||
type NamesIter = U::NamesIter;
|
||||
type Info = U::Info;
|
||||
type InfoIter = U::InfoIter;
|
||||
|
||||
fn protocol_names(&self) -> Self::NamesIter {
|
||||
self.upgrade.protocol_names()
|
||||
fn protocol_info(&self) -> Self::InfoIter {
|
||||
self.upgrade.protocol_info()
|
||||
}
|
||||
}
|
||||
|
||||
@ -156,9 +156,9 @@ where
|
||||
type Error = T;
|
||||
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 {
|
||||
fut: self.upgrade.upgrade_inbound(sock, id),
|
||||
fut: self.upgrade.upgrade_inbound(sock, info),
|
||||
fun: Some(self.fun)
|
||||
}
|
||||
}
|
||||
@ -172,8 +172,8 @@ where
|
||||
type Error = U::Error;
|
||||
type Future = U::Future;
|
||||
|
||||
fn upgrade_outbound(self, sock: C, id: Self::UpgradeId) -> Self::Future {
|
||||
self.upgrade.upgrade_outbound(sock, id)
|
||||
fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
|
||||
self.upgrade.upgrade_outbound(sock, info)
|
||||
}
|
||||
}
|
||||
|
||||
@ -191,11 +191,11 @@ impl<U, F> UpgradeInfo for MapOutboundUpgradeErr<U, F>
|
||||
where
|
||||
U: UpgradeInfo
|
||||
{
|
||||
type UpgradeId = U::UpgradeId;
|
||||
type NamesIter = U::NamesIter;
|
||||
type Info = U::Info;
|
||||
type InfoIter = U::InfoIter;
|
||||
|
||||
fn protocol_names(&self) -> Self::NamesIter {
|
||||
self.upgrade.protocol_names()
|
||||
fn protocol_info(&self) -> Self::InfoIter {
|
||||
self.upgrade.protocol_info()
|
||||
}
|
||||
}
|
||||
|
||||
@ -208,9 +208,9 @@ where
|
||||
type Error = T;
|
||||
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 {
|
||||
fut: self.upgrade.upgrade_outbound(sock, id),
|
||||
fut: self.upgrade.upgrade_outbound(sock, info),
|
||||
fun: Some(self.fun)
|
||||
}
|
||||
}
|
||||
@ -224,8 +224,8 @@ where
|
||||
type Error = U::Error;
|
||||
type Future = U::Future;
|
||||
|
||||
fn upgrade_inbound(self, sock: C, id: Self::UpgradeId) -> Self::Future {
|
||||
self.upgrade.upgrade_inbound(sock, id)
|
||||
fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
|
||||
self.upgrade.upgrade_inbound(sock, info)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -36,7 +36,7 @@
|
||||
//!
|
||||
//! 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
|
||||
//! is used in order to agree on which protocol to use amongst the ones supported.
|
||||
//!
|
||||
@ -64,7 +64,6 @@ mod error;
|
||||
mod map;
|
||||
mod select;
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures::future::Future;
|
||||
|
||||
pub use self::{
|
||||
@ -76,18 +75,28 @@ pub use self::{
|
||||
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,
|
||||
/// or both.
|
||||
pub trait UpgradeInfo {
|
||||
/// Opaque type representing a negotiable protocol.
|
||||
type UpgradeId;
|
||||
/// Iterator returned by `protocol_names`.
|
||||
type NamesIter: Iterator<Item = (Bytes, Self::UpgradeId)>;
|
||||
type Info: ProtocolName;
|
||||
/// Iterator returned by `protocol_info`.
|
||||
type InfoIter: IntoIterator<Item = Self::Info>;
|
||||
|
||||
/// Returns the list of protocols that are supported. Used during the negotiation process.
|
||||
///
|
||||
/// Each item returned by the iterator is a pair of a protocol name and an opaque identifier.
|
||||
fn protocol_names(&self) -> Self::NamesIter;
|
||||
fn protocol_info(&self) -> Self::InfoIter;
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// method is called to start the handshake.
|
||||
///
|
||||
/// The `id` is the identifier of the protocol, as produced by `protocol_names()`.
|
||||
fn upgrade_inbound(self, socket: C, id: Self::UpgradeId) -> Self::Future;
|
||||
/// The `info` is the identifier of the protocol, as produced by `protocol_info`.
|
||||
fn upgrade_inbound(self, socket: C, info: Self::Info) -> Self::Future;
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// method is called to start the handshake.
|
||||
///
|
||||
/// The `id` is the identifier of the protocol, as produced by `protocol_names()`.
|
||||
fn upgrade_outbound(self, socket: C, id: Self::UpgradeId) -> Self::Future;
|
||||
/// The `info` is the identifier of the protocol, as produced by `protocol_info`.
|
||||
fn upgrade_outbound(self, socket: C, info: Self::Info) -> Self::Future;
|
||||
}
|
||||
|
||||
/// Extention trait for `OutboundUpgrade`. Automatically implemented on all types that implement
|
||||
|
@ -18,10 +18,8 @@
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
// DEALINGS IN THE SOFTWARE.
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures::future::Either;
|
||||
use crate::{
|
||||
either::{EitherOutput, EitherError, EitherFuture2},
|
||||
either::{EitherOutput, EitherError, EitherFuture2, EitherName},
|
||||
upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}
|
||||
};
|
||||
|
||||
@ -46,11 +44,14 @@ where
|
||||
A: UpgradeInfo,
|
||||
B: UpgradeInfo
|
||||
{
|
||||
type UpgradeId = Either<A::UpgradeId, B::UpgradeId>;
|
||||
type NamesIter = NamesIterChain<A::NamesIter, B::NamesIter>;
|
||||
type Info = EitherName<A::Info, B::Info>;
|
||||
type InfoIter = InfoIterChain<
|
||||
<A::InfoIter as IntoIterator>::IntoIter,
|
||||
<B::InfoIter as IntoIterator>::IntoIter
|
||||
>;
|
||||
|
||||
fn protocol_names(&self) -> Self::NamesIter {
|
||||
NamesIterChain(self.0.protocol_names(), self.1.protocol_names())
|
||||
fn protocol_info(&self) -> Self::InfoIter {
|
||||
InfoIterChain(self.0.protocol_info().into_iter(), self.1.protocol_info().into_iter())
|
||||
}
|
||||
}
|
||||
|
||||
@ -63,10 +64,10 @@ where
|
||||
type Error = EitherError<EA, EB>;
|
||||
type Future = EitherFuture2<A::Future, B::Future>;
|
||||
|
||||
fn upgrade_inbound(self, sock: C, id: Self::UpgradeId) -> Self::Future {
|
||||
match id {
|
||||
Either::A(id) => EitherFuture2::A(self.0.upgrade_inbound(sock, id)),
|
||||
Either::B(id) => EitherFuture2::B(self.1.upgrade_inbound(sock, id))
|
||||
fn upgrade_inbound(self, sock: C, info: Self::Info) -> Self::Future {
|
||||
match info {
|
||||
EitherName::A(info) => EitherFuture2::A(self.0.upgrade_inbound(sock, info)),
|
||||
EitherName::B(info) => EitherFuture2::B(self.1.upgrade_inbound(sock, info))
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -80,31 +81,31 @@ where
|
||||
type Error = EitherError<EA, EB>;
|
||||
type Future = EitherFuture2<A::Future, B::Future>;
|
||||
|
||||
fn upgrade_outbound(self, sock: C, id: Self::UpgradeId) -> Self::Future {
|
||||
match id {
|
||||
Either::A(id) => EitherFuture2::A(self.0.upgrade_outbound(sock, id)),
|
||||
Either::B(id) => EitherFuture2::B(self.1.upgrade_outbound(sock, id))
|
||||
fn upgrade_outbound(self, sock: C, info: Self::Info) -> Self::Future {
|
||||
match info {
|
||||
EitherName::A(info) => EitherFuture2::A(self.0.upgrade_outbound(sock, info)),
|
||||
EitherName::B(info) => EitherFuture2::B(self.1.upgrade_outbound(sock, info))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterator that combines the protocol names of twp upgrades.
|
||||
#[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
|
||||
A: Iterator<Item = (Bytes, AId)>,
|
||||
B: Iterator<Item = (Bytes, BId)>,
|
||||
A: Iterator,
|
||||
B: Iterator
|
||||
{
|
||||
type Item = (Bytes, Either<AId, BId>);
|
||||
type Item = EitherName<A::Item, B::Item>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if let Some((name, id)) = self.0.next() {
|
||||
return Some((name, Either::A(id)))
|
||||
if let Some(info) = self.0.next() {
|
||||
return Some(EitherName::A(info))
|
||||
}
|
||||
if let Some((name, id)) = self.1.next() {
|
||||
return Some((name, Either::B(id)))
|
||||
if let Some(info) = self.1.next() {
|
||||
return Some(EitherName::B(info))
|
||||
}
|
||||
None
|
||||
}
|
||||
|
@ -31,8 +31,7 @@ use crate::ProtocolChoiceError;
|
||||
|
||||
/// Future, returned by `dialer_select_proto`, which selects a protocol and dialer
|
||||
/// either sequentially of by considering all protocols in parallel.
|
||||
pub type DialerSelectFuture<R, I, P> =
|
||||
Either<DialerSelectSeq<R, IgnoreMatchFn<I>, P>, DialerSelectPar<R, I, P>>;
|
||||
pub type DialerSelectFuture<R, I> = Either<DialerSelectSeq<R, I>, DialerSelectPar<R, I>>;
|
||||
|
||||
/// 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
|
||||
/// chosen protocol.
|
||||
#[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
|
||||
R: AsyncRead + AsyncWrite,
|
||||
I: Iterator<Item=(Bytes, M, P)>,
|
||||
M: FnMut(&Bytes, &Bytes) -> bool,
|
||||
I: IntoIterator,
|
||||
I::Item: AsRef<[u8]>
|
||||
{
|
||||
let iter = protocols.into_iter();
|
||||
// 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) {
|
||||
Either::A(dialer_select_proto_serial(inner, IgnoreMatchFn(protocols)))
|
||||
if iter.size_hint().1.map(|n| n <= 3).unwrap_or(false) {
|
||||
Either::A(dialer_select_proto_serial(inner, iter))
|
||||
} 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.
|
||||
///
|
||||
/// Same as `dialer_select_proto`. Tries protocols one by one. The iterator doesn't need to produce
|
||||
/// 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
|
||||
R: AsyncRead + AsyncWrite,
|
||||
I: Iterator<Item = (Bytes, P)>,
|
||||
I: Iterator,
|
||||
I::Item: AsRef<[u8]>
|
||||
{
|
||||
DialerSelectSeq {
|
||||
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
|
||||
/// and dialer sequentially.
|
||||
pub struct DialerSelectSeq<R: AsyncRead + AsyncWrite, I, P> {
|
||||
inner: DialerSelectSeqState<R, I, P>
|
||||
pub struct DialerSelectSeq<R: AsyncRead + AsyncWrite, I: Iterator> {
|
||||
inner: DialerSelectSeqState<R, I>
|
||||
}
|
||||
|
||||
enum DialerSelectSeqState<R: AsyncRead + AsyncWrite, I, P> {
|
||||
enum DialerSelectSeqState<R: AsyncRead + AsyncWrite, I: Iterator> {
|
||||
AwaitDialer {
|
||||
dialer_fut: DialerFuture<R>,
|
||||
protocols: I
|
||||
@ -112,25 +93,24 @@ enum DialerSelectSeqState<R: AsyncRead + AsyncWrite, I, P> {
|
||||
},
|
||||
SendProtocol {
|
||||
sender: sink::Send<Dialer<R>>,
|
||||
proto_name: Bytes,
|
||||
proto_value: P,
|
||||
proto_name: I::Item,
|
||||
protocols: I
|
||||
},
|
||||
AwaitProtocol {
|
||||
stream: StreamFuture<Dialer<R>>,
|
||||
proto_name: Bytes,
|
||||
proto_value: P,
|
||||
proto_name: I::Item,
|
||||
protocols: I
|
||||
},
|
||||
Undefined
|
||||
}
|
||||
|
||||
impl<R, I, P> Future for DialerSelectSeq<R, I, P>
|
||||
impl<R, I> Future for DialerSelectSeq<R, I>
|
||||
where
|
||||
I: Iterator<Item=(Bytes, P)>,
|
||||
I: Iterator,
|
||||
I::Item: AsRef<[u8]>,
|
||||
R: AsyncRead + AsyncWrite,
|
||||
{
|
||||
type Item = (P, R);
|
||||
type Item = (I::Item, R);
|
||||
type Error = ProtocolChoiceError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
@ -147,28 +127,26 @@ where
|
||||
self.inner = DialerSelectSeqState::NextProtocol { dialer, protocols }
|
||||
}
|
||||
DialerSelectSeqState::NextProtocol { dialer, mut protocols } => {
|
||||
let (proto_name, proto_value) =
|
||||
let proto_name =
|
||||
protocols.next().ok_or(ProtocolChoiceError::NoProtocolFound)?;
|
||||
let req = DialerToListenerMessage::ProtocolRequest {
|
||||
name: proto_name.clone()
|
||||
name: Bytes::from(proto_name.as_ref())
|
||||
};
|
||||
trace!("sending {:?}", req);
|
||||
let sender = dialer.send(req);
|
||||
self.inner = DialerSelectSeqState::SendProtocol {
|
||||
sender,
|
||||
proto_name,
|
||||
proto_value,
|
||||
protocols
|
||||
}
|
||||
}
|
||||
DialerSelectSeqState::SendProtocol { mut sender, proto_name, proto_value, protocols } => {
|
||||
DialerSelectSeqState::SendProtocol { mut sender, proto_name, protocols } => {
|
||||
let dialer = match sender.poll()? {
|
||||
Async::Ready(d) => d,
|
||||
Async::NotReady => {
|
||||
self.inner = DialerSelectSeqState::SendProtocol {
|
||||
sender,
|
||||
proto_name,
|
||||
proto_value,
|
||||
protocols
|
||||
};
|
||||
return Ok(Async::NotReady)
|
||||
@ -178,18 +156,16 @@ where
|
||||
self.inner = DialerSelectSeqState::AwaitProtocol {
|
||||
stream,
|
||||
proto_name,
|
||||
proto_value,
|
||||
protocols
|
||||
};
|
||||
}
|
||||
DialerSelectSeqState::AwaitProtocol { mut stream, proto_name, proto_value, protocols } => {
|
||||
DialerSelectSeqState::AwaitProtocol { mut stream, proto_name, protocols } => {
|
||||
let (m, r) = match stream.poll() {
|
||||
Ok(Async::Ready(x)) => x,
|
||||
Ok(Async::NotReady) => {
|
||||
self.inner = DialerSelectSeqState::AwaitProtocol {
|
||||
stream,
|
||||
proto_name,
|
||||
proto_value,
|
||||
protocols
|
||||
};
|
||||
return Ok(Async::NotReady)
|
||||
@ -198,8 +174,10 @@ where
|
||||
};
|
||||
trace!("received {:?}", m);
|
||||
match m.ok_or(ProtocolChoiceError::UnexpectedMessage)? {
|
||||
ListenerToDialerMessage::ProtocolAck { ref name } if name == &proto_name => {
|
||||
return Ok(Async::Ready((proto_value, r.into_inner())))
|
||||
ListenerToDialerMessage::ProtocolAck { ref name }
|
||||
if name.as_ref() == proto_name.as_ref() =>
|
||||
{
|
||||
return Ok(Async::Ready((proto_name, r.into_inner())))
|
||||
},
|
||||
ListenerToDialerMessage::NotAvailable => {
|
||||
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
|
||||
/// 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
|
||||
R: AsyncRead + AsyncWrite,
|
||||
I: Iterator<Item = (Bytes, M, P)>,
|
||||
M: FnMut(&Bytes, &Bytes) -> bool,
|
||||
I: Iterator,
|
||||
I::Item: AsRef<[u8]>,
|
||||
R: AsyncRead + AsyncWrite
|
||||
{
|
||||
DialerSelectPar {
|
||||
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
|
||||
/// 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.
|
||||
pub struct DialerSelectPar<R: AsyncRead + AsyncWrite, I, P> {
|
||||
inner: DialerSelectParState<R, I, P>
|
||||
pub struct DialerSelectPar<R: AsyncRead + AsyncWrite, I: Iterator> {
|
||||
inner: DialerSelectParState<R, I>
|
||||
}
|
||||
|
||||
enum DialerSelectParState<R: AsyncRead + AsyncWrite, I, P> {
|
||||
enum DialerSelectParState<R: AsyncRead + AsyncWrite, I: Iterator> {
|
||||
AwaitDialer {
|
||||
dialer_fut: DialerFuture<R>,
|
||||
protocols: I
|
||||
@ -253,24 +231,22 @@ enum DialerSelectParState<R: AsyncRead + AsyncWrite, I, P> {
|
||||
},
|
||||
SendProtocol {
|
||||
sender: sink::Send<Dialer<R>>,
|
||||
proto_name: Bytes,
|
||||
proto_val: P
|
||||
proto_name: I::Item
|
||||
},
|
||||
AwaitProtocol {
|
||||
stream: StreamFuture<Dialer<R>>,
|
||||
proto_name: Bytes,
|
||||
proto_val: P
|
||||
proto_name: I::Item
|
||||
},
|
||||
Undefined
|
||||
}
|
||||
|
||||
impl<R, I, M, P> Future for DialerSelectPar<R, I, P>
|
||||
impl<R, I> Future for DialerSelectPar<R, I>
|
||||
where
|
||||
I: Iterator<Item=(Bytes, M, P)>,
|
||||
M: FnMut(&Bytes, &Bytes) -> bool,
|
||||
I: Iterator,
|
||||
I::Item: AsRef<[u8]>,
|
||||
R: AsyncRead + AsyncWrite,
|
||||
{
|
||||
type Item = (P, R);
|
||||
type Item = (I::Item, R);
|
||||
type Error = ProtocolChoiceError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
@ -314,10 +290,10 @@ where
|
||||
_ => return Err(ProtocolChoiceError::UnexpectedMessage),
|
||||
};
|
||||
let mut found = None;
|
||||
for (local_name, mut match_fn, ident) in protocols {
|
||||
for local_name in protocols {
|
||||
for remote_name in &list {
|
||||
if match_fn(remote_name, &local_name) {
|
||||
found = Some((remote_name.clone(), ident));
|
||||
if remote_name.as_ref() == local_name.as_ref() {
|
||||
found = Some(local_name);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@ -325,21 +301,20 @@ where
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (proto_name, proto_val) = found.ok_or(ProtocolChoiceError::NoProtocolFound)?;
|
||||
trace!("sending {:?}", proto_name);
|
||||
let proto_name = found.ok_or(ProtocolChoiceError::NoProtocolFound)?;
|
||||
trace!("sending {:?}", proto_name.as_ref());
|
||||
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()? {
|
||||
Async::Ready(d) => d,
|
||||
Async::NotReady => {
|
||||
self.inner = DialerSelectParState::SendProtocol {
|
||||
sender,
|
||||
proto_name,
|
||||
proto_val
|
||||
proto_name
|
||||
};
|
||||
return Ok(Async::NotReady)
|
||||
}
|
||||
@ -347,18 +322,16 @@ where
|
||||
let stream = dialer.into_future();
|
||||
self.inner = DialerSelectParState::AwaitProtocol {
|
||||
stream,
|
||||
proto_name,
|
||||
proto_val
|
||||
proto_name
|
||||
};
|
||||
}
|
||||
DialerSelectParState::AwaitProtocol { mut stream, proto_name, proto_val } => {
|
||||
DialerSelectParState::AwaitProtocol { mut stream, proto_name } => {
|
||||
let (m, r) = match stream.poll() {
|
||||
Ok(Async::Ready(x)) => x,
|
||||
Ok(Async::NotReady) => {
|
||||
self.inner = DialerSelectParState::AwaitProtocol {
|
||||
stream,
|
||||
proto_name,
|
||||
proto_val
|
||||
proto_name
|
||||
};
|
||||
return Ok(Async::NotReady)
|
||||
}
|
||||
@ -366,8 +339,10 @@ where
|
||||
};
|
||||
trace!("received {:?}", m);
|
||||
match m {
|
||||
Some(ListenerToDialerMessage::ProtocolAck { ref name }) if name == &proto_name => {
|
||||
return Ok(Async::Ready((proto_val, r.into_inner())))
|
||||
Some(ListenerToDialerMessage::ProtocolAck { ref name })
|
||||
if name.as_ref() == proto_name.as_ref() =>
|
||||
{
|
||||
return Ok(Async::Ready((proto_name, r.into_inner())))
|
||||
}
|
||||
_ => return Err(ProtocolChoiceError::UnexpectedMessage)
|
||||
}
|
||||
|
@ -55,17 +55,12 @@
|
||||
//! let client = TcpStream::connect(&"127.0.0.1:10333".parse().unwrap())
|
||||
//! .from_err()
|
||||
//! .and_then(move |connec| {
|
||||
//! let protos = vec![
|
||||
//! (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();
|
||||
//! let protos = vec![b"/echo/1.0.0", b"/echo/2.5.0"];
|
||||
//! dialer_select_proto(connec, protos).map(|r| r.0)
|
||||
//! });
|
||||
//!
|
||||
//! let mut rt = Runtime::new().unwrap();
|
||||
//! let negotiated_protocol: MyProto = rt.block_on(client)
|
||||
//! .expect("failed to find a protocol");
|
||||
//! let negotiated_protocol = rt.block_on(client).expect("failed to find a protocol");
|
||||
//! println!("negotiated: {:?}", negotiated_protocol);
|
||||
//! # }
|
||||
//! ```
|
||||
|
@ -43,23 +43,32 @@ use crate::ProtocolChoiceError;
|
||||
///
|
||||
/// On success, returns the socket and the identifier of the chosen protocol (of type `P`). The
|
||||
/// 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
|
||||
R: AsyncRead + AsyncWrite,
|
||||
for<'r> &'r I: IntoIterator<Item = (Bytes, M, P)>,
|
||||
M: FnMut(&Bytes, &Bytes) -> bool,
|
||||
for<'r> &'r I: IntoIterator<Item = X>,
|
||||
X: AsRef<[u8]>
|
||||
{
|
||||
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.
|
||||
pub struct ListenerSelectFuture<R: AsyncRead + AsyncWrite, I, P> {
|
||||
inner: ListenerSelectState<R, I, P>
|
||||
pub struct ListenerSelectFuture<R: AsyncRead + AsyncWrite, I, X>
|
||||
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 {
|
||||
listener_fut: ListenerFuture<R>,
|
||||
protocols: I
|
||||
@ -71,18 +80,18 @@ enum ListenerSelectState<R: AsyncRead + AsyncWrite, I, P> {
|
||||
Outgoing {
|
||||
sender: sink::Send<Listener<R>>,
|
||||
protocols: I,
|
||||
outcome: Option<P>
|
||||
outcome: Option<X>
|
||||
},
|
||||
Undefined
|
||||
}
|
||||
|
||||
impl<R, I, M, P> Future for ListenerSelectFuture<R, I, P>
|
||||
impl<R, I, X> Future for ListenerSelectFuture<R, I, X>
|
||||
where
|
||||
for<'r> &'r I: IntoIterator<Item=(Bytes, M, P)>,
|
||||
M: FnMut(&Bytes, &Bytes) -> bool,
|
||||
for<'a> &'a I: IntoIterator<Item = X>,
|
||||
R: AsyncRead + AsyncWrite,
|
||||
X: AsRef<[u8]>
|
||||
{
|
||||
type Item = (P, R, I);
|
||||
type Item = (X, R, I);
|
||||
type Error = ProtocolChoiceError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
@ -111,7 +120,7 @@ where
|
||||
match msg {
|
||||
Some(DialerToListenerMessage::ProtocolsListRequest) => {
|
||||
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);
|
||||
let sender = listener.send(msg);
|
||||
@ -124,10 +133,10 @@ where
|
||||
Some(DialerToListenerMessage::ProtocolRequest { name }) => {
|
||||
let mut outcome = None;
|
||||
let mut send_back = ListenerToDialerMessage::NotAvailable;
|
||||
for (supported, mut matches, value) in &protocols {
|
||||
if matches(&name, &supported) {
|
||||
for supported in &protocols {
|
||||
if name.as_ref() == supported.as_ref() {
|
||||
send_back = ListenerToDialerMessage::ProtocolAck {name: name.clone()};
|
||||
outcome = Some(value);
|
||||
outcome = Some(supported);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
@ -95,27 +95,21 @@ fn select_proto_basic() {
|
||||
.map(|s| s.0.unwrap())
|
||||
.map_err(|(e, _)| e.into())
|
||||
.and_then(move |connec| {
|
||||
let protos = vec![
|
||||
(Bytes::from("/proto1"), <Bytes as PartialEq>::eq, 0),
|
||||
(Bytes::from("/proto2"), <Bytes as PartialEq>::eq, 1),
|
||||
];
|
||||
let protos = vec![b"/proto1", b"/proto2"];
|
||||
listener_select_proto(connec, VecRefIntoIter(protos)).map(|r| r.0)
|
||||
});
|
||||
|
||||
let client = TcpStream::connect(&listener_addr)
|
||||
.from_err()
|
||||
.and_then(move |connec| {
|
||||
let protos = vec![
|
||||
(Bytes::from("/proto3"), <Bytes as PartialEq>::eq, 2),
|
||||
(Bytes::from("/proto2"), <Bytes as PartialEq>::eq, 3),
|
||||
].into_iter();
|
||||
let protos = vec![b"/proto3", b"/proto2"];
|
||||
dialer_select_proto(connec, protos).map(|r| r.0)
|
||||
});
|
||||
let mut rt = Runtime::new().unwrap();
|
||||
let (dialer_chosen, listener_chosen) =
|
||||
rt.block_on(client.join(server)).unwrap();
|
||||
assert_eq!(dialer_chosen, 3);
|
||||
assert_eq!(listener_chosen, 1);
|
||||
assert_eq!(dialer_chosen, b"/proto2");
|
||||
assert_eq!(listener_chosen, b"/proto2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -129,20 +123,14 @@ fn no_protocol_found() {
|
||||
.map(|s| s.0.unwrap())
|
||||
.map_err(|(e, _)| e.into())
|
||||
.and_then(move |connec| {
|
||||
let protos = vec![
|
||||
(Bytes::from("/proto1"), <Bytes as PartialEq>::eq, 1),
|
||||
(Bytes::from("/proto2"), <Bytes as PartialEq>::eq, 2),
|
||||
];
|
||||
let protos = vec![b"/proto1", b"/proto2"];
|
||||
listener_select_proto(connec, VecRefIntoIter(protos)).map(|r| r.0)
|
||||
});
|
||||
|
||||
let client = TcpStream::connect(&listener_addr)
|
||||
.from_err()
|
||||
.and_then(move |connec| {
|
||||
let protos = vec![
|
||||
(Bytes::from("/proto3"), <Bytes as PartialEq>::eq, 3),
|
||||
(Bytes::from("/proto4"), <Bytes as PartialEq>::eq, 4),
|
||||
].into_iter();
|
||||
let protos = vec![b"/proto3", b"/proto4"];
|
||||
dialer_select_proto(connec, protos).map(|r| r.0)
|
||||
});
|
||||
let mut rt = Runtime::new().unwrap();
|
||||
@ -163,28 +151,22 @@ fn select_proto_parallel() {
|
||||
.map(|s| s.0.unwrap())
|
||||
.map_err(|(e, _)| e.into())
|
||||
.and_then(move |connec| {
|
||||
let protos = vec![
|
||||
(Bytes::from("/proto1"), <Bytes as PartialEq>::eq, 0),
|
||||
(Bytes::from("/proto2"), <Bytes as PartialEq>::eq, 1),
|
||||
];
|
||||
let protos = vec![b"/proto1", b"/proto2"];
|
||||
listener_select_proto(connec, VecRefIntoIter(protos)).map(|r| r.0)
|
||||
});
|
||||
|
||||
let client = TcpStream::connect(&listener_addr)
|
||||
.from_err()
|
||||
.and_then(move |connec| {
|
||||
let protos = vec![
|
||||
(Bytes::from("/proto3"), <Bytes as PartialEq>::eq, 2),
|
||||
(Bytes::from("/proto2"), <Bytes as PartialEq>::eq, 3),
|
||||
].into_iter();
|
||||
dialer_select_proto_parallel(connec, protos).map(|r| r.0)
|
||||
let protos = vec![b"/proto3", b"/proto2"];
|
||||
dialer_select_proto_parallel(connec, protos.into_iter()).map(|r| r.0)
|
||||
});
|
||||
|
||||
let mut rt = Runtime::new().unwrap();
|
||||
let (dialer_chosen, listener_chosen) =
|
||||
rt.block_on(client.join(server)).unwrap();
|
||||
assert_eq!(dialer_chosen, 3);
|
||||
assert_eq!(listener_chosen, 1);
|
||||
assert_eq!(dialer_chosen, b"/proto2");
|
||||
assert_eq!(listener_chosen, b"/proto2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -198,23 +180,20 @@ fn select_proto_serial() {
|
||||
.map(|s| s.0.unwrap())
|
||||
.map_err(|(e, _)| e.into())
|
||||
.and_then(move |connec| {
|
||||
let protos = vec![
|
||||
(Bytes::from("/proto1"), <Bytes as PartialEq>::eq, 0),
|
||||
(Bytes::from("/proto2"), <Bytes as PartialEq>::eq, 1),
|
||||
];
|
||||
let protos = vec![b"/proto1", b"/proto2"];
|
||||
listener_select_proto(connec, VecRefIntoIter(protos)).map(|r| r.0)
|
||||
});
|
||||
|
||||
let client = TcpStream::connect(&listener_addr)
|
||||
.from_err()
|
||||
.and_then(move |connec| {
|
||||
let protos = vec![(Bytes::from("/proto3"), 2), (Bytes::from("/proto2"), 3)].into_iter();
|
||||
dialer_select_proto_serial(connec, protos).map(|r| r.0)
|
||||
let protos = vec![b"/proto3", b"/proto2"];
|
||||
dialer_select_proto_serial(connec, protos.into_iter()).map(|r| r.0)
|
||||
});
|
||||
|
||||
let mut rt = Runtime::new().unwrap();
|
||||
let (dialer_chosen, listener_chosen) =
|
||||
rt.block_on(client.join(server)).unwrap();
|
||||
assert_eq!(dialer_chosen, 3);
|
||||
assert_eq!(listener_chosen, 1);
|
||||
assert_eq!(dialer_chosen, b"/proto2");
|
||||
assert_eq!(listener_chosen, b"/proto2");
|
||||
}
|
||||
|
@ -148,12 +148,12 @@ pub enum MaxBufferBehaviour {
|
||||
}
|
||||
|
||||
impl UpgradeInfo for MplexConfig {
|
||||
type UpgradeId = ();
|
||||
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>;
|
||||
type Info = &'static [u8];
|
||||
type InfoIter = iter::Once<Self::Info>;
|
||||
|
||||
#[inline]
|
||||
fn protocol_names(&self) -> Self::NamesIter {
|
||||
iter::once((Bytes::from("/mplex/6.7.0"), ()))
|
||||
fn protocol_info(&self) -> Self::InfoIter {
|
||||
iter::once(b"/mplex/6.7.0")
|
||||
}
|
||||
}
|
||||
|
||||
@ -165,7 +165,7 @@ where
|
||||
type Error = 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))
|
||||
}
|
||||
}
|
||||
@ -178,7 +178,7 @@ where
|
||||
type Error = 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))
|
||||
}
|
||||
}
|
||||
|
@ -9,7 +9,6 @@ keywords = ["peer-to-peer", "libp2p", "networking"]
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
|
||||
[dependencies]
|
||||
bytes = "0.4"
|
||||
futures = "0.1"
|
||||
libp2p-core = { version = "0.1.0", path = "../../core" }
|
||||
log = "0.4"
|
||||
|
@ -21,7 +21,6 @@
|
||||
//! Implements the Yamux multiplexing protocol for libp2p, see also the
|
||||
//! [specification](https://github.com/hashicorp/yamux/blob/master/spec.md).
|
||||
|
||||
extern crate bytes;
|
||||
extern crate futures;
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
@ -29,7 +28,6 @@ extern crate libp2p_core;
|
||||
extern crate tokio_io;
|
||||
extern crate yamux;
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures::{future::{self, FutureResult}, prelude::*};
|
||||
use libp2p_core::{muxing::Shutdown, upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}};
|
||||
use std::{io, iter};
|
||||
@ -136,11 +134,11 @@ impl Default for Config {
|
||||
}
|
||||
|
||||
impl UpgradeInfo for Config {
|
||||
type UpgradeId = ();
|
||||
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>;
|
||||
type Info = &'static [u8];
|
||||
type InfoIter = iter::Once<Self::Info>;
|
||||
|
||||
fn protocol_names(&self) -> Self::NamesIter {
|
||||
iter::once((Bytes::from("/yamux/1.0.0"), ()))
|
||||
fn protocol_info(&self) -> Self::InfoIter {
|
||||
iter::once(b"/yamux/1.0.0")
|
||||
}
|
||||
}
|
||||
|
||||
@ -152,7 +150,7 @@ where
|
||||
type Error = 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))
|
||||
}
|
||||
}
|
||||
@ -165,7 +163,7 @@ where
|
||||
type Error = 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))
|
||||
}
|
||||
}
|
||||
|
@ -18,7 +18,7 @@
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
// DEALINGS IN THE SOFTWARE.
|
||||
|
||||
use bytes::{BufMut, Bytes, BytesMut};
|
||||
use bytes::{BufMut, BytesMut};
|
||||
use crate::rpc_proto;
|
||||
use futures::future;
|
||||
use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo, PeerId};
|
||||
@ -42,12 +42,12 @@ impl FloodsubConfig {
|
||||
}
|
||||
|
||||
impl UpgradeInfo for FloodsubConfig {
|
||||
type UpgradeId = ();
|
||||
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>;
|
||||
type Info = &'static [u8];
|
||||
type InfoIter = iter::Once<Self::Info>;
|
||||
|
||||
#[inline]
|
||||
fn protocol_names(&self) -> Self::NamesIter {
|
||||
iter::once(("/floodsub/1.0.0".into(), ()))
|
||||
fn protocol_info(&self) -> Self::InfoIter {
|
||||
iter::once(b"/floodsub/1.0.0")
|
||||
}
|
||||
}
|
||||
|
||||
@ -60,7 +60,7 @@ where
|
||||
type Future = future::FutureResult<Self::Output, Self::Error>;
|
||||
|
||||
#[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() }))
|
||||
}
|
||||
}
|
||||
@ -74,7 +74,7 @@ where
|
||||
type Future = future::FutureResult<Self::Output, Self::Error>;
|
||||
|
||||
#[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() }))
|
||||
}
|
||||
}
|
||||
|
@ -18,7 +18,7 @@
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
// DEALINGS IN THE SOFTWARE.
|
||||
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use bytes::BytesMut;
|
||||
use futures::{future::{self, FutureResult}, Async, AsyncSink, Future, Poll, Sink, Stream};
|
||||
use libp2p_core::{
|
||||
Multiaddr, PublicKey,
|
||||
@ -134,12 +134,11 @@ pub struct IdentifyInfo {
|
||||
}
|
||||
|
||||
impl UpgradeInfo for IdentifyProtocolConfig {
|
||||
type UpgradeId = ();
|
||||
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>;
|
||||
type Info = &'static [u8];
|
||||
type InfoIter = iter::Once<Self::Info>;
|
||||
|
||||
#[inline]
|
||||
fn protocol_names(&self) -> Self::NamesIter {
|
||||
iter::once((Bytes::from("/ipfs/id/1.0.0"), ()))
|
||||
fn protocol_info(&self) -> Self::InfoIter {
|
||||
iter::once(b"/ipfs/id/1.0.0")
|
||||
}
|
||||
}
|
||||
|
||||
@ -151,7 +150,7 @@ where
|
||||
type Error = 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");
|
||||
let socket = Framed::new(socket, codec::UviBytes::default());
|
||||
let sender = IdentifySender { inner: socket };
|
||||
@ -167,7 +166,7 @@ where
|
||||
type Error = IoError;
|
||||
type Future = IdentifyOutboundFuture<C>;
|
||||
|
||||
fn upgrade_outbound(self, socket: C, _: ()) -> Self::Future {
|
||||
fn upgrade_outbound(self, socket: C, _: Self::Info) -> Self::Future {
|
||||
IdentifyOutboundFuture {
|
||||
inner: Framed::new(socket, codec::UviBytes::<BytesMut>::default()),
|
||||
}
|
||||
|
@ -26,7 +26,7 @@
|
||||
//! The `Stream` component is used to poll the underlying transport, and the `Sink` component is
|
||||
//! used to send messages.
|
||||
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use bytes::BytesMut;
|
||||
use futures::{future, sink, stream, Sink, Stream};
|
||||
use libp2p_core::{InboundUpgrade, Multiaddr, OutboundUpgrade, PeerId, UpgradeInfo};
|
||||
use multihash::Multihash;
|
||||
@ -136,12 +136,12 @@ impl Into<protobuf_structs::dht::Message_Peer> for KadPeer {
|
||||
pub struct KademliaProtocolConfig;
|
||||
|
||||
impl UpgradeInfo for KademliaProtocolConfig {
|
||||
type NamesIter = iter::Once<(Bytes, ())>;
|
||||
type UpgradeId = ();
|
||||
type Info = &'static [u8];
|
||||
type InfoIter = iter::Once<Self::Info>;
|
||||
|
||||
#[inline]
|
||||
fn protocol_names(&self) -> Self::NamesIter {
|
||||
iter::once(("/ipfs/kad/1.0.0".into(), ()))
|
||||
fn protocol_info(&self) -> Self::InfoIter {
|
||||
iter::once(b"/ipfs/kad/1.0.0")
|
||||
}
|
||||
}
|
||||
|
||||
@ -154,7 +154,7 @@ where
|
||||
type Error = IoError;
|
||||
|
||||
#[inline]
|
||||
fn upgrade_inbound(self, incoming: C, _: ()) -> Self::Future {
|
||||
fn upgrade_inbound(self, incoming: C, _: Self::Info) -> Self::Future {
|
||||
future::ok(
|
||||
Framed::new(incoming, codec::UviBytes::default())
|
||||
.from_err::<IoError>()
|
||||
@ -180,7 +180,7 @@ where
|
||||
type Error = IoError;
|
||||
|
||||
#[inline]
|
||||
fn upgrade_outbound(self, incoming: C, _: ()) -> Self::Future {
|
||||
fn upgrade_outbound(self, incoming: C, _: Self::Info) -> Self::Future {
|
||||
future::ok(
|
||||
Framed::new(incoming, codec::UviBytes::default())
|
||||
.from_err::<IoError>()
|
||||
|
@ -46,11 +46,11 @@ impl Observed {
|
||||
}
|
||||
|
||||
impl UpgradeInfo for Observed {
|
||||
type UpgradeId = ();
|
||||
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>;
|
||||
type Info = &'static [u8];
|
||||
type InfoIter = iter::Once<Self::Info>;
|
||||
|
||||
fn protocol_names(&self) -> Self::NamesIter {
|
||||
iter::once((Bytes::from("/paritytech/observed-address/0.1.0"), ()))
|
||||
fn protocol_info(&self) -> Self::InfoIter {
|
||||
iter::once(b"/paritytech/observed-address/0.1.0")
|
||||
}
|
||||
}
|
||||
|
||||
@ -62,7 +62,7 @@ where
|
||||
type Error = io::Error;
|
||||
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());
|
||||
Box::new(future::ok(Sender { io }))
|
||||
}
|
||||
@ -76,7 +76,7 @@ where
|
||||
type Error = io::Error;
|
||||
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 future = io.into_future()
|
||||
.map_err(|(e, _): (io::Error, FramedRead<C, UviBytes>)| e)
|
||||
@ -126,14 +126,14 @@ mod tests {
|
||||
.into_future()
|
||||
.map_err(|(e, _)| e.into())
|
||||
.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));
|
||||
|
||||
let client = TcpStream::connect(&server_addr)
|
||||
.map_err(|e| e.into())
|
||||
.and_then(|conn| {
|
||||
Observed::new().upgrade_outbound(conn, ())
|
||||
Observed::new().upgrade_outbound(conn, b"/paritytech/observed-address/0.1.0")
|
||||
})
|
||||
.map(move |addr| {
|
||||
eprintln!("{} {}", addr, observed_addr2);
|
||||
|
@ -44,11 +44,11 @@ impl<TUserData> Default for Ping<TUserData> {
|
||||
}
|
||||
|
||||
impl<TUserData> UpgradeInfo for Ping<TUserData> {
|
||||
type UpgradeId = ();
|
||||
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>;
|
||||
type Info = &'static [u8];
|
||||
type InfoIter = iter::Once<Self::Info>;
|
||||
|
||||
fn protocol_names(&self) -> Self::NamesIter {
|
||||
iter::once(("/ipfs/ping/1.0.0".into(), ()))
|
||||
fn protocol_info(&self) -> Self::InfoIter {
|
||||
iter::once(b"/ipfs/ping/1.0.0")
|
||||
}
|
||||
}
|
||||
|
||||
@ -61,7 +61,7 @@ where
|
||||
type Future = FutureResult<Self::Output, Self::Error>;
|
||||
|
||||
#[inline]
|
||||
fn upgrade_inbound(self, socket: TSocket, _: Self::UpgradeId) -> Self::Future {
|
||||
fn upgrade_inbound(self, socket: TSocket, _: Self::Info) -> Self::Future {
|
||||
let listener = PingListener {
|
||||
inner: Framed::new(socket, Codec),
|
||||
state: PingListenerState::Listening,
|
||||
@ -79,7 +79,7 @@ where
|
||||
type Future = FutureResult<Self::Output, Self::Error>;
|
||||
|
||||
#[inline]
|
||||
fn upgrade_outbound(self, socket: TSocket, _: Self::UpgradeId) -> Self::Future {
|
||||
fn upgrade_outbound(self, socket: TSocket, _: Self::Info) -> Self::Future {
|
||||
let dialer = PingDialer {
|
||||
inner: Framed::new(socket, Codec),
|
||||
need_writer_flush: false,
|
||||
@ -341,14 +341,14 @@ mod tests {
|
||||
.into_future()
|
||||
.map_err(|(e, _)| e.into())
|
||||
.and_then(|(c, _)| {
|
||||
Ping::<()>::default().upgrade_inbound(c.unwrap(), ())
|
||||
Ping::<()>::default().upgrade_inbound(c.unwrap(), b"/ipfs/ping/1.0.0")
|
||||
})
|
||||
.flatten();
|
||||
|
||||
let client = TcpStream::connect(&listener_addr)
|
||||
.map_err(|e| e.into())
|
||||
.and_then(|c| {
|
||||
Ping::<()>::default().upgrade_outbound(c, ())
|
||||
Ping::<()>::default().upgrade_outbound(c, b"/ipfs/ping/1.0.0")
|
||||
})
|
||||
.and_then(|mut pinger| {
|
||||
pinger.ping(());
|
||||
@ -371,14 +371,14 @@ mod tests {
|
||||
.into_future()
|
||||
.map_err(|(e, _)| e.into())
|
||||
.and_then(|(c, _)| {
|
||||
Ping::<u32>::default().upgrade_inbound(c.unwrap(), ())
|
||||
Ping::<u32>::default().upgrade_inbound(c.unwrap(), b"/ipfs/ping/1.0.0")
|
||||
})
|
||||
.flatten();
|
||||
|
||||
let client = TcpStream::connect(&listener_addr)
|
||||
.map_err(|e| e.into())
|
||||
.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| {
|
||||
for n in 0..20 {
|
||||
|
@ -9,7 +9,6 @@ keywords = ["peer-to-peer", "libp2p", "networking"]
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
|
||||
[dependencies]
|
||||
bytes = "0.4"
|
||||
futures = "0.1"
|
||||
libp2p-core = { version = "0.1.0", path = "../../core" }
|
||||
void = "1"
|
||||
|
@ -18,12 +18,10 @@
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
// DEALINGS IN THE SOFTWARE.
|
||||
|
||||
extern crate bytes;
|
||||
extern crate futures;
|
||||
extern crate libp2p_core;
|
||||
extern crate void;
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures::future::{self, FutureResult};
|
||||
use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo};
|
||||
use std::iter;
|
||||
@ -33,11 +31,11 @@ use void::Void;
|
||||
pub struct PlainTextConfig;
|
||||
|
||||
impl UpgradeInfo for PlainTextConfig {
|
||||
type UpgradeId = ();
|
||||
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>;
|
||||
type Info = &'static [u8];
|
||||
type InfoIter = iter::Once<Self::Info>;
|
||||
|
||||
fn protocol_names(&self) -> Self::NamesIter {
|
||||
iter::once((Bytes::from("/plaintext/1.0.0"), ()))
|
||||
fn protocol_info(&self) -> Self::InfoIter {
|
||||
iter::once(b"/plaintext/1.0.0")
|
||||
}
|
||||
}
|
||||
|
||||
@ -46,7 +44,7 @@ impl<C> InboundUpgrade<C> for PlainTextConfig {
|
||||
type Error = Void;
|
||||
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)
|
||||
}
|
||||
}
|
||||
@ -56,7 +54,7 @@ impl<C> OutboundUpgrade<C> for PlainTextConfig {
|
||||
type Error = Void;
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
@ -116,7 +116,7 @@ pub use self::error::SecioError;
|
||||
|
||||
#[cfg(feature = "secp256k1")]
|
||||
use asn1_der::{traits::FromDerEncoded, traits::FromDerObject, DerObject};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use bytes::BytesMut;
|
||||
use ed25519_dalek::Keypair as Ed25519KeyPair;
|
||||
use futures::stream::MapErr as StreamMapErr;
|
||||
use futures::{Future, Poll, Sink, StartSend, Stream};
|
||||
@ -193,7 +193,7 @@ impl SecioConfig {
|
||||
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
|
||||
T: AsyncRead + AsyncWrite + Send + 'static
|
||||
{
|
||||
@ -371,11 +371,11 @@ where
|
||||
}
|
||||
|
||||
impl UpgradeInfo for SecioConfig {
|
||||
type UpgradeId = ();
|
||||
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>;
|
||||
type Info = &'static [u8];
|
||||
type InfoIter = iter::Once<Self::Info>;
|
||||
|
||||
fn protocol_names(&self) -> Self::NamesIter {
|
||||
iter::once(("/secio/1.0.0".into(), ()))
|
||||
fn protocol_info(&self) -> Self::InfoIter {
|
||||
iter::once(b"/secio/1.0.0")
|
||||
}
|
||||
}
|
||||
|
||||
@ -387,8 +387,8 @@ where
|
||||
type Error = SecioError;
|
||||
type Future = Box<dyn Future<Item = Self::Output, Error = Self::Error> + Send>;
|
||||
|
||||
fn upgrade_inbound(self, socket: T, id: Self::UpgradeId) -> Self::Future {
|
||||
Box::new(self.handshake(socket, id))
|
||||
fn upgrade_inbound(self, socket: T, _: Self::Info) -> Self::Future {
|
||||
Box::new(self.handshake(socket))
|
||||
}
|
||||
}
|
||||
|
||||
@ -400,8 +400,8 @@ where
|
||||
type Error = SecioError;
|
||||
type Future = Box<dyn Future<Item = Self::Output, Error = Self::Error> + Send>;
|
||||
|
||||
fn upgrade_outbound(self, socket: T, id: Self::UpgradeId) -> Self::Future {
|
||||
Box::new(self.handshake(socket, id))
|
||||
fn upgrade_outbound(self, socket: T, _: Self::Info) -> Self::Future {
|
||||
Box::new(self.handshake(socket))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -27,7 +27,7 @@ use tokio_io::{AsyncRead, AsyncWrite};
|
||||
/// Implementation of `ConnectionUpgrade`. Convenient to use with small protocols.
|
||||
#[derive(Debug)]
|
||||
pub struct SimpleProtocol<F> {
|
||||
name: Bytes,
|
||||
info: Bytes,
|
||||
// Note: we put the closure `F` in an `Arc` because Rust closures aren't automatically clonable
|
||||
// yet.
|
||||
upgrade: Arc<F>,
|
||||
@ -36,12 +36,12 @@ pub struct SimpleProtocol<F> {
|
||||
impl<F> SimpleProtocol<F> {
|
||||
/// Builds a `SimpleProtocol`.
|
||||
#[inline]
|
||||
pub fn new<N>(name: N, upgrade: F) -> SimpleProtocol<F>
|
||||
pub fn new<N>(info: N, upgrade: F) -> SimpleProtocol<F>
|
||||
where
|
||||
N: Into<Bytes>,
|
||||
{
|
||||
SimpleProtocol {
|
||||
name: name.into(),
|
||||
info: info.into(),
|
||||
upgrade: Arc::new(upgrade),
|
||||
}
|
||||
}
|
||||
@ -51,19 +51,19 @@ impl<F> Clone for SimpleProtocol<F> {
|
||||
#[inline]
|
||||
fn clone(&self) -> Self {
|
||||
SimpleProtocol {
|
||||
name: self.name.clone(),
|
||||
info: self.info.clone(),
|
||||
upgrade: self.upgrade.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<F> UpgradeInfo for SimpleProtocol<F> {
|
||||
type UpgradeId = ();
|
||||
type NamesIter = iter::Once<(Bytes, Self::UpgradeId)>;
|
||||
type Info = Bytes;
|
||||
type InfoIter = iter::Once<Self::Info>;
|
||||
|
||||
#[inline]
|
||||
fn protocol_names(&self) -> Self::NamesIter {
|
||||
iter::once((self.name.clone(), ()))
|
||||
fn protocol_info(&self) -> Self::InfoIter {
|
||||
iter::once(self.info.clone())
|
||||
}
|
||||
}
|
||||
|
||||
@ -78,7 +78,7 @@ where
|
||||
type Future = FromErr<O::Future, IoError>;
|
||||
|
||||
#[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;
|
||||
upgrade(socket).into_future().from_err()
|
||||
}
|
||||
@ -95,7 +95,7 @@ where
|
||||
type Future = FromErr<O::Future, IoError>;
|
||||
|
||||
#[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;
|
||||
upgrade(socket).into_future().from_err()
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user