1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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());
}
}