use std::collections::{BTreeMap, VecDeque};
use simraft_core::{
Action, ClientId, ClientResult, ClusterConfig, Config, EntryKind, Event, LogIndex, Node,
NodeId, PersistKind, Role,
};
struct Driver {
nodes: BTreeMap<NodeId, Node>,
queue: VecDeque<(NodeId, Event)>,
stores: BTreeMap<NodeId, BTreeMap<String, String>>,
committed: bool,
}
impl Driver {
fn new() -> Self {
let cfg = ClusterConfig::new([NodeId(1), NodeId(2), NodeId(3)], Vec::new())
.expect("config validates");
let mut nodes = BTreeMap::new();
let mut stores = BTreeMap::new();
for id in [1_u64, 2, 3] {
nodes.insert(
NodeId(id),
Node::new(NodeId(id), Config::default(), cfg.clone(), id * 11)
.expect("node builds"),
);
stores.insert(NodeId(id), BTreeMap::new());
}
Self {
nodes,
queue: VecDeque::new(),
stores,
committed: false,
}
}
fn handle(&mut self, source: NodeId, actions: Vec<Action>) {
for action in actions {
match action {
Action::Send { to, msg } => {
self.queue
.push_back((to, Event::Message { from: source, msg }));
}
Action::PersistHardState { .. } => {
self.queue.push_back((
source,
Event::Persisted {
kind: PersistKind::HardState,
up_to_index: LogIndex::ZERO,
},
));
}
Action::PersistEntries { .. } => {
let up_to = self
.nodes
.get(&source)
.expect("source exists")
.log()
.last_index();
self.queue.push_back((
source,
Event::Persisted {
kind: PersistKind::Entries,
up_to_index: up_to,
},
));
}
Action::Apply { entry, .. } => {
if let EntryKind::Command { payload, .. } = entry.kind {
let text = std::str::from_utf8(&payload).expect("payload is text");
let (key, value) = text.split_once('=').expect("payload is key=value");
self.stores
.get_mut(&source)
.expect("store exists")
.insert(key.to_owned(), value.to_owned());
}
}
Action::ClientResponse {
result: ClientResult::Committed,
..
} => {
self.committed = true;
}
_ => {}
}
}
}
fn step(&mut self, node: NodeId, event: Event) {
let actions = self.nodes.get_mut(&node).expect("node exists").step(event);
self.handle(node, actions);
}
fn drain(&mut self) {
while let Some((to, event)) = self.queue.pop_front() {
self.step(to, event);
}
}
fn leader(&self) -> Option<NodeId> {
self.nodes
.values()
.find(|node| node.stats().role == Role::Leader)
.and_then(|node| node.stats().leader)
}
}
fn main() {
let mut driver = Driver::new();
let mut now = 0_u64;
let leader = loop {
now += 100;
for id in [NodeId(1), NodeId(2), NodeId(3)] {
driver.step(id, Event::Tick { now });
driver.drain();
}
if let Some(leader) = driver.leader() {
break leader;
}
assert!(now < 20_000, "the cluster elects a leader");
};
let term = driver
.nodes
.get(&leader)
.expect("leader exists")
.stats()
.current_term;
println!("embed: {leader} leads at {term}");
driver.step(
leader,
Event::Propose {
client_id: ClientId(1),
seq: 1,
payload: b"color=blue".to_vec(),
},
);
driver.drain();
now += 100;
driver.step(leader, Event::Tick { now });
driver.drain();
assert!(driver.committed, "the write commits");
for id in [NodeId(1), NodeId(2), NodeId(3)] {
let value = driver
.stores
.get(&id)
.expect("store exists")
.get("color")
.expect("the key is applied");
assert_eq!(value, "blue", "every node applies the write");
}
println!("embed: wrote color=blue and read it back on all three nodes");
let stats = driver.nodes.get(&leader).expect("leader exists").stats();
println!(
"embed: leader stats role={:?} term={} leader={} commit={} applied={} \
last_log={} snapshot_base={} peers={}",
stats.role,
stats.current_term.0,
stats.leader.expect("a leader acknowledges itself"),
stats.commit_index.0,
stats.last_applied.0,
stats.last_log_index.0,
stats.snapshot_index.0,
stats.peers.len()
);
assert_eq!(stats.commit_index, LogIndex(2), "the NoOp and the write");
assert_eq!(stats.last_applied, LogIndex(2));
}