openraft 0.10.2

Advanced Raft consensus
Documentation
//! Trigger an action to RaftCore by an external caller.

use openraft_macros::since;

use crate::RaftTypeConfig;
use crate::batch::Batch;
use crate::core::raft_msg::external_command::ExternalCommand;
use crate::errors::AllowNextRevertError;
use crate::errors::Fatal;
use crate::raft::RaftInner;
use crate::type_config::TypeConfigExt;
use crate::type_config::alias::BatchOf;
use crate::type_config::alias::LogIdOf;
use crate::type_config::alias::VoteOf;

/// Submit administrative requests to RaftCore.
///
/// It is created with [`Raft::trigger()`].
///
/// # Submission and completion
///
/// Except for [`Self::allow_next_revert`], these methods return `Ok(())` once the request is
/// accepted into the node's bounded API channel. If the channel is full, submission waits for
/// capacity. A failed send returns a [`Fatal`] error.
///
/// Successful submission does not mean the action has started or finished. RaftCore may skip
/// the action, and these calls do not report failures that occur after submission. To observe
/// the state you need, use [`Raft::wait()`] or [`Raft::metrics()`]. Metrics show the node's state,
/// not whether a particular request caused it.
///
/// [`Self::allow_next_revert`] also waits for RaftCore's permission-update result, not for any
/// subsequent replication reset.
///
/// # Examples
///
/// Submit a manual election, heartbeat, snapshot build, or log purge request:
///
/// ```no_run
/// # use openraft::Raft;
/// # use openraft::RaftTypeConfig;
/// # use openraft::errors::Fatal;
/// # use openraft::storage::RaftStateMachine;
/// #
/// # async fn example<C, SM>(raft: &Raft<C, SM>) -> Result<(), Fatal<C>>
/// # where
/// #     C: RaftTypeConfig,
/// #     SM: RaftStateMachine<C>,
/// # {
/// raft.trigger().elect(false).await?;
/// raft.trigger().heartbeat().await?;
/// raft.trigger().snapshot().await?;
///
/// // Request a purge up to and including log index 100.
/// raft.trigger().purge_log(100).await?;
/// # Ok(())
/// # }
/// ```
///
/// [`Raft::trigger()`]: crate::Raft::trigger
/// [`Raft::wait()`]: crate::Raft::wait
/// [`Raft::metrics()`]: crate::Raft::metrics
pub struct Trigger<'r, C>
where C: RaftTypeConfig
{
    raft_inner: &'r RaftInner<C>,
}

impl<'r, C> Trigger<'r, C>
where C: RaftTypeConfig
{
    pub(in crate::raft) fn new(raft_inner: &'r RaftInner<C>) -> Self {
        Self { raft_inner }
    }

    /// Queue a request for a manual election.
    ///
    /// When RaftCore handles the request, it does nothing if this node is already a leader or
    /// neither its effective nor its committed membership allows it to campaign.
    ///
    /// With `pre_vote = false`, an eligible node skips Pre-Vote, increments its term, and votes
    /// for itself. The term increases even if the node cannot win, which may make a healthy
    /// leader in a lower term step down.
    ///
    /// With `pre_vote = true`, a node whose local leader lease is still valid sends no Pre-Vote
    /// requests and leaves its vote unchanged. Otherwise, it probes without incrementing its
    /// own term and starts a real election only if a quorum would grant the vote. A peer's
    /// rejection can still report a higher vote, which the node can adopt and persist to catch
    /// up to a higher term without starting a real election.
    ///
    /// Pre-Vote is selected per call and does not require [`Config::enable_pre_vote`].
    ///
    /// Disabling automatic elections with
    /// [`raft.runtime_config().elect(false)`](crate::raft::RuntimeConfigHandle::elect) does not
    /// affect this request.
    ///
    /// To wait for a particular node to become leader, use
    /// [`Wait::current_leader`](crate::metrics::Wait::current_leader).
    ///
    /// [`Config::enable_pre_vote`]: crate::Config::enable_pre_vote
    pub async fn elect(&self, pre_vote: bool) -> Result<(), Fatal<C>> {
        self.raft_inner.send_external_command(ExternalCommand::Elect { pre_vote }).await
    }

    /// Queue a request for a heartbeat.
    ///
    /// RaftCore skips the heartbeat if the node is not the leader, is transferring leadership,
    /// or is in a [quorum-loss quiet period](field@crate::Config::quorum_loss_probe_interval).
    /// The [minimum heartbeat interval] still applies to each target.
    ///
    /// Disabling idle heartbeats with
    /// [`raft.runtime_config().heartbeat(false)`](crate::raft::RuntimeConfigHandle::heartbeat)
    /// does not affect this request.
    ///
    /// To observe quorum contact, watch [`RaftMetrics::last_quorum_acked`], which can also advance
    /// through ordinary replication.
    ///
    /// [minimum heartbeat interval]: field@crate::Config::heartbeat_min_interval
    /// [`RaftMetrics::last_quorum_acked`]: crate::RaftMetrics::last_quorum_acked
    pub async fn heartbeat(&self) -> Result<(), Fatal<C>> {
        self.raft_inner.send_external_command(ExternalCommand::Heartbeat).await
    }

    /// Queue one timer check and return once it is queued.
    ///
    /// RaftCore runs the heartbeat check that the heartbeat timer triggers, and an election check:
    /// a leader whose heartbeat is due sends one heartbeat, and a node whose election is due starts
    /// it. The check reads the current time when RaftCore handles it. A check before a deadline
    /// does nothing, and a check after several missed heartbeat intervals sends one heartbeat.
    ///
    /// Unlike [`Self::elect`] and [`Self::heartbeat`], the check honors `enable_elect` and
    /// `enable_heartbeat`. It runs whether `enable_tick` is on or off.
    ///
    /// With [`Config::enable_tick`] set to `false`, an application can drive the heartbeats of
    /// many nodes from one timer of its own. A due heartbeat is noticed only when a check runs, so
    /// the caller's interval adds to the heartbeat latency. Elections do not need this call: they
    /// run on their own election timer, controlled by [`Config::enable_elect`], whether
    /// `enable_tick` is on or off, and the election check is kept for backward compatibility. The
    /// heartbeat timer of a leader fires once per [`Config::heartbeat_interval`]. This call waits
    /// while the API channel of this node is full.
    ///
    /// Returns error when RaftCore has [`Fatal`] error, e.g., shut down or having storage error.
    ///
    /// [`Config::enable_tick`]: crate::Config::enable_tick
    /// [`Config::enable_elect`]: crate::Config::enable_elect
    /// [`Config::heartbeat_interval`]: crate::Config::heartbeat_interval
    #[since(version = "0.10.1")]
    pub async fn tick(&self) -> Result<(), Fatal<C>> {
        self.raft_inner.send_external_command(ExternalCommand::Tick).await
    }

    /// Queue a request to build a snapshot.
    ///
    /// If a build is already outstanding when RaftCore handles the request, no second build is
    /// started. Otherwise the state machine can decline the request by returning `None` from
    /// [`try_create_snapshot_builder`], which is called with `force = false`.
    ///
    /// To observe a snapshot that includes the log entry you need, watch
    /// [`RaftMetrics::snapshot`](crate::RaftMetrics::snapshot) for that log ID or a later one.
    ///
    /// [`try_create_snapshot_builder`]: crate::storage::RaftStateMachine::try_create_snapshot_builder
    pub async fn snapshot(&self) -> Result<(), Fatal<C>> {
        self.raft_inner.send_external_command(ExternalCommand::Snapshot).await
    }

    /// Queue a request to purge logs up to and including the given `upto` log index.
    ///
    /// Logs that are not included in a snapshot will **NOT** be purged.
    /// In such a scenario it will delete as many logs as possible.
    /// The [`max_in_snapshot_log_to_keep`] config is not taken into account
    /// when purging logs.
    ///
    /// To observe how far the purge has progressed, watch
    /// [`RaftMetrics::purged`](crate::RaftMetrics::purged).
    ///
    /// Openraft won't purge logs at once, e.g., it may be delayed by several seconds, because if it
    /// is a leader and a replication task has been replicating the logs to a follower, the logs
    /// can't be purged until the replication task is finished. A replication task that the node
    /// closed, as when it removes the target or stops leading, also delays the purge until the
    /// task has stopped.
    ///
    /// [`max_in_snapshot_log_to_keep`]: `crate::Config::max_in_snapshot_log_to_keep`
    pub async fn purge_log(&self, upto: u64) -> Result<(), Fatal<C>> {
        self.raft_inner.send_external_command(ExternalCommand::PurgeLog { upto }).await
    }

    /// Submit a command to inform RaftCore to transfer leadership to the specified node.
    ///
    /// By default, this also resets the target's active replication backoff. Set
    /// [`Config::reset_backoff_on_transfer_leader`] to `Some(false)` to disable the reset.
    ///
    /// While the transfer is pending, this node rejects new writes and linearizable reads with a
    /// forwarding error. Once the transfer deadline passes, an eligible source with automatic
    /// elections enabled can campaign again. The source can still report `Leader` and reject
    /// requests after the deadline.
    ///
    /// It returns once the request is queued, not when `to` has taken over. To learn the outcome,
    /// wait on the metrics; see
    /// [handing over leadership](crate::docs::cluster_control::leadership#handing-over-leadership)
    /// for the conditions that control recovery.
    ///
    /// If this node is not a Leader, it is just ignored.
    ///
    /// [`Config::reset_backoff_on_transfer_leader`]: crate::Config::reset_backoff_on_transfer_leader
    pub async fn transfer_leader(&self, to: C::NodeId) -> Result<(), Fatal<C>> {
        self.raft_inner
            .send_external_command(ExternalCommand::TriggerTransferLeader { to, removal: None })
            .await
    }

    /// Request to reset the current replication backoff for the specified nodes.
    ///
    /// A reset ends the current or next wait of the backoff that is active when it arrives.
    /// A backoff that starts later is not affected. Snapshot transfer retries are not affected
    /// either.
    ///
    /// If no node ids are specified, this applies to all replication targets.
    #[since(version = "0.10.0")]
    pub async fn reset_backoff(&self, to: impl IntoIterator<Item = C::NodeId>) -> Result<(), Fatal<C>> {
        let to = BatchOf::<C, _>::of(to);
        self.raft_inner.send_external_command(ExternalCommand::ResetBackoff { to }).await
    }

    /// Set or clear the current leader's one-shot permission to reset replication progress for
    /// `to` when it detects log reversion.
    ///
    /// Passing `allow = true` sets the permission; `allow = false` clears it. Neither value
    /// resets progress immediately. The permission belongs to the current leader's progress
    /// entry for `to` and does not carry across leadership changes.
    ///
    /// If a later conflict shows that `to` no longer holds a previously matched log entry, the
    /// leader can reset progress and search again for a matching entry. The reset clears the
    /// one-shot permission; a conflict that does not cause a reset leaves it in place.
    /// [`Config::allow_log_reversion`] permits resets even when `allow = false`. Without either
    /// permission, the leader does not reset progress, and the reversion fails a debug assertion
    /// in builds with debug assertions enabled.
    ///
    /// ### Result
    ///
    /// The outer [`Fatal`] error means that sending the request or receiving the response
    /// failed. Otherwise, the inner result reports what happened when RaftCore handled the
    /// request:
    ///
    /// - `Ok(())`: Only the permission was updated. This does not acknowledge a reset or recovery.
    /// - [`AllowNextRevertError::ForwardToLeader`]: This node was not the leader.
    /// - [`AllowNextRevertError::NodeNotFound`]: `to` had no replication progress entry.
    ///
    /// ### Production Considerations
    ///
    /// This one-shot permission only lets the current leader reset its replication progress for
    /// the target when it detects log reversion. It does not check whether future quorums will
    /// preserve committed data, nor does it restore the target's lost durable vote or log history.
    ///
    /// Neither this permission nor [`Config::allow_log_reversion`] makes it safe to erase a
    /// node's data and restart it under the same ID. See the [recovery FAQ][wipe-one-node] for
    /// the narrow conditions under which erasing one voter cannot lose committed data.
    ///
    /// [`Config::allow_log_reversion`]: `crate::Config::allow_log_reversion`
    /// [wipe-one-node]: crate::docs::faq#can-i-wipe-out-the-data-of-one-node-and-wait-for-the-leader-to-replicate-all-data-to-it-again
    pub async fn allow_next_revert(
        &self,
        to: &C::NodeId,
        allow: bool,
    ) -> Result<Result<(), AllowNextRevertError<C>>, Fatal<C>> {
        let (tx, rx) = C::oneshot();
        self.raft_inner
            .send_external_command(ExternalCommand::AllowNextRevert {
                to: to.clone(),
                allow,
                tx,
            })
            .await?;

        let res: Result<(), AllowNextRevertError<C>> = self.raft_inner.recv_msg(rx).await?;

        Ok(res)
    }

    /// Queue a request to recalculate the internal server state (Leader/Follower/Learner) based on
    /// the vote and membership config.
    ///
    /// Usually this method is not used at all: the internal server state is always recalculated
    /// automatically. The only exception is the step down of a Leader that is removed from the
    /// membership config: openraft allows such a removed node to keep acting as a Leader. By
    /// default it is stepped down automatically (see
    /// [`Config::removed_leader_step_down`](crate::Config::removed_leader_step_down));
    /// with the automated step down disabled, the application or the administrator decides when
    /// to revert it to a learner by calling this method.
    ///
    /// `vote` and `membership_log_id` are the expected current vote and the expected log id of
    /// the effective membership config: the refresh is dropped if either differs from the
    /// current state when the command is handled, so that a delayed command can not cause an
    /// unexpected refresh. A `None` skips the corresponding check: with both `None` the server
    /// state is refreshed unconditionally.
    ///
    /// To step down a removed Leader, call this method after the membership config that removes
    /// it is committed: a Leader keeps leading while that membership config is not yet
    /// committed, because it is the one responsible for replicating it.
    ///
    /// Returns error when RaftCore has [`Fatal`] error, e.g., shut down or having storage error.
    #[since(version = "0.10.0")]
    pub async fn refresh_server_state(
        &self,
        vote: Option<VoteOf<C>>,
        membership_log_id: Option<LogIdOf<C>>,
    ) -> Result<(), Fatal<C>> {
        let cmd = ExternalCommand::RefreshServerState {
            vote,
            membership_log_id,
        };
        self.raft_inner.send_external_command(cmd).await
    }
}