1use std::collections::BTreeMap;
29use std::fmt;
30use std::time::Duration;
31
32use crate::authoring::{Congestion, Kind, Reliability};
33use crate::contract::{Body, Rate, Resource};
34
35pub const NO_CEILING: u64 = 4_294_967_295;
38
39pub const STREAM_LIVENESS: Duration = Duration::from_secs(3600);
42
43pub const DEFAULT_LEASE: Duration = Duration::from_secs(10);
50
51pub const DEFAULT_KEEP_ALIVE: u32 = 4;
56
57pub const DEFAULT_WAIT_BEFORE_CLOSE: Duration = Duration::from_secs(5);
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub struct Routers {
77 pub lease: Duration,
78 pub keep_alive: u32,
79 pub wait_before_close: Duration,
80}
81
82impl Default for Routers {
83 fn default() -> Self {
86 Routers {
87 lease: DEFAULT_LEASE,
88 keep_alive: DEFAULT_KEEP_ALIVE,
89 wait_before_close: DEFAULT_WAIT_BEFORE_CLOSE,
90 }
91 }
92}
93
94impl Routers {
95 #[must_use]
98 pub fn of(transport: &crate::link::Transport) -> Routers {
99 Routers {
100 lease: Duration::from_millis(transport.lease_ms),
101 keep_alive: u32::try_from(transport.keep_alive).unwrap_or(u32::MAX),
102 wait_before_close: Duration::from_millis(transport.wait_before_close_ms),
103 }
104 }
105
106 #[must_use]
108 pub fn stall_bound(&self) -> Duration {
109 stall_bound(self.wait_before_close, self.lease, self.keep_alive)
110 }
111
112 #[must_use]
114 pub fn presence_tail(&self, timeout: Duration) -> Duration {
115 presence_tail(self.lease, self.wait_before_close, timeout)
116 }
117}
118
119#[must_use]
129pub fn stall_bound(wait_before_close: Duration, lease: Duration, keep_alive: u32) -> Duration {
130 let interval = lease.as_millis().div_ceil(u128::from(keep_alive.max(1)));
131 let interval = Duration::from_millis(u64::try_from(interval).unwrap_or(u64::MAX));
132 wait_before_close.min(lease.saturating_sub(interval))
133}
134
135#[must_use]
150pub fn presence_tail(lease: Duration, wait_before_close: Duration, timeout: Duration) -> Duration {
151 lease.max(wait_before_close).saturating_add(timeout)
152}
153
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157pub struct Delivery {
158 pub reliability: Reliability,
160 pub congestion: Congestion,
162 pub reader_lost: u64,
165 pub stall: ReaderStall,
168 pub miss_detection: MissDetection,
169}
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
177pub struct ReaderStall {
178 pub gap: Duration,
183 pub bound: Duration,
185 pub transport_closed: bool,
190}
191
192impl ReaderStall {
193 #[must_use]
196 pub fn stalled(&self) -> bool {
197 self.transport_closed || self.gap > self.bound
198 }
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
204pub struct MissDetection {
205 pub declared: bool,
208 pub used: bool,
210 pub misses: u64,
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
217pub enum LossReason {
218 ReaderLost,
220 ReaderStalled,
223 MissesDetected,
225 BestEffort,
228 CongestionDrop,
231 ReliableBlock,
234}
235
236impl LossReason {
237 #[must_use]
239 pub fn as_str(self) -> &'static str {
240 match self {
241 Self::ReaderLost => "reader_lost",
242 Self::ReaderStalled => "reader_stalled",
243 Self::MissesDetected => "misses_detected",
244 Self::BestEffort => "best_effort",
245 Self::CongestionDrop => "congestion_drop",
246 Self::ReliableBlock => "reliable_block",
247 }
248 }
249
250 #[must_use]
252 pub fn is_lossless(self) -> bool {
253 self == Self::ReliableBlock
254 }
255}
256
257impl fmt::Display for LossReason {
258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259 f.write_str(self.as_str())
260 }
261}
262
263#[must_use]
276pub fn lossless(d: &Delivery) -> LossReason {
277 let m = d.miss_detection;
278 if d.reader_lost > 0 {
279 LossReason::ReaderLost
280 } else if d.stall.stalled() {
281 LossReason::ReaderStalled
282 } else if m.declared && m.used && m.misses > 0 {
283 LossReason::MissesDetected
284 } else if d.reliability == Reliability::BestEffort {
285 LossReason::BestEffort
286 } else if d.congestion == Congestion::Drop {
287 LossReason::CongestionDrop
288 } else {
289 LossReason::ReliableBlock
290 }
291}
292
293#[must_use]
298pub fn delivery_of(
299 r: &Resource,
300 reader_lost: u64,
301 stall: ReaderStall,
302 misses: Option<u64>,
303) -> Option<Delivery> {
304 match &r.body {
305 Body::Data(d) => Some(Delivery {
306 reliability: d.reliability,
307 congestion: d.congestion,
308 reader_lost,
309 stall,
310 miss_detection: MissDetection {
311 declared: d
312 .history
313 .as_ref()
314 .is_some_and(|h| h.miss_detection_ms.is_some()),
315 used: misses.is_some(),
316 misses: misses.unwrap_or(0),
317 },
318 }),
319 Body::Operation(_) => None,
320 }
321}
322
323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325pub enum Bound {
326 Untemplated,
329 NoCeiling,
331 Of(u64),
333}
334
335impl Bound {
336 #[must_use]
338 pub fn token(self) -> String {
339 match self {
340 Self::Untemplated => "untemplated".to_owned(),
341 Self::NoCeiling => "no_ceiling".to_owned(),
342 Self::Of(n) => n.to_string(),
343 }
344 }
345
346 #[must_use]
348 pub fn limit(self) -> Option<u64> {
349 match self {
350 Self::Of(n) => Some(n),
351 _ => None,
352 }
353 }
354}
355
356impl fmt::Display for Bound {
357 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358 match self {
359 Self::Untemplated => f.write_str("no bound (a template without parameters)"),
360 Self::NoCeiling => f.write_str("no ceiling (4294967295)"),
361 Self::Of(n) => write!(f, "{n}"),
362 }
363 }
364}
365
366#[must_use]
378pub fn bound(contract: Option<u64>, stated: impl IntoIterator<Item = Option<u64>>) -> Bound {
379 let Some(c) = contract else {
380 return Bound::Untemplated;
381 };
382 let n = stated
383 .into_iter()
384 .map(|s| match s {
385 Some(n) if (1..=c).contains(&n) => n,
386 _ => c,
387 })
388 .max()
389 .unwrap_or(c);
390 if n == NO_CEILING {
391 Bound::NoCeiling
392 } else {
393 Bound::Of(n)
394 }
395}
396
397#[must_use]
399pub fn bound_of(r: &Resource, stated: impl IntoIterator<Item = Option<u64>>) -> Bound {
400 bound(r.cardinality, stated)
401}
402
403#[must_use]
405pub fn retention_of(r: &Resource) -> Option<Duration> {
406 match &r.body {
407 Body::Data(d) => d.retention_s.map(Duration::from_secs),
408 Body::Operation(_) => None,
409 }
410}
411
412#[must_use]
414pub fn rate_of(r: &Resource) -> Option<Rate> {
415 match &r.body {
416 Body::Data(d) => d.rate,
417 Body::Operation(_) => None,
418 }
419}
420
421impl Rate {
422 #[must_use]
425 pub fn limit(self) -> (u32, Duration) {
426 const HOUR: Duration = Duration::from_secs(3600);
427 match self {
428 Self::Rare => (1, HOUR),
429 Self::Low => (1, Duration::from_secs(60)),
430 Self::Burst(n) => (n, HOUR),
431 }
432 }
433}
434
435#[must_use]
440pub fn liveness(kind: Kind, retention: Option<Duration>) -> Option<Duration> {
441 match kind {
442 Kind::Stream => Some(STREAM_LIVENESS),
443 Kind::Event => retention,
444 Kind::State | Kind::Operation => None,
445 }
446}
447
448#[derive(Debug, Clone, PartialEq, Eq)]
450pub enum Reading {
451 Get { members: u64, complete: bool },
455 Window(Window),
457}
458
459#[derive(Debug, Clone, PartialEq, Eq, Default)]
464pub struct Window {
465 pub heard: BTreeMap<String, Vec<Duration>>,
469 pub listened: Duration,
473 pub lossless: bool,
476 pub present: bool,
480}
481
482#[derive(Debug, Clone, PartialEq, Eq, Default)]
485pub struct Occurrences {
486 pub listened: Duration,
488 pub lossless: bool,
491 pub present: bool,
494 pub members: BTreeMap<String, Vec<Duration>>,
497}
498
499#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
502pub enum Verdict {
503 Exceeds,
506 Within,
508 Unobservable,
510 NotAsked,
512}
513
514impl Verdict {
515 #[must_use]
517 pub fn as_str(self) -> &'static str {
518 match self {
519 Self::Exceeds => "exceeds",
520 Self::Within => "within",
521 Self::Unobservable => "unobservable",
522 Self::NotAsked => "not_asked",
523 }
524 }
525}
526
527impl fmt::Display for Verdict {
528 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
529 f.write_str(self.as_str())
530 }
531}
532
533#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
535pub enum Reason {
536 OverBound,
538 RateExceeded,
541 Complete,
546 RateKept,
549 Empty,
552 Incomplete,
554 Lossy,
558 WindowTooShort,
561 OwnerAbsent,
565 ReadingKind,
568 NoCeiling,
570 Untemplated,
572 Kind,
574 NoRate,
576}
577
578impl Reason {
579 #[must_use]
581 pub fn as_str(self) -> &'static str {
582 match self {
583 Self::OverBound => "over_bound",
584 Self::RateExceeded => "rate_exceeded",
585 Self::Complete => "complete",
586 Self::RateKept => "rate_kept",
587 Self::Empty => "empty",
588 Self::Incomplete => "incomplete",
589 Self::Lossy => "lossy",
590 Self::WindowTooShort => "window_too_short",
591 Self::OwnerAbsent => "owner_absent",
592 Self::ReadingKind => "reading_kind",
593 Self::NoCeiling => "no_ceiling",
594 Self::Untemplated => "untemplated",
595 Self::Kind => "kind",
596 Self::NoRate => "no_rate",
597 }
598 }
599}
600
601impl fmt::Display for Reason {
602 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
603 f.write_str(self.as_str())
604 }
605}
606
607#[derive(Debug, Clone, Copy, PartialEq, Eq)]
609pub struct Judged {
610 pub verdict: Verdict,
611 pub reason: Reason,
612 pub counted: u64,
616}
617
618impl Judged {
619 fn new(verdict: Verdict, reason: Reason, counted: u64) -> Self {
620 Self {
621 verdict,
622 reason,
623 counted,
624 }
625 }
626}
627
628#[must_use]
632pub fn most_within(heard: &BTreeMap<String, Vec<Duration>>, period: Option<Duration>) -> u64 {
633 let Some(period) = period else {
634 return heard.values().filter(|v| !v.is_empty()).count() as u64;
635 };
636 let mut at: Vec<(Duration, &str)> = heard
637 .iter()
638 .flat_map(|(m, ts)| ts.iter().map(move |t| (*t, m.as_str())))
639 .collect();
640 at.sort();
641 let mut inside: BTreeMap<&str, usize> = BTreeMap::new();
642 let (mut best, mut end) = (0usize, 0usize);
643 for start in 0..at.len() {
644 while end < at.len() && at[end].0 < at[start].0 + period {
645 *inside.entry(at[end].1).or_default() += 1;
646 end += 1;
647 }
648 best = best.max(inside.len());
649 let m = at[start].1;
650 if let Some(n) = inside.get_mut(m) {
651 *n -= 1;
652 if *n == 0 {
653 inside.remove(m);
654 }
655 }
656 }
657 best as u64
658}
659
660#[must_use]
671pub fn population(
672 kind: Kind,
673 bound: Bound,
674 retention: Option<Duration>,
675 reading: &Reading,
676) -> Judged {
677 use Verdict::{Exceeds, NotAsked, Unobservable, Within};
678 if kind == Kind::Operation {
679 return Judged::new(NotAsked, Reason::Kind, 0);
680 }
681 let n = match bound {
682 Bound::Untemplated => return Judged::new(NotAsked, Reason::Untemplated, 0),
683 Bound::NoCeiling => return Judged::new(NotAsked, Reason::NoCeiling, 0),
684 Bound::Of(n) => n,
685 };
686 let span = liveness(kind, retention);
687 let (counted, short_of) = match (kind, reading) {
688 (Kind::State, Reading::Get { members, complete }) => {
689 (*members, (!complete).then_some(Reason::Incomplete))
690 }
691 (Kind::Stream | Kind::Event, Reading::Window(w)) => {
692 let short = span.is_none_or(|span| w.listened < span);
693 let why = if !w.lossless {
694 Some(Reason::Lossy)
695 } else if short {
696 Some(Reason::WindowTooShort)
697 } else if !w.present {
698 Some(Reason::OwnerAbsent)
699 } else {
700 None
701 };
702 (most_within(&w.heard, span), why)
703 }
704 _ => return Judged::new(Unobservable, Reason::ReadingKind, 0),
705 };
706 if counted > n {
707 return Judged::new(Exceeds, Reason::OverBound, counted);
708 }
709 if let Some(why) = short_of {
710 return Judged::new(Unobservable, why, counted);
711 }
712 if counted == 0 {
713 return Judged::new(Unobservable, Reason::Empty, 0);
714 }
715 Judged::new(Within, Reason::Complete, counted)
716}
717
718#[must_use]
726pub fn rate(rate: Option<Rate>, o: &Occurrences) -> Judged {
727 use Verdict::{Exceeds, NotAsked, Unobservable, Within};
728 let Some(rate) = rate else {
729 return Judged::new(NotAsked, Reason::NoRate, 0);
730 };
731 let (n, period) = rate.limit();
732 let n = n as usize;
733 let mut most = 0usize;
734 for ts in o.members.values() {
735 let mut ts = ts.clone();
736 ts.sort();
737 let mut end = 0usize;
738 for start in 0..ts.len() {
739 while end < ts.len() && ts[end] < ts[start] + period {
740 end += 1;
741 }
742 most = most.max(end - start);
743 }
744 }
745 if most > n {
746 return Judged::new(Exceeds, Reason::RateExceeded, most as u64);
747 }
748 if !o.lossless {
749 return Judged::new(Unobservable, Reason::Lossy, most as u64);
750 }
751 if o.listened < period {
752 return Judged::new(Unobservable, Reason::WindowTooShort, most as u64);
753 }
754 if !o.present {
755 return Judged::new(Unobservable, Reason::OwnerAbsent, most as u64);
756 }
757 if most == 0 {
758 return Judged::new(Unobservable, Reason::Empty, 0);
759 }
760 Judged::new(Within, Reason::RateKept, most as u64)
761}
762
763#[cfg(test)]
764mod tests {
765 use super::*;
766
767 fn s(secs: f64) -> Duration {
768 Duration::from_secs_f64(secs)
769 }
770
771 fn heard(of: &[(&str, &[f64])]) -> BTreeMap<String, Vec<Duration>> {
772 of.iter()
773 .map(|(m, ts)| ((*m).to_owned(), ts.iter().map(|t| s(*t)).collect()))
774 .collect()
775 }
776
777 #[test]
778 fn the_bound_is_the_greatest_valid_one_stated() {
779 assert_eq!(bound(None, []), Bound::Untemplated);
780 assert_eq!(bound(Some(64), []), Bound::Of(64));
781 assert_eq!(bound(Some(64), [Some(32)]), Bound::Of(32));
782 assert_eq!(bound(Some(64), [Some(16), Some(32)]), Bound::Of(32));
783 assert_eq!(bound(Some(64), [Some(32), None]), Bound::Of(64));
784 assert_eq!(bound(Some(64), [Some(128)]), Bound::Of(64), "D007's");
785 assert_eq!(bound(Some(64), [Some(0)]), Bound::Of(64), "D007's");
786 assert_eq!(bound(Some(NO_CEILING), []), Bound::NoCeiling);
787 assert_eq!(bound(Some(NO_CEILING), [Some(500)]), Bound::Of(500));
788 assert_eq!(
789 bound(Some(NO_CEILING), [Some(NO_CEILING)]),
790 Bound::NoCeiling
791 );
792 }
793
794 #[test]
795 fn a_window_counts_the_members_live_at_once() {
796 let h = heard(&[("a", &[0.0]), ("b", &[10.0]), ("c", &[4000.0])]);
797 assert_eq!(most_within(&h, Some(STREAM_LIVENESS)), 2);
798 assert_eq!(most_within(&h, None), 3);
799 let h = heard(&[("a", &[0.0]), ("b", &[3600.0])]);
801 assert_eq!(most_within(&h, Some(STREAM_LIVENESS)), 1);
802 let h = heard(&[("a", &[0.0, 1.0, 2.0]), ("b", &[1.5])]);
804 assert_eq!(most_within(&h, Some(STREAM_LIVENESS)), 2);
805 assert_eq!(most_within(&BTreeMap::new(), Some(STREAM_LIVENESS)), 0);
806 }
807
808 #[test]
809 fn population_poles() {
810 let get = |members, complete| Reading::Get { members, complete };
811 let j = |kind, bound, r: &Reading| {
812 let j = population(kind, bound, Some(s(60.0)), r);
813 (j.verdict, j.reason)
814 };
815 use Reason as R;
816 use Verdict as V;
817 assert_eq!(
818 j(Kind::State, Bound::Of(2), &get(3, false)),
819 (V::Exceeds, R::OverBound)
820 );
821 assert_eq!(
822 j(Kind::State, Bound::Of(2), &get(2, true)),
823 (V::Within, R::Complete)
824 );
825 assert_eq!(
826 j(Kind::State, Bound::Of(2), &get(2, false)),
827 (V::Unobservable, R::Incomplete)
828 );
829 assert_eq!(
830 j(Kind::State, Bound::Of(2), &get(0, true)),
831 (V::Unobservable, R::Empty)
832 );
833 assert_eq!(
834 j(Kind::State, Bound::NoCeiling, &get(9, true)),
835 (V::NotAsked, R::NoCeiling)
836 );
837 assert_eq!(
838 j(Kind::State, Bound::Of(2), &get(0, false)),
839 (V::Unobservable, R::Incomplete)
840 );
841 let w = |listened: f64, lossless, present, of: &[(&str, &[f64])]| {
842 Reading::Window(Window {
843 heard: heard(of),
844 listened: s(listened),
845 lossless,
846 present,
847 })
848 };
849 let two: &[(&str, &[f64])] = &[("a", &[0.0]), ("b", &[1.0])];
850 assert_eq!(
852 j(Kind::Stream, Bound::Of(1), &w(5.0, false, false, two)),
853 (V::Exceeds, R::OverBound)
854 );
855 assert_eq!(
857 j(Kind::Stream, Bound::Of(2), &w(3600.0, true, true, two)),
858 (V::Within, R::Complete)
859 );
860 assert_eq!(
861 j(Kind::Stream, Bound::Of(2), &w(3599.0, true, true, two)),
862 (V::Unobservable, R::WindowTooShort)
863 );
864 assert_eq!(
865 j(Kind::Stream, Bound::Of(2), &w(3600.0, false, true, two)),
866 (V::Unobservable, R::Lossy)
867 );
868 assert_eq!(
869 j(Kind::Stream, Bound::Of(2), &w(3600.0, true, false, two)),
870 (V::Unobservable, R::OwnerAbsent)
871 );
872 assert_eq!(
873 j(Kind::Stream, Bound::Of(2), &w(3600.0, true, true, &[])),
874 (V::Unobservable, R::Empty)
875 );
876 assert_eq!(
877 j(Kind::State, Bound::Of(2), &w(3600.0, true, true, two)),
878 (V::Unobservable, R::ReadingKind)
879 );
880 assert_eq!(
881 j(Kind::Operation, Bound::Of(2), &w(3600.0, true, true, two)),
882 (V::NotAsked, R::Kind)
883 );
884 let apart: &[(&str, &[f64])] = &[("a", &[0.0]), ("b", &[61.0])];
886 assert_eq!(
887 j(Kind::Event, Bound::Of(1), &w(120.0, true, true, apart)),
888 (V::Within, R::Complete)
889 );
890 assert_eq!(
891 j(Kind::Event, Bound::Of(1), &w(59.0, true, true, apart)),
892 (V::Unobservable, R::WindowTooShort)
893 );
894 }
895
896 #[test]
897 fn a_face_policys_transport_is_what_its_routers_run() {
898 let s = Duration::from_secs;
899 let t = crate::link::Transport {
900 lease_ms: 240_000,
901 keep_alive: 4,
902 wait_before_close_ms: 240_000,
903 sequence: crate::link::Sequence::Bit16,
904 batch_bytes: 222,
905 open_timeout_ms: 10_000,
906 accept_timeout_ms: 10_000,
907 interests_timeout_ms: 10_000,
908 };
909 let rf = Routers::of(&t);
910 assert_eq!(rf.wait_before_close, s(240));
911 assert_eq!(
912 rf.presence_tail(s(15)),
913 s(255),
914 "RF: 240 s and the reply timeout"
915 );
916 assert_eq!(
917 rf.stall_bound(),
918 s(180),
919 "the lease less one 60-s keep-alive"
920 );
921 let sbd = Routers::of(&crate::link::Transport {
922 lease_ms: 3_600_000,
923 keep_alive: 2,
924 wait_before_close_ms: 3_600_000,
925 ..t
926 });
927 assert_eq!(sbd.stall_bound(), s(1800), "SBD's two keep-alives");
928 assert_eq!(
929 Routers::default().presence_tail(s(1)),
930 presence_tail(DEFAULT_LEASE, DEFAULT_WAIT_BEFORE_CLOSE, s(1)),
931 "given no policy, zenoh 1.10.1's"
932 );
933 }
934
935 #[test]
936 fn the_presence_tail_is_the_longer_of_the_lease_and_wait_before_close() {
937 let s = Duration::from_secs;
938 assert_eq!(
939 presence_tail(DEFAULT_LEASE, DEFAULT_WAIT_BEFORE_CLOSE, s(1)),
940 s(11),
941 "zenoh 1.10.1's defaults: the 10 s lease, then the timeout"
942 );
943 assert_eq!(
944 presence_tail(s(1), DEFAULT_WAIT_BEFORE_CLOSE, s(1)),
945 s(6),
946 "wait_before_close above the lease is the longer one: budget.md §1's 1 s lease"
947 );
948 assert_eq!(
949 presence_tail(s(1), s(10), s(1)),
950 s(11),
951 "zm-1.10.2-r1's 10 s wait_before_close beside a 1 s lease (#1011)"
952 );
953 assert_eq!(presence_tail(s(5), s(5), s(2)), s(7), "equal: either");
954 assert_eq!(
955 presence_tail(s(3), Duration::ZERO, Duration::ZERO),
956 s(3),
957 "no wait and no timeout: the lease alone"
958 );
959 }
960
961 #[test]
962 fn the_stall_bound_is_the_lesser_of_the_queue_and_the_lease() {
963 let s = Duration::from_secs;
964 assert_eq!(
965 stall_bound(DEFAULT_WAIT_BEFORE_CLOSE, DEFAULT_LEASE, DEFAULT_KEEP_ALIVE),
966 s(5),
967 "zenoh 1.10.1's defaults: 5 s, against 7.5 s for the lease"
968 );
969 assert_eq!(
970 stall_bound(s(10), DEFAULT_LEASE, DEFAULT_KEEP_ALIVE),
971 Duration::from_millis(7500),
972 "zm-1.10.2-r1's defaults: the lease's 7.5 s, against 10 s for the queue (#1011)"
973 );
974 assert_eq!(
975 stall_bound(DEFAULT_WAIT_BEFORE_CLOSE, s(1), DEFAULT_KEEP_ALIVE),
976 Duration::from_millis(750),
977 "a 1 s lease: its last keep-alive may be a quarter old"
978 );
979 assert_eq!(stall_bound(s(20), s(30), 3), s(20));
980 assert_eq!(
981 stall_bound(s(20), s(10), 0),
982 Duration::ZERO,
983 "keep_alive 0 as 1"
984 );
985 }
986
987 #[test]
988 fn lossless_rests_on_the_reader_and_the_qos() {
989 use LossReason as L;
990 let d = |reliability, congestion, reader_lost, declared, used, misses| Delivery {
991 reliability,
992 congestion,
993 reader_lost,
994 stall: ReaderStall {
995 gap: Duration::from_millis(50),
996 bound: DEFAULT_WAIT_BEFORE_CLOSE,
997 transport_closed: false,
998 },
999 miss_detection: MissDetection {
1000 declared,
1001 used,
1002 misses,
1003 },
1004 };
1005 let (re, be) = (Reliability::Reliable, Reliability::BestEffort);
1006 let (block, drop) = (Congestion::Block, Congestion::Drop);
1007 assert_eq!(
1008 lossless(&d(re, block, 0, false, false, 0)),
1009 L::ReliableBlock
1010 );
1011 assert!(L::ReliableBlock.is_lossless());
1012 assert_eq!(lossless(&d(re, block, 1, false, false, 0)), L::ReaderLost);
1013 assert_eq!(lossless(&d(be, drop, 0, false, false, 0)), L::BestEffort);
1014 assert_eq!(lossless(&d(be, block, 0, false, false, 0)), L::BestEffort);
1015 assert_eq!(
1016 lossless(&d(re, drop, 0, false, false, 0)),
1017 L::CongestionDrop
1018 );
1019 assert_eq!(lossless(&d(re, block, 0, true, true, 1)), L::MissesDetected);
1021 assert_eq!(lossless(&d(be, drop, 0, true, true, 0)), L::BestEffort);
1022 assert_eq!(lossless(&d(re, block, 0, false, true, 3)), L::ReliableBlock);
1024 assert_eq!(lossless(&d(re, block, 0, true, false, 3)), L::ReliableBlock);
1025 assert_eq!(lossless(&d(re, block, 2, true, true, 5)), L::ReaderLost);
1027 let stalled = |gap_ms, closed, base: Delivery| Delivery {
1031 stall: ReaderStall {
1032 gap: Duration::from_millis(gap_ms),
1033 bound: DEFAULT_WAIT_BEFORE_CLOSE,
1034 transport_closed: closed,
1035 },
1036 ..base
1037 };
1038 let clean = d(re, block, 0, false, false, 0);
1039 assert_eq!(lossless(&stalled(50, true, clean)), L::ReaderStalled);
1040 assert_eq!(lossless(&stalled(7000, false, clean)), L::ReaderStalled);
1041 assert_eq!(lossless(&stalled(5000, false, clean)), L::ReliableBlock);
1042 assert_eq!(
1043 lossless(&stalled(7000, false, d(re, block, 1, false, false, 0))),
1044 L::ReaderLost
1045 );
1046 assert_eq!(
1047 lossless(&stalled(50, true, d(re, block, 0, true, true, 2))),
1048 L::ReaderStalled
1049 );
1050 assert_eq!(
1051 lossless(&stalled(50, true, d(be, drop, 0, false, false, 0))),
1052 L::ReaderStalled
1053 );
1054 for r in [
1055 L::ReaderLost,
1056 L::ReaderStalled,
1057 L::MissesDetected,
1058 L::BestEffort,
1059 L::CongestionDrop,
1060 ] {
1061 assert!(!r.is_lossless(), "{r}");
1062 }
1063 }
1064
1065 #[test]
1066 fn rate_poles() {
1067 let o = |listened, lossless, of: &[(&str, &[f64])]| Occurrences {
1068 listened: s(listened),
1069 lossless,
1070 present: true,
1071 members: heard(of),
1072 };
1073 let j = |r, o: &Occurrences| {
1074 let j = rate(r, o);
1075 (j.verdict, j.reason)
1076 };
1077 use Reason as R;
1078 use Verdict as V;
1079 let low = Some(Rate::Low);
1080 assert_eq!(
1081 j(low, &o(5.0, true, &[("a", &[0.0, 59.9])])),
1082 (V::Exceeds, R::RateExceeded)
1083 );
1084 assert_eq!(
1085 j(low, &o(120.0, true, &[("a", &[0.0, 60.0])])),
1086 (V::Within, R::RateKept)
1087 );
1088 assert_eq!(
1089 j(low, &o(30.0, true, &[("a", &[0.0])])),
1090 (V::Unobservable, R::WindowTooShort)
1091 );
1092 assert_eq!(
1093 j(low, &o(120.0, false, &[("a", &[0.0])])),
1094 (V::Unobservable, R::Lossy)
1095 );
1096 assert_eq!(j(low, &o(120.0, true, &[])), (V::Unobservable, R::Empty));
1097 assert_eq!(
1099 j(low, &o(120.0, true, &[("a", &[0.0]), ("b", &[1.0])])),
1100 (V::Within, R::RateKept)
1101 );
1102 let burst = Some(Rate::Burst(3));
1103 assert_eq!(
1104 j(
1105 burst,
1106 &o(3600.0, true, &[("a", &[0.0, 1200.0, 2400.0, 3599.0])])
1107 ),
1108 (V::Exceeds, R::RateExceeded)
1109 );
1110 assert_eq!(
1111 j(
1112 burst,
1113 &o(3600.0, true, &[("a", &[0.0, 1200.0, 2400.0, 3600.0])])
1114 ),
1115 (V::Within, R::RateKept)
1116 );
1117 assert_eq!(j(None, &o(120.0, true, &[])), (V::NotAsked, R::NoRate));
1118 let absent = |listened, of: &[(&str, &[f64])]| Occurrences {
1121 present: false,
1122 ..o(listened, true, of)
1123 };
1124 assert_eq!(
1125 j(low, &absent(120.0, &[("a", &[0.0])])),
1126 (V::Unobservable, R::OwnerAbsent)
1127 );
1128 assert_eq!(
1129 j(low, &absent(120.0, &[])),
1130 (V::Unobservable, R::OwnerAbsent)
1131 );
1132 assert_eq!(
1133 j(low, &absent(30.0, &[("a", &[0.0])])),
1134 (V::Unobservable, R::WindowTooShort)
1135 );
1136 assert_eq!(
1137 j(low, &absent(120.0, &[("a", &[0.0, 1.0])])),
1138 (V::Exceeds, R::RateExceeded)
1139 );
1140 }
1141}