subscriber.rs 3.5 KB

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