pubsub.rs 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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. // NOTE: deliberately no Clone. Subscription's Drop unsubscribes it from
  36. // the publisher; a clone sharing the id would unsubscribe the original
  37. // when dropped. Share via Arc<Subscription<_>> instead.
  38. impl<T: Piped> Subscription<T> {
  39. pub fn get_id(&self) -> SubscriptionId {
  40. self.id
  41. }
  42. /// Receive message.
  43. pub async fn receive(&self) -> Result<T> {
  44. let msg_result = self.recv_queue.recv().await;
  45. msg_result.or(Err(Error::PublisherDestroyed))
  46. }
  47. }
  48. impl<T: Piped> Drop for Subscription<T> {
  49. fn drop(&mut self) {
  50. self.parent.unsubscribe(self.id)
  51. }
  52. }
  53. pub type PublisherPtr<T> = Arc<Publisher<T>>;
  54. #[derive(Debug)]
  55. pub struct Publisher<T> {
  56. subs: Mutex<HashMap<SubscriptionId, smol::channel::Sender<T>>>,
  57. }
  58. impl<T: Piped> Publisher<T> {
  59. pub fn new() -> Arc<Self> {
  60. Arc::new(Self { subs: Mutex::new(HashMap::new()) })
  61. }
  62. pub fn subscribe(self: Arc<Self>) -> Subscription<T> {
  63. let (sendr, recvr) = smol::channel::unbounded();
  64. let sub_id = OsRng.gen();
  65. // Optional to check whether this ID already exists.
  66. // It is nearly impossible to ever happen.
  67. self.subs.lock().unwrap().insert(sub_id, sendr);
  68. Subscription { id: sub_id, recv_queue: recvr, parent: self.clone() }
  69. }
  70. fn unsubscribe(&self, sub_id: SubscriptionId) {
  71. self.subs.lock().unwrap().remove(&sub_id);
  72. }
  73. /// Publish a message to subscriptions in the include list
  74. pub fn notify_with_include(&self, message_result: T, include_list: &[SubscriptionId]) {
  75. // Maybe we should just provide a method to get all IDs
  76. // Then people can call notify_with_exclude() instead.
  77. // TODO: just collect and clone directly into a Vec
  78. let subs = self.subs.lock().unwrap().clone();
  79. for (id, sub) in subs.into_iter() {
  80. if !include_list.contains(&id) {
  81. continue
  82. }
  83. if sub.try_send(message_result.clone()).is_err() {
  84. // The receiver was dropped before Drop::unsubscribe() took
  85. // effect, e.g. a task cancellation racing this notify.
  86. // Prune the dead subscription.
  87. self.subs.lock().unwrap().remove(&id);
  88. }
  89. }
  90. }
  91. /// Publish a message to all listening subscriptions.
  92. pub fn notify(&self, msg: T) {
  93. let subs = self.subs.lock().unwrap().clone();
  94. for (id, sub) in subs {
  95. if sub.try_send(msg.clone()).is_err() {
  96. // The receiver was dropped before Drop::unsubscribe() took
  97. // effect, e.g. a task cancellation racing this notify.
  98. // Prune the dead subscription.
  99. self.subs.lock().unwrap().remove(&id);
  100. }
  101. }
  102. }
  103. }