openraft 0.10.2

Advanced Raft consensus
Documentation
use openraft_macros::since;
use peel_off::Peel;

use crate::RaftTypeConfig;
use crate::StorageError;
use crate::errors::Fatal;
use crate::errors::ForwardToLeader;
use crate::errors::Infallible;
use crate::try_as_ref::TryAsRef;

/// Error returned by Raft API methods.
///
/// `RaftError` wraps either a [`Fatal`] error indicating the Raft node has stopped (due to storage
/// failure, panic, or shutdown), or an API-specific error `E` (such as [`ClientWriteError`] or
/// [`LinearizableReadError`]).
///
/// # Usage
///
/// Match on the error variant to handle appropriately:
///
/// ```ignore
/// match raft.client_write(req).await {
///     Ok(resp) => { /* handle response */ },
///     Err(RaftError::APIError(e)) => {
///         // Handle API error (e.g., forward to leader)
///     }
///     Err(RaftError::Fatal(f)) => {
///         // Raft stopped - initiate shutdown
///     }
/// }
/// ```
///
/// [`ClientWriteError`]: crate::errors::ClientWriteError
/// [`LinearizableReadError`]: crate::errors::LinearizableReadError
#[since(
    version = "0.10.2",
    change = "the accessors, `TryAsRef` and `Peel` no longer require `E: Debug`"
)]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum RaftError<C, E = Infallible>
where C: RaftTypeConfig
{
    /// API-specific error returned by Raft API methods.
    #[error(transparent)]
    APIError(E),

    /// Fatal error indicating the Raft node has stopped.
    // Reset serde trait bound for C but not for E
    #[cfg_attr(feature = "serde", serde(bound = ""))]
    #[error(transparent)]
    Fatal(#[from] Fatal<C>),
}

impl<C> RaftError<C, Infallible>
where C: RaftTypeConfig
{
    /// Return the [`Fatal`] error that this `RaftError` holds.
    ///
    /// This method exists only when the API error type is [`Infallible`], an enum without values,
    /// so the `APIError` variant cannot occur: every such `RaftError` holds a `Fatal` error, and
    /// the conversion always succeeds.
    #[since(version = "0.10.0")]
    pub fn unwrap_fatal(self) -> Fatal<C> {
        self.into_fatal().unwrap()
    }
}

impl<C, E> RaftError<C, E>
where C: RaftTypeConfig
{
    /// Return a reference to Self::APIError.
    pub fn api_error(&self) -> Option<&E> {
        match self {
            RaftError::APIError(e) => Some(e),
            RaftError::Fatal(_) => None,
        }
    }

    /// Try to convert self to APIError.
    pub fn into_api_error(self) -> Option<E> {
        match self {
            RaftError::APIError(e) => Some(e),
            RaftError::Fatal(_) => None,
        }
    }

    /// Return a reference to Self::Fatal.
    pub fn fatal(&self) -> Option<&Fatal<C>> {
        match self {
            RaftError::APIError(_) => None,
            RaftError::Fatal(f) => Some(f),
        }
    }

    /// Try to convert self to Fatal error.
    pub fn into_fatal(self) -> Option<Fatal<C>> {
        match self {
            RaftError::APIError(_) => None,
            RaftError::Fatal(f) => Some(f),
        }
    }

    /// Return the leader hint of the API error, if it has one.
    ///
    /// It returns what [`TryAsRef<ForwardToLeader>`] of `E` returns. The hint tells only where to
    /// send the next request; check the API error before retrying. A [`ClientWriteError`] has a
    /// hint both for [`ForwardToLeader`], which rejected the write before its entry was appended,
    /// and for [`LogEntryDiscarded`], whose write may still commit.
    ///
    /// [`TryAsRef<ForwardToLeader>`]: crate::TryAsRef
    /// [`ClientWriteError`]: crate::errors::ClientWriteError
    /// [`ForwardToLeader`]: crate::errors::ClientWriteError::ForwardToLeader
    /// [`LogEntryDiscarded`]: crate::errors::ClientWriteError::LogEntryDiscarded
    pub fn forward_to_leader(&self) -> Option<&ForwardToLeader<C>>
    where E: TryAsRef<ForwardToLeader<C>> {
        match self {
            RaftError::APIError(api_err) => api_err.try_as_ref(),
            RaftError::Fatal(_) => None,
        }
    }

    /// Convert the API error into a [`ForwardToLeader`], if the [`TryInto`] of `E` accepts it.
    ///
    /// Any other error is dropped, and `None` is returned; read the error first if its outcome
    /// matters. Of a [`ClientWriteError`], only [`ClientWriteError::ForwardToLeader`] converts.
    /// [`ClientWriteError::LogEntryDiscarded`] does not, as its write may still commit, so this
    /// returns `None` for it while [`forward_to_leader()`](Self::forward_to_leader) returns its
    /// hint.
    ///
    /// [`ClientWriteError`]: crate::errors::ClientWriteError
    /// [`ClientWriteError::ForwardToLeader`]: crate::errors::ClientWriteError::ForwardToLeader
    /// [`ClientWriteError::LogEntryDiscarded`]: crate::errors::ClientWriteError::LogEntryDiscarded
    pub fn into_forward_to_leader(self) -> Option<ForwardToLeader<C>>
    where E: TryInto<ForwardToLeader<C>> {
        match self {
            RaftError::APIError(api_err) => api_err.try_into().ok(),
            RaftError::Fatal(_) => None,
        }
    }
}

impl<C, E> TryAsRef<ForwardToLeader<C>> for RaftError<C, E>
where
    C: RaftTypeConfig,
    E: TryAsRef<ForwardToLeader<C>>,
{
    fn try_as_ref(&self) -> Option<&ForwardToLeader<C>> {
        self.forward_to_leader()
    }
}

impl<C, E> From<StorageError<C>> for RaftError<C, E>
where C: RaftTypeConfig
{
    fn from(se: StorageError<C>) -> Self {
        RaftError::Fatal(Fatal::from(se))
    }
}

/// Peel off `Fatal`, leaving the API error `E` as the residual.
impl<C, E> Peel for RaftError<C, E>
where C: RaftTypeConfig
{
    type Peeled = Fatal<C>;
    type Residual = E;

    fn peel(self) -> Result<E, Fatal<C>> {
        match self {
            RaftError::APIError(e) => Ok(e),
            RaftError::Fatal(f) => Err(f),
        }
    }
}

#[cfg(test)]
mod tests {
    use peel_off::Peel;

    use crate::engine::testing::UTConfig;
    use crate::errors::Fatal;
    use crate::errors::ForwardToLeader;
    use crate::errors::RaftError;
    use crate::try_as_ref::TryAsRef;

    type C = UTConfig;

    /// An API error that implements no `Debug`.
    struct NoDebug(u64);

    /// A non-`Debug` API error with a leader hint, like `ClientWriteError`: both variants have a
    /// hint, and only `Forward` converts into a [`ForwardToLeader`].
    enum NoDebugHint {
        Forward(ForwardToLeader<C>),
        Discarded(ForwardToLeader<C>),
    }

    impl TryAsRef<ForwardToLeader<C>> for NoDebugHint {
        fn try_as_ref(&self) -> Option<&ForwardToLeader<C>> {
            match self {
                NoDebugHint::Forward(f) | NoDebugHint::Discarded(f) => Some(f),
            }
        }
    }

    impl TryFrom<NoDebugHint> for ForwardToLeader<C> {
        type Error = NoDebugHint;

        fn try_from(e: NoDebugHint) -> Result<Self, NoDebugHint> {
            match e {
                NoDebugHint::Forward(f) => Ok(f),
                discarded => Err(discarded),
            }
        }
    }

    /// The accessors return the payload they hold when the API error implements no `Debug`.
    #[test]
    fn test_accessors_without_debug() {
        let api = || RaftError::<C, NoDebug>::APIError(NoDebug(3));
        assert_eq!(Some(3), api().api_error().map(|e| e.0));
        assert_eq!(Some(3), api().into_api_error().map(|e| e.0));
        assert_eq!(None, api().fatal());
        assert_eq!(None, api().into_fatal());

        let fatal = || RaftError::<C, NoDebug>::Fatal(Fatal::Panicked);
        assert_eq!(None, fatal().api_error().map(|e| e.0));
        assert_eq!(None, fatal().into_api_error().map(|e| e.0));
        assert_eq!(Some(&Fatal::Panicked), fatal().fatal());
        assert_eq!(Some(Fatal::Panicked), fatal().into_fatal());
    }

    /// `Peel` separates the fatal error from a non-`Debug` API error, also when `peel_off` peels a
    /// `Result` that holds the error.
    #[test]
    fn test_peel_without_debug() {
        let api = RaftError::<C, NoDebug>::APIError(NoDebug(3));
        assert_eq!(Ok(3), api.peel().map(|e| e.0));
        let fatal = RaftError::<C, NoDebug>::Fatal(Fatal::Panicked);
        assert_eq!(Err(Fatal::Panicked), fatal.peel().map(|e| e.0));

        let ok: Result<u64, RaftError<C, NoDebug>> = Ok(5);
        assert_eq!(Ok(Ok(5)), ok.peel().map(|r| r.map_err(|e| e.0)));
        let api: Result<u64, RaftError<C, NoDebug>> = Err(RaftError::APIError(NoDebug(3)));
        assert_eq!(Ok(Err(3)), api.peel().map(|r| r.map_err(|e| e.0)));
        let fatal: Result<u64, RaftError<C, NoDebug>> = Err(RaftError::Fatal(Fatal::Panicked));
        assert_eq!(Err(Fatal::Panicked), fatal.peel().map(|r| r.map_err(|e| e.0)));
    }

    /// A non-`Debug` API error keeps the forwarding distinction: both variants lend their hint,
    /// and only `Forward` converts into one.
    #[test]
    fn test_forward_to_leader_without_debug() {
        let hint = ForwardToLeader::<C>::new(2, ());
        let forward = || RaftError::<C, NoDebugHint>::APIError(NoDebugHint::Forward(hint.clone()));
        let discarded = || RaftError::<C, NoDebugHint>::APIError(NoDebugHint::Discarded(hint.clone()));

        assert_eq!(Some(&hint), forward().forward_to_leader());
        assert_eq!(Some(&hint), forward().try_as_ref());
        assert_eq!(Some(hint.clone()), forward().into_forward_to_leader());

        assert_eq!(Some(&hint), discarded().forward_to_leader());
        assert_eq!(Some(&hint), discarded().try_as_ref());
        assert_eq!(None, discarded().into_forward_to_leader());

        let fatal = || RaftError::<C, NoDebugHint>::Fatal(Fatal::Panicked);
        assert_eq!(None, fatal().forward_to_leader());
        assert_eq!(None, fatal().into_forward_to_leader());
    }
}