process_request_vote.rs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. use crate::{Raft, RequestVoteArgs, RequestVoteReply, State};
  2. // Command must be
  3. // 1. clone: they are copied to the persister.
  4. // 2. serialize: they are converted to bytes to persist.
  5. impl<Command: Clone + serde::Serialize> Raft<Command> {
  6. pub fn process_request_vote(
  7. &self,
  8. args: RequestVoteArgs,
  9. ) -> RequestVoteReply {
  10. // Note: do not change this to `let _ = ...`.
  11. let _guard = self.daemon_env.for_scope();
  12. let mut rf = self.inner_state.lock();
  13. let term = rf.current_term;
  14. #[allow(clippy::comparison_chain)]
  15. if args.term < term {
  16. return RequestVoteReply {
  17. term,
  18. vote_granted: false,
  19. };
  20. } else if args.term > term {
  21. rf.current_term = args.term;
  22. rf.voted_for = None;
  23. rf.state = State::Follower;
  24. self.election.reset_election_timer();
  25. self.persister.save_state(rf.persisted_state().into());
  26. }
  27. let voted_for = rf.voted_for;
  28. let last_log = rf.log.last_index_term();
  29. if (voted_for.is_none() || voted_for == Some(args.candidate_id))
  30. && (args.last_log_term > last_log.term
  31. || (args.last_log_term == last_log.term
  32. && args.last_log_index >= last_log.index))
  33. {
  34. rf.voted_for = Some(args.candidate_id);
  35. // It is possible that we have set a timer above when updating the
  36. // current term. It does not hurt to update the timer again.
  37. // We do need to persist, though.
  38. self.election.reset_election_timer();
  39. self.persister.save_state(rf.persisted_state().into());
  40. RequestVoteReply {
  41. term: args.term,
  42. vote_granted: true,
  43. }
  44. } else {
  45. RequestVoteReply {
  46. term: args.term,
  47. vote_granted: false,
  48. }
  49. }
  50. }
  51. }