Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revise naming of libp2p-ping symbols #2215

Merged
merged 4 commits into from
Sep 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 16 additions & 18 deletions examples/ipfs-private.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ use libp2p::{
identify::{Identify, IdentifyConfig, IdentifyEvent},
identity,
multiaddr::Protocol,
noise,
ping::{self, Ping, PingConfig, PingEvent},
noise, ping,
pnet::{PnetConfig, PreSharedKey},
swarm::{NetworkBehaviourEventProcess, SwarmEvent},
tcp::TcpConfig,
Expand Down Expand Up @@ -167,7 +166,7 @@ fn main() -> Result<(), Box<dyn Error>> {
struct MyBehaviour {
gossipsub: Gossipsub,
identify: Identify,
ping: Ping,
ping: ping::Behaviour,
}

impl NetworkBehaviourEventProcess<IdentifyEvent> for MyBehaviour {
Expand Down Expand Up @@ -196,44 +195,43 @@ fn main() -> Result<(), Box<dyn Error>> {
}
}

impl NetworkBehaviourEventProcess<PingEvent> for MyBehaviour {
impl NetworkBehaviourEventProcess<ping::Event> for MyBehaviour {
// Called when `ping` produces an event.
fn inject_event(&mut self, event: PingEvent) {
use ping::handler::{PingFailure, PingSuccess};
fn inject_event(&mut self, event: ping::Event) {
match event {
PingEvent {
ping::Event {
peer,
result: Result::Ok(PingSuccess::Ping { rtt }),
result: Result::Ok(ping::Success::Ping { rtt }),
} => {
println!(
"ping: rtt to {} is {} ms",
peer.to_base58(),
rtt.as_millis()
);
}
PingEvent {
ping::Event {
peer,
result: Result::Ok(PingSuccess::Pong),
result: Result::Ok(ping::Success::Pong),
} => {
println!("ping: pong from {}", peer.to_base58());
}
PingEvent {
ping::Event {
peer,
result: Result::Err(PingFailure::Timeout),
result: Result::Err(ping::Failure::Timeout),
} => {
println!("ping: timeout to {}", peer.to_base58());
}
PingEvent {
ping::Event {
peer,
result: Result::Err(PingFailure::Unsupported),
result: Result::Err(ping::Failure::Unsupported),
} => {
println!("ping: {} does not support ping protocol", peer.to_base58());
}
PingEvent {
ping::Event {
peer,
result: Result::Err(PingFailure::Other { error }),
result: Result::Err(ping::Failure::Other { error }),
} => {
println!("ping: failure with {}: {}", peer.to_base58(), error);
println!("ping: ping::Failure with {}: {}", peer.to_base58(), error);
}
}
}
Expand All @@ -255,7 +253,7 @@ fn main() -> Result<(), Box<dyn Error>> {
"/ipfs/0.1.0".into(),
local_key.public(),
)),
ping: Ping::new(PingConfig::new()),
ping: ping::Behaviour::new(ping::Config::new()),
};

println!("Subscribing to {:?}", gossipsub_topic);
Expand Down
5 changes: 2 additions & 3 deletions examples/ping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,8 @@

use futures::executor::block_on;
use futures::prelude::*;
use libp2p::ping::{Ping, PingConfig};
use libp2p::swarm::{Swarm, SwarmEvent};
use libp2p::{identity, PeerId};
use libp2p::{identity, ping, PeerId};
use std::error::Error;
use std::task::Poll;

Expand All @@ -60,7 +59,7 @@ fn main() -> Result<(), Box<dyn Error>> {
// For illustrative purposes, the ping protocol is configured to
// keep the connection alive, so a continuous sequence of pings
// can be observed.
let behaviour = Ping::new(PingConfig::new().with_keep_alive(true));
let behaviour = ping::Behaviour::new(ping::Config::new().with_keep_alive(true));

let mut swarm = Swarm::new(transport, behaviour, local_peer_id);

Expand Down
8 changes: 8 additions & 0 deletions protocols/ping/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@

[PR 2149]: https://github.com/libp2p/rust-libp2p/pull/2149/

- Rename types as per [discussion 2174].
`Ping` has been renamed to `Behaviour`.
The `Ping` prefix has been removed from various types like `PingEvent`.
Users should prefer importing the ping protocol as a module (`use libp2p::ping;`),
and refer to its types via `ping::`. For example: `ping::Behaviour` or `ping::Event`.

[discussion 2174]: https://github.com/libp2p/rust-libp2p/discussions/2174

# 0.30.0 [2021-07-12]

- Update dependencies.
Expand Down
71 changes: 34 additions & 37 deletions protocols/ping/src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use wasm_timer::Delay;

/// The configuration for outbound pings.
#[derive(Clone, Debug)]
pub struct PingConfig {
pub struct Config {
/// The timeout of an outbound ping.
timeout: Duration,
/// The duration between the last successful outbound or inbound ping
Expand All @@ -54,13 +54,13 @@ pub struct PingConfig {
keep_alive: bool,
}

impl PingConfig {
impl Config {
/// Creates a new `PingConfig` with the following default settings:
///
/// * [`PingConfig::with_interval`] 15s
/// * [`PingConfig::with_timeout`] 20s
/// * [`PingConfig::with_max_failures`] 1
/// * [`PingConfig::with_keep_alive`] false
/// * [`Config::with_interval`] 15s
/// * [`Config::with_timeout`] 20s
/// * [`Config::with_max_failures`] 1
/// * [`Config::with_keep_alive`] false
///
/// These settings have the following effect:
///
Expand Down Expand Up @@ -116,12 +116,9 @@ impl PingConfig {
}
}

/// The result of an inbound or outbound ping.
pub type PingResult = Result<PingSuccess, PingFailure>;

/// The successful result of processing an inbound or outbound ping.
#[derive(Debug)]
pub enum PingSuccess {
pub enum Success {
/// Received a ping and sent back a pong.
Pong,
/// Sent a ping and received back a pong.
Expand All @@ -132,7 +129,7 @@ pub enum PingSuccess {

/// An outbound ping failure.
#[derive(Debug)]
pub enum PingFailure {
pub enum Failure {
/// The ping timed out, i.e. no response was received within the
/// configured ping timeout.
Timeout,
Expand All @@ -144,22 +141,22 @@ pub enum PingFailure {
},
}

impl fmt::Display for PingFailure {
impl fmt::Display for Failure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PingFailure::Timeout => f.write_str("Ping timeout"),
PingFailure::Other { error } => write!(f, "Ping error: {}", error),
PingFailure::Unsupported => write!(f, "Ping protocol not supported"),
Failure::Timeout => f.write_str("Ping timeout"),
Failure::Other { error } => write!(f, "Ping error: {}", error),
Failure::Unsupported => write!(f, "Ping protocol not supported"),
}
}
}

impl Error for PingFailure {
impl Error for Failure {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
PingFailure::Timeout => None,
PingFailure::Other { error } => Some(&**error),
PingFailure::Unsupported => None,
Failure::Timeout => None,
Failure::Other { error } => Some(&**error),
Failure::Unsupported => None,
}
}
}
Expand All @@ -168,14 +165,14 @@ impl Error for PingFailure {
/// and answering ping queries.
///
/// If the remote doesn't respond, produces an error that closes the connection.
pub struct PingHandler {
pub struct Handler {
/// Configuration options.
config: PingConfig,
config: Config,
/// The timer used for the delay to the next ping as well as
/// the ping timeout.
timer: Delay,
/// Outbound ping failures that are pending to be processed by `poll()`.
pending_errors: VecDeque<PingFailure>,
pending_errors: VecDeque<Failure>,
/// The number of consecutive ping failures that occurred.
///
/// Each successful ping resets this counter to 0.
Expand Down Expand Up @@ -203,10 +200,10 @@ enum State {
Active,
}

impl PingHandler {
impl Handler {
/// Builds a new `PingHandler` with the given configuration.
pub fn new(config: PingConfig) -> Self {
PingHandler {
pub fn new(config: Config) -> Self {
Handler {
config,
timer: Delay::new(Duration::new(0, 0)),
pending_errors: VecDeque::with_capacity(2),
Expand All @@ -218,10 +215,10 @@ impl PingHandler {
}
}

impl ProtocolsHandler for PingHandler {
impl ProtocolsHandler for Handler {
type InEvent = Void;
type OutEvent = PingResult;
type Error = PingFailure;
type OutEvent = crate::Result;
type Error = Failure;
type InboundProtocol = protocol::Ping;
type OutboundProtocol = protocol::Ping;
type OutboundOpenInfo = ();
Expand Down Expand Up @@ -253,8 +250,8 @@ impl ProtocolsHandler for PingHandler {
return;
}
// Note: This timeout only covers protocol negotiation.
ProtocolsHandlerUpgrErr::Timeout => PingFailure::Timeout,
e => PingFailure::Other { error: Box::new(e) },
ProtocolsHandlerUpgrErr::Timeout => Failure::Timeout,
e => Failure::Other { error: Box::new(e) },
};

self.pending_errors.push_front(error);
Expand All @@ -271,14 +268,14 @@ impl ProtocolsHandler for PingHandler {
fn poll(
&mut self,
cx: &mut Context<'_>,
) -> Poll<ProtocolsHandlerEvent<protocol::Ping, (), PingResult, Self::Error>> {
) -> Poll<ProtocolsHandlerEvent<protocol::Ping, (), crate::Result, Self::Error>> {
match self.state {
State::Inactive { reported: true } => {
return Poll::Pending; // nothing to do on this connection
}
State::Inactive { reported: false } => {
self.state = State::Inactive { reported: true };
return Poll::Ready(ProtocolsHandlerEvent::Custom(Err(PingFailure::Unsupported)));
return Poll::Ready(ProtocolsHandlerEvent::Custom(Err(Failure::Unsupported)));
}
State::Active => {}
}
Expand All @@ -294,7 +291,7 @@ impl ProtocolsHandler for PingHandler {
Poll::Ready(Ok(stream)) => {
// A ping from a remote peer has been answered, wait for the next.
self.inbound = Some(protocol::recv_ping(stream).boxed());
return Poll::Ready(ProtocolsHandlerEvent::Custom(Ok(PingSuccess::Pong)));
return Poll::Ready(ProtocolsHandlerEvent::Custom(Ok(Success::Pong)));
}
}
}
Expand Down Expand Up @@ -328,7 +325,7 @@ impl ProtocolsHandler for PingHandler {
Some(PingState::Ping(mut ping)) => match ping.poll_unpin(cx) {
Poll::Pending => {
if self.timer.poll_unpin(cx).is_ready() {
self.pending_errors.push_front(PingFailure::Timeout);
self.pending_errors.push_front(Failure::Timeout);
} else {
self.outbound = Some(PingState::Ping(ping));
break;
Expand All @@ -338,13 +335,13 @@ impl ProtocolsHandler for PingHandler {
self.failures = 0;
self.timer.reset(self.config.interval);
self.outbound = Some(PingState::Idle(stream));
return Poll::Ready(ProtocolsHandlerEvent::Custom(Ok(PingSuccess::Ping {
return Poll::Ready(ProtocolsHandlerEvent::Custom(Ok(Success::Ping {
rtt,
})));
}
Poll::Ready(Err(e)) => {
self.pending_errors
.push_front(PingFailure::Other { error: Box::new(e) });
.push_front(Failure::Other { error: Box::new(e) });
}
},
Some(PingState::Idle(stream)) => match self.timer.poll_unpin(cx) {
Expand All @@ -357,7 +354,7 @@ impl ProtocolsHandler for PingHandler {
self.outbound = Some(PingState::Ping(protocol::send_ping(stream).boxed()));
}
Poll::Ready(Err(e)) => {
return Poll::Ready(ProtocolsHandlerEvent::Close(PingFailure::Other {
return Poll::Ready(ProtocolsHandlerEvent::Close(Failure::Other {
error: Box::new(e),
}))
}
Expand Down
Loading