session.rs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. use async_trait::async_trait;
  2. use log::*;
  3. use smol::Executor;
  4. use std::sync::Arc;
  5. use crate::{
  6. error::Result,
  7. net::{p2p::P2pPtr, protocols::ProtocolVersion, ChannelPtr},
  8. };
  9. /// Removes channel from the list of connected channels when a stop signal is
  10. /// received.
  11. async fn remove_sub_on_stop(p2p: P2pPtr, channel: ChannelPtr) {
  12. debug!(target: "net", "remove_sub_on_stop() [START]");
  13. // Subscribe to stop events
  14. let stop_sub = channel.clone().subscribe_stop().await;
  15. // Wait for a stop event
  16. let _ = stop_sub.receive().await;
  17. debug!(target: "net",
  18. "remove_sub_on_stop(): received stop event. Removing channel {}",
  19. channel.address()
  20. );
  21. // Remove channel from p2p
  22. p2p.remove(channel).await;
  23. debug!(target: "net", "remove_sub_on_stop() [END]");
  24. }
  25. #[async_trait]
  26. /// Session trait.
  27. pub trait Session: Sync {
  28. /// Registers a new channel with the session. Performs a network handshake
  29. /// and starts the channel.
  30. async fn register_channel(
  31. self: Arc<Self>,
  32. channel: ChannelPtr,
  33. executor: Arc<Executor<'_>>,
  34. ) -> Result<()> {
  35. debug!(target: "net", "Session::register_channel() [START]");
  36. let protocol_version = ProtocolVersion::new(channel.clone(), self.p2p().settings()).await;
  37. let handshake_task =
  38. self.perform_handshake_protocols(protocol_version, channel.clone(), executor.clone());
  39. // start channel
  40. channel.start(executor);
  41. handshake_task.await?;
  42. debug!(target: "net", "Session::register_channel() [END]");
  43. Ok(())
  44. }
  45. /// Performs network handshake to initialize channel. Adds the channel to
  46. /// the list of connected channels, and prepares to remove the channel
  47. /// when a stop signal is received.
  48. async fn perform_handshake_protocols(
  49. &self,
  50. protocol_version: Arc<ProtocolVersion>,
  51. channel: ChannelPtr,
  52. executor: Arc<Executor<'_>>,
  53. ) -> Result<()> {
  54. // Perform handshake
  55. protocol_version.run(executor.clone()).await?;
  56. // Channel is now initialized
  57. // Add channel to p2p
  58. self.p2p().store(channel.clone()).await;
  59. // Subscribe to stop, so can remove from p2p
  60. executor.spawn(remove_sub_on_stop(self.p2p(), channel)).detach();
  61. // Channel is ready for use
  62. Ok(())
  63. }
  64. /// Returns a pointer to the p2p network interface.
  65. fn p2p(&self) -> P2pPtr;
  66. }