message_subscriber.rs 9.1 KB

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