raft_rust/raft/state.rs
1// 日志条目与索引
2use super::{Entry, Index};
3// 统一 Error/Result
4use crate::error::Result;
5
6/// 由 Raft 管理的状态机。
7///
8/// 写命令经 `apply` 在所有节点上复制并应用;读命令经 `read` 只在领导者执行。
9pub trait State: Send {
10 /// 返回状态机中最后已应用的日志索引。
11 fn get_applied_index(&self) -> Index;
12
13 /// 将一条日志条目应用到状态机,并返回客户端结果。
14 fn apply(&mut self, entry: Entry) -> Result<Vec<u8>>;
15
16 /// 在状态机中执行读命令,并返回客户端结果。不得修改状态。
17 fn read(&self, command: Vec<u8>) -> Result<Vec<u8>>;
18
19 /// 导出快照字节(含足以恢复的完整状态)。
20 fn snapshot(&self) -> Result<Vec<u8>> {
21 // 默认无快照内容
22 Ok(Vec::new())
23 // 当前作用域结束
24 }
25
26 /// 从快照恢复,并将 applied 索引设为 `index`。
27 fn restore(&mut self, _snapshot: &[u8], _index: Index) -> Result<()> {
28 // 默认空实现成功返回
29 Ok(())
30 // 当前作用域结束
31 }
32// 当前作用域结束
33}