swarm-derive: Add prelude configuration option to NetworkBehaviour macro (#3055)

Currently, our `NetworkBehaviour` derive macro depends on the `libp2p` crate to be in scope. This prevents standalone usage which forces us to depend on `libp2p` in all our tests where we want to derive a `NetworkBehaviour`.

This PR introduces a `prelude` option that - by default - points to `libp2p::swarm::derive_prelude`, a new module added to `libp2p_swarm`. With this config option, users of `libp2p_swarm` can now refer to the macro without depending on `libp2p`, breaking the circular dependency in our workspace. For consistency with the ecosystem, the macro is now also re-exported by `libp2p_swarm` instead of `libp2p` at the same position as the trait that it implements.

Lastly, we introduce an off-by-default `macros` feature flag that shrinks the dependency tree for users that don't need the derive macro.
This commit is contained in:
Thomas Eizinger
2022-11-13 10:59:14 +11:00
committed by GitHub
parent c32f03c317
commit afb777e937
31 changed files with 211 additions and 132 deletions

View File

@ -67,6 +67,25 @@ pub mod dummy;
pub mod handler;
pub mod keep_alive;
/// Bundles all symbols required for the [`libp2p_swarm_derive::NetworkBehaviour`] macro.
#[doc(hidden)]
pub mod derive_prelude {
pub use crate::ConnectionHandler;
pub use crate::DialError;
pub use crate::IntoConnectionHandler;
pub use crate::IntoConnectionHandlerSelect;
pub use crate::NetworkBehaviour;
pub use crate::NetworkBehaviourAction;
pub use crate::PollParameters;
pub use futures::prelude as futures;
pub use libp2p_core::connection::ConnectionId;
pub use libp2p_core::either::EitherOutput;
pub use libp2p_core::transport::ListenerId;
pub use libp2p_core::ConnectedPoint;
pub use libp2p_core::Multiaddr;
pub use libp2p_core::PeerId;
}
pub use behaviour::{
CloseConnection, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters,
};
@ -80,6 +99,8 @@ pub use handler::{
IntoConnectionHandler, IntoConnectionHandlerSelect, KeepAlive, OneShotHandler,
OneShotHandlerConfig, SubstreamProtocol,
};
#[cfg(feature = "macros")]
pub use libp2p_swarm_derive::NetworkBehaviour;
pub use registry::{AddAddressResult, AddressRecord, AddressScore};
use connection::pool::{EstablishedConnection, Pool, PoolConfig, PoolEvent};
@ -1568,12 +1589,12 @@ mod tests {
use futures::future::poll_fn;
use futures::future::Either;
use futures::{executor, future, ready};
use libp2p::core::{identity, multiaddr, transport, upgrade};
use libp2p::plaintext;
use libp2p::yamux;
use libp2p_core::multiaddr::multiaddr;
use libp2p_core::transport::TransportEvent;
use libp2p_core::Endpoint;
use libp2p_core::{identity, multiaddr, transport, upgrade};
use libp2p_plaintext as plaintext;
use libp2p_yamux as yamux;
use quickcheck::*;
// Test execution state.