primitives.rs 4.9 KB

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