protocol_participant.rs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. use async_executor::Executor;
  2. use async_std::sync::Arc;
  3. use async_trait::async_trait;
  4. use log::debug;
  5. use crate::{
  6. consensus::{Participant, ValidatorStatePtr},
  7. net::{
  8. ChannelPtr, MessageSubscription, P2pPtr, ProtocolBase, ProtocolBasePtr,
  9. ProtocolJobsManager, ProtocolJobsManagerPtr,
  10. },
  11. Result,
  12. };
  13. pub struct ProtocolParticipant {
  14. participant_sub: MessageSubscription<Participant>,
  15. jobsman: ProtocolJobsManagerPtr,
  16. state: ValidatorStatePtr,
  17. p2p: P2pPtr,
  18. }
  19. impl ProtocolParticipant {
  20. pub async fn init(
  21. channel: ChannelPtr,
  22. state: ValidatorStatePtr,
  23. p2p: P2pPtr,
  24. ) -> Result<ProtocolBasePtr> {
  25. debug!("Adding ProtocolParticipant to the protocol registry");
  26. let msg_subsystem = channel.get_message_subsystem();
  27. msg_subsystem.add_dispatch::<Participant>().await;
  28. let participant_sub = channel.subscribe_msg::<Participant>().await?;
  29. Ok(Arc::new(Self {
  30. participant_sub,
  31. jobsman: ProtocolJobsManager::new("ParticipantProtocol", channel),
  32. state,
  33. p2p,
  34. }))
  35. }
  36. async fn handle_receive_participant(self: Arc<Self>) -> Result<()> {
  37. debug!("ProtocolParticipant::handle_receive_participant() [START]");
  38. loop {
  39. let participant = self.participant_sub.receive().await?;
  40. debug!("ProtocolParticipant::handle_receive_participant() recv: {:?}", participant);
  41. let participant_copy = (*participant).clone();
  42. if self.state.write().await.append_participant(participant_copy.clone()) {
  43. self.p2p.broadcast(participant_copy).await?;
  44. }
  45. }
  46. }
  47. }
  48. #[async_trait]
  49. impl ProtocolBase for ProtocolParticipant {
  50. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  51. debug!("ProtocolParticipant::start() [START]");
  52. self.jobsman.clone().start(executor.clone());
  53. self.jobsman
  54. .clone()
  55. .spawn(self.clone().handle_receive_participant(), executor.clone())
  56. .await;
  57. debug!("ProtocolParticipant::start() [END]");
  58. Ok(())
  59. }
  60. fn name(&self) -> &'static str {
  61. "ProtocolParticipant"
  62. }
  63. }