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);
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub struct Routers {
80 pub lease: Duration,
81 pub keep_alive: u32,
82 pub wait_before_close: Duration,
83}
84
85impl Default for Routers {
86 fn default() -> Self {
89 Routers {
90 lease: DEFAULT_LEASE,
91 keep_alive: DEFAULT_KEEP_ALIVE,
92 wait_before_close: DEFAULT_WAIT_BEFORE_CLOSE,
93 }
94 }
95}
96
97impl Routers {
98 #[must_use]
101 pub fn of(transport: &crate::link::Transport) -> Routers {
102 Routers {
103 lease: Duration::from_millis(transport.lease_ms),
104 keep_alive: u32::try_from(transport.keep_alive).unwrap_or(u32::MAX),
105 wait_before_close: Duration::from_millis(transport.wait_before_close_ms),
106 }
107 }
108
109 #[must_use]
114 pub fn of_binding(binding: crate::link::Binding) -> Routers {
115 Routers::of(&binding.defaults())
116 }
117
118 #[must_use]
120 pub fn stall_bound(&self) -> Duration {
121 stall_bound(self.wait_before_close, self.lease, self.keep_alive)
122 }
123
124 #[must_use]
126 pub fn presence_tail(&self, timeout: Duration) -> Duration {
127 presence_tail(self.lease, self.wait_before_close, timeout)
128 }
129}
130
131#[must_use]
141pub fn stall_bound(wait_before_close: Duration, lease: Duration, keep_alive: u32) -> Duration {
142 let interval = lease.as_millis().div_ceil(u128::from(keep_alive.max(1)));
143 let interval = Duration::from_millis(u64::try_from(interval).unwrap_or(u64::MAX));
144 wait_before_close.min(lease.saturating_sub(interval))
145}
146
147#[must_use]
162pub fn presence_tail(lease: Duration, wait_before_close: Duration, timeout: Duration) -> Duration {
163 lease.max(wait_before_close).saturating_add(timeout)
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub struct Delivery {
170 pub reliability: Reliability,
172 pub congestion: Congestion,
174 pub reader_lost: u64,
177 pub stall: ReaderStall,
180 pub miss_detection: MissDetection,
181}
182
183#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
189pub struct ReaderStall {
190 pub gap: Duration,
195 pub bound: Duration,
197 pub transport_closed: bool,
202}
203
204impl ReaderStall {
205 #[must_use]
208 pub fn stalled(&self) -> bool {
209 self.transport_closed || self.gap > self.bound
210 }
211}
212
213#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
216pub struct MissDetection {
217 pub declared: bool,
220 pub used: bool,
222 pub misses: u64,
224}
225
226#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
229pub enum LossReason {
230 ReaderLost,
232 ReaderStalled,
235 MissesDetected,
237 BestEffort,
240 CongestionDrop,
243 ReliableBlock,
246}
247
248impl LossReason {
249 #[must_use]
251 pub fn as_str(self) -> &'static str {
252 match self {
253 Self::ReaderLost => "reader_lost",
254 Self::ReaderStalled => "reader_stalled",
255 Self::MissesDetected => "misses_detected",
256 Self::BestEffort => "best_effort",
257 Self::CongestionDrop => "congestion_drop",
258 Self::ReliableBlock => "reliable_block",
259 }
260 }
261
262 #[must_use]
264 pub fn is_lossless(self) -> bool {
265 self == Self::ReliableBlock
266 }
267}
268
269impl fmt::Display for LossReason {
270 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271 f.write_str(self.as_str())
272 }
273}
274
275#[must_use]
288pub fn lossless(d: &Delivery) -> LossReason {
289 let m = d.miss_detection;
290 if d.reader_lost > 0 {
291 LossReason::ReaderLost
292 } else if d.stall.stalled() {
293 LossReason::ReaderStalled
294 } else if m.declared && m.used && m.misses > 0 {
295 LossReason::MissesDetected
296 } else if d.reliability == Reliability::BestEffort {
297 LossReason::BestEffort
298 } else if d.congestion == Congestion::Drop {
299 LossReason::CongestionDrop
300 } else {
301 LossReason::ReliableBlock
302 }
303}
304
305#[must_use]
310pub fn delivery_of(
311 r: &Resource,
312 reader_lost: u64,
313 stall: ReaderStall,
314 misses: Option<u64>,
315) -> Option<Delivery> {
316 match &r.body {
317 Body::Data(d) => Some(Delivery {
318 reliability: d.reliability,
319 congestion: d.congestion,
320 reader_lost,
321 stall,
322 miss_detection: MissDetection {
323 declared: d
324 .history
325 .as_ref()
326 .is_some_and(|h| h.miss_detection_ms.is_some()),
327 used: misses.is_some(),
328 misses: misses.unwrap_or(0),
329 },
330 }),
331 Body::Operation(_) => None,
332 }
333}
334
335#[derive(Debug, Clone, Copy, PartialEq, Eq)]
337pub enum Bound {
338 Untemplated,
341 NoCeiling,
343 Of(u64),
345}
346
347impl Bound {
348 #[must_use]
350 pub fn token(self) -> String {
351 match self {
352 Self::Untemplated => "untemplated".to_owned(),
353 Self::NoCeiling => "no_ceiling".to_owned(),
354 Self::Of(n) => n.to_string(),
355 }
356 }
357
358 #[must_use]
360 pub fn limit(self) -> Option<u64> {
361 match self {
362 Self::Of(n) => Some(n),
363 _ => None,
364 }
365 }
366}
367
368impl fmt::Display for Bound {
369 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370 match self {
371 Self::Untemplated => f.write_str("no bound (a template without parameters)"),
372 Self::NoCeiling => f.write_str("no ceiling (4294967295)"),
373 Self::Of(n) => write!(f, "{n}"),
374 }
375 }
376}
377
378#[must_use]
390pub fn bound(contract: Option<u64>, stated: impl IntoIterator<Item = Option<u64>>) -> Bound {
391 let Some(c) = contract else {
392 return Bound::Untemplated;
393 };
394 let n = stated
395 .into_iter()
396 .map(|s| match s {
397 Some(n) if (1..=c).contains(&n) => n,
398 _ => c,
399 })
400 .max()
401 .unwrap_or(c);
402 if n == NO_CEILING {
403 Bound::NoCeiling
404 } else {
405 Bound::Of(n)
406 }
407}
408
409#[must_use]
411pub fn bound_of(r: &Resource, stated: impl IntoIterator<Item = Option<u64>>) -> Bound {
412 bound(r.cardinality, stated)
413}
414
415#[must_use]
417pub fn retention_of(r: &Resource) -> Option<Duration> {
418 match &r.body {
419 Body::Data(d) => d.retention_s.map(Duration::from_secs),
420 Body::Operation(_) => None,
421 }
422}
423
424#[must_use]
426pub fn rate_of(r: &Resource) -> Option<Rate> {
427 match &r.body {
428 Body::Data(d) => d.rate,
429 Body::Operation(_) => None,
430 }
431}
432
433impl Rate {
434 #[must_use]
437 pub fn limit(self) -> (u32, Duration) {
438 const HOUR: Duration = Duration::from_secs(3600);
439 match self {
440 Self::Rare => (1, HOUR),
441 Self::Low => (1, Duration::from_secs(60)),
442 Self::Burst(n) => (n, HOUR),
443 }
444 }
445}
446
447#[must_use]
452pub fn liveness(kind: Kind, retention: Option<Duration>) -> Option<Duration> {
453 match kind {
454 Kind::Stream => Some(STREAM_LIVENESS),
455 Kind::Event => retention,
456 Kind::State | Kind::Operation => None,
457 }
458}
459
460#[derive(Debug, Clone, PartialEq, Eq)]
462pub enum Reading {
463 Get { members: u64, complete: bool },
467 Window(Window),
469}
470
471#[derive(Debug, Clone, PartialEq, Eq, Default)]
476pub struct Window {
477 pub heard: BTreeMap<String, Vec<Duration>>,
481 pub listened: Duration,
485 pub lossless: bool,
488 pub present: bool,
492}
493
494#[derive(Debug, Clone, PartialEq, Eq, Default)]
497pub struct Occurrences {
498 pub listened: Duration,
500 pub lossless: bool,
503 pub present: bool,
506 pub members: BTreeMap<String, Vec<Duration>>,
509}
510
511#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
514pub enum Verdict {
515 Exceeds,
518 Within,
520 Unobservable,
522 NotAsked,
524}
525
526impl Verdict {
527 #[must_use]
529 pub fn as_str(self) -> &'static str {
530 match self {
531 Self::Exceeds => "exceeds",
532 Self::Within => "within",
533 Self::Unobservable => "unobservable",
534 Self::NotAsked => "not_asked",
535 }
536 }
537}
538
539impl fmt::Display for Verdict {
540 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
541 f.write_str(self.as_str())
542 }
543}
544
545#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
547pub enum Reason {
548 OverBound,
550 RateExceeded,
553 Complete,
558 RateKept,
561 Empty,
564 Incomplete,
566 Lossy,
570 WindowTooShort,
573 OwnerAbsent,
577 ReadingKind,
580 NoCeiling,
582 Untemplated,
584 Kind,
586 NoRate,
588}
589
590impl Reason {
591 #[must_use]
593 pub fn as_str(self) -> &'static str {
594 match self {
595 Self::OverBound => "over_bound",
596 Self::RateExceeded => "rate_exceeded",
597 Self::Complete => "complete",
598 Self::RateKept => "rate_kept",
599 Self::Empty => "empty",
600 Self::Incomplete => "incomplete",
601 Self::Lossy => "lossy",
602 Self::WindowTooShort => "window_too_short",
603 Self::OwnerAbsent => "owner_absent",
604 Self::ReadingKind => "reading_kind",
605 Self::NoCeiling => "no_ceiling",
606 Self::Untemplated => "untemplated",
607 Self::Kind => "kind",
608 Self::NoRate => "no_rate",
609 }
610 }
611}
612
613impl fmt::Display for Reason {
614 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
615 f.write_str(self.as_str())
616 }
617}
618
619#[derive(Debug, Clone, Copy, PartialEq, Eq)]
621pub struct Judged {
622 pub verdict: Verdict,
623 pub reason: Reason,
624 pub counted: u64,
628}
629
630impl Judged {
631 fn new(verdict: Verdict, reason: Reason, counted: u64) -> Self {
632 Self {
633 verdict,
634 reason,
635 counted,
636 }
637 }
638}
639
640#[must_use]
644pub fn most_within(heard: &BTreeMap<String, Vec<Duration>>, period: Option<Duration>) -> u64 {
645 let Some(period) = period else {
646 return heard.values().filter(|v| !v.is_empty()).count() as u64;
647 };
648 let mut at: Vec<(Duration, &str)> = heard
649 .iter()
650 .flat_map(|(m, ts)| ts.iter().map(move |t| (*t, m.as_str())))
651 .collect();
652 at.sort();
653 let mut inside: BTreeMap<&str, usize> = BTreeMap::new();
654 let (mut best, mut end) = (0usize, 0usize);
655 for start in 0..at.len() {
656 while end < at.len() && at[end].0 < at[start].0 + period {
657 *inside.entry(at[end].1).or_default() += 1;
658 end += 1;
659 }
660 best = best.max(inside.len());
661 let m = at[start].1;
662 if let Some(n) = inside.get_mut(m) {
663 *n -= 1;
664 if *n == 0 {
665 inside.remove(m);
666 }
667 }
668 }
669 best as u64
670}
671
672#[must_use]
683pub fn population(
684 kind: Kind,
685 bound: Bound,
686 retention: Option<Duration>,
687 reading: &Reading,
688) -> Judged {
689 use Verdict::{Exceeds, NotAsked, Unobservable, Within};
690 if kind == Kind::Operation {
691 return Judged::new(NotAsked, Reason::Kind, 0);
692 }
693 let n = match bound {
694 Bound::Untemplated => return Judged::new(NotAsked, Reason::Untemplated, 0),
695 Bound::NoCeiling => return Judged::new(NotAsked, Reason::NoCeiling, 0),
696 Bound::Of(n) => n,
697 };
698 let span = liveness(kind, retention);
699 let (counted, short_of) = match (kind, reading) {
700 (Kind::State, Reading::Get { members, complete }) => {
701 (*members, (!complete).then_some(Reason::Incomplete))
702 }
703 (Kind::Stream | Kind::Event, Reading::Window(w)) => {
704 let short = span.is_none_or(|span| w.listened < span);
705 let why = if !w.lossless {
706 Some(Reason::Lossy)
707 } else if short {
708 Some(Reason::WindowTooShort)
709 } else if !w.present {
710 Some(Reason::OwnerAbsent)
711 } else {
712 None
713 };
714 (most_within(&w.heard, span), why)
715 }
716 _ => return Judged::new(Unobservable, Reason::ReadingKind, 0),
717 };
718 if counted > n {
719 return Judged::new(Exceeds, Reason::OverBound, counted);
720 }
721 if let Some(why) = short_of {
722 return Judged::new(Unobservable, why, counted);
723 }
724 if counted == 0 {
725 return Judged::new(Unobservable, Reason::Empty, 0);
726 }
727 Judged::new(Within, Reason::Complete, counted)
728}
729
730#[must_use]
738pub fn rate(rate: Option<Rate>, o: &Occurrences) -> Judged {
739 use Verdict::{Exceeds, NotAsked, Unobservable, Within};
740 let Some(rate) = rate else {
741 return Judged::new(NotAsked, Reason::NoRate, 0);
742 };
743 let (n, period) = rate.limit();
744 let n = n as usize;
745 let mut most = 0usize;
746 for ts in o.members.values() {
747 let mut ts = ts.clone();
748 ts.sort();
749 let mut end = 0usize;
750 for start in 0..ts.len() {
751 while end < ts.len() && ts[end] < ts[start] + period {
752 end += 1;
753 }
754 most = most.max(end - start);
755 }
756 }
757 if most > n {
758 return Judged::new(Exceeds, Reason::RateExceeded, most as u64);
759 }
760 if !o.lossless {
761 return Judged::new(Unobservable, Reason::Lossy, most as u64);
762 }
763 if o.listened < period {
764 return Judged::new(Unobservable, Reason::WindowTooShort, most as u64);
765 }
766 if !o.present {
767 return Judged::new(Unobservable, Reason::OwnerAbsent, most as u64);
768 }
769 if most == 0 {
770 return Judged::new(Unobservable, Reason::Empty, 0);
771 }
772 Judged::new(Within, Reason::RateKept, most as u64)
773}
774
775#[cfg(test)]
776mod tests {
777 use super::*;
778
779 fn s(secs: f64) -> Duration {
780 Duration::from_secs_f64(secs)
781 }
782
783 fn heard(of: &[(&str, &[f64])]) -> BTreeMap<String, Vec<Duration>> {
784 of.iter()
785 .map(|(m, ts)| ((*m).to_owned(), ts.iter().map(|t| s(*t)).collect()))
786 .collect()
787 }
788
789 #[test]
790 fn the_bound_is_the_greatest_valid_one_stated() {
791 assert_eq!(bound(None, []), Bound::Untemplated);
792 assert_eq!(bound(Some(64), []), Bound::Of(64));
793 assert_eq!(bound(Some(64), [Some(32)]), Bound::Of(32));
794 assert_eq!(bound(Some(64), [Some(16), Some(32)]), Bound::Of(32));
795 assert_eq!(bound(Some(64), [Some(32), None]), Bound::Of(64));
796 assert_eq!(bound(Some(64), [Some(128)]), Bound::Of(64), "D007's");
797 assert_eq!(bound(Some(64), [Some(0)]), Bound::Of(64), "D007's");
798 assert_eq!(bound(Some(NO_CEILING), []), Bound::NoCeiling);
799 assert_eq!(bound(Some(NO_CEILING), [Some(500)]), Bound::Of(500));
800 assert_eq!(
801 bound(Some(NO_CEILING), [Some(NO_CEILING)]),
802 Bound::NoCeiling
803 );
804 }
805
806 #[test]
807 fn a_window_counts_the_members_live_at_once() {
808 let h = heard(&[("a", &[0.0]), ("b", &[10.0]), ("c", &[4000.0])]);
809 assert_eq!(most_within(&h, Some(STREAM_LIVENESS)), 2);
810 assert_eq!(most_within(&h, None), 3);
811 let h = heard(&[("a", &[0.0]), ("b", &[3600.0])]);
813 assert_eq!(most_within(&h, Some(STREAM_LIVENESS)), 1);
814 let h = heard(&[("a", &[0.0, 1.0, 2.0]), ("b", &[1.5])]);
816 assert_eq!(most_within(&h, Some(STREAM_LIVENESS)), 2);
817 assert_eq!(most_within(&BTreeMap::new(), Some(STREAM_LIVENESS)), 0);
818 }
819
820 #[test]
821 fn population_poles() {
822 let get = |members, complete| Reading::Get { members, complete };
823 let j = |kind, bound, r: &Reading| {
824 let j = population(kind, bound, Some(s(60.0)), r);
825 (j.verdict, j.reason)
826 };
827 use Reason as R;
828 use Verdict as V;
829 assert_eq!(
830 j(Kind::State, Bound::Of(2), &get(3, false)),
831 (V::Exceeds, R::OverBound)
832 );
833 assert_eq!(
834 j(Kind::State, Bound::Of(2), &get(2, true)),
835 (V::Within, R::Complete)
836 );
837 assert_eq!(
838 j(Kind::State, Bound::Of(2), &get(2, false)),
839 (V::Unobservable, R::Incomplete)
840 );
841 assert_eq!(
842 j(Kind::State, Bound::Of(2), &get(0, true)),
843 (V::Unobservable, R::Empty)
844 );
845 assert_eq!(
846 j(Kind::State, Bound::NoCeiling, &get(9, true)),
847 (V::NotAsked, R::NoCeiling)
848 );
849 assert_eq!(
850 j(Kind::State, Bound::Of(2), &get(0, false)),
851 (V::Unobservable, R::Incomplete)
852 );
853 let w = |listened: f64, lossless, present, of: &[(&str, &[f64])]| {
854 Reading::Window(Window {
855 heard: heard(of),
856 listened: s(listened),
857 lossless,
858 present,
859 })
860 };
861 let two: &[(&str, &[f64])] = &[("a", &[0.0]), ("b", &[1.0])];
862 assert_eq!(
864 j(Kind::Stream, Bound::Of(1), &w(5.0, false, false, two)),
865 (V::Exceeds, R::OverBound)
866 );
867 assert_eq!(
869 j(Kind::Stream, Bound::Of(2), &w(3600.0, true, true, two)),
870 (V::Within, R::Complete)
871 );
872 assert_eq!(
873 j(Kind::Stream, Bound::Of(2), &w(3599.0, true, true, two)),
874 (V::Unobservable, R::WindowTooShort)
875 );
876 assert_eq!(
877 j(Kind::Stream, Bound::Of(2), &w(3600.0, false, true, two)),
878 (V::Unobservable, R::Lossy)
879 );
880 assert_eq!(
881 j(Kind::Stream, Bound::Of(2), &w(3600.0, true, false, two)),
882 (V::Unobservable, R::OwnerAbsent)
883 );
884 assert_eq!(
885 j(Kind::Stream, Bound::Of(2), &w(3600.0, true, true, &[])),
886 (V::Unobservable, R::Empty)
887 );
888 assert_eq!(
889 j(Kind::State, Bound::Of(2), &w(3600.0, true, true, two)),
890 (V::Unobservable, R::ReadingKind)
891 );
892 assert_eq!(
893 j(Kind::Operation, Bound::Of(2), &w(3600.0, true, true, two)),
894 (V::NotAsked, R::Kind)
895 );
896 let apart: &[(&str, &[f64])] = &[("a", &[0.0]), ("b", &[61.0])];
898 assert_eq!(
899 j(Kind::Event, Bound::Of(1), &w(120.0, true, true, apart)),
900 (V::Within, R::Complete)
901 );
902 assert_eq!(
903 j(Kind::Event, Bound::Of(1), &w(59.0, true, true, apart)),
904 (V::Unobservable, R::WindowTooShort)
905 );
906 }
907
908 #[test]
909 fn a_face_policys_transport_is_what_its_routers_run() {
910 let s = Duration::from_secs;
911 let t = crate::link::Transport {
912 lease_ms: 240_000,
913 keep_alive: 4,
914 wait_before_close_ms: 240_000,
915 sequence: crate::link::Sequence::Bit16,
916 batch_bytes: 222,
917 open_timeout_ms: 10_000,
918 accept_timeout_ms: 10_000,
919 interests_timeout_ms: 10_000,
920 };
921 let rf = Routers::of(&t);
922 assert_eq!(rf.wait_before_close, s(240));
923 assert_eq!(
924 rf.presence_tail(s(15)),
925 s(255),
926 "RF: 240 s and the reply timeout"
927 );
928 assert_eq!(
929 rf.stall_bound(),
930 s(180),
931 "the lease less one 60-s keep-alive"
932 );
933 let sbd = Routers::of(&crate::link::Transport {
934 lease_ms: 3_600_000,
935 keep_alive: 2,
936 wait_before_close_ms: 3_600_000,
937 ..t
938 });
939 assert_eq!(sbd.stall_bound(), s(1800), "SBD's two keep-alives");
940 assert_eq!(
941 Routers::default().presence_tail(s(1)),
942 presence_tail(DEFAULT_LEASE, DEFAULT_WAIT_BEFORE_CLOSE, s(1)),
943 "given no policy, zenoh 1.10.1's"
944 );
945 }
946
947 #[test]
954 fn a_bindings_defaults_are_what_its_routers_run() {
955 use crate::link::Binding;
956 let s = Duration::from_secs;
957 assert_eq!(
958 Routers::of_binding(Binding::Zenoh1_10_1),
959 Routers::default()
960 );
961 let zm = Routers::of_binding(Binding::Zm1_10_2R1);
962 assert_eq!(
963 (zm.lease, zm.keep_alive, zm.wait_before_close),
964 (s(10), 4, s(10))
965 );
966 assert_eq!(
967 zm.stall_bound(),
968 Duration::from_millis(7_500),
969 "the lease less a keep-alive decides, wait_before_close being 10 s"
970 );
971 let short = |r: Routers| Routers { lease: s(1), ..r };
972 assert_eq!(short(zm).presence_tail(s(1)), s(11));
973 assert_eq!(short(Routers::default()).presence_tail(s(1)), s(6));
974 }
975
976 #[test]
977 fn the_presence_tail_is_the_longer_of_the_lease_and_wait_before_close() {
978 let s = Duration::from_secs;
979 assert_eq!(
980 presence_tail(DEFAULT_LEASE, DEFAULT_WAIT_BEFORE_CLOSE, s(1)),
981 s(11),
982 "zenoh 1.10.1's defaults: the 10 s lease, then the timeout"
983 );
984 assert_eq!(
985 presence_tail(s(1), DEFAULT_WAIT_BEFORE_CLOSE, s(1)),
986 s(6),
987 "wait_before_close above the lease is the longer one: budget.md §1's 1 s lease"
988 );
989 assert_eq!(
990 presence_tail(s(1), s(10), s(1)),
991 s(11),
992 "zm-1.10.2-r1's 10 s wait_before_close beside a 1 s lease (#1011)"
993 );
994 assert_eq!(presence_tail(s(5), s(5), s(2)), s(7), "equal: either");
995 assert_eq!(
996 presence_tail(s(3), Duration::ZERO, Duration::ZERO),
997 s(3),
998 "no wait and no timeout: the lease alone"
999 );
1000 }
1001
1002 #[test]
1003 fn the_stall_bound_is_the_lesser_of_the_queue_and_the_lease() {
1004 let s = Duration::from_secs;
1005 assert_eq!(
1006 stall_bound(DEFAULT_WAIT_BEFORE_CLOSE, DEFAULT_LEASE, DEFAULT_KEEP_ALIVE),
1007 s(5),
1008 "zenoh 1.10.1's defaults: 5 s, against 7.5 s for the lease"
1009 );
1010 assert_eq!(
1011 stall_bound(s(10), DEFAULT_LEASE, DEFAULT_KEEP_ALIVE),
1012 Duration::from_millis(7500),
1013 "zm-1.10.2-r1's defaults: the lease's 7.5 s, against 10 s for the queue (#1011)"
1014 );
1015 assert_eq!(
1016 stall_bound(DEFAULT_WAIT_BEFORE_CLOSE, s(1), DEFAULT_KEEP_ALIVE),
1017 Duration::from_millis(750),
1018 "a 1 s lease: its last keep-alive may be a quarter old"
1019 );
1020 assert_eq!(stall_bound(s(20), s(30), 3), s(20));
1021 assert_eq!(
1022 stall_bound(s(20), s(10), 0),
1023 Duration::ZERO,
1024 "keep_alive 0 as 1"
1025 );
1026 }
1027
1028 #[test]
1029 fn lossless_rests_on_the_reader_and_the_qos() {
1030 use LossReason as L;
1031 let d = |reliability, congestion, reader_lost, declared, used, misses| Delivery {
1032 reliability,
1033 congestion,
1034 reader_lost,
1035 stall: ReaderStall {
1036 gap: Duration::from_millis(50),
1037 bound: DEFAULT_WAIT_BEFORE_CLOSE,
1038 transport_closed: false,
1039 },
1040 miss_detection: MissDetection {
1041 declared,
1042 used,
1043 misses,
1044 },
1045 };
1046 let (re, be) = (Reliability::Reliable, Reliability::BestEffort);
1047 let (block, drop) = (Congestion::Block, Congestion::Drop);
1048 assert_eq!(
1049 lossless(&d(re, block, 0, false, false, 0)),
1050 L::ReliableBlock
1051 );
1052 assert!(L::ReliableBlock.is_lossless());
1053 assert_eq!(lossless(&d(re, block, 1, false, false, 0)), L::ReaderLost);
1054 assert_eq!(lossless(&d(be, drop, 0, false, false, 0)), L::BestEffort);
1055 assert_eq!(lossless(&d(be, block, 0, false, false, 0)), L::BestEffort);
1056 assert_eq!(
1057 lossless(&d(re, drop, 0, false, false, 0)),
1058 L::CongestionDrop
1059 );
1060 assert_eq!(lossless(&d(re, block, 0, true, true, 1)), L::MissesDetected);
1062 assert_eq!(lossless(&d(be, drop, 0, true, true, 0)), L::BestEffort);
1063 assert_eq!(lossless(&d(re, block, 0, false, true, 3)), L::ReliableBlock);
1065 assert_eq!(lossless(&d(re, block, 0, true, false, 3)), L::ReliableBlock);
1066 assert_eq!(lossless(&d(re, block, 2, true, true, 5)), L::ReaderLost);
1068 let stalled = |gap_ms, closed, base: Delivery| Delivery {
1072 stall: ReaderStall {
1073 gap: Duration::from_millis(gap_ms),
1074 bound: DEFAULT_WAIT_BEFORE_CLOSE,
1075 transport_closed: closed,
1076 },
1077 ..base
1078 };
1079 let clean = d(re, block, 0, false, false, 0);
1080 assert_eq!(lossless(&stalled(50, true, clean)), L::ReaderStalled);
1081 assert_eq!(lossless(&stalled(7000, false, clean)), L::ReaderStalled);
1082 assert_eq!(lossless(&stalled(5000, false, clean)), L::ReliableBlock);
1083 assert_eq!(
1084 lossless(&stalled(7000, false, d(re, block, 1, false, false, 0))),
1085 L::ReaderLost
1086 );
1087 assert_eq!(
1088 lossless(&stalled(50, true, d(re, block, 0, true, true, 2))),
1089 L::ReaderStalled
1090 );
1091 assert_eq!(
1092 lossless(&stalled(50, true, d(be, drop, 0, false, false, 0))),
1093 L::ReaderStalled
1094 );
1095 for r in [
1096 L::ReaderLost,
1097 L::ReaderStalled,
1098 L::MissesDetected,
1099 L::BestEffort,
1100 L::CongestionDrop,
1101 ] {
1102 assert!(!r.is_lossless(), "{r}");
1103 }
1104 }
1105
1106 #[test]
1107 fn rate_poles() {
1108 let o = |listened, lossless, of: &[(&str, &[f64])]| Occurrences {
1109 listened: s(listened),
1110 lossless,
1111 present: true,
1112 members: heard(of),
1113 };
1114 let j = |r, o: &Occurrences| {
1115 let j = rate(r, o);
1116 (j.verdict, j.reason)
1117 };
1118 use Reason as R;
1119 use Verdict as V;
1120 let low = Some(Rate::Low);
1121 assert_eq!(
1122 j(low, &o(5.0, true, &[("a", &[0.0, 59.9])])),
1123 (V::Exceeds, R::RateExceeded)
1124 );
1125 assert_eq!(
1126 j(low, &o(120.0, true, &[("a", &[0.0, 60.0])])),
1127 (V::Within, R::RateKept)
1128 );
1129 assert_eq!(
1130 j(low, &o(30.0, true, &[("a", &[0.0])])),
1131 (V::Unobservable, R::WindowTooShort)
1132 );
1133 assert_eq!(
1134 j(low, &o(120.0, false, &[("a", &[0.0])])),
1135 (V::Unobservable, R::Lossy)
1136 );
1137 assert_eq!(j(low, &o(120.0, true, &[])), (V::Unobservable, R::Empty));
1138 assert_eq!(
1140 j(low, &o(120.0, true, &[("a", &[0.0]), ("b", &[1.0])])),
1141 (V::Within, R::RateKept)
1142 );
1143 let burst = Some(Rate::Burst(3));
1144 assert_eq!(
1145 j(
1146 burst,
1147 &o(3600.0, true, &[("a", &[0.0, 1200.0, 2400.0, 3599.0])])
1148 ),
1149 (V::Exceeds, R::RateExceeded)
1150 );
1151 assert_eq!(
1152 j(
1153 burst,
1154 &o(3600.0, true, &[("a", &[0.0, 1200.0, 2400.0, 3600.0])])
1155 ),
1156 (V::Within, R::RateKept)
1157 );
1158 assert_eq!(j(None, &o(120.0, true, &[])), (V::NotAsked, R::NoRate));
1159 let absent = |listened, of: &[(&str, &[f64])]| Occurrences {
1162 present: false,
1163 ..o(listened, true, of)
1164 };
1165 assert_eq!(
1166 j(low, &absent(120.0, &[("a", &[0.0])])),
1167 (V::Unobservable, R::OwnerAbsent)
1168 );
1169 assert_eq!(
1170 j(low, &absent(120.0, &[])),
1171 (V::Unobservable, R::OwnerAbsent)
1172 );
1173 assert_eq!(
1174 j(low, &absent(30.0, &[("a", &[0.0])])),
1175 (V::Unobservable, R::WindowTooShort)
1176 );
1177 assert_eq!(
1178 j(low, &absent(120.0, &[("a", &[0.0, 1.0])])),
1179 (V::Exceeds, R::RateExceeded)
1180 );
1181 }
1182}