term_marker.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. use std::sync::Arc;
  2. use parking_lot::Mutex;
  3. use serde::Serialize;
  4. use crate::election::ElectionState;
  5. use crate::{Persister, RaftState, State, Term};
  6. /// A closure that updates the `Term` of the `RaftState`.
  7. #[derive(Clone)]
  8. pub(crate) struct TermMarker<Command> {
  9. rf: Arc<Mutex<RaftState<Command>>>,
  10. election: Arc<ElectionState>,
  11. persister: Arc<dyn Persister>,
  12. }
  13. impl<Command: Clone + Serialize> TermMarker<Command> {
  14. /// Create a `TermMarker` that can be passed to async tasks.
  15. pub fn create(
  16. rf: Arc<Mutex<RaftState<Command>>>,
  17. election: Arc<ElectionState>,
  18. persister: Arc<dyn Persister>,
  19. ) -> Self {
  20. Self {
  21. rf,
  22. election,
  23. persister,
  24. }
  25. }
  26. pub fn mark(&self, term: Term) {
  27. let mut rf = self.rf.lock();
  28. mark_term(&mut rf, &self.election, self.persister.as_ref(), term)
  29. }
  30. }
  31. /// Update the term of the `RaftState`.
  32. pub(crate) fn mark_term<Command: Clone + Serialize>(
  33. rf: &mut RaftState<Command>,
  34. election: &ElectionState,
  35. persister: &dyn Persister,
  36. term: Term,
  37. ) {
  38. if term > rf.current_term {
  39. rf.current_term = term;
  40. rf.voted_for = None;
  41. rf.state = State::Follower;
  42. election.reset_election_timer();
  43. persister.save_state(rf.persisted_state().into());
  44. }
  45. }