primitives.rs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. use std::io;
  2. use fxhash::FxHashMap;
  3. use crate::{
  4. util::serial::{Decodable, Encodable, SerialDecodable, SerialEncodable},
  5. Error, Result,
  6. };
  7. pub type Channel<T> = (async_channel::Sender<T>, async_channel::Receiver<T>);
  8. pub type Sender = (async_channel::Sender<NetMsg>, async_channel::Receiver<NetMsg>);
  9. #[derive(PartialEq, Eq, Debug, Clone)]
  10. pub enum Role {
  11. Follower,
  12. Candidate,
  13. Leader,
  14. }
  15. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  16. pub struct SyncRequest {
  17. pub id: u64,
  18. pub logs_len: u64,
  19. pub last_term: u64,
  20. }
  21. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  22. pub struct SyncResponse {
  23. pub id: u64,
  24. pub logs: Logs,
  25. pub commit_length: u64,
  26. pub leader_id: NodeId,
  27. pub wipe: bool,
  28. }
  29. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  30. pub struct VoteRequest {
  31. pub node_id: NodeId,
  32. pub current_term: u64,
  33. pub log_length: u64,
  34. pub last_term: u64,
  35. }
  36. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  37. pub struct VoteResponse {
  38. pub node_id: NodeId,
  39. pub current_term: u64,
  40. pub ok: bool,
  41. }
  42. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  43. pub struct LogRequest {
  44. pub leader_id: NodeId,
  45. pub current_term: u64,
  46. pub prefix_len: u64,
  47. pub prefix_term: u64,
  48. pub commit_length: u64,
  49. pub suffix: Logs,
  50. }
  51. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  52. pub struct LogResponse {
  53. pub node_id: NodeId,
  54. pub current_term: u64,
  55. pub ack: u64,
  56. pub ok: bool,
  57. }
  58. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  59. pub struct NodeIdMsg {
  60. pub id: NodeId,
  61. }
  62. impl VoteResponse {
  63. pub fn set_ok(&mut self, ok: bool) {
  64. self.ok = ok;
  65. }
  66. }
  67. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  68. pub struct BroadcastMsgRequest(pub Vec<u8>);
  69. #[derive(Clone, Debug, SerialDecodable, SerialEncodable)]
  70. pub struct Log {
  71. pub term: u64,
  72. pub msg: Vec<u8>,
  73. }
  74. #[derive(Clone, Debug, Eq, PartialEq, Hash, SerialDecodable, SerialEncodable)]
  75. pub struct NodeId(pub String);
  76. #[derive(Clone, Debug, SerialDecodable, SerialEncodable)]
  77. pub struct Logs(pub Vec<Log>);
  78. impl Logs {
  79. pub fn len(&self) -> u64 {
  80. self.0.len() as u64
  81. }
  82. pub fn is_empty(&self) -> bool {
  83. self.0.is_empty()
  84. }
  85. pub fn slice_from(&self, start: u64) -> Option<Self> {
  86. if self.len() >= start {
  87. return Some(Self(self.0[start as usize..].to_vec()))
  88. }
  89. None
  90. }
  91. pub fn slice_to(&self, end: u64) -> Self {
  92. for i in (0..end).rev() {
  93. if self.len() >= i {
  94. return Self(self.0[..i as usize].to_vec())
  95. }
  96. }
  97. Self(vec![])
  98. }
  99. pub fn get(&self, index: u64) -> Result<Log> {
  100. match self.0.get(index as usize) {
  101. Some(l) => Ok(l.clone()),
  102. None => Err(Error::RaftError("unable to indexing into vector".into())),
  103. }
  104. }
  105. pub fn to_vec(&self) -> Vec<Log> {
  106. self.0.clone()
  107. }
  108. }
  109. #[derive(Clone, Debug)]
  110. pub struct MapLength(pub FxHashMap<NodeId, u64>);
  111. impl MapLength {
  112. pub fn get(&self, key: &NodeId) -> Result<u64> {
  113. match self.0.get(key) {
  114. Some(v) => Ok(*v),
  115. None => Err(Error::RaftError("unable to indexing into HashMap".into())),
  116. }
  117. }
  118. pub fn insert(&mut self, key: &NodeId, value: u64) {
  119. self.0.insert(key.clone(), value);
  120. }
  121. }
  122. #[derive(SerialDecodable, SerialEncodable, Clone, Debug)]
  123. pub struct NetMsg {
  124. pub id: u64,
  125. pub recipient_id: Option<NodeId>,
  126. pub method: NetMsgMethod,
  127. pub payload: Vec<u8>,
  128. }
  129. #[derive(Clone, Debug, PartialEq, Eq)]
  130. #[repr(u8)]
  131. pub enum NetMsgMethod {
  132. LogResponse = 0,
  133. LogRequest = 1,
  134. VoteResponse = 2,
  135. VoteRequest = 3,
  136. BroadcastRequest = 4,
  137. NodeIdMsg = 5,
  138. }
  139. impl Encodable for NetMsgMethod {
  140. fn encode<S: io::Write>(&self, s: S) -> Result<usize> {
  141. let len: usize = match self {
  142. Self::LogResponse => 0,
  143. Self::LogRequest => 1,
  144. Self::VoteResponse => 2,
  145. Self::VoteRequest => 3,
  146. Self::BroadcastRequest => 4,
  147. Self::NodeIdMsg => 5,
  148. };
  149. (len as u8).encode(s)
  150. }
  151. }
  152. impl Decodable for NetMsgMethod {
  153. fn decode<D: io::Read>(d: D) -> Result<Self> {
  154. let com: u8 = Decodable::decode(d)?;
  155. Ok(match com {
  156. 0 => Self::LogResponse,
  157. 1 => Self::LogRequest,
  158. 2 => Self::VoteResponse,
  159. 3 => Self::VoteRequest,
  160. 4 => Self::BroadcastRequest,
  161. _ => Self::NodeIdMsg,
  162. })
  163. }
  164. }