message_subscriber.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 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, sync::Arc};
  19. use async_std::sync::Mutex;
  20. use async_trait::async_trait;
  21. use log::{debug, warn};
  22. use rand::Rng;
  23. use crate::{Error, Result};
  24. use super::message::Message;
  25. /// 64bit identifier for message subscription.
  26. pub type MessageSubscriptionId = u64;
  27. type MessageResult<M> = Result<Arc<M>>;
  28. /// Handles message subscriptions through a subscription ID and a receiver
  29. /// channel.
  30. pub struct MessageSubscription<M: Message> {
  31. id: MessageSubscriptionId,
  32. recv_queue: smol::channel::Receiver<MessageResult<M>>,
  33. parent: Arc<MessageDispatcher<M>>,
  34. }
  35. impl<M: Message> MessageSubscription<M> {
  36. /// Start receiving messages.
  37. pub async fn receive(&self) -> MessageResult<M> {
  38. match self.recv_queue.recv().await {
  39. Ok(message) => message,
  40. Err(err) => {
  41. panic!("MessageSubscription::receive() recv_queue failed! {}", err);
  42. }
  43. }
  44. }
  45. /// Unsubscribe from a message subscription. Must be called manually.
  46. pub async fn unsubscribe(&self) {
  47. self.parent.clone().unsubscribe(self.id).await
  48. }
  49. }
  50. #[async_trait]
  51. /// Generic interface for message dispatcher.
  52. trait MessageDispatcherInterface: Send + Sync {
  53. async fn trigger(&self, payload: Vec<u8>);
  54. async fn trigger_error(&self, err: Error);
  55. fn as_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
  56. }
  57. /// A dispatchers that is unique to every Message. Maintains a list of subscribers that are subscribed to that unique Message type and handles sending messages across these subscriptions.
  58. struct MessageDispatcher<M: Message> {
  59. subs: Mutex<HashMap<MessageSubscriptionId, smol::channel::Sender<MessageResult<M>>>>,
  60. }
  61. impl<M: Message> MessageDispatcher<M> {
  62. /// Create a new message dispatcher.
  63. fn new() -> Self {
  64. MessageDispatcher { subs: Mutex::new(HashMap::new()) }
  65. }
  66. /// Create a random ID.
  67. fn random_id() -> MessageSubscriptionId {
  68. let mut rng = rand::thread_rng();
  69. rng.gen()
  70. }
  71. /// Subscribe to a channel. Assigns a new ID and adds it to the list of
  72. /// subscribers.
  73. pub async fn subscribe(self: Arc<Self>) -> MessageSubscription<M> {
  74. let (sender, recvr) = smol::channel::unbounded();
  75. let sub_id = Self::random_id();
  76. self.subs.lock().await.insert(sub_id, sender);
  77. MessageSubscription { id: sub_id, recv_queue: recvr, parent: self }
  78. }
  79. /// Unsubcribe from a channel. Removes the associated ID from the subscriber
  80. /// list.
  81. async fn unsubscribe(&self, sub_id: MessageSubscriptionId) {
  82. self.subs.lock().await.remove(&sub_id);
  83. }
  84. /// Private function to transmit a message to all subscriber channels. Automatically clear inactive
  85. /// channels. Used strictly internally.
  86. async fn _trigger_all(&self, message: MessageResult<M>) {
  87. debug!(
  88. target: "net",
  89. "MessageDispatcher<M={}>::trigger_all({}) [START, subs={}]",
  90. M::name(),
  91. if message.is_ok() { "msg" } else { "err" },
  92. self.subs.lock().await.len()
  93. );
  94. let mut garbage_ids = Vec::new();
  95. for (sub_id, sub) in &*self.subs.lock().await {
  96. match sub.send(message.clone()).await {
  97. Ok(()) => {}
  98. Err(_err) => {
  99. // Automatically clean out closed channels
  100. garbage_ids.push(*sub_id);
  101. // panic!("Error returned sending message in notify() call!
  102. // {}", err);
  103. }
  104. }
  105. }
  106. self.collect_garbage(garbage_ids).await;
  107. debug!(
  108. target: "net",
  109. "MessageDispatcher<M={}>::trigger_all({}) [END, subs={}]",
  110. M::name(),
  111. if message.is_ok() { "msg" } else { "err" },
  112. self.subs.lock().await.len()
  113. );
  114. }
  115. /// Remove inactive channels.
  116. async fn collect_garbage(&self, ids: Vec<MessageSubscriptionId>) {
  117. let mut subs = self.subs.lock().await;
  118. for id in &ids {
  119. subs.remove(id);
  120. }
  121. }
  122. }
  123. #[async_trait]
  124. // Local implementation of the Message Dispatcher Interface.
  125. impl<M: Message> MessageDispatcherInterface for MessageDispatcher<M> {
  126. /// Internal function to deserialize data into a message type and dispatch it across subscriber channels.
  127. async fn trigger(&self, payload: Vec<u8>) {
  128. // deserialize data into type
  129. // send down the pipes
  130. let cursor = Cursor::new(payload);
  131. match M::decode(cursor) {
  132. Ok(message) => {
  133. let message = Ok(Arc::new(message));
  134. self._trigger_all(message).await
  135. }
  136. Err(err) => {
  137. debug!("Unable to decode data. Dropping...: {}", err);
  138. }
  139. }
  140. }
  141. /// Interal function that sends a Error message to all subscriber channels.
  142. async fn trigger_error(&self, err: Error) {
  143. self._trigger_all(Err(err)).await;
  144. }
  145. /// Converts to Any trait. Enables the dynamic modification of static types.
  146. fn as_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
  147. self
  148. }
  149. }
  150. /// Generic publish/subscribe class that maintains a list of dispatchers. Dispatchers transmit
  151. /// messages to subscribers and are specific to one message type.
  152. pub struct MessageSubsystem {
  153. dispatchers: Mutex<HashMap<&'static str, Arc<dyn MessageDispatcherInterface>>>,
  154. }
  155. impl MessageSubsystem {
  156. /// Create a new message subsystem.
  157. pub fn new() -> Self {
  158. MessageSubsystem { dispatchers: Mutex::new(HashMap::new()) }
  159. }
  160. /// Add a new dispatcher for specified Message.
  161. pub async fn add_dispatch<M: Message>(&self) {
  162. self.dispatchers.lock().await.insert(M::name(), Arc::new(MessageDispatcher::<M>::new()));
  163. }
  164. /// Subscribes to a Message. Using the Message name, the method returns an the associated MessageDispatcher from the list of
  165. /// dispatchers and calls subscribe().
  166. pub async fn subscribe<M: Message>(&self) -> Result<MessageSubscription<M>> {
  167. let dispatcher = self.dispatchers.lock().await.get(M::name()).cloned();
  168. let sub = match dispatcher {
  169. Some(dispatcher) => {
  170. let dispatcher: Arc<MessageDispatcher<M>> = dispatcher
  171. .as_any()
  172. .downcast::<MessageDispatcher<M>>()
  173. .expect("Multiple messages registered with different names");
  174. dispatcher.subscribe().await
  175. }
  176. None => {
  177. // normall return failure here
  178. // for now panic
  179. return Err(Error::NetworkOperationFailed)
  180. }
  181. };
  182. Ok(sub)
  183. }
  184. /// Transmits a payload to a dispatcher. Returns an error if the payload
  185. /// fails to transmit.
  186. pub async fn notify(&self, command: &str, payload: Vec<u8>) {
  187. let dispatcher = self.dispatchers.lock().await.get(command).cloned();
  188. match dispatcher {
  189. Some(dispatcher) => {
  190. dispatcher.trigger(payload).await;
  191. }
  192. None => {
  193. warn!(
  194. target: "MessageSubsystem::notify",
  195. "MessageSubsystem::notify(\"{}\", payload) did not find a dispatcher",
  196. command
  197. );
  198. }
  199. }
  200. }
  201. /// Transmits an error message across dispatchers.
  202. pub async fn trigger_error(&self, err: Error) {
  203. // TODO: this could be parallelized
  204. for dispatcher in self.dispatchers.lock().await.values() {
  205. dispatcher.trigger_error(err.clone()).await;
  206. }
  207. }
  208. }
  209. impl Default for MessageSubsystem {
  210. fn default() -> Self {
  211. Self::new()
  212. }
  213. }
  214. /// Test functions for message subsystem.
  215. // This is a test function for the message subsystem code above
  216. // Normall we would use the #[test] macro but cannot since it is async code
  217. // Instead we call it using smol::block_on() in the unit test code after this
  218. // func
  219. #[cfg(test)]
  220. mod tests {
  221. use super::*;
  222. use darkfi_serial::{Decodable, Encodable};
  223. use std::io;
  224. #[async_std::test]
  225. async fn message_subscriber_test() {
  226. struct MyVersionMessage {
  227. x: u32,
  228. }
  229. impl Message for MyVersionMessage {
  230. fn name() -> &'static str {
  231. "verver"
  232. }
  233. }
  234. impl Encodable for MyVersionMessage {
  235. fn encode<S: io::Write>(&self, mut s: S) -> core::result::Result<usize, io::Error> {
  236. let mut len = 0;
  237. len += self.x.encode(&mut s)?;
  238. Ok(len)
  239. }
  240. }
  241. impl Decodable for MyVersionMessage {
  242. fn decode<D: io::Read>(mut d: D) -> core::result::Result<Self, io::Error> {
  243. Ok(Self { x: Decodable::decode(&mut d)? })
  244. }
  245. }
  246. println!("hello");
  247. let subsystem = MessageSubsystem::new();
  248. subsystem.add_dispatch::<MyVersionMessage>().await;
  249. // subscribe
  250. // 1. get dispatcher
  251. // 2. cast to specific type
  252. // 3. do sub, return sub
  253. let sub = subsystem.subscribe::<MyVersionMessage>().await.unwrap();
  254. let msg = MyVersionMessage { x: 110 };
  255. let mut payload = Vec::new();
  256. msg.encode(&mut payload).unwrap();
  257. // receive message and publish
  258. // 1. based on string, lookup relevant dispatcher interface
  259. // 2. publish data there
  260. subsystem.notify("verver", payload).await;
  261. // receive
  262. // 1. do a get easy
  263. let msg2 = sub.receive().await.unwrap();
  264. assert_eq!(msg2.x, 110);
  265. println!("{}", msg2.x);
  266. subsystem.trigger_error(Error::ChannelStopped).await;
  267. let msg2 = sub.receive().await;
  268. assert!(msg2.is_err());
  269. sub.unsubscribe().await;
  270. }
  271. }