protocol_raft.rs 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. use async_std::sync::{Arc, Mutex};
  2. use async_executor::Executor;
  3. use async_trait::async_trait;
  4. use chrono::Utc;
  5. use fxhash::FxHashMap;
  6. use log::debug;
  7. use rand::{rngs::OsRng, RngCore};
  8. use crate::{net, util::serial::serialize, Result};
  9. use super::primitives::{NetMsg, NetMsgMethod, NodeId, NodeIdMsg};
  10. pub struct ProtocolRaft {
  11. id: NodeId,
  12. jobsman: net::ProtocolJobsManagerPtr,
  13. notify_queue_sender: async_channel::Sender<NetMsg>,
  14. msg_sub: net::MessageSubscription<NetMsg>,
  15. p2p: net::P2pPtr,
  16. seen_msgs: Arc<Mutex<FxHashMap<String, i64>>>,
  17. channel: net::ChannelPtr,
  18. }
  19. impl ProtocolRaft {
  20. pub async fn init(
  21. id: NodeId,
  22. channel: net::ChannelPtr,
  23. notify_queue_sender: async_channel::Sender<NetMsg>,
  24. p2p: net::P2pPtr,
  25. seen_msgs: Arc<Mutex<FxHashMap<String, i64>>>,
  26. ) -> net::ProtocolBasePtr {
  27. let message_subsytem = channel.get_message_subsystem();
  28. message_subsytem.add_dispatch::<NetMsg>().await;
  29. let msg_sub = channel.subscribe_msg::<NetMsg>().await.expect("Missing NetMsg dispatcher!");
  30. Arc::new(Self {
  31. id,
  32. notify_queue_sender,
  33. msg_sub,
  34. jobsman: net::ProtocolJobsManager::new("ProtocolRaft", channel.clone()),
  35. p2p,
  36. seen_msgs,
  37. channel,
  38. })
  39. }
  40. async fn handle_receive_msg(self: Arc<Self>) -> Result<()> {
  41. debug!(target: "protocol_raft", "ProtocolRaft::handle_receive_msg() [START]");
  42. // on initialization send a NodeIdMsg
  43. let random_id = OsRng.next_u64();
  44. let node_id_msg = serialize(&NodeIdMsg { id: self.id.clone() });
  45. let net_msg = NetMsg {
  46. id: random_id,
  47. recipient_id: None,
  48. payload: node_id_msg.to_vec(),
  49. method: NetMsgMethod::NodeIdMsg,
  50. };
  51. {
  52. self.seen_msgs.lock().await.insert(random_id.to_string(), Utc::now().timestamp());
  53. }
  54. self.channel.send(net_msg).await?;
  55. loop {
  56. let msg = self.msg_sub.receive().await?;
  57. debug!(
  58. target: "protocol_raft",
  59. "ProtocolRaft::handle_receive_msg() received id: {:?} method {:?}",
  60. &msg.id, &msg.method
  61. );
  62. {
  63. let mut msgs = self.seen_msgs.lock().await;
  64. if msgs.contains_key(&msg.id.to_string()) {
  65. continue
  66. }
  67. msgs.insert(msg.id.to_string(), chrono::Utc::now().timestamp());
  68. }
  69. let msg = (*msg).clone();
  70. self.p2p.broadcast(msg.clone()).await?;
  71. // check if the local node and recipient id are equal
  72. if let Some(recipient_id) = &msg.recipient_id {
  73. if &self.id != recipient_id {
  74. continue
  75. }
  76. }
  77. self.notify_queue_sender.send(msg).await?;
  78. }
  79. }
  80. }
  81. #[async_trait]
  82. impl net::ProtocolBase for ProtocolRaft {
  83. /// Starts ping-pong keep-alive messages exchange. Runs ping-pong in the
  84. /// protocol task manager, then queues the reply. Sends out a ping and
  85. /// waits for pong reply. Waits for ping and replies with a pong.
  86. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  87. debug!(target: "protocol_raft", "ProtocolRaft::start() [START]");
  88. self.jobsman.clone().start(executor.clone());
  89. self.jobsman.clone().spawn(self.clone().handle_receive_msg(), executor.clone()).await;
  90. debug!(target: "protocol_raft", "ProtocolRaft::start() [END]");
  91. Ok(())
  92. }
  93. fn name(&self) -> &'static str {
  94. "ProtocolRaft"
  95. }
  96. }
  97. impl net::Message for NetMsg {
  98. fn name() -> &'static str {
  99. "netmsg"
  100. }
  101. }