term_marker.rs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. use std::sync::Arc;
  2. use parking_lot::Mutex;
  3. use crate::election::ElectionState;
  4. use crate::{Persister, Raft, RaftState, State, Term};
  5. use serde::Serialize;
  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. pub fn mark(&self, term: Term) {
  15. let mut rf = self.rf.lock();
  16. mark_term(&mut rf, &self.election, self.persister.as_ref(), term)
  17. }
  18. }
  19. impl<Command: Clone + Serialize> Raft<Command> {
  20. /// Create a `TermMarker` that can be passed to tasks.
  21. pub(crate) fn term_marker(&self) -> TermMarker<Command> {
  22. TermMarker {
  23. rf: self.inner_state.clone(),
  24. election: self.election.clone(),
  25. persister: self.persister.clone(),
  26. }
  27. }
  28. }
  29. /// Update the term of the `RaftState`.
  30. pub(crate) fn mark_term<Command: Clone + Serialize>(
  31. rf: &mut RaftState<Command>,
  32. election: &ElectionState,
  33. persister: &dyn Persister,
  34. term: Term,
  35. ) {
  36. if term > rf.current_term {
  37. rf.current_term = term;
  38. rf.voted_for = None;
  39. rf.state = State::Follower;
  40. election.reset_election_timer();
  41. persister.save_state(rf.persisted_state().into());
  42. }
  43. }