1use std::{
38 collections::HashMap,
39 pin::Pin,
40 sync::{Arc, Weak},
41 task::{Context, Poll},
42};
43
44use futures::stream::{FusedStream, Stream};
45use parking_lot::ReentrantMutex;
47use std::cell::RefCell;
48
49use crate::{
50 id_sequence::SeqID,
51 mpsc::{TracingUnboundedReceiver, TracingUnboundedSender},
52};
53
54#[cfg(test)]
55mod tests;
56
57pub trait Unsubscribe {
59 fn unsubscribe(&mut self, subs_id: SeqID);
61}
62
63pub trait Subscribe<K> {
65 fn subscribe(&mut self, subs_key: K, subs_id: SeqID);
67}
68
69pub trait Dispatch<M> {
71 type Item;
73 type Ret;
75
76 fn dispatch<F>(&mut self, message: M, dispatch: F) -> Self::Ret
84 where
85 F: FnMut(&SeqID, Self::Item);
86}
87
88#[derive(Debug)]
94pub struct Hub<M, R> {
95 tracing_key: &'static str,
96 shared: Arc<ReentrantMutex<RefCell<Shared<M, R>>>>,
97}
98
99#[derive(Debug)]
104pub struct Receiver<M, R>
105where
106 R: Unsubscribe,
107{
108 rx: TracingUnboundedReceiver<M>,
109
110 shared: Weak<ReentrantMutex<RefCell<Shared<M, R>>>>,
111 subs_id: SeqID,
112}
113
114#[derive(Debug)]
115struct Shared<M, R> {
116 id_sequence: crate::id_sequence::IDSequence,
117 registry: R,
118 sinks: HashMap<SeqID, TracingUnboundedSender<M>>,
119}
120
121impl<M, R> Hub<M, R>
122where
123 R: Unsubscribe,
124{
125 pub fn map_registry_for_tests<MapF, Ret>(&self, map: MapF) -> Ret
127 where
128 MapF: FnOnce(&R) -> Ret,
129 {
130 let shared_locked = self.shared.lock();
131 let shared_borrowed = shared_locked.borrow();
132 map(&shared_borrowed.registry)
133 }
134}
135
136impl<M, R> Drop for Receiver<M, R>
137where
138 R: Unsubscribe,
139{
140 fn drop(&mut self) {
141 if let Some(shared) = self.shared.upgrade() {
142 shared.lock().borrow_mut().unsubscribe(self.subs_id);
143 }
144 }
145}
146
147impl<M, R> Hub<M, R> {
148 pub fn new(tracing_key: &'static str) -> Self
150 where
151 R: Default,
152 {
153 Self::new_with_registry(tracing_key, Default::default())
154 }
155
156 pub fn new_with_registry(tracing_key: &'static str, registry: R) -> Self {
158 let shared =
159 Shared { registry, sinks: Default::default(), id_sequence: Default::default() };
160 let shared = Arc::new(ReentrantMutex::new(RefCell::new(shared)));
161 Self { tracing_key, shared }
162 }
163
164 pub fn subscribe<K>(&self, subs_key: K, queue_size_warning: usize) -> Receiver<M, R>
168 where
169 R: Subscribe<K> + Unsubscribe,
170 {
171 let shared_locked = self.shared.lock();
172 let mut shared_borrowed = shared_locked.borrow_mut();
173
174 let subs_id = shared_borrowed.id_sequence.next_id();
175
176 shared_borrowed.registry.subscribe(subs_key, subs_id);
180
181 let (tx, rx) = crate::mpsc::tracing_unbounded(self.tracing_key, queue_size_warning);
182 assert!(shared_borrowed.sinks.insert(subs_id, tx).is_none(), "Used IDSequence to create another ID. Should be unique until u64 is overflowed. Should be unique.");
183
184 Receiver { shared: Arc::downgrade(&self.shared), subs_id, rx }
185 }
186
187 pub fn send<Trigger>(&self, trigger: Trigger) -> <R as Dispatch<Trigger>>::Ret
191 where
192 R: Dispatch<Trigger, Item = M>,
193 {
194 let shared_locked = self.shared.lock();
195 let mut shared_borrowed = shared_locked.borrow_mut();
196 let (registry, sinks) = shared_borrowed.get_mut();
197
198 registry.dispatch(trigger, |subs_id, item| {
199 if let Some(tx) = sinks.get_mut(subs_id) {
200 if let Err(send_err) = tx.unbounded_send(item) {
201 log::warn!("Sink with SubsID = {} failed to perform unbounded_send: {} ({} as Dispatch<{}, Item = {}>::dispatch(...))", subs_id, send_err, std::any::type_name::<R>(),
202 std::any::type_name::<Trigger>(),
203 std::any::type_name::<M>());
204 }
205 } else {
206 log::warn!(
207 "No Sink for SubsID = {} ({} as Dispatch<{}, Item = {}>::dispatch(...))",
208 subs_id,
209 std::any::type_name::<R>(),
210 std::any::type_name::<Trigger>(),
211 std::any::type_name::<M>(),
212 );
213 }
214 })
215 }
216}
217
218impl<M, R> Shared<M, R> {
219 fn get_mut(&mut self) -> (&mut R, &mut HashMap<SeqID, TracingUnboundedSender<M>>) {
220 (&mut self.registry, &mut self.sinks)
221 }
222
223 fn unsubscribe(&mut self, subs_id: SeqID)
224 where
225 R: Unsubscribe,
226 {
227 self.sinks.remove(&subs_id);
231 self.registry.unsubscribe(subs_id);
232 }
233}
234
235impl<M, R> Clone for Hub<M, R> {
236 fn clone(&self) -> Self {
237 Self { tracing_key: self.tracing_key, shared: self.shared.clone() }
238 }
239}
240
241impl<M, R> Unpin for Receiver<M, R> where R: Unsubscribe {}
242
243impl<M, R> Stream for Receiver<M, R>
244where
245 R: Unsubscribe,
246{
247 type Item = M;
248
249 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
250 Pin::new(&mut self.get_mut().rx).poll_next(cx)
251 }
252}
253
254impl<Ch, R> FusedStream for Receiver<Ch, R>
255where
256 R: Unsubscribe,
257{
258 fn is_terminated(&self) -> bool {
259 self.rx.is_terminated()
260 }
261}