channel.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. use async_std::sync::{Arc, Mutex};
  2. use futures::{
  3. io::{ReadHalf, WriteHalf},
  4. AsyncReadExt,
  5. };
  6. use log::{debug, error, info};
  7. use rand::Rng;
  8. use serde_json::json;
  9. use smol::Executor;
  10. use url::Url;
  11. use crate::{
  12. system::{StoppableTask, StoppableTaskPtr, Subscriber, SubscriberPtr, Subscription},
  13. util::NanoTimestamp,
  14. Error, Result,
  15. };
  16. use super::{
  17. message,
  18. message_subscriber::{MessageSubscription, MessageSubsystem},
  19. SessionWeakPtr, TransportStream,
  20. };
  21. /// Atomic pointer to async channel.
  22. pub type ChannelPtr = Arc<Channel>;
  23. struct ChannelInfo {
  24. random_id: u32,
  25. remote_node_id: String,
  26. last_msg: String,
  27. last_status: String,
  28. // Message log which is cleared on querying get_info
  29. log: Mutex<Vec<(NanoTimestamp, String, String)>>,
  30. }
  31. impl ChannelInfo {
  32. fn new() -> Self {
  33. Self {
  34. random_id: rand::thread_rng().gen(),
  35. remote_node_id: String::new(),
  36. last_msg: String::new(),
  37. last_status: String::new(),
  38. log: Mutex::new(Vec::new()),
  39. }
  40. }
  41. async fn get_info(&self) -> serde_json::Value {
  42. let result = json!({
  43. "random_id": self.random_id,
  44. "remote_node_id": self.remote_node_id,
  45. "last_msg": self.last_msg,
  46. "last_status": self.last_status,
  47. "log": self.log.lock().await.clone(),
  48. });
  49. self.log.lock().await.clear();
  50. result
  51. }
  52. }
  53. /// Async channel for communication between nodes.
  54. pub struct Channel {
  55. reader: Mutex<ReadHalf<Box<dyn TransportStream>>>,
  56. writer: Mutex<WriteHalf<Box<dyn TransportStream>>>,
  57. address: Url,
  58. message_subsystem: MessageSubsystem,
  59. stop_subscriber: SubscriberPtr<Error>,
  60. receive_task: StoppableTaskPtr,
  61. stopped: Mutex<bool>,
  62. info: Mutex<ChannelInfo>,
  63. //session: SessionWeakPtr,
  64. }
  65. impl Channel {
  66. /// Sets up a new channel. Creates a reader and writer TCP stream and
  67. /// summons the message subscriber subsystem. Performs a network
  68. /// handshake on the subsystem dispatchers.
  69. pub async fn new(
  70. stream: Box<dyn TransportStream>,
  71. address: Url,
  72. //session: SessionWeakPtr,
  73. ) -> Arc<Self> {
  74. let (reader, writer) = stream.split();
  75. let reader = Mutex::new(reader);
  76. let writer = Mutex::new(writer);
  77. let message_subsystem = MessageSubsystem::new();
  78. Self::setup_dispatchers(&message_subsystem).await;
  79. Arc::new(Self {
  80. reader,
  81. writer,
  82. address,
  83. message_subsystem,
  84. stop_subscriber: Subscriber::new(),
  85. receive_task: StoppableTask::new(),
  86. stopped: Mutex::new(false),
  87. info: Mutex::new(ChannelInfo::new()),
  88. //session,
  89. })
  90. }
  91. pub async fn get_info(&self) -> serde_json::Value {
  92. self.info.lock().await.get_info().await
  93. }
  94. //async fn session_type_id(&self) -> Result<()> {
  95. // //
  96. //}
  97. /// Starts the channel. Runs a receive loop to start receiving messages or
  98. /// handles a network failure.
  99. pub fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) {
  100. debug!(target: "net", "Channel::start() [START, address={}]", self.address());
  101. let self2 = self.clone();
  102. self.receive_task.clone().start(
  103. self.clone().main_receive_loop(),
  104. |result| self2.handle_stop(result),
  105. Error::NetworkServiceStopped,
  106. executor,
  107. );
  108. debug!(target: "net", "Channel::start() [END, address={}]", self.address());
  109. }
  110. /// Stops the channel. Steps through each component of the channel
  111. /// connection and sends a stop signal. Notifies all subscribers that
  112. /// the channel has been closed.
  113. pub async fn stop(&self) {
  114. debug!(target: "net", "Channel::stop() [START, address={}]", self.address());
  115. if !(*self.stopped.lock().await) {
  116. *self.stopped.lock().await = true;
  117. self.stop_subscriber.notify(Error::ChannelStopped).await;
  118. self.receive_task.stop().await;
  119. self.message_subsystem.trigger_error(Error::ChannelStopped).await;
  120. debug!(target: "net", "Channel::stop() [END, address={}]", self.address());
  121. }
  122. }
  123. /// Creates a subscription to a stopped signal.
  124. /// If the channel is stopped then this will return a ChannelStopped error.
  125. pub async fn subscribe_stop(&self) -> Result<Subscription<Error>> {
  126. debug!(target: "net",
  127. "Channel::subscribe_stop() [START, address={}]",
  128. self.address()
  129. );
  130. {
  131. let stopped = *self.stopped.lock().await;
  132. if stopped {
  133. return Err(Error::ChannelStopped)
  134. }
  135. }
  136. let sub = self.stop_subscriber.clone().subscribe().await;
  137. debug!(target: "net",
  138. "Channel::subscribe_stop() [END, address={}]",
  139. self.address()
  140. );
  141. Ok(sub)
  142. }
  143. /// Sends a message across a channel. Calls function 'send_message' that
  144. /// creates a new payload and sends it over the TCP connection as a
  145. /// packet. Returns an error if something goes wrong.
  146. pub async fn send<M: message::Message>(&self, message: M) -> Result<()> {
  147. debug!(target: "net",
  148. "Channel::send() [START, command={:?}, address={}]",
  149. M::name(),
  150. self.address()
  151. );
  152. {
  153. let stopped = *self.stopped.lock().await;
  154. if stopped {
  155. return Err(Error::ChannelStopped)
  156. }
  157. }
  158. // Catch failure and stop channel, return a net error
  159. let result = match self.send_message(message).await {
  160. Ok(()) => Ok(()),
  161. Err(err) => {
  162. error!("Channel send error for [{}]: {}", self.address(), err);
  163. self.stop().await;
  164. Err(Error::ChannelStopped)
  165. }
  166. };
  167. debug!(target: "net",
  168. "Channel::send() [END, command={:?}, address={}]",
  169. M::name(),
  170. self.address()
  171. );
  172. {
  173. let info = &mut *self.info.lock().await;
  174. info.last_msg = M::name().to_string();
  175. info.last_status = "sent".to_string();
  176. }
  177. result
  178. }
  179. /// Implements send message functionality. Creates a new payload and encodes
  180. /// it. Then creates a message packet- the base type of the network- and
  181. /// copies the payload into it. Then we send the packet over the TCP
  182. /// stream.
  183. async fn send_message<M: message::Message>(&self, message: M) -> Result<()> {
  184. let mut payload = Vec::new();
  185. message.encode(&mut payload)?;
  186. let packet = message::Packet { command: String::from(M::name()), payload };
  187. let time = NanoTimestamp::current_time();
  188. //let time = time::unix_timestamp()?;
  189. {
  190. let info = &mut *self.info.lock().await;
  191. info.log.lock().await.push((time, "send".to_string(), packet.command.clone()));
  192. }
  193. let stream = &mut *self.writer.lock().await;
  194. message::send_packet(stream, packet).await
  195. }
  196. /// Subscribe to a messages on the message subsystem.
  197. pub async fn subscribe_msg<M: message::Message>(&self) -> Result<MessageSubscription<M>> {
  198. debug!(target: "net",
  199. "Channel::subscribe_msg() [START, command={:?}, address={}]",
  200. M::name(),
  201. self.address()
  202. );
  203. let sub = self.message_subsystem.subscribe::<M>().await;
  204. debug!(target: "net",
  205. "Channel::subscribe_msg() [END, command={:?}, address={}]",
  206. M::name(),
  207. self.address()
  208. );
  209. sub
  210. }
  211. /// Return the local socket address.
  212. pub fn address(&self) -> Url {
  213. self.address.clone()
  214. }
  215. pub async fn remote_node_id(&self) -> String {
  216. self.info.lock().await.remote_node_id.clone()
  217. }
  218. pub async fn set_remote_node_id(&self, remote_node_id: String) {
  219. self.info.lock().await.remote_node_id = remote_node_id;
  220. }
  221. /// End of file error. Triggered when unexpected end of file occurs.
  222. fn is_eof_error(err: Error) -> bool {
  223. match err {
  224. Error::Io(io_err) => io_err == std::io::ErrorKind::UnexpectedEof,
  225. _ => false,
  226. }
  227. }
  228. /// Perform network handshake for message subsystem dispatchers.
  229. async fn setup_dispatchers(message_subsystem: &MessageSubsystem) {
  230. message_subsystem.add_dispatch::<message::VersionMessage>().await;
  231. message_subsystem.add_dispatch::<message::VerackMessage>().await;
  232. message_subsystem.add_dispatch::<message::PingMessage>().await;
  233. message_subsystem.add_dispatch::<message::PongMessage>().await;
  234. message_subsystem.add_dispatch::<message::GetAddrsMessage>().await;
  235. message_subsystem.add_dispatch::<message::AddrsMessage>().await;
  236. }
  237. /// Convenience function that returns the Message Subsystem.
  238. pub fn get_message_subsystem(&self) -> &MessageSubsystem {
  239. &self.message_subsystem
  240. }
  241. /// Run the receive loop. Start receiving messages or handle network
  242. /// failure.
  243. async fn main_receive_loop(self: Arc<Self>) -> Result<()> {
  244. debug!(target: "net",
  245. "Channel::receive_loop() [START, address={}]",
  246. self.address()
  247. );
  248. let reader = &mut *self.reader.lock().await;
  249. loop {
  250. let packet = match message::read_packet(reader).await {
  251. Ok(packet) => packet,
  252. Err(err) => {
  253. if Self::is_eof_error(err.clone()) {
  254. info!("Inbound connection {} disconnected", self.address());
  255. } else {
  256. error!("Read error on channel: {}", err);
  257. }
  258. debug!(target: "net",
  259. "Channel::receive_loop() stopping channel {:?}",
  260. self.address()
  261. );
  262. self.stop().await;
  263. return Err(Error::ChannelStopped)
  264. }
  265. };
  266. {
  267. let info = &mut *self.info.lock().await;
  268. info.last_msg = packet.command.clone();
  269. info.last_status = "recv".to_string();
  270. let time = NanoTimestamp::current_time();
  271. //let time = time::unix_timestamp()?;
  272. info.log.lock().await.push((time, "recv".to_string(), packet.command.clone()));
  273. }
  274. // Send result to our subscribers
  275. self.message_subsystem.notify(&packet.command, packet.payload).await;
  276. }
  277. }
  278. /// Handle network errors. Panic if error passes silently, otherwise
  279. /// broadcast the error.
  280. async fn handle_stop(self: Arc<Self>, result: Result<()>) {
  281. debug!(target: "net", "Channel::handle_stop() [START, address={}]", self.address());
  282. match result {
  283. Ok(()) => panic!("Channel task should never complete without error status"),
  284. Err(err) => {
  285. // Send this error to all channel subscribers
  286. self.message_subsystem.trigger_error(err).await;
  287. }
  288. }
  289. debug!(target: "net", "Channel::handle_stop() [END, address={}]", self.address());
  290. }
  291. }