net.rs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. use async_std::sync::{Arc, Mutex};
  2. use async_executor::Executor;
  3. use async_trait::async_trait;
  4. use log::debug;
  5. use darkfi::{net, Result};
  6. use crate::{Event, GSet};
  7. pub struct ProtocolCrdt {
  8. jobsman: net::ProtocolJobsManagerPtr,
  9. notify_queue_sender: async_channel::Sender<Event>,
  10. event_sub: net::MessageSubscription<Event>,
  11. p2p: net::P2pPtr,
  12. gset: Arc<Mutex<GSet<Event>>>,
  13. }
  14. impl ProtocolCrdt {
  15. pub async fn init(
  16. channel: net::ChannelPtr,
  17. notify_queue_sender: async_channel::Sender<Event>,
  18. p2p: net::P2pPtr,
  19. gset: Arc<Mutex<GSet<Event>>>,
  20. ) -> net::ProtocolBasePtr {
  21. let message_subsytem = channel.get_message_subsystem();
  22. message_subsytem.add_dispatch::<Event>().await;
  23. let event_sub = channel.subscribe_msg::<Event>().await.expect("Missing Event dispatcher!");
  24. Arc::new(Self {
  25. notify_queue_sender,
  26. event_sub,
  27. jobsman: net::ProtocolJobsManager::new("ProtocolCrdt", channel),
  28. p2p,
  29. gset,
  30. })
  31. }
  32. async fn handle_receive_event(self: Arc<Self>) -> Result<()> {
  33. debug!(target: "crdt", "ProtocolCrdt::handle_receive_event() [START]");
  34. loop {
  35. let event = self.event_sub.receive().await?;
  36. debug!(
  37. target: "ircd",
  38. "ProtocolCrdt::handle_receive_event() received {:?}",
  39. event
  40. );
  41. if self.gset.lock().await.contains(&event) {
  42. continue
  43. }
  44. let event = (*event).clone();
  45. self.p2p.broadcast(event.clone()).await?;
  46. self.notify_queue_sender.send(event).await?;
  47. }
  48. }
  49. }
  50. #[async_trait]
  51. impl net::ProtocolBase for ProtocolCrdt {
  52. /// Starts ping-pong keep-alive messages exchange. Runs ping-pong in the
  53. /// protocol task manager, then queues the reply. Sends out a ping and
  54. /// waits for pong reply. Waits for ping and replies with a pong.
  55. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  56. debug!(target: "crdt", "ProtocolCrdt::start() [START]");
  57. self.jobsman.clone().start(executor.clone());
  58. self.jobsman.clone().spawn(self.clone().handle_receive_event(), executor.clone()).await;
  59. debug!(target: "crdt", "ProtocolCrdt::start() [END]");
  60. Ok(())
  61. }
  62. fn name(&self) -> &'static str {
  63. "ProtocolCrdt"
  64. }
  65. }