protocol_dchat.rs 1.9 KB

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