pubsub.rs 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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 rand::{rngs::OsRng, Rng};
  19. use std::{
  20. collections::HashMap,
  21. sync::{Arc, Mutex},
  22. };
  23. use crate::error::{Error, Result};
  24. pub type SubscriptionId = usize;
  25. // Waiting for trait aliases
  26. pub trait Piped: Clone + Send + 'static {}
  27. impl<T> Piped for T where T: Clone + Send + 'static {}
  28. #[derive(Debug)]
  29. /// Subscription to the Publisher. Created using `publisher.subscribe().await`.
  30. pub struct Subscription<T: Piped> {
  31. id: SubscriptionId,
  32. recv_queue: smol::channel::Receiver<T>,
  33. parent: Arc<Publisher<T>>,
  34. }
  35. impl<T: Piped> Subscription<T> {
  36. pub fn get_id(&self) -> SubscriptionId {
  37. self.id
  38. }
  39. /// Receive message.
  40. pub async fn receive(&self) -> Result<T> {
  41. let msg_result = self.recv_queue.recv().await;
  42. msg_result.or(Err(Error::PublisherDestroyed))
  43. }
  44. }
  45. impl<T: Piped> Drop for Subscription<T> {
  46. fn drop(&mut self) {
  47. self.parent.unsubscribe(self.id)
  48. }
  49. }
  50. pub type PublisherPtr<T> = Arc<Publisher<T>>;
  51. #[derive(Debug)]
  52. pub struct Publisher<T> {
  53. subs: Mutex<HashMap<SubscriptionId, smol::channel::Sender<T>>>,
  54. }
  55. impl<T: Piped> Publisher<T> {
  56. pub fn new() -> Arc<Self> {
  57. Arc::new(Self { subs: Mutex::new(HashMap::new()) })
  58. }
  59. pub fn subscribe(self: Arc<Self>) -> Subscription<T> {
  60. let (sendr, recvr) = smol::channel::unbounded();
  61. let sub_id = OsRng.gen();
  62. // Optional to check whether this ID already exists.
  63. // It is nearly impossible to ever happen.
  64. self.subs.lock().unwrap().insert(sub_id, sendr);
  65. Subscription { id: sub_id, recv_queue: recvr, parent: self.clone() }
  66. }
  67. fn unsubscribe(&self, sub_id: SubscriptionId) {
  68. self.subs.lock().unwrap().remove(&sub_id);
  69. }
  70. /// Publish a message to subscriptions in the include list
  71. pub fn notify_with_include(&self, message_result: T, include_list: &[SubscriptionId]) {
  72. // Maybe we should just provide a method to get all IDs
  73. // Then people can call notify_with_exclude() instead.
  74. // TODO: just collect and clone directly into a Vec
  75. let subs = self.subs.lock().unwrap().clone();
  76. for (id, sub) in subs.into_iter() {
  77. if !include_list.contains(&id) {
  78. continue
  79. }
  80. if let Err(e) = sub.try_send(message_result.clone()) {
  81. panic!("[system::publisher] Error returned sending message in notify_with_include() call! {}", e);
  82. }
  83. }
  84. }
  85. /// Publish a message to all listening subscriptions.
  86. pub fn notify(&self, msg: T) {
  87. let subs = self.subs.lock().unwrap().clone();
  88. for (id, sub) in subs {
  89. if let Err(e) = sub.try_send(msg.clone()) {
  90. // This should never happen since Drop calls unsubscribe()
  91. panic!("Error in notify() call for sub={}! {}", id, e);
  92. }
  93. }
  94. }
  95. }