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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
use crate::*;
use concurrent_queue::PushError;
use event_listener::EventListener;
use futures::{Future, FutureExt};
use std::{
pin::Pin,
task::{Context, Poll},
};
use tokio::time::Sleep;
impl<M> Channel<M> {
pub fn send(&self, msg: M) -> Snd<'_, M> {
Snd::new(self, msg)
}
pub fn send_now(&self, msg: M) -> Result<(), TrySendError<M>> {
Ok(self.push_msg(msg)?)
}
pub fn try_send(&self, msg: M) -> Result<(), TrySendError<M>> {
match self.capacity() {
Capacity::Bounded(_) => Ok(self.push_msg(msg)?),
Capacity::Unbounded(backoff) => match backoff.get_timeout(self.msg_count()) {
Some(_) => Err(TrySendError::Full(msg)),
None => Ok(self.push_msg(msg)?),
},
}
}
pub fn send_blocking(&self, mut msg: M) -> Result<(), SendError<M>> {
match self.capacity() {
Capacity::Bounded(_) => loop {
msg = match self.push_msg(msg) {
Ok(()) => {
return Ok(());
}
Err(PushError::Closed(msg)) => {
return Err(SendError(msg));
}
Err(PushError::Full(msg)) => msg,
};
self.get_send_listener().wait();
},
Capacity::Unbounded(backoff) => {
let timeout = backoff.get_timeout(self.msg_count());
if let Some(timeout) = timeout {
std::thread::sleep(timeout);
}
self.push_msg(msg).map_err(|e| match e {
PushError::Full(_) => unreachable!("unbounded"),
PushError::Closed(msg) => SendError(msg),
})
}
}
}
}
#[derive(Debug)]
pub struct Snd<'a, M> {
channel: &'a Channel<M>,
msg: Option<M>,
fut: Option<SndFut>,
}
#[derive(Debug)]
enum SndFut {
Listener(EventListener),
Sleep(Pin<Box<Sleep>>),
}
impl Unpin for SndFut {}
impl Future for SndFut {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match &mut *self {
SndFut::Listener(listener) => listener.poll_unpin(cx),
SndFut::Sleep(sleep) => sleep.poll_unpin(cx),
}
}
}
impl<'a, M> Snd<'a, M> {
pub(crate) fn new(channel: &'a Channel<M>, msg: M) -> Self {
match &channel.capacity {
Capacity::Bounded(_) => Snd {
channel,
msg: Some(msg),
fut: None,
},
Capacity::Unbounded(back_pressure) => Snd {
channel,
msg: Some(msg),
fut: back_pressure
.get_timeout(channel.msg_count())
.map(|timeout| SndFut::Sleep(Box::pin(tokio::time::sleep(timeout)))),
},
}
}
fn poll_bounded_send(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), SendError<M>>> {
macro_rules! try_send {
($msg:ident) => {
match self.channel.try_send($msg) {
Ok(()) => return Poll::Ready(Ok(())),
Err(e) => match e {
TrySendError::Closed(msg) => return Poll::Ready(Err(SendError(msg))),
TrySendError::Full(msg_new) => $msg = msg_new,
},
}
};
}
let mut msg = self.msg.take().unwrap();
try_send!(msg);
loop {
if self.fut.is_none() {
self.fut = Some(SndFut::Listener(self.channel.get_send_listener()))
}
try_send!(msg);
match self.fut.as_mut().unwrap().poll_unpin(cx) {
Poll::Ready(()) => {
try_send!(msg);
self.fut = None
}
Poll::Pending => {
self.msg = Some(msg);
return Poll::Pending;
}
}
}
}
fn poll_unbounded_send(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), SendError<M>>> {
if let Some(fut) = &mut self.fut {
match fut.poll_unpin(cx) {
Poll::Ready(()) => self.poll_push_unbounded(),
Poll::Pending => Poll::Pending,
}
} else {
self.poll_push_unbounded()
}
}
fn poll_push_unbounded(&mut self) -> Poll<Result<(), SendError<M>>> {
let msg = self.msg.take().unwrap();
match self.channel.push_msg(msg) {
Ok(()) => Poll::Ready(Ok(())),
Err(PushError::Closed(msg)) => Poll::Ready(Err(SendError(msg))),
Err(PushError::Full(_msg)) => unreachable!(),
}
}
}
impl<'a, M> Unpin for Snd<'a, M> {}
impl<'a, M> Future for Snd<'a, M> {
type Output = Result<(), SendError<M>>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.channel.capacity() {
Capacity::Bounded(_) => self.poll_bounded_send(cx),
Capacity::Unbounded(_) => self.poll_unbounded_send(cx),
}
}
}
#[cfg(test)]
mod test {
use std::{sync::Arc, time::Duration};
use tokio::time::Instant;
use crate::*;
#[test]
fn try_send_with_space() {
let channel = Channel::<()>::new(1, 1, Capacity::Bounded(10));
channel.try_send(()).unwrap();
channel.send_now(()).unwrap();
assert_eq!(channel.msg_count(), 2);
let channel = Channel::<()>::new(1, 1, Capacity::Unbounded(BackPressure::disabled()));
channel.try_send(()).unwrap();
channel.send_now(()).unwrap();
assert_eq!(channel.msg_count(), 2);
}
#[test]
fn try_send_unbounded_full() {
let channel = Channel::<()>::new(
1,
1,
Capacity::Unbounded(BackPressure::linear(0, Duration::from_secs(1))),
);
assert_eq!(channel.try_send(()), Err(TrySendError::Full(())));
assert_eq!(channel.send_now(()), Ok(()));
assert_eq!(channel.msg_count(), 1);
}
#[test]
fn try_send_bounded_full() {
let channel = Channel::<()>::new(1, 1, Capacity::Bounded(1));
channel.try_send(()).unwrap();
assert_eq!(channel.try_send(()), Err(TrySendError::Full(())));
assert_eq!(channel.send_now(()), Err(TrySendError::Full(())));
assert_eq!(channel.msg_count(), 1);
}
#[tokio::test]
async fn send_with_space() {
let channel = Channel::<()>::new(1, 1, Capacity::Bounded(10));
channel.send(()).await.unwrap();
assert_eq!(channel.msg_count(), 1);
let channel = Channel::<()>::new(1, 1, Capacity::Unbounded(BackPressure::disabled()));
channel.send(()).await.unwrap();
assert_eq!(channel.msg_count(), 1);
}
#[tokio::test]
async fn send_unbounded_full() {
let channel = Channel::<()>::new(
1,
1,
Capacity::Unbounded(BackPressure::linear(0, Duration::from_millis(1))),
);
let time = Instant::now();
channel.send(()).await.unwrap();
channel.send(()).await.unwrap();
channel.send(()).await.unwrap();
assert!(time.elapsed().as_millis() > 6);
assert_eq!(channel.msg_count(), 3);
}
#[tokio::test]
async fn send_bounded_full() {
let channel = Arc::new(Channel::<()>::new(1, 1, Capacity::Bounded(1)));
let channel_clone = channel.clone();
tokio::task::spawn(async move {
let time = Instant::now();
channel_clone.send(()).await.unwrap();
channel_clone.send(()).await.unwrap();
channel_clone.send(()).await.unwrap();
assert!(time.elapsed().as_millis() > 2);
});
channel.recv(&mut false, &mut None).await.unwrap();
tokio::time::sleep(Duration::from_millis(1)).await;
channel.recv(&mut false, &mut None).await.unwrap();
tokio::time::sleep(Duration::from_millis(1)).await;
channel.recv(&mut false, &mut None).await.unwrap();
}
}