121 lines
4.2 KiB
Rust
Raw Normal View History

// Copyright 2017-2018 Parity Technologies (UK) Ltd.
2017-11-22 10:58:06 +01:00
//
// 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.
2019-04-16 15:57:29 +02:00
//! This module implements the `/ipfs/ping/1.0.0` protocol.
//!
Remove libp2p-ping keep-alive functionality. (#1067) * Fix connection & handler shutdown when using `KeepAlive::Now`. Delay::new(Instant::now()) is never immediately ready, resulting in `KeepAlive::Now` to have no effect, since the delay is re-created on every execution of `poll()` in the `NodeHandlerWrapper`. It can also send the node handler into a busy-loop, since every newly created Delay will trigger a task wakeup, which creates a new Delay with Instant::now(), and so forth. The use of `Delay::new(Instant::now())` for "immediate" connection shutdown is therefore removed here entirely. An important assumption is thereby that as long as the node handler non-empty `negotiating_in` and `negotiating_out`, the handler is not dependent on such a Delay for task wakeup. * Correction to the libp2p-ping connection timeout. The current connection timeout is always short of one `interval`, because the "countdown" begins with the last received or sent pong (depending on the policy). In effect, the current default config has a connection timeout of 5 seconds (20 - 15) from the point when a ping is sent. Instead, the "countdown" of the connection timeout should always begin with the next scheduled ping. That also makes all configurations valid, avoiding pitfalls. The important properties of the ping handler are now checked to hold for all configurations, in particular: * The next ping must be scheduled no earlier than the ping interval and no later than the connection timeout. * The "countdown" for the connection timeout starts on the next ping, i.e. the full connection timeout remains at the instant when the next ping is sent. * Do not keep connections alive. The ping protocol is not supposed to keep otherwise idle connections alive, only to add an additional condition for terminating them in the form of a configurable number of consecutive failed ping requests. In this context, the `PingPolicy` does not seem useful any longer.
2019-04-20 16:16:31 +02:00
//! The ping protocol can be used as a simple application-layer health check
//! for connections of any [`Transport`] as well as to measure and record
//! round-trip times.
2017-11-22 10:58:06 +01:00
//!
//! # Usage
//!
2019-04-16 15:57:29 +02:00
//! The [`Ping`] struct implements the [`NetworkBehaviour`] trait. When used with a [`Swarm`],
//! it will respond to inbound ping requests and as necessary periodically send outbound
Remove libp2p-ping keep-alive functionality. (#1067) * Fix connection & handler shutdown when using `KeepAlive::Now`. Delay::new(Instant::now()) is never immediately ready, resulting in `KeepAlive::Now` to have no effect, since the delay is re-created on every execution of `poll()` in the `NodeHandlerWrapper`. It can also send the node handler into a busy-loop, since every newly created Delay will trigger a task wakeup, which creates a new Delay with Instant::now(), and so forth. The use of `Delay::new(Instant::now())` for "immediate" connection shutdown is therefore removed here entirely. An important assumption is thereby that as long as the node handler non-empty `negotiating_in` and `negotiating_out`, the handler is not dependent on such a Delay for task wakeup. * Correction to the libp2p-ping connection timeout. The current connection timeout is always short of one `interval`, because the "countdown" begins with the last received or sent pong (depending on the policy). In effect, the current default config has a connection timeout of 5 seconds (20 - 15) from the point when a ping is sent. Instead, the "countdown" of the connection timeout should always begin with the next scheduled ping. That also makes all configurations valid, avoiding pitfalls. The important properties of the ping handler are now checked to hold for all configurations, in particular: * The next ping must be scheduled no earlier than the ping interval and no later than the connection timeout. * The "countdown" for the connection timeout starts on the next ping, i.e. the full connection timeout remains at the instant when the next ping is sent. * Do not keep connections alive. The ping protocol is not supposed to keep otherwise idle connections alive, only to add an additional condition for terminating them in the form of a configurable number of consecutive failed ping requests. In this context, the `PingPolicy` does not seem useful any longer.
2019-04-20 16:16:31 +02:00
//! ping requests on every established connection. If a configurable number of pings fail,
//! the connection will be closed.
2017-11-22 10:58:06 +01:00
//!
2019-04-16 15:57:29 +02:00
//! The `Ping` network behaviour produces [`PingEvent`]s, which may be consumed from the `Swarm`
//! by an application, e.g. to collect statistics.
//!
Remove libp2p-ping keep-alive functionality. (#1067) * Fix connection & handler shutdown when using `KeepAlive::Now`. Delay::new(Instant::now()) is never immediately ready, resulting in `KeepAlive::Now` to have no effect, since the delay is re-created on every execution of `poll()` in the `NodeHandlerWrapper`. It can also send the node handler into a busy-loop, since every newly created Delay will trigger a task wakeup, which creates a new Delay with Instant::now(), and so forth. The use of `Delay::new(Instant::now())` for "immediate" connection shutdown is therefore removed here entirely. An important assumption is thereby that as long as the node handler non-empty `negotiating_in` and `negotiating_out`, the handler is not dependent on such a Delay for task wakeup. * Correction to the libp2p-ping connection timeout. The current connection timeout is always short of one `interval`, because the "countdown" begins with the last received or sent pong (depending on the policy). In effect, the current default config has a connection timeout of 5 seconds (20 - 15) from the point when a ping is sent. Instead, the "countdown" of the connection timeout should always begin with the next scheduled ping. That also makes all configurations valid, avoiding pitfalls. The important properties of the ping handler are now checked to hold for all configurations, in particular: * The next ping must be scheduled no earlier than the ping interval and no later than the connection timeout. * The "countdown" for the connection timeout starts on the next ping, i.e. the full connection timeout remains at the instant when the next ping is sent. * Do not keep connections alive. The ping protocol is not supposed to keep otherwise idle connections alive, only to add an additional condition for terminating them in the form of a configurable number of consecutive failed ping requests. In this context, the `PingPolicy` does not seem useful any longer.
2019-04-20 16:16:31 +02:00
//! > **Note**: The ping protocol does not keep otherwise idle connections alive,
//! > it only adds an additional condition for terminating the connection, namely
//! > a certain number of failed ping requests.
//!
//! [`Swarm`]: libp2p_swarm::Swarm
2019-04-16 15:57:29 +02:00
//! [`Transport`]: libp2p_core::Transport
2017-11-22 10:58:06 +01:00
pub mod protocol;
pub mod handler;
Remove libp2p-ping keep-alive functionality. (#1067) * Fix connection & handler shutdown when using `KeepAlive::Now`. Delay::new(Instant::now()) is never immediately ready, resulting in `KeepAlive::Now` to have no effect, since the delay is re-created on every execution of `poll()` in the `NodeHandlerWrapper`. It can also send the node handler into a busy-loop, since every newly created Delay will trigger a task wakeup, which creates a new Delay with Instant::now(), and so forth. The use of `Delay::new(Instant::now())` for "immediate" connection shutdown is therefore removed here entirely. An important assumption is thereby that as long as the node handler non-empty `negotiating_in` and `negotiating_out`, the handler is not dependent on such a Delay for task wakeup. * Correction to the libp2p-ping connection timeout. The current connection timeout is always short of one `interval`, because the "countdown" begins with the last received or sent pong (depending on the policy). In effect, the current default config has a connection timeout of 5 seconds (20 - 15) from the point when a ping is sent. Instead, the "countdown" of the connection timeout should always begin with the next scheduled ping. That also makes all configurations valid, avoiding pitfalls. The important properties of the ping handler are now checked to hold for all configurations, in particular: * The next ping must be scheduled no earlier than the ping interval and no later than the connection timeout. * The "countdown" for the connection timeout starts on the next ping, i.e. the full connection timeout remains at the instant when the next ping is sent. * Do not keep connections alive. The ping protocol is not supposed to keep otherwise idle connections alive, only to add an additional condition for terminating them in the form of a configurable number of consecutive failed ping requests. In this context, the `PingPolicy` does not seem useful any longer.
2019-04-20 16:16:31 +02:00
pub use handler::{PingConfig, PingResult, PingSuccess, PingFailure};
2019-04-16 15:57:29 +02:00
use handler::PingHandler;
use libp2p_core::{Multiaddr, PeerId, connection::ConnectionId};
use libp2p_swarm::{NetworkBehaviour, NetworkBehaviourAction, PollParameters};
use std::{collections::VecDeque, task::Context, task::Poll};
2019-04-16 15:57:29 +02:00
use void::Void;
2019-04-16 15:57:29 +02:00
/// `Ping` is a [`NetworkBehaviour`] that responds to inbound pings and
/// periodically sends outbound pings on every established connection.
///
/// See the crate root documentation for more information.
pub struct Ping {
2019-04-16 15:57:29 +02:00
/// Configuration for outbound pings.
config: PingConfig,
/// Queue of events to yield to the swarm.
events: VecDeque<PingEvent>,
}
2019-04-16 15:57:29 +02:00
/// Event generated by the `Ping` network behaviour.
#[derive(Debug)]
pub struct PingEvent {
/// The peer ID of the remote.
pub peer: PeerId,
/// The result of an inbound or outbound ping.
pub result: PingResult,
}
impl Ping {
2019-04-16 15:57:29 +02:00
/// Creates a new `Ping` network behaviour with the given configuration.
pub fn new(config: PingConfig) -> Self {
Ping {
2019-04-16 15:57:29 +02:00
config,
events: VecDeque::new(),
}
}
}
impl Default for Ping {
fn default() -> Self {
2019-04-16 15:57:29 +02:00
Ping::new(PingConfig::new())
}
}
impl NetworkBehaviour for Ping {
type ProtocolsHandler = PingHandler;
type OutEvent = PingEvent;
fn new_handler(&mut self) -> Self::ProtocolsHandler {
2019-04-16 15:57:29 +02:00
PingHandler::new(self.config.clone())
}
fn addresses_of_peer(&mut self, _peer_id: &PeerId) -> Vec<Multiaddr> {
Vec::new()
}
fn inject_connected(&mut self, _: &PeerId) {}
fn inject_disconnected(&mut self, _: &PeerId) {}
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(&mut self, peer: PeerId, _: ConnectionId, result: PingResult) {
2019-04-16 15:57:29 +02:00
self.events.push_front(PingEvent { peer, result })
}
2020-07-27 20:27:33 +00:00
fn poll(&mut self, _: &mut Context<'_>, _: &mut impl PollParameters)
-> Poll<NetworkBehaviourAction<Void, PingEvent>>
2019-04-16 15:57:29 +02:00
{
if let Some(e) = self.events.pop_back() {
Poll::Ready(NetworkBehaviourAction::GenerateEvent(e))
2019-04-16 15:57:29 +02:00
} else {
Poll::Pending
}
}
}