message_subscriber.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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, io::Cursor};
  19. use async_std::sync::{Arc, Mutex};
  20. use async_trait::async_trait;
  21. use futures::stream::{FuturesUnordered, StreamExt};
  22. use log::{debug, warn};
  23. use rand::{rngs::OsRng, Rng};
  24. use super::message::Message;
  25. use crate::{Error, Result};
  26. /// 64-bit identifier for message subscription.
  27. pub type MessageSubscriptionId = u64;
  28. type MessageResult<M> = Result<Arc<M>>;
  29. /// A dispatcher that is unique to every [`Message`].
  30. /// Maintains a list of subscribers that are subscribed to that
  31. /// unique Message type and handles sending messages across these
  32. /// subscriptions.
  33. #[derive(Debug)]
  34. struct MessageDispatcher<M: Message> {
  35. subs: Mutex<HashMap<MessageSubscriptionId, smol::channel::Sender<MessageResult<M>>>>,
  36. }
  37. impl<M: Message> MessageDispatcher<M> {
  38. /// Create a new message dispatcher
  39. fn new() -> Self {
  40. Self { subs: Mutex::new(HashMap::new()) }
  41. }
  42. /// Create a random ID.
  43. fn random_id() -> MessageSubscriptionId {
  44. //let mut rng = rand::thread_rng();
  45. OsRng.gen()
  46. }
  47. /// Subscribe to a channel.
  48. /// Assigns a new ID and adds it to the list of subscribers.
  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_subscriber::_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_subscriber::_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. /// Unsubscribe from a message subscription. Must be called manually.
  127. pub async fn unsubscribe(&self) {
  128. self.parent.unsubscribe(self.id).await
  129. }
  130. }
  131. /// Generic interface for the message dispatcher.
  132. #[async_trait]
  133. trait MessageDispatcherInterface: Send + Sync {
  134. async fn trigger(&self, payload: &[u8]);
  135. async fn trigger_error(&self, err: Error);
  136. fn as_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
  137. }
  138. /// Local implementation of the Message Dispatcher Interface
  139. #[async_trait]
  140. impl<M: Message> MessageDispatcherInterface for MessageDispatcher<M> {
  141. /// Internal function to deserialize data into a message type
  142. /// and dispatch it across subscriber channels.
  143. async fn trigger(&self, payload: &[u8]) {
  144. // Deserialize data into type, send down the pipes.
  145. let cursor = Cursor::new(payload);
  146. match M::decode(cursor) {
  147. Ok(message) => {
  148. let message = Ok(Arc::new(message));
  149. self._trigger_all(message).await
  150. }
  151. Err(err) => {
  152. debug!(
  153. target: "net::message_subscriber::trigger()",
  154. "Unable to decode data. Dropping...: {}",
  155. err,
  156. );
  157. }
  158. }
  159. }
  160. /// Internal function that sends an error message to all subscriber channels.
  161. async fn trigger_error(&self, err: Error) {
  162. self._trigger_all(Err(err)).await;
  163. }
  164. /// Converts to `Any` trait. Enables the dynamic modification of static types.
  165. fn as_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
  166. self
  167. }
  168. }
  169. /// Generic publish/subscribe class that maintains a list of dispatchers.
  170. /// Dispatchers transmit messages to subscribers and are specific to one
  171. /// message type.
  172. #[derive(Default)]
  173. pub struct MessageSubsystem {
  174. dispatchers: Mutex<HashMap<&'static str, Arc<dyn MessageDispatcherInterface>>>,
  175. }
  176. impl MessageSubsystem {
  177. /// Create a new message subsystem.
  178. pub fn new() -> Self {
  179. Self { dispatchers: Mutex::new(HashMap::new()) }
  180. }
  181. /// Add a new dispatcher for specified [`Message`].
  182. pub async fn add_dispatch<M: Message>(&self) {
  183. self.dispatchers.lock().await.insert(M::NAME, Arc::new(MessageDispatcher::<M>::new()));
  184. }
  185. /// Subscribes to a [`Message`]. Using the Message name, the method
  186. /// returns the associated [`MessageDispatcher`] from the list of
  187. /// dispatchers and calls `subscribe()`.
  188. pub async fn subscribe<M: Message>(&self) -> Result<MessageSubscription<M>> {
  189. let dispatcher = self.dispatchers.lock().await.get(M::NAME).cloned();
  190. let sub = match dispatcher {
  191. Some(dispatcher) => {
  192. let dispatcher: Arc<MessageDispatcher<M>> = dispatcher
  193. .as_any()
  194. .downcast::<MessageDispatcher<M>>()
  195. .expect("Multiple messages registered with different names");
  196. dispatcher.subscribe().await
  197. }
  198. None => {
  199. // Normal return failure here
  200. return Err(Error::NetworkOperationFailed)
  201. }
  202. };
  203. Ok(sub)
  204. }
  205. /// Transmits a payload to a dispatcher.
  206. /// Returns an error if the payload fails to transmit.
  207. pub async fn notify(&self, command: &str, payload: &[u8]) {
  208. let Some(dispatcher) = self.dispatchers.lock().await.get(command).cloned() else {
  209. warn!(
  210. target: "net::message_subscriber::notify",
  211. "message_subscriber::notify: Command '{}' did not find a dispatcher",
  212. command,
  213. );
  214. return
  215. };
  216. dispatcher.trigger(payload).await;
  217. }
  218. /// Concurrently transmits an error message across dispatchers.
  219. pub async fn trigger_error(&self, err: Error) {
  220. let mut futures = FuturesUnordered::new();
  221. let dispatchers = self.dispatchers.lock().await;
  222. for dispatcher in dispatchers.values() {
  223. let dispatcher = dispatcher.clone();
  224. let error = err.clone();
  225. futures.push(async move { dispatcher.trigger_error(error).await });
  226. }
  227. drop(dispatchers);
  228. while let Some(_r) = futures.next().await {}
  229. }
  230. }
  231. #[cfg(test)]
  232. mod tests {
  233. use super::*;
  234. use darkfi_serial::{serialize, SerialDecodable, SerialEncodable};
  235. #[async_std::test]
  236. async fn message_subscriber_test() {
  237. #[derive(SerialEncodable, SerialDecodable)]
  238. struct MyVersionMessage(pub u32);
  239. crate::impl_p2p_message!(MyVersionMessage, "verver");
  240. let subsystem = MessageSubsystem::new();
  241. subsystem.add_dispatch::<MyVersionMessage>().await;
  242. // Subscribe:
  243. // 1. Get dispatcher
  244. // 2. Cast to specific type
  245. // 3. Do sub, return sub
  246. let sub = subsystem.subscribe::<MyVersionMessage>().await.unwrap();
  247. // Receive message and publish:
  248. // 1. Based on string, lookup relevant dispatcher interface
  249. // 2. Publish data there
  250. let msg = MyVersionMessage(110);
  251. let payload = serialize(&msg);
  252. subsystem.notify("verver", &payload).await;
  253. // Receive:
  254. // 1. Do a get easy
  255. let msg2 = sub.receive().await.unwrap();
  256. assert_eq!(msg.0, msg2.0);
  257. // Trigger an error
  258. subsystem.trigger_error(Error::ChannelStopped).await;
  259. let msg2 = sub.receive().await;
  260. assert!(msg2.is_err());
  261. sub.unsubscribe().await;
  262. }
  263. }