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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#![forbid(unsafe_code)]
#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
use async_std::{channel, prelude::FutureExt, sync::Mutex};
use std::any::Any;
#[doc(hidden)]
#[cfg(feature = "derive")]
pub use async_reply_derive::*;
pub fn endpoints() -> (Requester, Replyer) {
let (sndr, recv) = channel::bounded(10);
(
Requester { inner: sndr },
Replyer {
buffer: Mutex::default(),
inner: recv,
},
)
}
#[derive(Debug, Clone)]
pub struct Requester {
inner: channel::Sender<Box<dyn Any + Send>>,
}
#[derive(Debug)]
pub struct Replyer {
buffer: Mutex<Vec<Box<dyn Any + Send>>>,
inner: channel::Receiver<Box<dyn Any + Send>>,
}
#[must_use = "ReplyHandle should be used to respond to the received message"]
#[derive(Debug)]
pub struct ReplyHandle<T>(channel::Sender<T>);
struct MessageHandle<M: Message> {
msg: M,
sndr: ReplyHandle<M::Response>,
}
pub trait Message: 'static + Send {
type Response: Send;
}
impl Requester {
pub async fn send<M>(&self, msg: M) -> Result<M::Response, Error>
where
M: Message,
{
let (sndr, recv) = channel::bounded::<M::Response>(1);
let sndr = ReplyHandle(sndr);
self.inner
.send(Box::new(MessageHandle { msg, sndr }))
.await?;
recv.recv().await.map_err(Error::ReplayError)
}
}
impl Replyer {
pub async fn recv<M>(&self) -> Result<(M, ReplyHandle<M::Response>), Error>
where
M: Message,
{
let is_message_type = |any: &Box<dyn Any + Send>| any.is::<MessageHandle<M>>();
loop {
let buffer_search_fut = async {
loop {
let mut buffer = self.buffer.lock().await;
let msg_index = buffer
.iter()
.enumerate()
.find(|(_, elem)| is_message_type(elem))
.map(|(index, _)| index);
if let Some(index) = msg_index {
return Ok(buffer.remove(index));
}
async_std::task::yield_now().await;
}
};
let channel_search_fut = async { self.inner.recv().await.map_err(Error::ReceivError) };
let msg = buffer_search_fut.race(channel_search_fut).await?;
if is_message_type(&msg) {
return Ok(msg.downcast::<MessageHandle<M>>().unwrap().into_tuple());
}
self.buffer.lock().await.push(msg);
}
}
}
impl<T> ReplyHandle<T> {
pub async fn respond(&self, r: T) -> Result<(), Error> {
Ok(self.0.send(r).await?)
}
}
impl<M: Message> MessageHandle<M> {
fn into_tuple(self) -> (M, ReplyHandle<M::Response>) {
(self.msg, self.sndr)
}
}
#[derive(Debug, derive_more::Display, derive_more::Error, derive_more::From)]
pub enum Error {
SendError,
#[from(ignore)]
#[display(transparent)]
ReplayError(async_std::channel::RecvError),
#[display(transparent)]
ReceivError(async_std::channel::RecvError),
}
impl<T> From<channel::SendError<T>> for Error {
fn from(_e: channel::SendError<T>) -> Self {
Error::SendError
}
}