mirror of
https://github.com/fluencelabs/rust-libp2p
synced 2025-06-12 01:21:21 +00:00
Add a custom derive for NetworkBehaviour (#619)
* Add ProtocolsHandlerSelect * Add a custom derive for NetworkBehaviour * Remove 2018 edition * More work * Update the tests and work * Allow ignored fields * More fixes * Give access to everything in the poll method
This commit is contained in:
@ -23,6 +23,7 @@ libp2p-ping = { path = "./protocols/ping" }
|
||||
libp2p-ratelimit = { path = "./transports/ratelimit" }
|
||||
libp2p-relay = { path = "./transports/relay" }
|
||||
libp2p-core = { path = "./core" }
|
||||
libp2p-core-derive = { path = "./misc/core-derive" }
|
||||
libp2p-secio = { path = "./protocols/secio", default-features = false }
|
||||
libp2p-transport-timeout = { path = "./transports/timeout" }
|
||||
libp2p-uds = { path = "./transports/uds" }
|
||||
@ -51,6 +52,7 @@ tokio-stdin = "0.1"
|
||||
[workspace]
|
||||
members = [
|
||||
"core",
|
||||
"misc/core-derive",
|
||||
"misc/multiaddr",
|
||||
"misc/multihash",
|
||||
"misc/multistream-select",
|
||||
|
@ -18,6 +18,7 @@
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
// DEALINGS IN THE SOFTWARE.
|
||||
|
||||
use either::EitherOutput;
|
||||
use futures::prelude::*;
|
||||
use nodes::handled_node::{NodeHandler, NodeHandlerEndpoint, NodeHandlerEvent};
|
||||
use std::{io, marker::PhantomData, time::Duration};
|
||||
@ -156,6 +157,19 @@ pub trait ProtocolsHandler {
|
||||
MapOutEvent { inner: self, map }
|
||||
}
|
||||
|
||||
/// Builds an implementation of `ProtocolsHandler` that handles both this protocol and the
|
||||
/// other one together.
|
||||
#[inline]
|
||||
fn select<TProto2>(self, other: TProto2) -> ProtocolsHandlerSelect<Self, TProto2>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
ProtocolsHandlerSelect {
|
||||
proto1: self,
|
||||
proto2: other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a builder that will allow creating a `NodeHandler` that handles this protocol
|
||||
/// exclusively.
|
||||
#[inline]
|
||||
@ -680,3 +694,129 @@ where
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
|
||||
/// Implementation of `ProtocolsHandler` that combines two protocols into one.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProtocolsHandlerSelect<TProto1, TProto2> {
|
||||
proto1: TProto1,
|
||||
proto2: TProto2,
|
||||
}
|
||||
|
||||
impl<TSubstream, TProto1, TProto2, TProto1Out, TProto2Out>
|
||||
ProtocolsHandler for ProtocolsHandlerSelect<TProto1, TProto2>
|
||||
where TProto1: ProtocolsHandler<Substream = TSubstream>,
|
||||
TProto2: ProtocolsHandler<Substream = TSubstream>,
|
||||
TSubstream: AsyncRead + AsyncWrite,
|
||||
TProto1::Protocol: ConnectionUpgrade<TSubstream, Output = TProto1Out>,
|
||||
TProto2::Protocol: ConnectionUpgrade<TSubstream, Output = TProto2Out>,
|
||||
{
|
||||
type InEvent = EitherOutput<TProto1::InEvent, TProto2::InEvent>;
|
||||
type OutEvent = EitherOutput<TProto1::OutEvent, TProto2::OutEvent>;
|
||||
type Substream = TSubstream;
|
||||
type Protocol = upgrade::OrUpgrade<upgrade::toggleable::Toggleable<upgrade::map::Map<TProto1::Protocol, fn(TProto1Out) -> EitherOutput<TProto1Out, TProto2Out>>>, upgrade::toggleable::Toggleable<upgrade::map::Map<TProto2::Protocol, fn(TProto2Out) -> EitherOutput<TProto1Out, TProto2Out>>>>;
|
||||
type OutboundOpenInfo = EitherOutput<TProto1::OutboundOpenInfo, TProto2::OutboundOpenInfo>;
|
||||
|
||||
#[inline]
|
||||
fn listen_protocol(&self) -> Self::Protocol {
|
||||
let proto1 = upgrade::toggleable(upgrade::map::<_, fn(_) -> _>(self.proto1.listen_protocol(), EitherOutput::First));
|
||||
let proto2 = upgrade::toggleable(upgrade::map::<_, fn(_) -> _>(self.proto2.listen_protocol(), EitherOutput::Second));
|
||||
upgrade::or(proto1, proto2)
|
||||
}
|
||||
|
||||
fn inject_fully_negotiated(&mut self, protocol: <Self::Protocol as ConnectionUpgrade<TSubstream>>::Output, endpoint: NodeHandlerEndpoint<Self::OutboundOpenInfo>) {
|
||||
match (protocol, endpoint) {
|
||||
(EitherOutput::First(protocol), NodeHandlerEndpoint::Dialer(EitherOutput::First(info))) => {
|
||||
self.proto1.inject_fully_negotiated(protocol, NodeHandlerEndpoint::Dialer(info));
|
||||
},
|
||||
(EitherOutput::Second(protocol), NodeHandlerEndpoint::Dialer(EitherOutput::Second(info))) => {
|
||||
self.proto2.inject_fully_negotiated(protocol, NodeHandlerEndpoint::Dialer(info));
|
||||
},
|
||||
(EitherOutput::First(_), NodeHandlerEndpoint::Dialer(EitherOutput::Second(_))) => {
|
||||
panic!("wrong API usage: the protocol doesn't match the upgrade info")
|
||||
},
|
||||
(EitherOutput::Second(_), NodeHandlerEndpoint::Dialer(EitherOutput::First(_))) => {
|
||||
panic!("wrong API usage: the protocol doesn't match the upgrade info")
|
||||
},
|
||||
(EitherOutput::First(protocol), NodeHandlerEndpoint::Listener) => {
|
||||
self.proto1.inject_fully_negotiated(protocol, NodeHandlerEndpoint::Listener);
|
||||
},
|
||||
(EitherOutput::Second(protocol), NodeHandlerEndpoint::Listener) => {
|
||||
self.proto2.inject_fully_negotiated(protocol, NodeHandlerEndpoint::Listener);
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn inject_event(&mut self, event: Self::InEvent) {
|
||||
match event {
|
||||
EitherOutput::First(event) => self.proto1.inject_event(event),
|
||||
EitherOutput::Second(event) => self.proto2.inject_event(event),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn inject_inbound_closed(&mut self) {
|
||||
self.proto1.inject_inbound_closed();
|
||||
self.proto2.inject_inbound_closed();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn inject_dial_upgrade_error(&mut self, info: Self::OutboundOpenInfo, error: io::Error) {
|
||||
match info {
|
||||
EitherOutput::First(info) => self.proto1.inject_dial_upgrade_error(info, error),
|
||||
EitherOutput::Second(info) => self.proto2.inject_dial_upgrade_error(info, error),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn shutdown(&mut self) {
|
||||
self.proto1.shutdown();
|
||||
self.proto2.shutdown();
|
||||
}
|
||||
|
||||
fn poll(&mut self) -> Poll<Option<ProtocolsHandlerEvent<Self::Protocol, Self::OutboundOpenInfo, Self::OutEvent>>, io::Error> {
|
||||
match self.proto1.poll()? {
|
||||
Async::Ready(Some(ProtocolsHandlerEvent::Custom(event))) => {
|
||||
return Ok(Async::Ready(Some(ProtocolsHandlerEvent::Custom(EitherOutput::First(event)))));
|
||||
},
|
||||
Async::Ready(Some(ProtocolsHandlerEvent::OutboundSubstreamRequest { upgrade, info})) => {
|
||||
let upgrade = {
|
||||
let proto1 = upgrade::toggleable(upgrade::map::<_, fn(_) -> _>(upgrade, EitherOutput::First));
|
||||
let mut proto2 = upgrade::toggleable(upgrade::map::<_, fn(_) -> _>(self.proto2.listen_protocol(), EitherOutput::Second));
|
||||
proto2.disable();
|
||||
upgrade::or(proto1, proto2)
|
||||
};
|
||||
|
||||
return Ok(Async::Ready(Some(ProtocolsHandlerEvent::OutboundSubstreamRequest {
|
||||
upgrade,
|
||||
info: EitherOutput::First(info),
|
||||
})));
|
||||
},
|
||||
Async::Ready(None) => return Ok(Async::Ready(None)),
|
||||
Async::NotReady => ()
|
||||
};
|
||||
|
||||
match self.proto2.poll()? {
|
||||
Async::Ready(Some(ProtocolsHandlerEvent::Custom(event))) => {
|
||||
return Ok(Async::Ready(Some(ProtocolsHandlerEvent::Custom(EitherOutput::Second(event)))));
|
||||
},
|
||||
Async::Ready(Some(ProtocolsHandlerEvent::OutboundSubstreamRequest { upgrade, info })) => {
|
||||
let upgrade = {
|
||||
let mut proto1 = upgrade::toggleable(upgrade::map::<_, fn(_) -> _>(self.proto1.listen_protocol(), EitherOutput::First));
|
||||
proto1.disable();
|
||||
let proto2 = upgrade::toggleable(upgrade::map::<_, fn(_) -> _>(upgrade, EitherOutput::Second));
|
||||
upgrade::or(proto1, proto2)
|
||||
};
|
||||
|
||||
return Ok(Async::Ready(Some(ProtocolsHandlerEvent::OutboundSubstreamRequest {
|
||||
upgrade,
|
||||
info: EitherOutput::Second(info),
|
||||
})));
|
||||
},
|
||||
Async::Ready(None) => return Ok(Async::Ready(None)),
|
||||
Async::NotReady => ()
|
||||
};
|
||||
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
|
@ -18,7 +18,6 @@
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
// DEALINGS IN THE SOFTWARE.
|
||||
|
||||
use std::io::Error as IoError;
|
||||
use futures::prelude::*;
|
||||
use tokio_io::{AsyncRead, AsyncWrite};
|
||||
use upgrade::{ConnectionUpgrade, Endpoint};
|
||||
@ -39,9 +38,8 @@ pub struct Map<U, F> {
|
||||
impl<C, U, F, O> ConnectionUpgrade<C> for Map<U, F>
|
||||
where
|
||||
U: ConnectionUpgrade<C>,
|
||||
U::Future: Send + 'static, // TODO: 'static :(
|
||||
C: AsyncRead + AsyncWrite,
|
||||
F: FnOnce(U::Output) -> O + Send + 'static, // TODO: 'static :(
|
||||
F: FnOnce(U::Output) -> O,
|
||||
{
|
||||
type NamesIter = U::NamesIter;
|
||||
type UpgradeIdentifier = U::UpgradeIdentifier;
|
||||
@ -51,7 +49,7 @@ where
|
||||
}
|
||||
|
||||
type Output = O;
|
||||
type Future = Box<Future<Item = O, Error = IoError> + Send>;
|
||||
type Future = MapFuture<U::Future, F>;
|
||||
|
||||
fn upgrade(
|
||||
self,
|
||||
@ -59,10 +57,28 @@ where
|
||||
id: Self::UpgradeIdentifier,
|
||||
ty: Endpoint,
|
||||
) -> Self::Future {
|
||||
let map = self.map;
|
||||
let fut = self.upgrade
|
||||
.upgrade(socket, id, ty)
|
||||
.map(map);
|
||||
Box::new(fut) as Box<_>
|
||||
MapFuture {
|
||||
inner: self.upgrade.upgrade(socket, id, ty),
|
||||
map: Some(self.map),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MapFuture<TInnerFut, TMap> {
|
||||
inner: TInnerFut,
|
||||
map: Option<TMap>,
|
||||
}
|
||||
|
||||
impl<TInnerFut, TIn, TMap, TOut> Future for MapFuture<TInnerFut, TMap>
|
||||
where TInnerFut: Future<Item = TIn>,
|
||||
TMap: FnOnce(TIn) -> TOut,
|
||||
{
|
||||
type Item = TOut;
|
||||
type Error = TInnerFut::Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
let item = try_ready!(self.inner.poll());
|
||||
let map = self.map.take().expect("Future has already finished");
|
||||
Ok(Async::Ready(map(item)))
|
||||
}
|
||||
}
|
||||
|
15
misc/core-derive/Cargo.toml
Normal file
15
misc/core-derive/Cargo.toml
Normal file
@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "libp2p-core-derive"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
license = "MIT"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
syn = { version = "0.15", default-features = false, features = ["derive", "parsing", "printing", "proc-macro"] }
|
||||
quote = "0.6"
|
||||
|
||||
[dev-dependencies]
|
||||
libp2p = { path = "../.." }
|
394
misc/core-derive/src/lib.rs
Normal file
394
misc/core-derive/src/lib.rs
Normal file
@ -0,0 +1,394 @@
|
||||
// Copyright 2018 Parity Technologies (UK) Ltd.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a
|
||||
// copy of this software and associated documentation files (the "Software"),
|
||||
// to deal in the Software without restriction, including without limitation
|
||||
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
// and/or sell copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
// DEALINGS IN THE SOFTWARE.
|
||||
|
||||
#![recursion_limit = "256"]
|
||||
|
||||
extern crate proc_macro;
|
||||
#[macro_use]
|
||||
extern crate syn;
|
||||
#[macro_use]
|
||||
extern crate quote;
|
||||
|
||||
use self::proc_macro::TokenStream;
|
||||
use syn::{DeriveInput, Data, DataStruct, Ident};
|
||||
|
||||
/// The interface that satisfies Rust.
|
||||
#[proc_macro_derive(NetworkBehaviour, attributes(behaviour))]
|
||||
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
|
||||
let ast = parse_macro_input!(input as DeriveInput);
|
||||
build(&ast)
|
||||
}
|
||||
|
||||
/// The actual implementation.
|
||||
fn build(ast: &DeriveInput) -> TokenStream {
|
||||
match ast.data {
|
||||
Data::Struct(ref s) => build_struct(ast, s),
|
||||
Data::Enum(_) => unimplemented!("Deriving NetworkBehavior is not implemented for enums"),
|
||||
Data::Union(_) => unimplemented!("Deriving NetworkBehavior is not implemented for unions"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The version for structs
|
||||
fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream {
|
||||
let name = &ast.ident;
|
||||
let (_, ty_generics, where_clause) = ast.generics.split_for_impl();
|
||||
let trait_to_impl = quote!{::libp2p::core::nodes::swarm::NetworkBehavior};
|
||||
let either_ident = quote!{::libp2p::core::either::EitherOutput};
|
||||
let network_behaviour_action = quote!{::libp2p::core::nodes::swarm::NetworkBehaviorAction};
|
||||
let protocols_handler = quote!{::libp2p::core::nodes::protocols_handler::ProtocolsHandler};
|
||||
let proto_select_ident = quote!{::libp2p::core::nodes::protocols_handler::ProtocolsHandlerSelect};
|
||||
let peer_id = quote!{::libp2p::core::PeerId};
|
||||
let connected_point = quote!{::libp2p::core::nodes::ConnectedPoint};
|
||||
|
||||
// Name of the type parameter that represents the substream.
|
||||
let substream_generic = {
|
||||
let mut n = "TSubstream".to_string();
|
||||
// Avoid collisions.
|
||||
while ast.generics.type_params().any(|tp| tp.ident.to_string() == n) {
|
||||
n.push('1');
|
||||
}
|
||||
let n = Ident::new(&n, name.span());
|
||||
quote!{#n}
|
||||
};
|
||||
|
||||
// Build the generics.
|
||||
let impl_generics = {
|
||||
let tp = ast.generics.type_params();
|
||||
let lf = ast.generics.lifetimes();
|
||||
let cst = ast.generics.const_params();
|
||||
quote!{<#(#lf,)* #(#tp,)* #(#cst,)* #substream_generic>}
|
||||
};
|
||||
|
||||
// Build the `where ...` clause of the trait implementation.
|
||||
let where_clause = {
|
||||
let mut additional = data_struct.fields.iter().flat_map(|field| {
|
||||
if is_ignored(&field) {
|
||||
return vec![];
|
||||
}
|
||||
|
||||
let ty = &field.ty;
|
||||
vec![
|
||||
quote!{#ty: #trait_to_impl},
|
||||
quote!{<#ty as #trait_to_impl>::ProtocolsHandler: #protocols_handler<Substream = #substream_generic>},
|
||||
// Note: this bound is required because of https://github.com/rust-lang/rust/issues/55697
|
||||
quote!{<<#ty as #trait_to_impl>::ProtocolsHandler as #protocols_handler>::Protocol: ::libp2p::core::ConnectionUpgrade<#substream_generic>},
|
||||
]
|
||||
}).collect::<Vec<_>>();
|
||||
|
||||
additional.push(quote!{#substream_generic: ::libp2p::tokio_io::AsyncRead});
|
||||
additional.push(quote!{#substream_generic: ::libp2p::tokio_io::AsyncWrite});
|
||||
|
||||
if let Some(where_clause) = where_clause {
|
||||
Some(quote!{#where_clause, #(#additional),*})
|
||||
} else {
|
||||
Some(quote!{where #(#additional),*})
|
||||
}
|
||||
};
|
||||
|
||||
// The final out event.
|
||||
// If we find a `#[behaviour(out_event = "Foo")]` attribute on the struct, we set `Foo` as
|
||||
// the out event. Otherwise we use `()`.
|
||||
let out_event = {
|
||||
let mut out = quote!{()};
|
||||
for meta_items in ast.attrs.iter().filter_map(get_meta_items) {
|
||||
for meta_item in meta_items {
|
||||
match meta_item {
|
||||
syn::NestedMeta::Meta(syn::Meta::NameValue(ref m)) if m.ident == "out_event" => {
|
||||
if let syn::Lit::Str(ref s) = m.lit {
|
||||
let ident: Ident = syn::parse_str(&s.value()).unwrap();
|
||||
out = quote!{#ident};
|
||||
}
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
|
||||
// Build the list of statements to put in the body of `inject_connected()`.
|
||||
let inject_connected_stmts = {
|
||||
let num_fields = data_struct.fields.iter().filter(|f| !is_ignored(f)).count();
|
||||
data_struct.fields.iter().enumerate().filter_map(move |(field_n, field)| {
|
||||
if is_ignored(&field) {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(if field_n == num_fields - 1 {
|
||||
match field.ident {
|
||||
Some(ref i) => quote!{ self.#i.inject_connected(peer_id, endpoint); },
|
||||
None => quote!{ self.#field_n.inject_connected(peer_id, endpoint); },
|
||||
}
|
||||
} else {
|
||||
match field.ident {
|
||||
Some(ref i) => quote!{ self.#i.inject_connected(peer_id.clone(), endpoint.clone()); },
|
||||
None => quote!{ self.#field_n.inject_connected(peer_id.clone(), endpoint.clone()); },
|
||||
}
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
// Build the list of statements to put in the body of `inject_disconnected()`.
|
||||
let inject_disconnected_stmts = {
|
||||
let num_fields = data_struct.fields.iter().filter(|f| !is_ignored(f)).count();
|
||||
data_struct.fields.iter().enumerate().filter_map(move |(field_n, field)| {
|
||||
if is_ignored(&field) {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(if field_n == num_fields - 1 {
|
||||
match field.ident {
|
||||
Some(ref i) => quote!{ self.#i.inject_disconnected(peer_id, endpoint); },
|
||||
None => quote!{ self.#field_n.inject_disconnected(peer_id, endpoint); },
|
||||
}
|
||||
} else {
|
||||
match field.ident {
|
||||
Some(ref i) => quote!{ self.#i.inject_disconnected(peer_id, endpoint.clone()); },
|
||||
None => quote!{ self.#field_n.inject_disconnected(peer_id, endpoint.clone()); },
|
||||
}
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
// Build the list of variants to put in the body of `inject_node_event()`.
|
||||
//
|
||||
// The event type is a construction of nested `#either_ident`s of the events of the children.
|
||||
// We call `inject_node_event` on the corresponding child.
|
||||
let inject_node_event_stmts = data_struct.fields.iter().enumerate().filter(|f| !is_ignored(&f.1)).enumerate().map(|(enum_n, (field_n, field))| {
|
||||
let mut elem = if enum_n != 0 {
|
||||
quote!{ #either_ident::Second(ev) }
|
||||
} else {
|
||||
quote!{ ev }
|
||||
};
|
||||
|
||||
for _ in 0 .. data_struct.fields.iter().filter(|f| !is_ignored(f)).count() - 1 - field_n {
|
||||
elem = quote!{ #either_ident::First(#elem) };
|
||||
}
|
||||
|
||||
Some(match field.ident {
|
||||
Some(ref i) => quote!{ #elem => self.#i.inject_node_event(peer_id, ev) },
|
||||
None => quote!{ #elem => self.#field_n.inject_node_event(peer_id, ev) },
|
||||
})
|
||||
});
|
||||
|
||||
// The `ProtocolsHandler` associated type.
|
||||
let protocols_handler_ty = {
|
||||
let mut ph_ty = None;
|
||||
for field in data_struct.fields.iter() {
|
||||
if is_ignored(&field) {
|
||||
continue;
|
||||
}
|
||||
let ty = &field.ty;
|
||||
let field_info = quote!{ <#ty as #trait_to_impl>::ProtocolsHandler };
|
||||
match ph_ty {
|
||||
Some(ev) => ph_ty = Some(quote!{ #proto_select_ident<#ev, #field_info> }),
|
||||
ref mut ev @ None => *ev = Some(field_info),
|
||||
}
|
||||
}
|
||||
ph_ty.unwrap_or(quote!{()}) // TODO: `!` instead
|
||||
};
|
||||
|
||||
// The content of `new_handler()`.
|
||||
// Example output: `self.field1.select(self.field2.select(self.field3))`.
|
||||
let new_handler = {
|
||||
let mut out_handler = None;
|
||||
|
||||
for (field_n, field) in data_struct.fields.iter().enumerate() {
|
||||
if is_ignored(&field) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let field_name = match field.ident {
|
||||
Some(ref i) => quote!{ self.#i },
|
||||
None => quote!{ self.#field_n },
|
||||
};
|
||||
|
||||
let builder = quote! {
|
||||
#field_name.new_handler()
|
||||
};
|
||||
|
||||
match out_handler {
|
||||
Some(h) => out_handler = Some(quote!{ #h.select(#builder) }),
|
||||
ref mut h @ None => *h = Some(builder),
|
||||
}
|
||||
}
|
||||
|
||||
out_handler.unwrap_or(quote!{()}) // TODO: incorrect
|
||||
};
|
||||
|
||||
// The method to use to poll.
|
||||
// If we find a `#[behaviour(poll_method = "poll")]` attribute on the struct, we call
|
||||
// `self.poll()` at the end of the polling.
|
||||
let poll_method = {
|
||||
let mut poll_method = quote!{Async::NotReady};
|
||||
for meta_items in ast.attrs.iter().filter_map(get_meta_items) {
|
||||
for meta_item in meta_items {
|
||||
match meta_item {
|
||||
syn::NestedMeta::Meta(syn::Meta::NameValue(ref m)) if m.ident == "poll_method" => {
|
||||
if let syn::Lit::Str(ref s) = m.lit {
|
||||
let ident: Ident = syn::parse_str(&s.value()).unwrap();
|
||||
poll_method = quote!{#name::#ident(self)};
|
||||
}
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
poll_method
|
||||
};
|
||||
|
||||
// List of statements to put in `poll()`.
|
||||
//
|
||||
// We poll each child one by one and wrap around the output.
|
||||
let poll_stmts = data_struct.fields.iter().enumerate().filter(|f| !is_ignored(&f.1)).enumerate().map(|(enum_n, (field_n, field))| {
|
||||
let field_name = match field.ident {
|
||||
Some(ref i) => quote!{ self.#i },
|
||||
None => quote!{ self.#field_n },
|
||||
};
|
||||
|
||||
let mut handler_fn: Option<Ident> = None;
|
||||
for meta_items in field.attrs.iter().filter_map(get_meta_items) {
|
||||
for meta_item in meta_items {
|
||||
match meta_item {
|
||||
// Parse `#[behaviour(handler = "foo")]`
|
||||
syn::NestedMeta::Meta(syn::Meta::NameValue(ref m)) if m.ident == "handler" => {
|
||||
if let syn::Lit::Str(ref s) = m.lit {
|
||||
handler_fn = Some(syn::parse_str(&s.value()).unwrap());
|
||||
}
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let handling = if let Some(handler_fn) = handler_fn {
|
||||
quote!{self.#handler_fn(event)}
|
||||
} else {
|
||||
quote!{}
|
||||
};
|
||||
|
||||
let mut wrapped_event = if enum_n != 0 {
|
||||
quote!{ #either_ident::Second(event) }
|
||||
} else {
|
||||
quote!{ event }
|
||||
};
|
||||
for _ in 0 .. data_struct.fields.iter().filter(|f| !is_ignored(f)).count() - 1 - field_n {
|
||||
wrapped_event = quote!{ #either_ident::First(#wrapped_event) };
|
||||
}
|
||||
|
||||
Some(quote!{
|
||||
loop {
|
||||
match #field_name.poll() {
|
||||
Async::Ready(#network_behaviour_action::GenerateEvent(event)) => {
|
||||
#handling
|
||||
}
|
||||
Async::Ready(#network_behaviour_action::DialAddress { address }) => {
|
||||
return Async::Ready(#network_behaviour_action::DialAddress { address });
|
||||
}
|
||||
Async::Ready(#network_behaviour_action::DialPeer { peer_id }) => {
|
||||
return Async::Ready(#network_behaviour_action::DialPeer { peer_id });
|
||||
}
|
||||
Async::Ready(#network_behaviour_action::SendEvent { peer_id, event }) => {
|
||||
return Async::Ready(#network_behaviour_action::SendEvent {
|
||||
peer_id,
|
||||
event: #wrapped_event,
|
||||
});
|
||||
}
|
||||
Async::NotReady => break,
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
// Now the magic happens.
|
||||
let final_quote = quote!{
|
||||
impl #impl_generics #trait_to_impl for #name #ty_generics
|
||||
#where_clause
|
||||
{
|
||||
type ProtocolsHandler = #protocols_handler_ty;
|
||||
type OutEvent = #out_event;
|
||||
|
||||
#[inline]
|
||||
fn new_handler(&mut self) -> Self::ProtocolsHandler {
|
||||
use #protocols_handler;
|
||||
#new_handler
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn inject_connected(&mut self, peer_id: #peer_id, endpoint: #connected_point) {
|
||||
#(#inject_connected_stmts);*
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn inject_disconnected(&mut self, peer_id: &#peer_id, endpoint: #connected_point) {
|
||||
#(#inject_disconnected_stmts);*
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn inject_node_event(
|
||||
&mut self,
|
||||
peer_id: #peer_id,
|
||||
event: <Self::ProtocolsHandler as #protocols_handler>::OutEvent
|
||||
) {
|
||||
match event {
|
||||
#(#inject_node_event_stmts),*
|
||||
}
|
||||
}
|
||||
|
||||
fn poll(&mut self) -> ::libp2p::futures::Async<#network_behaviour_action<<Self::ProtocolsHandler as #protocols_handler>::InEvent, Self::OutEvent>> {
|
||||
use libp2p::futures::prelude::*;
|
||||
#(#poll_stmts)*
|
||||
let f: ::libp2p::futures::Async<#network_behaviour_action<<Self::ProtocolsHandler as #protocols_handler>::InEvent, Self::OutEvent>> = #poll_method;
|
||||
f
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
final_quote.into()
|
||||
}
|
||||
|
||||
fn get_meta_items(attr: &syn::Attribute) -> Option<Vec<syn::NestedMeta>> {
|
||||
if attr.path.segments.len() == 1 && attr.path.segments[0].ident == "behaviour" {
|
||||
match attr.interpret_meta() {
|
||||
Some(syn::Meta::List(ref meta)) => Some(meta.nested.iter().cloned().collect()),
|
||||
_ => {
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if a field is marked as ignored by the user.
|
||||
fn is_ignored(field: &syn::Field) -> bool {
|
||||
for meta_items in field.attrs.iter().filter_map(get_meta_items) {
|
||||
for meta_item in meta_items {
|
||||
match meta_item {
|
||||
syn::NestedMeta::Meta(syn::Meta::Word(ref m)) if m == "ignore" => {
|
||||
return true;
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
122
misc/core-derive/tests/test.rs
Normal file
122
misc/core-derive/tests/test.rs
Normal file
@ -0,0 +1,122 @@
|
||||
// Copyright 2018 Parity Technologies (UK) Ltd.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a
|
||||
// copy of this software and associated documentation files (the "Software"),
|
||||
// to deal in the Software without restriction, including without limitation
|
||||
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
// and/or sell copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
// DEALINGS IN THE SOFTWARE.
|
||||
|
||||
#[macro_use]
|
||||
extern crate libp2p;
|
||||
|
||||
// TODO: doesn't compile
|
||||
/*#[test]
|
||||
fn empty() {
|
||||
#[allow(dead_code)]
|
||||
#[derive(NetworkBehaviour)]
|
||||
struct Foo {}
|
||||
}*/
|
||||
|
||||
#[test]
|
||||
fn one_field() {
|
||||
#[allow(dead_code)]
|
||||
#[derive(NetworkBehaviour)]
|
||||
struct Foo<TSubstream> {
|
||||
ping: libp2p::ping::PeriodicPingBehaviour<TSubstream>,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_fields() {
|
||||
#[allow(dead_code)]
|
||||
#[derive(NetworkBehaviour)]
|
||||
struct Foo<TSubstream> {
|
||||
ping_dialer: libp2p::ping::PeriodicPingBehaviour<TSubstream>,
|
||||
ping_listener: libp2p::ping::PingListenBehaviour<TSubstream>,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_fields() {
|
||||
#[allow(dead_code)]
|
||||
#[derive(NetworkBehaviour)]
|
||||
struct Foo<TSubstream> {
|
||||
ping_dialer: libp2p::ping::PeriodicPingBehaviour<TSubstream>,
|
||||
ping_listener: libp2p::ping::PingListenBehaviour<TSubstream>,
|
||||
identify: libp2p::identify::PeriodicIdentification<TSubstream>,
|
||||
#[behaviour(ignore)]
|
||||
foo: String,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_handler() {
|
||||
#[allow(dead_code)]
|
||||
#[derive(NetworkBehaviour)]
|
||||
// TODO: remove the generics requirements once identify no longer requires them
|
||||
struct Foo<TSubstream: libp2p::tokio_io::AsyncRead + libp2p::tokio_io::AsyncWrite + Send + Sync + 'static> {
|
||||
#[behaviour(handler = "foo")]
|
||||
identify: libp2p::identify::PeriodicIdentifyBehaviour<TSubstream>,
|
||||
}
|
||||
|
||||
impl<TSubstream: libp2p::tokio_io::AsyncRead + libp2p::tokio_io::AsyncWrite + Send + Sync + 'static> Foo<TSubstream> {
|
||||
// TODO: for some reason, the parameter cannot be `PeriodicIdentifyBehaviourEvent` or we
|
||||
// get a compilation error ; figure out why or open an issue to Rust
|
||||
fn foo(&mut self, ev: <libp2p::identify::PeriodicIdentifyBehaviour<TSubstream> as libp2p::core::nodes::NetworkBehavior>::OutEvent) {
|
||||
let libp2p::identify::PeriodicIdentifyBehaviourEvent::Identified { .. } = ev;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_polling() {
|
||||
#[allow(dead_code)]
|
||||
#[derive(NetworkBehaviour)]
|
||||
#[behaviour(poll_method = "foo")]
|
||||
struct Foo<TSubstream> {
|
||||
ping: libp2p::ping::PeriodicPingBehaviour<TSubstream>,
|
||||
identify: libp2p::identify::PeriodicIdentifyBehaviour<TSubstream>,
|
||||
}
|
||||
|
||||
impl<TSubstream> Foo<TSubstream> {
|
||||
fn foo<T>(&mut self) -> libp2p::futures::Async<libp2p::core::nodes::NetworkBehaviorAction<T, ()>> { libp2p::futures::Async::NotReady }
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_event_no_polling() {
|
||||
#[allow(dead_code)]
|
||||
#[derive(NetworkBehaviour)]
|
||||
#[behaviour(out_event = "String")]
|
||||
struct Foo<TSubstream> {
|
||||
ping: libp2p::ping::PeriodicPingBehaviour<TSubstream>,
|
||||
identify: libp2p::identify::PeriodicIdentifyBehaviour<TSubstream>,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_event_and_polling() {
|
||||
#[allow(dead_code)]
|
||||
#[derive(NetworkBehaviour)]
|
||||
#[behaviour(poll_method = "foo", out_event = "String")]
|
||||
struct Foo<TSubstream> {
|
||||
ping: libp2p::ping::PeriodicPingBehaviour<TSubstream>,
|
||||
identify: libp2p::identify::PeriodicIdentifyBehaviour<TSubstream>,
|
||||
}
|
||||
|
||||
impl<TSubstream> Foo<TSubstream> {
|
||||
fn foo<T>(&mut self) -> libp2p::futures::Async<libp2p::core::nodes::NetworkBehaviorAction<T, String>> { libp2p::futures::Async::NotReady }
|
||||
}
|
||||
}
|
@ -137,6 +137,7 @@ pub extern crate multihash;
|
||||
pub extern crate tokio_io;
|
||||
pub extern crate tokio_codec;
|
||||
|
||||
extern crate libp2p_core_derive;
|
||||
extern crate tokio_executor;
|
||||
|
||||
pub extern crate libp2p_core as core;
|
||||
@ -163,6 +164,7 @@ mod transport_ext;
|
||||
|
||||
pub mod simple;
|
||||
|
||||
pub use libp2p_core_derive::NetworkBehaviour;
|
||||
pub use self::core::{Transport, ConnectionUpgrade, PeerId};
|
||||
pub use self::multiaddr::Multiaddr;
|
||||
pub use self::simple::SimpleProtocol;
|
||||
|
Reference in New Issue
Block a user