Skip to main content

labstream_net/
queue.rs

1//! A bounded sample queue that drops the oldest sample. SPEC.md 8.7.
2//!
3//! liblsl holds one of these per consumer on the outlet side
4//! (`src/consumer_queue.h`), and one on the inlet side for samples that the
5//! application has not pulled yet (`src/data_receiver.h:35`). Both drop the
6//! oldest sample when they fill.
7//!
8//! The recorded behavior that this matches is in
9//! `artifacts/behavior-liblsl.json`. A ring of 100 samples, fed 600 samples
10//! faster than the reader consumed them, delivered sample 0 and then samples
11//! 500 to 599. The writer never waited.
12
13use 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/// A queue that never blocks its writer.
20#[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    /// Build a queue that holds `capacity` samples.
31    ///
32    /// A capacity of zero would drop every sample, so the value floors at 1.
33    /// liblsl floors the same way (`src/stream_info_impl.cpp:268`).
34    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    /// How many samples the queue holds when full.
46    pub fn capacity(&self) -> usize {
47        self.capacity
48    }
49
50    /// How many samples the queue has dropped.
51    ///
52    /// Nothing on the wire carries this number. SPEC.md 8.7 records that a
53    /// reader cannot see a loss, so this exists for a local report only.
54    pub fn dropped(&self) -> u64 {
55        self.dropped.load(Ordering::SeqCst)
56    }
57
58    /// How many samples are waiting.
59    pub fn len(&self) -> usize {
60        self.inner.lock().unwrap().len()
61    }
62
63    /// True when no sample is waiting.
64    pub fn is_empty(&self) -> bool {
65        self.len() == 0
66    }
67
68    /// Add one sample. This never waits.
69    ///
70    /// A full queue loses its oldest sample. The writer carries on, so a slow
71    /// reader never holds back the source. SPEC.md 8.7.
72    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    /// Add several samples with one lock. This never waits.
84    ///
85    /// The result is the same as one [`SampleQueue::push`] for each sample, in
86    /// order. A full queue loses its oldest samples, and the count of dropped
87    /// samples grows by the number that the queue lost. The recorded behavior in
88    /// `artifacts/behavior-liblsl.json` therefore still holds.
89    ///
90    /// One lock for a block is the difference between a stream that a program
91    /// can read at 1000 Hz and one that it cannot.
92    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        // A block can satisfy more than one reader, so every reader wakes.
110        self.room.notify_all();
111    }
112
113    /// Take the oldest sample, waiting up to `timeout`.
114    ///
115    /// Returns `None` when the timeout passes with nothing waiting, or when the
116    /// queue is closed and empty.
117    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    /// Take every sample that waits, up to `max`, with one lock.
143    ///
144    /// The samples go to the end of `out`. The call gives how many it added.
145    ///
146    /// The timeout applies to the first sample only. When one sample waits, the
147    /// call takes what is there and returns. It never waits for `max` samples,
148    /// because a program that shows live signals must show what arrived.
149    ///
150    /// A closed and empty queue gives zero.
151    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    /// Wake every reader and stop the queue.
184    pub fn close(&self) {
185        *self.closed.lock().unwrap() = true;
186        self.room.notify_all();
187    }
188
189    /// True once [`SampleQueue::close`] has run.
190    pub fn is_closed(&self) -> bool {
191        *self.closed.lock().unwrap()
192    }
193}
194
195/// A set of consumers that all receive the same sample.
196///
197/// liblsl calls this the send buffer (`src/send_buffer.h`). Each consumer holds
198/// its own queue, so a slow consumer loses only its own samples. SPEC.md 8.8.
199#[derive(Debug, Default)]
200pub struct Fanout {
201    consumers: Mutex<Vec<Arc<SampleQueue>>>,
202}
203
204impl Fanout {
205    /// Build an empty set.
206    pub fn new() -> Self {
207        Fanout::default()
208    }
209
210    /// Add a consumer with its own queue.
211    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    /// Remove a consumer.
218    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    /// How many consumers are connected.
226    pub fn count(&self) -> usize {
227        self.consumers.lock().unwrap().len()
228    }
229
230    /// Give one sample to every consumer.
231    ///
232    /// A consumer that has gone away is dropped from the set. The call never
233    /// waits, whatever any consumer is doing.
234    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    /// Give several samples to every consumer, with one lock for the set.
243    ///
244    /// The result for each consumer is the same as one [`Fanout::push`] for each
245    /// sample, in order.
246    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    /// Close every consumer queue.
258    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        // The recorded shape from `artifacts/behavior-liblsl.json`, in small.
287        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        // The batch call is an optimization. It must lose the same samples, keep
307        // the same samples, and count the same drops.
308        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        // A reader that waited for `max` samples would hold a viewer back by the
355        // time that the rest of the block needs.
356        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        // A queue of one, written a million times, must finish at once. A
389        // design that waited for a reader would never return.
390        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        // SPEC.md 8.8. The fast queue is large and the slow queue is small.
450        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}