message_publisher.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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. use std::{any::Any, collections::HashMap, sync::Arc, time::Duration};
  19. use async_trait::async_trait;
  20. use futures::stream::{FuturesUnordered, StreamExt};
  21. use log::{debug, error, warn};
  22. use rand::{rngs::OsRng, Rng};
  23. use smol::{io::AsyncReadExt, lock::Mutex};
  24. use super::message::Message;
  25. use crate::{net::transport::PtStream, system::timeout::timeout, Error, Result};
  26. use darkfi_serial::{AsyncDecodable, VarInt};
  27. /// 64-bit identifier for message subscription.
  28. pub type MessageSubscriptionId = u64;
  29. type MessageResult<M> = Result<Arc<M>>;
  30. /// A dispatcher that is unique to every [`Message`].
  31. /// Maintains a list of subscriptions to a unique Message
  32. /// type and handles sending messages across these
  33. /// subscriptions.
  34. #[derive(Debug)]
  35. struct MessageDispatcher<M: Message> {
  36. subs: Mutex<HashMap<MessageSubscriptionId, smol::channel::Sender<MessageResult<M>>>>,
  37. }
  38. impl<M: Message> MessageDispatcher<M> {
  39. /// Create a new message dispatcher
  40. fn new() -> Self {
  41. Self { subs: Mutex::new(HashMap::new()) }
  42. }
  43. /// Create a random ID.
  44. fn random_id() -> MessageSubscriptionId {
  45. OsRng.gen()
  46. }
  47. /// Subscribe to a channel.
  48. /// Assigns a new ID and adds it to the list of subscriptions.
  49. pub async fn subscribe(self: Arc<Self>) -> MessageSubscription<M> {
  50. let (sender, recv_queue) = smol::channel::unbounded();
  51. // Guard against overwriting
  52. let mut id = Self::random_id();
  53. let mut subs = self.subs.lock().await;
  54. loop {
  55. if subs.contains_key(&id) {
  56. id = Self::random_id();
  57. continue
  58. }
  59. subs.insert(id, sender);
  60. break
  61. }
  62. drop(subs);
  63. MessageSubscription { id, recv_queue, parent: self }
  64. }
  65. /// Unsubscribe from a channel.
  66. /// Removes the associated ID from the subscriber list.
  67. async fn unsubscribe(&self, sub_id: MessageSubscriptionId) {
  68. self.subs.lock().await.remove(&sub_id);
  69. }
  70. /// Private function to concurrently transmit a message to all subscriber channels.
  71. /// Automatically clear all inactive channels. Strictly used internally.
  72. async fn _trigger_all(&self, message: MessageResult<M>) {
  73. let mut subs = self.subs.lock().await;
  74. debug!(
  75. target: "net::message_publisher::_trigger_all()", "START msg={}({}), subs={}",
  76. if message.is_ok() { "Ok" } else {"Err"},
  77. M::NAME, subs.len(),
  78. );
  79. let mut futures = FuturesUnordered::new();
  80. let mut garbage_ids = vec![];
  81. // Prep the futures for concurrent execution
  82. for (sub_id, sub) in &*subs {
  83. let sub_id = *sub_id;
  84. let sub = sub.clone();
  85. let message = message.clone();
  86. futures.push(async move {
  87. match sub.send(message).await {
  88. Ok(res) => Ok((sub_id, res)),
  89. Err(err) => Err((sub_id, err)),
  90. }
  91. });
  92. }
  93. // Start polling
  94. while let Some(r) = futures.next().await {
  95. if let Err((sub_id, _err)) = r {
  96. garbage_ids.push(sub_id);
  97. }
  98. }
  99. // Garbage cleanup
  100. for sub_id in garbage_ids {
  101. subs.remove(&sub_id);
  102. }
  103. debug!(
  104. target: "net::message_publisher::_trigger_all()", "END msg={}({}), subs={}",
  105. if message.is_ok() { "Ok" } else { "Err" },
  106. M::NAME, subs.len(),
  107. );
  108. }
  109. }
  110. /// Handles message subscriptions through a subscription ID and
  111. /// a receiver channel.
  112. #[derive(Debug)]
  113. pub struct MessageSubscription<M: Message> {
  114. id: MessageSubscriptionId,
  115. recv_queue: smol::channel::Receiver<MessageResult<M>>,
  116. parent: Arc<MessageDispatcher<M>>,
  117. }
  118. impl<M: Message> MessageSubscription<M> {
  119. /// Start receiving messages.
  120. pub async fn receive(&self) -> MessageResult<M> {
  121. match self.recv_queue.recv().await {
  122. Ok(message) => message,
  123. Err(e) => panic!("MessageSubscription::receive(): recv_queue failed! {}", e),
  124. }
  125. }
  126. /// Start receiving messages with timeout.
  127. pub async fn receive_with_timeout(&self, seconds: u64) -> MessageResult<M> {
  128. let dur = Duration::from_secs(seconds);
  129. let Ok(res) = timeout(dur, self.recv_queue.recv()).await else {
  130. return Err(Error::ConnectTimeout)
  131. };
  132. match res {
  133. Ok(message) => message,
  134. Err(e) => {
  135. panic!("MessageSubscription::receive_with_timeout(): recv_queue failed! {}", e)
  136. }
  137. }
  138. }
  139. /// Cleans existing items from the receiver channel.
  140. pub async fn clean(&self) -> Result<()> {
  141. loop {
  142. match self.recv_queue.try_recv() {
  143. Ok(_) => continue,
  144. Err(smol::channel::TryRecvError::Empty) => return Ok(()),
  145. Err(e) => panic!("MessageSubscription::receive(): recv_queue failed! {}", e),
  146. }
  147. }
  148. }
  149. /// Unsubscribe from a message subscription. Must be called manually.
  150. pub async fn unsubscribe(&self) {
  151. self.parent.unsubscribe(self.id).await
  152. }
  153. }
  154. /// Generic interface for the message dispatcher.
  155. #[async_trait]
  156. trait MessageDispatcherInterface: Send + Sync {
  157. async fn trigger(&self, stream: &mut smol::io::ReadHalf<Box<dyn PtStream + 'static>>);
  158. async fn trigger_error(&self, err: Error);
  159. fn as_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
  160. }
  161. /// Local implementation of the Message Dispatcher Interface
  162. #[async_trait]
  163. impl<M: Message> MessageDispatcherInterface for MessageDispatcher<M> {
  164. /// Internal function to deserialize data into a message type
  165. /// and dispatch it across subscriber channels. Reads directly
  166. /// from an inbound stream.
  167. ///
  168. /// We extract the message length from the stream and use `take()`
  169. /// to allocate an appropiately sized buffer as a basic DDOS protection.
  170. async fn trigger(&self, stream: &mut smol::io::ReadHalf<Box<dyn PtStream + 'static>>) {
  171. match VarInt::decode_async(stream).await {
  172. Ok(int) => {
  173. // TODO: check the message length does not exceed some bound.
  174. let len = int.0;
  175. let mut take = stream.take(len);
  176. // Deserialize stream into type, send down the pipes.
  177. match M::decode_async(&mut take).await {
  178. Ok(payload) => {
  179. let message = Ok(Arc::new(payload));
  180. self._trigger_all(message).await
  181. }
  182. Err(err) => {
  183. error!(
  184. target: "net::message_publisher::trigger()",
  185. "Unable to decode data. Dropping...: {}",
  186. err,
  187. );
  188. }
  189. }
  190. }
  191. Err(err) => {
  192. error!(
  193. target: "net::message_publisher::trigger()",
  194. "Unable to decode VarInt. Dropping...: {}",
  195. err,
  196. );
  197. }
  198. }
  199. }
  200. /// Internal function that sends an error message to all subscriber channels.
  201. async fn trigger_error(&self, err: Error) {
  202. self._trigger_all(Err(err)).await;
  203. }
  204. /// Converts to `Any` trait. Enables the dynamic modification of static types.
  205. fn as_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
  206. self
  207. }
  208. }
  209. /// Generic publish/subscribe class that maintains a list of dispatchers.
  210. /// Dispatchers transmit messages to subscribers and are specific to one
  211. /// message type.
  212. #[derive(Default)]
  213. pub struct MessageSubsystem {
  214. dispatchers: Mutex<HashMap<&'static str, Arc<dyn MessageDispatcherInterface>>>,
  215. }
  216. impl MessageSubsystem {
  217. /// Create a new message subsystem.
  218. pub fn new() -> Self {
  219. Self { dispatchers: Mutex::new(HashMap::new()) }
  220. }
  221. /// Add a new dispatcher for specified [`Message`].
  222. pub async fn add_dispatch<M: Message>(&self) {
  223. self.dispatchers.lock().await.insert(M::NAME, Arc::new(MessageDispatcher::<M>::new()));
  224. }
  225. /// Subscribes to a [`Message`]. Using the Message name, the method
  226. /// returns the associated `MessageDispatcher` from the list of
  227. /// dispatchers and calls `subscribe()`.
  228. pub async fn subscribe<M: Message>(&self) -> Result<MessageSubscription<M>> {
  229. let dispatcher = self.dispatchers.lock().await.get(M::NAME).cloned();
  230. let sub = match dispatcher {
  231. Some(dispatcher) => {
  232. let dispatcher: Arc<MessageDispatcher<M>> = dispatcher
  233. .as_any()
  234. .downcast::<MessageDispatcher<M>>()
  235. .expect("Multiple messages registered with different names");
  236. dispatcher.subscribe().await
  237. }
  238. None => {
  239. // Normal return failure here
  240. return Err(Error::NetworkOperationFailed)
  241. }
  242. };
  243. Ok(sub)
  244. }
  245. /// Transmits a payload to a dispatcher.
  246. /// Returns an error if the payload fails to transmit.
  247. pub async fn notify(
  248. &self,
  249. command: &str,
  250. reader: &mut smol::io::ReadHalf<Box<dyn PtStream + 'static>>,
  251. ) -> Result<()> {
  252. let Some(dispatcher) = self.dispatchers.lock().await.get(command).cloned() else {
  253. warn!(
  254. target: "net::message_publisher::notify",
  255. "message_publisher::notify: Command '{}' did not find a dispatcher",
  256. command,
  257. );
  258. return Err(Error::MissingDispatcher)
  259. };
  260. dispatcher.trigger(reader).await;
  261. Ok(())
  262. }
  263. /// Concurrently transmits an error message across dispatchers.
  264. pub async fn trigger_error(&self, err: Error) {
  265. let mut futures = FuturesUnordered::new();
  266. let dispatchers = self.dispatchers.lock().await;
  267. for dispatcher in dispatchers.values() {
  268. let dispatcher = dispatcher.clone();
  269. let error = err.clone();
  270. futures.push(async move { dispatcher.trigger_error(error).await });
  271. }
  272. drop(dispatchers);
  273. while let Some(_r) = futures.next().await {}
  274. }
  275. }