primitives.rs 4.8 KB

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