use raft::{Client, Config, Error, RawNode, State};
struct Database {
raft: RawNode<StateMachine>,
}
impl Database {
fn new(config: Config) -> Result<Database, Error> {
let raft = RawNode::new(config, StateMachine)?;
Ok(Database { raft })
}
fn get(&self, key: String) -> Option<String> {
self.raft.apply_command(GetCommand { key }, false).unwrap()
}
fn set(&self, key: String, value: String) -> Result<(), Error> {
self.raft.apply_command(SetCommand { key, value }, true)
}
}
struct StateMachine {
kv_store: HashMap<String, String>,
}
impl raft::StateMachine for StateMachine {
type Command = Command;
type Query = Query;
type Response = Response;
fn apply_command(&mut self, cmd: Command) {
match cmd {
SetCommand { key, value } => {
self.kv_store.insert(key, value);
}
GetCommand { key } => {}
}
}
fn query(&self, query: Query) -> Option<Response> {
match query {
GetQuery { key } => self.kv_store.get(&key).map(Response::Value),
}
}
}
enum Command {
SetCommand { key: String, value: String },
GetCommand { key: String },
}
enum Query {
GetQuery { key: String }
}
enum Response {
Value(String),
}
This defines a Database struct which wraps a RawNode from the raft crate. The StateMachine implements the raft::StateMachine trait to handle commands and queries. Commands like SetCommand are replicated using Raft consensus, while reads are served locally.