1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
use crate::{Id, Response};
use std::{
collections::HashMap,
sync::{Arc, Weak},
time::Duration,
};
use tokio::{
io,
sync::{mpsc, Mutex},
time,
};
#[derive(Clone)]
pub struct PostOffice<T> {
mailboxes: Arc<Mutex<HashMap<Id, mpsc::Sender<T>>>>,
}
impl<T> Default for PostOffice<T>
where
T: Send + 'static,
{
fn default() -> Self {
Self::new(Duration::from_secs(60))
}
}
impl<T> PostOffice<T>
where
T: Send + 'static,
{
pub fn new(cleanup: Duration) -> Self {
let mailboxes = Arc::new(Mutex::new(HashMap::new()));
let mref = Arc::downgrade(&mailboxes);
tokio::spawn(async move {
while let Some(m) = Weak::upgrade(&mref) {
m.lock()
.await
.retain(|_id, tx: &mut mpsc::Sender<T>| !tx.is_closed());
drop(m);
time::sleep(cleanup).await;
}
});
Self { mailboxes }
}
pub async fn make_mailbox(&self, id: Id, buffer: usize) -> Mailbox<T> {
let (tx, rx) = mpsc::channel(buffer);
self.mailboxes.lock().await.insert(id.clone(), tx);
Mailbox { id, rx }
}
pub async fn deliver(&self, id: &Id, value: T) -> bool {
if let Some(tx) = self.mailboxes.lock().await.get_mut(id) {
let success = tx.send(value).await.is_ok();
if !success {
self.mailboxes.lock().await.remove(id);
}
success
} else {
false
}
}
}
impl<T> PostOffice<Response<T>>
where
T: Send + 'static,
{
pub async fn deliver_response(&self, res: Response<T>) -> bool {
self.deliver(&res.origin_id.clone(), res).await
}
}
pub struct Mailbox<T> {
id: Id,
rx: mpsc::Receiver<T>,
}
impl<T> Mailbox<T> {
pub fn id(&self) -> &Id {
&self.id
}
pub async fn next(&mut self) -> Option<T> {
self.rx.recv().await
}
pub async fn next_timeout(&mut self, duration: Duration) -> io::Result<Option<T>> {
time::timeout(duration, self.next())
.await
.map_err(|x| io::Error::new(io::ErrorKind::TimedOut, x))
}
pub fn close(&mut self) {
self.rx.close()
}
}