1use std::collections::{BTreeMap, BTreeSet};
31use std::fmt;
32use std::time::Duration;
33
34use serde_json::Value;
35
36use crate::authoring::Kind;
37use crate::contract::Resource;
38use crate::freshness::{ClockMeasure, StampAge};
39
40pub const PROFILE: &str = "timing.v1";
42
43pub const NAME: &str = "timing";
45
46pub const PERIOD_MS: &str = "timing.period_ms";
48pub const DEADLINE_MS: &str = "timing.deadline_ms";
50pub const LIFESPAN_MS: &str = "timing.lifespan_ms";
52
53pub const VOCABULARY: &[&str] = &["period_ms", "deadline_ms", "lifespan_ms"];
56
57pub const MAX_MS: u64 = (1 << 53) - 1;
60
61pub const FORGET_AFTER: Duration = Duration::from_secs(3600);
65
66pub const BOUND_FLOOR: Duration = Duration::from_millis(1);
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
73pub enum Invalid {
74 PeriodValue,
75 DeadlineValue,
76 LifespanValue,
77}
78
79impl Invalid {
80 #[must_use]
82 pub fn as_str(self) -> &'static str {
83 match self {
84 Self::PeriodValue => "period_value",
85 Self::DeadlineValue => "deadline_value",
86 Self::LifespanValue => "lifespan_value",
87 }
88 }
89
90 #[must_use]
92 pub fn says(self) -> &'static str {
93 match self {
94 Self::PeriodValue => {
95 "timing.period_ms is not a whole number of milliseconds from 1 to 2^53-1"
96 }
97 Self::DeadlineValue => {
98 "timing.deadline_ms is not a whole number of milliseconds from 1 to 2^53-1"
99 }
100 Self::LifespanValue => {
101 "timing.lifespan_ms is not a whole number of milliseconds from 1 to 2^53-1"
102 }
103 }
104 }
105}
106
107impl fmt::Display for Invalid {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 f.write_str(self.says())
110 }
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
115pub struct Declared {
116 pub period: Option<Duration>,
117 pub deadline: Option<Duration>,
118 pub lifespan: Option<Duration>,
119}
120
121impl Declared {
122 #[must_use]
125 pub fn below_period(&self) -> bool {
126 matches!((self.period, self.deadline), (Some(p), Some(d)) if d < p)
127 }
128
129 #[must_use]
132 pub fn judged_deadline(&self) -> Option<Duration> {
133 if self.below_period() {
134 None
135 } else {
136 self.deadline
137 }
138 }
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
144pub enum Declaration {
145 NotThisProfiles,
147 Ignored,
151 Invalid(Vec<Invalid>),
154 Declared(Declared),
156}
157
158impl Declaration {
159 #[must_use]
161 pub fn as_str(&self) -> &'static str {
162 match self {
163 Self::NotThisProfiles => "not_this_profiles",
164 Self::Ignored => "ignored",
165 Self::Invalid(_) => "invalid",
166 Self::Declared(_) => "declared",
167 }
168 }
169
170 #[must_use]
172 pub fn declared(&self) -> Option<&Declared> {
173 match self {
174 Self::Declared(d) => Some(d),
175 _ => None,
176 }
177 }
178}
179
180fn millis(v: &Value) -> Option<u64> {
184 let n = v.as_number()?;
185 if let Some(u) = n.as_u64() {
186 return (1..=MAX_MS).contains(&u).then_some(u);
187 }
188 if n.is_i64() {
189 return None;
190 }
191 let f = n.as_f64()?;
192 let max = MAX_MS as f64;
193 (f.is_finite() && f.fract() == 0.0 && f >= 1.0 && f <= max).then_some(f as u64)
194}
195
196fn any_key(annotations: &BTreeMap<String, Value>) -> bool {
197 [PERIOD_MS, DEADLINE_MS, LIFESPAN_MS]
198 .iter()
199 .any(|k| annotations.contains_key(*k))
200}
201
202#[must_use]
208pub fn declaration(kind: Kind, annotations: &BTreeMap<String, Value>) -> Declaration {
209 if !any_key(annotations) {
210 return Declaration::NotThisProfiles;
211 }
212 if kind != Kind::Stream {
213 return Declaration::Ignored;
214 }
215 let mut why = Vec::new();
216 let mut read = |key: &str, wrong: Invalid| -> Option<Duration> {
217 let v = annotations.get(key)?;
218 let ms = millis(v);
219 if ms.is_none() {
220 why.push(wrong);
221 }
222 ms.map(Duration::from_millis)
223 };
224 let declared = Declared {
225 period: read(PERIOD_MS, Invalid::PeriodValue),
226 deadline: read(DEADLINE_MS, Invalid::DeadlineValue),
227 lifespan: read(LIFESPAN_MS, Invalid::LifespanValue),
228 };
229 if why.is_empty() {
230 Declaration::Declared(declared)
231 } else {
232 Declaration::Invalid(why)
233 }
234}
235
236#[must_use]
238pub fn declaration_of(r: &Resource) -> Declaration {
239 declaration(r.kind, &r.annotations)
240}
241
242#[must_use]
246pub fn requirement_declaration(annotations: &BTreeMap<String, Value>) -> Declaration {
247 if any_key(annotations) {
248 Declaration::Ignored
249 } else {
250 Declaration::NotThisProfiles
251 }
252}
253
254#[must_use]
260pub fn tracker_for<S: Into<String>>(
261 kind: Kind,
262 d: &Declaration,
263 bound: Option<u64>,
264 known: impl IntoIterator<Item = S>,
265) -> Option<Tracker> {
266 if kind != Kind::Stream {
267 return None;
268 }
269 let deadline = d.declared()?.judged_deadline()?;
270 Some(Tracker::new(deadline, bound, known))
271}
272
273#[must_use]
276pub fn detection_bound(deadline: Duration) -> Duration {
277 (deadline / 50).max(BOUND_FLOOR)
278}
279
280#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
285pub struct Mono(Duration);
286
287impl Mono {
288 pub const ZERO: Self = Self(Duration::ZERO);
290
291 #[must_use]
293 pub const fn after(d: Duration) -> Self {
294 Self(d)
295 }
296
297 #[must_use]
299 pub const fn from_nanos(ns: u64) -> Self {
300 Self(Duration::from_nanos(ns))
301 }
302
303 #[must_use]
305 pub const fn since_origin(self) -> Duration {
306 self.0
307 }
308
309 #[must_use]
311 pub fn saturating_add(self, d: Duration) -> Self {
312 Self(self.0.saturating_add(d))
313 }
314
315 #[must_use]
318 pub fn saturating_since(self, earlier: Self) -> Duration {
319 self.0.saturating_sub(earlier.0)
320 }
321}
322
323#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
325pub enum OwnerState {
326 #[default]
329 Unseen,
330 Present,
333 Unconfirmed,
335 Absent,
337}
338
339impl OwnerState {
340 #[must_use]
342 pub fn as_str(self) -> &'static str {
343 match self {
344 Self::Unseen => "unseen",
345 Self::Present => "present",
346 Self::Unconfirmed => "unconfirmed",
347 Self::Absent => "absent",
348 }
349 }
350
351 #[must_use]
353 pub fn parse(s: &str) -> Option<Self> {
354 Some(match s {
355 "unseen" => Self::Unseen,
356 "present" => Self::Present,
357 "unconfirmed" => Self::Unconfirmed,
358 "absent" => Self::Absent,
359 _ => return None,
360 })
361 }
362}
363
364#[derive(Debug, Clone, Copy, PartialEq, Eq)]
366pub enum Event<'a> {
367 Start,
369 Arrival { member: &'a str, expired: bool },
373 Owner(OwnerState),
375 MemberSeen(&'a str),
380 MemberGone(&'a str),
384 Tick,
386}
387
388#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
390pub enum EndReason {
391 Gone,
393 Forgotten,
395}
396
397impl EndReason {
398 #[must_use]
400 pub fn as_str(self) -> &'static str {
401 match self {
402 Self::Gone => "gone",
403 Self::Forgotten => "forgotten",
404 }
405 }
406}
407
408#[derive(Debug, Clone, PartialEq, Eq)]
410pub enum Report {
411 Missed {
416 at: Mono,
417 member: String,
418 due: Mono,
419 by: Mono,
420 owner: OwnerState,
421 },
422 Met { at: Mono, member: String },
424 Ended {
427 at: Mono,
428 member: String,
429 reason: EndReason,
430 },
431 BeyondBound { at: Mono, member: String },
434}
435
436impl Report {
437 #[must_use]
439 pub fn as_str(&self) -> &'static str {
440 match self {
441 Self::Missed { .. } => "missed",
442 Self::Met { .. } => "met",
443 Self::Ended { .. } => "ended",
444 Self::BeyondBound { .. } => "beyond_bound",
445 }
446 }
447
448 #[must_use]
450 pub fn member(&self) -> &str {
451 match self {
452 Self::Missed { member, .. }
453 | Self::Met { member, .. }
454 | Self::Ended { member, .. }
455 | Self::BeyondBound { member, .. } => member,
456 }
457 }
458
459 #[must_use]
461 pub fn at(&self) -> Mono {
462 match self {
463 Self::Missed { at, .. }
464 | Self::Met { at, .. }
465 | Self::Ended { at, .. }
466 | Self::BeyondBound { at, .. } => *at,
467 }
468 }
469}
470
471#[derive(Debug, Clone, Copy, PartialEq, Eq)]
473pub enum MemberState {
474 Idle { after_end: bool },
478 Waiting { since: Mono },
481 Heard { last: Mono },
483 Missed { last: Option<Mono> },
485}
486
487#[derive(Debug, Clone, Copy)]
488struct Held {
489 known: bool,
490 state: MemberState,
491}
492
493#[derive(Debug, Clone)]
499pub struct Tracker {
500 deadline: Duration,
501 bound: Option<u64>,
502 start: Option<Mono>,
503 owner: OwnerState,
504 owner_since: Option<Mono>,
505 held: BTreeMap<String, Held>,
506 epoch: bool,
509 seen: BTreeMap<String, Mono>,
512 beyond: BTreeSet<String>,
514}
515
516impl Tracker {
517 pub fn new<S: Into<String>>(
523 deadline: Duration,
524 bound: Option<u64>,
525 known: impl IntoIterator<Item = S>,
526 ) -> Self {
527 let held = known
528 .into_iter()
529 .map(|m| {
530 (
531 m.into(),
532 Held {
533 known: true,
534 state: MemberState::Idle { after_end: false },
535 },
536 )
537 })
538 .collect();
539 Self {
540 deadline,
541 bound,
542 start: None,
543 owner: OwnerState::Unseen,
544 owner_since: None,
545 held,
546 epoch: false,
547 seen: BTreeMap::new(),
548 beyond: BTreeSet::new(),
549 }
550 }
551
552 #[must_use]
558 pub fn with_epoch(mut self) -> Self {
559 self.epoch = true;
560 self
561 }
562
563 #[must_use]
565 pub fn deadline(&self) -> Duration {
566 self.deadline
567 }
568
569 #[must_use]
571 pub fn owner(&self) -> OwnerState {
572 self.owner
573 }
574
575 pub fn held(&self) -> impl Iterator<Item = &str> {
577 self.held.keys().map(String::as_str)
578 }
579
580 #[must_use]
582 pub fn state(&self, member: &str) -> Option<MemberState> {
583 self.held.get(member).map(|h| h.state)
584 }
585
586 #[must_use]
590 pub fn next_due(&self) -> Option<Mono> {
591 self.held
592 .values()
593 .filter_map(|h| match h.state {
594 MemberState::Heard { last } => Some(last),
595 MemberState::Waiting { since } => Some(since),
596 _ => None,
597 })
598 .min()
599 .map(|t| t.saturating_add(self.deadline))
600 }
601
602 pub fn observe(&mut self, at: Mono, event: Event<'_>) -> Vec<Report> {
606 let mut out = self.evaluate(at);
607 self.apply(at, event, &mut out);
608 out
609 }
610
611 fn evaluate(&mut self, at: Mono) -> Vec<Report> {
612 let (d, bound, owner) = (self.deadline, detection_bound(self.deadline), self.owner);
613 let mut out = Vec::new();
614 let mut forgotten = Vec::new();
615 for (name, h) in &mut self.held {
616 let from = match h.state {
617 MemberState::Heard { last } => Some((last, Some(last))),
618 MemberState::Waiting { since } => Some((since, None)),
619 _ => None,
620 };
621 if let Some((from, last)) = from {
622 let due = from.saturating_add(d);
623 if at > due {
624 h.state = MemberState::Missed { last };
625 out.push(Report::Missed {
626 at,
627 member: name.clone(),
628 due,
629 by: due.saturating_add(bound),
630 owner,
631 });
632 }
633 }
634 if !h.known
635 && let MemberState::Missed { last: Some(last) } = h.state
636 && at.saturating_since(last) >= FORGET_AFTER
637 {
638 forgotten.push(name.clone());
639 out.push(Report::Ended {
640 at,
641 member: name.clone(),
642 reason: EndReason::Forgotten,
643 });
644 }
645 }
646 for name in forgotten {
647 self.held.remove(&name);
648 }
649 out
650 }
651
652 fn wait_known(&mut self, since: Mono) {
653 for h in self.held.values_mut() {
654 if h.known && h.state == (MemberState::Idle { after_end: false }) {
655 h.state = MemberState::Waiting { since };
656 }
657 }
658 }
659
660 fn apply(&mut self, at: Mono, event: Event<'_>, out: &mut Vec<Report>) {
661 match event {
662 Event::Start => {
663 if self.start.is_some() {
664 return;
665 }
666 self.start = Some(at);
667 if self.epoch {
668 for (name, h) in &mut self.held {
669 if let Some(seen) = self.seen.get(name)
670 && h.known
671 && matches!(h.state, MemberState::Idle { .. })
672 {
673 h.state = MemberState::Waiting {
674 since: (*seen).max(at),
675 };
676 }
677 }
678 } else if self.owner == OwnerState::Present {
679 let since = self.owner_since.map_or(at, |s| s.max(at));
680 self.wait_known(since);
681 }
682 }
683 Event::Arrival { member, expired } => {
684 if self.start.is_none() || expired {
685 return;
686 }
687 if let Some(h) = self.held.get_mut(member) {
688 let was_missed = matches!(h.state, MemberState::Missed { .. });
689 h.state = MemberState::Heard { last: at };
690 if was_missed {
691 out.push(Report::Met {
692 at,
693 member: member.to_owned(),
694 });
695 }
696 } else if self
697 .bound
698 .is_some_and(|b| u64::try_from(self.held.len()).unwrap_or(u64::MAX) >= b)
699 {
700 if self.beyond.insert(member.to_owned()) {
702 out.push(Report::BeyondBound {
703 at,
704 member: member.to_owned(),
705 });
706 }
707 } else {
708 self.beyond.remove(member);
709 self.held.insert(
710 member.to_owned(),
711 Held {
712 known: false,
713 state: MemberState::Heard { last: at },
714 },
715 );
716 }
717 }
718 Event::Owner(state) => match (self.owner, state) {
719 (OwnerState::Unseen | OwnerState::Absent, OwnerState::Present) => {
720 self.owner = OwnerState::Present;
721 self.owner_since = Some(at);
722 if let Some(start) = self.start
723 && !self.epoch
724 {
725 self.wait_known(at.max(start));
726 }
727 }
728 (OwnerState::Unconfirmed, OwnerState::Present)
729 | (OwnerState::Present, OwnerState::Unconfirmed) => self.owner = state,
730 (_, OwnerState::Absent) => {
731 self.owner = OwnerState::Absent;
732 self.owner_since = None;
733 if !self.epoch {
734 for h in self.held.values_mut() {
735 if matches!(h.state, MemberState::Waiting { .. }) {
736 h.state = MemberState::Idle { after_end: false };
737 }
738 }
739 }
740 }
741 _ => {}
742 },
743 Event::MemberSeen(member) => {
744 if !self.epoch || self.seen.contains_key(member) {
745 return;
746 }
747 self.seen.insert(member.to_owned(), at);
748 if self.start.is_some()
749 && let Some(h) = self.held.get_mut(member)
750 && h.known
751 && matches!(h.state, MemberState::Idle { .. })
752 {
753 h.state = MemberState::Waiting { since: at };
754 }
755 }
756 Event::MemberGone(member) => {
757 if self.epoch && self.seen.remove(member).is_none() {
760 return;
761 }
762 let Some(h) = self.held.get_mut(member) else {
763 return;
764 };
765 if matches!(
766 h.state,
767 MemberState::Heard { .. } | MemberState::Missed { .. }
768 ) {
769 out.push(Report::Ended {
770 at,
771 member: member.to_owned(),
772 reason: EndReason::Gone,
773 });
774 }
775 if h.known {
776 h.state = MemberState::Idle { after_end: true };
777 } else {
778 self.held.remove(member);
779 }
780 }
781 Event::Tick => {}
782 }
783 }
784}
785
786#[must_use]
791pub fn zid_value(s: &str) -> Option<u128> {
792 let ok = !s.is_empty() && s.len() <= 32 && s.bytes().all(|b| b.is_ascii_hexdigit());
793 if ok {
794 u128::from_str_radix(s, 16).ok()
795 } else {
796 None
797 }
798}
799
800#[derive(Debug, Clone, Copy, PartialEq, Eq)]
802pub struct Stamped {
803 pub age: StampAge,
806 pub id: u128,
808}
809
810#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
812pub enum SampleVerdict {
813 Live,
814 Expired,
815 Unobservable,
816 NotAsked,
817 NotThisProfiles,
818}
819
820impl SampleVerdict {
821 #[must_use]
823 pub fn as_str(self) -> &'static str {
824 match self {
825 Self::Live => "live",
826 Self::Expired => "expired",
827 Self::Unobservable => "unobservable",
828 Self::NotAsked => "not_asked",
829 Self::NotThisProfiles => "not_this_profiles",
830 }
831 }
832
833 #[must_use]
835 pub fn parse(s: &str) -> Option<Self> {
836 Some(match s {
837 "live" => Self::Live,
838 "expired" => Self::Expired,
839 "unobservable" => Self::Unobservable,
840 "not_asked" => Self::NotAsked,
841 "not_this_profiles" => Self::NotThisProfiles,
842 _ => return None,
843 })
844 }
845}
846
847#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
849pub enum Reason {
850 Kind,
852 Invalid,
854 NoDeadline,
856 NoPeriod,
858 NoLifespan,
860 BelowPeriod,
862 AcrossFace,
864 Lost,
866 Missed,
868 OwnerNotPresent,
871 Ended,
873 NotHeard,
875 WindowTooShort,
877 Met,
879 Kept,
881 NotKept,
883 Expired,
885 Live,
887 NoBound,
889 Unstamped,
891 Unattributed,
893 ForeignStamp,
895 ClockDisagrees,
897 NoSample,
899}
900
901impl Reason {
902 #[must_use]
904 pub fn as_str(self) -> &'static str {
905 match self {
906 Self::Kind => "kind",
907 Self::Invalid => "invalid",
908 Self::NoDeadline => "no_deadline",
909 Self::NoPeriod => "no_period",
910 Self::NoLifespan => "no_lifespan",
911 Self::BelowPeriod => "below_period",
912 Self::AcrossFace => "across_face",
913 Self::Lost => "lost",
914 Self::Missed => "missed",
915 Self::OwnerNotPresent => "owner_not_present",
916 Self::Ended => "ended",
917 Self::NotHeard => "not_heard",
918 Self::WindowTooShort => "window_too_short",
919 Self::Met => "met",
920 Self::Kept => "kept",
921 Self::NotKept => "not_kept",
922 Self::Expired => "expired",
923 Self::Live => "live",
924 Self::NoBound => "no_bound",
925 Self::Unstamped => "unstamped",
926 Self::Unattributed => "unattributed",
927 Self::ForeignStamp => "foreign_stamp",
928 Self::ClockDisagrees => "clock_disagrees",
929 Self::NoSample => "no_sample",
930 }
931 }
932
933 #[must_use]
935 pub fn parse(s: &str) -> Option<Self> {
936 [
937 Self::Kind,
938 Self::Invalid,
939 Self::NoDeadline,
940 Self::NoPeriod,
941 Self::NoLifespan,
942 Self::BelowPeriod,
943 Self::AcrossFace,
944 Self::Lost,
945 Self::Missed,
946 Self::OwnerNotPresent,
947 Self::Ended,
948 Self::NotHeard,
949 Self::WindowTooShort,
950 Self::Met,
951 Self::Kept,
952 Self::NotKept,
953 Self::Expired,
954 Self::Live,
955 Self::NoBound,
956 Self::Unstamped,
957 Self::Unattributed,
958 Self::ForeignStamp,
959 Self::ClockDisagrees,
960 Self::NoSample,
961 ]
962 .into_iter()
963 .find(|r| r.as_str() == s)
964 }
965
966 #[must_use]
968 pub fn says(self) -> &'static str {
969 match self {
970 Self::Kind => "only a stream has a period, a deadline or a lifespan",
971 Self::Invalid => "its timing declaration is invalid",
972 Self::NoDeadline => "no timing.deadline_ms",
973 Self::NoPeriod => "no timing.period_ms",
974 Self::NoLifespan => "no timing.lifespan_ms",
975 Self::BelowPeriod => "its deadline is below its period, so it is no deadline",
976 Self::AcrossFace => "read across a constrained face, where presence does not cross",
977 Self::Lost => "this reader lost a delivery, or stalled, in the window",
978 Self::Missed => "nothing arrived within its deadline while its owner was present",
979 Self::OwnerNotPresent => "its owner was not present throughout",
980 Self::Ended => "the member ended in the window",
981 Self::NotHeard => "the member was not heard in the window",
982 Self::WindowTooShort => "the window was too short to tell",
983 Self::Met => "every arrival within its deadline",
984 Self::Kept => "published at its period",
985 Self::NotKept => "fewer samples arrived than its period promises",
986 Self::Expired => "a sample arrived older than its lifespan",
987 Self::Live => "every sample arrived within its lifespan",
988 Self::NoBound => {
989 "the deployment states no bound on its clocks, so nothing is discarded"
990 }
991 Self::Unstamped => "the sample carries no stamp",
992 Self::Unattributed => {
993 "no meta.zid is held for the provider, so a stamp is unattributable"
994 }
995 Self::ForeignStamp => "the stamp is not the owner's: a router's, or another session's",
996 Self::ClockDisagrees => {
997 "the stamp's clock was seen ahead of this reader's by more than the stated bound"
998 }
999 Self::NoSample => "no sample was read",
1000 }
1001 }
1002}
1003
1004impl fmt::Display for Reason {
1005 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1006 f.write_str(self.as_str())
1007 }
1008}
1009
1010#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1012pub struct Sample {
1013 pub verdict: SampleVerdict,
1014 pub reason: Reason,
1015}
1016
1017impl Sample {
1018 const fn new(verdict: SampleVerdict, reason: Reason) -> Self {
1019 Self { verdict, reason }
1020 }
1021
1022 #[must_use]
1024 pub fn discarded(&self) -> bool {
1025 self.verdict == SampleVerdict::Expired
1026 }
1027}
1028
1029#[derive(Debug, Clone)]
1035pub struct LifespanReader {
1036 premise: Result<Duration, Sample>,
1037 epsilon: Option<Duration>,
1038 owners: BTreeSet<u128>,
1039 clocks: BTreeMap<u128, ClockMeasure>,
1040}
1041
1042impl LifespanReader {
1043 pub fn new(
1049 kind: Kind,
1050 d: &Declaration,
1051 epsilon: Option<Duration>,
1052 owners: impl IntoIterator<Item = u128>,
1053 ) -> Self {
1054 let premise = if kind != Kind::Stream {
1055 Err(Sample::new(SampleVerdict::NotThisProfiles, Reason::Kind))
1056 } else {
1057 match d {
1058 Declaration::Invalid(_) => {
1059 Err(Sample::new(SampleVerdict::Unobservable, Reason::Invalid))
1060 }
1061 Declaration::Declared(Declared {
1062 lifespan: Some(l), ..
1063 }) => Ok(*l),
1064 _ => Err(Sample::new(SampleVerdict::NotAsked, Reason::NoLifespan)),
1065 }
1066 };
1067 Self {
1068 premise,
1069 epsilon,
1070 owners: owners.into_iter().collect(),
1071 clocks: BTreeMap::new(),
1072 }
1073 }
1074
1075 pub fn set_owners(&mut self, owners: impl IntoIterator<Item = u128>) {
1077 self.owners = owners.into_iter().collect();
1078 }
1079
1080 pub fn judge(&mut self, stamp: Option<Stamped>) -> Sample {
1084 use Reason as R;
1085 use SampleVerdict as V;
1086 let lifespan = match self.premise {
1087 Ok(l) => l,
1088 Err(s) => return s,
1089 };
1090 let Some(eps) = self.epsilon else {
1091 return Sample::new(V::Unobservable, R::NoBound);
1092 };
1093 let Some(stamp) = stamp else {
1094 return Sample::new(V::Unobservable, R::Unstamped);
1095 };
1096 if self.owners.is_empty() {
1097 return Sample::new(V::Unobservable, R::Unattributed);
1098 }
1099 if !self.owners.contains(&stamp.id) {
1100 return Sample::new(V::Unobservable, R::ForeignStamp);
1101 }
1102 let m = self
1103 .clocks
1104 .entry(stamp.id)
1105 .and_modify(|m| m.record(stamp.age))
1106 .or_insert_with(|| ClockMeasure::new(stamp.age));
1107 let e = eps.as_nanos() as i128;
1108 if m.most_ahead().nanos() < -e {
1109 return Sample::new(V::Unobservable, R::ClockDisagrees);
1110 }
1111 if stamp.age.nanos() - e > lifespan.as_nanos() as i128 {
1112 Sample::new(V::Expired, R::Expired)
1113 } else {
1114 Sample::new(V::Live, R::Live)
1115 }
1116 }
1117}
1118
1119#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1123pub enum PeriodVerdict {
1124 NotHeard,
1126 TooShort,
1128 Kept,
1130 NotKept,
1131}
1132
1133impl PeriodVerdict {
1134 #[must_use]
1136 pub fn as_str(self) -> &'static str {
1137 match self {
1138 Self::NotHeard => "not_heard",
1139 Self::TooShort => "too_short",
1140 Self::Kept => "kept",
1141 Self::NotKept => "not_kept",
1142 }
1143 }
1144
1145 #[must_use]
1147 pub fn parse(s: &str) -> Option<Self> {
1148 Some(match s {
1149 "not_heard" => Self::NotHeard,
1150 "too_short" => Self::TooShort,
1151 "kept" => Self::Kept,
1152 "not_kept" => Self::NotKept,
1153 _ => return None,
1154 })
1155 }
1156}
1157
1158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1161pub struct PeriodReading {
1162 pub verdict: PeriodVerdict,
1163 pub arrivals: u64,
1164 pub span: Option<Duration>,
1165}
1166
1167#[must_use]
1173pub fn period_window(
1174 period: Duration,
1175 from: Mono,
1176 to: Mono,
1177 known: bool,
1178 ended: Option<Mono>,
1179 arrivals: &[Mono],
1180) -> PeriodReading {
1181 let start = if known {
1182 Some(from)
1183 } else {
1184 arrivals.iter().copied().find(|t| (from..=to).contains(t))
1185 };
1186 let Some(start) = start else {
1187 return PeriodReading {
1188 verdict: PeriodVerdict::NotHeard,
1189 arrivals: 0,
1190 span: None,
1191 };
1192 };
1193 let end = ended.unwrap_or(to);
1194 let span = end.saturating_since(start);
1195 let n = arrivals
1196 .iter()
1197 .filter(|t| (start..=end).contains(*t))
1198 .count() as u64;
1199 let (p, s) = (period.as_nanos(), span.as_nanos());
1200 let verdict = if s < 3 * p {
1201 PeriodVerdict::TooShort
1202 } else if (u128::from(n) + 2) * p >= s {
1203 PeriodVerdict::Kept
1204 } else {
1205 PeriodVerdict::NotKept
1206 };
1207 PeriodReading {
1208 verdict,
1209 arrivals: n,
1210 span: Some(span),
1211 }
1212}
1213
1214#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1219pub enum Answer {
1220 Yes,
1221 No,
1222 Unobservable,
1223 NotAsked,
1224 NotThisProfiles,
1225}
1226
1227impl Answer {
1228 #[must_use]
1230 pub fn as_str(self) -> &'static str {
1231 match self {
1232 Self::Yes => "yes",
1233 Self::No => "no",
1234 Self::Unobservable => "unobservable",
1235 Self::NotAsked => "not_asked",
1236 Self::NotThisProfiles => "not_this_profiles",
1237 }
1238 }
1239}
1240
1241impl fmt::Display for Answer {
1242 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1243 f.write_str(self.as_str())
1244 }
1245}
1246
1247#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1249pub struct Judged {
1250 pub answer: Answer,
1251 pub reason: Reason,
1252}
1253
1254impl Judged {
1255 const fn new(answer: Answer, reason: Reason) -> Self {
1256 Self { answer, reason }
1257 }
1258}
1259
1260#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1262pub struct Window {
1263 pub across_face: bool,
1265 pub lost: bool,
1268 pub owner_present: bool,
1270}
1271
1272#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1274pub struct DeadlineAccount {
1275 pub held: Duration,
1279 pub missed_present: u32,
1281 pub missed_not_present: u32,
1283 pub ended: bool,
1285}
1286
1287impl DeadlineAccount {
1288 pub fn count(&mut self, r: &Report) {
1290 if let Report::Missed { owner, .. } = r {
1291 if *owner == OwnerState::Present {
1292 self.missed_present += 1;
1293 } else {
1294 self.missed_not_present += 1;
1295 }
1296 }
1297 if matches!(r, Report::Ended { .. }) {
1298 self.ended = true;
1299 }
1300 }
1301}
1302
1303#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1306pub struct HeldSpan {
1307 longest: Duration,
1309 from: Option<Mono>,
1311 ended: Option<Mono>,
1313}
1314
1315impl HeldSpan {
1316 #[must_use]
1319 pub fn held_to(&self, at: Mono) -> Duration {
1320 self.longest
1321 .max(self.from.map_or(Duration::ZERO, |f| at.saturating_since(f)))
1322 }
1323
1324 #[must_use]
1326 pub fn ended(&self) -> Option<Mono> {
1327 self.ended
1328 }
1329
1330 #[must_use]
1332 pub fn counting(&self) -> bool {
1333 self.from.is_some()
1334 }
1335
1336 fn run(&mut self, at: Mono) {
1337 if self.from.is_none() && self.ended.is_none() {
1338 self.from = Some(at);
1339 }
1340 }
1341
1342 fn stop(&mut self, at: Mono) {
1343 if let Some(f) = self.from.take() {
1344 self.longest = self.longest.max(at.saturating_since(f));
1345 }
1346 }
1347}
1348
1349#[derive(Debug, Clone, Default)]
1372pub struct Holding {
1373 spans: BTreeMap<String, HeldSpan>,
1374 closed: bool,
1375}
1376
1377impl Holding {
1378 #[must_use]
1380 pub fn new() -> Self {
1381 Self::default()
1382 }
1383
1384 pub fn observe(&mut self, tracker: &Tracker, event: Event<'_>, reports: &[Report], at: Mono) {
1395 if self.closed {
1396 return;
1397 }
1398 for r in reports {
1399 if let Report::Ended { member, .. } = r {
1400 let s = self.spans.entry(member.clone()).or_default();
1401 s.stop(at);
1402 s.ended.get_or_insert(at);
1403 }
1404 }
1405 let touched = match event {
1406 Event::Arrival { member, .. }
1407 | Event::MemberSeen(member)
1408 | Event::MemberGone(member) => Some(member),
1409 Event::Start | Event::Owner(_) | Event::Tick => None,
1410 };
1411 match touched {
1412 Some(member) => {
1413 let mut names: Vec<&str> = vec![member];
1414 names.extend(reports.iter().map(Report::member));
1415 names.sort_unstable();
1416 names.dedup();
1417 for name in names {
1418 self.move_one(tracker, name, at);
1419 }
1420 }
1421 None => {
1422 for name in tracker.held() {
1423 self.move_one(tracker, name, at);
1424 }
1425 for (name, s) in &mut self.spans {
1426 if s.counting() && tracker.state(name).is_none() {
1427 s.stop(at);
1428 }
1429 }
1430 }
1431 }
1432 }
1433
1434 fn move_one(&mut self, tracker: &Tracker, name: &str, at: Mono) {
1438 let Some(state) = tracker.state(name) else {
1439 if let Some(s) = self.spans.get_mut(name) {
1440 s.stop(at);
1441 }
1442 return;
1443 };
1444 let counts = matches!(
1445 state,
1446 MemberState::Heard { .. } | MemberState::Missed { .. } | MemberState::Waiting { .. }
1447 );
1448 if !counts && !self.spans.contains_key(name) {
1449 self.spans.insert(name.to_owned(), HeldSpan::default());
1451 return;
1452 }
1453 let s = self.spans.entry(name.to_owned()).or_default();
1454 if counts {
1455 s.run(at);
1456 } else {
1457 s.stop(at);
1458 }
1459 }
1460
1461 pub fn close(&mut self, at: Mono) {
1464 for s in self.spans.values_mut() {
1465 s.stop(at);
1466 }
1467 self.closed = true;
1468 }
1469
1470 pub fn spans(&self) -> impl Iterator<Item = (&str, &HeldSpan)> {
1473 self.spans.iter().map(|(k, s)| (k.as_str(), s))
1474 }
1475
1476 #[must_use]
1478 pub fn span(&self, member: &str) -> Option<&HeldSpan> {
1479 self.spans.get(member)
1480 }
1481}
1482
1483fn premise(kind: Kind, d: &Declaration) -> Result<Declared, Judged> {
1485 if kind != Kind::Stream {
1486 return Err(Judged::new(Answer::NotThisProfiles, Reason::Kind));
1487 }
1488 match d {
1489 Declaration::Invalid(_) => Err(Judged::new(Answer::Unobservable, Reason::Invalid)),
1490 Declaration::Declared(x) => Ok(*x),
1491 Declaration::NotThisProfiles | Declaration::Ignored => Ok(Declared::default()),
1492 }
1493}
1494
1495#[must_use]
1498pub fn deadline_met(kind: Kind, d: &Declaration, w: &Window, a: &DeadlineAccount) -> Judged {
1499 use Answer as A;
1500 use Reason as R;
1501 let x = match premise(kind, d) {
1502 Ok(x) => x,
1503 Err(j) => return j,
1504 };
1505 let Some(deadline) = x.deadline else {
1506 return Judged::new(A::NotAsked, R::NoDeadline);
1507 };
1508 if x.below_period() {
1509 return Judged::new(A::Unobservable, R::BelowPeriod);
1510 }
1511 if w.across_face {
1512 return Judged::new(A::Unobservable, R::AcrossFace);
1513 }
1514 if a.missed_present > 0 {
1515 return if w.lost {
1516 Judged::new(A::Unobservable, R::Lost)
1517 } else {
1518 Judged::new(A::No, R::Missed)
1519 };
1520 }
1521 if a.missed_not_present > 0 {
1522 return Judged::new(A::Unobservable, R::OwnerNotPresent);
1523 }
1524 if a.ended {
1525 return Judged::new(A::NotAsked, R::Ended);
1526 }
1527 if a.held.is_zero() {
1528 return Judged::new(A::NotAsked, R::NotHeard);
1529 }
1530 if a.held <= deadline {
1531 return Judged::new(A::Unobservable, R::WindowTooShort);
1532 }
1533 Judged::new(A::Yes, R::Met)
1534}
1535
1536#[must_use]
1539pub fn period_kept(kind: Kind, d: &Declaration, w: &Window, p: PeriodVerdict) -> Judged {
1540 use Answer as A;
1541 use Reason as R;
1542 let x = match premise(kind, d) {
1543 Ok(x) => x,
1544 Err(j) => return j,
1545 };
1546 if x.period.is_none() {
1547 return Judged::new(A::NotAsked, R::NoPeriod);
1548 }
1549 if w.across_face {
1550 return Judged::new(A::Unobservable, R::AcrossFace);
1551 }
1552 match p {
1553 PeriodVerdict::NotHeard => Judged::new(A::NotAsked, R::NotHeard),
1554 PeriodVerdict::TooShort => Judged::new(A::Unobservable, R::WindowTooShort),
1555 PeriodVerdict::Kept => Judged::new(A::Yes, R::Kept),
1556 PeriodVerdict::NotKept if w.lost => Judged::new(A::Unobservable, R::Lost),
1557 PeriodVerdict::NotKept if !w.owner_present => {
1558 Judged::new(A::Unobservable, R::OwnerNotPresent)
1559 }
1560 PeriodVerdict::NotKept => Judged::new(A::No, R::NotKept),
1561 }
1562}
1563
1564#[must_use]
1567pub fn lifespan_expired(kind: Kind, d: &Declaration, samples: &[Sample]) -> Judged {
1568 use Answer as A;
1569 use Reason as R;
1570 let x = match premise(kind, d) {
1571 Ok(x) => x,
1572 Err(j) => return j,
1573 };
1574 if x.lifespan.is_none() {
1575 return Judged::new(A::NotAsked, R::NoLifespan);
1576 }
1577 if samples.iter().any(|s| s.verdict == SampleVerdict::Expired) {
1578 return Judged::new(A::Yes, R::Expired);
1579 }
1580 if let Some(s) = samples
1581 .iter()
1582 .find(|s| s.verdict == SampleVerdict::Unobservable)
1583 {
1584 return Judged::new(A::Unobservable, s.reason);
1585 }
1586 if samples.iter().any(|s| s.verdict == SampleVerdict::Live) {
1587 return Judged::new(A::No, R::Live);
1588 }
1589 Judged::new(A::Unobservable, R::NoSample)
1590}
1591
1592#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1594pub enum Question {
1595 Deadline,
1597 Period,
1599 Lifespan,
1601}
1602
1603impl Question {
1604 #[must_use]
1606 pub fn as_str(self) -> &'static str {
1607 match self {
1608 Self::Deadline => "deadline",
1609 Self::Period => "period",
1610 Self::Lifespan => "lifespan",
1611 }
1612 }
1613
1614 #[must_use]
1616 pub fn parse(s: &str) -> Option<Self> {
1617 Some(match s {
1618 "deadline" => Self::Deadline,
1619 "period" => Self::Period,
1620 "lifespan" => Self::Lifespan,
1621 _ => return None,
1622 })
1623 }
1624
1625 #[must_use]
1627 pub fn finding(self) -> Answer {
1628 match self {
1629 Self::Deadline | Self::Period => Answer::No,
1630 Self::Lifespan => Answer::Yes,
1631 }
1632 }
1633}
1634
1635#[must_use]
1644pub fn roll_up(question: Question, answers: impl IntoIterator<Item = Answer>) -> Answer {
1645 let finding = question.finding();
1646 let other = if finding == Answer::Yes {
1647 Answer::No
1648 } else {
1649 Answer::Yes
1650 };
1651 let (mut poles, mut unestablished) = (0u64, false);
1652 let (mut aside, mut not_asked) = (0u64, false);
1653 for a in answers {
1654 if a == finding {
1655 return finding;
1656 }
1657 match a {
1658 Answer::NotAsked => {
1659 aside += 1;
1660 not_asked = true;
1661 }
1662 Answer::NotThisProfiles => aside += 1,
1663 a if a == other => poles += 1,
1664 _ => unestablished = true,
1665 }
1666 }
1667 if unestablished {
1668 Answer::Unobservable
1669 } else if poles > 0 {
1670 other
1671 } else if aside == 0 {
1672 Answer::Unobservable
1673 } else if not_asked {
1674 Answer::NotAsked
1675 } else {
1676 Answer::NotThisProfiles
1677 }
1678}
1679
1680pub fn roll_up_first<K: AsRef<str>, R>(
1687 question: Question,
1688 members: impl IntoIterator<Item = (K, Answer, R)>,
1689) -> (Answer, Option<(K, R)>) {
1690 let members: Vec<(K, Answer, R)> = members.into_iter().collect();
1691 let answer = roll_up(question, members.iter().map(|(_, a, _)| *a));
1692 let first = members
1693 .into_iter()
1694 .filter(|(_, a, _)| *a == answer)
1695 .min_by(|(x, _, _), (y, _, _)| x.as_ref().as_bytes().cmp(y.as_ref().as_bytes()))
1696 .map(|(k, _, r)| (k, r));
1697 (answer, first)
1698}
1699
1700#[cfg(test)]
1701mod tests {
1702 use super::*;
1703 use serde_json::json;
1704
1705 fn ann(pairs: &[(&str, Value)]) -> BTreeMap<String, Value> {
1706 pairs
1707 .iter()
1708 .map(|(k, v)| ((*k).to_owned(), v.clone()))
1709 .collect()
1710 }
1711
1712 fn ms(n: u64) -> Mono {
1713 Mono::after(Duration::from_millis(n))
1714 }
1715
1716 #[test]
1717 fn a_value_is_a_whole_number_of_milliseconds_above_zero() {
1718 let d = |v: Value| declaration(Kind::Stream, &ann(&[(DEADLINE_MS, v)]));
1719 assert_eq!(
1720 d(json!(100)).declared().and_then(|x| x.deadline),
1721 Some(Duration::from_millis(100))
1722 );
1723 assert_eq!(
1724 d(json!(100.0)).declared().and_then(|x| x.deadline),
1725 Some(Duration::from_millis(100))
1726 );
1727 for bad in [
1728 json!(0),
1729 json!(-0.0),
1730 json!(-1),
1731 json!(1.5),
1732 json!(MAX_MS + 1),
1733 ] {
1734 assert_eq!(d(bad), Declaration::Invalid(vec![Invalid::DeadlineValue]));
1735 }
1736 assert_eq!(
1737 declaration(Kind::State, &ann(&[(DEADLINE_MS, json!("x"))])),
1738 Declaration::Ignored,
1739 "the kind first"
1740 );
1741 }
1742
1743 #[test]
1744 fn the_bound_has_a_millisecond_floor() {
1745 assert_eq!(
1746 detection_bound(Duration::from_millis(100)),
1747 Duration::from_millis(2)
1748 );
1749 assert_eq!(detection_bound(Duration::from_millis(30)), BOUND_FLOOR);
1750 assert_eq!(
1751 detection_bound(Duration::from_millis(75)),
1752 Duration::from_micros(1500)
1753 );
1754 }
1755
1756 #[test]
1757 fn a_paused_commander_is_missed_once_then_met() {
1758 let mut t = Tracker::new(Duration::from_millis(100), Some(1), ["cmd"]);
1759 t.observe(ms(0), Event::Owner(OwnerState::Present));
1760 t.observe(ms(0), Event::Start);
1761 let arrive = |t: &mut Tracker, at| {
1762 t.observe(
1763 ms(at),
1764 Event::Arrival {
1765 member: "cmd",
1766 expired: false,
1767 },
1768 )
1769 };
1770 assert!(arrive(&mut t, 10).is_empty());
1771 assert_eq!(t.next_due(), Some(ms(110)));
1772 let r = t.observe(ms(111), Event::Tick);
1773 assert_eq!(r.len(), 1);
1774 assert_eq!(r[0].as_str(), "missed");
1775 assert!(t.observe(ms(500), Event::Tick).is_empty(), "edge-triggered");
1776 let r = arrive(&mut t, 600);
1777 assert_eq!(r.len(), 1);
1778 assert_eq!(r[0].as_str(), "met");
1779 }
1780
1781 #[test]
1782 fn a_clock_ahead_beyond_epsilon_stays_unobservable() {
1783 let d = declaration(Kind::Stream, &ann(&[(LIFESPAN_MS, json!(100))]));
1784 let mut r = LifespanReader::new(Kind::Stream, &d, Some(Duration::from_millis(10)), [7]);
1785 let at = |s: f64| {
1786 Some(Stamped {
1787 age: StampAge::from_secs_f64(s),
1788 id: 7,
1789 })
1790 };
1791 assert_eq!(r.judge(at(0.05)).reason, Reason::Live);
1792 assert_eq!(r.judge(at(-0.05)).reason, Reason::ClockDisagrees);
1793 assert_eq!(r.judge(at(0.05)).reason, Reason::ClockDisagrees);
1794 assert_eq!(
1795 r.judge(Some(Stamped {
1796 age: StampAge::from_secs_f64(0.5),
1797 id: 8
1798 }))
1799 .reason,
1800 Reason::ForeignStamp
1801 );
1802 }
1803
1804 #[test]
1805 fn the_roll_up_reads_each_questions_finding() {
1806 let d = Question::Deadline;
1807 assert_eq!(roll_up(d, [Answer::Yes, Answer::NotAsked]), Answer::Yes);
1808 assert_eq!(
1809 roll_up(d, [Answer::Yes, Answer::Unobservable]),
1810 Answer::Unobservable
1811 );
1812 assert_eq!(roll_up(d, [Answer::Unobservable, Answer::No]), Answer::No);
1813 assert_eq!(roll_up(d, []), Answer::Unobservable);
1814 let l = Question::Lifespan;
1815 assert_eq!(roll_up(l, [Answer::No, Answer::Yes]), Answer::Yes, "F-264");
1816 assert_eq!(roll_up(l, [Answer::No, Answer::No]), Answer::No);
1817 assert_eq!(roll_up(l, [Answer::NotAsked]), Answer::NotAsked);
1819 assert_eq!(
1820 roll_up(l, [Answer::NotThisProfiles, Answer::NotAsked]),
1821 Answer::NotAsked
1822 );
1823 assert_eq!(
1824 roll_up(Question::Period, [Answer::NotThisProfiles]),
1825 Answer::NotThisProfiles
1826 );
1827 assert_eq!(
1828 roll_up(d, [Answer::NotAsked, Answer::Unobservable]),
1829 Answer::Unobservable,
1830 "an unobservable member is never set aside"
1831 );
1832 }
1833
1834 #[test]
1837 fn a_roll_ups_reason_is_its_first_members_in_byte_order() {
1838 let d = Question::Deadline;
1839 let (a, first) = roll_up_first(
1840 d,
1841 [
1842 ("axis/a", Answer::Unobservable, Reason::OwnerNotPresent),
1843 ("axis/B", Answer::Unobservable, Reason::WindowTooShort),
1844 ],
1845 );
1846 assert_eq!(
1847 (a, first),
1848 (
1849 Answer::Unobservable,
1850 Some(("axis/B", Reason::WindowTooShort))
1851 ),
1852 "B (0x42) before a (0x61): bytes, never a locale"
1853 );
1854 let (a, first) = roll_up_first(
1855 d,
1856 [
1857 ("axis/a", Answer::Unobservable, Reason::Lost),
1858 ("cmd", Answer::No, Reason::Missed),
1859 ],
1860 );
1861 assert_eq!(
1862 (a, first),
1863 (Answer::No, Some(("cmd", Reason::Missed))),
1864 "the first member giving the answer, not the first member"
1865 );
1866 let (a, first) = roll_up_first(
1867 Question::Lifespan,
1868 [
1869 ("a", Answer::NotThisProfiles, Reason::Kind),
1870 ("b", Answer::NotAsked, Reason::NoLifespan),
1871 ],
1872 );
1873 assert_eq!(
1874 (a, first),
1875 (Answer::NotAsked, Some(("b", Reason::NoLifespan)))
1876 );
1877 let (a, first) = roll_up_first(d, std::iter::empty::<(&str, Answer, Reason)>());
1878 assert_eq!((a, first), (Answer::Unobservable, None));
1879 }
1880
1881 fn holding_of(t: &mut Tracker, h: &mut Holding, at: u64, e: Event<'_>) -> Vec<Report> {
1882 let r = t.observe(ms(at), e);
1883 h.observe(t, e, &r, ms(at));
1884 r
1885 }
1886
1887 #[test]
1891 fn a_known_member_is_held_only_while_it_is_waited_for() {
1892 let mut t = Tracker::new(Duration::from_millis(500), Some(1), ["cmd"]);
1893 let mut h = Holding::new();
1894 holding_of(&mut t, &mut h, 0, Event::Owner(OwnerState::Present));
1895 holding_of(&mut t, &mut h, 0, Event::Start);
1896 holding_of(&mut t, &mut h, 150, Event::Owner(OwnerState::Unconfirmed));
1897 holding_of(&mut t, &mut h, 330, Event::Owner(OwnerState::Absent));
1898 let r = holding_of(&mut t, &mut h, 3000, Event::Tick);
1899 assert!(r.is_empty(), "no miss: the wait stopped before its due");
1900 h.close(ms(3000));
1901 assert_eq!(
1902 h.span("cmd").map(|s| s.held_to(ms(3000))),
1903 Some(Duration::from_millis(330)),
1904 "the unconfirmed while waits on (§2.5), the absence stops it"
1905 );
1906 let mut t = Tracker::new(Duration::from_millis(500), Some(1), ["cmd"]);
1908 let mut h = Holding::new();
1909 holding_of(&mut t, &mut h, 0, Event::Owner(OwnerState::Present));
1910 holding_of(&mut t, &mut h, 0, Event::Start);
1911 holding_of(&mut t, &mut h, 330, Event::Owner(OwnerState::Absent));
1912 holding_of(&mut t, &mut h, 1000, Event::Owner(OwnerState::Present));
1913 let r = holding_of(&mut t, &mut h, 1501, Event::Tick);
1914 assert_eq!(r.len(), 1, "{r:?}");
1915 h.close(ms(2000));
1916 assert_eq!(
1917 h.span("cmd").map(|s| s.held_to(ms(2000))),
1918 Some(Duration::from_millis(1000))
1919 );
1920 }
1921
1922 #[test]
1926 fn two_short_waits_hold_the_longer_never_their_sum() {
1927 let mut t = Tracker::new(Duration::from_millis(500), Some(1), ["cmd"]);
1928 let mut h = Holding::new();
1929 holding_of(&mut t, &mut h, 0, Event::Owner(OwnerState::Present));
1930 holding_of(&mut t, &mut h, 0, Event::Start);
1931 holding_of(&mut t, &mut h, 300, Event::Owner(OwnerState::Absent));
1932 holding_of(&mut t, &mut h, 1000, Event::Owner(OwnerState::Present));
1933 holding_of(&mut t, &mut h, 1400, Event::Owner(OwnerState::Absent));
1934 let r = holding_of(&mut t, &mut h, 3000, Event::Tick);
1935 assert!(r.is_empty(), "no miss in either wait: {r:?}");
1936 h.close(ms(3000));
1937 let held = h.span("cmd").map(|s| s.held_to(ms(3000))).unwrap();
1938 assert_eq!(held, Duration::from_millis(400));
1939 let d = declaration(
1940 Kind::Stream,
1941 &ann(&[(DEADLINE_MS, json!(500)), (PERIOD_MS, json!(100))]),
1942 );
1943 let account = DeadlineAccount {
1944 held,
1945 ..DeadlineAccount::default()
1946 };
1947 let j = deadline_met(Kind::Stream, &d, &Window::default(), &account);
1948 assert_eq!(
1949 (j.answer, j.reason),
1950 (Answer::Unobservable, Reason::WindowTooShort)
1951 );
1952 }
1953
1954 #[test]
1957 fn a_member_heard_again_is_held_over_its_first_life() {
1958 let mut t =
1959 Tracker::new(Duration::from_millis(500), Some(4), Vec::<String>::new()).with_epoch();
1960 let mut h = Holding::new();
1961 holding_of(&mut t, &mut h, 0, Event::Owner(OwnerState::Present));
1962 holding_of(&mut t, &mut h, 0, Event::Start);
1963 holding_of(&mut t, &mut h, 0, Event::MemberSeen("axis/x"));
1964 let arrival = Event::Arrival {
1965 member: "axis/x",
1966 expired: false,
1967 };
1968 for at in [100, 500, 900] {
1969 holding_of(&mut t, &mut h, at, arrival);
1970 }
1971 let r = holding_of(&mut t, &mut h, 1100, Event::MemberGone("axis/x"));
1972 assert_eq!(r.len(), 1, "ended, and no miss: {r:?}");
1973 holding_of(&mut t, &mut h, 2000, Event::MemberSeen("axis/x"));
1974 holding_of(&mut t, &mut h, 2000, arrival);
1975 holding_of(&mut t, &mut h, 4000, arrival);
1976 h.close(ms(5000));
1977 let s = h.span("axis/x").copied().expect("held");
1978 assert_eq!(s.ended(), Some(ms(1100)));
1979 assert_eq!(s.held_to(ms(5000)), Duration::from_millis(1000));
1980 }
1981}