channel.rs 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. use async_std::sync::Mutex;
  2. use std::sync::atomic::{AtomicBool, Ordering};
  3. use log::*;
  4. use futures::FutureExt;
  5. use futures::io::{ReadHalf, WriteHalf};
  6. use futures::AsyncReadExt;
  7. use smol::{Async, Executor};
  8. use std::future::Future;
  9. use std::net::{SocketAddr, TcpStream};
  10. use std::pin::Pin;
  11. use std::sync::Arc;
  12. use crate::error::{Error, Result};
  13. use crate::net::messages;
  14. use crate::net::settings::SettingsPtr;
  15. use crate::net::message_subscriber::{MessageSubscriberPtr, MessageSubscription, MessageSubscriber};
  16. use crate::net::utility::clone_net_error;
  17. use crate::system::{SubscriberPtr, Subscription, Subscriber};
  18. pub type ChannelPtr = Arc<Channel>;
  19. pub struct Channel {
  20. reader: Mutex<ReadHalf<Async<TcpStream>>>,
  21. writer: Mutex<WriteHalf<Async<TcpStream>>>,
  22. address: SocketAddr,
  23. message_subscriber: MessageSubscriberPtr,
  24. stop_subscriber: SubscriberPtr<Error>,
  25. stopped: AtomicBool,
  26. settings: SettingsPtr,
  27. }
  28. impl Channel {
  29. pub fn new(stream: Async<TcpStream>, address: SocketAddr, settings: SettingsPtr) -> Arc<Self> {
  30. let (reader, writer) = stream.split();
  31. let reader = Mutex::new(reader);
  32. let writer = Mutex::new(writer);
  33. Arc::new(Self {
  34. reader,
  35. writer,
  36. address,
  37. message_subscriber: MessageSubscriber::new(),
  38. stop_subscriber: Subscriber::new(),
  39. stopped: AtomicBool::new(false),
  40. settings,
  41. })
  42. }
  43. pub fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) {
  44. executor.spawn(self.receive_loop()).detach();
  45. }
  46. pub async fn send(self: Arc<Self>, message: messages::Message) -> Result<()> {
  47. if self.stopped.load(Ordering::Relaxed) {
  48. return Err(Error::ChannelStopped);
  49. }
  50. // Catch failure and stop channel, return a net error
  51. match messages::send_message(&mut *self.writer.lock().await, message).await {
  52. Ok(()) => Ok(()),
  53. Err(err) => {
  54. error!("Channel error {}, closing {}", err, self.address());
  55. self.stop().await;
  56. Err(Error::ChannelStopped)
  57. }
  58. }
  59. }
  60. pub fn address(&self) -> SocketAddr {
  61. self.address
  62. }
  63. pub async fn subscribe_msg(self: Arc<Self>, packet_type: messages::PacketType) -> MessageSubscription {
  64. self.message_subscriber.clone().subscribe(packet_type).await
  65. }
  66. pub async fn subscribe_stop(self: Arc<Self>) -> Subscription<Error> {
  67. self.stop_subscriber.clone().subscribe().await
  68. }
  69. pub async fn stop(&self) {
  70. self.stopped.store(false, Ordering::Relaxed);
  71. let stop_err = Arc::new(Error::ChannelStopped);
  72. self.stop_subscriber.notify(stop_err).await;
  73. }
  74. async fn receive_loop(self: Arc<Self>) -> Result<()> {
  75. let stop_sub = self.clone().subscribe_stop().await;
  76. let reader = &mut *self.reader.lock().await;
  77. loop {
  78. let message_result = futures::select! {
  79. message_result = messages::receive_message(reader).fuse() => {
  80. match message_result {
  81. Ok(message) => Ok(Arc::new(message)),
  82. Err(err) => {
  83. error!("Read error on channel {}", err);
  84. self.stop().await;
  85. Err(Error::ChannelStopped)
  86. }
  87. }
  88. }
  89. stop_err = stop_sub.receive().fuse() => {
  90. Err(clone_net_error(&*stop_err))
  91. }
  92. };
  93. // Save status before using the message
  94. let stopped = message_result.is_err();
  95. // Send result to our subscribers
  96. self.message_subscriber.notify(message_result).await;
  97. // If channel is stopped, timed out or any other error then terminate loop.
  98. if stopped {
  99. break;
  100. }
  101. }
  102. Ok(())
  103. }
  104. }