raft_state.rs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. }
  23. impl<Command> RaftState<Command> {
  24. pub fn create(peer_size: usize, me: Peer) -> Self {
  25. RaftState {
  26. current_term: Term(0),
  27. voted_for: None,
  28. log: LogArray::create(),
  29. commit_index: 0,
  30. last_applied: 0,
  31. next_index: vec![1; peer_size],
  32. match_index: vec![0; peer_size],
  33. current_step: vec![0; peer_size],
  34. state: State::Follower,
  35. leader_id: me,
  36. }
  37. }
  38. }
  39. impl<Command: Clone> RaftState<Command> {
  40. pub fn persisted_state(&self) -> PersistedRaftState<Command> {
  41. self.into()
  42. }
  43. }
  44. impl<Command> RaftState<Command> {
  45. pub fn is_leader(&self) -> bool {
  46. self.state == State::Leader
  47. }
  48. }