protocol_dchat.rs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. use async_executor::Executor;
  2. use async_std::sync::Arc;
  3. use async_trait::async_trait;
  4. use darkfi::{net, Result};
  5. use log::debug;
  6. use crate::dchatmsg::{DchatMsg, DchatMsgsBuffer};
  7. pub struct ProtocolDchat {
  8. jobsman: net::ProtocolJobsManagerPtr,
  9. msg_sub: net::MessageSubscription<DchatMsg>,
  10. msgs: DchatMsgsBuffer,
  11. }
  12. impl ProtocolDchat {
  13. pub async fn init(channel: net::ChannelPtr, msgs: DchatMsgsBuffer) -> net::ProtocolBasePtr {
  14. debug!(target: "dchat", "ProtocolDchat::init() [START]");
  15. let message_subsytem = channel.get_message_subsystem();
  16. message_subsytem.add_dispatch::<DchatMsg>().await;
  17. let msg_sub =
  18. channel.subscribe_msg::<DchatMsg>().await.expect("Missing DchatMsg dispatcher!");
  19. Arc::new(Self {
  20. jobsman: net::ProtocolJobsManager::new("ProtocolDchat", channel.clone()),
  21. msg_sub,
  22. msgs,
  23. })
  24. }
  25. async fn handle_receive_msg(self: Arc<Self>) -> Result<()> {
  26. debug!(target: "dchat", "ProtocolDchat::handle_receive_msg() [START]");
  27. while let Ok(msg) = self.msg_sub.receive().await {
  28. let msg = (*msg).to_owned();
  29. self.msgs.lock().await.push(msg);
  30. }
  31. Ok(())
  32. }
  33. }
  34. #[async_trait]
  35. impl net::ProtocolBase for ProtocolDchat {
  36. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  37. debug!(target: "dchat", "ProtocolDchat::ProtocolBase::start() [START]");
  38. self.jobsman.clone().start(executor.clone());
  39. self.jobsman.clone().spawn(self.clone().handle_receive_msg(), executor.clone()).await;
  40. debug!(target: "dchat", "ProtocolDchat::ProtocolBase::start() [STOP]");
  41. Ok(())
  42. }
  43. fn name(&self) -> &'static str {
  44. "ProtocolDchat"
  45. }
  46. }