1use labstream_wire::Sample;
14use std::collections::VecDeque;
15use std::sync::atomic::{AtomicU64, Ordering};
16use std::sync::{Arc, Condvar, Mutex};
17use std::time::{Duration, Instant};
18
19#[derive(Debug)]
21pub struct SampleQueue {
22 inner: Mutex<VecDeque<Sample>>,
23 room: Condvar,
24 capacity: usize,
25 dropped: AtomicU64,
26 closed: Mutex<bool>,
27}
28
29impl SampleQueue {
30 pub fn new(capacity: usize) -> Self {
35 let capacity = capacity.max(1);
36 SampleQueue {
37 inner: Mutex::new(VecDeque::with_capacity(capacity.min(4096))),
38 room: Condvar::new(),
39 capacity,
40 dropped: AtomicU64::new(0),
41 closed: Mutex::new(false),
42 }
43 }
44
45 pub fn capacity(&self) -> usize {
47 self.capacity
48 }
49
50 pub fn dropped(&self) -> u64 {
55 self.dropped.load(Ordering::SeqCst)
56 }
57
58 pub fn len(&self) -> usize {
60 self.inner.lock().unwrap().len()
61 }
62
63 pub fn is_empty(&self) -> bool {
65 self.len() == 0
66 }
67
68 pub fn push(&self, s: Sample) {
73 let mut q = self.inner.lock().unwrap();
74 if q.len() >= self.capacity {
75 q.pop_front();
76 self.dropped.fetch_add(1, Ordering::SeqCst);
77 }
78 q.push_back(s);
79 drop(q);
80 self.room.notify_one();
81 }
82
83 pub fn push_many(&self, samples: &[Sample]) {
93 if samples.is_empty() {
94 return;
95 }
96 let mut q = self.inner.lock().unwrap();
97 let mut lost = 0u64;
98 for s in samples {
99 if q.len() >= self.capacity {
100 q.pop_front();
101 lost += 1;
102 }
103 q.push_back(s.clone());
104 }
105 drop(q);
106 if lost > 0 {
107 self.dropped.fetch_add(lost, Ordering::SeqCst);
108 }
109 self.room.notify_all();
111 }
112
113 pub fn pop(&self, timeout: Duration) -> Option<Sample> {
118 let end = Instant::now() + timeout;
119 let mut q = self.inner.lock().unwrap();
120 loop {
121 if let Some(s) = q.pop_front() {
122 return Some(s);
123 }
124 if *self.closed.lock().unwrap() {
125 return None;
126 }
127 let left = end.saturating_duration_since(Instant::now());
128 if left.is_zero() {
129 return None;
130 }
131 let (guard, result) = self
132 .room
133 .wait_timeout(q, left.min(Duration::from_millis(100)))
134 .unwrap();
135 q = guard;
136 if result.timed_out() && Instant::now() >= end {
137 return q.pop_front();
138 }
139 }
140 }
141
142 pub fn pop_many(&self, out: &mut Vec<Sample>, max: usize, timeout: Duration) -> usize {
152 if max == 0 {
153 return 0;
154 }
155 let end = Instant::now() + timeout;
156 let mut q = self.inner.lock().unwrap();
157 loop {
158 if !q.is_empty() {
159 let take = q.len().min(max);
160 out.extend(q.drain(..take));
161 return take;
162 }
163 if *self.closed.lock().unwrap() {
164 return 0;
165 }
166 let left = end.saturating_duration_since(Instant::now());
167 if left.is_zero() {
168 return 0;
169 }
170 let (guard, result) = self
171 .room
172 .wait_timeout(q, left.min(Duration::from_millis(100)))
173 .unwrap();
174 q = guard;
175 if result.timed_out() && Instant::now() >= end {
176 let take = q.len().min(max);
177 out.extend(q.drain(..take));
178 return take;
179 }
180 }
181 }
182
183 pub fn close(&self) {
185 *self.closed.lock().unwrap() = true;
186 self.room.notify_all();
187 }
188
189 pub fn is_closed(&self) -> bool {
191 *self.closed.lock().unwrap()
192 }
193}
194
195#[derive(Debug, Default)]
200pub struct Fanout {
201 consumers: Mutex<Vec<Arc<SampleQueue>>>,
202}
203
204impl Fanout {
205 pub fn new() -> Self {
207 Fanout::default()
208 }
209
210 pub fn add(&self, capacity: usize) -> Arc<SampleQueue> {
212 let q = Arc::new(SampleQueue::new(capacity));
213 self.consumers.lock().unwrap().push(Arc::clone(&q));
214 q
215 }
216
217 pub fn remove(&self, q: &Arc<SampleQueue>) {
219 self.consumers
220 .lock()
221 .unwrap()
222 .retain(|c| !Arc::ptr_eq(c, q));
223 }
224
225 pub fn count(&self) -> usize {
227 self.consumers.lock().unwrap().len()
228 }
229
230 pub fn push(&self, s: &Sample) {
235 let mut set = self.consumers.lock().unwrap();
236 set.retain(|q| !q.is_closed());
237 for q in set.iter() {
238 q.push(s.clone());
239 }
240 }
241
242 pub fn push_many(&self, samples: &[Sample]) {
247 if samples.is_empty() {
248 return;
249 }
250 let mut set = self.consumers.lock().unwrap();
251 set.retain(|q| !q.is_closed());
252 for q in set.iter() {
253 q.push_many(samples);
254 }
255 }
256
257 pub fn close(&self) {
259 for q in self.consumers.lock().unwrap().iter() {
260 q.close();
261 }
262 }
263}
264
265#[cfg(test)]
266mod tests {
267 use super::*;
268 use labstream_wire::Value;
269
270 fn sample(i: i32) -> Sample {
271 Sample {
272 timestamp: i as f64,
273 values: vec![Value::I32(i)],
274 }
275 }
276
277 fn index(s: &Sample) -> i32 {
278 match s.values[0] {
279 Value::I32(v) => v,
280 _ => panic!("wrong format"),
281 }
282 }
283
284 #[test]
285 fn a_full_queue_keeps_the_newest() {
286 let q = SampleQueue::new(100);
288 for i in 0..600 {
289 q.push(sample(i));
290 }
291 assert_eq!(q.len(), 100);
292 assert_eq!(q.dropped(), 500);
293
294 let first = q.pop(Duration::from_millis(10)).expect("a sample");
295 assert_eq!(index(&first), 500, "the oldest surviving sample");
296
297 let mut last = first;
298 while let Some(s) = q.pop(Duration::from_millis(10)) {
299 last = s;
300 }
301 assert_eq!(index(&last), 599, "the newest sample");
302 }
303
304 #[test]
305 fn a_block_write_gives_what_single_writes_give() {
306 let one = SampleQueue::new(100);
309 let many = SampleQueue::new(100);
310 let block: Vec<Sample> = (0..600).map(sample).collect();
311 for s in &block {
312 one.push(s.clone());
313 }
314 many.push_many(&block);
315
316 assert_eq!(one.len(), many.len());
317 assert_eq!(one.dropped(), many.dropped());
318 while let Some(a) = one.pop(Duration::from_millis(10)) {
319 let b = many.pop(Duration::from_millis(10)).expect("the same count");
320 assert_eq!(index(&a), index(&b));
321 }
322 assert!(many.pop(Duration::from_millis(10)).is_none());
323 }
324
325 #[test]
326 fn a_block_read_takes_what_waits_in_order() {
327 let q = SampleQueue::new(100);
328 q.push_many(&(0..10).map(sample).collect::<Vec<_>>());
329
330 let mut out = Vec::new();
331 let got = q.pop_many(&mut out, 4, Duration::from_millis(10));
332 assert_eq!(got, 4, "the call stops at max");
333 assert_eq!(out.iter().map(index).collect::<Vec<_>>(), [0, 1, 2, 3]);
334
335 let got = q.pop_many(&mut out, 100, Duration::from_millis(10));
336 assert_eq!(got, 6, "the call takes what waits, and not more");
337 assert_eq!(out.len(), 10, "the samples go to the end of the buffer");
338 assert_eq!(index(&out[9]), 9);
339 }
340
341 #[test]
342 fn a_block_read_of_an_empty_queue_gives_nothing() {
343 let q = SampleQueue::new(10);
344 let mut out = Vec::new();
345 assert_eq!(q.pop_many(&mut out, 8, Duration::from_millis(5)), 0);
346 assert!(out.is_empty());
347
348 q.close();
349 assert_eq!(q.pop_many(&mut out, 8, Duration::from_millis(50)), 0);
350 }
351
352 #[test]
353 fn a_block_read_waits_for_the_first_sample_only() {
354 let q = Arc::new(SampleQueue::new(10));
357 let writer = Arc::clone(&q);
358 std::thread::spawn(move || {
359 std::thread::sleep(Duration::from_millis(20));
360 writer.push_many(&[sample(1), sample(2)]);
361 });
362 let mut out = Vec::new();
363 let start = Instant::now();
364 let got = q.pop_many(&mut out, 1000, Duration::from_secs(5));
365 assert_eq!(got, 2, "the call takes the block that arrived");
366 assert!(
367 start.elapsed() < Duration::from_secs(1),
368 "the call returned"
369 );
370 }
371
372 #[test]
373 fn a_block_reaches_every_consumer() {
374 let fan = Fanout::new();
375 let a = fan.add(10);
376 let b = fan.add(10);
377 fan.push_many(&[sample(7), sample(8)]);
378
379 for q in [&a, &b] {
380 let mut out = Vec::new();
381 assert_eq!(q.pop_many(&mut out, 10, Duration::from_millis(10)), 2);
382 assert_eq!(out.iter().map(index).collect::<Vec<_>>(), [7, 8]);
383 }
384 }
385
386 #[test]
387 fn the_writer_never_waits() {
388 let q = SampleQueue::new(1);
391 let start = Instant::now();
392 for i in 0..1_000_000 {
393 q.push(sample(i));
394 }
395 assert!(
396 start.elapsed() < Duration::from_secs(10),
397 "the writer waited"
398 );
399 assert_eq!(q.len(), 1);
400 assert_eq!(index(&q.pop(Duration::from_millis(10)).unwrap()), 999_999);
401 }
402
403 #[test]
404 fn a_capacity_of_zero_floors_at_one() {
405 let q = SampleQueue::new(0);
406 assert_eq!(q.capacity(), 1);
407 q.push(sample(7));
408 assert_eq!(index(&q.pop(Duration::from_millis(10)).unwrap()), 7);
409 }
410
411 #[test]
412 fn an_empty_queue_reports_nothing_after_the_timeout() {
413 let q = SampleQueue::new(4);
414 let start = Instant::now();
415 assert!(q.pop(Duration::from_millis(120)).is_none());
416 assert!(start.elapsed() >= Duration::from_millis(100));
417 }
418
419 #[test]
420 fn a_closed_queue_stops_a_reader_at_once() {
421 let q = Arc::new(SampleQueue::new(4));
422 let c = Arc::clone(&q);
423 std::thread::spawn(move || {
424 std::thread::sleep(Duration::from_millis(30));
425 c.close();
426 });
427 let start = Instant::now();
428 assert!(q.pop(Duration::from_secs(10)).is_none());
429 assert!(
430 start.elapsed() < Duration::from_secs(2),
431 "the reader waited out the timeout"
432 );
433 }
434
435 #[test]
436 fn a_reader_wakes_when_a_sample_arrives() {
437 let q = Arc::new(SampleQueue::new(4));
438 let c = Arc::clone(&q);
439 std::thread::spawn(move || {
440 std::thread::sleep(Duration::from_millis(30));
441 c.push(sample(42));
442 });
443 let got = q.pop(Duration::from_secs(2)).expect("a sample");
444 assert_eq!(index(&got), 42);
445 }
446
447 #[test]
448 fn a_slow_consumer_never_holds_back_a_fast_one() {
449 let f = Fanout::new();
451 let fast = f.add(1000);
452 let slow = f.add(10);
453 for i in 0..500 {
454 f.push(&sample(i));
455 }
456 assert_eq!(fast.len(), 500, "the fast consumer lost samples");
457 assert_eq!(fast.dropped(), 0);
458 assert_eq!(slow.len(), 10);
459 assert_eq!(slow.dropped(), 490);
460 }
461
462 #[test]
463 fn a_closed_consumer_leaves_the_set() {
464 let f = Fanout::new();
465 let a = f.add(10);
466 let b = f.add(10);
467 assert_eq!(f.count(), 2);
468 b.close();
469 f.push(&sample(1));
470 assert_eq!(f.count(), 1, "a closed consumer must be removed");
471 assert_eq!(a.len(), 1);
472 }
473
474 #[test]
475 fn removing_a_consumer_stops_its_samples() {
476 let f = Fanout::new();
477 let a = f.add(10);
478 f.push(&sample(1));
479 f.remove(&a);
480 f.push(&sample(2));
481 assert_eq!(a.len(), 1, "a removed consumer must receive nothing more");
482 }
483}