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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
//! Defines various error types.

use std::convert::Infallible;
use std::sync::Arc;

use thiserror::Error;

use crate::append::AppendError;
use crate::invocation::AbstainOf;
use crate::invocation::CoordNumOf;
use crate::invocation::Invocation;
use crate::invocation::LogEntryIdOf;
use crate::invocation::LogEntryOf;
use crate::invocation::NayOf;

/// Reason spawning a node failed.
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum SpawnError<E> {
    /// Failed to start task to maintain `State`.
    #[error("executor raised an error")]
    ExecutorError(E),

    /// A decoration's [`wrap` method][crate::decoration::Decoration::wrap]
    /// failed.
    #[error("a node decoration raised an error")]
    Decoration(#[source] Box<dyn std::error::Error + Send + Sync + 'static>),
}

/// Reason node snapshot couldn't be affirmed.
#[derive(Debug, Error)]
pub enum AffirmSnapshotError {
    /// The given snapshot is unknown.
    #[error("unknown snapshot")]
    Unknown,

    /// Node is shut down.
    #[error("node is shut down")]
    ShutDown,
}

/// Reason node snapshot couldn't be installed.
#[derive(Debug, Error)]
pub enum InstallSnapshotError {
    /// The node's current state is more up-to-date.
    #[error("snapshot is outdated")]
    Outdated,

    /// Node is shut down.
    #[error("node is shut down")]
    ShutDown,
}

/// Reason node's state couldn't be read.
#[derive(Debug, Error)]
pub enum ReadStaleError {
    /// Node doesn't have state.
    #[error("node is disoriented")]
    Disoriented,

    /// Node is shut down.
    #[error("node is shut down")]
    ShutDown,
}

/// Reason preparing round for proposals failed.
#[derive(Error)]
pub enum PrepareError<I: Invocation> {
    /// Node abstained from voting.
    #[error("promise war deliberately withheld")]
    Abstained(AbstainOf<I>),

    /// Another node es running for leader with a greater coordination number.
    #[error("conflicting promise")]
    Supplanted(CoordNumOf<I>),

    /// Round is already settled.
    #[error("round already converged")]
    Converged(CoordNumOf<I>, Option<(CoordNumOf<I>, Arc<LogEntryOf<I>>)>),

    /// Node is in passive mode.
    #[error("node is passive")]
    Passive,

    /// Node is shut down.
    #[error("node is shut down")]
    ShutDown,
}

impl<I: Invocation> std::fmt::Debug for PrepareError<I> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PrepareError::Abstained(abstention) => f
                .debug_tuple("PrepareError::Abstained")
                .field(abstention)
                .finish(),
            PrepareError::Supplanted(coord_num) => f
                .debug_tuple("PrepareError::Supplanted")
                .field(coord_num)
                .finish(),
            PrepareError::Converged(coord_num, converged) => f
                .debug_tuple("PrepareError::Converged")
                .field(coord_num)
                .field(converged)
                .finish(),
            PrepareError::Passive => f.debug_tuple("PrepareError::Passive").finish(),
            PrepareError::ShutDown => f.debug_tuple("PrepareError::ShutDown").finish(),
        }
    }
}

impl<I: Invocation> From<PrepareError<I>> for AppendError<I> {
    fn from(e: PrepareError<I>) -> Self {
        match e {
            PrepareError::Abstained(reason) => AppendError::NoQuorum {
                abstentions: vec![reason],
                communication_errors: Vec::new(),
                rejections: Vec::new(),
            },
            PrepareError::Supplanted(_) => AppendError::Lost,
            PrepareError::Converged(_, log_entry) => AppendError::Converged {
                caught_up: log_entry.is_some(),
            },
            PrepareError::Passive => AppendError::Passive,
            PrepareError::ShutDown => AppendError::ShutDown,
        }
    }
}

/// A proposal could not be accepted.
#[derive(Error)]
pub enum AcceptError<I: Invocation> {
    /// Another node has become leader with a greater coordination number.
    #[error("conflicting promise")]
    Supplanted(CoordNumOf<I>),

    /// Round is already settled.
    #[error("round already converged")]
    Converged(CoordNumOf<I>, Option<(CoordNumOf<I>, Arc<LogEntryOf<I>>)>),

    /// Node is in passive mode.
    #[error("node is passive")]
    Passive,

    /// Node rejected the proposal.
    #[error("proposal was rejected")]
    Rejected(NayOf<I>),

    /// Node is shut down.
    #[error("node is shut down")]
    ShutDown,
}

impl<I: Invocation> std::fmt::Debug for AcceptError<I> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AcceptError::Supplanted(coord_num) => f
                .debug_tuple("AcceptError::Conflict")
                .field(coord_num)
                .finish(),
            AcceptError::Converged(coord_num, converged) => f
                .debug_tuple("AcceptError::Converged")
                .field(coord_num)
                .field(converged)
                .finish(),
            AcceptError::Passive => f.debug_tuple("AcceptError::Passive").finish(),
            AcceptError::Rejected(rejection) => f
                .debug_tuple("AcceptError::Rejected")
                .field(rejection)
                .finish(),
            AcceptError::ShutDown => f.debug_tuple("AcceptError::ShutDown").finish(),
        }
    }
}

impl<I: Invocation> From<AcceptError<I>> for AppendError<I> {
    fn from(e: AcceptError<I>) -> Self {
        match e {
            AcceptError::Supplanted(_) => AppendError::Lost,
            AcceptError::Converged(_, log_entry) => AppendError::Converged {
                caught_up: log_entry.is_some(),
            },
            AcceptError::Passive => AppendError::Passive,
            AcceptError::Rejected(reason) => AppendError::NoQuorum {
                abstentions: Vec::new(),
                communication_errors: Vec::new(),
                rejections: vec![reason],
            },
            AcceptError::ShutDown => AppendError::ShutDown,
        }
    }
}

/// Committing a log entry failed.
#[non_exhaustive]
#[derive(Error)]
pub enum CommitError<I: Invocation> {
    /// Node doesn't have state.
    #[error("node is disoriented")]
    Disoriented,

    /// The given id could not be resolved to a log entry.
    #[error("given log entry id is invalid")]
    InvalidEntryId(LogEntryIdOf<I>),

    /// Node is shut down.
    #[error("node is shut down")]
    ShutDown,
}

impl<I: Invocation> std::fmt::Debug for CommitError<I> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CommitError::Disoriented => f.debug_tuple("CommitError::Disoriented").finish(),
            CommitError::InvalidEntryId(entry_id) => f
                .debug_tuple("CommitError::InvalidEntryId")
                .field(entry_id)
                .finish(),
            CommitError::ShutDown => f.debug_tuple("CommitError::ShutDown").finish(),
        }
    }
}

impl<I: Invocation> From<CommitError<I>> for AppendError<I> {
    fn from(e: CommitError<I>) -> Self {
        match e {
            CommitError::Disoriented => AppendError::Disoriented,
            CommitError::InvalidEntryId(_) => unreachable!(),
            CommitError::ShutDown => AppendError::ShutDown,
        }
    }
}

/// Node doesn't have state.
#[derive(Clone, Copy, Debug, Error)]
#[error("node is disoriented")]
pub struct Disoriented;

/// Node is shut down.
#[derive(Clone, Copy, Debug, Error)]
#[error("node is shut down")]
pub struct ShutDown;

impl From<Infallible> for ShutDown {
    fn from(_: Infallible) -> Self {
        Self
    }
}

impl From<ShutDownOr<Infallible>> for ShutDown {
    fn from(_: ShutDownOr<Infallible>) -> Self {
        Self
    }
}

/// Node is shut down.
#[derive(Clone, Copy, Debug)]
pub enum ShutDownOr<E> {
    /// An event other than 'shut down' occured.
    Other(E),

    /// Node is shut down.
    ShutDown,
}

impl<E> ShutDownOr<E> {
    /// Applies the mapping function to the other event, if present.
    pub fn map<T, F: FnOnce(E) -> T>(self, f: F) -> ShutDownOr<T> {
        match self {
            ShutDownOr::Other(e) => ShutDownOr::Other(f(e)),
            ShutDownOr::ShutDown => ShutDownOr::ShutDown,
        }
    }

    /// Expect an event other than 'shut down' to have occured.
    ///
    /// Panics if a shut down occured.
    pub fn expect_other(self) -> E {
        match self {
            ShutDownOr::Other(e) => e,
            ShutDownOr::ShutDown => panic!("Node is unexpectedly shut down."),
        }
    }
}

impl<E> From<E> for ShutDownOr<E> {
    fn from(e: E) -> Self {
        ShutDownOr::Other(e)
    }
}