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
use crate::message_queues::{PerKeyQueue, QueueStyle};
use anyhow::{ensure, Result};
use diem_infallible::{Mutex, NonZeroUsize};
use diem_metrics::IntCounterVec;
use futures::{
channel::oneshot,
stream::{FusedStream, Stream},
};
use std::{
fmt::{Debug, Formatter},
hash::Hash,
pin::Pin,
sync::Arc,
task::{Context, Poll, Waker},
};
#[derive(Debug)]
struct SharedState<K: Eq + Hash + Clone, M> {
internal_queue: PerKeyQueue<K, (M, Option<oneshot::Sender<ElementStatus<M>>>)>,
waker: Option<Waker>,
num_senders: usize,
receiver_dropped: bool,
stream_terminated: bool,
}
#[derive(Debug)]
pub struct Sender<K: Eq + Hash + Clone, M> {
shared_state: Arc<Mutex<SharedState<K, M>>>,
}
pub enum ElementStatus<M> {
Dequeued,
Dropped(M),
}
impl<M: PartialEq> PartialEq for ElementStatus<M> {
fn eq(&self, other: &ElementStatus<M>) -> bool {
match (self, other) {
(ElementStatus::Dequeued, ElementStatus::Dequeued) => true,
(ElementStatus::Dropped(a), ElementStatus::Dropped(b)) => a.eq(b),
_ => false,
}
}
}
impl<M: Debug> Debug for ElementStatus<M> {
fn fmt(&self, f: &mut Formatter) -> std::result::Result<(), std::fmt::Error> {
match self {
ElementStatus::Dequeued => write!(f, "Dequeued"),
ElementStatus::Dropped(v) => write!(f, "Dropped({:?})", v),
}
}
}
impl<K: Eq + Hash + Clone, M> Sender<K, M> {
pub fn push(&mut self, key: K, message: M) -> Result<()> {
self.push_with_feedback(key, message, None)
}
pub fn push_with_feedback(
&mut self,
key: K,
message: M,
status_ch: Option<oneshot::Sender<ElementStatus<M>>>,
) -> Result<()> {
let mut shared_state = self.shared_state.lock();
ensure!(!shared_state.receiver_dropped, "Channel is closed");
debug_assert!(shared_state.num_senders > 0);
let dropped = shared_state.internal_queue.push(key, (message, status_ch));
if let Some((dropped_val, Some(dropped_status_ch))) = dropped {
let _err = dropped_status_ch.send(ElementStatus::Dropped(dropped_val));
}
if let Some(w) = shared_state.waker.take() {
w.wake();
}
Ok(())
}
}
impl<K: Eq + Hash + Clone, M> Clone for Sender<K, M> {
fn clone(&self) -> Self {
let shared_state = self.shared_state.clone();
{
let mut shared_state_lock = shared_state.lock();
debug_assert!(shared_state_lock.num_senders > 0);
shared_state_lock.num_senders += 1;
}
Sender { shared_state }
}
}
impl<K: Eq + Hash + Clone, M> Drop for Sender<K, M> {
fn drop(&mut self) {
let mut shared_state = self.shared_state.lock();
debug_assert!(shared_state.num_senders > 0);
shared_state.num_senders -= 1;
if shared_state.num_senders == 0 {
if let Some(waker) = shared_state.waker.take() {
waker.wake();
}
}
}
}
pub struct Receiver<K: Eq + Hash + Clone, M> {
shared_state: Arc<Mutex<SharedState<K, M>>>,
}
impl<K: Eq + Hash + Clone, M> Receiver<K, M> {
pub fn clear(&mut self) {
let mut shared_state = self.shared_state.lock();
shared_state.internal_queue.clear();
}
}
impl<K: Eq + Hash + Clone, M> Drop for Receiver<K, M> {
fn drop(&mut self) {
let mut shared_state = self.shared_state.lock();
debug_assert!(!shared_state.receiver_dropped);
shared_state.receiver_dropped = true;
}
}
impl<K: Eq + Hash + Clone, M> Stream for Receiver<K, M> {
type Item = M;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut shared_state = self.shared_state.lock();
if let Some((val, status_ch)) = shared_state.internal_queue.pop() {
if let Some(status_ch) = status_ch {
let _err = status_ch.send(ElementStatus::Dequeued);
}
Poll::Ready(Some(val))
} else if shared_state.num_senders == 0 {
shared_state.stream_terminated = true;
Poll::Ready(None)
} else {
shared_state.waker = Some(cx.waker().clone());
Poll::Pending
}
}
}
impl<K: Eq + Hash + Clone, M> FusedStream for Receiver<K, M> {
fn is_terminated(&self) -> bool {
self.shared_state.lock().stream_terminated
}
}
pub fn new<K: Eq + Hash + Clone, M>(
queue_style: QueueStyle,
max_queue_size_per_key: usize,
counters: Option<&'static IntCounterVec>,
) -> (Sender<K, M>, Receiver<K, M>) {
let max_queue_size_per_key =
NonZeroUsize!(max_queue_size_per_key, "diem_channel cannot be of size 0");
let shared_state = Arc::new(Mutex::new(SharedState {
internal_queue: PerKeyQueue::new(queue_style, max_queue_size_per_key, counters),
waker: None,
num_senders: 1,
receiver_dropped: false,
stream_terminated: false,
}));
let shared_state_clone = Arc::clone(&shared_state);
(
Sender { shared_state },
Receiver {
shared_state: shared_state_clone,
},
)
}