manual_session.rs 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. use async_std::sync::Mutex;
  2. use std::{
  3. net::SocketAddr,
  4. sync::{Arc, Weak},
  5. };
  6. use async_executor::Executor;
  7. use async_trait::async_trait;
  8. use log::*;
  9. use serde_json::json;
  10. use crate::{
  11. system::{StoppableTask, StoppableTaskPtr},
  12. util::sleep,
  13. Error, Result,
  14. };
  15. use super::{
  16. super::{Connector, P2p},
  17. Session, SessionBitflag, SESSION_MANUAL,
  18. };
  19. pub struct ManualSession {
  20. p2p: Weak<P2p>,
  21. connect_slots: Mutex<Vec<StoppableTaskPtr>>,
  22. }
  23. impl ManualSession {
  24. /// Create a new inbound session.
  25. pub fn new(p2p: Weak<P2p>) -> Arc<Self> {
  26. Arc::new(Self { p2p, connect_slots: Mutex::new(Vec::new()) })
  27. }
  28. /// Stop the outbound session.
  29. pub async fn stop(&self) {
  30. let connect_slots = &*self.connect_slots.lock().await;
  31. for slot in connect_slots {
  32. slot.stop().await;
  33. }
  34. }
  35. pub async fn connect(self: Arc<Self>, addr: &SocketAddr, executor: Arc<Executor<'_>>) {
  36. let task = StoppableTask::new();
  37. task.clone().start(
  38. self.clone().channel_connect_loop(*addr, executor.clone()),
  39. // Ignore stop handler
  40. |_| async {},
  41. Error::ServiceStopped,
  42. executor.clone(),
  43. );
  44. self.connect_slots.lock().await.push(task);
  45. }
  46. pub async fn channel_connect_loop(
  47. self: Arc<Self>,
  48. addr: SocketAddr,
  49. executor: Arc<Executor<'_>>,
  50. ) -> Result<()> {
  51. let connector = Connector::new(self.p2p().settings());
  52. let settings = self.p2p().settings();
  53. let attempts = settings.manual_attempt_limit;
  54. let mut remaining = attempts;
  55. loop {
  56. // Loop forever if attempts is 0
  57. // Otherwise loop attempts number of times
  58. remaining = if attempts == 0 { 1 } else { remaining - 1 };
  59. if remaining == 0 {
  60. break
  61. }
  62. self.p2p().add_pending(addr).await;
  63. info!(target: "net", "Connecting to manual outbound [{}]", addr);
  64. match connector.connect(addr).await {
  65. Ok(channel) => {
  66. // Blacklist goes here
  67. info!(target: "net", "Connected to manual outbound [{}]", addr);
  68. let stop_sub = channel.subscribe_stop().await;
  69. self.clone().register_channel(channel.clone(), executor.clone()).await?;
  70. // Channel is now connected but not yet setup
  71. // Remove pending lock since register_channel will add the channel to p2p
  72. self.p2p().remove_pending(&addr).await;
  73. //self.clone().attach_protocols(channel, executor.clone()).await?;
  74. // Wait for channel to close
  75. stop_sub.receive().await;
  76. }
  77. Err(err) => {
  78. info!(target: "net", "Unable to connect to manual outbound [{}]: {}", addr, err);
  79. sleep(settings.connect_timeout_seconds.into()).await;
  80. }
  81. }
  82. }
  83. warn!(
  84. target: "net",
  85. "Suspending manual connection to [{}] after {} failed attempts.",
  86. addr,
  87. attempts
  88. );
  89. Ok(())
  90. }
  91. // Starts sending keep-alive and address messages across the channels.
  92. /*async fn attach_protocols(
  93. self: Arc<Self>,
  94. channel: ChannelPtr,
  95. executor: Arc<Executor<'_>>,
  96. ) -> Result<()> {
  97. let hosts = self.p2p().hosts();
  98. let protocol_ping = ProtocolPing::new(channel.clone(), self.p2p());
  99. let protocol_addr = ProtocolAddress::new(channel, hosts).await;
  100. protocol_ping.start(executor.clone()).await;
  101. protocol_addr.start(executor).await;
  102. Ok(())
  103. }*/
  104. }
  105. #[async_trait]
  106. impl Session for ManualSession {
  107. async fn get_info(&self) -> serde_json::Value {
  108. json!({
  109. "key": 110
  110. })
  111. }
  112. fn p2p(&self) -> Arc<P2p> {
  113. self.p2p.upgrade().unwrap()
  114. }
  115. fn selector_id(&self) -> SessionBitflag {
  116. SESSION_MANUAL
  117. }
  118. }