Skip to main content

simraft_core/
error.rs

1//! Domain error types for simraft-core.
2//!
3//! Every error carries concrete diagnostic context (the offending values,
4//! the required bounds, the conflicting fields), never a bare variant
5//! name. See invariant E-01 in docs/INVARIANTS.md.
6
7use crate::ids::{LogIndex, NodeId, Term};
8use core::fmt;
9
10/// A cluster configuration failed validation.
11///
12/// Returned by `Config::validate` and by `Node::new`. Each variant names
13/// the fields involved and the values that conflict, so an operator can
14/// fix the configuration without reading the validation code.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum ConfigError {
17    /// A field that must be positive was zero.
18    ZeroValue {
19        /// The field that was zero.
20        field: &'static str,
21    },
22    /// `min_election_timeout` is below `10 * heartbeat_interval`.
23    ElectionTimeoutRatio {
24        /// The configured minimum election timeout, in ticks.
25        min_election_timeout: u64,
26        /// The configured heartbeat interval, in ticks.
27        heartbeat_interval: u64,
28        /// The smallest legal minimum election timeout for this heartbeat
29        /// interval, in ticks.
30        required_min: u64,
31    },
32    /// `max_election_timeout` is below `2 * min_election_timeout`.
33    ElectionRangeRatio {
34        /// The configured minimum election timeout, in ticks.
35        min_election_timeout: u64,
36        /// The configured maximum election timeout, in ticks.
37        max_election_timeout: u64,
38        /// The smallest legal maximum election timeout, in ticks.
39        required_min_max: u64,
40    },
41    /// `max_election_timeout` does not exceed `min_election_timeout`, so
42    /// the randomized election window is empty.
43    ElectionRangeOrder {
44        /// The configured minimum election timeout, in ticks.
45        min_election_timeout: u64,
46        /// The configured maximum election timeout, in ticks.
47        max_election_timeout: u64,
48    },
49    /// A proposed cluster configuration has no voters.
50    EmptyVoters,
51    /// A node was listed in both `voters` and `learners`.
52    OverlappingMember {
53        /// The node that appeared in both sets.
54        node: NodeId,
55    },
56}
57
58impl fmt::Display for ConfigError {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        match self {
61            Self::ZeroValue { field } => {
62                write!(f, "config field {field} must be positive, got 0")
63            }
64            Self::ElectionTimeoutRatio {
65                min_election_timeout,
66                heartbeat_interval,
67                required_min,
68            } => write!(
69                f,
70                "min_election_timeout {min_election_timeout} is below 10 * heartbeat_interval \
71                 {heartbeat_interval}; required minimum is {required_min}"
72            ),
73            Self::ElectionRangeRatio {
74                min_election_timeout,
75                max_election_timeout,
76                required_min_max,
77            } => write!(
78                f,
79                "max_election_timeout {max_election_timeout} is below 2 * min_election_timeout \
80                 {min_election_timeout}; required minimum is {required_min_max}"
81            ),
82            Self::ElectionRangeOrder {
83                min_election_timeout,
84                max_election_timeout,
85            } => write!(
86                f,
87                "max_election_timeout {max_election_timeout} must exceed \
88                 min_election_timeout {min_election_timeout}"
89            ),
90            Self::EmptyVoters => {
91                write!(f, "cluster configuration must keep at least one voter")
92            }
93            Self::OverlappingMember { node } => {
94                write!(
95                    f,
96                    "node {node} cannot be both a voter and a learner in the same configuration"
97                )
98            }
99        }
100    }
101}
102
103impl std::error::Error for ConfigError {}
104
105/// A protocol-level rejection with the deciding values named.
106///
107/// The request was well formed but the protocol rules forbid it in
108/// the current state. Every variant names the values that decided
109/// the rejection (invariant E-01, docs/ARCHITECTURE.md section 13).
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub enum ProtocolError {
112    /// A configuration change was proposed while an earlier one is
113    /// still uncommitted (invariant M-01).
114    ConfigChangePending {
115        /// The log index of the newest, still uncommitted config entry.
116        last_config_index: LogIndex,
117        /// The leader's commit index when the change was rejected.
118        commit_index: LogIndex,
119    },
120    /// A configuration change was proposed before the leader's
121    /// current-term `NoOp` entry committed (invariant M-02).
122    LeaderNoopUncommitted {
123        /// The index of the leader's election `NoOp` entry.
124        noop_index: LogIndex,
125        /// The leader's commit index when the change was rejected.
126        commit_index: LogIndex,
127    },
128    /// A learner was proposed for promotion before it had replicated
129    /// through the leader's commit index (invariant M-04).
130    LearnerNotCaughtUp {
131        /// The learner proposed for promotion.
132        node: NodeId,
133        /// The learner's match index on the leader.
134        match_index: LogIndex,
135        /// The index the learner must reach before promotion.
136        required: LogIndex,
137    },
138    /// An `AddLearner` or `PromoteVoter` named a node that is already
139    /// a voter.
140    AlreadyVoter {
141        /// The node named by the change.
142        node: NodeId,
143    },
144    /// A `PromoteVoter` named a node that is not a learner.
145    NotLearner {
146        /// The node named by the change.
147        node: NodeId,
148    },
149    /// A change named a node that is not a member in either role.
150    NotMember {
151        /// The node named by the change.
152        node: NodeId,
153    },
154    /// A `RemoveVoter` named the last remaining voter; a cluster may
155    /// shrink to one voter, never to none.
156    LastVoterRemoval {
157        /// The node named by the change.
158        node: NodeId,
159    },
160    /// A client proposal arrived while the leader's uncommitted tail
161    /// already held `Config::max_uncommitted_entries` entries.
162    TooManyUncommitted {
163        /// The number of uncommitted entries currently in the log.
164        uncommitted: usize,
165        /// The configured maximum uncommitted entries.
166        limit: usize,
167    },
168}
169
170impl fmt::Display for ProtocolError {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        match self {
173            Self::ConfigChangePending {
174                last_config_index,
175                commit_index,
176            } => write!(
177                f,
178                "config change rejected: entry at {last_config_index} is still \
179                 uncommitted (commit {commit_index})"
180            ),
181            Self::LeaderNoopUncommitted {
182                noop_index,
183                commit_index,
184            } => write!(
185                f,
186                "config change rejected: leader NoOp at {noop_index} has not \
187                 committed (commit {commit_index})"
188            ),
189            Self::LearnerNotCaughtUp {
190                node,
191                match_index,
192                required,
193            } => write!(
194                f,
195                "learner {node} cannot be promoted: match {match_index} is below \
196                 the required {required}"
197            ),
198            Self::AlreadyVoter { node } => {
199                write!(f, "node {node} is already a voter")
200            }
201            Self::NotLearner { node } => {
202                write!(f, "node {node} is not a learner")
203            }
204            Self::NotMember { node } => {
205                write!(f, "node {node} is not a cluster member")
206            }
207            Self::LastVoterRemoval { node } => {
208                write!(
209                    f,
210                    "removing node {node} would leave the cluster with no voters"
211                )
212            }
213            Self::TooManyUncommitted { uncommitted, limit } => {
214                write!(
215                    f,
216                    "proposal rejected: {uncommitted} uncommitted entries reach \
217                     max_uncommitted_entries limit {limit}"
218                )
219            }
220        }
221    }
222}
223
224impl std::error::Error for ProtocolError {}
225
226/// A snapshot transfer failed. The variant names the snapshot identity
227/// and the offsets that decided the failure (docs/ARCHITECTURE.md
228/// section 13).
229#[derive(Debug, Clone, PartialEq, Eq)]
230pub enum SnapshotError {
231    /// A chunk arrived at an offset other than the number of bytes
232    /// already buffered for its snapshot identity (invariant N-02).
233    ChunkOffset {
234        /// The snapshot's last included index.
235        last_included_index: LogIndex,
236        /// The snapshot's last included term.
237        last_included_term: Term,
238        /// The offset the follower was ready to accept.
239        expected_offset: u64,
240        /// The offset the chunk actually carried.
241        received_offset: u64,
242    },
243}
244
245impl fmt::Display for SnapshotError {
246    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247        match self {
248            Self::ChunkOffset {
249                last_included_index,
250                last_included_term,
251                expected_offset,
252                received_offset,
253            } => write!(
254                f,
255                "snapshot chunk for ({last_included_index}, {last_included_term}) \
256                 arrived at offset {received_offset}, expected offset {expected_offset}"
257            ),
258        }
259    }
260}
261
262impl std::error::Error for SnapshotError {}