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 crate::health::{ConsumerHealth, Gap, GapKind, OutletHealth, MAX_GAPS};
14use crate::history::{History, HistoryLimits, HistoryRead};
15use labstream_proto::meta::MetadataUpdate;
16use labstream_wire::{PackedSample, Sample, TimestampDeducer, IRREGULAR_RATE};
17use std::collections::{BTreeMap, VecDeque};
18use std::sync::atomic::{AtomicU64, Ordering};
19use std::sync::{Arc, Condvar, Mutex};
20use std::time::{Duration, Instant};
21
22/// Maximum number of live metadata updates retained in the outlet log.
23const MAX_META_LOG: usize = 4096;
24
25/// The samples of a queue, and the number after the last one.
26///
27/// Each push adds one to `back`, also for a sample that the queue drops at
28/// once. A removal does not change it. The samples in the queue thus always
29/// have the numbers `back - len .. back`, with no gap: the queue drops only
30/// from the front, and a push only adds at the back. `docs/extensions.md`.
31#[derive(Debug)]
32struct Ring {
33    q: VecDeque<PackedSample>,
34    back: u64,
35    /// The full timestamp of each sample that leaves the queue, in order.
36    /// Only a queue for a `resume` consumer has one. `docs/extensions.md`,
37    /// rule 5 of the resend timestamps.
38    deducer: Option<TimestampDeducer>,
39    /// Timestamp of the last sample taken by the reader, for drop-gap tracking.
40    last_popped_ts: Option<f64>,
41    /// Samples dropped since the last sample taken by the reader.
42    pending_drop_count: u64,
43    /// Start timestamp latched when `pending_drop_count` became non-zero.
44    pending_drop_start: Option<f64>,
45    /// Completed drop gaps, bounded to `MAX_GAPS`.
46    drop_gaps: VecDeque<Gap>,
47    /// Sparse `(ring_pos, skipped_count)` markers recording wire-lost or
48    /// queue-dropped samples immediately before `ring_pos`, for loss-aware
49    /// dejitter (`docs/roadmap.md`, step 2). Always empty on a clean stream.
50    skips: VecDeque<(u64, u64)>,
51}
52
53impl std::ops::Deref for Ring {
54    type Target = VecDeque<PackedSample>;
55    fn deref(&self) -> &VecDeque<PackedSample> {
56        &self.q
57    }
58}
59
60impl std::ops::DerefMut for Ring {
61    fn deref_mut(&mut self) -> &mut VecDeque<PackedSample> {
62        &mut self.q
63    }
64}
65
66impl Ring {
67    /// The number of the sample at the front.
68    fn front_number(&self) -> u64 {
69        self.back.wrapping_sub(self.q.len() as u64)
70    }
71
72    /// Record that `count` samples starting near `dropped_ts` were discarded.
73    fn note_drop(&mut self, dropped_ts: f64, count: u64) {
74        if count == 0 {
75            return;
76        }
77        if self.pending_drop_count == 0 {
78            self.pending_drop_start = self.last_popped_ts.or(Some(dropped_ts));
79        }
80        self.pending_drop_count = self.pending_drop_count.saturating_add(count);
81    }
82
83    /// Finalize any pending drop gap when the reader receives a sample at `end_ts`.
84    fn note_pop(&mut self, first_ts: f64, last_ts: f64) {
85        if self.pending_drop_count > 0 {
86            let count = self.pending_drop_count;
87            let start = self.pending_drop_start.unwrap_or(first_ts);
88            self.pending_drop_count = 0;
89            self.pending_drop_start = None;
90            if start.is_finite() && first_ts.is_finite() {
91                if self.drop_gaps.len() >= MAX_GAPS {
92                    self.drop_gaps.pop_front();
93                }
94                self.drop_gaps.push_back(Gap {
95                    start,
96                    end: first_ts,
97                    count,
98                    kind: GapKind::Dropped,
99                });
100            }
101        }
102        self.last_popped_ts = Some(last_ts);
103    }
104
105    /// Record that `count` samples were skipped immediately before `pos`,
106    /// keeping `self.skips` sorted by ascending position.
107    fn push_skip(&mut self, pos: u64, count: u64) {
108        if count == 0 {
109            return;
110        }
111        if let Some((last_pos, last_count)) = self.skips.back_mut() {
112            if *last_pos == pos {
113                *last_count = last_count.saturating_add(count);
114                return;
115            }
116            if *last_pos < pos {
117                self.skips.push_back((pos, count));
118                return;
119            }
120        } else {
121            self.skips.push_back((pos, count));
122            return;
123        }
124        // Front insertion (e.g. `drop_front` while a later wire skip exists).
125        if let Some((first_pos, first_count)) = self.skips.front_mut() {
126            if *first_pos == pos {
127                *first_count = first_count.saturating_add(count);
128                return;
129            }
130            if pos < *first_pos {
131                self.skips.push_front((pos, count));
132                return;
133            }
134        }
135        for i in 0..self.skips.len() {
136            let (p, c) = &mut self.skips[i];
137            if *p == pos {
138                *c = c.saturating_add(count);
139                return;
140            }
141            if pos < *p {
142                self.skips.insert(i, (pos, count));
143                return;
144            }
145        }
146        self.skips.push_back((pos, count));
147    }
148
149    /// Take all skipped-sample counts that precede `ring_pos`.
150    fn take_skips_at(&mut self, ring_pos: u64) -> u64 {
151        if self.skips.is_empty() {
152            return 0;
153        }
154        let mut total = 0u64;
155        while let Some(&(pos, count)) = self.skips.front() {
156            if pos <= ring_pos {
157                total = total.saturating_add(count);
158                self.skips.pop_front();
159            } else {
160                break;
161            }
162        }
163        total
164    }
165
166    /// Remove the oldest sample because the queue is full.
167    ///
168    /// The deducer sees the sample, so the full timestamp of the next sample
169    /// stays correct after the drop.
170    fn drop_front(&mut self) {
171        let front_pos = self.front_number();
172        if let Some(old) = self.q.pop_front() {
173            self.note_drop(old.timestamp, 1);
174            // The next surviving sample is at `front_pos + 1`; attach 1 skipped
175            // sample there so loss-aware dejitter accounts for inlet drops too.
176            self.push_skip(front_pos.wrapping_add(1), 1);
177            if let Some(d) = self.deducer.as_mut() {
178                d.apply(old.timestamp);
179            }
180        }
181    }
182}
183
184/// A queue that never blocks its writer.
185#[derive(Debug)]
186pub struct SampleQueue {
187    inner: Mutex<Ring>,
188    room: Condvar,
189    capacity: usize,
190    dropped: AtomicU64,
191    closed: Mutex<bool>,
192    /// Set by [`SampleQueue::wake`]. The next wait returns at once.
193    woken: std::sync::atomic::AtomicBool,
194}
195
196impl SampleQueue {
197    /// Build a queue that holds `capacity` samples.
198    ///
199    /// A capacity of zero would drop every sample, so the value floors at 1.
200    /// liblsl floors the same way (`src/stream_info_impl.cpp:268`).
201    pub fn new(capacity: usize) -> Self {
202        Self::with_first_number(capacity, 0)
203    }
204
205    /// Build a queue whose first pushed sample gets the number `first`.
206    ///
207    /// The `seq` feature numbers the samples of an outlet with one counter.
208    /// A consumer that connects later starts at the current count.
209    pub fn with_first_number(capacity: usize, first: u64) -> Self {
210        Self::build(capacity, first, None)
211    }
212
213    /// Build a queue that also gives the full timestamp of each sample.
214    ///
215    /// `deducer` must hold the state after the sample with the number
216    /// `first - 1`. [`SampleQueue::pop_many_full`] then gives the full
217    /// timestamps, also after a drop.
218    pub fn with_deducer(capacity: usize, first: u64, deducer: TimestampDeducer) -> Self {
219        Self::build(capacity, first, Some(deducer))
220    }
221
222    fn build(capacity: usize, first: u64, deducer: Option<TimestampDeducer>) -> Self {
223        let capacity = capacity.max(1);
224        SampleQueue {
225            inner: Mutex::new(Ring {
226                q: VecDeque::with_capacity(capacity.min(4096)),
227                back: first,
228                deducer,
229                last_popped_ts: None,
230                pending_drop_count: 0,
231                pending_drop_start: None,
232                drop_gaps: VecDeque::new(),
233                skips: VecDeque::new(),
234            }),
235            room: Condvar::new(),
236            capacity,
237            dropped: AtomicU64::new(0),
238            closed: Mutex::new(false),
239            woken: std::sync::atomic::AtomicBool::new(false),
240        }
241    }
242
243    /// How many samples the queue holds when full.
244    pub fn capacity(&self) -> usize {
245        self.capacity
246    }
247
248    /// How many samples the queue has dropped.
249    ///
250    /// Nothing on the wire carries this number. SPEC.md 8.7 records that a
251    /// reader cannot see a loss, so this exists for a local report only.
252    pub fn dropped(&self) -> u64 {
253        self.dropped.load(Ordering::SeqCst)
254    }
255
256    /// How many samples are waiting.
257    pub fn len(&self) -> usize {
258        self.inner.lock().unwrap().len()
259    }
260
261    /// True when no sample is waiting.
262    pub fn is_empty(&self) -> bool {
263        self.len() == 0
264    }
265
266    /// Add one sample. This never waits.
267    ///
268    /// A full queue loses its oldest sample. The writer carries on, so a slow
269    /// reader never holds back the source. SPEC.md 8.7.
270    pub fn push(&self, s: Sample) {
271        self.push_packed(PackedSample::from(s));
272    }
273
274    /// Add one [`PackedSample`]. This never waits.
275    pub fn push_packed(&self, s: PackedSample) {
276        let mut q = self.inner.lock().unwrap();
277        if q.len() >= self.capacity {
278            q.drop_front();
279            self.dropped.fetch_add(1, Ordering::SeqCst);
280        }
281        q.push_back(s);
282        q.back = q.back.wrapping_add(1);
283        drop(q);
284        self.room.notify_one();
285    }
286
287    /// Add several samples with one lock. This never waits.
288    ///
289    /// The result is the same as one [`SampleQueue::push`] for each sample, in
290    /// order. A full queue loses its oldest samples, and the count of dropped
291    /// samples grows by the number that the queue lost. The recorded behavior in
292    /// `artifacts/behavior-liblsl.json` therefore still holds.
293    ///
294    /// One lock for a block is the difference between a stream that a program
295    /// can read at 1000 Hz and one that it cannot.
296    pub fn push_many(&self, samples: &[Sample]) {
297        if samples.is_empty() {
298            return;
299        }
300        let packed: Vec<PackedSample> = samples.iter().map(PackedSample::from_sample).collect();
301        self.push_many_packed(&packed);
302    }
303
304    /// Add several [`PackedSample`]s with one lock, cloning only `Arc` handles.
305    pub fn push_many_packed(&self, samples: &[PackedSample]) {
306        if samples.is_empty() {
307            return;
308        }
309        let mut q = self.inner.lock().unwrap();
310        let mut lost = 0u64;
311        for s in samples {
312            if q.len() >= self.capacity {
313                q.drop_front();
314                lost += 1;
315            }
316            q.push_back(s.clone());
317        }
318        q.back = q.back.wrapping_add(samples.len() as u64);
319        drop(q);
320        if lost > 0 {
321            self.dropped.fetch_add(lost, Ordering::SeqCst);
322        }
323        if samples.len() == 1 {
324            self.room.notify_one();
325        } else {
326            self.room.notify_all();
327        }
328    }
329
330    /// Move every sample out of `samples` into the queue, with one lock.
331    ///
332    /// The result is the same as [`SampleQueue::push_many`], but no sample is
333    /// copied. `samples` is empty after the call and keeps its capacity, so
334    /// the caller can fill it again with no new allocation.
335    ///
336    /// A queue with a deducer must not use this call, because the samples
337    /// that the queue drops at once never pass the deducer.
338    pub fn push_owned(&self, samples: &mut Vec<Sample>) {
339        self.push_owned_with_skips(samples, &[]);
340    }
341
342    /// Move every [`PackedSample`] out of `samples` into the queue, with one lock.
343    pub fn push_owned_packed(&self, samples: &mut Vec<PackedSample>) {
344        self.push_owned_packed_with_skips(samples, &[]);
345    }
346
347    /// Like [`SampleQueue::push_owned`], and attach sparse `(batch_index, count)`
348    /// skipped-sample counts for loss-aware dejitter (`docs/roadmap.md`, step 2).
349    pub(crate) fn push_owned_with_skips(&self, samples: &mut Vec<Sample>, skips: &[(usize, u64)]) {
350        let mut packed: Vec<PackedSample> = samples.drain(..).map(PackedSample::from).collect();
351        self.push_owned_packed_with_skips(&mut packed, skips);
352    }
353
354    /// Like [`SampleQueue::push_owned_packed`], and attach sparse
355    /// `(batch_index, count)` skipped-sample counts for loss-aware dejitter.
356    pub(crate) fn push_owned_packed_with_skips(
357        &self,
358        samples: &mut Vec<PackedSample>,
359        skips: &[(usize, u64)],
360    ) {
361        if samples.is_empty() {
362            if !skips.is_empty() {
363                let mut q = self.inner.lock().unwrap();
364                let pos = q.back;
365                for &(_, count) in skips {
366                    q.push_skip(pos, count);
367                }
368            }
369            return;
370        }
371        let batch_len = samples.len();
372        let mut q = self.inner.lock().unwrap();
373        debug_assert!(q.deducer.is_none());
374        let base_pos = q.back;
375        for &(offset, count) in skips {
376            q.push_skip(base_pos.wrapping_add(offset as u64), count);
377        }
378        let mut lost = 0u64;
379        // Samples that the queue drops at once are never moved in.
380        let skip = batch_len.saturating_sub(self.capacity);
381        // Each sample takes a number, also the ones that are never moved in.
382        q.back = q.back.wrapping_add(batch_len as u64);
383        if skip > 0 {
384            let old_len = q.len() as u64;
385            if let Some(old) = q.q.front() {
386                let ts = old.timestamp;
387                q.note_drop(ts, old_len);
388                lost += old_len;
389                q.q.clear();
390            }
391            let skipped_ts = samples[0].timestamp;
392            q.note_drop(skipped_ts, skip as u64);
393            lost += skip as u64;
394            let first_kept_pos = base_pos.wrapping_add(skip as u64);
395            q.push_skip(first_kept_pos, lost);
396            for s in samples.drain(..).skip(skip) {
397                q.push_back(s);
398            }
399        } else {
400            for s in samples.drain(..) {
401                if q.len() >= self.capacity {
402                    q.drop_front();
403                    lost += 1;
404                }
405                q.push_back(s);
406            }
407        }
408        drop(q);
409        if lost > 0 {
410            self.dropped.fetch_add(lost, Ordering::SeqCst);
411        }
412        if batch_len == 1 {
413            self.room.notify_one();
414        } else {
415            self.room.notify_all();
416        }
417    }
418
419    /// Record `count` skipped samples before the next sample that enters this queue.
420    pub(crate) fn record_skipped(&self, count: u64) {
421        if count == 0 {
422            return;
423        }
424        let mut q = self.inner.lock().unwrap();
425        let pos = q.back;
426        q.push_skip(pos, count);
427    }
428
429    /// Drop any pending skip markers (used when attaching to a new outlet run).
430    pub(crate) fn clear_skips(&self) {
431        self.inner.lock().unwrap().skips.clear();
432    }
433
434    /// Take the oldest sample, waiting up to `timeout`.
435    ///
436    /// Returns `None` when the timeout passes with nothing waiting, or when the
437    /// queue is closed and empty.
438    pub fn pop(&self, timeout: Duration) -> Option<Sample> {
439        self.pop_packed_with_skip(timeout)
440            .map(|(s, _)| s.to_sample())
441    }
442
443    /// Take the oldest [`PackedSample`], waiting up to `timeout`.
444    pub fn pop_packed(&self, timeout: Duration) -> Option<PackedSample> {
445        self.pop_packed_with_skip(timeout).map(|(s, _)| s)
446    }
447
448    /// Take the oldest sample and the count of skipped samples immediately
449    /// before it, waiting up to `timeout`.
450    #[cfg(test)]
451    pub(crate) fn pop_with_skip(&self, timeout: Duration) -> Option<(Sample, u64)> {
452        self.pop_packed_with_skip(timeout)
453            .map(|(s, sk)| (s.to_sample(), sk))
454    }
455
456    /// Take the oldest [`PackedSample`] and the count of skipped samples
457    /// immediately before it, waiting up to `timeout`.
458    pub(crate) fn pop_packed_with_skip(&self, timeout: Duration) -> Option<(PackedSample, u64)> {
459        let mut end: Option<Instant> = None;
460        let mut q = self.inner.lock().unwrap();
461        loop {
462            if !q.is_empty() {
463                let pos = q.front_number();
464                let skipped = q.take_skips_at(pos);
465                let s = q.pop_front().unwrap();
466                q.note_pop(s.timestamp, s.timestamp);
467                return Some((s, skipped));
468            }
469            if timeout.is_zero() || *self.closed.lock().unwrap() {
470                return None;
471            }
472            let deadline = *end.get_or_insert_with(|| Instant::now() + timeout);
473            let left = deadline.saturating_duration_since(Instant::now());
474            if left.is_zero() {
475                return None;
476            }
477            let (guard, result) = self
478                .room
479                .wait_timeout(q, left.min(Duration::from_millis(100)))
480                .unwrap();
481            q = guard;
482            if result.timed_out() && Instant::now() >= deadline {
483                if !q.is_empty() {
484                    let pos = q.front_number();
485                    let skipped = q.take_skips_at(pos);
486                    let s = q.pop_front().unwrap();
487                    q.note_pop(s.timestamp, s.timestamp);
488                    return Some((s, skipped));
489                }
490                return None;
491            }
492        }
493    }
494
495    /// Take every sample that waits, up to `max`, with one lock.
496    ///
497    /// The samples go to the end of `out`. The call gives how many it added.
498    ///
499    /// The timeout applies to the first sample only. When one sample waits, the
500    /// call takes what is there and returns. It never waits for `max` samples,
501    /// because a program that shows live signals must show what arrived.
502    ///
503    /// A closed and empty queue gives zero.
504    pub fn pop_many(&self, out: &mut Vec<Sample>, max: usize, timeout: Duration) -> usize {
505        self.pop_many_with_skips(out, None, max, timeout)
506    }
507
508    /// Take every [`PackedSample`] that waits, up to `max`, with one lock.
509    pub fn pop_many_packed(
510        &self,
511        out: &mut Vec<PackedSample>,
512        max: usize,
513        timeout: Duration,
514    ) -> usize {
515        self.pop_many_packed_with_skips(out, None, max, timeout)
516    }
517
518    /// Like [`SampleQueue::pop_many`], and append `(offset_in_popped, skipped)`
519    /// pairs to `skips_out` when any samples were skipped within this block.
520    pub(crate) fn pop_many_with_skips(
521        &self,
522        out: &mut Vec<Sample>,
523        skips_out: Option<&mut Vec<(usize, u64)>>,
524        max: usize,
525        timeout: Duration,
526    ) -> usize {
527        let mut packed = Vec::new();
528        let got = self.pop_many_packed_with_skips(&mut packed, skips_out, max, timeout);
529        out.extend(packed.iter().map(PackedSample::to_sample));
530        got
531    }
532
533    /// Like [`SampleQueue::pop_many_packed`], and append `(offset_in_popped, skipped)`
534    /// pairs to `skips_out` when any samples were skipped within this block.
535    pub(crate) fn pop_many_packed_with_skips(
536        &self,
537        out: &mut Vec<PackedSample>,
538        mut skips_out: Option<&mut Vec<(usize, u64)>>,
539        max: usize,
540        timeout: Duration,
541    ) -> usize {
542        if max == 0 {
543            return 0;
544        }
545        let mut end: Option<Instant> = None;
546        let mut q = self.inner.lock().unwrap();
547        let drain_into = |q: &mut Ring,
548                          out: &mut Vec<PackedSample>,
549                          skips_out: &mut Option<&mut Vec<(usize, u64)>>,
550                          max: usize|
551         -> usize {
552            let take = q.len().min(max);
553            if take == 0 {
554                return 0;
555            }
556            let first_pos = q.front_number();
557            if !q.skips.is_empty() {
558                if let Some(dst) = skips_out.as_mut() {
559                    let lead = q.take_skips_at(first_pos);
560                    if lead > 0 {
561                        dst.push((0, lead));
562                    }
563                    let end_pos = first_pos.wrapping_add(take as u64);
564                    while let Some(&(pos, count)) = q.skips.front() {
565                        if pos < end_pos {
566                            let idx = (pos.wrapping_sub(first_pos)) as usize;
567                            dst.push((idx, count));
568                            q.skips.pop_front();
569                        } else {
570                            break;
571                        }
572                    }
573                } else {
574                    let end_pos = first_pos.wrapping_add(take as u64);
575                    while let Some(&(pos, _)) = q.skips.front() {
576                        if pos < end_pos {
577                            q.skips.pop_front();
578                        } else {
579                            break;
580                        }
581                    }
582                }
583            }
584            let first_ts = q.q[0].timestamp;
585            let last_ts = q.q[take - 1].timestamp;
586            out.extend(q.drain(..take));
587            q.note_pop(first_ts, last_ts);
588            take
589        };
590
591        loop {
592            if !q.is_empty() {
593                return drain_into(&mut q, out, &mut skips_out, max);
594            }
595            if timeout.is_zero() || *self.closed.lock().unwrap() {
596                return 0;
597            }
598            let deadline = *end.get_or_insert_with(|| Instant::now() + timeout);
599            let left = deadline.saturating_duration_since(Instant::now());
600            if left.is_zero() {
601                return 0;
602            }
603            let (guard, result) = self
604                .room
605                .wait_timeout(q, left.min(Duration::from_millis(100)))
606                .unwrap();
607            q = guard;
608            if result.timed_out() && Instant::now() >= deadline {
609                return drain_into(&mut q, out, &mut skips_out, max);
610            }
611        }
612    }
613
614    /// Like [`SampleQueue::pop_many`], and also give the number of the first
615    /// sample that it took.
616    ///
617    /// The samples that it took have consecutive numbers. With no sample, the
618    /// number is the one that the next sample gets.
619    pub fn pop_many_numbered(
620        &self,
621        out: &mut Vec<Sample>,
622        max: usize,
623        timeout: Duration,
624    ) -> (usize, u64) {
625        let mut packed = Vec::new();
626        let res = self.pop_many_packed_inner(&mut packed, None, max, timeout);
627        out.extend(packed.iter().map(PackedSample::to_sample));
628        res
629    }
630
631    /// Like [`SampleQueue::pop_many_numbered`], returning [`PackedSample`]s.
632    pub fn pop_many_numbered_packed(
633        &self,
634        out: &mut Vec<PackedSample>,
635        max: usize,
636        timeout: Duration,
637    ) -> (usize, u64) {
638        self.pop_many_packed_inner(out, None, max, timeout)
639    }
640
641    /// Like [`SampleQueue::pop_many_numbered`], and also add the full
642    /// timestamp of each sample that it took to the end of `full`.
643    ///
644    /// A queue with no deducer gives the timestamps of the samples as they
645    /// are.
646    pub fn pop_many_full(
647        &self,
648        out: &mut Vec<Sample>,
649        full: &mut Vec<f64>,
650        max: usize,
651        timeout: Duration,
652    ) -> (usize, u64) {
653        let mut packed = Vec::new();
654        let res = self.pop_many_packed_inner(&mut packed, Some(full), max, timeout);
655        out.extend(packed.iter().map(PackedSample::to_sample));
656        res
657    }
658
659    /// Like [`SampleQueue::pop_many_full`], returning [`PackedSample`]s.
660    pub fn pop_many_full_packed(
661        &self,
662        out: &mut Vec<PackedSample>,
663        full: &mut Vec<f64>,
664        max: usize,
665        timeout: Duration,
666    ) -> (usize, u64) {
667        self.pop_many_packed_inner(out, Some(full), max, timeout)
668    }
669
670    fn pop_many_packed_inner(
671        &self,
672        out: &mut Vec<PackedSample>,
673        mut full: Option<&mut Vec<f64>>,
674        max: usize,
675        timeout: Duration,
676    ) -> (usize, u64) {
677        let mut end: Option<Instant> = None;
678        let mut q = self.inner.lock().unwrap();
679        loop {
680            if max == 0
681                || !q.is_empty()
682                || timeout.is_zero()
683                || *self.closed.lock().unwrap()
684                || self.woken.swap(false, Ordering::SeqCst)
685            {
686                let first = q.front_number();
687                let take = q.len().min(max);
688                let ring = &mut *q;
689                for s in ring.q.drain(..take) {
690                    // The deducer sees each sample that leaves the queue, also
691                    // when the caller does not ask for the full timestamps.
692                    let t = match ring.deducer.as_mut() {
693                        Some(d) => d.apply(s.timestamp),
694                        None => s.timestamp,
695                    };
696                    if let Some(f) = full.as_mut() {
697                        f.push(t);
698                    }
699                    out.push(s);
700                }
701                return (take, first);
702            }
703            let deadline = *end.get_or_insert_with(|| Instant::now() + timeout);
704            let left = deadline.saturating_duration_since(Instant::now());
705            if left.is_zero() {
706                return (0, q.front_number());
707            }
708            let (guard, _) = self
709                .room
710                .wait_timeout(q, left.min(Duration::from_millis(100)))
711                .unwrap();
712            q = guard;
713        }
714    }
715
716    /// End the current wait of [`SampleQueue::pop_many_numbered`] or
717    /// [`SampleQueue::pop_many_full`] at once, with what the queue holds. A
718    /// session uses it when a request of its consumer arrives.
719    pub fn wake(&self) {
720        let _q = self.inner.lock().unwrap();
721        self.woken.store(true, Ordering::SeqCst);
722        self.room.notify_all();
723    }
724
725    /// Wake every reader and stop the queue.
726    pub fn close(&self) {
727        *self.closed.lock().unwrap() = true;
728        self.room.notify_all();
729    }
730
731    /// True once [`SampleQueue::close`] has run.
732    pub fn is_closed(&self) -> bool {
733        *self.closed.lock().unwrap()
734    }
735
736    /// Number of recorded drop gaps (including any in-progress overflow).
737    pub(crate) fn drop_gap_count(&self) -> usize {
738        let q = self.inner.lock().unwrap();
739        let pending = usize::from(q.pending_drop_count > 0 && q.q.front().is_some());
740        q.drop_gaps.len() + pending
741    }
742
743    /// Snapshot all drop gaps on this queue, shifted by `shift`.
744    pub(crate) fn drop_gaps(&self, shift: f64) -> Vec<Gap> {
745        let q = self.inner.lock().unwrap();
746        let mut out: Vec<Gap> = q
747            .drop_gaps
748            .iter()
749            .map(|g| Gap {
750                start: g.start + shift,
751                end: g.end + shift,
752                count: g.count,
753                kind: g.kind,
754            })
755            .collect();
756        if q.pending_drop_count > 0 {
757            if let Some(front) = q.q.front() {
758                let start = q.pending_drop_start.unwrap_or(front.timestamp);
759                if start.is_finite() && front.timestamp.is_finite() {
760                    out.push(Gap {
761                        start: start + shift,
762                        end: front.timestamp + shift,
763                        count: q.pending_drop_count,
764                        kind: GapKind::Dropped,
765                    });
766                }
767            }
768        }
769        out
770    }
771
772    /// Drain all finalized drop gaps on this queue, shifted by `shift`.
773    pub(crate) fn take_drop_gaps(&self, shift: f64) -> Vec<Gap> {
774        let mut q = self.inner.lock().unwrap();
775        q.drop_gaps
776            .drain(..)
777            .map(|g| Gap {
778                start: g.start + shift,
779                end: g.end + shift,
780                count: g.count,
781                kind: g.kind,
782            })
783            .collect()
784    }
785}
786
787#[derive(Debug)]
788struct ConsumerEntry {
789    id: u64,
790    peer: String,
791    queue: Arc<SampleQueue>,
792}
793
794#[derive(Debug)]
795struct ShmConsumerEntry {
796    id: u64,
797    peer: String,
798    writer: Arc<crate::shm::ShmWriter>,
799    channels: Option<Vec<u16>>,
800}
801
802/// A set of consumers that all receive the same sample.
803///
804/// liblsl calls this the send buffer (`src/send_buffer.h`). Each consumer holds
805/// its own queue, so a slow consumer loses only its own samples. SPEC.md 8.8.
806///
807/// The fanout also holds the history of the `resume` feature, and the
808/// timestamp deducer that gives the history its full timestamps.
809/// `docs/extensions.md`, section `resume`.
810#[derive(Debug, Default)]
811pub struct Fanout {
812    consumers: Mutex<Consumers>,
813    meta_gen: AtomicU64,
814    meta: Mutex<MetadataLog>,
815}
816
817#[derive(Debug, Default)]
818struct MetadataLog {
819    next_id: u64,
820    entries: VecDeque<(u64, MetadataUpdate)>,
821    latest: BTreeMap<String, MetadataUpdate>,
822}
823
824/// The queues of a fanout, the number of the next pushed sample, and the
825/// history.
826///
827/// One lock holds all of them, so a new queue starts at the number that the
828/// next push gives, every queue sees the same numbers, and the history holds
829/// the same numbers.
830#[derive(Debug)]
831struct Consumers {
832    list: Vec<ConsumerEntry>,
833    shm_list: Vec<ShmConsumerEntry>,
834    ts_scratch: Vec<f64>,
835    next_consumer_id: u64,
836    next: u64,
837    /// Calculates the full timestamp of each pushed sample, in the order of
838    /// the numbers. It runs also when there is no history, so that a history
839    /// that starts in the middle of a chunk gets correct timestamps.
840    deducer: TimestampDeducer,
841    srate: f64,
842    limits: HistoryLimits,
843    /// `None` until the first consumer agrees to `resume/1`.
844    history: Option<History>,
845}
846
847impl Default for Consumers {
848    fn default() -> Self {
849        Consumers {
850            list: Vec::new(),
851            shm_list: Vec::new(),
852            ts_scratch: Vec::new(),
853            next_consumer_id: 1,
854            next: 0,
855            deducer: TimestampDeducer::new(IRREGULAR_RATE),
856            srate: IRREGULAR_RATE,
857            limits: HistoryLimits::DEFAULT,
858            history: None,
859        }
860    }
861}
862
863impl Consumers {
864    /// Give one sample its number, its full timestamp, and its place in the
865    /// history.
866    fn record_packed_with_full(&mut self, s: &PackedSample, full: f64) {
867        if let Some(h) = self.history.as_mut() {
868            debug_assert_eq!(h.next(), self.next);
869            h.push_packed(s.with_timestamp(full));
870        }
871        self.next = self.next.wrapping_add(1);
872    }
873}
874
875impl Fanout {
876    /// Build an empty set for a stream with an irregular rate and the
877    /// default history limits.
878    pub fn new() -> Self {
879        Fanout::default()
880    }
881
882    /// Build an empty set for a stream with the nominal rate `srate`.
883    ///
884    /// The rate gives the deduced timestamps and the time limit of the
885    /// history.
886    pub fn with_rate(srate: f64, limits: HistoryLimits) -> Self {
887        Fanout {
888            consumers: Mutex::new(Consumers {
889                deducer: TimestampDeducer::new(srate),
890                srate,
891                limits,
892                ..Consumers::default()
893            }),
894            meta_gen: AtomicU64::new(0),
895            meta: Mutex::new(MetadataLog::default()),
896        }
897    }
898
899    /// Record a live metadata change at the current sample sequence boundary
900    /// and wake all active consumers (`docs/roadmap.md`, step 16).
901    pub fn push_metadata(&self, key: String, value: String, timestamp: f64) -> MetadataUpdate {
902        let (seq, queues): (u64, Vec<Arc<SampleQueue>>) = {
903            let set = self.consumers.lock().unwrap();
904            let qs = set.list.iter().map(|c| Arc::clone(&c.queue)).collect();
905            (set.next, qs)
906        };
907        let update = MetadataUpdate {
908            seq,
909            timestamp,
910            key: key.clone(),
911            value,
912        };
913        {
914            let mut log = self.meta.lock().unwrap();
915            log.next_id = log.next_id.wrapping_add(1);
916            let id = log.next_id;
917            if log.entries.len() >= MAX_META_LOG {
918                log.entries.pop_front();
919            }
920            log.entries.push_back((id, update.clone()));
921            log.latest.insert(key, update.clone());
922            self.meta_gen.store(id, Ordering::Release);
923        }
924        for q in queues {
925            q.wake();
926        }
927        update
928    }
929
930    /// Current metadata generation counter (0 when no metadata was pushed).
931    pub fn metadata_generation(&self) -> u64 {
932        self.meta_gen.load(Ordering::Acquire)
933    }
934
935    /// Snapshot the current latest metadata map together with its generation.
936    pub fn metadata_snapshot(&self) -> (u64, BTreeMap<String, MetadataUpdate>) {
937        if self.meta_gen.load(Ordering::Acquire) == 0 {
938            return (0, BTreeMap::new());
939        }
940        let log = self.meta.lock().unwrap();
941        (log.next_id, log.latest.clone())
942    }
943
944    /// Append any live metadata updates emitted after `*cursor` into `out` and
945    /// advance `*cursor`. Fast-paths with a single atomic load when idle.
946    pub fn read_metadata_since(&self, cursor: &mut u64, out: &mut Vec<MetadataUpdate>) {
947        let gen = self.meta_gen.load(Ordering::Acquire);
948        if gen == *cursor {
949            return;
950        }
951        let log = self.meta.lock().unwrap();
952        for (id, upd) in &log.entries {
953            if *id > *cursor {
954                out.push(upd.clone());
955            }
956        }
957        *cursor = log.next_id;
958    }
959
960    /// Start the history, if the limits allow it. The result is true when
961    /// the history is on.
962    ///
963    /// The history holds each sample that the outlet pushes from this point.
964    /// A second call changes nothing. `docs/extensions.md`, history rule 3.
965    pub fn start_history(&self) -> bool {
966        let mut set = self.consumers.lock().unwrap();
967        if set.history.is_none() && set.limits.allow_history() {
968            let h = History::new(set.limits.clone(), set.srate, set.next);
969            set.history = Some(h);
970        }
971        set.history.is_some()
972    }
973
974    /// How many samples the history holds across RAM and disk. Zero when it is off.
975    pub fn history_len(&self) -> usize {
976        let set = self.consumers.lock().unwrap();
977        set.history.as_ref().map_or(0, History::len)
978    }
979
980    /// Bytes currently held by the history in RAM. Zero when it is off.
981    pub fn history_ram_bytes(&self) -> usize {
982        let set = self.consumers.lock().unwrap();
983        set.history.as_ref().map_or(0, History::bytes)
984    }
985
986    /// Bytes currently held by the history in disk spool segments. Zero when off.
987    pub fn history_disk_bytes(&self) -> u64 {
988        let set = self.consumers.lock().unwrap();
989        set.history.as_ref().map_or(0, History::disk_bytes)
990    }
991
992    /// Path of the active disk spool directory, if disk spilling has started.
993    pub fn history_spool_dir(&self) -> Option<std::path::PathBuf> {
994        let set = self.consumers.lock().unwrap();
995        set.history.as_ref().and_then(History::spool_dir)
996    }
997
998    /// Copy at most `max` samples of the history to the end of `out`, from
999    /// the number `from`, and below the number `until`. Each sample has its
1000    /// full timestamp.
1001    ///
1002    /// The call takes the lock of the set one time. A push thus waits for at
1003    /// most the copy of `max` samples (and never for disk I/O).
1004    /// [`History::read`] gives the rules and the result.
1005    pub fn read_history(
1006        &self,
1007        from: u64,
1008        until: u64,
1009        max: usize,
1010        out: &mut Vec<Sample>,
1011    ) -> Option<(u64, usize)> {
1012        let mut packed = Vec::new();
1013        let res = self.read_history_packed(from, until, max, &mut packed)?;
1014        out.extend(packed.iter().map(PackedSample::to_sample));
1015        Some(res)
1016    }
1017
1018    /// Share at most `max` packed samples of the history to the end of `out`.
1019    ///
1020    /// RAM reads clone `Arc` handles under the lock; disk reads execute
1021    /// outside the `Fanout` lock so live pushes and other consumers never
1022    /// wait on disk I/O.
1023    pub fn read_history_packed(
1024        &self,
1025        from: u64,
1026        until: u64,
1027        max: usize,
1028        out: &mut Vec<PackedSample>,
1029    ) -> Option<(u64, usize)> {
1030        let plan = {
1031            let set = self.consumers.lock().unwrap();
1032            set.history
1033                .as_ref()?
1034                .plan_read_packed(from, until, max, out)
1035        };
1036        match plan {
1037            HistoryRead::Empty => None,
1038            HistoryRead::Ready { first, count } => Some((first, count)),
1039            HistoryRead::Disk(disk_plan) => disk_plan.execute(out),
1040        }
1041    }
1042
1043    /// Add a consumer with its own queue.
1044    pub fn add(&self, capacity: usize) -> Arc<SampleQueue> {
1045        self.add_with_peer(capacity, String::new())
1046    }
1047
1048    /// Add a consumer with its own queue and peer label.
1049    pub(crate) fn add_with_peer(&self, capacity: usize, peer: String) -> Arc<SampleQueue> {
1050        let mut set = self.consumers.lock().unwrap();
1051        let id = set.next_consumer_id;
1052        set.next_consumer_id = id.wrapping_add(1);
1053        let q = Arc::new(SampleQueue::with_first_number(capacity, set.next));
1054        set.list.push(ConsumerEntry {
1055            id,
1056            peer,
1057            queue: Arc::clone(&q),
1058        });
1059        q
1060    }
1061
1062    /// Add a consumer for the `resume` feature. The result is its queue and
1063    /// `N`, the number of the first sample that the queue gets.
1064    ///
1065    /// The queue gives the full timestamp of each sample
1066    /// ([`SampleQueue::pop_many_full`]). The history holds the samples below
1067    /// `N`. `docs/extensions.md`, resend rule 1.
1068    pub fn add_resumable(&self, capacity: usize) -> (Arc<SampleQueue>, u64) {
1069        self.add_resumable_with_peer(capacity, String::new())
1070    }
1071
1072    /// Add a resumable consumer with its peer label.
1073    pub(crate) fn add_resumable_with_peer(
1074        &self,
1075        capacity: usize,
1076        peer: String,
1077    ) -> (Arc<SampleQueue>, u64) {
1078        let mut set = self.consumers.lock().unwrap();
1079        let id = set.next_consumer_id;
1080        set.next_consumer_id = id.wrapping_add(1);
1081        let n = set.next;
1082        let q = Arc::new(SampleQueue::with_deducer(capacity, n, set.deducer.clone()));
1083        set.list.push(ConsumerEntry {
1084            id,
1085            peer,
1086            queue: Arc::clone(&q),
1087        });
1088        (q, n)
1089    }
1090
1091    /// The number that the next pushed sample gets.
1092    pub fn next_number(&self) -> u64 {
1093        self.consumers.lock().unwrap().next
1094    }
1095
1096    /// Add a direct `shm/1` consumer ring to the fanout.
1097    pub(crate) fn add_shm_with_peer(
1098        &self,
1099        writer: Arc<crate::shm::ShmWriter>,
1100        peer: String,
1101        channels: Option<Vec<u16>>,
1102    ) -> u64 {
1103        let mut set = self.consumers.lock().unwrap();
1104        let id = set.next_consumer_id;
1105        set.next_consumer_id = id.wrapping_add(1);
1106        let n = set.next;
1107        set.shm_list.push(ShmConsumerEntry {
1108            id,
1109            peer,
1110            writer,
1111            channels,
1112        });
1113        n
1114    }
1115
1116    /// Remove a `shm/1` consumer ring from the fanout.
1117    pub(crate) fn remove_shm(&self, writer: &Arc<crate::shm::ShmWriter>) {
1118        self.consumers
1119            .lock()
1120            .unwrap()
1121            .shm_list
1122            .retain(|c| !Arc::ptr_eq(&c.writer, writer));
1123    }
1124
1125    /// Remove a consumer.
1126    pub fn remove(&self, q: &Arc<SampleQueue>) {
1127        self.consumers
1128            .lock()
1129            .unwrap()
1130            .list
1131            .retain(|c| !Arc::ptr_eq(&c.queue, q));
1132    }
1133
1134    /// How many consumers are connected.
1135    pub fn count(&self) -> usize {
1136        let set = self.consumers.lock().unwrap();
1137        set.list.len() + set.shm_list.len()
1138    }
1139
1140    /// Snapshot the fill and drop state of every connected consumer queue.
1141    pub fn health(&self) -> OutletHealth {
1142        let mut set = self.consumers.lock().unwrap();
1143        set.list.retain(|c| !c.queue.is_closed());
1144        set.shm_list.retain(|c| !c.writer.is_closed());
1145        let mut consumers: Vec<ConsumerHealth> = set
1146            .list
1147            .iter()
1148            .map(|c| ConsumerHealth {
1149                id: c.id,
1150                peer: c.peer.clone(),
1151                fill: c.queue.len(),
1152                capacity: c.queue.capacity(),
1153                dropped: c.queue.dropped(),
1154            })
1155            .collect();
1156        consumers.extend(set.shm_list.iter().map(|c| ConsumerHealth {
1157            id: c.id,
1158            peer: c.peer.clone(),
1159            fill: c.writer.fill(),
1160            capacity: c.writer.requested_capacity(),
1161            dropped: c.writer.outlet_dropped(),
1162        }));
1163        OutletHealth {
1164            consumers,
1165            history_len: set.history.as_ref().map_or(0, History::len),
1166            pushed: set.next,
1167        }
1168    }
1169
1170    /// Give one sample to every consumer.
1171    ///
1172    /// A consumer that has gone away is dropped from the set. The call never
1173    /// waits, whatever any consumer is doing.
1174    pub fn push(&self, s: &Sample) {
1175        self.push_packed(PackedSample::from_sample(s));
1176    }
1177
1178    /// Zero-allocation numeric single-sample push: writes directly to any
1179    /// `shm/1` consumer rings first, and allocates a [`PackedSample`] only if
1180    /// queued consumers or `resume/1` history exist.
1181    pub(crate) fn push_numeric_raw(
1182        &self,
1183        timestamp: f64,
1184        format: labstream_wire::Format,
1185        bytes: &[u8],
1186    ) {
1187        let mut set = self.consumers.lock().unwrap();
1188        let seq = set.next;
1189        let full = set.deducer.apply(timestamp);
1190        if !set.shm_list.is_empty() {
1191            set.shm_list.retain(|c| !c.writer.is_closed());
1192            for c in set.shm_list.iter() {
1193                c.writer
1194                    .push_raw_one(seq, full, bytes, c.channels.as_deref());
1195            }
1196        }
1197        if !set.list.is_empty() || set.history.is_some() {
1198            let s = PackedSample::from_raw_bytes(timestamp, format, Arc::from(bytes));
1199            set.list.retain(|c| !c.queue.is_closed());
1200            for c in set.list.iter() {
1201                c.queue.push_packed(s.clone());
1202            }
1203            set.record_packed_with_full(&s, full);
1204        } else {
1205            set.next = set.next.wrapping_add(1);
1206        }
1207    }
1208
1209    /// Give one [`PackedSample`] to every consumer and the `resume` history,
1210    /// sharing its `Arc` payload with zero byte copies.
1211    pub fn push_packed(&self, s: PackedSample) {
1212        let mut set = self.consumers.lock().unwrap();
1213        let seq = set.next;
1214        let full = set.deducer.apply(s.timestamp);
1215        // SHM consumers get the sample first (zero-hop direct write + wake).
1216        if !set.shm_list.is_empty() {
1217            set.shm_list.retain(|c| !c.writer.is_closed());
1218            if let labstream_wire::PackedValues::Numeric { bytes, .. } = &s.values {
1219                for c in set.shm_list.iter() {
1220                    c.writer
1221                        .push_raw_one(seq, full, bytes, c.channels.as_deref());
1222                }
1223            }
1224        }
1225        // The consumers get the sample first, so that recording into the
1226        // history does not delay them. The lock holds both steps, so a new
1227        // queue and the history still agree on each number.
1228        set.list.retain(|c| !c.queue.is_closed());
1229        for c in set.list.iter() {
1230            c.queue.push_packed(s.clone());
1231        }
1232        set.record_packed_with_full(&s, full);
1233    }
1234
1235    /// Give several samples to every consumer, with one lock for the set.
1236    ///
1237    /// The result for each consumer is the same as one [`Fanout::push`] for each
1238    /// sample, in order.
1239    pub fn push_many(&self, samples: &[Sample]) {
1240        if samples.is_empty() {
1241            return;
1242        }
1243        let packed: Vec<PackedSample> = samples.iter().map(PackedSample::from_sample).collect();
1244        self.push_many_packed(&packed);
1245    }
1246
1247    /// Give several [`PackedSample`]s to every consumer and the `resume`
1248    /// history with one lock, sharing each `Arc` payload with zero byte copies.
1249    pub fn push_many_packed(&self, samples: &[PackedSample]) {
1250        if samples.is_empty() {
1251            return;
1252        }
1253        let mut set = self.consumers.lock().unwrap();
1254        let first_seq = set.next;
1255        let mut full_ts = std::mem::take(&mut set.ts_scratch);
1256        full_ts.clear();
1257        full_ts.reserve(samples.len());
1258        for s in samples {
1259            full_ts.push(set.deducer.apply(s.timestamp));
1260        }
1261        if !set.shm_list.is_empty() {
1262            set.shm_list.retain(|c| !c.writer.is_closed());
1263            for c in set.shm_list.iter() {
1264                c.writer
1265                    .push_batch(first_seq, samples, &full_ts, c.channels.as_deref());
1266            }
1267        }
1268        // The consumers first, as in [`Fanout::push_packed`].
1269        set.list.retain(|c| !c.queue.is_closed());
1270        for c in set.list.iter() {
1271            c.queue.push_many_packed(samples);
1272        }
1273        for (s, &full) in samples.iter().zip(&full_ts) {
1274            set.record_packed_with_full(s, full);
1275        }
1276        set.ts_scratch = full_ts;
1277    }
1278
1279    /// Push a flat contiguous numeric chunk with per-sample timestamps, writing
1280    /// directly to any `shm/1` consumers before allocating `PackedSample`s for
1281    /// queued consumers or `resume/1` history.
1282    pub(crate) fn push_chunk_numeric_raw(
1283        &self,
1284        format: labstream_wire::Format,
1285        raw: &[u8],
1286        row_bytes: usize,
1287        timestamps: &[f64],
1288    ) {
1289        let n = timestamps.len();
1290        if n == 0 || row_bytes == 0 || raw.len() < n * row_bytes {
1291            return;
1292        }
1293        let mut set = self.consumers.lock().unwrap();
1294        let first_seq = set.next;
1295        let mut full_ts = std::mem::take(&mut set.ts_scratch);
1296        full_ts.clear();
1297        full_ts.reserve(n);
1298        for &t in timestamps {
1299            full_ts.push(set.deducer.apply(t));
1300        }
1301        if !set.shm_list.is_empty() {
1302            set.shm_list.retain(|c| !c.writer.is_closed());
1303            for c in set.shm_list.iter() {
1304                c.writer
1305                    .push_chunk_raw(first_seq, raw, row_bytes, &full_ts, c.channels.as_deref());
1306            }
1307        }
1308        if !set.list.is_empty() || set.history.is_some() {
1309            let block: Vec<PackedSample> = (0..n)
1310                .map(|k| {
1311                    PackedSample::from_raw_bytes(
1312                        timestamps[k],
1313                        format,
1314                        Arc::from(&raw[k * row_bytes..(k + 1) * row_bytes]),
1315                    )
1316                })
1317                .collect();
1318            set.list.retain(|c| !c.queue.is_closed());
1319            for c in set.list.iter() {
1320                c.queue.push_many_packed(&block);
1321            }
1322            for (s, &full) in block.iter().zip(&full_ts) {
1323                set.record_packed_with_full(s, full);
1324            }
1325        } else {
1326            set.next = set.next.wrapping_add(n as u64);
1327        }
1328        set.ts_scratch = full_ts;
1329    }
1330
1331    /// Close every consumer queue and shared-memory ring.
1332    pub fn close(&self) {
1333        let set = self.consumers.lock().unwrap();
1334        for c in set.list.iter() {
1335            c.queue.close();
1336        }
1337        for c in set.shm_list.iter() {
1338            c.writer.close();
1339        }
1340    }
1341}
1342
1343#[cfg(test)]
1344mod tests {
1345    use super::*;
1346    use labstream_wire::Value;
1347
1348    fn sample(i: i32) -> Sample {
1349        Sample {
1350            timestamp: i as f64,
1351            values: vec![Value::I32(i)],
1352        }
1353    }
1354
1355    fn index(s: &Sample) -> i32 {
1356        match s.values[0] {
1357            Value::I32(v) => v,
1358            _ => panic!("wrong format"),
1359        }
1360    }
1361
1362    #[test]
1363    fn a_full_queue_keeps_the_newest() {
1364        // The recorded shape from `artifacts/behavior-liblsl.json`, in small.
1365        let q = SampleQueue::new(100);
1366        for i in 0..600 {
1367            q.push(sample(i));
1368        }
1369        assert_eq!(q.len(), 100);
1370        assert_eq!(q.dropped(), 500);
1371
1372        let first = q.pop(Duration::from_millis(10)).expect("a sample");
1373        assert_eq!(index(&first), 500, "the oldest surviving sample");
1374
1375        let mut last = first;
1376        while let Some(s) = q.pop(Duration::from_millis(10)) {
1377            last = s;
1378        }
1379        assert_eq!(index(&last), 599, "the newest sample");
1380    }
1381
1382    #[test]
1383    fn a_block_write_gives_what_single_writes_give() {
1384        // The batch call is an optimization. It must lose the same samples, keep
1385        // the same samples, and count the same drops.
1386        let one = SampleQueue::new(100);
1387        let many = SampleQueue::new(100);
1388        let block: Vec<Sample> = (0..600).map(sample).collect();
1389        for s in &block {
1390            one.push(s.clone());
1391        }
1392        many.push_many(&block);
1393
1394        assert_eq!(one.len(), many.len());
1395        assert_eq!(one.dropped(), many.dropped());
1396        while let Some(a) = one.pop(Duration::from_millis(10)) {
1397            let b = many.pop(Duration::from_millis(10)).expect("the same count");
1398            assert_eq!(index(&a), index(&b));
1399        }
1400        assert!(many.pop(Duration::from_millis(10)).is_none());
1401    }
1402
1403    #[test]
1404    fn an_owned_block_write_gives_what_single_writes_give() {
1405        // The same rules as `push_many`, with the existing samples first, then
1406        // a block larger than the queue.
1407        for (before, block_len) in [(0, 50), (30, 50), (30, 600), (0, 100), (99, 1)] {
1408            let one = SampleQueue::new(100);
1409            let owned = SampleQueue::new(100);
1410            for i in 0..before {
1411                one.push(sample(i));
1412                owned.push(sample(i));
1413            }
1414            let mut block: Vec<Sample> = (1000..1000 + block_len).map(sample).collect();
1415            for s in &block {
1416                one.push(s.clone());
1417            }
1418            owned.push_owned(&mut block);
1419            assert!(block.is_empty(), "the call takes every sample");
1420
1421            assert_eq!(one.len(), owned.len());
1422            assert_eq!(one.dropped(), owned.dropped(), "{before} then {block_len}");
1423            while let Some(a) = one.pop(Duration::from_millis(10)) {
1424                let b = owned
1425                    .pop(Duration::from_millis(10))
1426                    .expect("the same count");
1427                assert_eq!(index(&a), index(&b));
1428            }
1429            assert!(owned.pop(Duration::from_millis(10)).is_none());
1430        }
1431    }
1432
1433    #[test]
1434    fn a_block_read_takes_what_waits_in_order() {
1435        let q = SampleQueue::new(100);
1436        q.push_many(&(0..10).map(sample).collect::<Vec<_>>());
1437
1438        let mut out = Vec::new();
1439        let got = q.pop_many(&mut out, 4, Duration::from_millis(10));
1440        assert_eq!(got, 4, "the call stops at max");
1441        assert_eq!(out.iter().map(index).collect::<Vec<_>>(), [0, 1, 2, 3]);
1442
1443        let got = q.pop_many(&mut out, 100, Duration::from_millis(10));
1444        assert_eq!(got, 6, "the call takes what waits, and not more");
1445        assert_eq!(out.len(), 10, "the samples go to the end of the buffer");
1446        assert_eq!(index(&out[9]), 9);
1447    }
1448
1449    #[test]
1450    fn a_block_read_of_an_empty_queue_gives_nothing() {
1451        let q = SampleQueue::new(10);
1452        let mut out = Vec::new();
1453        assert_eq!(q.pop_many(&mut out, 8, Duration::from_millis(5)), 0);
1454        assert!(out.is_empty());
1455
1456        q.close();
1457        assert_eq!(q.pop_many(&mut out, 8, Duration::from_millis(50)), 0);
1458    }
1459
1460    #[test]
1461    fn a_block_read_waits_for_the_first_sample_only() {
1462        // A reader that waited for `max` samples would hold a viewer back by the
1463        // time that the rest of the block needs.
1464        let q = Arc::new(SampleQueue::new(10));
1465        let writer = Arc::clone(&q);
1466        std::thread::spawn(move || {
1467            std::thread::sleep(Duration::from_millis(20));
1468            writer.push_many(&[sample(1), sample(2)]);
1469        });
1470        let mut out = Vec::new();
1471        let start = Instant::now();
1472        let got = q.pop_many(&mut out, 1000, Duration::from_secs(5));
1473        assert_eq!(got, 2, "the call takes the block that arrived");
1474        assert!(
1475            start.elapsed() < Duration::from_secs(1),
1476            "the call returned"
1477        );
1478    }
1479
1480    #[test]
1481    fn a_block_reaches_every_consumer() {
1482        let fan = Fanout::new();
1483        let a = fan.add(10);
1484        let b = fan.add(10);
1485        fan.push_many(&[sample(7), sample(8)]);
1486
1487        for q in [&a, &b] {
1488            let mut out = Vec::new();
1489            assert_eq!(q.pop_many(&mut out, 10, Duration::from_millis(10)), 2);
1490            assert_eq!(out.iter().map(index).collect::<Vec<_>>(), [7, 8]);
1491        }
1492    }
1493
1494    #[test]
1495    fn the_writer_never_waits() {
1496        // A queue of one, written a million times, must finish at once. A
1497        // design that waited for a reader would never return.
1498        let q = SampleQueue::new(1);
1499        let start = Instant::now();
1500        for i in 0..1_000_000 {
1501            q.push(sample(i));
1502        }
1503        assert!(
1504            start.elapsed() < Duration::from_secs(10),
1505            "the writer waited"
1506        );
1507        assert_eq!(q.len(), 1);
1508        assert_eq!(index(&q.pop(Duration::from_millis(10)).unwrap()), 999_999);
1509    }
1510
1511    #[test]
1512    fn a_capacity_of_zero_floors_at_one() {
1513        let q = SampleQueue::new(0);
1514        assert_eq!(q.capacity(), 1);
1515        q.push(sample(7));
1516        assert_eq!(index(&q.pop(Duration::from_millis(10)).unwrap()), 7);
1517    }
1518
1519    #[test]
1520    fn an_empty_queue_reports_nothing_after_the_timeout() {
1521        let q = SampleQueue::new(4);
1522        let start = Instant::now();
1523        assert!(q.pop(Duration::from_millis(120)).is_none());
1524        assert!(start.elapsed() >= Duration::from_millis(100));
1525    }
1526
1527    #[test]
1528    fn a_closed_queue_stops_a_reader_at_once() {
1529        let q = Arc::new(SampleQueue::new(4));
1530        let c = Arc::clone(&q);
1531        std::thread::spawn(move || {
1532            std::thread::sleep(Duration::from_millis(30));
1533            c.close();
1534        });
1535        let start = Instant::now();
1536        assert!(q.pop(Duration::from_secs(10)).is_none());
1537        assert!(
1538            start.elapsed() < Duration::from_secs(2),
1539            "the reader waited out the timeout"
1540        );
1541    }
1542
1543    #[test]
1544    fn a_reader_wakes_when_a_sample_arrives() {
1545        let q = Arc::new(SampleQueue::new(4));
1546        let c = Arc::clone(&q);
1547        std::thread::spawn(move || {
1548            std::thread::sleep(Duration::from_millis(30));
1549            c.push(sample(42));
1550        });
1551        let got = q.pop(Duration::from_secs(2)).expect("a sample");
1552        assert_eq!(index(&got), 42);
1553    }
1554
1555    #[test]
1556    fn a_slow_consumer_never_holds_back_a_fast_one() {
1557        // SPEC.md 8.8. The fast queue is large and the slow queue is small.
1558        let f = Fanout::new();
1559        let fast = f.add(1000);
1560        let slow = f.add(10);
1561        for i in 0..500 {
1562            f.push(&sample(i));
1563        }
1564        assert_eq!(fast.len(), 500, "the fast consumer lost samples");
1565        assert_eq!(fast.dropped(), 0);
1566        assert_eq!(slow.len(), 10);
1567        assert_eq!(slow.dropped(), 490);
1568    }
1569
1570    #[test]
1571    fn a_closed_consumer_leaves_the_set() {
1572        let f = Fanout::new();
1573        let a = f.add(10);
1574        let b = f.add(10);
1575        assert_eq!(f.count(), 2);
1576        b.close();
1577        f.push(&sample(1));
1578        assert_eq!(f.count(), 1, "a closed consumer must be removed");
1579        assert_eq!(a.len(), 1);
1580    }
1581
1582    #[test]
1583    fn removing_a_consumer_stops_its_samples() {
1584        let f = Fanout::new();
1585        let a = f.add(10);
1586        f.push(&sample(1));
1587        f.remove(&a);
1588        f.push(&sample(2));
1589        assert_eq!(a.len(), 1, "a removed consumer must receive nothing more");
1590    }
1591
1592    /// A small generator, so the test runs the same steps on each run.
1593    struct Steps(u64);
1594
1595    impl Steps {
1596        fn next(&mut self, below: u64) -> u64 {
1597            self.0 ^= self.0 << 13;
1598            self.0 ^= self.0 >> 7;
1599            self.0 ^= self.0 << 17;
1600            self.0 % below
1601        }
1602    }
1603
1604    #[test]
1605    fn the_numbers_follow_a_model_with_one_number_for_each_sample() {
1606        // Each sample carries its own number as its value. The model keeps
1607        // the numbers. Every way to push, drop and pop must agree with it.
1608        for seed in 1..40u64 {
1609            let mut steps = Steps(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15));
1610            let capacity = 1 + steps.next(12) as usize;
1611            let first = steps.next(1000);
1612            let q = SampleQueue::with_first_number(capacity, first);
1613            let mut model: VecDeque<u64> = VecDeque::new();
1614            let mut next = first;
1615            for _ in 0..400 {
1616                match steps.next(5) {
1617                    0 => {
1618                        q.push(sample(next as i32));
1619                        model.push_back(next);
1620                        next += 1;
1621                    }
1622                    1 | 2 => {
1623                        let k = steps.next(30) as usize;
1624                        let block: Vec<Sample> =
1625                            (0..k).map(|i| sample((next + i as u64) as i32)).collect();
1626                        if steps.next(2) == 0 {
1627                            q.push_many(&block);
1628                        } else {
1629                            let mut owned = block;
1630                            q.push_owned(&mut owned);
1631                        }
1632                        for i in 0..k as u64 {
1633                            model.push_back(next + i);
1634                        }
1635                        next += k as u64;
1636                    }
1637                    3 => {
1638                        let got = q.pop(Duration::ZERO);
1639                        let want = model.pop_front();
1640                        assert_eq!(got.map(|s| index(&s) as u64), want);
1641                    }
1642                    _ => {
1643                        let max = 1 + steps.next(20) as usize;
1644                        let mut out = Vec::new();
1645                        let (n, number) = q.pop_many_numbered(&mut out, max, Duration::ZERO);
1646                        assert_eq!(n, out.len());
1647                        let want_first = model.front().copied().unwrap_or(next);
1648                        assert_eq!(number, want_first, "seed {seed}");
1649                        for (i, s) in out.iter().enumerate() {
1650                            assert_eq!(index(s) as u64, number + i as u64, "seed {seed}");
1651                            assert_eq!(model.pop_front(), Some(number + i as u64));
1652                        }
1653                    }
1654                }
1655                while model.len() > capacity {
1656                    model.pop_front();
1657                }
1658                assert_eq!(q.len(), model.len(), "seed {seed}");
1659            }
1660        }
1661    }
1662
1663    #[test]
1664    fn a_late_consumer_starts_at_the_current_number() {
1665        let f = Fanout::new();
1666        let a = f.add(100);
1667        for i in 0..5 {
1668            f.push(&sample(i));
1669        }
1670        let b = f.add(100);
1671        assert_eq!(f.next_number(), 5);
1672        f.push_many(&[sample(5), sample(6)]);
1673        let mut out = Vec::new();
1674        assert_eq!(a.pop_many_numbered(&mut out, 100, Duration::ZERO), (7, 0));
1675        out.clear();
1676        assert_eq!(b.pop_many_numbered(&mut out, 100, Duration::ZERO), (2, 5));
1677        assert_eq!(index(&out[0]), 5);
1678    }
1679
1680    /// A chunk as `Outlet::push_chunk` makes it: a timestamp on the first
1681    /// sample, and the deduced tag on the others. SPEC.md 9.2.
1682    fn chunk(first: i32, len: i32, t: f64) -> Vec<Sample> {
1683        (first..first + len)
1684            .map(|i| Sample {
1685                timestamp: if i == first {
1686                    t
1687                } else {
1688                    labstream_wire::DEDUCED_TIMESTAMP
1689                },
1690                values: vec![Value::I32(i)],
1691            })
1692            .collect()
1693    }
1694
1695    #[test]
1696    fn the_history_is_off_until_a_consumer_asks_for_it() {
1697        let f = Fanout::with_rate(100.0, HistoryLimits::DEFAULT);
1698        let q = f.add(100);
1699        f.push_many(&chunk(0, 10, 1.0));
1700        assert_eq!(f.history_len(), 0);
1701        assert_eq!(f.read_history(0, 10, 256, &mut Vec::new()), None);
1702
1703        assert!(f.start_history());
1704        assert!(f.start_history(), "a second call changes nothing");
1705        assert_eq!(
1706            f.history_len(),
1707            0,
1708            "the history holds no sample from before"
1709        );
1710
1711        // The history holds the samples that no consumer gets.
1712        f.remove(&q);
1713        f.push_many(&chunk(10, 5, 2.0));
1714        f.push(&sample(15));
1715        assert_eq!(f.history_len(), 6);
1716        let mut out = Vec::new();
1717        assert_eq!(
1718            f.read_history(0, f.next_number(), 256, &mut out),
1719            Some((10, 6))
1720        );
1721        assert_eq!(
1722            out.iter().map(index).collect::<Vec<_>>(),
1723            (10..16).collect::<Vec<_>>()
1724        );
1725    }
1726
1727    #[test]
1728    fn limits_that_turn_the_history_off_keep_it_off() {
1729        let f = Fanout::with_rate(100.0, HistoryLimits::OFF);
1730        assert!(!f.start_history());
1731        f.push(&sample(0));
1732        assert_eq!(f.history_len(), 0);
1733    }
1734
1735    #[test]
1736    fn the_history_and_the_queues_use_the_same_numbers() {
1737        let f = Fanout::with_rate(100.0, HistoryLimits::DEFAULT);
1738        f.push_many(&chunk(0, 7, 1.0));
1739        f.start_history();
1740        let q = f.add(100);
1741        f.push_many(&chunk(7, 20, 2.0));
1742        let mut live = Vec::new();
1743        let (_, first) = q.pop_many_numbered(&mut live, 100, Duration::ZERO);
1744        assert_eq!(first, 7);
1745        let mut old = Vec::new();
1746        assert_eq!(
1747            f.read_history(first, u64::MAX / 4, 256, &mut old),
1748            Some((7, 20))
1749        );
1750        let a: Vec<i32> = live.iter().map(index).collect();
1751        let b: Vec<i32> = old.iter().map(index).collect();
1752        assert_eq!(a, b);
1753        // A resend stops below the first number of the new queue, so no
1754        // sample goes to the consumer twice.
1755        assert_eq!(f.read_history(0, first, 256, &mut Vec::new()), None);
1756        let q2 = f.add(100);
1757        let n = f.next_number();
1758        f.push_many(&chunk(27, 5, 3.0));
1759        let mut resent = Vec::new();
1760        assert_eq!(f.read_history(10, n, 256, &mut resent), Some((10, 17)));
1761        assert_eq!(index(resent.last().unwrap()) as u64, n - 1);
1762        let mut live = Vec::new();
1763        assert_eq!(q2.pop_many_numbered(&mut live, 100, Duration::ZERO), (5, n));
1764    }
1765
1766    #[test]
1767    fn the_history_holds_the_timestamps_that_an_inlet_calculates() {
1768        // A rate with no exact binary form, so that each addition rounds.
1769        let srate = 300.0;
1770        let f = Fanout::with_rate(srate, HistoryLimits::DEFAULT);
1771        // Push the first part of a chunk, then start the history in the
1772        // middle of the next chunk.
1773        let mut pushed = chunk(0, 9, 1.234_567);
1774        pushed.extend(chunk(9, 9, 1.5));
1775        let second = chunk(18, 9, 2.0);
1776        f.push_many(&pushed);
1777        f.push_many(&second[..4]);
1778        f.start_history();
1779        f.push_many(&second[4..]);
1780        f.push(&sample(27));
1781        pushed.extend(second);
1782        pushed.push(sample(27));
1783
1784        // An inlet with no dropout reads every sample of the connection.
1785        let mut inlet = TimestampDeducer::new(srate);
1786        let want: Vec<u64> = pushed
1787            .iter()
1788            .map(|s| inlet.apply(s.timestamp).to_bits())
1789            .collect();
1790
1791        let mut got = Vec::new();
1792        assert_eq!(f.read_history(0, 28, 256, &mut got), Some((22, 6)));
1793        assert_eq!(got.len(), 6);
1794        for s in &got {
1795            assert_ne!(s.timestamp, labstream_wire::DEDUCED_TIMESTAMP);
1796            let i = index(s) as usize;
1797            assert_eq!(s.timestamp.to_bits(), want[i], "sample {i}");
1798        }
1799    }
1800
1801    #[test]
1802    fn a_read_takes_one_block() {
1803        let f = Fanout::with_rate(1000.0, HistoryLimits::DEFAULT);
1804        f.start_history();
1805        for i in 0..1000 {
1806            f.push(&sample(i));
1807        }
1808        let mut out = Vec::new();
1809        let mut from = 0;
1810        let mut blocks = 0;
1811        while let Some((first, count)) = f.read_history(from, 1000, 256, &mut out) {
1812            from = first + count as u64;
1813            blocks += 1;
1814        }
1815        assert_eq!(blocks, 4);
1816        assert_eq!(out.len(), 1000);
1817        assert_eq!(
1818            out.iter().map(index).collect::<Vec<_>>(),
1819            (0..1000).collect::<Vec<_>>()
1820        );
1821    }
1822
1823    #[test]
1824    fn a_full_queue_records_a_coalesced_drop_gap() {
1825        let q = SampleQueue::new(4);
1826        q.push(sample(10));
1827        let first = q.pop(Duration::from_millis(10)).unwrap();
1828        assert_eq!(first.timestamp, 10.0);
1829
1830        // Overflow the 4-sample queue with 10 samples (11..=20): drops 6 (11..=16).
1831        let mut batch: Vec<Sample> = (11..=20).map(sample).collect();
1832        q.push_owned(&mut batch);
1833        assert_eq!(q.dropped(), 6);
1834        let pending = q.drop_gaps(0.0);
1835        assert_eq!(pending.len(), 1);
1836        assert_eq!(pending[0].start, 10.0);
1837        assert_eq!(pending[0].end, 17.0);
1838        assert_eq!(pending[0].count, 6);
1839        assert_eq!(pending[0].kind, GapKind::Dropped);
1840
1841        let next = q.pop(Duration::from_millis(10)).unwrap();
1842        assert_eq!(next.timestamp, 17.0);
1843        let taken = q.take_drop_gaps(50.0);
1844        assert_eq!(taken.len(), 1);
1845        assert_eq!(taken[0].start, 60.0);
1846        assert_eq!(taken[0].end, 67.0);
1847        assert_eq!(taken[0].count, 6);
1848        assert!(q.drop_gaps(0.0).is_empty());
1849    }
1850
1851    #[test]
1852    fn fanout_health_reports_fill_capacity_and_drops_per_consumer() {
1853        let fan = Fanout::new();
1854        let fast = fan.add_with_peer(10, "127.0.0.1:40001".to_string());
1855        let slow = fan.add_with_peer(3, "127.0.0.1:40002".to_string());
1856
1857        for i in 0..8 {
1858            fan.push(&sample(i));
1859            let _ = fast.pop(Duration::from_millis(1));
1860        }
1861
1862        let h = fan.health();
1863        assert_eq!(h.pushed, 8);
1864        assert_eq!(h.consumers.len(), 2);
1865        assert_eq!(h.consumers[0].id, 1);
1866        assert_eq!(h.consumers[0].peer, "127.0.0.1:40001");
1867        assert_eq!(h.consumers[0].fill, 0);
1868        assert_eq!(h.consumers[0].capacity, 10);
1869        assert_eq!(h.consumers[0].dropped, 0);
1870
1871        assert_eq!(h.consumers[1].id, 2);
1872        assert_eq!(h.consumers[1].peer, "127.0.0.1:40002");
1873        assert_eq!(h.consumers[1].fill, 3);
1874        assert_eq!(h.consumers[1].capacity, 3);
1875        assert_eq!(h.consumers[1].dropped, 5);
1876        drop(slow);
1877    }
1878
1879    #[test]
1880    fn queue_delivers_exact_skip_positions_on_pop_and_pop_many() {
1881        let q = SampleQueue::new(32);
1882        let mut batch: Vec<Sample> = (0..6).map(sample).collect();
1883        // 100 samples lost between sample 2 and sample 3.
1884        q.push_owned_with_skips(&mut batch, &[(3, 100)]);
1885
1886        let mut out = Vec::new();
1887        let mut skips = Vec::new();
1888        let got = q.pop_many_with_skips(&mut out, Some(&mut skips), 32, Duration::ZERO);
1889        assert_eq!(got, 6);
1890        assert_eq!(skips, vec![(3, 100)]);
1891
1892        // Also test combining a front drop with a later wire skip.
1893        let q2 = SampleQueue::new(3);
1894        let mut b1: Vec<Sample> = vec![sample(0), sample(1), sample(2)];
1895        q2.push_owned_with_skips(&mut b1, &[(2, 50)]);
1896        // Push one more sample -> drops sample 0 at front (1 drop skip before sample 1),
1897        // while keeping the 50-sample wire skip before sample 2.
1898        q2.push(sample(3));
1899        let (s1, sk1) = q2.pop_with_skip(Duration::ZERO).unwrap();
1900        assert_eq!(index(&s1), 1);
1901        assert_eq!(sk1, 1);
1902        let (s2, sk2) = q2.pop_with_skip(Duration::ZERO).unwrap();
1903        assert_eq!(index(&s2), 2);
1904        assert_eq!(sk2, 50);
1905    }
1906}