message_subscriber.rs 9.1 KB

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