manual_session.rs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. //! Manual connections session. Manages the creation of manual sessions.
  19. //! Used to create a manual session and to stop and start the session.
  20. //!
  21. //! A manual session is a type of outbound session in which we attempt
  22. //! connection to a predefined set of peers.
  23. //!
  24. //! Class consists of a weak pointer to the p2p interface and a vector of
  25. //! outbound connection slots. Using a weak pointer to p2p allows us to
  26. //! avoid circular dependencies. The vector of slots is wrapped in a mutex
  27. //! lock. This is switched on every time we instantiate a connection slot
  28. //! and insures that no other part of the program uses the slots at the
  29. //! same time.
  30. use std::sync::Arc;
  31. use async_trait::async_trait;
  32. use log::{info, warn};
  33. use smol::lock::Mutex;
  34. use url::Url;
  35. use super::{
  36. super::{
  37. channel::ChannelPtr,
  38. connector::Connector,
  39. p2p::{P2p, P2pPtr},
  40. },
  41. Session, SessionBitFlag, SESSION_MANUAL,
  42. };
  43. use crate::{
  44. system::{sleep, LazyWeak, StoppableTask, StoppableTaskPtr, Subscriber, SubscriberPtr},
  45. Error, Result,
  46. };
  47. pub type ManualSessionPtr = Arc<ManualSession>;
  48. /// Defines manual connections session.
  49. pub struct ManualSession {
  50. pub(in crate::net) p2p: LazyWeak<P2p>,
  51. connect_slots: Mutex<Vec<StoppableTaskPtr>>,
  52. /// Subscriber used to signal channels processing
  53. channel_subscriber: SubscriberPtr<Result<ChannelPtr>>,
  54. }
  55. impl ManualSession {
  56. /// Create a new manual session.
  57. pub fn new() -> ManualSessionPtr {
  58. Arc::new(Self {
  59. p2p: LazyWeak::new(),
  60. connect_slots: Mutex::new(Vec::new()),
  61. channel_subscriber: Subscriber::new(),
  62. })
  63. }
  64. /// Stops the manual session.
  65. pub async fn stop(&self) {
  66. let connect_slots = &*self.connect_slots.lock().await;
  67. for slot in connect_slots {
  68. slot.stop().await;
  69. }
  70. }
  71. /// Connect the manual session to the given address
  72. pub async fn connect(self: Arc<Self>, addr: Url) {
  73. let ex = self.p2p().executor();
  74. let task = StoppableTask::new();
  75. task.clone().start(
  76. self.clone().channel_connect_loop(addr),
  77. // Ignore stop handler
  78. |_| async {},
  79. Error::NetworkServiceStopped,
  80. ex,
  81. );
  82. self.connect_slots.lock().await.push(task);
  83. }
  84. /// Creates a connector object and tries to connect using it
  85. pub async fn channel_connect_loop(self: Arc<Self>, addr: Url) -> Result<()> {
  86. let ex = self.p2p().executor();
  87. let parent = Arc::downgrade(&self);
  88. let settings = self.p2p().settings();
  89. let connector = Connector::new(settings.clone(), parent);
  90. let attempts = settings.manual_attempt_limit;
  91. let mut remaining = attempts;
  92. // Add the peer to list of pending channels
  93. self.p2p().add_pending(&addr).await;
  94. // Loop forever if attempts==0, otherwise loop attempts number of times.
  95. let mut tried_attempts = 0;
  96. loop {
  97. tried_attempts += 1;
  98. info!(
  99. target: "net::manual_session",
  100. "[P2P] Connecting to manual outbound [{}] (attempt #{})",
  101. addr, tried_attempts,
  102. );
  103. match connector.connect(&addr).await {
  104. Ok((url, channel)) => {
  105. info!(
  106. target: "net::manual_session",
  107. "[P2P] Manual outbound connected [{}]", url,
  108. );
  109. let stop_sub =
  110. channel.subscribe_stop().await.expect("Channel should not be stopped");
  111. // Channel is now connected but not yet setup
  112. // Register the new channel
  113. self.register_channel(channel.clone(), ex.clone()).await?;
  114. // Remove pending lock since register_channel will add the channel to p2p
  115. self.p2p().remove_pending(&addr).await;
  116. // Add this connection to the anchorlist, remove it from the [otherlist]
  117. self.upgrade_connection(&addr).await;
  118. // Notify that channel processing has finished
  119. self.channel_subscriber.notify(Ok(channel)).await;
  120. // Wait for channel to close
  121. stop_sub.receive().await;
  122. info!(
  123. target: "net::manual_session",
  124. "[P2P] Manual outbound disconnected [{}]", url,
  125. );
  126. // DEV NOTE: Here we can choose to attempt reconnection again
  127. return Ok(())
  128. }
  129. Err(e) => {
  130. warn!(
  131. target: "net::manual_session",
  132. "[P2P] Unable to connect to manual outbound [{}]: {}",
  133. addr, e,
  134. );
  135. }
  136. }
  137. // Wait and try again.
  138. // TODO: Should we notify about the failure now, or after all attempts
  139. // have failed?
  140. self.channel_subscriber.notify(Err(Error::ConnectFailed)).await;
  141. remaining = if attempts == 0 { 1 } else { remaining - 1 };
  142. if remaining == 0 {
  143. break
  144. }
  145. info!(
  146. target: "net::manual_session",
  147. "[P2P] Waiting {} seconds until next manual outbound connection attempt [{}]",
  148. settings.outbound_connect_timeout, addr,
  149. );
  150. sleep(settings.outbound_connect_timeout).await;
  151. }
  152. warn!(
  153. target: "net::manual_session",
  154. "[P2P] Suspending manual connection to {} after {} failed attempts",
  155. addr, attempts,
  156. );
  157. self.p2p().remove_pending(&addr).await;
  158. Ok(())
  159. }
  160. }
  161. #[async_trait]
  162. impl Session for ManualSession {
  163. fn p2p(&self) -> P2pPtr {
  164. self.p2p.upgrade()
  165. }
  166. fn type_id(&self) -> SessionBitFlag {
  167. SESSION_MANUAL
  168. }
  169. }