inbound_session.rs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. use async_std::sync::Mutex;
  2. use async_trait::async_trait;
  3. use serde_json::json;
  4. use std::{
  5. net::SocketAddr,
  6. sync::{Arc, Weak},
  7. };
  8. use async_executor::Executor;
  9. use fxhash::FxHashMap;
  10. use log::{error, info};
  11. use crate::{
  12. error::{Error, Result},
  13. net::{
  14. session::{Session, SessionBitflag, SESSION_INBOUND},
  15. Acceptor, AcceptorPtr, ChannelPtr, P2p,
  16. },
  17. system::{StoppableTask, StoppableTaskPtr},
  18. };
  19. struct InboundInfo {
  20. channel: ChannelPtr,
  21. }
  22. impl InboundInfo {
  23. async fn get_info(&self) -> serde_json::Value {
  24. self.channel.get_info().await
  25. }
  26. }
  27. /// Defines inbound connections session.
  28. pub struct InboundSession {
  29. p2p: Weak<P2p>,
  30. acceptor: AcceptorPtr,
  31. accept_task: StoppableTaskPtr,
  32. connect_infos: Mutex<FxHashMap<SocketAddr, InboundInfo>>,
  33. }
  34. impl InboundSession {
  35. /// Create a new inbound session.
  36. pub fn new(p2p: Weak<P2p>) -> Arc<Self> {
  37. let acceptor = Acceptor::new();
  38. Arc::new(Self {
  39. p2p,
  40. acceptor,
  41. accept_task: StoppableTask::new(),
  42. connect_infos: Mutex::new(FxHashMap::default()),
  43. })
  44. }
  45. /// Starts the inbound session. Begins by accepting connections and fails if
  46. /// the address is not configured. Then runs the channel subscription
  47. /// loop.
  48. pub fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  49. match self.p2p().settings().inbound {
  50. Some(accept_addr) => {
  51. self.clone().start_accept_session(accept_addr, executor.clone())?;
  52. }
  53. None => {
  54. info!(target: "net", "Not configured for accepting incoming connections.");
  55. return Ok(())
  56. }
  57. }
  58. self.accept_task.clone().start(
  59. self.clone().channel_sub_loop(executor.clone()),
  60. // Ignore stop handler
  61. |_| async {},
  62. Error::ServiceStopped,
  63. executor,
  64. );
  65. Ok(())
  66. }
  67. /// Stops the inbound session.
  68. pub async fn stop(&self) {
  69. self.acceptor.stop().await;
  70. self.accept_task.stop().await;
  71. }
  72. /// Start accepting connections for inbound session.
  73. fn start_accept_session(
  74. self: Arc<Self>,
  75. accept_addr: SocketAddr,
  76. executor: Arc<Executor<'_>>,
  77. ) -> Result<()> {
  78. info!(target: "net", "Starting inbound session on {}", accept_addr);
  79. let result = self.acceptor.clone().start(accept_addr, executor);
  80. if let Err(err) = result.clone() {
  81. error!(target: "net", "Error starting listener: {}", err);
  82. }
  83. result
  84. }
  85. /// Wait for all new channels created by the acceptor and call
  86. /// setup_channel() on them.
  87. async fn channel_sub_loop(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  88. let channel_sub = self.acceptor.clone().subscribe().await;
  89. loop {
  90. let channel = channel_sub.receive().await?;
  91. // Spawn a detached task to process the channel
  92. // This will just perform the channel setup then exit.
  93. executor.spawn(self.clone().setup_channel(channel, executor.clone())).detach();
  94. }
  95. }
  96. /// Registers the channel. First performs a network handshake and starts the
  97. /// channel. Then starts sending keep-alive and address messages across the
  98. /// channel.
  99. async fn setup_channel(
  100. self: Arc<Self>,
  101. channel: ChannelPtr,
  102. executor: Arc<Executor<'_>>,
  103. ) -> Result<()> {
  104. info!(target: "net", "Connected inbound [{}]", channel.address());
  105. self.clone().register_channel(channel.clone(), executor.clone()).await?;
  106. self.manage_channel_for_get_info(channel).await;
  107. Ok(())
  108. }
  109. async fn manage_channel_for_get_info(&self, channel: ChannelPtr) {
  110. let key = channel.address();
  111. self.connect_infos.lock().await.insert(key, InboundInfo { channel: channel.clone() });
  112. let stop_sub = channel.subscribe_stop().await;
  113. stop_sub.receive().await;
  114. self.connect_infos.lock().await.remove(&key);
  115. }
  116. }
  117. #[async_trait]
  118. impl Session for InboundSession {
  119. async fn get_info(&self) -> serde_json::Value {
  120. let mut infos = FxHashMap::default();
  121. for (addr, info) in self.connect_infos.lock().await.iter() {
  122. infos.insert(addr.to_string(), info.get_info().await);
  123. }
  124. json!({
  125. "connected": infos,
  126. })
  127. }
  128. fn p2p(&self) -> Arc<P2p> {
  129. self.p2p.upgrade().unwrap()
  130. }
  131. fn selector_id(&self) -> SessionBitflag {
  132. SESSION_INBOUND
  133. }
  134. }