openraft 0.10.2

Advanced Raft consensus
Documentation
use std::time::Duration;

use futures_util::Stream;
use futures_util::StreamExt;

use crate::OptionalSend;
use crate::RaftTypeConfig;
use crate::core::heartbeat::errors::HeartbeatFailure;
use crate::core::heartbeat::event::HeartbeatEvent;
use crate::core::heartbeat::failure_log::FailureLog;
use crate::network::NetStreamAppend;
use crate::network::RPCOption;
use crate::raft::AppendEntriesRequest;
use crate::raft::AppendError;
use crate::raft::AppendResult;
use crate::type_config::TypeConfigExt;
use crate::type_config::alias::CommittedVoteOf;

/// Sends one heartbeat to one target, and logs whether it got a reply in time.
///
/// It borrows the fields of the `HeartbeatWorker` that one heartbeat needs.
pub(crate) struct HeartbeatSend<'a, C, N>
where
    C: RaftTypeConfig,
    N: NetStreamAppend<C>,
{
    pub(crate) network: &'a mut N,

    /// The vote of the leader that sends the heartbeat.
    pub(crate) leader_vote: &'a CommittedVoteOf<C>,

    /// The heartbeat interval: a heartbeat without a response within it counts as failed.
    pub(crate) interval: Duration,

    pub(crate) log: FailureLog<'a, C>,
}

impl<C, N> HeartbeatSend<'_, C, N>
where
    C: RaftTypeConfig,
    N: NetStreamAppend<C>,
{
    /// Sends `heartbeat`, and returns its reply if one arrived.
    ///
    /// The heartbeat fails when the network fails it, when its response stream ends without a
    /// response, and when no response arrives within `interval`. A heartbeat without a response in
    /// time keeps running, and its reply is returned when it arrives late. Nothing cuts it short
    /// before its response, not even a stop of the worker: `call()` describes the errors that
    /// dropping it would cause.
    pub(crate) async fn send(self, heartbeat: &HeartbeatEvent<C>) -> Option<AppendResult<C>> {
        let Self {
            network,
            leader_vote,
            interval,
            mut log,
        } = self;

        let request = AppendEntriesRequest {
            vote: leader_vote.clone().into_vote(),
            // Use last known matching log id as prev_log_id to detect follower state reversion.
            // prev_log_id == None does not conflict.
            //
            // Fail test `t99_issue_1500_heartbeat_cause_reversion_panic` by changing the
            // following line to `prev_log_id = heartbeat.cluster_committed.clone()`.
            prev_log_id: heartbeat.matching.clone(),
            leader_commit: heartbeat.cluster_committed.clone(),
            entries: vec![],
        };

        // `stream::iter()` over an array is `Unpin`, so the one-request input needs no
        // `Box::pin()` and no allocation.
        let input = futures_util::stream::iter([request]);
        let sent_at = C::now();

        // `log.id` and `log.target` are copied references, so the call does not borrow `log`, which
        // counts the failure at the deadline while the call runs on.
        let call = Self::call(network, log.id, log.target, input, RPCOption::new(interval));
        let mut call = std::pin::pin!(call);

        // The deadline only counts the heartbeat as failed. The call is polled until it completes,
        // because dropping it before its response stream ends makes the target's server close the
        // connection, see `call()`.
        match C::timeout(interval, call.as_mut()).await {
            Ok(result) => log.ended(result),
            Err(_elapsed) => {
                log.failed(HeartbeatFailure::Timeout(interval));
                let result = call.await;
                log.ended_late(result, C::now() - sent_at, interval)
            }
        }
    }

    /// Opens the response stream of one heartbeat and reads it until it ends.
    ///
    /// A transport may return more than one response, so all of them are read, and the one that
    /// matters most is returned: a higher vote, then a conflict, then a success. When no response
    /// arrives, it returns why, for the caller to log.
    ///
    /// # Why the stream is read to its end
    ///
    /// The caller polls the returned future until it completes, even after the heartbeat's
    /// deadline or a stop of the worker, and the future reads the stream until it ends. Dropping
    /// either earlier cancels the request in flight, and a transport over HTTP/2, such as tonic,
    /// then resets the request's stream with `RST_STREAM`. A server on the `h2` crate, as tonic's
    /// is, counts the reset streams that it has received but not accepted yet, and closes the
    /// connection with `GOAWAY` when more of them wait than its limit, 20 by default. They pile up
    /// at a server that stalls, such as a stopped process: when it resumes, it finds one for each
    /// heartbeat dropped meanwhile, and `h2::proto::streams::recv` logs at warn level:
    ///
    /// ```text
    /// recv_reset; remotely-reset pending-accept streams reached limit (20)
    /// ```
    ///
    /// Every request still in flight on that connection then fails, for every Raft group that
    /// shares it. A tonic client gets a `Status` that displays as, wrapped here:
    ///
    /// ```text
    /// code: 'Some resource has been exhausted', message: "h2 protocol error: http2 error",
    /// source: tonic::transport::Error(Transport, hyper::Error(Http2,
    /// Error { kind: GoAway(b"too_many_resets", ENHANCE_YOUR_CALM, Remote) }))
    /// ```
    ///
    /// It waits as long as it takes for the first response or error, and drops the stream early in
    /// two cases only: at an error, and `option.hard_ttl()` after a response if the stream has not
    /// ended by then. The request has ended or been answered by then, so the target's server has
    /// accepted its stream, and the reset does not count toward that limit.
    async fn call<S>(
        network: &mut N,
        id: &C::NodeId,
        target: &C::NodeId,
        input: S,
        option: RPCOption,
    ) -> Result<AppendResult<C>, HeartbeatFailure<C>>
    where
        S: Stream<Item = AppendEntriesRequest<C>> + OptionalSend + Unpin + 'static,
    {
        let interval = option.hard_ttl();
        let mut output = network.stream_append(input, option).await.map_err(HeartbeatFailure::Rpc)?;

        let mut reply: Option<AppendResult<C>> = None;
        loop {
            let next = match reply {
                None => output.next().await,
                Some(_) => match C::timeout(interval, output.next()).await {
                    Ok(next) => next,
                    Err(_elapsed) => {
                        tracing::warn!("id={} target={} heartbeat responses did not end in time", id, target);
                        break;
                    }
                },
            };
            let result = match next {
                Some(Ok(result)) => result,
                Some(Err(error)) => {
                    let Some(reply) = reply else {
                        return Err(HeartbeatFailure::Rpc(error));
                    };
                    tracing::warn!(
                        "id={} target={} heartbeat response failed after a reply: {}",
                        id,
                        target,
                        error
                    );
                    return Ok(reply);
                }
                None => break,
            };

            if reply.as_ref().is_none_or(|kept| importance(&result) > importance(kept)) {
                reply = Some(result);
            }
        }
        reply.ok_or(HeartbeatFailure::NoResponse)
    }
}

/// How much a heartbeat response tells the leader: a higher vote ends its leadership, a conflict
/// reports a log without the matching entry, and a success only acknowledges it.
fn importance<C>(result: &AppendResult<C>) -> u8
where C: RaftTypeConfig {
    match result {
        Ok(_) => 0,
        Err(AppendError::Conflict { .. }) => 1,
        Err(AppendError::HigherVote(_)) => 2,
    }
}