protocol_keep_alive.rs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. use async_std::sync::Arc;
  2. use async_executor::Executor;
  3. use async_trait::async_trait;
  4. use log::{debug, error};
  5. use url::Url;
  6. use crate::{
  7. consensus::{KeepAlive, ValidatorStatePtr},
  8. net::{
  9. ChannelPtr, MessageSubscription, P2pPtr, ProtocolBase, ProtocolBasePtr,
  10. ProtocolJobsManager, ProtocolJobsManagerPtr,
  11. },
  12. Result,
  13. };
  14. pub struct ProtocolKeepAlive {
  15. keep_alive_sub: MessageSubscription<KeepAlive>,
  16. jobsman: ProtocolJobsManagerPtr,
  17. state: ValidatorStatePtr,
  18. p2p: P2pPtr,
  19. channel_address: Url,
  20. }
  21. impl ProtocolKeepAlive {
  22. pub async fn init(
  23. channel: ChannelPtr,
  24. state: ValidatorStatePtr,
  25. p2p: P2pPtr,
  26. ) -> Result<ProtocolBasePtr> {
  27. debug!("Adding ProtocolKeepAlive to the protocol registry");
  28. let msg_subsystem = channel.get_message_subsystem();
  29. msg_subsystem.add_dispatch::<KeepAlive>().await;
  30. let keep_alive_sub = channel.subscribe_msg::<KeepAlive>().await?;
  31. let channel_address = channel.address();
  32. Ok(Arc::new(Self {
  33. keep_alive_sub,
  34. jobsman: ProtocolJobsManager::new("ProtocolKeepAlive", channel),
  35. state,
  36. p2p,
  37. channel_address,
  38. }))
  39. }
  40. async fn handle_receive_keep_alive(self: Arc<Self>) -> Result<()> {
  41. debug!("ProtocolKeepAlive::handle_receive_keep_alive() [START]");
  42. let exclude_list = vec![self.channel_address.clone()];
  43. loop {
  44. let keep_alive = match self.keep_alive_sub.receive().await {
  45. Ok(v) => v,
  46. Err(e) => {
  47. error!("ProtocolKeepAlive::handle_receive_keep_alive(): recv error: {}", e);
  48. continue
  49. }
  50. };
  51. debug!("ProtocolKeepAlive::handle_receive_keep_alive() recv: {:?}", keep_alive);
  52. let keep_alive_copy = (*keep_alive).clone();
  53. if self.state.write().await.participant_keep_alive(keep_alive_copy.clone()) {
  54. if let Err(e) =
  55. self.p2p.broadcast_with_exclude(keep_alive_copy, &exclude_list).await
  56. {
  57. error!(
  58. "ProtocolKeepAlive::handle_receive_keep_alive(): p2p broadcast failed: {}",
  59. e
  60. );
  61. };
  62. }
  63. }
  64. }
  65. }
  66. #[async_trait]
  67. impl ProtocolBase for ProtocolKeepAlive {
  68. async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  69. debug!("ProtocolKeepAlive::start() [START]");
  70. self.jobsman.clone().start(executor.clone());
  71. self.jobsman
  72. .clone()
  73. .spawn(self.clone().handle_receive_keep_alive(), executor.clone())
  74. .await;
  75. debug!("ProtocolKeepAlive::start() [END]");
  76. Ok(())
  77. }
  78. fn name(&self) -> &'static str {
  79. "ProtocolKeepAlive"
  80. }
  81. }