1use std::{
2 collections::{BinaryHeap, HashMap},
3 hash::Hash,
4 sync::{Mutex, RwLock, atomic::AtomicBool},
5 time::{Duration, Instant},
6};
7
8use tokio::sync::oneshot::{self, Receiver, Sender};
9
10pub enum Reply<R, E> {
11 Ok(R),
12 Err(E),
13 Timeout,
14}
15
16#[derive(PartialEq, Eq)]
17struct RegisteredTimeout<Id>
18where
19 Id: Eq + Hash,
20{
21 id: Id,
22 expires_at: Instant,
23}
24
25impl<Id> Ord for RegisteredTimeout<Id>
26where
27 Id: Eq + Hash,
28{
29 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
30 other.expires_at.cmp(&self.expires_at)
31 }
32}
33
34impl<Id> PartialOrd for RegisteredTimeout<Id>
35where
36 Id: PartialEq + Eq + Hash,
37{
38 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
39 Some(self.cmp(other))
40 }
41}
42
43pub struct ReplyManager<Id, R, E>
44where
45 Id: Eq + Hash,
46{
47 replies_registry: Mutex<HashMap<Id, Sender<Reply<R, E>>>>,
48 registered_timeouts: RwLock<BinaryHeap<RegisteredTimeout<Id>>>,
49 clean_running: AtomicBool,
50 tick_interval: tokio::time::Duration,
52}
53
54impl<Id, R, E> ReplyManager<Id, R, E>
55where
56 Id: Eq + Hash + Clone,
57{
58 pub fn new(tick_interval: tokio::time::Duration) -> Self {
59 Self {
60 replies_registry: Mutex::new(HashMap::new()),
61 registered_timeouts: RwLock::new(BinaryHeap::new()),
62 clean_running: AtomicBool::new(false),
63 tick_interval,
64 }
65 }
66
67 pub fn register(&self, id: impl Into<Id>, expires_in: Duration) -> Receiver<Reply<R, E>> {
68 let (tx, rx) = oneshot::channel::<Reply<R, E>>();
69
70 let id = id.into();
71 self.replies_registry
72 .lock()
73 .expect("Should lock always be acquirable")
74 .insert(id.clone(), tx);
75
76 self.registered_timeouts
77 .write()
78 .expect("Should write lock always be acquirable")
79 .push(RegisteredTimeout {
80 id,
81 expires_at: Instant::now()
82 .checked_add(expires_in)
83 .expect("Should expires never overflow internal structure"),
84 });
85 rx
86 }
87
88 pub fn ok(&self, id: &Id, result: R) {
89 if let Some(pending_reply) = self.replies_registry.lock().expect("").remove(id) {
90 let _ = pending_reply.send(Reply::Ok(result));
91 }
92 }
93
94 pub fn error(&self, id: &Id, error: E) {
95 if let Some(pending_reply) = self.replies_registry.lock().expect("").remove(id) {
96 let _ = pending_reply.send(Reply::Err(error));
97 }
98 }
99
100 pub async fn vacuum(&self) {
101 if self
102 .clean_running
103 .swap(true, std::sync::atomic::Ordering::AcqRel)
104 {
105 return;
106 }
107
108 tokio::time::sleep(self.tick_interval).await;
109
110 let now = Instant::now();
111 loop {
112 if let Some(registered_timeout) = self
113 .registered_timeouts
114 .read()
115 .expect("Should read lock always be acquirable")
116 .peek()
117 {
118 if now < registered_timeout.expires_at {
119 break;
120 }
121 } else {
122 break;
123 }
124
125 let registered_timeout = self
126 .registered_timeouts
127 .write()
128 .expect("Should write lock always be acquirable")
129 .pop()
130 .expect("Should always exists timeout entry if checked before");
131
132 if let Some(pending_reply) = self
133 .replies_registry
134 .lock()
135 .expect("")
136 .remove(®istered_timeout.id)
137 {
138 let _ = pending_reply.send(Reply::Timeout);
139 }
140 }
141
142 self.clean_running
143 .store(false, std::sync::atomic::Ordering::Release);
144 }
145}