1use std::collections::BTreeMap;
32use std::fmt;
33use std::time::{Duration, SystemTime};
34
35use serde_json::Value;
36
37use crate::authoring::Kind;
38use crate::contract::Resource;
39use crate::wire::Stamp;
40
41pub const PROFILE: &str = "freshness.v1";
43
44pub const PROFILE_V2: &str = crate::heartbeat::PROFILE;
48
49#[must_use]
55pub fn uses_v2(c: &crate::contract::Contract) -> bool {
56 c.uses.iter().any(|u| u.to_string() == PROFILE_V2)
57}
58
59pub const NAME: &str = "freshness";
61
62pub const TTL_S: &str = "freshness.ttl_s";
64
65pub const VOCABULARY: &[&str] = &["ttl_s"];
68
69pub const MAX_TTL_S: u64 = (1 << 53) - 1;
72
73pub const DEFAULT_DELTA: Duration = Duration::from_millis(500);
76
77#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum Horizon {
81 Undeclared,
83 Ignored,
86 Invalid(String),
89 Never,
91 Within(Duration),
93}
94
95impl Horizon {
96 #[must_use]
98 pub fn ttl(&self) -> Option<Duration> {
99 match self {
100 Self::Within(t) => Some(*t),
101 _ => None,
102 }
103 }
104
105 #[must_use]
108 pub fn refresh_bound(&self) -> Option<Duration> {
109 self.ttl().map(|t| t / 2)
110 }
111}
112
113impl fmt::Display for Horizon {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 match self {
116 Self::Undeclared => f.write_str("no horizon"),
117 Self::Ignored => f.write_str("a horizon this kind ignores"),
118 Self::Invalid(v) => write!(f, "{v}, not a horizon"),
119 Self::Never => f.write_str("ttl_s = 0, never stale"),
120 Self::Within(t) => write!(f, "ttl_s = {}", t.as_secs()),
121 }
122 }
123}
124
125#[must_use]
129pub fn horizon(kind: Kind, annotations: &BTreeMap<String, Value>) -> Horizon {
130 let Some(v) = annotations.get(TTL_S) else {
131 return Horizon::Undeclared;
132 };
133 if matches!(kind, Kind::Event | Kind::Operation) {
134 return Horizon::Ignored;
135 }
136 match seconds(v) {
137 Some(0) => Horizon::Never,
138 Some(n) => Horizon::Within(Duration::from_secs(n)),
139 None => Horizon::Invalid(v.to_string()),
140 }
141}
142
143#[must_use]
145pub fn horizon_of(r: &Resource) -> Horizon {
146 horizon(r.kind, &r.annotations)
147}
148
149fn seconds(v: &Value) -> Option<u64> {
153 let n = v.as_number()?;
154 if let Some(u) = n.as_u64() {
155 return (u <= MAX_TTL_S).then_some(u);
156 }
157 if n.is_i64() {
158 return None;
159 }
160 let f = n.as_f64()?;
161 let max = MAX_TTL_S as f64;
163 (f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= max).then_some(f as u64)
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
170pub struct StampAge(i128);
171
172impl StampAge {
173 #[must_use]
175 pub fn between(stamp: SystemTime, now: SystemTime) -> Self {
176 match now.duration_since(stamp) {
177 Ok(d) => Self::behind(d),
178 Err(e) => Self::ahead(e.duration()),
179 }
180 }
181
182 #[must_use]
184 pub fn behind(d: Duration) -> Self {
185 Self(d.as_nanos() as i128)
186 }
187
188 #[must_use]
190 pub fn ahead(d: Duration) -> Self {
191 Self(-(d.as_nanos() as i128))
192 }
193
194 #[must_use]
196 pub fn from_secs_f64(s: f64) -> Self {
197 Self((s * 1e9).round() as i128)
198 }
199
200 #[must_use]
201 pub fn as_secs_f64(self) -> f64 {
202 self.0 as f64 / 1e9
203 }
204
205 #[must_use]
207 pub fn nanos(self) -> i128 {
208 self.0
209 }
210}
211
212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215pub enum ClockTrust {
216 Trusted { delta: Duration },
218 Untrusted,
220}
221
222#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228pub struct ClockMeasure {
229 closest: StampAge,
230 most_ahead: StampAge,
231}
232
233impl ClockMeasure {
234 #[must_use]
236 pub fn new(offset: StampAge) -> Self {
237 Self {
238 closest: offset,
239 most_ahead: offset,
240 }
241 }
242
243 pub fn record(&mut self, offset: StampAge) {
245 if offset.nanos().unsigned_abs() < self.closest.nanos().unsigned_abs() {
246 self.closest = offset;
247 }
248 if offset < self.most_ahead {
249 self.most_ahead = offset;
250 }
251 }
252
253 #[must_use]
255 pub fn merge(mut self, other: Self) -> Self {
256 self.record(other.closest);
257 self.record(other.most_ahead);
258 self
259 }
260
261 #[must_use]
263 pub fn closest(&self) -> StampAge {
264 self.closest
265 }
266
267 #[must_use]
269 pub fn most_ahead(&self) -> StampAge {
270 self.most_ahead
271 }
272
273 #[must_use]
276 pub fn trust(&self, delta: Duration) -> ClockTrust {
277 let d = delta.as_nanos() as i128;
278 if self.closest.nanos().unsigned_abs() <= delta.as_nanos() && self.most_ahead.nanos() >= -d
279 {
280 ClockTrust::Trusted { delta }
281 } else {
282 ClockTrust::Untrusted
283 }
284 }
285}
286
287impl ClockTrust {
288 #[must_use]
291 pub fn from_offsets(offsets: impl IntoIterator<Item = StampAge>, delta: Duration) -> Self {
292 let mut it = offsets.into_iter();
293 let Some(first) = it.next() else {
294 return Self::Untrusted;
295 };
296 let mut m = ClockMeasure::new(first);
297 it.for_each(|o| m.record(o));
298 m.trust(delta)
299 }
300
301 #[must_use]
305 pub fn measured(offset: StampAge, delta: Duration) -> Self {
306 if offset.0.unsigned_abs() <= delta.as_nanos() {
307 Self::Trusted { delta }
308 } else {
309 Self::Untrusted
310 }
311 }
312}
313
314#[derive(Debug, Clone, Copy, PartialEq, Eq)]
317pub enum Last {
318 Put(Duration),
320 Delete(Duration),
322}
323
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326pub enum Reply {
327 Put { stamp_age: Option<StampAge> },
330 Delete,
332}
333
334#[derive(Debug, Clone, Copy, PartialEq, Eq)]
336pub enum Observation {
337 Subscribed {
341 last: Option<Last>,
342 listened: Duration,
343 complete: bool,
344 },
345 Got {
349 reply: Option<Reply>,
350 clock: ClockTrust,
351 },
352 Archived,
354}
355
356#[derive(Debug, Clone, Copy, PartialEq, Eq)]
359pub enum Entry {
360 Omitted,
362 Tombstone,
364 Live { stamp_age: Option<StampAge> },
369}
370
371impl Observation {
372 #[must_use]
379 pub fn of_entry(complete: bool, entry: Entry, clock: ClockTrust) -> Observation {
380 let reply = match entry {
381 Entry::Omitted if !complete => None,
382 Entry::Omitted | Entry::Tombstone => Some(Reply::Delete),
383 Entry::Live { stamp_age } => Some(Reply::Put { stamp_age }),
384 };
385 Observation::Got { reply, clock }
386 }
387}
388
389#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
392pub enum Verdict {
393 Fresh,
394 Stale,
395 Unobservable,
397 NotAsked,
400}
401
402impl Verdict {
403 #[must_use]
405 pub fn as_str(self) -> &'static str {
406 match self {
407 Self::Fresh => "fresh",
408 Self::Stale => "stale",
409 Self::Unobservable => "unobservable",
410 Self::NotAsked => "not_asked",
411 }
412 }
413}
414
415impl fmt::Display for Verdict {
416 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417 f.write_str(self.as_str())
418 }
419}
420
421#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
423pub enum Reason {
424 WithinHorizon,
426 NeverStale,
428 BeyondHorizon,
430 NoDelivery,
432 NotAHorizon,
434 ListenedTooShort,
436 Incomplete,
438 Silent,
440 NoStamp,
442 ClockUntrusted,
444 ClockDisagrees,
447 NearHorizon,
449 NoObservation,
451 NoHorizon,
453 Kind,
455 LastKnown,
457 Deleted,
459}
460
461impl Reason {
462 #[must_use]
464 pub fn as_str(self) -> &'static str {
465 match self {
466 Self::WithinHorizon => "within_horizon",
467 Self::NeverStale => "never_stale",
468 Self::BeyondHorizon => "beyond_horizon",
469 Self::NoDelivery => "no_delivery",
470 Self::NotAHorizon => "not_a_horizon",
471 Self::ListenedTooShort => "listened_too_short",
472 Self::Incomplete => "incomplete",
473 Self::Silent => "silent",
474 Self::NoStamp => "no_stamp",
475 Self::ClockUntrusted => "clock_untrusted",
476 Self::ClockDisagrees => "clock_disagrees",
477 Self::NearHorizon => "near_horizon",
478 Self::NoObservation => "no_observation",
479 Self::NoHorizon => "no_horizon",
480 Self::Kind => "kind",
481 Self::LastKnown => "last_known",
482 Self::Deleted => "deleted",
483 }
484 }
485
486 #[must_use]
488 pub fn says(self) -> &'static str {
489 match self {
490 Self::WithinHorizon => "confirmed within its horizon",
491 Self::NeverStale => "ttl_s = 0, never stale",
492 Self::BeyondHorizon => "not confirmed within its horizon",
493 Self::NoDelivery => "nothing delivered for longer than its horizon",
494 Self::NotAHorizon => "its freshness.ttl_s is not a horizon",
495 Self::ListenedTooShort => {
496 "nothing delivered, and not listened to for longer than its horizon"
497 }
498 Self::Incomplete => "deliveries were lost, and none within the horizon arrived",
499 Self::Silent => "no value was read",
500 Self::NoStamp => "the reply carries no stamp",
501 Self::ClockUntrusted => {
502 "this reader's clock is not trusted to the HLC delta against the stamping clock"
503 }
504 Self::ClockDisagrees => "the stamp is ahead of this reader's clock beyond the delta",
505 Self::NearHorizon => "the age is within the delta of the horizon",
506 Self::NoObservation => "nothing was observed",
507 Self::NoHorizon => "no freshness.ttl_s, so freshness is not asked",
508 Self::Kind => "an event or an operation has no freshness",
509 Self::LastKnown => "an archive's last-known value is never current",
510 Self::Deleted => "deleted, so no value",
511 }
512 }
513}
514
515impl fmt::Display for Reason {
516 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517 f.write_str(self.as_str())
518 }
519}
520
521#[derive(Debug, Clone, Copy, PartialEq, Eq)]
523pub struct Judged {
524 pub verdict: Verdict,
525 pub reason: Reason,
526}
527
528impl Judged {
529 const fn new(verdict: Verdict, reason: Reason) -> Self {
530 Self { verdict, reason }
531 }
532}
533
534#[must_use]
538pub fn judge(h: &Horizon, o: &Observation) -> Judged {
539 use Reason as R;
540 use Verdict as V;
541 match h {
542 Horizon::Undeclared => return Judged::new(V::NotAsked, R::NoHorizon),
543 Horizon::Ignored => return Judged::new(V::NotAsked, R::Kind),
544 _ => {}
545 }
546 if matches!(o, Observation::Archived) {
547 return Judged::new(V::NotAsked, R::LastKnown);
548 }
549 let ttl = match h {
550 Horizon::Invalid(_) => return Judged::new(V::Unobservable, R::NotAHorizon),
551 Horizon::Never => None,
552 Horizon::Within(t) => Some(*t),
553 Horizon::Undeclared | Horizon::Ignored => unreachable!("returned above"),
554 };
555 match (*o, ttl) {
556 (Observation::Archived, _) => unreachable!("returned above"),
557 (
559 Observation::Subscribed {
560 last: Some(Last::Delete(_)),
561 ..
562 },
563 _,
564 ) => Judged::new(V::NotAsked, R::Deleted),
565 (Observation::Subscribed { .. }, None) => Judged::new(V::Fresh, R::NeverStale),
566 (
567 Observation::Subscribed {
568 last,
569 listened,
570 complete,
571 },
572 Some(ttl),
573 ) => match last {
574 Some(Last::Put(a)) if a <= ttl => Judged::new(V::Fresh, R::WithinHorizon),
575 _ if !complete => Judged::new(V::Unobservable, R::Incomplete),
576 Some(_) => Judged::new(V::Stale, R::BeyondHorizon),
577 None if listened > ttl => Judged::new(V::Stale, R::NoDelivery),
578 None => Judged::new(V::Unobservable, R::ListenedTooShort),
579 },
580 (Observation::Got { reply: None, .. }, _) => Judged::new(V::Unobservable, R::Silent),
582 (
583 Observation::Got {
584 reply: Some(Reply::Delete),
585 ..
586 },
587 _,
588 ) => Judged::new(V::NotAsked, R::Deleted),
589 (Observation::Got { .. }, None) => Judged::new(V::Fresh, R::NeverStale),
590 (
591 Observation::Got {
592 reply: Some(Reply::Put { stamp_age }),
593 clock,
594 },
595 Some(ttl),
596 ) => {
597 let Some(age) = stamp_age else {
598 return Judged::new(V::Unobservable, R::NoStamp);
599 };
600 let ClockTrust::Trusted { delta } = clock else {
601 return Judged::new(V::Unobservable, R::ClockUntrusted);
602 };
603 let (a, t, d) = (age.0, ttl.as_nanos() as i128, delta.as_nanos() as i128);
604 if a < -d {
605 Judged::new(V::Unobservable, R::ClockDisagrees)
606 } else if a + d <= t {
607 Judged::new(V::Fresh, R::WithinHorizon)
608 } else if a - d > t {
609 Judged::new(V::Stale, R::BeyondHorizon)
610 } else {
611 Judged::new(V::Unobservable, R::NearHorizon)
612 }
613 }
614 }
615}
616
617#[must_use]
622pub fn combine(judged: impl IntoIterator<Item = Judged>) -> Judged {
623 let rank = |v: Verdict| match v {
624 Verdict::Fresh => 0,
625 Verdict::Stale => 1,
626 Verdict::Unobservable => 2,
627 Verdict::NotAsked => 3,
628 };
629 judged
630 .into_iter()
631 .fold(None, |best: Option<Judged>, j| match best {
632 Some(b) if rank(b.verdict) <= rank(j.verdict) => Some(b),
633 _ => Some(j),
634 })
635 .unwrap_or(Judged::new(Verdict::Unobservable, Reason::NoObservation))
636}
637
638#[must_use]
644pub fn judge_all(h: &Horizon, observations: &[Observation]) -> Judged {
645 if observations.is_empty() {
646 return match h {
647 Horizon::Undeclared => Judged::new(Verdict::NotAsked, Reason::NoHorizon),
648 Horizon::Ignored => Judged::new(Verdict::NotAsked, Reason::Kind),
649 Horizon::Invalid(_) => Judged::new(Verdict::Unobservable, Reason::NotAHorizon),
650 Horizon::Never | Horizon::Within(_) => {
651 Judged::new(Verdict::Unobservable, Reason::NoObservation)
652 }
653 };
654 }
655 combine(observations.iter().map(|o| judge(h, o)))
656}
657
658pub trait Arrival: Copy + Ord {
663 fn since(self, earlier: Self) -> Duration;
666}
667
668impl Arrival for std::time::Instant {
669 fn since(self, earlier: Self) -> Duration {
670 self.saturating_duration_since(earlier)
671 }
672}
673
674impl Arrival for crate::timing::Mono {
675 fn since(self, earlier: Self) -> Duration {
676 self.saturating_since(earlier)
677 }
678}
679
680#[derive(Debug, Clone, Copy, PartialEq, Eq)]
682struct Held<T> {
683 collection: usize,
684 stamp: Option<Stamp>,
687 deleted: bool,
688 at: T,
690 confirmed: Option<T>,
692}
693
694#[derive(Debug, Clone, PartialEq, Eq)]
697pub enum SectionRead {
698 NotFollowed,
700 Absent,
702 Diverged,
705 Confirmed(Vec<String>),
708}
709
710impl SectionRead {
711 #[must_use]
713 pub fn as_str(&self) -> &'static str {
714 match self {
715 Self::NotFollowed => "not_followed",
716 Self::Absent => "absent",
717 Self::Diverged => "diverged",
718 Self::Confirmed(_) => "confirmed",
719 }
720 }
721}
722
723#[derive(Debug, Clone, PartialEq, Eq)]
725pub enum Applied {
726 Revision,
728 Refused(crate::heartbeat::BodyRefusal),
730 Older,
733 Read {
736 gap: bool,
737 sections: Vec<SectionRead>,
738 },
739}
740
741#[derive(Debug, Clone)]
763pub struct View<T> {
764 layout: crate::heartbeat::Layout,
765 follows: Vec<bool>,
766 members: BTreeMap<String, Held<T>>,
767 diverged: Vec<u32>,
768 last: Option<Stamp>,
769 gap: bool,
770 time: Option<crate::heartbeat::Time>,
771 heartbeats: u64,
772}
773
774impl<T: Arrival> View<T> {
775 #[must_use]
777 pub fn new(layout: crate::heartbeat::Layout) -> Self {
778 let n = layout.collections.len();
779 Self {
780 layout,
781 follows: vec![false; n],
782 members: BTreeMap::new(),
783 diverged: vec![0; n],
784 last: None,
785 gap: false,
786 time: None,
787 heartbeats: 0,
788 }
789 }
790
791 #[must_use]
793 pub fn layout(&self) -> &crate::heartbeat::Layout {
794 &self.layout
795 }
796
797 pub fn follow(&mut self, index: usize) -> bool {
799 match self.follows.get_mut(index) {
800 Some(f) => {
801 *f = true;
802 true
803 }
804 None => false,
805 }
806 }
807
808 pub fn follow_resource(&mut self, resource: &str) -> bool {
811 self.layout
812 .index_of(resource)
813 .is_some_and(|i| self.follow(i))
814 }
815
816 #[must_use]
818 pub fn follows_any(&self) -> bool {
819 self.follows.iter().any(|f| *f)
820 }
821
822 pub fn put(&mut self, key: &str, stamp: Option<Stamp>, at: T) {
826 self.mutation(key, stamp, false, at);
827 }
828
829 pub fn delete(&mut self, key: &str, stamp: Option<Stamp>, at: T) {
832 self.mutation(key, stamp, true, at);
833 }
834
835 fn mutation(&mut self, key: &str, stamp: Option<Stamp>, deleted: bool, at: T) {
836 let Some(k) = crate::heartbeat::base_relative(key) else {
837 return;
838 };
839 let Some(collection) = self.layout.collection_of(k) else {
840 return;
841 };
842 if let (Some(h), Some(s)) = (self.members.get(k).and_then(|h| h.stamp), stamp)
843 && h.run == s.run
844 && s.seq <= h.seq
845 {
846 return;
847 }
848 self.members.insert(
849 k.to_owned(),
850 Held {
851 collection,
852 stamp,
853 deleted,
854 at,
855 confirmed: None,
856 },
857 );
858 }
859
860 pub fn replace<'k>(
866 &mut self,
867 index: usize,
868 live: impl IntoIterator<Item = (&'k str, Option<Stamp>)>,
869 at: T,
870 ) {
871 self.members.retain(|_, h| h.collection != index);
872 for (key, stamp) in live {
873 let Some(k) = crate::heartbeat::base_relative(key) else {
874 continue;
875 };
876 if self.layout.collection_of(k) == Some(index) {
877 self.members.insert(
878 k.to_owned(),
879 Held {
880 collection: index,
881 stamp,
882 deleted: false,
883 at,
884 confirmed: None,
885 },
886 );
887 }
888 }
889 if let Some(d) = self.diverged.get_mut(index) {
890 *d = 0;
891 }
892 }
893
894 pub fn reread<'k>(
903 &mut self,
904 index: usize,
905 live: impl IntoIterator<Item = (&'k str, Option<Stamp>)>,
906 asked: T,
907 at: T,
908 ) {
909 let heard: Vec<(String, Held<T>)> = self
910 .members
911 .iter()
912 .filter(|(_, h)| h.collection == index && h.at >= asked)
913 .map(|(k, h)| (k.clone(), *h))
914 .collect();
915 self.replace(index, live, at);
916 for (k, h) in heard {
917 let keep = match self.members.get(&k) {
918 None => true,
919 Some(answered) => match (h.stamp, answered.stamp) {
920 (Some(mine), Some(theirs)) => mine.run == theirs.run && mine.seq > theirs.seq,
921 _ => false,
922 },
923 };
924 if keep {
925 self.members.insert(k, h);
926 }
927 }
928 }
929
930 fn live(&self, index: usize) -> impl Iterator<Item = (&String, &Held<T>)> {
932 self.members
933 .iter()
934 .filter(move |(_, h)| h.collection == index && !h.deleted)
935 }
936
937 #[must_use]
940 pub fn digest(&self, index: usize) -> Option<crate::heartbeat::Digest> {
941 let mut d = crate::heartbeat::Digest::EMPTY;
942 for (k, h) in self.live(index) {
943 d.toggle(k, h.stamp?);
944 }
945 Some(d)
946 }
947
948 pub fn apply(&mut self, tag: crate::wire::Tag, stamp: Stamp, body: &[u8], at: T) -> Applied {
951 use crate::heartbeat::{Heartbeat, Members};
952 if tag != self.layout.tag {
953 return Applied::Revision;
954 }
955 let hb = match Heartbeat::parse(body, &self.layout) {
956 Ok(hb) => hb,
957 Err(r) => return Applied::Refused(r),
958 };
959 let gap = match self.last {
960 Some(l) if l.run == stamp.run => {
961 match crate::seed::Order::Serial.seqs(l.seq, stamp.seq) {
962 Some(std::cmp::Ordering::Greater) => {
963 stamp.seq.get().wrapping_sub(l.seq.get()) & crate::wire::Seq::MAX.get() != 1
964 }
965 _ => return Applied::Older,
966 }
967 }
968 _ => false,
969 };
970 self.last = Some(stamp);
971 self.gap = gap;
972 self.time = Some(hb.time);
973 self.heartbeats += 1;
974 let mut sections = Vec::with_capacity(hb.sections.len());
975 for (i, section) in hb.sections.iter().enumerate() {
976 if !self.follows[i] {
977 sections.push(SectionRead::NotFollowed);
978 continue;
979 }
980 let Some(s) = section else {
981 self.diverged[i] = 0;
982 sections.push(SectionRead::Absent);
983 continue;
984 };
985 let keys: Vec<String> = self.live(i).map(|(k, _)| k.clone()).collect();
986 let same_count = match &s.members {
987 Members::One { .. } => keys.len() <= 1,
988 m => m.live() == Some(keys.len() as u64),
989 };
990 if self.digest(i) != Some(s.digest) || !same_count {
991 self.diverged[i] = self.diverged[i].saturating_add(1);
992 sections.push(SectionRead::Diverged);
993 continue;
994 }
995 self.diverged[i] = 0;
996 let vouched: Vec<String> = s
997 .members
998 .vouched()
999 .into_iter()
1000 .filter_map(|r| keys.get(usize::try_from(r).ok()?).cloned())
1001 .collect();
1002 for k in &vouched {
1003 if let Some(h) = self.members.get_mut(k) {
1004 h.confirmed = Some(at);
1005 }
1006 }
1007 sections.push(SectionRead::Confirmed(vouched));
1008 }
1009 Applied::Read { gap, sections }
1010 }
1011
1012 pub fn confirm(&mut self, key: &str, at: T) {
1017 let Some(k) = crate::heartbeat::base_relative(key) else {
1018 return;
1019 };
1020 if let Some(h) = self.members.get_mut(k)
1021 && !h.deleted
1022 && h.confirmed.is_none_or(|c| c < at)
1023 {
1024 h.confirmed = Some(at);
1025 }
1026 }
1027
1028 #[must_use]
1030 pub fn confirmed(&self, key: &str) -> Option<T> {
1031 let k = crate::heartbeat::base_relative(key)?;
1032 self.members.get(k).and_then(|h| h.confirmed)
1033 }
1034
1035 #[must_use]
1037 pub fn reread_due(&self) -> Vec<usize> {
1038 (0..self.diverged.len())
1039 .filter(|i| self.follows[*i] && self.diverged[*i] >= 2)
1040 .collect()
1041 }
1042
1043 #[must_use]
1045 pub fn gap(&self) -> bool {
1046 self.gap
1047 }
1048
1049 #[must_use]
1051 pub fn owner_time(&self) -> Option<crate::heartbeat::Time> {
1052 self.time
1053 }
1054
1055 #[must_use]
1057 pub fn last_heartbeat(&self) -> Option<Stamp> {
1058 self.last
1059 }
1060
1061 #[must_use]
1063 pub fn heartbeats(&self) -> u64 {
1064 self.heartbeats
1065 }
1066
1067 #[must_use]
1071 pub fn last(&self, key: &str, now: T) -> Option<Last> {
1072 let k = crate::heartbeat::base_relative(key)?;
1073 let h = self.members.get(k)?;
1074 Some(if h.deleted {
1075 Last::Delete(now.since(h.at))
1076 } else {
1077 Last::Put(now.since(h.confirmed.map_or(h.at, |c| c.max(h.at))))
1078 })
1079 }
1080
1081 #[must_use]
1086 pub fn observation(
1087 &self,
1088 key: &str,
1089 now: T,
1090 listened: Duration,
1091 complete: bool,
1092 ) -> Observation {
1093 Observation::Subscribed {
1094 last: self.last(key, now),
1095 listened,
1096 complete: complete && !self.gap,
1097 }
1098 }
1099}
1100
1101#[must_use]
1108pub fn confirmed_last(delivered: Option<Last>, heartbeat: Option<Duration>) -> Option<Last> {
1109 match (delivered, heartbeat) {
1110 (Some(Last::Put(a)), Some(h)) => Some(Last::Put(a.min(h))),
1111 (None, Some(h)) => Some(Last::Put(h)),
1112 (d, _) => d,
1113 }
1114}
1115
1116#[cfg(test)]
1117mod tests {
1118 use super::*;
1119 use serde_json::json;
1120
1121 fn ann(v: Value) -> BTreeMap<String, Value> {
1122 BTreeMap::from([(TTL_S.to_owned(), v)])
1123 }
1124
1125 #[test]
1126 fn the_horizon_is_a_whole_number_of_seconds() {
1127 let h = |v: Value| horizon(Kind::State, &ann(v));
1128 assert_eq!(h(json!(60)), Horizon::Within(Duration::from_secs(60)));
1129 assert_eq!(h(json!(60.0)), Horizon::Within(Duration::from_secs(60)));
1130 assert_eq!(h(json!(-0.0)), Horizon::Never);
1131 assert_eq!(h(json!(0)), Horizon::Never);
1132 assert!(matches!(h(json!(1.5)), Horizon::Invalid(_)));
1133 assert!(matches!(h(json!(-1)), Horizon::Invalid(_)));
1134 assert!(matches!(h(json!(MAX_TTL_S + 1)), Horizon::Invalid(_)));
1135 assert_eq!(
1136 horizon(Kind::Event, &ann(json!("x"))),
1137 Horizon::Ignored,
1138 "the kind first"
1139 );
1140 assert_eq!(horizon(Kind::State, &BTreeMap::new()), Horizon::Undeclared);
1141 assert_eq!(
1142 h(json!(61)).refresh_bound(),
1143 Some(Duration::from_millis(30_500))
1144 );
1145 }
1146
1147 #[test]
1148 fn a_trusted_reply_is_judged_in_the_band() {
1149 let h = Horizon::Within(Duration::from_secs(2));
1150 let got = |s: f64| Observation::Got {
1151 reply: Some(Reply::Put {
1152 stamp_age: Some(StampAge::from_secs_f64(s)),
1153 }),
1154 clock: ClockTrust::Trusted {
1155 delta: DEFAULT_DELTA,
1156 },
1157 };
1158 let v = |s: f64| judge(&h, &got(s)).reason;
1159 assert_eq!(v(1.5), Reason::WithinHorizon);
1160 assert_eq!(v(1.6), Reason::NearHorizon);
1161 assert_eq!(v(2.5), Reason::NearHorizon);
1162 assert_eq!(v(2.6), Reason::BeyondHorizon);
1163 assert_eq!(v(-0.5), Reason::WithinHorizon);
1164 assert_eq!(v(-0.6), Reason::ClockDisagrees);
1165 }
1166
1167 #[test]
1168 fn fresh_wins_then_stale_then_unobservable() {
1169 let j = |v, r| Judged::new(v, r);
1170 assert_eq!(
1171 combine([
1172 j(Verdict::Stale, Reason::NoDelivery),
1173 j(Verdict::Fresh, Reason::WithinHorizon)
1174 ])
1175 .verdict,
1176 Verdict::Fresh
1177 );
1178 assert_eq!(
1179 combine([
1180 j(Verdict::Unobservable, Reason::ClockUntrusted),
1181 j(Verdict::Stale, Reason::NoDelivery)
1182 ])
1183 .reason,
1184 Reason::NoDelivery
1185 );
1186 assert_eq!(combine([]).reason, Reason::NoObservation);
1187 }
1188
1189 mod view {
1190 use super::super::*;
1191 use crate::contract::load_str;
1192 use crate::heartbeat::{Digest, Heartbeat, Layout, Members, Section, Time};
1193 use crate::timing::Mono;
1194 use crate::wire::{Run, Seq, Tag};
1195
1196 const HB: &str = r#"
1197[interface]
1198name = "hb"
1199major = 1
1200minor = 0
1201uses = ["freshness.v1"]
1202[resources.link]
1203kind = "state"
1204type = { raw = "text/plain" }
1205annotations = { "freshness.ttl_s" = 2 }
1206[resources."peer/{peer}"]
1207kind = "state"
1208type = { raw = "text/plain" }
1209params = { peer = "string" }
1210cardinality = 5
1211annotations = { "freshness.ttl_s" = 2 }
1212"#;
1213 const LINK: &str = "zk2/lab/n1/hb.v1/state/link";
1214 const A: &str = "zk2/lab/n1/hb.v1/state/peer/a";
1215 const B: &str = "zk2/lab/n1/hb.v1/state/peer/b";
1216
1217 fn layout() -> Layout {
1218 let c = load_str(HB, std::path::Path::new("."), None)
1219 .contract
1220 .unwrap();
1221 Layout::of(&c)
1222 }
1223 fn st(run: u16, seq: u32) -> Stamp {
1224 Stamp {
1225 run: Run::U16(run),
1226 seq: Seq::new(seq).unwrap(),
1227 }
1228 }
1229 fn ms(n: u64) -> Mono {
1230 Mono::after(Duration::from_millis(n))
1231 }
1232 fn body(l: &Layout, link: Option<Section>, peers: Option<Section>) -> Vec<u8> {
1234 Heartbeat {
1235 time: Time::Unknown,
1236 sections: vec![link, peers],
1237 }
1238 .write(l)
1239 .unwrap()
1240 }
1241 fn view() -> View<Mono> {
1242 let mut v = View::new(layout());
1243 assert!(v.follow_resource("state/link"));
1244 assert!(v.follow_resource("state/peer/{peer}"));
1245 assert!(!v.follow_resource("state/nothing"));
1246 v
1247 }
1248
1249 #[test]
1250 fn a_heartbeat_whose_digest_is_the_views_confirms_what_it_vouches_for() {
1251 let l = layout();
1252 let mut v = view();
1253 v.put(LINK, Some(st(1, 1)), ms(0));
1254 v.put(A, Some(st(1, 2)), ms(0));
1255 v.put(B, Some(st(1, 3)), ms(0));
1256 let link = Section {
1257 digest: Digest::of([(LINK, st(1, 1))]),
1258 members: Members::One { vouched: true },
1259 };
1260 let peers = Section {
1261 digest: Digest::of([(A, st(1, 2)), (B, st(1, 3))]),
1262 members: Members::templated(2, [1]),
1263 };
1264 let got = v.apply(
1265 l.tag,
1266 st(9, 0),
1267 &body(&l, Some(link), Some(peers)),
1268 ms(1500),
1269 );
1270 assert_eq!(
1271 got,
1272 Applied::Read {
1273 gap: false,
1274 sections: vec![
1275 SectionRead::Confirmed(vec![LINK.into()]),
1276 SectionRead::Confirmed(vec![B.into()]),
1277 ]
1278 }
1279 );
1280 assert_eq!(v.confirmed(B), Some(ms(1500)));
1281 assert_eq!(v.confirmed(A), None, "not vouched for");
1282 let h = Horizon::Within(Duration::from_secs(2));
1284 let j = |k: &str| {
1285 judge(
1286 &h,
1287 &v.observation(k, ms(3000), Duration::from_secs(3), true),
1288 )
1289 };
1290 assert_eq!(j(LINK).verdict, Verdict::Fresh);
1291 assert_eq!(j(B).verdict, Verdict::Fresh);
1292 assert_eq!(
1293 j(A).verdict,
1294 Verdict::Stale,
1295 "a cleared bit is no confirmation"
1296 );
1297 assert_eq!(v.confirmed(&format!("prod/{LINK}")), Some(ms(1500)));
1299 }
1300
1301 #[test]
1302 fn a_missed_change_diverges_and_two_in_a_row_are_due_a_read() {
1303 let l = layout();
1304 let mut v = view();
1305 v.put(A, Some(st(1, 2)), ms(0));
1306 let owner = Digest::of([(A, st(1, 5)), (B, st(1, 6))]);
1308 let sec = || Section {
1309 digest: owner,
1310 members: Members::templated(2, [0, 1]),
1311 };
1312 for (seq, due) in [(0, false), (1, true)] {
1313 let got = v.apply(l.tag, st(9, seq), &body(&l, None, Some(sec())), ms(1000));
1314 assert_eq!(
1315 got,
1316 Applied::Read {
1317 gap: false,
1318 sections: vec![SectionRead::Absent, SectionRead::Diverged]
1319 }
1320 );
1321 assert_eq!(v.reread_due() == vec![1], due);
1322 }
1323 assert_eq!(v.confirmed(A), None);
1324 v.replace(1, [(A, Some(st(1, 5))), (B, Some(st(1, 6)))], ms(1100));
1326 assert!(v.reread_due().is_empty());
1327 let got = v.apply(l.tag, st(9, 2), &body(&l, None, Some(sec())), ms(1200));
1328 assert_eq!(
1329 got,
1330 Applied::Read {
1331 gap: false,
1332 sections: vec![
1333 SectionRead::Absent,
1334 SectionRead::Confirmed(vec![A.into(), B.into()])
1335 ]
1336 }
1337 );
1338 }
1339
1340 #[test]
1341 fn a_deleted_member_leaves_the_digest_and_a_stale_put_is_not_taken() {
1342 let mut v = view();
1343 v.put(A, Some(st(1, 4)), ms(0));
1344 v.put(A, Some(st(1, 3)), ms(10));
1345 assert_eq!(v.digest(1), Some(Digest::of([(A, st(1, 4))])));
1346 v.delete(A, Some(st(1, 5)), ms(20));
1347 assert_eq!(v.digest(1), Some(Digest::EMPTY));
1348 assert_eq!(
1349 v.last(A, ms(30)),
1350 Some(Last::Delete(Duration::from_millis(10)))
1351 );
1352 v.put(A, Some(st(2, 0)), ms(40));
1354 assert_eq!(v.digest(1), Some(Digest::of([(A, st(2, 0))])));
1355 v.put(B, None, ms(50));
1357 assert_eq!(v.digest(1), None);
1358 v.put("zk2/lab/n1/hb.v1/state/other", Some(st(1, 1)), ms(60));
1360 assert_eq!(v.last("zk2/lab/n1/hb.v1/state/other", ms(70)), None);
1361 }
1362
1363 #[test]
1364 fn a_gap_is_a_heartbeat_lost_and_the_tag_and_the_order_guard() {
1365 let l = layout();
1366 let mut v = view();
1367 v.put(LINK, Some(st(1, 1)), ms(0));
1368 let link = || {
1369 Some(Section {
1370 digest: Digest::of([(LINK, st(1, 1))]),
1371 members: Members::One { vouched: true },
1372 })
1373 };
1374 let b = body(&l, link(), None);
1375 let other = Tag::new((l.tag.get() + 1) % 16).unwrap();
1376 assert_eq!(v.apply(other, st(9, 0), &b, ms(100)), Applied::Revision);
1377 assert!(matches!(
1378 v.apply(l.tag, st(9, 0), &b, ms(100)),
1379 Applied::Read { gap: false, .. }
1380 ));
1381 assert!(matches!(
1382 v.apply(l.tag, st(9, 3), &b, ms(200)),
1383 Applied::Read { gap: true, .. }
1384 ));
1385 assert!(v.gap());
1386 let o = v.observation(LINK, ms(5000), Duration::from_secs(5), true);
1387 assert_eq!(
1388 judge(&Horizon::Within(Duration::from_secs(2)), &o).reason,
1389 Reason::Incomplete
1390 );
1391 assert_eq!(v.apply(l.tag, st(9, 3), &b, ms(300)), Applied::Older);
1392 assert_eq!(v.apply(l.tag, st(9, 1), &b, ms(300)), Applied::Older);
1393 assert!(matches!(
1394 v.apply(l.tag, st(9, 4), &b, ms(400)),
1395 Applied::Read { gap: false, .. }
1396 ));
1397 assert!(!v.gap());
1398 assert!(matches!(
1400 v.apply(l.tag, st(10, 0), &b, ms(500)),
1401 Applied::Read { gap: false, .. }
1402 ));
1403 assert!(matches!(
1405 v.apply(l.tag, st(10, 1), &b[..2], ms(600)),
1406 Applied::Refused(_)
1407 ));
1408 assert_eq!(v.heartbeats(), 4);
1409 }
1410 }
1411
1412 #[test]
1413 fn a_measured_offset_trusts_within_the_delta_either_way() {
1414 let d = DEFAULT_DELTA;
1415 assert!(matches!(
1416 ClockTrust::measured(StampAge::ahead(d), d),
1417 ClockTrust::Trusted { .. }
1418 ));
1419 assert_eq!(
1420 ClockTrust::measured(StampAge::behind(Duration::from_millis(501)), d),
1421 ClockTrust::Untrusted
1422 );
1423 }
1424}