rabia_core/error.rs
1//! # Error Types
2//!
3//! Comprehensive error handling for the Rabia consensus protocol.
4
5use crate::{BatchId, NodeId, PhaseId};
6use thiserror::Error;
7
8/// Error types that can occur during Rabia consensus operations.
9///
10/// This enum covers all possible error conditions that can arise
11/// during consensus protocol execution, from network failures to
12/// state corruption. Each error includes context information to
13/// aid in debugging and recovery.
14///
15/// # Error Categories
16///
17/// - **Network Errors**: Communication failures between nodes
18/// - **Persistence Errors**: Storage and retrieval failures
19/// - **State Machine Errors**: Application-level execution failures
20/// - **Consensus Errors**: Protocol-level violations or failures
21/// - **Resource Errors**: Missing nodes, phases, or batches
22/// - **Integrity Errors**: Checksum mismatches and corruption
23/// - **Timeout Errors**: Operations that exceed time limits
24///
25/// # Examples
26///
27/// ```rust
28/// use rabia_core::RabiaError;
29///
30/// let error = RabiaError::network("Connection refused");
31/// if error.is_retryable() {
32/// println!("This error can be retried");
33/// }
34/// ```
35#[derive(Error, Debug)]
36pub enum RabiaError {
37 /// Network communication failure between nodes
38 #[error("Network error: {message}")]
39 Network { message: String },
40
41 /// Persistent storage operation failure
42 #[error("Persistence error: {message}")]
43 Persistence { message: String },
44
45 /// State machine execution failure
46 #[error("State machine error: {message}")]
47 StateMachine { message: String },
48
49 /// Consensus protocol violation or failure
50 #[error("Consensus error: {message}")]
51 Consensus { message: String },
52
53 /// Referenced node was not found in the cluster
54 #[error("Node {node_id} not found")]
55 NodeNotFound { node_id: NodeId },
56
57 /// Referenced consensus phase was not found
58 #[error("Phase {phase_id} not found")]
59 PhaseNotFound { phase_id: PhaseId },
60
61 /// Referenced command batch was not found
62 #[error("Batch {batch_id} not found")]
63 BatchNotFound { batch_id: BatchId },
64
65 /// Invalid state machine transition attempted
66 #[error("Invalid state transition from {from} to {to}")]
67 InvalidStateTransition { from: String, to: String },
68
69 /// Insufficient nodes available to form a quorum
70 #[error("Quorum not available: {current}/{required} nodes")]
71 QuorumNotAvailable { current: usize, required: usize },
72
73 /// Data integrity check failed due to checksum mismatch
74 #[error("Checksum mismatch: expected {expected}, got {actual}")]
75 ChecksumMismatch { expected: u32, actual: u32 },
76
77 /// State corruption detected in persistent storage
78 #[error("State corruption detected: {details}")]
79 StateCorruption { details: String },
80
81 /// Incomplete write operation detected
82 #[error("Partial write detected: {details}")]
83 PartialWrite { details: String },
84
85 /// Operation exceeded its timeout limit
86 #[error("Timeout occurred: {operation}")]
87 Timeout { operation: String },
88
89 /// JSON serialization/deserialization failure
90 #[error("Serialization error: {0}")]
91 Serialization(#[from] serde_json::Error),
92
93 /// File system or network I/O failure
94 #[error("IO error: {0}")]
95 Io(#[from] std::io::Error),
96
97 /// Unexpected internal error
98 #[error("Internal error: {message}")]
99 Internal { message: String },
100}
101
102/// Type alias for Results in the Rabia consensus system.
103///
104/// This type alias provides a convenient way to return results that may
105/// contain Rabia-specific errors without having to specify the error type
106/// each time.
107///
108/// # Examples
109///
110/// ```rust
111/// use rabia_core::{Result, RabiaError};
112///
113/// fn consensus_operation() -> Result<String> {
114/// Ok("Success".to_string())
115/// }
116/// ```
117pub type Result<T> = std::result::Result<T, RabiaError>;
118
119impl RabiaError {
120 /// Creates a new network error with the given message.
121 ///
122 /// # Examples
123 ///
124 /// ```rust
125 /// use rabia_core::RabiaError;
126 ///
127 /// let error = RabiaError::network("Connection timeout");
128 /// ```
129 pub fn network(message: impl Into<String>) -> Self {
130 Self::Network {
131 message: message.into(),
132 }
133 }
134
135 /// Creates a new persistence error with the given message.
136 ///
137 /// # Examples
138 ///
139 /// ```rust
140 /// use rabia_core::RabiaError;
141 ///
142 /// let error = RabiaError::persistence("Disk full");
143 /// ```
144 pub fn persistence(message: impl Into<String>) -> Self {
145 Self::Persistence {
146 message: message.into(),
147 }
148 }
149
150 /// Creates a new state machine error with the given message.
151 ///
152 /// # Examples
153 ///
154 /// ```rust
155 /// use rabia_core::RabiaError;
156 ///
157 /// let error = RabiaError::state_machine("Invalid command");
158 /// ```
159 pub fn state_machine(message: impl Into<String>) -> Self {
160 Self::StateMachine {
161 message: message.into(),
162 }
163 }
164
165 /// Creates a new consensus error with the given message.
166 ///
167 /// # Examples
168 ///
169 /// ```rust
170 /// use rabia_core::RabiaError;
171 ///
172 /// let error = RabiaError::consensus("Phase mismatch");
173 /// ```
174 pub fn consensus(message: impl Into<String>) -> Self {
175 Self::Consensus {
176 message: message.into(),
177 }
178 }
179
180 /// Creates a new internal error with the given message.
181 ///
182 /// # Examples
183 ///
184 /// ```rust
185 /// use rabia_core::RabiaError;
186 ///
187 /// let error = RabiaError::internal("Unexpected condition");
188 /// ```
189 pub fn internal(message: impl Into<String>) -> Self {
190 Self::Internal {
191 message: message.into(),
192 }
193 }
194
195 /// Creates a new timeout error with the given operation.
196 ///
197 /// # Examples
198 ///
199 /// ```rust
200 /// use rabia_core::RabiaError;
201 ///
202 /// let error = RabiaError::timeout("consensus operation");
203 /// ```
204 pub fn timeout(operation: impl Into<String>) -> Self {
205 Self::Timeout {
206 operation: operation.into(),
207 }
208 }
209
210 /// Creates a new serialization error with the given message.
211 ///
212 /// # Examples
213 ///
214 /// ```rust
215 /// use rabia_core::RabiaError;
216 ///
217 /// let error = RabiaError::serialization("Invalid JSON");
218 /// ```
219 pub fn serialization(message: impl Into<String>) -> Self {
220 Self::Internal {
221 message: format!("Serialization error: {}", message.into()),
222 }
223 }
224
225 /// Determines if this error condition is potentially recoverable.
226 ///
227 /// Retryable errors are typically transient conditions that may
228 /// resolve themselves with time or retry attempts. Non-retryable
229 /// errors usually indicate permanent failures or programming errors.
230 ///
231 /// # Returns
232 ///
233 /// `true` if the error might be resolved by retrying the operation
234 ///
235 /// # Examples
236 ///
237 /// ```rust
238 /// use rabia_core::RabiaError;
239 ///
240 /// let network_error = RabiaError::network("Connection timeout");
241 /// assert!(network_error.is_retryable());
242 ///
243 /// let corruption_error = RabiaError::ChecksumMismatch {
244 /// expected: 123,
245 /// actual: 456,
246 /// };
247 /// assert!(!corruption_error.is_retryable());
248 /// ```
249 pub fn is_retryable(&self) -> bool {
250 matches!(
251 self,
252 Self::Network { .. } | Self::Timeout { .. } | Self::QuorumNotAvailable { .. }
253 )
254 }
255}