mod.rs 5.4 KB

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