foundationdb/recipes/leader_election/
errors.rs

1// Copyright 2024 foundationdb-rs developers
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! Error types returned by leader-election operations.
9
10use crate::tuple::PackError;
11use crate::{FdbBindingError, FdbError, RetryableError};
12use std::fmt;
13
14/// Leader-election-specific errors.
15///
16/// [`LeaderElectionError::Fdb`] retains the underlying FoundationDB error for
17/// the caller's transaction runner to classify. The other variants identify
18/// invalid local configuration, unsupported durable data, or a protocol limit.
19#[derive(Debug)]
20pub enum LeaderElectionError {
21    /// The durable state could not be decoded or violated a protocol invariant.
22    ///
23    /// Do not treat this as an unowned state. It can indicate corrupt data, an
24    /// incompatible schema, or data written outside this recipe.
25    InvalidState(String),
26    /// A [`ParticipantId`](super::ParticipantId) was empty.
27    ///
28    /// Empty text cannot distinguish a participating process incarnation.
29    InvalidParticipantId,
30    /// A [`ParticipantId`](super::ParticipantId) exceeds the encoded-size limit.
31    ///
32    /// The limit includes tuple encoding and NUL escaping, so it guarantees the
33    /// complete durable election state fits below FoundationDB's value limit.
34    ParticipantIdTooLarge {
35        /// Tuple-encoded participant ID size in bytes.
36        encoded_size: usize,
37        /// Maximum supported tuple-encoded participant ID size in bytes.
38        limit: usize,
39    },
40    /// A configured lease duration was zero.
41    ///
42    /// A zero duration would make every local validity interval immediately
43    /// expired, so [`super::LeaderElection::new`] rejects it.
44    InvalidLeaseDuration,
45    /// The durable revision reached `u64::MAX`.
46    ///
47    /// No further ownership transition can create a strictly newer fencing
48    /// rank in this election subspace.
49    RevisionExhausted,
50    /// An underlying FoundationDB read, write, or commit-related error occurred.
51    ///
52    /// Inspect the source error and let the enclosing transaction runner apply
53    /// its normal retry policy where appropriate.
54    Fdb(FdbError),
55    /// A transaction-runner error occurred.
56    Binding(Box<FdbBindingError>),
57    /// Failed to encode or decode the recipe's durable tuple state.
58    ///
59    /// On reads this can accompany malformed or incompatible durable data; on
60    /// writes it prevents staging the requested state change.
61    PackError(PackError),
62}
63
64impl fmt::Display for LeaderElectionError {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        match self {
67            Self::InvalidState(message) => write!(f, "Invalid leader election state: {message}"),
68            Self::InvalidParticipantId => write!(f, "Participant ID must not be empty"),
69            Self::ParticipantIdTooLarge {
70                encoded_size,
71                limit,
72            } => write!(
73                f,
74                "Encoded participant ID is {encoded_size} bytes, above the {limit}-byte limit"
75            ),
76            Self::InvalidLeaseDuration => write!(f, "Lease duration must not be zero"),
77            Self::RevisionExhausted => write!(f, "Leader-election revision is exhausted"),
78            Self::Fdb(error) => write!(f, "Database error: {error}"),
79            Self::Binding(error) => write!(f, "Retry loop error: {error}"),
80            Self::PackError(error) => write!(f, "Pack error: {error:?}"),
81        }
82    }
83}
84
85impl std::error::Error for LeaderElectionError {
86    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
87        match self {
88            Self::Fdb(error) => Some(error),
89            Self::Binding(error) => Some(error.as_ref()),
90            Self::PackError(error) => Some(error),
91            Self::InvalidState(_)
92            | Self::InvalidParticipantId
93            | Self::ParticipantIdTooLarge { .. }
94            | Self::InvalidLeaseDuration
95            | Self::RevisionExhausted => None,
96        }
97    }
98}
99
100impl From<FdbError> for LeaderElectionError {
101    fn from(error: FdbError) -> Self {
102        Self::Fdb(error)
103    }
104}
105
106impl From<FdbBindingError> for LeaderElectionError {
107    fn from(error: FdbBindingError) -> Self {
108        Self::Binding(Box::new(error))
109    }
110}
111
112impl From<PackError> for LeaderElectionError {
113    fn from(error: PackError) -> Self {
114        Self::PackError(error)
115    }
116}
117
118/// The `source()` chain exposes wrapped FoundationDB errors, so the default
119/// retry decision is transparent to `Database::run`.
120impl RetryableError for LeaderElectionError {}
121
122/// Result type for [`super::LeaderElection`] operations.
123pub type Result<T> = std::result::Result<T, LeaderElectionError>;
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128    use crate::{RetryDecision, RetryableError};
129
130    #[test]
131    fn fdb_errors_are_retry_transparent() {
132        let error = LeaderElectionError::Fdb(FdbError::from_code(1020));
133
134        assert!(matches!(error.retry_decision(), RetryDecision::Fdb(_)));
135    }
136
137    #[test]
138    fn runner_errors_are_preserved() {
139        let error = LeaderElectionError::from(FdbBindingError::ReferenceToTransactionKept);
140
141        assert!(matches!(error, LeaderElectionError::Binding(_)));
142    }
143
144    #[test]
145    fn runner_error_source_chain_is_retry_transparent() {
146        let error = LeaderElectionError::from(FdbBindingError::from(FdbError::from_code(1020)));
147
148        assert!(matches!(error.retry_decision(), RetryDecision::Fdb(_)));
149    }
150}