2018-11-12 17:12:47 +01:00
|
|
|
// 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"]
|
|
|
|
|
2022-08-08 07:18:32 +02:00
|
|
|
use heck::ToUpperCamelCase;
|
2019-02-11 14:58:15 +01:00
|
|
|
use proc_macro::TokenStream;
|
2021-08-11 13:12:12 +02:00
|
|
|
use quote::quote;
|
2022-08-28 10:51:49 +02:00
|
|
|
use syn::{parse_macro_input, Data, DataStruct, DeriveInput};
|
2018-11-12 17:12:47 +01:00
|
|
|
|
2020-01-14 13:48:16 +02:00
|
|
|
/// Generates a delegating `NetworkBehaviour` implementation for the struct this is used for. See
|
|
|
|
/// the trait documentation for better description.
|
2018-11-12 17:12:47 +01:00
|
|
|
#[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),
|
2018-11-16 12:59:57 +01:00
|
|
|
Data::Enum(_) => unimplemented!("Deriving NetworkBehaviour is not implemented for enums"),
|
|
|
|
Data::Union(_) => unimplemented!("Deriving NetworkBehaviour is not implemented for unions"),
|
2018-11-12 17:12:47 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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();
|
2021-08-11 13:12:12 +02:00
|
|
|
let multiaddr = quote! {::libp2p::core::Multiaddr};
|
|
|
|
let trait_to_impl = quote! {::libp2p::swarm::NetworkBehaviour};
|
|
|
|
let either_ident = quote! {::libp2p::core::either::EitherOutput};
|
|
|
|
let network_behaviour_action = quote! {::libp2p::swarm::NetworkBehaviourAction};
|
2022-05-18 02:52:50 -05:00
|
|
|
let into_connection_handler = quote! {::libp2p::swarm::IntoConnectionHandler};
|
|
|
|
let connection_handler = quote! {::libp2p::swarm::ConnectionHandler};
|
2022-02-21 13:32:24 +01:00
|
|
|
let into_proto_select_ident = quote! {::libp2p::swarm::IntoConnectionHandlerSelect};
|
2021-08-11 13:12:12 +02:00
|
|
|
let peer_id = quote! {::libp2p::core::PeerId};
|
|
|
|
let connection_id = quote! {::libp2p::core::connection::ConnectionId};
|
2021-10-14 18:05:07 +02:00
|
|
|
let dial_errors = quote! {Option<&Vec<::libp2p::core::Multiaddr>>};
|
2021-08-11 13:12:12 +02:00
|
|
|
let connected_point = quote! {::libp2p::core::ConnectedPoint};
|
2022-07-04 04:16:57 +02:00
|
|
|
let listener_id = quote! {::libp2p::core::transport::ListenerId};
|
2021-08-31 17:00:51 +02:00
|
|
|
let dial_error = quote! {::libp2p::swarm::DialError};
|
2021-08-11 13:12:12 +02:00
|
|
|
|
|
|
|
let poll_parameters = quote! {::libp2p::swarm::PollParameters};
|
2018-12-01 13:34:57 +01:00
|
|
|
|
2018-11-12 17:12:47 +01:00
|
|
|
// Build the generics.
|
|
|
|
let impl_generics = {
|
|
|
|
let tp = ast.generics.type_params();
|
|
|
|
let lf = ast.generics.lifetimes();
|
|
|
|
let cst = ast.generics.const_params();
|
2021-08-11 13:12:12 +02:00
|
|
|
quote! {<#(#lf,)* #(#tp,)* #(#cst,)*>}
|
2018-11-12 17:12:47 +01:00
|
|
|
};
|
|
|
|
|
2022-08-08 07:18:32 +02:00
|
|
|
let (out_event_name, out_event_definition, out_event_from_clauses) = {
|
|
|
|
// If we find a `#[behaviour(out_event = "Foo")]` attribute on the
|
|
|
|
// struct, we set `Foo` as the out event. If not, the `OutEvent` is
|
|
|
|
// generated.
|
|
|
|
let user_provided_out_event_name: Option<syn::Type> = ast
|
|
|
|
.attrs
|
|
|
|
.iter()
|
|
|
|
.filter_map(get_meta_items)
|
|
|
|
.flatten()
|
|
|
|
.filter_map(|meta_item| {
|
|
|
|
if let syn::NestedMeta::Meta(syn::Meta::NameValue(ref m)) = meta_item {
|
|
|
|
if m.path.is_ident("out_event") {
|
2018-11-12 17:12:47 +01:00
|
|
|
if let syn::Lit::Str(ref s) = m.lit {
|
2022-08-08 07:18:32 +02:00
|
|
|
return Some(syn::parse_str(&s.value()).unwrap());
|
2018-11-12 17:12:47 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-08-08 07:18:32 +02:00
|
|
|
None
|
|
|
|
})
|
|
|
|
.next();
|
|
|
|
|
2022-08-26 07:08:33 +02:00
|
|
|
match user_provided_out_event_name {
|
2022-08-08 07:18:32 +02:00
|
|
|
// User provided `OutEvent`.
|
2022-08-26 07:08:33 +02:00
|
|
|
Some(name) => {
|
2022-08-08 07:18:32 +02:00
|
|
|
let definition = None;
|
2022-08-29 07:39:47 +02:00
|
|
|
let from_clauses = data_struct
|
|
|
|
.fields
|
2022-08-08 07:18:32 +02:00
|
|
|
.iter()
|
|
|
|
.map(|field| {
|
|
|
|
let ty = &field.ty;
|
|
|
|
quote! {#name #ty_generics: From< <#ty as #trait_to_impl>::OutEvent >}
|
|
|
|
})
|
|
|
|
.collect::<Vec<_>>();
|
|
|
|
(name, definition, from_clauses)
|
|
|
|
}
|
|
|
|
// User did not provide `OutEvent`. Generate it.
|
2022-08-26 07:08:33 +02:00
|
|
|
None => {
|
2022-08-08 07:18:32 +02:00
|
|
|
let name: syn::Type = syn::parse_str(&(ast.ident.to_string() + "Event")).unwrap();
|
|
|
|
let definition = {
|
2022-08-29 07:39:47 +02:00
|
|
|
let fields = data_struct
|
|
|
|
.fields
|
2022-08-08 07:18:32 +02:00
|
|
|
.iter()
|
|
|
|
.map(|field| {
|
|
|
|
let variant: syn::Variant = syn::parse_str(
|
|
|
|
&field
|
|
|
|
.ident
|
|
|
|
.clone()
|
|
|
|
.expect(
|
|
|
|
"Fields of NetworkBehaviour implementation to be named.",
|
|
|
|
)
|
|
|
|
.to_string()
|
|
|
|
.to_upper_camel_case(),
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
let ty = &field.ty;
|
|
|
|
quote! {#variant(<#ty as NetworkBehaviour>::OutEvent)}
|
|
|
|
})
|
|
|
|
.collect::<Vec<_>>();
|
|
|
|
let visibility = &ast.vis;
|
|
|
|
|
|
|
|
Some(quote! {
|
2022-08-17 08:40:32 +02:00
|
|
|
#[derive(::std::fmt::Debug)]
|
2022-08-17 06:43:47 +02:00
|
|
|
#visibility enum #name #impl_generics
|
|
|
|
#where_clause
|
|
|
|
{
|
2022-08-08 07:18:32 +02:00
|
|
|
#(#fields),*
|
|
|
|
}
|
|
|
|
})
|
|
|
|
};
|
|
|
|
let from_clauses = vec![];
|
|
|
|
(name, definition, from_clauses)
|
|
|
|
}
|
2018-11-12 17:12:47 +01:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2020-07-08 19:32:47 +10:00
|
|
|
// Build the `where ...` clause of the trait implementation.
|
|
|
|
let where_clause = {
|
2022-08-29 07:39:47 +02:00
|
|
|
let additional = data_struct
|
|
|
|
.fields
|
2021-08-11 13:12:12 +02:00
|
|
|
.iter()
|
2022-08-08 07:18:32 +02:00
|
|
|
.map(|field| {
|
2020-07-08 19:32:47 +10:00
|
|
|
let ty = &field.ty;
|
2022-08-08 07:18:32 +02:00
|
|
|
quote! {#ty: #trait_to_impl}
|
2020-07-08 19:32:47 +10:00
|
|
|
})
|
2022-08-08 07:18:32 +02:00
|
|
|
.chain(out_event_from_clauses)
|
2020-07-08 19:32:47 +10:00
|
|
|
.collect::<Vec<_>>();
|
|
|
|
|
|
|
|
if let Some(where_clause) = where_clause {
|
|
|
|
if where_clause.predicates.trailing_punct() {
|
2022-08-08 07:18:32 +02:00
|
|
|
Some(quote! {#where_clause #(#additional),* })
|
2020-07-08 19:32:47 +10:00
|
|
|
} else {
|
2021-08-11 13:12:12 +02:00
|
|
|
Some(quote! {#where_clause, #(#additional),*})
|
2020-07-08 19:32:47 +10:00
|
|
|
}
|
|
|
|
} else {
|
2021-08-11 13:12:12 +02:00
|
|
|
Some(quote! {where #(#additional),*})
|
2020-07-08 19:32:47 +10:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2019-01-26 23:57:53 +01:00
|
|
|
// Build the list of statements to put in the body of `addresses_of_peer()`.
|
|
|
|
let addresses_of_peer_stmts = {
|
2022-08-29 07:39:47 +02:00
|
|
|
data_struct
|
|
|
|
.fields
|
2021-08-11 13:12:12 +02:00
|
|
|
.iter()
|
|
|
|
.enumerate()
|
2022-03-18 11:37:00 -04:00
|
|
|
.map(move |(field_n, field)| match field.ident {
|
|
|
|
Some(ref i) => quote! { out.extend(self.#i.addresses_of_peer(peer_id)); },
|
|
|
|
None => quote! { out.extend(self.#field_n.addresses_of_peer(peer_id)); },
|
2019-01-26 23:57:53 +01:00
|
|
|
})
|
|
|
|
};
|
|
|
|
|
2020-03-31 15:41:13 +02:00
|
|
|
// Build the list of statements to put in the body of `inject_connection_established()`.
|
|
|
|
let inject_connection_established_stmts = {
|
2022-08-29 07:39:47 +02:00
|
|
|
data_struct.fields.iter().enumerate().map(move |(field_n, field)| {
|
2022-03-18 11:37:00 -04:00
|
|
|
match field.ident {
|
2022-02-09 10:08:28 -05:00
|
|
|
Some(ref i) => quote!{ self.#i.inject_connection_established(peer_id, connection_id, endpoint, errors, other_established); },
|
|
|
|
None => quote!{ self.#field_n.inject_connection_established(peer_id, connection_id, endpoint, errors, other_established); },
|
2022-03-18 11:37:00 -04:00
|
|
|
}
|
2020-03-31 15:41:13 +02:00
|
|
|
})
|
|
|
|
};
|
|
|
|
|
2020-06-30 17:10:53 +02:00
|
|
|
// Build the list of statements to put in the body of `inject_address_change()`.
|
|
|
|
let inject_address_change_stmts = {
|
2022-08-29 07:39:47 +02:00
|
|
|
data_struct.fields.iter().enumerate().map(move |(field_n, field)| {
|
2022-03-18 11:37:00 -04:00
|
|
|
match field.ident {
|
2020-06-30 17:10:53 +02:00
|
|
|
Some(ref i) => quote!{ self.#i.inject_address_change(peer_id, connection_id, old, new); },
|
|
|
|
None => quote!{ self.#field_n.inject_address_change(peer_id, connection_id, old, new); },
|
2022-03-18 11:37:00 -04:00
|
|
|
}
|
2020-06-30 17:10:53 +02:00
|
|
|
})
|
|
|
|
};
|
|
|
|
|
2020-03-31 15:41:13 +02:00
|
|
|
// Build the list of statements to put in the body of `inject_connection_closed()`.
|
|
|
|
let inject_connection_closed_stmts = {
|
2022-08-29 07:39:47 +02:00
|
|
|
data_struct.fields
|
2021-08-31 17:00:51 +02:00
|
|
|
.iter()
|
|
|
|
.enumerate()
|
|
|
|
// The outmost handler belongs to the last behaviour.
|
|
|
|
.rev()
|
|
|
|
.enumerate()
|
|
|
|
.map(move |(enum_n, (field_n, field))| {
|
|
|
|
let handler = if field_n == 0 {
|
|
|
|
// Given that the iterator is reversed, this is the innermost handler only.
|
|
|
|
quote! { let handler = handlers }
|
|
|
|
} else {
|
|
|
|
quote! {
|
|
|
|
let (handlers, handler) = handlers.into_inner()
|
|
|
|
}
|
|
|
|
};
|
|
|
|
let inject = match field.ident {
|
2022-02-09 10:08:28 -05:00
|
|
|
Some(ref i) => quote!{ self.#i.inject_connection_closed(peer_id, connection_id, endpoint, handler, remaining_established) },
|
|
|
|
None => quote!{ self.#enum_n.inject_connection_closed(peer_id, connection_id, endpoint, handler, remaining_established) },
|
2021-08-31 17:00:51 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
quote! {
|
|
|
|
#handler;
|
|
|
|
#inject;
|
|
|
|
}
|
2018-11-12 17:12:47 +01:00
|
|
|
})
|
|
|
|
};
|
|
|
|
|
2019-01-30 14:55:39 +01:00
|
|
|
// Build the list of statements to put in the body of `inject_dial_failure()`.
|
|
|
|
let inject_dial_failure_stmts = {
|
2022-08-29 07:39:47 +02:00
|
|
|
data_struct
|
|
|
|
.fields
|
2021-08-11 13:12:12 +02:00
|
|
|
.iter()
|
|
|
|
.enumerate()
|
2021-08-31 17:00:51 +02:00
|
|
|
// The outmost handler belongs to the last behaviour.
|
|
|
|
.rev()
|
|
|
|
.enumerate()
|
|
|
|
.map(move |(enum_n, (field_n, field))| {
|
|
|
|
let handler = if field_n == 0 {
|
|
|
|
// Given that the iterator is reversed, this is the innermost handler only.
|
|
|
|
quote! { let handler = handlers }
|
|
|
|
} else {
|
|
|
|
quote! {
|
|
|
|
let (handlers, handler) = handlers.into_inner()
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let inject = match field.ident {
|
|
|
|
Some(ref i) => {
|
2021-11-18 13:21:12 +01:00
|
|
|
quote! { self.#i.inject_dial_failure(peer_id, handler, error) }
|
2021-08-31 17:00:51 +02:00
|
|
|
}
|
|
|
|
None => {
|
2021-11-18 13:21:12 +01:00
|
|
|
quote! { self.#enum_n.inject_dial_failure(peer_id, handler, error) }
|
2021-08-31 17:00:51 +02:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
quote! {
|
|
|
|
#handler;
|
|
|
|
#inject;
|
2021-08-11 13:12:12 +02:00
|
|
|
}
|
2021-08-31 17:00:51 +02:00
|
|
|
})
|
|
|
|
};
|
2019-01-30 14:55:39 +01:00
|
|
|
|
2021-08-31 17:00:51 +02:00
|
|
|
// Build the list of statements to put in the body of `inject_listen_failure()`.
|
|
|
|
let inject_listen_failure_stmts = {
|
2022-08-29 07:39:47 +02:00
|
|
|
data_struct.fields
|
2021-08-31 17:00:51 +02:00
|
|
|
.iter()
|
|
|
|
.enumerate()
|
|
|
|
.rev()
|
|
|
|
.enumerate()
|
|
|
|
.map(move |(enum_n, (field_n, field))| {
|
|
|
|
let handler = if field_n == 0 {
|
|
|
|
quote! { let handler = handlers }
|
|
|
|
} else {
|
|
|
|
quote! {
|
|
|
|
let (handlers, handler) = handlers.into_inner()
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let inject = match field.ident {
|
|
|
|
Some(ref i) => quote! { self.#i.inject_listen_failure(local_addr, send_back_addr, handler) },
|
|
|
|
None => quote! { self.#enum_n.inject_listen_failure(local_addr, send_back_addr, handler) },
|
|
|
|
};
|
|
|
|
|
|
|
|
quote! {
|
|
|
|
#handler;
|
|
|
|
#inject;
|
|
|
|
}
|
2019-01-30 14:55:39 +01:00
|
|
|
})
|
|
|
|
};
|
|
|
|
|
2021-03-24 17:21:53 +01:00
|
|
|
// Build the list of statements to put in the body of `inject_new_listener()`.
|
|
|
|
let inject_new_listener_stmts = {
|
2022-08-29 07:39:47 +02:00
|
|
|
data_struct
|
|
|
|
.fields
|
2021-08-11 13:12:12 +02:00
|
|
|
.iter()
|
|
|
|
.enumerate()
|
2022-03-18 11:37:00 -04:00
|
|
|
.map(move |(field_n, field)| match field.ident {
|
|
|
|
Some(ref i) => quote! { self.#i.inject_new_listener(id); },
|
|
|
|
None => quote! { self.#field_n.inject_new_listener(id); },
|
2021-03-24 17:21:53 +01:00
|
|
|
})
|
|
|
|
};
|
|
|
|
|
2019-04-16 15:36:08 +02:00
|
|
|
// Build the list of statements to put in the body of `inject_new_listen_addr()`.
|
|
|
|
let inject_new_listen_addr_stmts = {
|
2022-08-29 07:39:47 +02:00
|
|
|
data_struct
|
|
|
|
.fields
|
2021-08-11 13:12:12 +02:00
|
|
|
.iter()
|
|
|
|
.enumerate()
|
2022-03-18 11:37:00 -04:00
|
|
|
.map(move |(field_n, field)| match field.ident {
|
|
|
|
Some(ref i) => quote! { self.#i.inject_new_listen_addr(id, addr); },
|
|
|
|
None => quote! { self.#field_n.inject_new_listen_addr(id, addr); },
|
2019-04-16 15:36:08 +02:00
|
|
|
})
|
|
|
|
};
|
|
|
|
|
|
|
|
// Build the list of statements to put in the body of `inject_expired_listen_addr()`.
|
|
|
|
let inject_expired_listen_addr_stmts = {
|
2022-08-29 07:39:47 +02:00
|
|
|
data_struct
|
|
|
|
.fields
|
2021-08-11 13:12:12 +02:00
|
|
|
.iter()
|
|
|
|
.enumerate()
|
2022-03-18 11:37:00 -04:00
|
|
|
.map(move |(field_n, field)| match field.ident {
|
|
|
|
Some(ref i) => quote! { self.#i.inject_expired_listen_addr(id, addr); },
|
|
|
|
None => quote! { self.#field_n.inject_expired_listen_addr(id, addr); },
|
2019-04-16 15:36:08 +02:00
|
|
|
})
|
|
|
|
};
|
|
|
|
|
2019-04-16 17:00:20 +02:00
|
|
|
// Build the list of statements to put in the body of `inject_new_external_addr()`.
|
|
|
|
let inject_new_external_addr_stmts = {
|
2022-08-29 07:39:47 +02:00
|
|
|
data_struct
|
|
|
|
.fields
|
2021-08-11 13:12:12 +02:00
|
|
|
.iter()
|
|
|
|
.enumerate()
|
2022-03-18 11:37:00 -04:00
|
|
|
.map(move |(field_n, field)| match field.ident {
|
|
|
|
Some(ref i) => quote! { self.#i.inject_new_external_addr(addr); },
|
|
|
|
None => quote! { self.#field_n.inject_new_external_addr(addr); },
|
2019-04-16 17:00:20 +02:00
|
|
|
})
|
|
|
|
};
|
|
|
|
|
2021-03-24 17:21:53 +01:00
|
|
|
// Build the list of statements to put in the body of `inject_expired_external_addr()`.
|
|
|
|
let inject_expired_external_addr_stmts = {
|
2022-08-29 07:39:47 +02:00
|
|
|
data_struct
|
|
|
|
.fields
|
2021-08-11 13:12:12 +02:00
|
|
|
.iter()
|
|
|
|
.enumerate()
|
2022-03-18 11:37:00 -04:00
|
|
|
.map(move |(field_n, field)| match field.ident {
|
|
|
|
Some(ref i) => quote! { self.#i.inject_expired_external_addr(addr); },
|
|
|
|
None => quote! { self.#field_n.inject_expired_external_addr(addr); },
|
2021-03-24 17:21:53 +01:00
|
|
|
})
|
|
|
|
};
|
|
|
|
|
2019-08-13 15:41:12 +02:00
|
|
|
// Build the list of statements to put in the body of `inject_listener_error()`.
|
|
|
|
let inject_listener_error_stmts = {
|
2022-08-29 07:39:47 +02:00
|
|
|
data_struct
|
|
|
|
.fields
|
2021-08-11 13:12:12 +02:00
|
|
|
.iter()
|
|
|
|
.enumerate()
|
2022-03-18 11:37:00 -04:00
|
|
|
.map(move |(field_n, field)| match field.ident {
|
|
|
|
Some(ref i) => quote!(self.#i.inject_listener_error(id, err);),
|
|
|
|
None => quote!(self.#field_n.inject_listener_error(id, err);),
|
2019-08-13 15:41:12 +02:00
|
|
|
})
|
|
|
|
};
|
|
|
|
|
|
|
|
// Build the list of statements to put in the body of `inject_listener_closed()`.
|
|
|
|
let inject_listener_closed_stmts = {
|
2022-08-29 07:39:47 +02:00
|
|
|
data_struct
|
|
|
|
.fields
|
2021-08-11 13:12:12 +02:00
|
|
|
.iter()
|
|
|
|
.enumerate()
|
2022-03-18 11:37:00 -04:00
|
|
|
.map(move |(field_n, field)| match field.ident {
|
|
|
|
Some(ref i) => quote!(self.#i.inject_listener_closed(id, reason);),
|
|
|
|
None => quote!(self.#field_n.inject_listener_closed(id, reason);),
|
2019-08-13 15:41:12 +02:00
|
|
|
})
|
|
|
|
};
|
|
|
|
|
Multiple connections per peer (#1440)
* Allow multiple connections per peer in libp2p-core.
Instead of trying to enforce a single connection per peer,
which involves quite a bit of additional complexity e.g.
to prioritise simultaneously opened connections and can
have other undesirable consequences [1], we now
make multiple connections per peer a feature.
The gist of these changes is as follows:
The concept of a "node" with an implicit 1-1 correspondence
to a connection has been replaced with the "first-class"
concept of a "connection". The code from `src/nodes` has moved
(with varying degrees of modification) to `src/connection`.
A `HandledNode` has become a `Connection`, a `NodeHandler` a
`ConnectionHandler`, the `CollectionStream` was the basis for
the new `connection::Pool`, and so forth.
Conceptually, a `Network` contains a `connection::Pool` which
in turn internally employs the `connection::Manager` for
handling the background `connection::manager::Task`s, one
per connection, as before. These are all considered implementation
details. On the public API, `Peer`s are managed as before through
the `Network`, except now the API has changed with the shift of focus
to (potentially multiple) connections per peer. The `NetworkEvent`s have
accordingly also undergone changes.
The Swarm APIs remain largely unchanged, except for the fact that
`inject_replaced` is no longer called. It may now practically happen
that multiple `ProtocolsHandler`s are associated with a single
`NetworkBehaviour`, one per connection. If implementations of
`NetworkBehaviour` rely somehow on communicating with exactly
one `ProtocolsHandler`, this may cause issues, but it is unlikely.
[1]: https://github.com/paritytech/substrate/issues/4272
* Fix intra-rustdoc links.
* Update core/src/connection/pool.rs
Co-Authored-By: Max Inden <mail@max-inden.de>
* Address some review feedback and fix doc links.
* Allow responses to be sent on the same connection.
* Remove unnecessary remainders of inject_replaced.
* Update swarm/src/behaviour.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update swarm/src/lib.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/manager.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/manager.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/pool.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Incorporate more review feedback.
* Move module declaration below imports.
* Update core/src/connection/manager.rs
Co-Authored-By: Toralf Wittner <tw@dtex.org>
* Update core/src/connection/manager.rs
Co-Authored-By: Toralf Wittner <tw@dtex.org>
* Simplify as per review.
* Fix rustoc link.
* Add try_notify_handler and simplify.
* Relocate DialingConnection and DialingAttempt.
For better visibility constraints.
* Small cleanup.
* Small cleanup. More robust EstablishedConnectionIter.
* Clarify semantics of `DialingPeer::connect`.
* Don't call inject_disconnected on InvalidPeerId.
To preserve the previous behavior and ensure calls to
`inject_disconnected` are always paired with calls to
`inject_connected`.
* Provide public ConnectionId constructor.
Mainly needed for testing purposes, e.g. in substrate.
* Move the established connection limit check to the right place.
* Clean up connection error handling.
Separate connection errors into those occuring during
connection setup or upon rejecting a newly established
connection (the `PendingConnectionError`) and those
errors occurring on previously established connections,
i.e. for which a `ConnectionEstablished` event has
been emitted by the connection pool earlier.
* Revert change in log level and clarify an invariant.
* Remove inject_replaced entirely.
* Allow notifying all connection handlers.
Thereby simplify by introducing a new enum `NotifyHandler`,
used with a single constructor `NetworkBehaviourAction::NotifyHandler`.
* Finishing touches.
Small API simplifications and code deduplication.
Some more useful debug logging.
Co-authored-by: Max Inden <mail@max-inden.de>
Co-authored-by: Pierre Krieger <pierre.krieger1708@gmail.com>
Co-authored-by: Toralf Wittner <tw@dtex.org>
2020-03-04 13:49:25 +01:00
|
|
|
// Build the list of variants to put in the body of `inject_event()`.
|
2018-11-12 17:12:47 +01:00
|
|
|
//
|
|
|
|
// The event type is a construction of nested `#either_ident`s of the events of the children.
|
Multiple connections per peer (#1440)
* Allow multiple connections per peer in libp2p-core.
Instead of trying to enforce a single connection per peer,
which involves quite a bit of additional complexity e.g.
to prioritise simultaneously opened connections and can
have other undesirable consequences [1], we now
make multiple connections per peer a feature.
The gist of these changes is as follows:
The concept of a "node" with an implicit 1-1 correspondence
to a connection has been replaced with the "first-class"
concept of a "connection". The code from `src/nodes` has moved
(with varying degrees of modification) to `src/connection`.
A `HandledNode` has become a `Connection`, a `NodeHandler` a
`ConnectionHandler`, the `CollectionStream` was the basis for
the new `connection::Pool`, and so forth.
Conceptually, a `Network` contains a `connection::Pool` which
in turn internally employs the `connection::Manager` for
handling the background `connection::manager::Task`s, one
per connection, as before. These are all considered implementation
details. On the public API, `Peer`s are managed as before through
the `Network`, except now the API has changed with the shift of focus
to (potentially multiple) connections per peer. The `NetworkEvent`s have
accordingly also undergone changes.
The Swarm APIs remain largely unchanged, except for the fact that
`inject_replaced` is no longer called. It may now practically happen
that multiple `ProtocolsHandler`s are associated with a single
`NetworkBehaviour`, one per connection. If implementations of
`NetworkBehaviour` rely somehow on communicating with exactly
one `ProtocolsHandler`, this may cause issues, but it is unlikely.
[1]: https://github.com/paritytech/substrate/issues/4272
* Fix intra-rustdoc links.
* Update core/src/connection/pool.rs
Co-Authored-By: Max Inden <mail@max-inden.de>
* Address some review feedback and fix doc links.
* Allow responses to be sent on the same connection.
* Remove unnecessary remainders of inject_replaced.
* Update swarm/src/behaviour.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update swarm/src/lib.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/manager.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/manager.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/pool.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Incorporate more review feedback.
* Move module declaration below imports.
* Update core/src/connection/manager.rs
Co-Authored-By: Toralf Wittner <tw@dtex.org>
* Update core/src/connection/manager.rs
Co-Authored-By: Toralf Wittner <tw@dtex.org>
* Simplify as per review.
* Fix rustoc link.
* Add try_notify_handler and simplify.
* Relocate DialingConnection and DialingAttempt.
For better visibility constraints.
* Small cleanup.
* Small cleanup. More robust EstablishedConnectionIter.
* Clarify semantics of `DialingPeer::connect`.
* Don't call inject_disconnected on InvalidPeerId.
To preserve the previous behavior and ensure calls to
`inject_disconnected` are always paired with calls to
`inject_connected`.
* Provide public ConnectionId constructor.
Mainly needed for testing purposes, e.g. in substrate.
* Move the established connection limit check to the right place.
* Clean up connection error handling.
Separate connection errors into those occuring during
connection setup or upon rejecting a newly established
connection (the `PendingConnectionError`) and those
errors occurring on previously established connections,
i.e. for which a `ConnectionEstablished` event has
been emitted by the connection pool earlier.
* Revert change in log level and clarify an invariant.
* Remove inject_replaced entirely.
* Allow notifying all connection handlers.
Thereby simplify by introducing a new enum `NotifyHandler`,
used with a single constructor `NetworkBehaviourAction::NotifyHandler`.
* Finishing touches.
Small API simplifications and code deduplication.
Some more useful debug logging.
Co-authored-by: Max Inden <mail@max-inden.de>
Co-authored-by: Pierre Krieger <pierre.krieger1708@gmail.com>
Co-authored-by: Toralf Wittner <tw@dtex.org>
2020-03-04 13:49:25 +01:00
|
|
|
// We call `inject_event` on the corresponding child.
|
2022-08-29 07:39:47 +02:00
|
|
|
let inject_node_event_stmts = data_struct.fields.iter().enumerate().enumerate().map(|(enum_n, (field_n, field))| {
|
2018-11-12 17:12:47 +01:00
|
|
|
let mut elem = if enum_n != 0 {
|
|
|
|
quote!{ #either_ident::Second(ev) }
|
|
|
|
} else {
|
|
|
|
quote!{ ev }
|
|
|
|
};
|
|
|
|
|
2022-08-29 07:39:47 +02:00
|
|
|
for _ in 0 .. data_struct.fields.len() - 1 - enum_n {
|
2018-11-12 17:12:47 +01:00
|
|
|
elem = quote!{ #either_ident::First(#elem) };
|
|
|
|
}
|
|
|
|
|
|
|
|
Some(match field.ident {
|
2020-04-10 00:01:26 +10:00
|
|
|
Some(ref i) => quote!{ #elem => #trait_to_impl::inject_event(&mut self.#i, peer_id, connection_id, ev) },
|
|
|
|
None => quote!{ #elem => #trait_to_impl::inject_event(&mut self.#field_n, peer_id, connection_id, ev) },
|
2018-11-12 17:12:47 +01:00
|
|
|
})
|
|
|
|
});
|
|
|
|
|
2022-02-21 13:32:24 +01:00
|
|
|
// The [`ConnectionHandler`] associated type.
|
2022-05-18 02:52:50 -05:00
|
|
|
let connection_handler_ty = {
|
2018-11-12 17:12:47 +01:00
|
|
|
let mut ph_ty = None;
|
2022-08-29 07:39:47 +02:00
|
|
|
for field in data_struct.fields.iter() {
|
2018-11-12 17:12:47 +01:00
|
|
|
let ty = &field.ty;
|
2022-02-21 13:32:24 +01:00
|
|
|
let field_info = quote! { <#ty as #trait_to_impl>::ConnectionHandler };
|
2018-11-12 17:12:47 +01:00
|
|
|
match ph_ty {
|
2021-08-11 13:12:12 +02:00
|
|
|
Some(ev) => ph_ty = Some(quote! { #into_proto_select_ident<#ev, #field_info> }),
|
2018-11-12 17:12:47 +01:00
|
|
|
ref mut ev @ None => *ev = Some(field_info),
|
|
|
|
}
|
|
|
|
}
|
2021-08-31 17:00:51 +02:00
|
|
|
// ph_ty = Some(quote! )
|
2021-08-11 13:12:12 +02:00
|
|
|
ph_ty.unwrap_or(quote! {()}) // TODO: `!` instead
|
2018-11-12 17:12:47 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
// The content of `new_handler()`.
|
|
|
|
// Example output: `self.field1.select(self.field2.select(self.field3))`.
|
|
|
|
let new_handler = {
|
|
|
|
let mut out_handler = None;
|
|
|
|
|
2022-08-29 07:39:47 +02:00
|
|
|
for (field_n, field) in data_struct.fields.iter().enumerate() {
|
2018-11-12 17:12:47 +01:00
|
|
|
let field_name = match field.ident {
|
2021-08-11 13:12:12 +02:00
|
|
|
Some(ref i) => quote! { self.#i },
|
|
|
|
None => quote! { self.#field_n },
|
2018-11-12 17:12:47 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
let builder = quote! {
|
|
|
|
#field_name.new_handler()
|
|
|
|
};
|
|
|
|
|
|
|
|
match out_handler {
|
2021-08-11 13:12:12 +02:00
|
|
|
Some(h) => {
|
2022-05-18 02:52:50 -05:00
|
|
|
out_handler = Some(quote! { #into_connection_handler::select(#h, #builder) })
|
2021-08-11 13:12:12 +02:00
|
|
|
}
|
2018-11-12 17:12:47 +01:00
|
|
|
ref mut h @ None => *h = Some(builder),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-31 17:00:51 +02:00
|
|
|
out_handler.unwrap_or(quote! {()}) // TODO: See test `empty`.
|
2018-11-12 17:12:47 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
// List of statements to put in `poll()`.
|
|
|
|
//
|
|
|
|
// We poll each child one by one and wrap around the output.
|
2022-08-29 07:39:47 +02:00
|
|
|
let poll_stmts = data_struct.fields.iter().enumerate().map(|(field_n, field)| {
|
2022-08-08 07:18:32 +02:00
|
|
|
let field = field
|
|
|
|
.ident
|
|
|
|
.clone()
|
|
|
|
.expect("Fields of NetworkBehaviour implementation to be named.");
|
2018-11-12 17:12:47 +01:00
|
|
|
|
2022-08-08 07:18:32 +02:00
|
|
|
let mut wrapped_event = if field_n != 0 {
|
2018-11-12 17:12:47 +01:00
|
|
|
quote!{ #either_ident::Second(event) }
|
|
|
|
} else {
|
|
|
|
quote!{ event }
|
|
|
|
};
|
2022-08-29 07:39:47 +02:00
|
|
|
for _ in 0 .. data_struct.fields.len() - 1 - field_n {
|
2018-11-12 17:12:47 +01:00
|
|
|
wrapped_event = quote!{ #either_ident::First(#wrapped_event) };
|
|
|
|
}
|
|
|
|
|
2021-11-15 14:17:23 +01:00
|
|
|
// `Dial` provides a handler of the specific behaviour triggering the
|
|
|
|
// event. Though in order for the final handler to be able to handle
|
|
|
|
// protocols of all behaviours, the provided handler needs to be
|
|
|
|
// combined with handlers of all other behaviours.
|
2021-08-31 17:00:51 +02:00
|
|
|
let provided_handler_and_new_handlers = {
|
|
|
|
let mut out_handler = None;
|
|
|
|
|
2022-08-29 07:39:47 +02:00
|
|
|
for (f_n, f) in data_struct.fields.iter().enumerate() {
|
2021-08-31 17:00:51 +02:00
|
|
|
let f_name = match f.ident {
|
|
|
|
Some(ref i) => quote! { self.#i },
|
|
|
|
None => quote! { self.#f_n },
|
|
|
|
};
|
|
|
|
|
|
|
|
let builder = if field_n == f_n {
|
|
|
|
// The behaviour that triggered the event. Thus, instead of
|
|
|
|
// creating a new handler, use the provided handler.
|
|
|
|
quote! { provided_handler }
|
|
|
|
} else {
|
|
|
|
quote! { #f_name.new_handler() }
|
|
|
|
};
|
|
|
|
|
|
|
|
match out_handler {
|
|
|
|
Some(h) => {
|
2022-05-18 02:52:50 -05:00
|
|
|
out_handler = Some(quote! { #into_connection_handler::select(#h, #builder) })
|
2021-08-31 17:00:51 +02:00
|
|
|
}
|
|
|
|
ref mut h @ None => *h = Some(builder),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
out_handler.unwrap_or(quote! {()}) // TODO: See test `empty`.
|
|
|
|
};
|
|
|
|
|
2022-08-26 07:08:33 +02:00
|
|
|
let generate_event_match_arm = {
|
2022-08-08 07:18:32 +02:00
|
|
|
// If the `NetworkBehaviour`'s `OutEvent` is generated by the derive macro, wrap the sub
|
|
|
|
// `NetworkBehaviour` `OutEvent` in the variant of the generated `OutEvent`. If the
|
|
|
|
// `NetworkBehaviour`'s `OutEvent` is provided by the user, use the corresponding `From`
|
|
|
|
// implementation.
|
|
|
|
let into_out_event = if out_event_definition.is_some() {
|
|
|
|
let event_variant: syn::Variant = syn::parse_str(
|
|
|
|
&field
|
|
|
|
.to_string()
|
|
|
|
.to_upper_camel_case()
|
|
|
|
).unwrap();
|
|
|
|
quote! { #out_event_name::#event_variant(event) }
|
|
|
|
} else {
|
|
|
|
quote! { event.into() }
|
|
|
|
};
|
|
|
|
|
2020-07-08 19:32:47 +10:00
|
|
|
quote! {
|
|
|
|
std::task::Poll::Ready(#network_behaviour_action::GenerateEvent(event)) => {
|
2022-08-08 07:18:32 +02:00
|
|
|
return std::task::Poll::Ready(#network_behaviour_action::GenerateEvent(#into_out_event))
|
2020-07-08 19:32:47 +10:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2018-11-12 17:12:47 +01:00
|
|
|
Some(quote!{
|
|
|
|
loop {
|
2022-08-08 07:18:32 +02:00
|
|
|
match #trait_to_impl::poll(&mut self.#field, cx, poll_params) {
|
2020-07-08 19:32:47 +10:00
|
|
|
#generate_event_match_arm
|
2021-11-15 14:17:23 +01:00
|
|
|
std::task::Poll::Ready(#network_behaviour_action::Dial { opts, handler: provided_handler }) => {
|
|
|
|
return std::task::Poll::Ready(#network_behaviour_action::Dial { opts, handler: #provided_handler_and_new_handlers });
|
2018-11-12 17:12:47 +01:00
|
|
|
}
|
Multiple connections per peer (#1440)
* Allow multiple connections per peer in libp2p-core.
Instead of trying to enforce a single connection per peer,
which involves quite a bit of additional complexity e.g.
to prioritise simultaneously opened connections and can
have other undesirable consequences [1], we now
make multiple connections per peer a feature.
The gist of these changes is as follows:
The concept of a "node" with an implicit 1-1 correspondence
to a connection has been replaced with the "first-class"
concept of a "connection". The code from `src/nodes` has moved
(with varying degrees of modification) to `src/connection`.
A `HandledNode` has become a `Connection`, a `NodeHandler` a
`ConnectionHandler`, the `CollectionStream` was the basis for
the new `connection::Pool`, and so forth.
Conceptually, a `Network` contains a `connection::Pool` which
in turn internally employs the `connection::Manager` for
handling the background `connection::manager::Task`s, one
per connection, as before. These are all considered implementation
details. On the public API, `Peer`s are managed as before through
the `Network`, except now the API has changed with the shift of focus
to (potentially multiple) connections per peer. The `NetworkEvent`s have
accordingly also undergone changes.
The Swarm APIs remain largely unchanged, except for the fact that
`inject_replaced` is no longer called. It may now practically happen
that multiple `ProtocolsHandler`s are associated with a single
`NetworkBehaviour`, one per connection. If implementations of
`NetworkBehaviour` rely somehow on communicating with exactly
one `ProtocolsHandler`, this may cause issues, but it is unlikely.
[1]: https://github.com/paritytech/substrate/issues/4272
* Fix intra-rustdoc links.
* Update core/src/connection/pool.rs
Co-Authored-By: Max Inden <mail@max-inden.de>
* Address some review feedback and fix doc links.
* Allow responses to be sent on the same connection.
* Remove unnecessary remainders of inject_replaced.
* Update swarm/src/behaviour.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update swarm/src/lib.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/manager.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/manager.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/pool.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Incorporate more review feedback.
* Move module declaration below imports.
* Update core/src/connection/manager.rs
Co-Authored-By: Toralf Wittner <tw@dtex.org>
* Update core/src/connection/manager.rs
Co-Authored-By: Toralf Wittner <tw@dtex.org>
* Simplify as per review.
* Fix rustoc link.
* Add try_notify_handler and simplify.
* Relocate DialingConnection and DialingAttempt.
For better visibility constraints.
* Small cleanup.
* Small cleanup. More robust EstablishedConnectionIter.
* Clarify semantics of `DialingPeer::connect`.
* Don't call inject_disconnected on InvalidPeerId.
To preserve the previous behavior and ensure calls to
`inject_disconnected` are always paired with calls to
`inject_connected`.
* Provide public ConnectionId constructor.
Mainly needed for testing purposes, e.g. in substrate.
* Move the established connection limit check to the right place.
* Clean up connection error handling.
Separate connection errors into those occuring during
connection setup or upon rejecting a newly established
connection (the `PendingConnectionError`) and those
errors occurring on previously established connections,
i.e. for which a `ConnectionEstablished` event has
been emitted by the connection pool earlier.
* Revert change in log level and clarify an invariant.
* Remove inject_replaced entirely.
* Allow notifying all connection handlers.
Thereby simplify by introducing a new enum `NotifyHandler`,
used with a single constructor `NetworkBehaviourAction::NotifyHandler`.
* Finishing touches.
Small API simplifications and code deduplication.
Some more useful debug logging.
Co-authored-by: Max Inden <mail@max-inden.de>
Co-authored-by: Pierre Krieger <pierre.krieger1708@gmail.com>
Co-authored-by: Toralf Wittner <tw@dtex.org>
2020-03-04 13:49:25 +01:00
|
|
|
std::task::Poll::Ready(#network_behaviour_action::NotifyHandler { peer_id, handler, event }) => {
|
|
|
|
return std::task::Poll::Ready(#network_behaviour_action::NotifyHandler {
|
2018-11-12 17:12:47 +01:00
|
|
|
peer_id,
|
Multiple connections per peer (#1440)
* Allow multiple connections per peer in libp2p-core.
Instead of trying to enforce a single connection per peer,
which involves quite a bit of additional complexity e.g.
to prioritise simultaneously opened connections and can
have other undesirable consequences [1], we now
make multiple connections per peer a feature.
The gist of these changes is as follows:
The concept of a "node" with an implicit 1-1 correspondence
to a connection has been replaced with the "first-class"
concept of a "connection". The code from `src/nodes` has moved
(with varying degrees of modification) to `src/connection`.
A `HandledNode` has become a `Connection`, a `NodeHandler` a
`ConnectionHandler`, the `CollectionStream` was the basis for
the new `connection::Pool`, and so forth.
Conceptually, a `Network` contains a `connection::Pool` which
in turn internally employs the `connection::Manager` for
handling the background `connection::manager::Task`s, one
per connection, as before. These are all considered implementation
details. On the public API, `Peer`s are managed as before through
the `Network`, except now the API has changed with the shift of focus
to (potentially multiple) connections per peer. The `NetworkEvent`s have
accordingly also undergone changes.
The Swarm APIs remain largely unchanged, except for the fact that
`inject_replaced` is no longer called. It may now practically happen
that multiple `ProtocolsHandler`s are associated with a single
`NetworkBehaviour`, one per connection. If implementations of
`NetworkBehaviour` rely somehow on communicating with exactly
one `ProtocolsHandler`, this may cause issues, but it is unlikely.
[1]: https://github.com/paritytech/substrate/issues/4272
* Fix intra-rustdoc links.
* Update core/src/connection/pool.rs
Co-Authored-By: Max Inden <mail@max-inden.de>
* Address some review feedback and fix doc links.
* Allow responses to be sent on the same connection.
* Remove unnecessary remainders of inject_replaced.
* Update swarm/src/behaviour.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update swarm/src/lib.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/manager.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/manager.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/pool.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Incorporate more review feedback.
* Move module declaration below imports.
* Update core/src/connection/manager.rs
Co-Authored-By: Toralf Wittner <tw@dtex.org>
* Update core/src/connection/manager.rs
Co-Authored-By: Toralf Wittner <tw@dtex.org>
* Simplify as per review.
* Fix rustoc link.
* Add try_notify_handler and simplify.
* Relocate DialingConnection and DialingAttempt.
For better visibility constraints.
* Small cleanup.
* Small cleanup. More robust EstablishedConnectionIter.
* Clarify semantics of `DialingPeer::connect`.
* Don't call inject_disconnected on InvalidPeerId.
To preserve the previous behavior and ensure calls to
`inject_disconnected` are always paired with calls to
`inject_connected`.
* Provide public ConnectionId constructor.
Mainly needed for testing purposes, e.g. in substrate.
* Move the established connection limit check to the right place.
* Clean up connection error handling.
Separate connection errors into those occuring during
connection setup or upon rejecting a newly established
connection (the `PendingConnectionError`) and those
errors occurring on previously established connections,
i.e. for which a `ConnectionEstablished` event has
been emitted by the connection pool earlier.
* Revert change in log level and clarify an invariant.
* Remove inject_replaced entirely.
* Allow notifying all connection handlers.
Thereby simplify by introducing a new enum `NotifyHandler`,
used with a single constructor `NetworkBehaviourAction::NotifyHandler`.
* Finishing touches.
Small API simplifications and code deduplication.
Some more useful debug logging.
Co-authored-by: Max Inden <mail@max-inden.de>
Co-authored-by: Pierre Krieger <pierre.krieger1708@gmail.com>
Co-authored-by: Toralf Wittner <tw@dtex.org>
2020-03-04 13:49:25 +01:00
|
|
|
handler,
|
2018-11-12 17:12:47 +01:00
|
|
|
event: #wrapped_event,
|
|
|
|
});
|
|
|
|
}
|
2020-11-18 15:52:33 +01:00
|
|
|
std::task::Poll::Ready(#network_behaviour_action::ReportObservedAddr { address, score }) => {
|
|
|
|
return std::task::Poll::Ready(#network_behaviour_action::ReportObservedAddr { address, score });
|
2018-12-01 13:34:57 +01:00
|
|
|
}
|
2021-07-03 00:35:51 +07:00
|
|
|
std::task::Poll::Ready(#network_behaviour_action::CloseConnection { peer_id, connection }) => {
|
|
|
|
return std::task::Poll::Ready(#network_behaviour_action::CloseConnection { peer_id, connection });
|
|
|
|
}
|
2019-11-25 10:45:04 +01:00
|
|
|
std::task::Poll::Pending => break,
|
2018-11-12 17:12:47 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
});
|
|
|
|
|
|
|
|
// Now the magic happens.
|
2021-08-11 13:12:12 +02:00
|
|
|
let final_quote = quote! {
|
2022-08-08 07:18:32 +02:00
|
|
|
#out_event_definition
|
|
|
|
|
2019-01-26 23:57:53 +01:00
|
|
|
impl #impl_generics #trait_to_impl for #name #ty_generics
|
2018-11-12 17:12:47 +01:00
|
|
|
#where_clause
|
|
|
|
{
|
2022-05-18 02:52:50 -05:00
|
|
|
type ConnectionHandler = #connection_handler_ty;
|
2022-08-08 07:18:32 +02:00
|
|
|
type OutEvent = #out_event_name #ty_generics;
|
2018-11-12 17:12:47 +01:00
|
|
|
|
2022-02-21 13:32:24 +01:00
|
|
|
fn new_handler(&mut self) -> Self::ConnectionHandler {
|
2022-05-18 02:52:50 -05:00
|
|
|
use #into_connection_handler;
|
2018-11-12 17:12:47 +01:00
|
|
|
#new_handler
|
|
|
|
}
|
|
|
|
|
2019-01-30 14:55:39 +01:00
|
|
|
fn addresses_of_peer(&mut self, peer_id: &#peer_id) -> Vec<#multiaddr> {
|
2019-01-26 23:57:53 +01:00
|
|
|
let mut out = Vec::new();
|
|
|
|
#(#addresses_of_peer_stmts);*
|
|
|
|
out
|
|
|
|
}
|
|
|
|
|
2022-02-09 10:08:28 -05:00
|
|
|
fn inject_connection_established(&mut self, peer_id: &#peer_id, connection_id: &#connection_id, endpoint: &#connected_point, errors: #dial_errors, other_established: usize) {
|
2020-03-31 15:41:13 +02:00
|
|
|
#(#inject_connection_established_stmts);*
|
|
|
|
}
|
|
|
|
|
2020-06-30 17:10:53 +02:00
|
|
|
fn inject_address_change(&mut self, peer_id: &#peer_id, connection_id: &#connection_id, old: &#connected_point, new: &#connected_point) {
|
|
|
|
#(#inject_address_change_stmts);*
|
|
|
|
}
|
|
|
|
|
2022-05-18 02:52:50 -05:00
|
|
|
fn inject_connection_closed(&mut self, peer_id: &#peer_id, connection_id: &#connection_id, endpoint: &#connected_point, handlers: <Self::ConnectionHandler as #into_connection_handler>::Handler, remaining_established: usize) {
|
2020-03-31 15:41:13 +02:00
|
|
|
#(#inject_connection_closed_stmts);*
|
|
|
|
}
|
|
|
|
|
2022-02-21 13:32:24 +01:00
|
|
|
fn inject_dial_failure(&mut self, peer_id: Option<#peer_id>, handlers: Self::ConnectionHandler, error: &#dial_error) {
|
2019-01-30 14:55:39 +01:00
|
|
|
#(#inject_dial_failure_stmts);*
|
|
|
|
}
|
|
|
|
|
2022-02-21 13:32:24 +01:00
|
|
|
fn inject_listen_failure(&mut self, local_addr: &#multiaddr, send_back_addr: &#multiaddr, handlers: Self::ConnectionHandler) {
|
2021-08-31 17:00:51 +02:00
|
|
|
#(#inject_listen_failure_stmts);*
|
|
|
|
}
|
|
|
|
|
2021-03-24 17:21:53 +01:00
|
|
|
fn inject_new_listener(&mut self, id: #listener_id) {
|
|
|
|
#(#inject_new_listener_stmts);*
|
|
|
|
}
|
|
|
|
|
|
|
|
fn inject_new_listen_addr(&mut self, id: #listener_id, addr: &#multiaddr) {
|
2019-04-16 15:36:08 +02:00
|
|
|
#(#inject_new_listen_addr_stmts);*
|
|
|
|
}
|
|
|
|
|
2021-03-24 17:21:53 +01:00
|
|
|
fn inject_expired_listen_addr(&mut self, id: #listener_id, addr: &#multiaddr) {
|
2019-04-16 15:36:08 +02:00
|
|
|
#(#inject_expired_listen_addr_stmts);*
|
|
|
|
}
|
|
|
|
|
2019-04-16 17:00:20 +02:00
|
|
|
fn inject_new_external_addr(&mut self, addr: &#multiaddr) {
|
|
|
|
#(#inject_new_external_addr_stmts);*
|
|
|
|
}
|
|
|
|
|
2021-03-24 17:21:53 +01:00
|
|
|
fn inject_expired_external_addr(&mut self, addr: &#multiaddr) {
|
|
|
|
#(#inject_expired_external_addr_stmts);*
|
|
|
|
}
|
|
|
|
|
2019-08-13 15:41:12 +02:00
|
|
|
fn inject_listener_error(&mut self, id: #listener_id, err: &(dyn std::error::Error + 'static)) {
|
|
|
|
#(#inject_listener_error_stmts);*
|
|
|
|
}
|
|
|
|
|
2020-05-25 15:27:49 +02:00
|
|
|
fn inject_listener_closed(&mut self, id: #listener_id, reason: std::result::Result<(), &std::io::Error>) {
|
2019-08-13 15:41:12 +02:00
|
|
|
#(#inject_listener_closed_stmts);*
|
|
|
|
}
|
|
|
|
|
Multiple connections per peer (#1440)
* Allow multiple connections per peer in libp2p-core.
Instead of trying to enforce a single connection per peer,
which involves quite a bit of additional complexity e.g.
to prioritise simultaneously opened connections and can
have other undesirable consequences [1], we now
make multiple connections per peer a feature.
The gist of these changes is as follows:
The concept of a "node" with an implicit 1-1 correspondence
to a connection has been replaced with the "first-class"
concept of a "connection". The code from `src/nodes` has moved
(with varying degrees of modification) to `src/connection`.
A `HandledNode` has become a `Connection`, a `NodeHandler` a
`ConnectionHandler`, the `CollectionStream` was the basis for
the new `connection::Pool`, and so forth.
Conceptually, a `Network` contains a `connection::Pool` which
in turn internally employs the `connection::Manager` for
handling the background `connection::manager::Task`s, one
per connection, as before. These are all considered implementation
details. On the public API, `Peer`s are managed as before through
the `Network`, except now the API has changed with the shift of focus
to (potentially multiple) connections per peer. The `NetworkEvent`s have
accordingly also undergone changes.
The Swarm APIs remain largely unchanged, except for the fact that
`inject_replaced` is no longer called. It may now practically happen
that multiple `ProtocolsHandler`s are associated with a single
`NetworkBehaviour`, one per connection. If implementations of
`NetworkBehaviour` rely somehow on communicating with exactly
one `ProtocolsHandler`, this may cause issues, but it is unlikely.
[1]: https://github.com/paritytech/substrate/issues/4272
* Fix intra-rustdoc links.
* Update core/src/connection/pool.rs
Co-Authored-By: Max Inden <mail@max-inden.de>
* Address some review feedback and fix doc links.
* Allow responses to be sent on the same connection.
* Remove unnecessary remainders of inject_replaced.
* Update swarm/src/behaviour.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update swarm/src/lib.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/manager.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/manager.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/pool.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Incorporate more review feedback.
* Move module declaration below imports.
* Update core/src/connection/manager.rs
Co-Authored-By: Toralf Wittner <tw@dtex.org>
* Update core/src/connection/manager.rs
Co-Authored-By: Toralf Wittner <tw@dtex.org>
* Simplify as per review.
* Fix rustoc link.
* Add try_notify_handler and simplify.
* Relocate DialingConnection and DialingAttempt.
For better visibility constraints.
* Small cleanup.
* Small cleanup. More robust EstablishedConnectionIter.
* Clarify semantics of `DialingPeer::connect`.
* Don't call inject_disconnected on InvalidPeerId.
To preserve the previous behavior and ensure calls to
`inject_disconnected` are always paired with calls to
`inject_connected`.
* Provide public ConnectionId constructor.
Mainly needed for testing purposes, e.g. in substrate.
* Move the established connection limit check to the right place.
* Clean up connection error handling.
Separate connection errors into those occuring during
connection setup or upon rejecting a newly established
connection (the `PendingConnectionError`) and those
errors occurring on previously established connections,
i.e. for which a `ConnectionEstablished` event has
been emitted by the connection pool earlier.
* Revert change in log level and clarify an invariant.
* Remove inject_replaced entirely.
* Allow notifying all connection handlers.
Thereby simplify by introducing a new enum `NotifyHandler`,
used with a single constructor `NetworkBehaviourAction::NotifyHandler`.
* Finishing touches.
Small API simplifications and code deduplication.
Some more useful debug logging.
Co-authored-by: Max Inden <mail@max-inden.de>
Co-authored-by: Pierre Krieger <pierre.krieger1708@gmail.com>
Co-authored-by: Toralf Wittner <tw@dtex.org>
2020-03-04 13:49:25 +01:00
|
|
|
fn inject_event(
|
2018-11-12 17:12:47 +01:00
|
|
|
&mut self,
|
|
|
|
peer_id: #peer_id,
|
Multiple connections per peer (#1440)
* Allow multiple connections per peer in libp2p-core.
Instead of trying to enforce a single connection per peer,
which involves quite a bit of additional complexity e.g.
to prioritise simultaneously opened connections and can
have other undesirable consequences [1], we now
make multiple connections per peer a feature.
The gist of these changes is as follows:
The concept of a "node" with an implicit 1-1 correspondence
to a connection has been replaced with the "first-class"
concept of a "connection". The code from `src/nodes` has moved
(with varying degrees of modification) to `src/connection`.
A `HandledNode` has become a `Connection`, a `NodeHandler` a
`ConnectionHandler`, the `CollectionStream` was the basis for
the new `connection::Pool`, and so forth.
Conceptually, a `Network` contains a `connection::Pool` which
in turn internally employs the `connection::Manager` for
handling the background `connection::manager::Task`s, one
per connection, as before. These are all considered implementation
details. On the public API, `Peer`s are managed as before through
the `Network`, except now the API has changed with the shift of focus
to (potentially multiple) connections per peer. The `NetworkEvent`s have
accordingly also undergone changes.
The Swarm APIs remain largely unchanged, except for the fact that
`inject_replaced` is no longer called. It may now practically happen
that multiple `ProtocolsHandler`s are associated with a single
`NetworkBehaviour`, one per connection. If implementations of
`NetworkBehaviour` rely somehow on communicating with exactly
one `ProtocolsHandler`, this may cause issues, but it is unlikely.
[1]: https://github.com/paritytech/substrate/issues/4272
* Fix intra-rustdoc links.
* Update core/src/connection/pool.rs
Co-Authored-By: Max Inden <mail@max-inden.de>
* Address some review feedback and fix doc links.
* Allow responses to be sent on the same connection.
* Remove unnecessary remainders of inject_replaced.
* Update swarm/src/behaviour.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update swarm/src/lib.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/manager.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/manager.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Update core/src/connection/pool.rs
Co-Authored-By: Pierre Krieger <pierre.krieger1708@gmail.com>
* Incorporate more review feedback.
* Move module declaration below imports.
* Update core/src/connection/manager.rs
Co-Authored-By: Toralf Wittner <tw@dtex.org>
* Update core/src/connection/manager.rs
Co-Authored-By: Toralf Wittner <tw@dtex.org>
* Simplify as per review.
* Fix rustoc link.
* Add try_notify_handler and simplify.
* Relocate DialingConnection and DialingAttempt.
For better visibility constraints.
* Small cleanup.
* Small cleanup. More robust EstablishedConnectionIter.
* Clarify semantics of `DialingPeer::connect`.
* Don't call inject_disconnected on InvalidPeerId.
To preserve the previous behavior and ensure calls to
`inject_disconnected` are always paired with calls to
`inject_connected`.
* Provide public ConnectionId constructor.
Mainly needed for testing purposes, e.g. in substrate.
* Move the established connection limit check to the right place.
* Clean up connection error handling.
Separate connection errors into those occuring during
connection setup or upon rejecting a newly established
connection (the `PendingConnectionError`) and those
errors occurring on previously established connections,
i.e. for which a `ConnectionEstablished` event has
been emitted by the connection pool earlier.
* Revert change in log level and clarify an invariant.
* Remove inject_replaced entirely.
* Allow notifying all connection handlers.
Thereby simplify by introducing a new enum `NotifyHandler`,
used with a single constructor `NetworkBehaviourAction::NotifyHandler`.
* Finishing touches.
Small API simplifications and code deduplication.
Some more useful debug logging.
Co-authored-by: Max Inden <mail@max-inden.de>
Co-authored-by: Pierre Krieger <pierre.krieger1708@gmail.com>
Co-authored-by: Toralf Wittner <tw@dtex.org>
2020-03-04 13:49:25 +01:00
|
|
|
connection_id: #connection_id,
|
2022-05-18 02:52:50 -05:00
|
|
|
event: <<Self::ConnectionHandler as #into_connection_handler>::Handler as #connection_handler>::OutEvent
|
2018-11-12 17:12:47 +01:00
|
|
|
) {
|
|
|
|
match event {
|
|
|
|
#(#inject_node_event_stmts),*
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-21 13:32:24 +01:00
|
|
|
fn poll(&mut self, cx: &mut std::task::Context, poll_params: &mut impl #poll_parameters) -> std::task::Poll<#network_behaviour_action<Self::OutEvent, Self::ConnectionHandler>> {
|
2018-11-12 17:12:47 +01:00
|
|
|
use libp2p::futures::prelude::*;
|
|
|
|
#(#poll_stmts)*
|
2022-08-28 10:51:49 +02:00
|
|
|
std::task::Poll::Pending
|
2018-11-12 17:12:47 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
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" {
|
2019-11-25 10:45:04 +01:00
|
|
|
match attr.parse_meta() {
|
|
|
|
Ok(syn::Meta::List(ref meta)) => Some(meta.nested.iter().cloned().collect()),
|
|
|
|
Ok(_) => None,
|
|
|
|
Err(e) => {
|
|
|
|
eprintln!("error parsing attribute metadata: {}", e);
|
2018-11-12 17:12:47 +01:00
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|