publisher.rs 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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 PublisherPtr<T> = Arc<Publisher<T>>;
  23. pub type SubscriptionId = usize;
  24. #[derive(Debug)]
  25. /// Subscription to the Publisher. Created using `publisher.subscribe().await`.
  26. pub struct Subscription<T> {
  27. id: SubscriptionId,
  28. recv_queue: smol::channel::Receiver<T>,
  29. parent: Arc<Publisher<T>>,
  30. }
  31. impl<T: Clone> Subscription<T> {
  32. pub fn get_id(&self) -> SubscriptionId {
  33. self.id
  34. }
  35. /// Receive message.
  36. pub async fn receive(&self) -> T {
  37. let message_result = self.recv_queue.recv().await;
  38. match message_result {
  39. Ok(message_result) => message_result,
  40. Err(err) => {
  41. panic!("Subscription::receive() recv_queue failed! {}", err);
  42. }
  43. }
  44. }
  45. /// Must be called manually since async Drop is not possible in Rust
  46. pub async fn unsubscribe(&self) {
  47. self.parent.clone().unsubscribe(self.id).await
  48. }
  49. }
  50. /// Simple broadcast (publish-subscribe) class.
  51. #[derive(Debug)]
  52. pub struct Publisher<T> {
  53. subs: Mutex<HashMap<SubscriptionId, smol::channel::Sender<T>>>,
  54. }
  55. impl<T: Clone> Publisher<T> {
  56. /// Construct a new publisher.
  57. pub fn new() -> Arc<Self> {
  58. Arc::new(Self { subs: Mutex::new(HashMap::new()) })
  59. }
  60. fn random_id() -> SubscriptionId {
  61. OsRng.gen()
  62. }
  63. /// Make sure you call this method early in your setup. That way the subscription
  64. /// will begin accumulating messages from notify.
  65. /// Then when your main loop begins calling `sub.receive().await`, the messages will
  66. /// already be queued.
  67. pub async fn subscribe(self: Arc<Self>) -> Subscription<T> {
  68. let (sender, recvr) = smol::channel::unbounded();
  69. // Poor-man's do/while
  70. let mut subs = self.subs.lock().await;
  71. let mut sub_id = Self::random_id();
  72. while subs.contains_key(&sub_id) {
  73. sub_id = Self::random_id();
  74. }
  75. subs.insert(sub_id, sender);
  76. Subscription { id: sub_id, recv_queue: recvr, parent: self.clone() }
  77. }
  78. async fn unsubscribe(self: Arc<Self>, sub_id: SubscriptionId) {
  79. self.subs.lock().await.remove(&sub_id);
  80. }
  81. /// Publish a message to all listening subscriptions.
  82. pub async fn notify(&self, message_result: T) {
  83. self.notify_with_exclude(message_result, &[]).await
  84. }
  85. /// Publish a message to all listening subscriptions but exclude some subset.
  86. pub async fn notify_with_exclude(&self, message_result: T, exclude_list: &[SubscriptionId]) {
  87. for (id, sub) in (*self.subs.lock().await).iter() {
  88. if exclude_list.contains(id) {
  89. continue
  90. }
  91. if let Err(e) = sub.send(message_result.clone()).await {
  92. warn!(
  93. target: "system::publisher",
  94. "[system::publisher] Error returned sending message in notify_with_exclude() call! {}", e,
  95. );
  96. }
  97. }
  98. }
  99. }