1use 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
22const MAX_META_LOG: usize = 4096;
24
25#[derive(Debug)]
32struct Ring {
33 q: VecDeque<PackedSample>,
34 back: u64,
35 deducer: Option<TimestampDeducer>,
39 last_popped_ts: Option<f64>,
41 pending_drop_count: u64,
43 pending_drop_start: Option<f64>,
45 drop_gaps: VecDeque<Gap>,
47 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 fn front_number(&self) -> u64 {
69 self.back.wrapping_sub(self.q.len() as u64)
70 }
71
72 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 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 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 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 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 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 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#[derive(Debug)]
186pub struct SampleQueue {
187 inner: Mutex<Ring>,
188 room: Condvar,
189 capacity: usize,
190 dropped: AtomicU64,
191 closed: Mutex<bool>,
192 woken: std::sync::atomic::AtomicBool,
194}
195
196impl SampleQueue {
197 pub fn new(capacity: usize) -> Self {
202 Self::with_first_number(capacity, 0)
203 }
204
205 pub fn with_first_number(capacity: usize, first: u64) -> Self {
210 Self::build(capacity, first, None)
211 }
212
213 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 pub fn capacity(&self) -> usize {
245 self.capacity
246 }
247
248 pub fn dropped(&self) -> u64 {
253 self.dropped.load(Ordering::SeqCst)
254 }
255
256 pub fn len(&self) -> usize {
258 self.inner.lock().unwrap().len()
259 }
260
261 pub fn is_empty(&self) -> bool {
263 self.len() == 0
264 }
265
266 pub fn push(&self, s: Sample) {
271 self.push_packed(PackedSample::from(s));
272 }
273
274 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 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 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 pub fn push_owned(&self, samples: &mut Vec<Sample>) {
339 self.push_owned_with_skips(samples, &[]);
340 }
341
342 pub fn push_owned_packed(&self, samples: &mut Vec<PackedSample>) {
344 self.push_owned_packed_with_skips(samples, &[]);
345 }
346
347 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 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 let skip = batch_len.saturating_sub(self.capacity);
381 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 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 pub(crate) fn clear_skips(&self) {
431 self.inner.lock().unwrap().skips.clear();
432 }
433
434 pub fn pop(&self, timeout: Duration) -> Option<Sample> {
439 self.pop_packed_with_skip(timeout)
440 .map(|(s, _)| s.to_sample())
441 }
442
443 pub fn pop_packed(&self, timeout: Duration) -> Option<PackedSample> {
445 self.pop_packed_with_skip(timeout).map(|(s, _)| s)
446 }
447
448 #[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 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 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 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 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 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 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 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 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 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 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 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 pub fn close(&self) {
727 *self.closed.lock().unwrap() = true;
728 self.room.notify_all();
729 }
730
731 pub fn is_closed(&self) -> bool {
733 *self.closed.lock().unwrap()
734 }
735
736 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 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 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#[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#[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 deducer: TimestampDeducer,
841 srate: f64,
842 limits: HistoryLimits,
843 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 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 pub fn new() -> Self {
879 Fanout::default()
880 }
881
882 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 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 pub fn metadata_generation(&self) -> u64 {
932 self.meta_gen.load(Ordering::Acquire)
933 }
934
935 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 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 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 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 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 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 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 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 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 pub fn add(&self, capacity: usize) -> Arc<SampleQueue> {
1045 self.add_with_peer(capacity, String::new())
1046 }
1047
1048 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 pub fn add_resumable(&self, capacity: usize) -> (Arc<SampleQueue>, u64) {
1069 self.add_resumable_with_peer(capacity, String::new())
1070 }
1071
1072 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 pub fn next_number(&self) -> u64 {
1093 self.consumers.lock().unwrap().next
1094 }
1095
1096 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 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 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 pub fn count(&self) -> usize {
1136 let set = self.consumers.lock().unwrap();
1137 set.list.len() + set.shm_list.len()
1138 }
1139
1140 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 pub fn push(&self, s: &Sample) {
1175 self.push_packed(PackedSample::from_sample(s));
1176 }
1177
1178 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 let srate = 300.0;
1770 let f = Fanout::with_rate(srate, HistoryLimits::DEFAULT);
1771 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 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 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 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 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 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}