-
Notifications
You must be signed in to change notification settings - Fork 0
/
sequencer.rs
232 lines (190 loc) · 7.29 KB
/
sequencer.rs
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
use color_eyre::{eyre::eyre, Result};
use std::{collections::BTreeSet, fmt::Debug, sync::Arc};
use tokio::sync::{broadcast, mpsc, Mutex};
///
/// Receive values from multiple providers and order / deduplicate them.
///
pub struct Sequencer<T> {
pub inbound: mpsc::UnboundedReceiver<T>,
pub outbound: mpsc::UnboundedSender<T>,
pub shutdown: broadcast::Receiver<()>,
pub queue: Arc<Mutex<BTreeSet<T>>>,
pub cache: Arc<Mutex<BTreeSet<T>>>,
pub cache_size_max: usize,
}
impl<T> Sequencer<T>
where
T: Clone + Debug + Ord + PartialOrd + Send + Sync + 'static,
{
pub fn new(
inbound: mpsc::UnboundedReceiver<T>,
outbound: mpsc::UnboundedSender<T>,
shutdown: broadcast::Receiver<()>,
cache_size_max: usize,
) -> Result<Self> {
if cache_size_max == 0 {
return Err(eyre!("Cache size must be greater than 0"));
}
Ok(Self {
inbound,
outbound,
shutdown,
queue: Arc::new(Mutex::new(BTreeSet::new())),
cache: Arc::new(Mutex::new(BTreeSet::new())),
cache_size_max,
})
}
pub async fn consume(mut self) -> Result<()> {
let handle = tokio::spawn(async move {
let mut last_seen = None;
while let Some(item) = self.inbound.recv().await {
let mut queue = self.queue.lock().await;
let mut cache = self.cache.lock().await;
// Ignore if in cache
if cache.contains(&item) {
continue;
}
// If we've seen other values, ignore if below the last seen value
if let Some(last_seen) = last_seen.clone() {
if item < last_seen {
continue;
}
}
// Insert into queue
queue.insert(item);
// Get the last value from the set
let last_value = queue.iter().next().unwrap().clone();
// Send it out
self.outbound
.send(last_value.clone())
.map_err(|err| eyre!("Failed to send item: {}", err))?;
// Remove it from the set
queue.remove(&last_value);
// If the cache is full, remove the oldest item
if cache.len() >= self.cache_size_max {
let x = cache.iter().next().unwrap().clone();
cache.remove(&x);
}
// Update the cache
cache.insert(last_value.clone());
// Update the last seen value
last_seen = Some(last_value);
}
Ok(())
});
tokio::select! {
_ = self.shutdown.recv() => Ok(()),
result = handle => {
result?
}
}
}
}
#[cfg(test)]
mod tests {
use tokio::try_join;
use crate::util::{is_sorted, no_sequential_duplicates};
use super::*;
#[test]
fn bad_sequencer_cache_size() {
let (_inbound_tx, inbound_rx) = mpsc::unbounded_channel::<()>();
let (outbound_tx, _outbound_rx) = mpsc::unbounded_channel();
let (_shutdown_tx, shutdown_rx) = broadcast::channel(1);
let result = Sequencer::new(inbound_rx, outbound_tx, shutdown_rx, 0);
assert!(result.is_err());
}
#[tokio::test]
async fn sequencer_consume() {
// Create channels for inbound and outbound
let (inbound_tx, inbound_rx) = mpsc::unbounded_channel();
let (outbound_tx, mut outbound_rx) = mpsc::unbounded_channel();
let (shutdown_tx, shutdown_rx) = broadcast::channel(1);
// Create a sequencer
let sequencer = Sequencer::new(inbound_rx, outbound_tx.clone(), shutdown_rx, 10).unwrap();
// Spawn a task to consume
let sequencer_handle = tokio::spawn(async move {
sequencer.consume().await.unwrap();
});
// Spawn 16 tasks to produce values
let mut producers = vec![];
for i in 0..16 {
let inbound_tx = inbound_tx.clone();
let producer = tokio::spawn(async move {
let start = i * 2;
for j in start..(start + 16) {
inbound_tx
.send(j)
.map_err(|err| eyre!("Failed to send item: {}", err))
.unwrap();
}
});
producers.push(producer);
}
// Wait for the producers to finish
for producer in producers {
producer.await.unwrap();
}
// Shutdown the system
shutdown_tx.send(()).unwrap();
// Wait for the sequencer to finish
let _ = try_join!(sequencer_handle).unwrap();
drop(inbound_tx);
drop(outbound_tx);
// Consume the outbound stream
let mut expected = vec![];
while let Ok(item) = outbound_rx.try_recv() {
expected.push(item);
}
// Verify the outbound stream is sorted (aka sequential) and has no sequential duplicates
is_sorted(&expected);
no_sequential_duplicates(&expected);
}
#[tokio::test]
async fn cache_eviction() {
// Create channels for inbound and outbound
let (inbound_tx, inbound_rx) = mpsc::unbounded_channel();
let (outbound_tx, mut outbound_rx) = mpsc::unbounded_channel();
let (shutdown_tx, shutdown_rx) = broadcast::channel(1);
// Create a sequencer
let sequencer = Sequencer::new(inbound_rx, outbound_tx.clone(), shutdown_rx, 10).unwrap();
// Spawn a task to consume
let sequencer_handle = tokio::spawn(async move {
sequencer.consume().await.unwrap();
});
// Send the same value twice
inbound_tx.send(1).unwrap();
inbound_tx.send(1).unwrap();
// Shutdown the system
shutdown_tx.send(()).unwrap();
// Wait for the sequencer to finish
let _ = try_join!(sequencer_handle).unwrap();
// Assert we only get one value
assert_eq!(outbound_rx.try_recv().unwrap(), 1);
assert!(outbound_rx.try_recv().is_err());
}
#[tokio::test]
async fn ignore_previously_seen_sequential_value() {
// Create channels for inbound and outbound
let (inbound_tx, inbound_rx) = mpsc::unbounded_channel();
let (outbound_tx, mut outbound_rx) = mpsc::unbounded_channel();
let (shutdown_tx, shutdown_rx) = broadcast::channel(1);
// Create a sequencer
let sequencer = Sequencer::new(inbound_rx, outbound_tx.clone(), shutdown_rx, 10).unwrap();
// Spawn a task to consume
let sequencer_handle = tokio::spawn(async move {
sequencer.consume().await.unwrap();
});
// Send the same value twice
inbound_tx.send(1).unwrap();
inbound_tx.send(2).unwrap();
inbound_tx.send(1).unwrap();
// Shutdown the system
shutdown_tx.send(()).unwrap();
// Wait for the sequencer to finish
let _ = try_join!(sequencer_handle).unwrap();
// Assert we only get one value
assert_eq!(outbound_rx.try_recv().unwrap(), 1);
assert_eq!(outbound_rx.try_recv().unwrap(), 2);
assert!(outbound_rx.try_recv().is_err());
}
}