message_subscriber.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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, io::Cursor, sync::Arc, time::Duration};
  19. use async_trait::async_trait;
  20. use futures::stream::{FuturesUnordered, StreamExt};
  21. use log::{debug, warn};
  22. use rand::{rngs::OsRng, Rng};
  23. use smol::lock::Mutex;
  24. use super::message::Message;
  25. use crate::{system::timeout::timeout, 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. /// 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. /// Unsubscribe from a message subscription. Must be called manually.
  140. pub async fn unsubscribe(&self) {
  141. self.parent.unsubscribe(self.id).await
  142. }
  143. }
  144. /// Generic interface for the message dispatcher.
  145. #[async_trait]
  146. trait MessageDispatcherInterface: Send + Sync {
  147. async fn trigger(&self, payload: &[u8]);
  148. async fn trigger_error(&self, err: Error);
  149. fn as_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
  150. }
  151. /// Local implementation of the Message Dispatcher Interface
  152. #[async_trait]
  153. impl<M: Message> MessageDispatcherInterface for MessageDispatcher<M> {
  154. /// Internal function to deserialize data into a message type
  155. /// and dispatch it across subscriber channels.
  156. async fn trigger(&self, payload: &[u8]) {
  157. // Deserialize data into type, send down the pipes.
  158. let cursor = Cursor::new(payload);
  159. match M::decode(cursor) {
  160. Ok(message) => {
  161. let message = Ok(Arc::new(message));
  162. self._trigger_all(message).await
  163. }
  164. Err(err) => {
  165. debug!(
  166. target: "net::message_subscriber::trigger()",
  167. "Unable to decode data. Dropping...: {}",
  168. err,
  169. );
  170. }
  171. }
  172. }
  173. /// Internal function that sends an error message to all subscriber channels.
  174. async fn trigger_error(&self, err: Error) {
  175. self._trigger_all(Err(err)).await;
  176. }
  177. /// Converts to `Any` trait. Enables the dynamic modification of static types.
  178. fn as_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
  179. self
  180. }
  181. }
  182. /// Generic publish/subscribe class that maintains a list of dispatchers.
  183. /// Dispatchers transmit messages to subscribers and are specific to one
  184. /// message type.
  185. #[derive(Default)]
  186. pub struct MessageSubsystem {
  187. dispatchers: Mutex<HashMap<&'static str, Arc<dyn MessageDispatcherInterface>>>,
  188. }
  189. impl MessageSubsystem {
  190. /// Create a new message subsystem.
  191. pub fn new() -> Self {
  192. Self { dispatchers: Mutex::new(HashMap::new()) }
  193. }
  194. /// Add a new dispatcher for specified [`Message`].
  195. pub async fn add_dispatch<M: Message>(&self) {
  196. self.dispatchers.lock().await.insert(M::NAME, Arc::new(MessageDispatcher::<M>::new()));
  197. }
  198. /// Subscribes to a [`Message`]. Using the Message name, the method
  199. /// returns the associated `MessageDispatcher` from the list of
  200. /// dispatchers and calls `subscribe()`.
  201. pub async fn subscribe<M: Message>(&self) -> Result<MessageSubscription<M>> {
  202. let dispatcher = self.dispatchers.lock().await.get(M::NAME).cloned();
  203. let sub = match dispatcher {
  204. Some(dispatcher) => {
  205. let dispatcher: Arc<MessageDispatcher<M>> = dispatcher
  206. .as_any()
  207. .downcast::<MessageDispatcher<M>>()
  208. .expect("Multiple messages registered with different names");
  209. dispatcher.subscribe().await
  210. }
  211. None => {
  212. // Normal return failure here
  213. return Err(Error::NetworkOperationFailed)
  214. }
  215. };
  216. Ok(sub)
  217. }
  218. /// Transmits a payload to a dispatcher.
  219. /// Returns an error if the payload fails to transmit.
  220. pub async fn notify(&self, command: &str, payload: &[u8]) -> Result<()> {
  221. let Some(dispatcher) = self.dispatchers.lock().await.get(command).cloned() else {
  222. warn!(
  223. target: "net::message_subscriber::notify",
  224. "message_subscriber::notify: Command '{}' did not find a dispatcher",
  225. command,
  226. );
  227. return Err(Error::MissingDispatcher)
  228. };
  229. dispatcher.trigger(payload).await;
  230. Ok(())
  231. }
  232. /// Concurrently transmits an error message across dispatchers.
  233. pub async fn trigger_error(&self, err: Error) {
  234. let mut futures = FuturesUnordered::new();
  235. let dispatchers = self.dispatchers.lock().await;
  236. for dispatcher in dispatchers.values() {
  237. let dispatcher = dispatcher.clone();
  238. let error = err.clone();
  239. futures.push(async move { dispatcher.trigger_error(error).await });
  240. }
  241. drop(dispatchers);
  242. while let Some(_r) = futures.next().await {}
  243. }
  244. }
  245. #[cfg(test)]
  246. mod tests {
  247. use super::*;
  248. use darkfi_serial::{serialize, SerialDecodable, SerialEncodable};
  249. #[test]
  250. fn message_subscriber_test() {
  251. #[derive(SerialEncodable, SerialDecodable)]
  252. struct MyVersionMessage(pub u32);
  253. crate::impl_p2p_message!(MyVersionMessage, "verver");
  254. smol::block_on(async {
  255. let subsystem = MessageSubsystem::new();
  256. subsystem.add_dispatch::<MyVersionMessage>().await;
  257. // Subscribe:
  258. // 1. Get dispatcher
  259. // 2. Cast to specific type
  260. // 3. Do sub, return sub
  261. let sub = subsystem.subscribe::<MyVersionMessage>().await.unwrap();
  262. // Receive message and publish:
  263. // 1. Based on string, lookup relevant dispatcher interface
  264. // 2. Publish data there
  265. let msg = MyVersionMessage(110);
  266. let payload = serialize(&msg);
  267. subsystem.notify("verver", &payload).await.unwrap();
  268. // Receive:
  269. // 1. Do a get easy
  270. let msg2 = sub.receive().await.unwrap();
  271. assert_eq!(msg.0, msg2.0);
  272. // Trigger an error
  273. subsystem.trigger_error(Error::ChannelStopped).await;
  274. let msg2 = sub.receive().await;
  275. assert!(msg2.is_err());
  276. sub.unsubscribe().await;
  277. });
  278. }
  279. }