openraft 0.10.2

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

use rand::RngExt;

use crate::AsyncRuntime;
use crate::Config;
use crate::RaftTypeConfig;
use crate::engine::time_state;
use crate::type_config::alias::AsyncRuntimeOf;

/// Config for Engine
#[derive(Clone, Debug)]
#[derive(PartialEq, Eq)]
pub(crate) struct EngineConfig<C: RaftTypeConfig> {
    /// The id of this node.
    pub(crate) id: C::NodeId,

    /// The maximum number of applied logs to keep before purging.
    pub(crate) max_in_snapshot_log_to_keep: u64,

    /// The minimal number of applied logs to purge in a batch.
    pub(crate) purge_batch_size: u64,

    pub(crate) allow_log_reversion: bool,

    /// Inclusive lower bound for a sampled election timeout, in milliseconds.
    pub(crate) election_timeout_min: u64,

    /// Exclusive upper bound for a sampled election timeout, in milliseconds.
    pub(crate) election_timeout_max: u64,

    pub(crate) timer_config: time_state::Config,

    pub(crate) enable_leader_restore: bool,

    /// Duration of each alternating suppression or send phase after the Leader lease expires.
    pub(crate) quorum_loss_probe_interval: Option<Duration>,

    /// Whether relaxed reads are enabled, so that the leader lets followers apply only what it has
    /// applied.
    pub(crate) enable_relaxed_read: bool,
}

impl<C> EngineConfig<C>
where C: RaftTypeConfig
{
    pub(crate) fn new(id: C::NodeId, config: &Config) -> Self {
        let mut this = Self {
            id,
            max_in_snapshot_log_to_keep: config.max_in_snapshot_log_to_keep,
            purge_batch_size: config.purge_batch_size,
            allow_log_reversion: config.get_allow_log_reversion(),
            election_timeout_min: config.election_timeout_min,
            election_timeout_max: config.election_timeout_max,

            timer_config: time_state::Config {
                election_timeout: Duration::ZERO, // sampled below
                // Double the duration, not the milliseconds: twice a large `u64` overflows.
                smaller_log_timeout: Duration::from_millis(config.election_timeout_max) * 2,
                leader_lease: Duration::from_millis(config.election_timeout_max),
            },

            enable_leader_restore: config.enable_leader_restore(),
            quorum_loss_probe_interval: config.quorum_loss_probe_interval.map(Duration::from_millis),
            enable_relaxed_read: config.get_enable_relaxed_read(),
        };
        this.resample_election_timeout();
        this
    }

    #[allow(dead_code)]
    pub(crate) fn new_default(id: C::NodeId) -> Self {
        Self {
            id,
            max_in_snapshot_log_to_keep: 1000,
            purge_batch_size: 256,
            allow_log_reversion: false,
            election_timeout_min: 150,
            election_timeout_max: 300,
            timer_config: time_state::Config::default(),
            enable_leader_restore: true,
            quorum_loss_probe_interval: None,
            enable_relaxed_read: false,
        }
    }

    /// Sample the timeout that gates the next election campaign.
    pub(crate) fn resample_election_timeout(&mut self) {
        let election_timeout =
            AsyncRuntimeOf::<C>::thread_rng().random_range(self.election_timeout_min..self.election_timeout_max);
        self.timer_config.election_timeout = Duration::from_millis(election_timeout);
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::EngineConfig;
    use crate::Config;
    use crate::engine::testing::UTConfig;

    /// The delay after seeing a greater log is twice the election timeout maximum, also for a
    /// maximum whose millisecond count doubled does not fit in `u64`.
    #[test]
    fn test_smaller_log_timeout_is_twice_the_election_timeout_max() {
        let half = u64::MAX / 2;
        for max in [300, half, half + 1, u64::MAX] {
            let min = max / 2;
            let config = Config {
                election_timeout_min: min,
                election_timeout_max: max,
                ..Default::default()
            }
            .validate()
            .unwrap();

            let timers = EngineConfig::<UTConfig>::new(0, &config).timer_config;

            assert_eq!(
                u128::from(max) * 2,
                timers.smaller_log_timeout.as_millis(),
                "max: {max}"
            );
            assert_eq!(Duration::from_millis(max), timers.leader_lease, "max: {max}");

            let sampled = timers.election_timeout.as_millis();
            assert!(
                u128::from(min) <= sampled && sampled < u128::from(max),
                "max: {max}, sampled: {sampled}"
            );
        }
    }
}