raft_state.rs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. use crate::{
  2. log_array::LogArray, persister::PersistedRaftState, Index, Peer, Term,
  3. };
  4. #[derive(Copy, Clone, Debug, Eq, PartialEq)]
  5. pub(crate) enum State {
  6. Follower,
  7. Candidate,
  8. // TODO: add PreVote
  9. Leader,
  10. }
  11. pub(crate) struct RaftState<Command> {
  12. pub current_term: Term,
  13. pub voted_for: Option<Peer>,
  14. pub log: LogArray<Command>,
  15. pub commit_index: Index,
  16. pub last_applied: Index,
  17. pub next_index: Vec<Index>,
  18. pub match_index: Vec<Index>,
  19. pub current_step: Vec<i64>,
  20. pub state: State,
  21. pub leader_id: Peer,
  22. // Index of the first commit of each term as the leader.
  23. pub sentinel_commit_index: Index,
  24. }
  25. impl<Command: Default> RaftState<Command> {
  26. pub fn create(peer_size: usize, me: Peer) -> Self {
  27. RaftState {
  28. current_term: Term(0),
  29. voted_for: None,
  30. log: crate::log_array::LogArray::create(),
  31. commit_index: 0,
  32. last_applied: 0,
  33. next_index: vec![1; peer_size],
  34. match_index: vec![0; peer_size],
  35. current_step: vec![0; peer_size],
  36. state: State::Follower,
  37. leader_id: me,
  38. sentinel_commit_index: 0,
  39. }
  40. }
  41. }
  42. impl<Command: Clone> RaftState<Command> {
  43. pub fn persisted_state(&self) -> PersistedRaftState<Command> {
  44. self.into()
  45. }
  46. }
  47. impl<Command> RaftState<Command> {
  48. pub fn is_leader(&self) -> bool {
  49. self.state == State::Leader
  50. }
  51. }