subscriber.rs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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::collections::HashMap;
  19. use async_std::sync::{Arc, Mutex};
  20. use log::warn;
  21. use rand::Rng;
  22. pub type SubscriberPtr<T> = Arc<Subscriber<T>>;
  23. pub type SubscriptionId = u64;
  24. pub struct Subscription<T> {
  25. id: SubscriptionId,
  26. recv_queue: smol::channel::Receiver<T>,
  27. parent: Arc<Subscriber<T>>,
  28. }
  29. impl<T: Clone> Subscription<T> {
  30. pub fn get_id(&self) -> SubscriptionId {
  31. self.id
  32. }
  33. pub async fn receive(&self) -> T {
  34. let message_result = self.recv_queue.recv().await;
  35. match message_result {
  36. Ok(message_result) => message_result,
  37. Err(err) => {
  38. panic!("MessageSubscription::receive() recv_queue failed! {}", err);
  39. }
  40. }
  41. }
  42. // Must be called manually since async Drop is not possible in Rust
  43. pub async fn unsubscribe(&self) {
  44. self.parent.clone().unsubscribe(self.id).await
  45. }
  46. }
  47. // Simple broadcast (publish-subscribe) class
  48. pub struct Subscriber<T> {
  49. subs: Mutex<HashMap<u64, smol::channel::Sender<T>>>,
  50. }
  51. impl<T: Clone> Subscriber<T> {
  52. pub fn new() -> Arc<Self> {
  53. Arc::new(Self { subs: Mutex::new(HashMap::new()) })
  54. }
  55. fn random_id() -> SubscriptionId {
  56. let mut rng = rand::thread_rng();
  57. rng.gen()
  58. }
  59. pub async fn subscribe(self: Arc<Self>) -> Subscription<T> {
  60. let (sender, recvr) = smol::channel::unbounded();
  61. let sub_id = Self::random_id();
  62. self.subs.lock().await.insert(sub_id, sender);
  63. Subscription { id: sub_id, recv_queue: recvr, parent: self.clone() }
  64. }
  65. async fn unsubscribe(self: Arc<Self>, sub_id: SubscriptionId) {
  66. self.subs.lock().await.remove(&sub_id);
  67. }
  68. pub async fn notify(&self, message_result: T) {
  69. for sub in (*self.subs.lock().await).values() {
  70. if let Err(e) = sub.send(message_result.clone()).await {
  71. warn!(target: "system::subscriber", "Error returned sending message in notify() call! {}", e);
  72. }
  73. }
  74. }
  75. pub async fn notify_with_exclude(&self, message_result: T, exclude_list: &[SubscriptionId]) {
  76. for (id, sub) in (*self.subs.lock().await).iter() {
  77. if exclude_list.contains(id) {
  78. continue
  79. }
  80. if let Err(e) = sub.send(message_result.clone()).await {
  81. warn!(target: "system::subscriber", "Error returned sending message in notify_with_exclude() call! {}", e);
  82. }
  83. }
  84. }
  85. }