channel.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. Session, SessionBitflag, 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. /// Starts the channel. Runs a receive loop to start receiving messages or
  95. /// handles a network failure.
  96. pub fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) {
  97. debug!(target: "net", "Channel::start() [START, address={}]", self.address());
  98. let self2 = self.clone();
  99. self.receive_task.clone().start(
  100. self.clone().main_receive_loop(),
  101. |result| self2.handle_stop(result),
  102. Error::NetworkServiceStopped,
  103. executor,
  104. );
  105. debug!(target: "net", "Channel::start() [END, address={}]", self.address());
  106. }
  107. /// Stops the channel. Steps through each component of the channel
  108. /// connection and sends a stop signal. Notifies all subscribers that
  109. /// the channel has been closed.
  110. pub async fn stop(&self) {
  111. debug!(target: "net", "Channel::stop() [START, address={}]", self.address());
  112. if !(*self.stopped.lock().await) {
  113. *self.stopped.lock().await = true;
  114. self.stop_subscriber.notify(Error::ChannelStopped).await;
  115. self.receive_task.stop().await;
  116. self.message_subsystem.trigger_error(Error::ChannelStopped).await;
  117. debug!(target: "net", "Channel::stop() [END, address={}]", self.address());
  118. }
  119. }
  120. /// Creates a subscription to a stopped signal.
  121. /// If the channel is stopped then this will return a ChannelStopped error.
  122. pub async fn subscribe_stop(&self) -> Result<Subscription<Error>> {
  123. debug!(target: "net",
  124. "Channel::subscribe_stop() [START, address={}]",
  125. self.address()
  126. );
  127. {
  128. let stopped = *self.stopped.lock().await;
  129. if stopped {
  130. return Err(Error::ChannelStopped)
  131. }
  132. }
  133. let sub = self.stop_subscriber.clone().subscribe().await;
  134. debug!(target: "net",
  135. "Channel::subscribe_stop() [END, address={}]",
  136. self.address()
  137. );
  138. Ok(sub)
  139. }
  140. /// Sends a message across a channel. Calls function 'send_message' that
  141. /// creates a new payload and sends it over the TCP connection as a
  142. /// packet. Returns an error if something goes wrong.
  143. pub async fn send<M: message::Message>(&self, message: M) -> Result<()> {
  144. debug!(target: "net",
  145. "Channel::send() [START, command={:?}, address={}]",
  146. M::name(),
  147. self.address()
  148. );
  149. {
  150. let stopped = *self.stopped.lock().await;
  151. if stopped {
  152. return Err(Error::ChannelStopped)
  153. }
  154. }
  155. // Catch failure and stop channel, return a net error
  156. let result = match self.send_message(message).await {
  157. Ok(()) => Ok(()),
  158. Err(err) => {
  159. error!("Channel send error for [{}]: {}", self.address(), err);
  160. self.stop().await;
  161. Err(Error::ChannelStopped)
  162. }
  163. };
  164. debug!(target: "net",
  165. "Channel::send() [END, command={:?}, address={}]",
  166. M::name(),
  167. self.address()
  168. );
  169. {
  170. let info = &mut *self.info.lock().await;
  171. info.last_msg = M::name().to_string();
  172. info.last_status = "sent".to_string();
  173. }
  174. result
  175. }
  176. /// Implements send message functionality. Creates a new payload and encodes
  177. /// it. Then creates a message packet- the base type of the network- and
  178. /// copies the payload into it. Then we send the packet over the TCP
  179. /// stream.
  180. async fn send_message<M: message::Message>(&self, message: M) -> Result<()> {
  181. let mut payload = Vec::new();
  182. message.encode(&mut payload)?;
  183. let packet = message::Packet { command: String::from(M::name()), payload };
  184. let time = NanoTimestamp::current_time();
  185. //let time = time::unix_timestamp()?;
  186. {
  187. let info = &mut *self.info.lock().await;
  188. info.log.lock().await.push((time, "send".to_string(), packet.command.clone()));
  189. }
  190. let stream = &mut *self.writer.lock().await;
  191. message::send_packet(stream, packet).await
  192. }
  193. /// Subscribe to a messages on the message subsystem.
  194. pub async fn subscribe_msg<M: message::Message>(&self) -> Result<MessageSubscription<M>> {
  195. debug!(target: "net",
  196. "Channel::subscribe_msg() [START, command={:?}, address={}]",
  197. M::name(),
  198. self.address()
  199. );
  200. let sub = self.message_subsystem.subscribe::<M>().await;
  201. debug!(target: "net",
  202. "Channel::subscribe_msg() [END, command={:?}, address={}]",
  203. M::name(),
  204. self.address()
  205. );
  206. sub
  207. }
  208. /// Return the local socket address.
  209. pub fn address(&self) -> Url {
  210. self.address.clone()
  211. }
  212. pub async fn remote_node_id(&self) -> String {
  213. self.info.lock().await.remote_node_id.clone()
  214. }
  215. pub async fn set_remote_node_id(&self, remote_node_id: String) {
  216. self.info.lock().await.remote_node_id = remote_node_id;
  217. }
  218. /// End of file error. Triggered when unexpected end of file occurs.
  219. fn is_eof_error(err: Error) -> bool {
  220. match err {
  221. Error::Io(io_err) => io_err == std::io::ErrorKind::UnexpectedEof,
  222. _ => false,
  223. }
  224. }
  225. /// Perform network handshake for message subsystem dispatchers.
  226. async fn setup_dispatchers(message_subsystem: &MessageSubsystem) {
  227. message_subsystem.add_dispatch::<message::VersionMessage>().await;
  228. message_subsystem.add_dispatch::<message::VerackMessage>().await;
  229. message_subsystem.add_dispatch::<message::PingMessage>().await;
  230. message_subsystem.add_dispatch::<message::PongMessage>().await;
  231. message_subsystem.add_dispatch::<message::GetAddrsMessage>().await;
  232. message_subsystem.add_dispatch::<message::AddrsMessage>().await;
  233. }
  234. /// Convenience function that returns the Message Subsystem.
  235. pub fn get_message_subsystem(&self) -> &MessageSubsystem {
  236. &self.message_subsystem
  237. }
  238. /// Run the receive loop. Start receiving messages or handle network
  239. /// failure.
  240. async fn main_receive_loop(self: Arc<Self>) -> Result<()> {
  241. debug!(target: "net",
  242. "Channel::receive_loop() [START, address={}]",
  243. self.address()
  244. );
  245. let reader = &mut *self.reader.lock().await;
  246. loop {
  247. let packet = match message::read_packet(reader).await {
  248. Ok(packet) => packet,
  249. Err(err) => {
  250. if Self::is_eof_error(err.clone()) {
  251. info!("Inbound connection {} disconnected", self.address());
  252. } else {
  253. error!("Read error on channel {}: {}", self.address(), err);
  254. }
  255. debug!(target: "net",
  256. "Channel::receive_loop() stopping channel {}",
  257. self.address()
  258. );
  259. self.stop().await;
  260. return Err(Error::ChannelStopped)
  261. }
  262. };
  263. {
  264. let info = &mut *self.info.lock().await;
  265. info.last_msg = packet.command.clone();
  266. info.last_status = "recv".to_string();
  267. let time = NanoTimestamp::current_time();
  268. //let time = time::unix_timestamp()?;
  269. info.log.lock().await.push((time, "recv".to_string(), packet.command.clone()));
  270. }
  271. // Send result to our subscribers
  272. self.message_subsystem.notify(&packet.command, packet.payload).await;
  273. }
  274. }
  275. /// Handle network errors. Panic if error passes silently, otherwise
  276. /// broadcast the error.
  277. async fn handle_stop(self: Arc<Self>, result: Result<()>) {
  278. debug!(target: "net", "Channel::handle_stop() [START, address={}]", self.address());
  279. match result {
  280. Ok(()) => panic!("Channel task should never complete without error status"),
  281. Err(err) => {
  282. // Send this error to all channel subscribers
  283. self.message_subsystem.trigger_error(err).await;
  284. }
  285. }
  286. debug!(target: "net", "Channel::handle_stop() [END, address={}]", self.address());
  287. }
  288. fn session(&self) -> Arc<dyn Session> {
  289. self.session.upgrade().unwrap()
  290. }
  291. pub fn session_type_id(&self) -> SessionBitflag {
  292. let session = self.session();
  293. session.type_id()
  294. }
  295. }