inbound_session.rs 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. use async_executor::Executor;
  2. use log::*;
  3. use std::net::SocketAddr;
  4. use std::sync::{Arc, Weak};
  5. use crate::net::error::{NetError, NetResult};
  6. use crate::net::protocols::{ProtocolAddress, ProtocolPing};
  7. use crate::net::sessions::Session;
  8. use crate::net::{Acceptor, AcceptorPtr};
  9. use crate::net::{ChannelPtr, P2p};
  10. use crate::system::{StoppableTask, StoppableTaskPtr};
  11. /// Inbound connections session. Manages the creation of inbound sessions. Used
  12. /// to create an inbound session and start and stop the session.
  13. ///
  14. /// Class consists of 3 pointers: a weak pointer to the peer-to-peer class, an
  15. /// acceptor pointer, and a stoppable task pointer. Using a weak pointer to P2P
  16. /// allows us to avoid circular dependencies.
  17. pub struct InboundSession {
  18. p2p: Weak<P2p>,
  19. acceptor: AcceptorPtr,
  20. accept_task: StoppableTaskPtr,
  21. }
  22. impl InboundSession {
  23. /// Create a new inbound session.
  24. pub fn new(p2p: Weak<P2p>) -> Arc<Self> {
  25. let acceptor = Acceptor::new();
  26. Arc::new(Self {
  27. p2p,
  28. acceptor,
  29. accept_task: StoppableTask::new(),
  30. })
  31. }
  32. /// Starts the inbound session. Begins by accepting connections and fails if
  33. /// the address is not configured. Then runs the channel subscription
  34. /// loop.
  35. pub fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> NetResult<()> {
  36. match self.p2p().settings().inbound {
  37. Some(accept_addr) => {
  38. self.clone()
  39. .start_accept_session(accept_addr, executor.clone())?;
  40. }
  41. None => {
  42. info!("Not configured for accepting incoming connections.");
  43. return Ok(());
  44. }
  45. }
  46. self.accept_task.clone().start(
  47. self.clone().channel_sub_loop(executor.clone()),
  48. // Ignore stop handler
  49. |_| async {},
  50. NetError::ServiceStopped,
  51. executor,
  52. );
  53. Ok(())
  54. }
  55. /// Stops the inbound session.
  56. pub async fn stop(&self) {
  57. self.acceptor.stop().await;
  58. self.accept_task.stop().await;
  59. }
  60. /// Start accepting connections for inbound session.
  61. fn start_accept_session(
  62. self: Arc<Self>,
  63. accept_addr: SocketAddr,
  64. executor: Arc<Executor<'_>>,
  65. ) -> NetResult<()> {
  66. info!("Starting inbound session on {}", accept_addr);
  67. let result = self.acceptor.clone().start(accept_addr, executor);
  68. if let Err(err) = result {
  69. error!("Error starting listener: {}", err);
  70. }
  71. result
  72. }
  73. /// Wait for all new channels created by the acceptor and call
  74. /// setup_channel() on them.
  75. async fn channel_sub_loop(self: Arc<Self>, executor: Arc<Executor<'_>>) -> NetResult<()> {
  76. let channel_sub = self.acceptor.clone().subscribe().await;
  77. loop {
  78. let channel = channel_sub.receive().await?;
  79. // Spawn a detached task to process the channel
  80. // This will just perform the channel setup then exit.
  81. executor
  82. .spawn(self.clone().setup_channel(channel, executor.clone()))
  83. .detach();
  84. }
  85. }
  86. /// Registers the channel. First performs a network handshake and starts the
  87. /// channel. Then starts sending keep-alive and address messages across the
  88. /// channel.
  89. async fn setup_channel(
  90. self: Arc<Self>,
  91. channel: ChannelPtr,
  92. executor: Arc<Executor<'_>>,
  93. ) -> NetResult<()> {
  94. info!("Connected inbound [{}]", channel.address());
  95. self.clone()
  96. .register_channel(channel.clone(), executor.clone())
  97. .await?;
  98. self.attach_protocols(channel, executor).await
  99. }
  100. /// Starts sending keep-alive and address messages across the channels.
  101. async fn attach_protocols(
  102. self: Arc<Self>,
  103. channel: ChannelPtr,
  104. executor: Arc<Executor<'_>>,
  105. ) -> NetResult<()> {
  106. let settings = self.p2p().settings().clone();
  107. let hosts = self.p2p().hosts().clone();
  108. let protocol_ping = ProtocolPing::new(channel.clone(), settings.clone());
  109. let protocol_addr = ProtocolAddress::new(channel, hosts).await;
  110. protocol_ping.start(executor.clone()).await;
  111. protocol_addr.start(executor).await;
  112. Ok(())
  113. }
  114. }
  115. impl Session for InboundSession {
  116. fn p2p(&self) -> Arc<P2p> {
  117. self.p2p.upgrade().unwrap()
  118. }
  119. }