reth_eth_wire/pinger.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
use crate::errors::PingerError;
use std::{
pin::Pin,
task::{Context, Poll},
time::Duration,
};
use tokio::time::{Instant, Interval, Sleep};
use tokio_stream::Stream;
/// The pinger is a state machine that is created with a maximum number of pongs that can be
/// missed.
#[derive(Debug)]
pub(crate) struct Pinger {
/// The timer used for the next ping.
ping_interval: Interval,
/// The timer used for the next ping.
timeout_timer: Pin<Box<Sleep>>,
/// The timeout duration for each ping.
timeout: Duration,
/// Keeps track of the state
state: PingState,
}
// === impl Pinger ===
impl Pinger {
/// Creates a new [`Pinger`] with the given ping interval duration,
/// and timeout duration.
pub(crate) fn new(ping_interval: Duration, timeout_duration: Duration) -> Self {
let now = Instant::now();
let timeout_timer = tokio::time::sleep(timeout_duration);
Self {
state: PingState::Ready,
ping_interval: tokio::time::interval_at(now + ping_interval, ping_interval),
timeout_timer: Box::pin(timeout_timer),
timeout: timeout_duration,
}
}
/// Mark a pong as received, and transition the pinger to the `Ready` state if it was in the
/// `WaitingForPong` state. Unsets the sleep timer.
pub(crate) fn on_pong(&mut self) -> Result<(), PingerError> {
match self.state {
PingState::Ready => Err(PingerError::UnexpectedPong),
PingState::WaitingForPong => {
self.state = PingState::Ready;
self.ping_interval.reset();
Ok(())
}
PingState::TimedOut => {
// if we receive a pong after timeout then we also reset the state, since the
// connection was kept alive after timeout
self.state = PingState::Ready;
self.ping_interval.reset();
Ok(())
}
}
}
/// Returns the current state of the pinger.
pub(crate) const fn state(&self) -> PingState {
self.state
}
/// Polls the state of the pinger and returns whether a new ping needs to be sent or if a
/// previous ping timed out.
pub(crate) fn poll_ping(
&mut self,
cx: &mut Context<'_>,
) -> Poll<Result<PingerEvent, PingerError>> {
match self.state() {
PingState::Ready => {
if self.ping_interval.poll_tick(cx).is_ready() {
self.timeout_timer.as_mut().reset(Instant::now() + self.timeout);
self.state = PingState::WaitingForPong;
return Poll::Ready(Ok(PingerEvent::Ping))
}
}
PingState::WaitingForPong => {
if self.timeout_timer.is_elapsed() {
self.state = PingState::TimedOut;
return Poll::Ready(Ok(PingerEvent::Timeout))
}
}
PingState::TimedOut => {
// we treat continuous calls while in timeout as pending, since the connection is
// not yet terminated
return Poll::Pending
}
};
Poll::Pending
}
}
impl Stream for Pinger {
type Item = Result<PingerEvent, PingerError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.get_mut().poll_ping(cx).map(Some)
}
}
/// This represents the possible states of the pinger.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PingState {
/// There are no pings in flight, or all pings have been responded to, and we are ready to send
/// a ping at a later point.
Ready,
/// We have sent a ping and are waiting for a pong, but the peer has missed n pongs.
WaitingForPong,
/// The peer has failed to respond to a ping.
TimedOut,
}
/// The element type produced by a [`Pinger`], representing either a new
/// [`Ping`](super::P2PMessage::Ping)
/// message to send, or an indication that the peer should be timed out.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum PingerEvent {
/// A new [`Ping`](super::P2PMessage::Ping) message should be sent.
Ping,
/// The peer should be timed out.
Timeout,
}
#[cfg(test)]
mod tests {
use super::*;
use futures::StreamExt;
#[tokio::test]
async fn test_ping_timeout() {
let interval = Duration::from_millis(300);
// we should wait for the interval to elapse and receive a pong before the timeout elapses
let mut pinger = Pinger::new(interval, Duration::from_millis(20));
assert_eq!(pinger.next().await.unwrap().unwrap(), PingerEvent::Ping);
pinger.on_pong().unwrap();
assert_eq!(pinger.next().await.unwrap().unwrap(), PingerEvent::Ping);
tokio::time::sleep(interval).await;
assert_eq!(pinger.next().await.unwrap().unwrap(), PingerEvent::Timeout);
pinger.on_pong().unwrap();
assert_eq!(pinger.next().await.unwrap().unwrap(), PingerEvent::Ping);
}
}