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 OtherClass,
704 Absent,
706 Diverged,
709 Confirmed(Vec<String>),
712}
713
714impl SectionRead {
715 #[must_use]
717 pub fn as_str(&self) -> &'static str {
718 match self {
719 Self::NotFollowed => "not_followed",
720 Self::OtherClass => "other_class",
721 Self::Absent => "absent",
722 Self::Diverged => "diverged",
723 Self::Confirmed(_) => "confirmed",
724 }
725 }
726}
727
728#[derive(Debug, Clone, PartialEq, Eq)]
730pub enum Applied {
731 Revision,
733 Refused(crate::heartbeat::BodyRefusal),
735 Older,
738 Read {
741 gap: bool,
742 sections: Vec<SectionRead>,
743 },
744}
745
746#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
752pub struct Sequence {
753 last: Option<Stamp>,
754 gap: bool,
755}
756
757#[derive(Debug, Clone, Copy, PartialEq, Eq)]
759pub struct Sequenced {
760 pub gap: bool,
763 pub run: bool,
766}
767
768impl Sequence {
769 pub fn read(&mut self, stamp: Stamp) -> Option<Sequenced> {
774 let read = match self.last {
775 Some(l) if l.run == stamp.run => {
776 match crate::seed::Order::Serial.seqs(l.seq, stamp.seq) {
777 Some(std::cmp::Ordering::Greater) => Sequenced {
778 gap: stamp.seq.get().wrapping_sub(l.seq.get())
779 & crate::wire::Seq::MAX.get()
780 != 1,
781 run: false,
782 },
783 _ => return None,
784 }
785 }
786 Some(_) => Sequenced {
787 gap: false,
788 run: true,
789 },
790 None => Sequenced {
791 gap: false,
792 run: false,
793 },
794 };
795 self.last = Some(stamp);
796 self.gap = read.gap;
797 Some(read)
798 }
799
800 #[must_use]
802 pub fn last(&self) -> Option<Stamp> {
803 self.last
804 }
805
806 #[must_use]
808 pub fn gap(&self) -> bool {
809 self.gap
810 }
811}
812
813#[derive(Debug, Clone, PartialEq, Eq)]
818pub enum GroupRead {
819 Refused(crate::heartbeat::GroupRefusal),
823 NotFollowed,
826 Revision,
829 Read(Vec<SectionRead>),
831}
832
833#[derive(Debug, Clone, PartialEq, Eq)]
836pub struct GroupApplied {
837 pub index: u16,
838 pub iface: Option<crate::grammar::IfaceId>,
839 pub read: GroupRead,
840}
841
842#[derive(Debug, Clone, PartialEq, Eq)]
844pub enum OwnerApplied {
845 Refused(crate::heartbeat::OwnerRefusal),
848 Older,
851 Read {
855 gap: bool,
856 groups: Vec<GroupApplied>,
857 },
858}
859
860#[derive(Debug, Clone)]
882pub struct View<T> {
883 layout: crate::heartbeat::Layout,
884 follows: Vec<bool>,
885 members: BTreeMap<String, Held<T>>,
886 diverged: Vec<u32>,
887 seq: Sequence,
890 time: Option<crate::heartbeat::Time>,
891 heartbeats: u64,
892}
893
894impl<T: Arrival> View<T> {
895 #[must_use]
897 pub fn new(layout: crate::heartbeat::Layout) -> Self {
898 let n = layout.collections.len();
899 Self {
900 layout,
901 follows: vec![false; n],
902 members: BTreeMap::new(),
903 diverged: vec![0; n],
904 seq: Sequence::default(),
905 time: None,
906 heartbeats: 0,
907 }
908 }
909
910 #[must_use]
912 pub fn layout(&self) -> &crate::heartbeat::Layout {
913 &self.layout
914 }
915
916 pub fn follow(&mut self, index: usize) -> bool {
918 match self.follows.get_mut(index) {
919 Some(f) => {
920 *f = true;
921 true
922 }
923 None => false,
924 }
925 }
926
927 pub fn follow_resource(&mut self, resource: &str) -> bool {
930 self.layout
931 .index_of(resource)
932 .is_some_and(|i| self.follow(i))
933 }
934
935 #[must_use]
937 pub fn follows_any(&self) -> bool {
938 self.follows.iter().any(|f| *f)
939 }
940
941 pub fn put(&mut self, key: &str, stamp: Option<Stamp>, at: T) {
945 self.mutation(key, stamp, false, at);
946 }
947
948 pub fn delete(&mut self, key: &str, stamp: Option<Stamp>, at: T) {
951 self.mutation(key, stamp, true, at);
952 }
953
954 fn mutation(&mut self, key: &str, stamp: Option<Stamp>, deleted: bool, at: T) {
955 let Some(k) = crate::heartbeat::base_relative(key) else {
956 return;
957 };
958 let Some(collection) = self.layout.collection_of(k) else {
959 return;
960 };
961 if let (Some(h), Some(s)) = (self.members.get(k).and_then(|h| h.stamp), stamp)
962 && h.run == s.run
963 && s.seq <= h.seq
964 {
965 return;
966 }
967 self.members.insert(
968 k.to_owned(),
969 Held {
970 collection,
971 stamp,
972 deleted,
973 at,
974 confirmed: None,
975 },
976 );
977 }
978
979 pub fn replace<'k>(
985 &mut self,
986 index: usize,
987 live: impl IntoIterator<Item = (&'k str, Option<Stamp>)>,
988 at: T,
989 ) {
990 self.members.retain(|_, h| h.collection != index);
991 for (key, stamp) in live {
992 let Some(k) = crate::heartbeat::base_relative(key) else {
993 continue;
994 };
995 if self.layout.collection_of(k) == Some(index) {
996 self.members.insert(
997 k.to_owned(),
998 Held {
999 collection: index,
1000 stamp,
1001 deleted: false,
1002 at,
1003 confirmed: None,
1004 },
1005 );
1006 }
1007 }
1008 if let Some(d) = self.diverged.get_mut(index) {
1009 *d = 0;
1010 }
1011 }
1012
1013 pub fn reread<'k>(
1022 &mut self,
1023 index: usize,
1024 live: impl IntoIterator<Item = (&'k str, Option<Stamp>)>,
1025 asked: T,
1026 at: T,
1027 ) {
1028 let heard: Vec<(String, Held<T>)> = self
1029 .members
1030 .iter()
1031 .filter(|(_, h)| h.collection == index && h.at >= asked)
1032 .map(|(k, h)| (k.clone(), *h))
1033 .collect();
1034 self.replace(index, live, at);
1035 for (k, h) in heard {
1036 let keep = match self.members.get(&k) {
1037 None => true,
1038 Some(answered) => match (h.stamp, answered.stamp) {
1039 (Some(mine), Some(theirs)) => mine.run == theirs.run && mine.seq > theirs.seq,
1040 _ => false,
1041 },
1042 };
1043 if keep {
1044 self.members.insert(k, h);
1045 }
1046 }
1047 }
1048
1049 fn live(&self, index: usize) -> impl Iterator<Item = (&String, &Held<T>)> {
1051 self.members
1052 .iter()
1053 .filter(move |(_, h)| h.collection == index && !h.deleted)
1054 }
1055
1056 #[must_use]
1059 pub fn digest(&self, index: usize) -> Option<crate::heartbeat::Digest> {
1060 let mut d = crate::heartbeat::Digest::EMPTY;
1061 for (k, h) in self.live(index) {
1062 d.toggle(k, h.stamp?);
1063 }
1064 Some(d)
1065 }
1066
1067 pub fn apply(&mut self, tag: crate::wire::Tag, stamp: Stamp, body: &[u8], at: T) -> Applied {
1070 use crate::heartbeat::Heartbeat;
1071 if tag != self.layout.tag {
1072 return Applied::Revision;
1073 }
1074 let hb = match Heartbeat::parse(body, &self.layout) {
1075 Ok(hb) => hb,
1076 Err(r) => return Applied::Refused(r),
1077 };
1078 let Some(read) = self.seq.read(stamp) else {
1079 return Applied::Older;
1080 };
1081 self.time = Some(hb.time);
1082 self.heartbeats += 1;
1083 let mut sections = Vec::with_capacity(hb.sections.len());
1084 for (i, section) in hb.sections.iter().enumerate() {
1085 sections.push(if self.follows[i] {
1086 self.read_section(i, section.as_ref(), at)
1087 } else {
1088 SectionRead::NotFollowed
1089 });
1090 }
1091 Applied::Read {
1092 gap: read.gap,
1093 sections,
1094 }
1095 }
1096
1097 fn read_section(
1102 &mut self,
1103 i: usize,
1104 section: Option<&crate::heartbeat::Section>,
1105 at: T,
1106 ) -> SectionRead {
1107 use crate::heartbeat::Members;
1108 let Some(s) = section else {
1109 self.diverged[i] = 0;
1110 return SectionRead::Absent;
1111 };
1112 let keys: Vec<String> = self.live(i).map(|(k, _)| k.clone()).collect();
1113 let same_count = match &s.members {
1114 Members::One { .. } => keys.len() <= 1,
1115 m => m.live() == Some(keys.len() as u64),
1116 };
1117 if self.digest(i) != Some(s.digest) || !same_count {
1118 self.diverged[i] = self.diverged[i].saturating_add(1);
1119 return SectionRead::Diverged;
1120 }
1121 self.diverged[i] = 0;
1122 let vouched: Vec<String> = s
1123 .members
1124 .vouched()
1125 .into_iter()
1126 .filter_map(|r| keys.get(usize::try_from(r).ok()?).cloned())
1127 .collect();
1128 for k in &vouched {
1129 if let Some(h) = self.members.get_mut(k) {
1130 h.confirmed = Some(at);
1131 }
1132 }
1133 SectionRead::Confirmed(vouched)
1134 }
1135
1136 pub fn apply_group(
1157 &mut self,
1158 class: crate::heartbeat::Class,
1159 entry: &crate::catalog::Entry,
1160 group: &crate::heartbeat::Group,
1161 time: crate::heartbeat::Time,
1162 at: T,
1163 ) -> GroupRead {
1164 if entry.iface != self.layout.iface || !self.follows_any() {
1165 return GroupRead::NotFollowed;
1166 }
1167 if entry.contract != self.layout.fingerprint || !group.tag_is(&self.layout) {
1168 return GroupRead::Revision;
1169 }
1170 let read = match group.read(&self.layout) {
1171 Ok(s) => s,
1172 Err(r) => return GroupRead::Refused(r),
1173 };
1174 let mut sections = Vec::with_capacity(read.len());
1175 for (i, section) in read.iter().enumerate() {
1176 sections.push(if !self.follows[i] {
1177 SectionRead::NotFollowed
1178 } else if self.layout.collections[i].class != class {
1179 SectionRead::OtherClass
1180 } else {
1181 self.read_section(i, section.as_ref(), at)
1182 });
1183 }
1184 if sections
1190 .iter()
1191 .any(|s| !matches!(s, SectionRead::NotFollowed | SectionRead::OtherClass))
1192 {
1193 self.time = Some(time);
1194 self.heartbeats += 1;
1195 }
1196 GroupRead::Read(sections)
1197 }
1198
1199 pub fn confirm(&mut self, key: &str, at: T) {
1204 let Some(k) = crate::heartbeat::base_relative(key) else {
1205 return;
1206 };
1207 if let Some(h) = self.members.get_mut(k)
1208 && !h.deleted
1209 && h.confirmed.is_none_or(|c| c < at)
1210 {
1211 h.confirmed = Some(at);
1212 }
1213 }
1214
1215 #[must_use]
1217 pub fn confirmed(&self, key: &str) -> Option<T> {
1218 let k = crate::heartbeat::base_relative(key)?;
1219 self.members.get(k).and_then(|h| h.confirmed)
1220 }
1221
1222 #[must_use]
1224 pub fn reread_due(&self) -> Vec<usize> {
1225 (0..self.diverged.len())
1226 .filter(|i| self.follows[*i] && self.diverged[*i] >= 2)
1227 .collect()
1228 }
1229
1230 #[must_use]
1234 pub fn gap(&self) -> bool {
1235 self.seq.gap()
1236 }
1237
1238 #[must_use]
1240 pub fn follows(&self, index: usize) -> bool {
1241 self.follows.get(index).copied().unwrap_or(false)
1242 }
1243
1244 #[must_use]
1248 pub fn classes(&self) -> Vec<crate::heartbeat::Class> {
1249 crate::heartbeat::Class::ALL
1250 .into_iter()
1251 .filter(|c| {
1252 self.layout
1253 .collections
1254 .iter()
1255 .zip(&self.follows)
1256 .any(|(x, f)| *f && x.class == *c)
1257 })
1258 .collect()
1259 }
1260
1261 #[must_use]
1265 pub fn owner_time(&self) -> Option<crate::heartbeat::Time> {
1266 self.time
1267 }
1268
1269 #[must_use]
1272 pub fn last_heartbeat(&self) -> Option<Stamp> {
1273 self.seq.last()
1274 }
1275
1276 #[must_use]
1279 pub fn heartbeats(&self) -> u64 {
1280 self.heartbeats
1281 }
1282
1283 #[must_use]
1287 pub fn last(&self, key: &str, now: T) -> Option<Last> {
1288 let k = crate::heartbeat::base_relative(key)?;
1289 let h = self.members.get(k)?;
1290 Some(if h.deleted {
1291 Last::Delete(now.since(h.at))
1292 } else {
1293 Last::Put(now.since(h.confirmed.map_or(h.at, |c| c.max(h.at))))
1294 })
1295 }
1296
1297 #[must_use]
1302 pub fn observation(
1303 &self,
1304 key: &str,
1305 now: T,
1306 listened: Duration,
1307 complete: bool,
1308 ) -> Observation {
1309 Observation::Subscribed {
1310 last: self.last(key, now),
1311 listened,
1312 complete: complete && !self.seq.gap(),
1313 }
1314 }
1315}
1316
1317#[derive(Debug, Clone, Copy)]
1321pub struct Catalogs<'a> {
1322 pub held: &'a [crate::catalog::Catalog],
1323 pub named: Option<crate::catalog::CatalogId>,
1324}
1325
1326#[derive(Debug, Clone, Default)]
1328struct ClassKey {
1329 seq: Sequence,
1330 named: std::collections::BTreeSet<crate::grammar::IfaceId>,
1333 read: u64,
1334}
1335
1336#[derive(Debug, Clone)]
1354pub struct Views<T> {
1355 views: BTreeMap<crate::grammar::IfaceId, View<T>>,
1356 keys: BTreeMap<crate::heartbeat::Class, ClassKey>,
1357}
1358
1359impl<T> Default for Views<T> {
1360 fn default() -> Self {
1361 Self {
1362 views: BTreeMap::new(),
1363 keys: BTreeMap::new(),
1364 }
1365 }
1366}
1367
1368impl<T: Arrival> Views<T> {
1369 #[must_use]
1371 pub fn new() -> Self {
1372 Self::default()
1373 }
1374
1375 pub fn insert(&mut self, view: View<T>) -> Option<View<T>> {
1377 self.views.insert(view.layout().iface.clone(), view)
1378 }
1379
1380 #[must_use]
1382 pub fn view(&self, iface: &crate::grammar::IfaceId) -> Option<&View<T>> {
1383 self.views.get(iface)
1384 }
1385
1386 pub fn view_mut(&mut self, iface: &crate::grammar::IfaceId) -> Option<&mut View<T>> {
1389 self.views.get_mut(iface)
1390 }
1391
1392 #[must_use]
1395 pub fn view_of(&self, key: &str) -> Option<&View<T>> {
1396 self.views.get(&iface_of(key)?)
1397 }
1398
1399 pub fn view_of_mut(&mut self, key: &str) -> Option<&mut View<T>> {
1401 self.views.get_mut(&iface_of(key)?)
1402 }
1403
1404 pub fn iter(&self) -> impl Iterator<Item = &View<T>> {
1406 self.views.values()
1407 }
1408
1409 #[must_use]
1413 pub fn classes(&self) -> Vec<crate::heartbeat::Class> {
1414 crate::heartbeat::Class::ALL
1415 .into_iter()
1416 .filter(|c| self.views.values().any(|v| v.classes().contains(c)))
1417 .collect()
1418 }
1419
1420 #[must_use]
1426 pub fn class_horizon(&self, class: crate::heartbeat::Class) -> Option<Duration> {
1427 self.views
1428 .values()
1429 .filter_map(|v| v.layout().class_horizon(class))
1430 .min()
1431 }
1432
1433 pub fn apply_owner(
1449 &mut self,
1450 class: crate::heartbeat::Class,
1451 tag: crate::wire::Tag,
1452 stamp: Stamp,
1453 body: &[u8],
1454 through: Catalogs<'_>,
1455 at: T,
1456 ) -> OwnerApplied {
1457 let hb = match crate::heartbeat::OwnerHeartbeat::parse(tag, body) {
1458 Ok(hb) => hb,
1459 Err(r) => return OwnerApplied::Refused(r),
1460 };
1461 let key = self.keys.entry(class).or_default();
1462 let Some(read) = key.seq.read(stamp) else {
1463 return OwnerApplied::Older;
1464 };
1465 if read.run {
1466 key.named.clear();
1469 }
1470 key.read += 1;
1471 let mut groups = Vec::with_capacity(hb.groups.len());
1472 for g in &hb.groups {
1473 let entry = match g.entry(through.held, through.named) {
1474 Ok(e) => e,
1475 Err(r) => {
1476 groups.push(GroupApplied {
1477 index: g.index,
1478 iface: None,
1479 read: GroupRead::Refused(r),
1480 });
1481 continue;
1482 }
1483 };
1484 key.named.insert(entry.iface.clone());
1487 let read = match self.views.get_mut(&entry.iface) {
1488 Some(v) => v.apply_group(class, entry, g, hb.time, at),
1489 None => GroupRead::NotFollowed,
1490 };
1491 groups.push(GroupApplied {
1492 index: g.index,
1493 iface: Some(entry.iface.clone()),
1494 read,
1495 });
1496 }
1497 OwnerApplied::Read {
1498 gap: read.gap,
1499 groups,
1500 }
1501 }
1502
1503 #[must_use]
1507 pub fn gap(&self, class: crate::heartbeat::Class) -> Option<bool> {
1508 let k = self.keys.get(&class)?;
1509 k.seq.last().map(|_| k.seq.gap())
1510 }
1511
1512 #[must_use]
1514 pub fn last(&self, class: crate::heartbeat::Class) -> Option<Stamp> {
1515 self.keys.get(&class)?.seq.last()
1516 }
1517
1518 #[must_use]
1521 pub fn owner_heartbeats(&self, class: crate::heartbeat::Class) -> u64 {
1522 self.keys.get(&class).map_or(0, |k| k.read)
1523 }
1524
1525 #[must_use]
1532 pub fn is_lost(&self, iface: &crate::grammar::IfaceId, index: usize) -> bool {
1533 let Some(v) = self.views.get(iface) else {
1534 return false;
1535 };
1536 if !v.follows(index) {
1537 return false;
1538 }
1539 v.gap()
1540 || self
1541 .keys
1542 .get(&v.layout().collections[index].class)
1543 .is_some_and(|k| k.seq.gap() && k.named.contains(iface))
1544 }
1545
1546 #[must_use]
1549 pub fn lost(&self) -> Vec<(crate::grammar::IfaceId, usize)> {
1550 self.views
1551 .iter()
1552 .flat_map(|(iface, v)| {
1553 (0..v.layout().collections.len())
1554 .filter(|i| self.is_lost(iface, *i))
1555 .map(|i| (iface.clone(), i))
1556 })
1557 .collect()
1558 }
1559
1560 #[must_use]
1565 pub fn observation(
1566 &self,
1567 key: &str,
1568 now: T,
1569 listened: Duration,
1570 complete: bool,
1571 ) -> Option<Observation> {
1572 let v = self.view_of(key)?;
1573 let lost = crate::heartbeat::base_relative(key)
1574 .and_then(|k| v.layout().collection_of(k))
1575 .is_some_and(|i| self.is_lost(&v.layout().iface, i));
1576 Some(v.observation(key, now, listened, complete && !lost))
1577 }
1578}
1579
1580fn iface_of(key: &str) -> Option<crate::grammar::IfaceId> {
1582 match crate::grammar::parse(crate::heartbeat::base_relative(key)?) {
1583 Ok(crate::grammar::ZkKey::Data { iface, .. }) => Some(iface),
1584 _ => None,
1585 }
1586}
1587
1588#[must_use]
1595pub fn confirmed_last(delivered: Option<Last>, heartbeat: Option<Duration>) -> Option<Last> {
1596 match (delivered, heartbeat) {
1597 (Some(Last::Put(a)), Some(h)) => Some(Last::Put(a.min(h))),
1598 (None, Some(h)) => Some(Last::Put(h)),
1599 (d, _) => d,
1600 }
1601}
1602
1603#[cfg(test)]
1604mod tests {
1605 use super::*;
1606 use serde_json::json;
1607
1608 fn ann(v: Value) -> BTreeMap<String, Value> {
1609 BTreeMap::from([(TTL_S.to_owned(), v)])
1610 }
1611
1612 #[test]
1613 fn the_horizon_is_a_whole_number_of_seconds() {
1614 let h = |v: Value| horizon(Kind::State, &ann(v));
1615 assert_eq!(h(json!(60)), Horizon::Within(Duration::from_secs(60)));
1616 assert_eq!(h(json!(60.0)), Horizon::Within(Duration::from_secs(60)));
1617 assert_eq!(h(json!(-0.0)), Horizon::Never);
1618 assert_eq!(h(json!(0)), Horizon::Never);
1619 assert!(matches!(h(json!(1.5)), Horizon::Invalid(_)));
1620 assert!(matches!(h(json!(-1)), Horizon::Invalid(_)));
1621 assert!(matches!(h(json!(MAX_TTL_S + 1)), Horizon::Invalid(_)));
1622 assert_eq!(
1623 horizon(Kind::Event, &ann(json!("x"))),
1624 Horizon::Ignored,
1625 "the kind first"
1626 );
1627 assert_eq!(horizon(Kind::State, &BTreeMap::new()), Horizon::Undeclared);
1628 assert_eq!(
1629 h(json!(61)).refresh_bound(),
1630 Some(Duration::from_millis(30_500))
1631 );
1632 }
1633
1634 #[test]
1635 fn a_trusted_reply_is_judged_in_the_band() {
1636 let h = Horizon::Within(Duration::from_secs(2));
1637 let got = |s: f64| Observation::Got {
1638 reply: Some(Reply::Put {
1639 stamp_age: Some(StampAge::from_secs_f64(s)),
1640 }),
1641 clock: ClockTrust::Trusted {
1642 delta: DEFAULT_DELTA,
1643 },
1644 };
1645 let v = |s: f64| judge(&h, &got(s)).reason;
1646 assert_eq!(v(1.5), Reason::WithinHorizon);
1647 assert_eq!(v(1.6), Reason::NearHorizon);
1648 assert_eq!(v(2.5), Reason::NearHorizon);
1649 assert_eq!(v(2.6), Reason::BeyondHorizon);
1650 assert_eq!(v(-0.5), Reason::WithinHorizon);
1651 assert_eq!(v(-0.6), Reason::ClockDisagrees);
1652 }
1653
1654 #[test]
1655 fn fresh_wins_then_stale_then_unobservable() {
1656 let j = |v, r| Judged::new(v, r);
1657 assert_eq!(
1658 combine([
1659 j(Verdict::Stale, Reason::NoDelivery),
1660 j(Verdict::Fresh, Reason::WithinHorizon)
1661 ])
1662 .verdict,
1663 Verdict::Fresh
1664 );
1665 assert_eq!(
1666 combine([
1667 j(Verdict::Unobservable, Reason::ClockUntrusted),
1668 j(Verdict::Stale, Reason::NoDelivery)
1669 ])
1670 .reason,
1671 Reason::NoDelivery
1672 );
1673 assert_eq!(combine([]).reason, Reason::NoObservation);
1674 }
1675
1676 mod view {
1677 use super::super::*;
1678 use crate::contract::load_str;
1679 use crate::heartbeat::{Digest, Heartbeat, Layout, Members, Section, Time};
1680 use crate::timing::Mono;
1681 use crate::wire::{Run, Seq, Tag};
1682
1683 const HB: &str = r#"
1684[interface]
1685name = "hb"
1686major = 1
1687minor = 0
1688uses = ["freshness.v1"]
1689[resources.link]
1690kind = "state"
1691type = { raw = "text/plain" }
1692annotations = { "freshness.ttl_s" = 2 }
1693[resources."peer/{peer}"]
1694kind = "state"
1695type = { raw = "text/plain" }
1696params = { peer = "string" }
1697cardinality = 5
1698annotations = { "freshness.ttl_s" = 2 }
1699"#;
1700 const LINK: &str = "zk2/lab/n1/hb.v1/state/link";
1701 const A: &str = "zk2/lab/n1/hb.v1/state/peer/a";
1702 const B: &str = "zk2/lab/n1/hb.v1/state/peer/b";
1703
1704 fn layout() -> Layout {
1705 let c = load_str(HB, std::path::Path::new("."), None)
1706 .contract
1707 .unwrap();
1708 Layout::of(&c)
1709 }
1710 fn st(run: u16, seq: u32) -> Stamp {
1711 Stamp {
1712 run: Run::U16(run),
1713 seq: Seq::new(seq).unwrap(),
1714 }
1715 }
1716 fn ms(n: u64) -> Mono {
1717 Mono::after(Duration::from_millis(n))
1718 }
1719 fn body(l: &Layout, link: Option<Section>, peers: Option<Section>) -> Vec<u8> {
1721 Heartbeat {
1722 time: Time::Unknown,
1723 sections: vec![link, peers],
1724 }
1725 .write(l)
1726 .unwrap()
1727 }
1728 fn view() -> View<Mono> {
1729 let mut v = View::new(layout());
1730 assert!(v.follow_resource("state/link"));
1731 assert!(v.follow_resource("state/peer/{peer}"));
1732 assert!(!v.follow_resource("state/nothing"));
1733 v
1734 }
1735
1736 #[test]
1737 fn a_heartbeat_whose_digest_is_the_views_confirms_what_it_vouches_for() {
1738 let l = layout();
1739 let mut v = view();
1740 v.put(LINK, Some(st(1, 1)), ms(0));
1741 v.put(A, Some(st(1, 2)), ms(0));
1742 v.put(B, Some(st(1, 3)), ms(0));
1743 let link = Section {
1744 digest: Digest::of([(LINK, st(1, 1))]),
1745 members: Members::One { vouched: true },
1746 };
1747 let peers = Section {
1748 digest: Digest::of([(A, st(1, 2)), (B, st(1, 3))]),
1749 members: Members::templated(2, [1]),
1750 };
1751 let got = v.apply(
1752 l.tag,
1753 st(9, 0),
1754 &body(&l, Some(link), Some(peers)),
1755 ms(1500),
1756 );
1757 assert_eq!(
1758 got,
1759 Applied::Read {
1760 gap: false,
1761 sections: vec![
1762 SectionRead::Confirmed(vec![LINK.into()]),
1763 SectionRead::Confirmed(vec![B.into()]),
1764 ]
1765 }
1766 );
1767 assert_eq!(v.confirmed(B), Some(ms(1500)));
1768 assert_eq!(v.confirmed(A), None, "not vouched for");
1769 let h = Horizon::Within(Duration::from_secs(2));
1771 let j = |k: &str| {
1772 judge(
1773 &h,
1774 &v.observation(k, ms(3000), Duration::from_secs(3), true),
1775 )
1776 };
1777 assert_eq!(j(LINK).verdict, Verdict::Fresh);
1778 assert_eq!(j(B).verdict, Verdict::Fresh);
1779 assert_eq!(
1780 j(A).verdict,
1781 Verdict::Stale,
1782 "a cleared bit is no confirmation"
1783 );
1784 assert_eq!(v.confirmed(&format!("prod/{LINK}")), Some(ms(1500)));
1786 }
1787
1788 #[test]
1789 fn a_missed_change_diverges_and_two_in_a_row_are_due_a_read() {
1790 let l = layout();
1791 let mut v = view();
1792 v.put(A, Some(st(1, 2)), ms(0));
1793 let owner = Digest::of([(A, st(1, 5)), (B, st(1, 6))]);
1795 let sec = || Section {
1796 digest: owner,
1797 members: Members::templated(2, [0, 1]),
1798 };
1799 for (seq, due) in [(0, false), (1, true)] {
1800 let got = v.apply(l.tag, st(9, seq), &body(&l, None, Some(sec())), ms(1000));
1801 assert_eq!(
1802 got,
1803 Applied::Read {
1804 gap: false,
1805 sections: vec![SectionRead::Absent, SectionRead::Diverged]
1806 }
1807 );
1808 assert_eq!(v.reread_due() == vec![1], due);
1809 }
1810 assert_eq!(v.confirmed(A), None);
1811 v.replace(1, [(A, Some(st(1, 5))), (B, Some(st(1, 6)))], ms(1100));
1813 assert!(v.reread_due().is_empty());
1814 let got = v.apply(l.tag, st(9, 2), &body(&l, None, Some(sec())), ms(1200));
1815 assert_eq!(
1816 got,
1817 Applied::Read {
1818 gap: false,
1819 sections: vec![
1820 SectionRead::Absent,
1821 SectionRead::Confirmed(vec![A.into(), B.into()])
1822 ]
1823 }
1824 );
1825 }
1826
1827 #[test]
1828 fn a_deleted_member_leaves_the_digest_and_a_stale_put_is_not_taken() {
1829 let mut v = view();
1830 v.put(A, Some(st(1, 4)), ms(0));
1831 v.put(A, Some(st(1, 3)), ms(10));
1832 assert_eq!(v.digest(1), Some(Digest::of([(A, st(1, 4))])));
1833 v.delete(A, Some(st(1, 5)), ms(20));
1834 assert_eq!(v.digest(1), Some(Digest::EMPTY));
1835 assert_eq!(
1836 v.last(A, ms(30)),
1837 Some(Last::Delete(Duration::from_millis(10)))
1838 );
1839 v.put(A, Some(st(2, 0)), ms(40));
1841 assert_eq!(v.digest(1), Some(Digest::of([(A, st(2, 0))])));
1842 v.put(B, None, ms(50));
1844 assert_eq!(v.digest(1), None);
1845 v.put("zk2/lab/n1/hb.v1/state/other", Some(st(1, 1)), ms(60));
1847 assert_eq!(v.last("zk2/lab/n1/hb.v1/state/other", ms(70)), None);
1848 }
1849
1850 #[test]
1851 fn a_gap_is_a_heartbeat_lost_and_the_tag_and_the_order_guard() {
1852 let l = layout();
1853 let mut v = view();
1854 v.put(LINK, Some(st(1, 1)), ms(0));
1855 let link = || {
1856 Some(Section {
1857 digest: Digest::of([(LINK, st(1, 1))]),
1858 members: Members::One { vouched: true },
1859 })
1860 };
1861 let b = body(&l, link(), None);
1862 let other = Tag::new((l.tag.get() + 1) % 16).unwrap();
1863 assert_eq!(v.apply(other, st(9, 0), &b, ms(100)), Applied::Revision);
1864 assert!(matches!(
1865 v.apply(l.tag, st(9, 0), &b, ms(100)),
1866 Applied::Read { gap: false, .. }
1867 ));
1868 assert!(matches!(
1869 v.apply(l.tag, st(9, 3), &b, ms(200)),
1870 Applied::Read { gap: true, .. }
1871 ));
1872 assert!(v.gap());
1873 let o = v.observation(LINK, ms(5000), Duration::from_secs(5), true);
1874 assert_eq!(
1875 judge(&Horizon::Within(Duration::from_secs(2)), &o).reason,
1876 Reason::Incomplete
1877 );
1878 assert_eq!(v.apply(l.tag, st(9, 3), &b, ms(300)), Applied::Older);
1879 assert_eq!(v.apply(l.tag, st(9, 1), &b, ms(300)), Applied::Older);
1880 assert!(matches!(
1881 v.apply(l.tag, st(9, 4), &b, ms(400)),
1882 Applied::Read { gap: false, .. }
1883 ));
1884 assert!(!v.gap());
1885 assert!(matches!(
1887 v.apply(l.tag, st(10, 0), &b, ms(500)),
1888 Applied::Read { gap: false, .. }
1889 ));
1890 assert!(matches!(
1892 v.apply(l.tag, st(10, 1), &b[..2], ms(600)),
1893 Applied::Refused(_)
1894 ));
1895 assert_eq!(v.heartbeats(), 4);
1896 }
1897 }
1898
1899 mod views {
1902 use super::super::*;
1903 use crate::catalog::Catalog;
1904 use crate::contract::load_str;
1905 use crate::heartbeat::{
1906 Class, Digest, Group, GroupRefusal, Layout, Members, OwnerHeartbeat, Section, Time,
1907 };
1908 use crate::timing::Mono;
1909 use crate::wire::{Run, Seq, Tag};
1910
1911 const MIXED: &str = r#"
1912[interface]
1913name = "mixed"
1914major = 1
1915minor = 0
1916uses = ["freshness.v2", "link.v1"]
1917[resources."peer/{peer}"]
1918kind = "state"
1919type = { raw = "text/plain" }
1920params = { peer = "string" }
1921cardinality = 8
1922annotations = { "freshness.ttl_s" = 120 }
1923[resources.status]
1924kind = "state"
1925type = { raw = "text/plain" }
1926annotations = { "freshness.ttl_s" = 60, "link.exposure" = "link" }
1927"#;
1928 const VITAL: &str = r#"
1929[interface]
1930name = "vital"
1931major = 1
1932minor = 0
1933uses = ["freshness.v2"]
1934[resources.status]
1935kind = "state"
1936type = { raw = "text/plain" }
1937annotations = { "freshness.ttl_s" = 60 }
1938"#;
1939 const PEER: &str = "zk2/lab/n1/mixed.v1/state/peer/p1";
1940 const STATUS: &str = "zk2/lab/n1/mixed.v1/state/status";
1941 const VITALS: &str = "zk2/lab/n1/vital.v1/state/status";
1942
1943 fn layout(text: &str) -> Layout {
1944 Layout::of(
1945 &load_str(text, std::path::Path::new("."), None)
1946 .contract
1947 .unwrap(),
1948 )
1949 }
1950 fn st(run: u16, seq: u32) -> Stamp {
1951 Stamp {
1952 run: Run::U16(run),
1953 seq: Seq::new(seq).unwrap(),
1954 }
1955 }
1956 fn ms(n: u64) -> Mono {
1957 Mono::after(Duration::from_millis(n))
1958 }
1959 fn catalog(mixed: &Layout, vital: &Layout) -> Catalog {
1961 let mut c = Catalog::new(0).unwrap();
1962 c.push(mixed.iface.clone(), mixed.fingerprint.clone())
1963 .unwrap();
1964 c.push(vital.iface.clone(), vital.fingerprint.clone())
1965 .unwrap();
1966 c
1967 }
1968 fn one(key: &str, stamp: Stamp) -> Option<Section> {
1969 Some(Section {
1970 digest: Digest::of([(key, stamp)]),
1971 members: Members::One { vouched: true },
1972 })
1973 }
1974 fn mixed_host(l: &Layout) -> Group {
1977 let peers = Section {
1978 digest: Digest::of([(PEER, st(1, 1))]),
1979 members: Members::templated(1, [0]),
1980 };
1981 Group::of(0, l, &[Some(peers), None]).unwrap()
1982 }
1983 fn vital_host(l: &Layout) -> Group {
1984 Group::of(1, l, &[one(VITALS, st(1, 3))]).unwrap()
1985 }
1986 fn body(groups: Vec<Group>) -> Vec<u8> {
1987 OwnerHeartbeat {
1988 time: Time::Unknown,
1989 groups,
1990 }
1991 .write()
1992 .unwrap()
1993 }
1994 fn views(mixed: &Layout, vital: &Layout) -> Views<Mono> {
1996 let mut vs = Views::new();
1997 for l in [mixed, vital] {
1998 let mut v = View::new(l.clone());
1999 for i in 0..l.collections.len() {
2000 assert!(v.follow(i));
2001 }
2002 assert!(vs.insert(v).is_none());
2003 }
2004 vs.view_of_mut(PEER)
2005 .unwrap()
2006 .put(PEER, Some(st(1, 1)), ms(0));
2007 vs.view_of_mut(STATUS)
2008 .unwrap()
2009 .put(STATUS, Some(st(1, 2)), ms(0));
2010 vs.view_of_mut(VITALS)
2011 .unwrap()
2012 .put(VITALS, Some(st(1, 3)), ms(0));
2013 vs
2014 }
2015
2016 #[test]
2017 fn a_class_is_the_exposure_and_a_key_is_one_classs() {
2018 let (mixed, vital) = (layout(MIXED), layout(VITAL));
2019 assert_eq!(
2020 mixed
2021 .collections
2022 .iter()
2023 .map(|c| c.class)
2024 .collect::<Vec<_>>(),
2025 vec![Class::Host, Class::Link]
2026 );
2027 assert_eq!(mixed.classes(), vec![Class::Link, Class::Host]);
2028 assert_eq!(vital.classes(), vec![Class::Host]);
2029 assert_eq!(
2030 mixed.class_horizon(Class::Link),
2031 Some(Duration::from_secs(60))
2032 );
2033 assert_eq!(
2034 mixed.class_horizon(Class::Host),
2035 Some(Duration::from_secs(120))
2036 );
2037 assert_eq!(vital.class_horizon(Class::Link), None);
2038 let mut v = View::<Mono>::new(mixed.clone());
2040 assert!(v.classes().is_empty());
2041 assert!(v.follow_resource("state/status"));
2042 assert_eq!(v.classes(), vec![Class::Link]);
2043 let vs = views(&mixed, &vital);
2044 assert_eq!(vs.classes(), vec![Class::Link, Class::Host]);
2045 }
2046
2047 #[test]
2053 fn a_group_on_the_other_classs_key_is_no_heartbeat_applied() {
2054 let (mixed, vital) = (layout(MIXED), layout(VITAL));
2055 let cat = catalog(&mixed, &vital);
2056 let through = Catalogs {
2057 held: std::slice::from_ref(&cat),
2058 named: Some(cat.id()),
2059 };
2060 let mut v = View::new(mixed.clone());
2062 assert!(v.follow_resource("state/status"));
2063 v.put(STATUS, Some(st(1, 2)), ms(0));
2064 let mut vs = Views::new();
2065 vs.insert(v);
2066 let known = Time::At { secs: 7, ms: 0 };
2067 let put = |g: Group| {
2068 OwnerHeartbeat {
2069 time: known,
2070 groups: vec![g],
2071 }
2072 .write()
2073 .unwrap()
2074 };
2075 let host = vs.apply_owner(
2077 Class::Host,
2078 Tag::new(0).unwrap(),
2079 st(9, 0),
2080 &put(mixed_host(&mixed)),
2081 through,
2082 ms(10),
2083 );
2084 let OwnerApplied::Read { groups, .. } = host else {
2085 panic!("read: {host:?}");
2086 };
2087 assert_eq!(
2088 groups[0].read,
2089 GroupRead::Read(vec![SectionRead::NotFollowed, SectionRead::OtherClass])
2090 );
2091 let view = vs.view(&mixed.iface).unwrap();
2092 assert_eq!(view.heartbeats(), 0, "no section read, none applied");
2093 assert_eq!(view.owner_time(), None);
2094 assert_eq!(vs.owner_heartbeats(Class::Host), 1, "read on its key");
2095 let link = Group::of(0, &mixed, &[None, one(STATUS, st(1, 2))]).unwrap();
2097 let applied = vs.apply_owner(
2098 Class::Link,
2099 Tag::new(0).unwrap(),
2100 st(9, 0),
2101 &put(link),
2102 through,
2103 ms(20),
2104 );
2105 let OwnerApplied::Read { groups, .. } = applied else {
2106 panic!("read: {applied:?}");
2107 };
2108 assert_eq!(
2109 groups[0].read,
2110 GroupRead::Read(vec![
2111 SectionRead::NotFollowed,
2112 SectionRead::Confirmed(vec![STATUS.to_owned()])
2113 ])
2114 );
2115 let view = vs.view(&mixed.iface).unwrap();
2116 assert_eq!(view.heartbeats(), 1);
2117 assert_eq!(view.owner_time(), Some(known));
2118 let absent = Group::of(0, &mixed, &[None, None]).unwrap();
2121 vs.apply_owner(
2122 Class::Link,
2123 Tag::new(0).unwrap(),
2124 st(9, 1),
2125 &put(absent),
2126 through,
2127 ms(30),
2128 );
2129 assert_eq!(vs.view(&mixed.iface).unwrap().heartbeats(), 2);
2130 }
2131
2132 #[test]
2133 fn a_sequence_is_its_keys_alone() {
2134 let mut s = Sequence::default();
2135 let first = s.read(st(9, 5)).unwrap();
2136 assert!(!first.gap && !first.run);
2137 assert_eq!(s.read(st(9, 5)), None, "the same seq");
2138 assert_eq!(s.read(st(9, 4)), None, "an earlier one");
2139 assert_eq!(s.read(st(9, 5 + (1 << 23))), None, "2^23 ahead, unordered");
2140 assert_eq!(s.last(), Some(st(9, 5)), "an older one moves nothing");
2141 assert!(!s.read(st(9, 6)).unwrap().gap);
2142 assert!(s.read(st(9, 8)).unwrap().gap);
2143 assert!(s.gap());
2144 let other = s.read(st(10, 3)).unwrap();
2145 assert!(other.run && !other.gap, "another run starts it again");
2146 assert!(!s.gap());
2147 let mut s = Sequence::default();
2149 s.read(st(9, Seq::MAX.get())).unwrap();
2150 assert!(!s.read(st(9, 0)).unwrap().gap);
2151 }
2152
2153 #[test]
2154 fn a_gap_loses_what_a_group_on_the_key_named_within_the_run() {
2155 let (mixed, vital) = (layout(MIXED), layout(VITAL));
2156 let held = [catalog(&mixed, &vital)];
2157 let named = Some(held[0].id());
2158 let mut vs = views(&mixed, &vital);
2159 let alone = body(vec![mixed_host(&mixed)]);
2160 let both = body(vec![mixed_host(&mixed), vital_host(&vital)]);
2161 let through = Catalogs { held: &held, named };
2162 let host = |vs: &mut Views<Mono>, stamp, body: &[u8], at| match vs.apply_owner(
2163 Class::Host,
2164 Tag::NONE,
2165 stamp,
2166 body,
2167 through,
2168 ms(at),
2169 ) {
2170 OwnerApplied::Read { gap, .. } => gap,
2171 other => panic!("{other:?}"),
2172 };
2173 let lost = |vs: &Views<Mono>| -> Vec<(String, usize)> {
2174 vs.lost()
2175 .into_iter()
2176 .map(|(i, c)| (i.to_string(), c))
2177 .collect()
2178 };
2179 assert!(!host(&mut vs, st(9, 0), &alone, 100));
2182 assert!(host(&mut vs, st(9, 2), &alone, 200));
2183 assert_eq!(lost(&vs), vec![("mixed.v1".to_owned(), 0)]);
2184 assert!(vs.is_lost(&mixed.iface, 0));
2185 assert!(!vs.is_lost(&mixed.iface, 1), "a `link` collection");
2186 assert!(!vs.is_lost(&vital.iface, 0), "not named on the key");
2187 let o = |vs: &Views<Mono>, key| {
2189 let o = vs
2190 .observation(key, ms(250), Duration::from_secs(1), true)
2191 .unwrap();
2192 matches!(o, Observation::Subscribed { complete: true, .. })
2193 };
2194 assert!(!o(&vs, PEER));
2195 assert!(o(&vs, STATUS));
2196 assert!(o(&vs, VITALS));
2197 assert_eq!(vs.gap(Class::Host), Some(true));
2198 assert_eq!(vs.gap(Class::Link), None, "nothing read on the `link` key");
2199 assert!(!host(&mut vs, st(9, 3), &both, 300));
2201 assert!(lost(&vs).is_empty());
2202 assert!(host(&mut vs, st(9, 5), &alone, 400));
2205 assert_eq!(
2206 lost(&vs),
2207 vec![("mixed.v1".to_owned(), 0), ("vital.v1".to_owned(), 0)]
2208 );
2209 assert!(!host(&mut vs, st(10, 0), &alone, 500));
2212 assert!(lost(&vs).is_empty());
2213 assert!(host(&mut vs, st(10, 2), &alone, 600));
2214 assert_eq!(lost(&vs), vec![("mixed.v1".to_owned(), 0)]);
2215 assert_eq!(vs.owner_heartbeats(Class::Host), 6);
2216 assert_eq!(vs.last(Class::Host), Some(st(10, 2)));
2217 assert!(
2219 vs.observation(
2220 "zk2/lab/n1/other.v1/state/x",
2221 ms(700),
2222 Duration::from_secs(1),
2223 true
2224 )
2225 .is_none()
2226 );
2227 }
2228
2229 #[test]
2230 fn a_group_stops_at_the_first_step_that_answers() {
2231 let (mixed, vital) = (layout(MIXED), layout(VITAL));
2232 let cat = catalog(&mixed, &vital);
2233 let (e_mixed, e_vital) = (cat.entry(0).unwrap(), cat.entry(1).unwrap());
2234 let mut v = View::<Mono>::new(vital.clone());
2235 let g = vital_host(&vital);
2236 assert_eq!(
2239 v.apply_group(Class::Host, e_vital, &g, Time::Unknown, ms(1)),
2240 GroupRead::NotFollowed
2241 );
2242 assert!(v.follow(0));
2243 v.put(VITALS, Some(st(1, 3)), ms(0));
2244 assert_eq!(
2245 v.apply_group(Class::Host, e_mixed, &g, Time::Unknown, ms(1)),
2246 GroupRead::NotFollowed
2247 );
2248 let elsewhere = crate::catalog::Entry {
2250 iface: vital.iface.clone(),
2251 contract: mixed.fingerprint.clone(),
2252 };
2253 assert_eq!(
2254 v.apply_group(Class::Host, &elsewhere, &g, Time::Unknown, ms(1)),
2255 GroupRead::Revision
2256 );
2257 let mut retagged = g.clone();
2258 retagged.tag = Tag::new((vital.tag.get() + 1) % 16).unwrap();
2259 assert_eq!(
2260 v.apply_group(Class::Host, e_vital, &retagged, Time::Unknown, ms(1)),
2261 GroupRead::Revision
2262 );
2263 let diverged = Group::of(1, &vital, &[one(VITALS, st(1, 4))]).unwrap();
2267 assert_eq!(
2268 v.apply_group(Class::Host, e_vital, &diverged, Time::Unknown, ms(2)),
2269 GroupRead::Read(vec![SectionRead::Diverged])
2270 );
2271 let mut short = g.clone();
2272 short.sections.bits -= 1;
2273 assert_eq!(
2274 v.apply_group(Class::Host, e_vital, &short, Time::Unknown, ms(3)),
2275 GroupRead::Refused(GroupRefusal::Short)
2276 );
2277 assert!(v.reread_due().is_empty());
2278 assert_eq!(
2279 v.apply_group(Class::Host, e_vital, &diverged, Time::Unknown, ms(4)),
2280 GroupRead::Read(vec![SectionRead::Diverged])
2281 );
2282 assert_eq!(v.reread_due(), vec![0]);
2283 assert_eq!(
2286 v.apply_group(Class::Link, e_vital, &g, Time::Unknown, ms(5)),
2287 GroupRead::Read(vec![SectionRead::OtherClass])
2288 );
2289 assert_eq!(v.reread_due(), vec![0]);
2290 assert_eq!(v.confirmed(VITALS), None);
2291 assert_eq!(
2292 v.apply_group(Class::Host, e_vital, &g, Time::Unknown, ms(6)),
2293 GroupRead::Read(vec![SectionRead::Confirmed(vec![VITALS.to_owned()])])
2294 );
2295 assert_eq!(v.confirmed(VITALS), Some(ms(6)));
2296 assert!(v.reread_due().is_empty());
2297 assert_eq!(v.last_heartbeat(), None);
2299 assert!(!v.gap());
2300 }
2301
2302 #[test]
2303 fn an_owner_heartbeat_key_names_its_class() {
2304 use crate::heartbeat::{covered, owner_class, owner_key};
2305 let k = owner_key("lab", "n1", Class::Link);
2306 assert_eq!(k, "zk2/lab/n1/freshness.v2/stream/heartbeats/link");
2307 let (addr, class) = owner_class(&format!("ns/{k}")).unwrap();
2308 assert_eq!((addr.to_string().as_str(), class), ("lab/n1", Class::Link));
2309 assert_eq!(
2310 owner_class("zk2/lab/n1/freshness.v2/stream/heartbeats/host").map(|x| x.1),
2311 Some(Class::Host)
2312 );
2313 assert!(owner_class("zk2/lab/n1/freshness.v2/stream/heartbeats/near").is_none());
2315 assert!(owner_class("zk2/lab/n1/freshness.v2/stream/heartbeat/link.v1").is_none());
2316 assert!(covered(&k).is_none());
2317 }
2318 }
2319
2320 #[test]
2321 fn a_measured_offset_trusts_within_the_delta_either_way() {
2322 let d = DEFAULT_DELTA;
2323 assert!(matches!(
2324 ClockTrust::measured(StampAge::ahead(d), d),
2325 ClockTrust::Trusted { .. }
2326 ));
2327 assert_eq!(
2328 ClockTrust::measured(StampAge::behind(Duration::from_millis(501)), d),
2329 ClockTrust::Untrusted
2330 );
2331 }
2332}