mod.rs 4.9 KB

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