raft_state.rs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. use std::time::Instant;
  2. use crate::{
  3. log_array::LogArray, persister::PersistedRaftState, Index, Peer, Term,
  4. };
  5. #[derive(Copy, Clone, Debug, Eq, PartialEq)]
  6. pub(crate) enum State {
  7. Follower(FollowerData),
  8. Prevote,
  9. Candidate,
  10. Leader,
  11. }
  12. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
  13. pub(crate) struct FollowerData {
  14. last_heartbeat: Option<Instant>,
  15. }
  16. #[repr(align(64))]
  17. pub(crate) struct RaftState<Command> {
  18. pub current_term: Term,
  19. pub voted_for: Option<Peer>,
  20. pub log: LogArray<Command>,
  21. pub commit_index: Index,
  22. pub match_index: Vec<Index>,
  23. pub state: State,
  24. pub leader_id: Peer,
  25. }
  26. impl<Command> RaftState<Command> {
  27. pub fn create(peer_size: usize, me: Peer) -> Self {
  28. RaftState {
  29. current_term: Term(0),
  30. voted_for: None,
  31. log: LogArray::create(),
  32. commit_index: 0,
  33. match_index: vec![0; peer_size],
  34. state: State::Follower(FollowerData::default()),
  35. leader_id: me,
  36. }
  37. }
  38. pub fn step_down(&mut self) {
  39. self.voted_for = None;
  40. self.state = State::Follower(FollowerData::default());
  41. }
  42. pub fn meet_leader(&mut self, leader_id: Peer) {
  43. self.leader_id = leader_id;
  44. self.state = State::Follower(FollowerData {
  45. last_heartbeat: Some(Instant::now()),
  46. })
  47. }
  48. pub fn last_heartbeat(&self) -> Option<Instant> {
  49. let State::Follower(follower_data) = &self.state else {
  50. return None;
  51. };
  52. return follower_data.last_heartbeat;
  53. }
  54. }
  55. impl<Command: Clone> RaftState<Command> {
  56. pub fn persisted_state(&self) -> PersistedRaftState<Command> {
  57. self.into()
  58. }
  59. }
  60. impl<Command> RaftState<Command> {
  61. pub fn is_leader(&self) -> bool {
  62. self.state == State::Leader
  63. }
  64. }