inbound_session.rs 4.0 KB

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