Skip to main content

rabia_core/
persistence.rs

1use crate::state_machine::Snapshot;
2use crate::{PhaseId, Result};
3use async_trait::async_trait;
4use serde::{Deserialize, Serialize};
5
6/// Simple state structure for Rabia engine persistence.
7///
8/// This contains only the essential state information needed for Rabia consensus.
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct EngineState {
11    pub current_phase: PhaseId,
12    pub last_committed_phase: PhaseId,
13    pub snapshot: Option<Snapshot>,
14}
15
16impl EngineState {
17    pub fn new(
18        current_phase: PhaseId,
19        last_committed_phase: PhaseId,
20        snapshot: Option<Snapshot>,
21    ) -> Self {
22        Self {
23            current_phase,
24            last_committed_phase,
25            snapshot,
26        }
27    }
28
29    /// Serialize the engine state to bytes for persistence.
30    pub fn to_bytes(&self) -> Result<Vec<u8>> {
31        serde_json::to_vec(self).map_err(|e| {
32            crate::RabiaError::serialization(format!("Failed to serialize engine state: {}", e))
33        })
34    }
35
36    /// Deserialize engine state from bytes.
37    pub fn from_bytes(data: &[u8]) -> Result<Self> {
38        serde_json::from_slice(data).map_err(|e| {
39            crate::RabiaError::serialization(format!("Failed to deserialize engine state: {}", e))
40        })
41    }
42}
43
44/// Simplified persistence layer for Rabia consensus protocol.
45///
46/// Rabia only needs to persist a single state value - the current SMR (State Machine Replication) state.
47/// This simplified interface removes the complexity of WAL, checkpoints, and versioning that was
48/// unnecessary for Rabia's consensus requirements.
49#[async_trait]
50pub trait PersistenceLayer: Send + Sync {
51    /// Save the current state to persistent storage.
52    ///
53    /// # Arguments
54    /// * `state` - The state data as bytes to persist
55    ///
56    /// # Returns
57    /// * `Ok(())` if the state was successfully saved
58    /// * `Err(RabiaError)` if the save operation failed
59    async fn save_state(&self, state: &[u8]) -> Result<()>;
60
61    /// Load the current state from persistent storage.
62    ///
63    /// # Returns
64    /// * `Ok(Some(state))` if state was found and loaded successfully  
65    /// * `Ok(None)` if no state exists (first startup)
66    /// * `Err(RabiaError)` if the load operation failed
67    async fn load_state(&self) -> Result<Option<Vec<u8>>>;
68}