persister.rs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. use std::convert::TryFrom;
  2. use bytes::Bytes;
  3. use crate::{LogEntry, Peer, RaftState, Term};
  4. use serde::de::DeserializeOwned;
  5. use serde::Serialize;
  6. pub trait Persister: Send + Sync {
  7. fn read_state(&self) -> Bytes;
  8. fn save_state(&self, bytes: Bytes);
  9. }
  10. #[derive(Serialize, Deserialize)]
  11. pub(crate) struct PersistedRaftState<Command> {
  12. pub current_term: Term,
  13. pub voted_for: Option<Peer>,
  14. pub log: Vec<LogEntry<Command>>,
  15. }
  16. impl<Command: Clone, T: AsRef<RaftState<Command>>> From<T>
  17. for PersistedRaftState<Command>
  18. {
  19. fn from(raft_state: T) -> Self {
  20. Self::from(raft_state.as_ref())
  21. }
  22. }
  23. impl<Command: Clone> From<&RaftState<Command>> for PersistedRaftState<Command> {
  24. fn from(raft_state: &RaftState<Command>) -> Self {
  25. Self {
  26. current_term: raft_state.current_term,
  27. voted_for: raft_state.voted_for,
  28. log: raft_state.log.clone(),
  29. }
  30. }
  31. }
  32. impl<Command: DeserializeOwned> TryFrom<Bytes> for PersistedRaftState<Command> {
  33. type Error = bincode::Error;
  34. fn try_from(value: Bytes) -> Result<Self, Self::Error> {
  35. bincode::deserialize(value.as_ref())
  36. }
  37. }
  38. impl<Command: Serialize> Into<Bytes> for PersistedRaftState<Command> {
  39. fn into(self) -> Bytes {
  40. bincode::serialize(&self)
  41. .expect("Serialization should not fail")
  42. .into()
  43. }
  44. }