term_marker.rs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. use std::sync::Arc;
  2. use parking_lot::Mutex;
  3. use crate::election::ElectionState;
  4. use crate::storage::SharedLogPersister;
  5. use crate::{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: SharedLogPersister<Command>,
  12. }
  13. impl<Command> 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: SharedLogPersister<Command>,
  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. if term > rf.current_term {
  29. rf.current_term = term;
  30. rf.voted_for = None;
  31. rf.state = State::Follower;
  32. self.election.reset_election_timer();
  33. self.persister.save_term_vote(&rf);
  34. }
  35. }
  36. }