use std::collections::BTreeMap;
use std::fmt;
use std::time::{Duration, SystemTime};
use serde_json::Value;
use crate::authoring::Kind;
use crate::contract::Resource;
use crate::wire::Stamp;
pub const PROFILE: &str = "freshness.v1";
pub const PROFILE_V2: &str = crate::heartbeat::PROFILE;
#[must_use]
pub fn uses_v2(c: &crate::contract::Contract) -> bool {
c.uses.iter().any(|u| u.to_string() == PROFILE_V2)
}
pub const NAME: &str = "freshness";
pub const TTL_S: &str = "freshness.ttl_s";
pub const VOCABULARY: &[&str] = &["ttl_s"];
pub const MAX_TTL_S: u64 = (1 << 53) - 1;
pub const DEFAULT_DELTA: Duration = Duration::from_millis(500);
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Horizon {
Undeclared,
Ignored,
Invalid(String),
Never,
Within(Duration),
}
impl Horizon {
#[must_use]
pub fn ttl(&self) -> Option<Duration> {
match self {
Self::Within(t) => Some(*t),
_ => None,
}
}
#[must_use]
pub fn refresh_bound(&self) -> Option<Duration> {
self.ttl().map(|t| t / 2)
}
}
impl fmt::Display for Horizon {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Undeclared => f.write_str("no horizon"),
Self::Ignored => f.write_str("a horizon this kind ignores"),
Self::Invalid(v) => write!(f, "{v}, not a horizon"),
Self::Never => f.write_str("ttl_s = 0, never stale"),
Self::Within(t) => write!(f, "ttl_s = {}", t.as_secs()),
}
}
}
#[must_use]
pub fn horizon(kind: Kind, annotations: &BTreeMap<String, Value>) -> Horizon {
let Some(v) = annotations.get(TTL_S) else {
return Horizon::Undeclared;
};
if matches!(kind, Kind::Event | Kind::Operation) {
return Horizon::Ignored;
}
match seconds(v) {
Some(0) => Horizon::Never,
Some(n) => Horizon::Within(Duration::from_secs(n)),
None => Horizon::Invalid(v.to_string()),
}
}
#[must_use]
pub fn horizon_of(r: &Resource) -> Horizon {
horizon(r.kind, &r.annotations)
}
fn seconds(v: &Value) -> Option<u64> {
let n = v.as_number()?;
if let Some(u) = n.as_u64() {
return (u <= MAX_TTL_S).then_some(u);
}
if n.is_i64() {
return None;
}
let f = n.as_f64()?;
let max = MAX_TTL_S as f64;
(f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= max).then_some(f as u64)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StampAge(i128);
impl StampAge {
#[must_use]
pub fn between(stamp: SystemTime, now: SystemTime) -> Self {
match now.duration_since(stamp) {
Ok(d) => Self::behind(d),
Err(e) => Self::ahead(e.duration()),
}
}
#[must_use]
pub fn behind(d: Duration) -> Self {
Self(d.as_nanos() as i128)
}
#[must_use]
pub fn ahead(d: Duration) -> Self {
Self(-(d.as_nanos() as i128))
}
#[must_use]
pub fn from_secs_f64(s: f64) -> Self {
Self((s * 1e9).round() as i128)
}
#[must_use]
pub fn as_secs_f64(self) -> f64 {
self.0 as f64 / 1e9
}
#[must_use]
pub fn nanos(self) -> i128 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClockTrust {
Trusted { delta: Duration },
Untrusted,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClockMeasure {
closest: StampAge,
most_ahead: StampAge,
}
impl ClockMeasure {
#[must_use]
pub fn new(offset: StampAge) -> Self {
Self {
closest: offset,
most_ahead: offset,
}
}
pub fn record(&mut self, offset: StampAge) {
if offset.nanos().unsigned_abs() < self.closest.nanos().unsigned_abs() {
self.closest = offset;
}
if offset < self.most_ahead {
self.most_ahead = offset;
}
}
#[must_use]
pub fn merge(mut self, other: Self) -> Self {
self.record(other.closest);
self.record(other.most_ahead);
self
}
#[must_use]
pub fn closest(&self) -> StampAge {
self.closest
}
#[must_use]
pub fn most_ahead(&self) -> StampAge {
self.most_ahead
}
#[must_use]
pub fn trust(&self, delta: Duration) -> ClockTrust {
let d = delta.as_nanos() as i128;
if self.closest.nanos().unsigned_abs() <= delta.as_nanos() && self.most_ahead.nanos() >= -d
{
ClockTrust::Trusted { delta }
} else {
ClockTrust::Untrusted
}
}
}
impl ClockTrust {
#[must_use]
pub fn from_offsets(offsets: impl IntoIterator<Item = StampAge>, delta: Duration) -> Self {
let mut it = offsets.into_iter();
let Some(first) = it.next() else {
return Self::Untrusted;
};
let mut m = ClockMeasure::new(first);
it.for_each(|o| m.record(o));
m.trust(delta)
}
#[must_use]
pub fn measured(offset: StampAge, delta: Duration) -> Self {
if offset.0.unsigned_abs() <= delta.as_nanos() {
Self::Trusted { delta }
} else {
Self::Untrusted
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Last {
Put(Duration),
Delete(Duration),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reply {
Put { stamp_age: Option<StampAge> },
Delete,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Observation {
Subscribed {
last: Option<Last>,
listened: Duration,
complete: bool,
},
Got {
reply: Option<Reply>,
clock: ClockTrust,
},
Archived,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Entry {
Omitted,
Tombstone,
Live { stamp_age: Option<StampAge> },
}
impl Observation {
#[must_use]
pub fn of_entry(complete: bool, entry: Entry, clock: ClockTrust) -> Observation {
let reply = match entry {
Entry::Omitted if !complete => None,
Entry::Omitted | Entry::Tombstone => Some(Reply::Delete),
Entry::Live { stamp_age } => Some(Reply::Put { stamp_age }),
};
Observation::Got { reply, clock }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Verdict {
Fresh,
Stale,
Unobservable,
NotAsked,
}
impl Verdict {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Fresh => "fresh",
Self::Stale => "stale",
Self::Unobservable => "unobservable",
Self::NotAsked => "not_asked",
}
}
}
impl fmt::Display for Verdict {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Reason {
WithinHorizon,
NeverStale,
BeyondHorizon,
NoDelivery,
NotAHorizon,
ListenedTooShort,
Incomplete,
Silent,
NoStamp,
ClockUntrusted,
ClockDisagrees,
NearHorizon,
NoObservation,
NoHorizon,
Kind,
LastKnown,
Deleted,
}
impl Reason {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::WithinHorizon => "within_horizon",
Self::NeverStale => "never_stale",
Self::BeyondHorizon => "beyond_horizon",
Self::NoDelivery => "no_delivery",
Self::NotAHorizon => "not_a_horizon",
Self::ListenedTooShort => "listened_too_short",
Self::Incomplete => "incomplete",
Self::Silent => "silent",
Self::NoStamp => "no_stamp",
Self::ClockUntrusted => "clock_untrusted",
Self::ClockDisagrees => "clock_disagrees",
Self::NearHorizon => "near_horizon",
Self::NoObservation => "no_observation",
Self::NoHorizon => "no_horizon",
Self::Kind => "kind",
Self::LastKnown => "last_known",
Self::Deleted => "deleted",
}
}
#[must_use]
pub fn says(self) -> &'static str {
match self {
Self::WithinHorizon => "confirmed within its horizon",
Self::NeverStale => "ttl_s = 0, never stale",
Self::BeyondHorizon => "not confirmed within its horizon",
Self::NoDelivery => "nothing delivered for longer than its horizon",
Self::NotAHorizon => "its freshness.ttl_s is not a horizon",
Self::ListenedTooShort => {
"nothing delivered, and not listened to for longer than its horizon"
}
Self::Incomplete => "deliveries were lost, and none within the horizon arrived",
Self::Silent => "no value was read",
Self::NoStamp => "the reply carries no stamp",
Self::ClockUntrusted => {
"this reader's clock is not trusted to the HLC delta against the stamping clock"
}
Self::ClockDisagrees => "the stamp is ahead of this reader's clock beyond the delta",
Self::NearHorizon => "the age is within the delta of the horizon",
Self::NoObservation => "nothing was observed",
Self::NoHorizon => "no freshness.ttl_s, so freshness is not asked",
Self::Kind => "an event or an operation has no freshness",
Self::LastKnown => "an archive's last-known value is never current",
Self::Deleted => "deleted, so no value",
}
}
}
impl fmt::Display for Reason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Judged {
pub verdict: Verdict,
pub reason: Reason,
}
impl Judged {
const fn new(verdict: Verdict, reason: Reason) -> Self {
Self { verdict, reason }
}
}
#[must_use]
pub fn judge(h: &Horizon, o: &Observation) -> Judged {
use Reason as R;
use Verdict as V;
match h {
Horizon::Undeclared => return Judged::new(V::NotAsked, R::NoHorizon),
Horizon::Ignored => return Judged::new(V::NotAsked, R::Kind),
_ => {}
}
if matches!(o, Observation::Archived) {
return Judged::new(V::NotAsked, R::LastKnown);
}
let ttl = match h {
Horizon::Invalid(_) => return Judged::new(V::Unobservable, R::NotAHorizon),
Horizon::Never => None,
Horizon::Within(t) => Some(*t),
Horizon::Undeclared | Horizon::Ignored => unreachable!("returned above"),
};
match (*o, ttl) {
(Observation::Archived, _) => unreachable!("returned above"),
(
Observation::Subscribed {
last: Some(Last::Delete(_)),
..
},
_,
) => Judged::new(V::NotAsked, R::Deleted),
(Observation::Subscribed { .. }, None) => Judged::new(V::Fresh, R::NeverStale),
(
Observation::Subscribed {
last,
listened,
complete,
},
Some(ttl),
) => match last {
Some(Last::Put(a)) if a <= ttl => Judged::new(V::Fresh, R::WithinHorizon),
_ if !complete => Judged::new(V::Unobservable, R::Incomplete),
Some(_) => Judged::new(V::Stale, R::BeyondHorizon),
None if listened > ttl => Judged::new(V::Stale, R::NoDelivery),
None => Judged::new(V::Unobservable, R::ListenedTooShort),
},
(Observation::Got { reply: None, .. }, _) => Judged::new(V::Unobservable, R::Silent),
(
Observation::Got {
reply: Some(Reply::Delete),
..
},
_,
) => Judged::new(V::NotAsked, R::Deleted),
(Observation::Got { .. }, None) => Judged::new(V::Fresh, R::NeverStale),
(
Observation::Got {
reply: Some(Reply::Put { stamp_age }),
clock,
},
Some(ttl),
) => {
let Some(age) = stamp_age else {
return Judged::new(V::Unobservable, R::NoStamp);
};
let ClockTrust::Trusted { delta } = clock else {
return Judged::new(V::Unobservable, R::ClockUntrusted);
};
let (a, t, d) = (age.0, ttl.as_nanos() as i128, delta.as_nanos() as i128);
if a < -d {
Judged::new(V::Unobservable, R::ClockDisagrees)
} else if a + d <= t {
Judged::new(V::Fresh, R::WithinHorizon)
} else if a - d > t {
Judged::new(V::Stale, R::BeyondHorizon)
} else {
Judged::new(V::Unobservable, R::NearHorizon)
}
}
}
}
#[must_use]
pub fn combine(judged: impl IntoIterator<Item = Judged>) -> Judged {
let rank = |v: Verdict| match v {
Verdict::Fresh => 0,
Verdict::Stale => 1,
Verdict::Unobservable => 2,
Verdict::NotAsked => 3,
};
judged
.into_iter()
.fold(None, |best: Option<Judged>, j| match best {
Some(b) if rank(b.verdict) <= rank(j.verdict) => Some(b),
_ => Some(j),
})
.unwrap_or(Judged::new(Verdict::Unobservable, Reason::NoObservation))
}
#[must_use]
pub fn judge_all(h: &Horizon, observations: &[Observation]) -> Judged {
if observations.is_empty() {
return match h {
Horizon::Undeclared => Judged::new(Verdict::NotAsked, Reason::NoHorizon),
Horizon::Ignored => Judged::new(Verdict::NotAsked, Reason::Kind),
Horizon::Invalid(_) => Judged::new(Verdict::Unobservable, Reason::NotAHorizon),
Horizon::Never | Horizon::Within(_) => {
Judged::new(Verdict::Unobservable, Reason::NoObservation)
}
};
}
combine(observations.iter().map(|o| judge(h, o)))
}
pub trait Arrival: Copy + Ord {
fn since(self, earlier: Self) -> Duration;
}
impl Arrival for std::time::Instant {
fn since(self, earlier: Self) -> Duration {
self.saturating_duration_since(earlier)
}
}
impl Arrival for crate::timing::Mono {
fn since(self, earlier: Self) -> Duration {
self.saturating_since(earlier)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Held<T> {
collection: usize,
stamp: Option<Stamp>,
deleted: bool,
at: T,
confirmed: Option<T>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SectionRead {
NotFollowed,
OtherClass,
Absent,
Diverged,
Confirmed(Vec<String>),
}
impl SectionRead {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::NotFollowed => "not_followed",
Self::OtherClass => "other_class",
Self::Absent => "absent",
Self::Diverged => "diverged",
Self::Confirmed(_) => "confirmed",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Applied {
Revision,
Refused(crate::heartbeat::BodyRefusal),
Older,
Read {
gap: bool,
sections: Vec<SectionRead>,
},
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Sequence {
last: Option<Stamp>,
gap: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Sequenced {
pub gap: bool,
pub run: bool,
}
impl Sequence {
pub fn read(&mut self, stamp: Stamp) -> Option<Sequenced> {
let read = match self.last {
Some(l) if l.run == stamp.run => {
match crate::seed::Order::Serial.seqs(l.seq, stamp.seq) {
Some(std::cmp::Ordering::Greater) => Sequenced {
gap: stamp.seq.get().wrapping_sub(l.seq.get())
& crate::wire::Seq::MAX.get()
!= 1,
run: false,
},
_ => return None,
}
}
Some(_) => Sequenced {
gap: false,
run: true,
},
None => Sequenced {
gap: false,
run: false,
},
};
self.last = Some(stamp);
self.gap = read.gap;
Some(read)
}
#[must_use]
pub fn last(&self) -> Option<Stamp> {
self.last
}
#[must_use]
pub fn gap(&self) -> bool {
self.gap
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GroupRead {
Refused(crate::heartbeat::GroupRefusal),
NotFollowed,
Revision,
Read(Vec<SectionRead>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GroupApplied {
pub index: u16,
pub iface: Option<crate::grammar::IfaceId>,
pub read: GroupRead,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OwnerApplied {
Refused(crate::heartbeat::OwnerRefusal),
Older,
Read {
gap: bool,
groups: Vec<GroupApplied>,
},
}
#[derive(Debug, Clone)]
pub struct View<T> {
layout: crate::heartbeat::Layout,
follows: Vec<bool>,
members: BTreeMap<String, Held<T>>,
diverged: Vec<u32>,
seq: Sequence,
time: Option<crate::heartbeat::Time>,
heartbeats: u64,
}
impl<T: Arrival> View<T> {
#[must_use]
pub fn new(layout: crate::heartbeat::Layout) -> Self {
let n = layout.collections.len();
Self {
layout,
follows: vec![false; n],
members: BTreeMap::new(),
diverged: vec![0; n],
seq: Sequence::default(),
time: None,
heartbeats: 0,
}
}
#[must_use]
pub fn layout(&self) -> &crate::heartbeat::Layout {
&self.layout
}
pub fn follow(&mut self, index: usize) -> bool {
match self.follows.get_mut(index) {
Some(f) => {
*f = true;
true
}
None => false,
}
}
pub fn follow_resource(&mut self, resource: &str) -> bool {
self.layout
.index_of(resource)
.is_some_and(|i| self.follow(i))
}
#[must_use]
pub fn follows_any(&self) -> bool {
self.follows.iter().any(|f| *f)
}
pub fn put(&mut self, key: &str, stamp: Option<Stamp>, at: T) {
self.mutation(key, stamp, false, at);
}
pub fn delete(&mut self, key: &str, stamp: Option<Stamp>, at: T) {
self.mutation(key, stamp, true, at);
}
fn mutation(&mut self, key: &str, stamp: Option<Stamp>, deleted: bool, at: T) {
let Some(k) = crate::heartbeat::base_relative(key) else {
return;
};
let Some(collection) = self.layout.collection_of(k) else {
return;
};
if let (Some(h), Some(s)) = (self.members.get(k).and_then(|h| h.stamp), stamp)
&& h.run == s.run
&& s.seq <= h.seq
{
return;
}
self.members.insert(
k.to_owned(),
Held {
collection,
stamp,
deleted,
at,
confirmed: None,
},
);
}
pub fn replace<'k>(
&mut self,
index: usize,
live: impl IntoIterator<Item = (&'k str, Option<Stamp>)>,
at: T,
) {
self.members.retain(|_, h| h.collection != index);
for (key, stamp) in live {
let Some(k) = crate::heartbeat::base_relative(key) else {
continue;
};
if self.layout.collection_of(k) == Some(index) {
self.members.insert(
k.to_owned(),
Held {
collection: index,
stamp,
deleted: false,
at,
confirmed: None,
},
);
}
}
if let Some(d) = self.diverged.get_mut(index) {
*d = 0;
}
}
pub fn reread<'k>(
&mut self,
index: usize,
live: impl IntoIterator<Item = (&'k str, Option<Stamp>)>,
asked: T,
at: T,
) {
let heard: Vec<(String, Held<T>)> = self
.members
.iter()
.filter(|(_, h)| h.collection == index && h.at >= asked)
.map(|(k, h)| (k.clone(), *h))
.collect();
self.replace(index, live, at);
for (k, h) in heard {
let keep = match self.members.get(&k) {
None => true,
Some(answered) => match (h.stamp, answered.stamp) {
(Some(mine), Some(theirs)) => mine.run == theirs.run && mine.seq > theirs.seq,
_ => false,
},
};
if keep {
self.members.insert(k, h);
}
}
}
fn live(&self, index: usize) -> impl Iterator<Item = (&String, &Held<T>)> {
self.members
.iter()
.filter(move |(_, h)| h.collection == index && !h.deleted)
}
#[must_use]
pub fn digest(&self, index: usize) -> Option<crate::heartbeat::Digest> {
let mut d = crate::heartbeat::Digest::EMPTY;
for (k, h) in self.live(index) {
d.toggle(k, h.stamp?);
}
Some(d)
}
pub fn apply(&mut self, tag: crate::wire::Tag, stamp: Stamp, body: &[u8], at: T) -> Applied {
use crate::heartbeat::Heartbeat;
if tag != self.layout.tag {
return Applied::Revision;
}
let hb = match Heartbeat::parse(body, &self.layout) {
Ok(hb) => hb,
Err(r) => return Applied::Refused(r),
};
let Some(read) = self.seq.read(stamp) else {
return Applied::Older;
};
self.time = Some(hb.time);
self.heartbeats += 1;
let mut sections = Vec::with_capacity(hb.sections.len());
for (i, section) in hb.sections.iter().enumerate() {
sections.push(if self.follows[i] {
self.read_section(i, section.as_ref(), at)
} else {
SectionRead::NotFollowed
});
}
Applied::Read {
gap: read.gap,
sections,
}
}
fn read_section(
&mut self,
i: usize,
section: Option<&crate::heartbeat::Section>,
at: T,
) -> SectionRead {
use crate::heartbeat::Members;
let Some(s) = section else {
self.diverged[i] = 0;
return SectionRead::Absent;
};
let keys: Vec<String> = self.live(i).map(|(k, _)| k.clone()).collect();
let same_count = match &s.members {
Members::One { .. } => keys.len() <= 1,
m => m.live() == Some(keys.len() as u64),
};
if self.digest(i) != Some(s.digest) || !same_count {
self.diverged[i] = self.diverged[i].saturating_add(1);
return SectionRead::Diverged;
}
self.diverged[i] = 0;
let vouched: Vec<String> = s
.members
.vouched()
.into_iter()
.filter_map(|r| keys.get(usize::try_from(r).ok()?).cloned())
.collect();
for k in &vouched {
if let Some(h) = self.members.get_mut(k) {
h.confirmed = Some(at);
}
}
SectionRead::Confirmed(vouched)
}
pub fn apply_group(
&mut self,
class: crate::heartbeat::Class,
entry: &crate::catalog::Entry,
group: &crate::heartbeat::Group,
time: crate::heartbeat::Time,
at: T,
) -> GroupRead {
if entry.iface != self.layout.iface || !self.follows_any() {
return GroupRead::NotFollowed;
}
if entry.contract != self.layout.fingerprint || !group.tag_is(&self.layout) {
return GroupRead::Revision;
}
let read = match group.read(&self.layout) {
Ok(s) => s,
Err(r) => return GroupRead::Refused(r),
};
let mut sections = Vec::with_capacity(read.len());
for (i, section) in read.iter().enumerate() {
sections.push(if !self.follows[i] {
SectionRead::NotFollowed
} else if self.layout.collections[i].class != class {
SectionRead::OtherClass
} else {
self.read_section(i, section.as_ref(), at)
});
}
if sections
.iter()
.any(|s| !matches!(s, SectionRead::NotFollowed | SectionRead::OtherClass))
{
self.time = Some(time);
self.heartbeats += 1;
}
GroupRead::Read(sections)
}
pub fn confirm(&mut self, key: &str, at: T) {
let Some(k) = crate::heartbeat::base_relative(key) else {
return;
};
if let Some(h) = self.members.get_mut(k)
&& !h.deleted
&& h.confirmed.is_none_or(|c| c < at)
{
h.confirmed = Some(at);
}
}
#[must_use]
pub fn confirmed(&self, key: &str) -> Option<T> {
let k = crate::heartbeat::base_relative(key)?;
self.members.get(k).and_then(|h| h.confirmed)
}
#[must_use]
pub fn reread_due(&self) -> Vec<usize> {
(0..self.diverged.len())
.filter(|i| self.follows[*i] && self.diverged[*i] >= 2)
.collect()
}
#[must_use]
pub fn gap(&self) -> bool {
self.seq.gap()
}
#[must_use]
pub fn follows(&self, index: usize) -> bool {
self.follows.get(index).copied().unwrap_or(false)
}
#[must_use]
pub fn classes(&self) -> Vec<crate::heartbeat::Class> {
crate::heartbeat::Class::ALL
.into_iter()
.filter(|c| {
self.layout
.collections
.iter()
.zip(&self.follows)
.any(|(x, f)| *f && x.class == *c)
})
.collect()
}
#[must_use]
pub fn owner_time(&self) -> Option<crate::heartbeat::Time> {
self.time
}
#[must_use]
pub fn last_heartbeat(&self) -> Option<Stamp> {
self.seq.last()
}
#[must_use]
pub fn heartbeats(&self) -> u64 {
self.heartbeats
}
#[must_use]
pub fn last(&self, key: &str, now: T) -> Option<Last> {
let k = crate::heartbeat::base_relative(key)?;
let h = self.members.get(k)?;
Some(if h.deleted {
Last::Delete(now.since(h.at))
} else {
Last::Put(now.since(h.confirmed.map_or(h.at, |c| c.max(h.at))))
})
}
#[must_use]
pub fn observation(
&self,
key: &str,
now: T,
listened: Duration,
complete: bool,
) -> Observation {
Observation::Subscribed {
last: self.last(key, now),
listened,
complete: complete && !self.seq.gap(),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Catalogs<'a> {
pub held: &'a [crate::catalog::Catalog],
pub named: Option<crate::catalog::CatalogId>,
}
#[derive(Debug, Clone, Default)]
struct ClassKey {
seq: Sequence,
named: std::collections::BTreeSet<crate::grammar::IfaceId>,
read: u64,
}
#[derive(Debug, Clone)]
pub struct Views<T> {
views: BTreeMap<crate::grammar::IfaceId, View<T>>,
keys: BTreeMap<crate::heartbeat::Class, ClassKey>,
}
impl<T> Default for Views<T> {
fn default() -> Self {
Self {
views: BTreeMap::new(),
keys: BTreeMap::new(),
}
}
}
impl<T: Arrival> Views<T> {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn insert(&mut self, view: View<T>) -> Option<View<T>> {
self.views.insert(view.layout().iface.clone(), view)
}
#[must_use]
pub fn view(&self, iface: &crate::grammar::IfaceId) -> Option<&View<T>> {
self.views.get(iface)
}
pub fn view_mut(&mut self, iface: &crate::grammar::IfaceId) -> Option<&mut View<T>> {
self.views.get_mut(iface)
}
#[must_use]
pub fn view_of(&self, key: &str) -> Option<&View<T>> {
self.views.get(&iface_of(key)?)
}
pub fn view_of_mut(&mut self, key: &str) -> Option<&mut View<T>> {
self.views.get_mut(&iface_of(key)?)
}
pub fn iter(&self) -> impl Iterator<Item = &View<T>> {
self.views.values()
}
#[must_use]
pub fn classes(&self) -> Vec<crate::heartbeat::Class> {
crate::heartbeat::Class::ALL
.into_iter()
.filter(|c| self.views.values().any(|v| v.classes().contains(c)))
.collect()
}
#[must_use]
pub fn class_horizon(&self, class: crate::heartbeat::Class) -> Option<Duration> {
self.views
.values()
.filter_map(|v| v.layout().class_horizon(class))
.min()
}
pub fn apply_owner(
&mut self,
class: crate::heartbeat::Class,
tag: crate::wire::Tag,
stamp: Stamp,
body: &[u8],
through: Catalogs<'_>,
at: T,
) -> OwnerApplied {
let hb = match crate::heartbeat::OwnerHeartbeat::parse(tag, body) {
Ok(hb) => hb,
Err(r) => return OwnerApplied::Refused(r),
};
let key = self.keys.entry(class).or_default();
let Some(read) = key.seq.read(stamp) else {
return OwnerApplied::Older;
};
if read.run {
key.named.clear();
}
key.read += 1;
let mut groups = Vec::with_capacity(hb.groups.len());
for g in &hb.groups {
let entry = match g.entry(through.held, through.named) {
Ok(e) => e,
Err(r) => {
groups.push(GroupApplied {
index: g.index,
iface: None,
read: GroupRead::Refused(r),
});
continue;
}
};
key.named.insert(entry.iface.clone());
let read = match self.views.get_mut(&entry.iface) {
Some(v) => v.apply_group(class, entry, g, hb.time, at),
None => GroupRead::NotFollowed,
};
groups.push(GroupApplied {
index: g.index,
iface: Some(entry.iface.clone()),
read,
});
}
OwnerApplied::Read {
gap: read.gap,
groups,
}
}
#[must_use]
pub fn gap(&self, class: crate::heartbeat::Class) -> Option<bool> {
let k = self.keys.get(&class)?;
k.seq.last().map(|_| k.seq.gap())
}
#[must_use]
pub fn last(&self, class: crate::heartbeat::Class) -> Option<Stamp> {
self.keys.get(&class)?.seq.last()
}
#[must_use]
pub fn owner_heartbeats(&self, class: crate::heartbeat::Class) -> u64 {
self.keys.get(&class).map_or(0, |k| k.read)
}
#[must_use]
pub fn is_lost(&self, iface: &crate::grammar::IfaceId, index: usize) -> bool {
let Some(v) = self.views.get(iface) else {
return false;
};
if !v.follows(index) {
return false;
}
v.gap()
|| self
.keys
.get(&v.layout().collections[index].class)
.is_some_and(|k| k.seq.gap() && k.named.contains(iface))
}
#[must_use]
pub fn lost(&self) -> Vec<(crate::grammar::IfaceId, usize)> {
self.views
.iter()
.flat_map(|(iface, v)| {
(0..v.layout().collections.len())
.filter(|i| self.is_lost(iface, *i))
.map(|i| (iface.clone(), i))
})
.collect()
}
#[must_use]
pub fn observation(
&self,
key: &str,
now: T,
listened: Duration,
complete: bool,
) -> Option<Observation> {
let v = self.view_of(key)?;
let lost = crate::heartbeat::base_relative(key)
.and_then(|k| v.layout().collection_of(k))
.is_some_and(|i| self.is_lost(&v.layout().iface, i));
Some(v.observation(key, now, listened, complete && !lost))
}
}
fn iface_of(key: &str) -> Option<crate::grammar::IfaceId> {
match crate::grammar::parse(crate::heartbeat::base_relative(key)?) {
Ok(crate::grammar::ZkKey::Data { iface, .. }) => Some(iface),
_ => None,
}
}
#[must_use]
pub fn confirmed_last(delivered: Option<Last>, heartbeat: Option<Duration>) -> Option<Last> {
match (delivered, heartbeat) {
(Some(Last::Put(a)), Some(h)) => Some(Last::Put(a.min(h))),
(None, Some(h)) => Some(Last::Put(h)),
(d, _) => d,
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn ann(v: Value) -> BTreeMap<String, Value> {
BTreeMap::from([(TTL_S.to_owned(), v)])
}
#[test]
fn the_horizon_is_a_whole_number_of_seconds() {
let h = |v: Value| horizon(Kind::State, &ann(v));
assert_eq!(h(json!(60)), Horizon::Within(Duration::from_secs(60)));
assert_eq!(h(json!(60.0)), Horizon::Within(Duration::from_secs(60)));
assert_eq!(h(json!(-0.0)), Horizon::Never);
assert_eq!(h(json!(0)), Horizon::Never);
assert!(matches!(h(json!(1.5)), Horizon::Invalid(_)));
assert!(matches!(h(json!(-1)), Horizon::Invalid(_)));
assert!(matches!(h(json!(MAX_TTL_S + 1)), Horizon::Invalid(_)));
assert_eq!(
horizon(Kind::Event, &ann(json!("x"))),
Horizon::Ignored,
"the kind first"
);
assert_eq!(horizon(Kind::State, &BTreeMap::new()), Horizon::Undeclared);
assert_eq!(
h(json!(61)).refresh_bound(),
Some(Duration::from_millis(30_500))
);
}
#[test]
fn a_trusted_reply_is_judged_in_the_band() {
let h = Horizon::Within(Duration::from_secs(2));
let got = |s: f64| Observation::Got {
reply: Some(Reply::Put {
stamp_age: Some(StampAge::from_secs_f64(s)),
}),
clock: ClockTrust::Trusted {
delta: DEFAULT_DELTA,
},
};
let v = |s: f64| judge(&h, &got(s)).reason;
assert_eq!(v(1.5), Reason::WithinHorizon);
assert_eq!(v(1.6), Reason::NearHorizon);
assert_eq!(v(2.5), Reason::NearHorizon);
assert_eq!(v(2.6), Reason::BeyondHorizon);
assert_eq!(v(-0.5), Reason::WithinHorizon);
assert_eq!(v(-0.6), Reason::ClockDisagrees);
}
#[test]
fn fresh_wins_then_stale_then_unobservable() {
let j = |v, r| Judged::new(v, r);
assert_eq!(
combine([
j(Verdict::Stale, Reason::NoDelivery),
j(Verdict::Fresh, Reason::WithinHorizon)
])
.verdict,
Verdict::Fresh
);
assert_eq!(
combine([
j(Verdict::Unobservable, Reason::ClockUntrusted),
j(Verdict::Stale, Reason::NoDelivery)
])
.reason,
Reason::NoDelivery
);
assert_eq!(combine([]).reason, Reason::NoObservation);
}
mod view {
use super::super::*;
use crate::contract::load_str;
use crate::heartbeat::{Digest, Heartbeat, Layout, Members, Section, Time};
use crate::timing::Mono;
use crate::wire::{Run, Seq, Tag};
const HB: &str = r#"
[interface]
name = "hb"
major = 1
minor = 0
uses = ["freshness.v1"]
[resources.link]
kind = "state"
type = { raw = "text/plain" }
annotations = { "freshness.ttl_s" = 2 }
[resources."peer/{peer}"]
kind = "state"
type = { raw = "text/plain" }
params = { peer = "string" }
cardinality = 5
annotations = { "freshness.ttl_s" = 2 }
"#;
const LINK: &str = "zk2/lab/n1/hb.v1/state/link";
const A: &str = "zk2/lab/n1/hb.v1/state/peer/a";
const B: &str = "zk2/lab/n1/hb.v1/state/peer/b";
fn layout() -> Layout {
let c = load_str(HB, std::path::Path::new("."), None)
.contract
.unwrap();
Layout::of(&c)
}
fn st(run: u16, seq: u32) -> Stamp {
Stamp {
run: Run::U16(run),
seq: Seq::new(seq).unwrap(),
}
}
fn ms(n: u64) -> Mono {
Mono::after(Duration::from_millis(n))
}
fn body(l: &Layout, link: Option<Section>, peers: Option<Section>) -> Vec<u8> {
Heartbeat {
time: Time::Unknown,
sections: vec![link, peers],
}
.write(l)
.unwrap()
}
fn view() -> View<Mono> {
let mut v = View::new(layout());
assert!(v.follow_resource("state/link"));
assert!(v.follow_resource("state/peer/{peer}"));
assert!(!v.follow_resource("state/nothing"));
v
}
#[test]
fn a_heartbeat_whose_digest_is_the_views_confirms_what_it_vouches_for() {
let l = layout();
let mut v = view();
v.put(LINK, Some(st(1, 1)), ms(0));
v.put(A, Some(st(1, 2)), ms(0));
v.put(B, Some(st(1, 3)), ms(0));
let link = Section {
digest: Digest::of([(LINK, st(1, 1))]),
members: Members::One { vouched: true },
};
let peers = Section {
digest: Digest::of([(A, st(1, 2)), (B, st(1, 3))]),
members: Members::templated(2, [1]),
};
let got = v.apply(
l.tag,
st(9, 0),
&body(&l, Some(link), Some(peers)),
ms(1500),
);
assert_eq!(
got,
Applied::Read {
gap: false,
sections: vec![
SectionRead::Confirmed(vec![LINK.into()]),
SectionRead::Confirmed(vec![B.into()]),
]
}
);
assert_eq!(v.confirmed(B), Some(ms(1500)));
assert_eq!(v.confirmed(A), None, "not vouched for");
let h = Horizon::Within(Duration::from_secs(2));
let j = |k: &str| {
judge(
&h,
&v.observation(k, ms(3000), Duration::from_secs(3), true),
)
};
assert_eq!(j(LINK).verdict, Verdict::Fresh);
assert_eq!(j(B).verdict, Verdict::Fresh);
assert_eq!(
j(A).verdict,
Verdict::Stale,
"a cleared bit is no confirmation"
);
assert_eq!(v.confirmed(&format!("prod/{LINK}")), Some(ms(1500)));
}
#[test]
fn a_missed_change_diverges_and_two_in_a_row_are_due_a_read() {
let l = layout();
let mut v = view();
v.put(A, Some(st(1, 2)), ms(0));
let owner = Digest::of([(A, st(1, 5)), (B, st(1, 6))]);
let sec = || Section {
digest: owner,
members: Members::templated(2, [0, 1]),
};
for (seq, due) in [(0, false), (1, true)] {
let got = v.apply(l.tag, st(9, seq), &body(&l, None, Some(sec())), ms(1000));
assert_eq!(
got,
Applied::Read {
gap: false,
sections: vec![SectionRead::Absent, SectionRead::Diverged]
}
);
assert_eq!(v.reread_due() == vec![1], due);
}
assert_eq!(v.confirmed(A), None);
v.replace(1, [(A, Some(st(1, 5))), (B, Some(st(1, 6)))], ms(1100));
assert!(v.reread_due().is_empty());
let got = v.apply(l.tag, st(9, 2), &body(&l, None, Some(sec())), ms(1200));
assert_eq!(
got,
Applied::Read {
gap: false,
sections: vec![
SectionRead::Absent,
SectionRead::Confirmed(vec![A.into(), B.into()])
]
}
);
}
#[test]
fn a_deleted_member_leaves_the_digest_and_a_stale_put_is_not_taken() {
let mut v = view();
v.put(A, Some(st(1, 4)), ms(0));
v.put(A, Some(st(1, 3)), ms(10));
assert_eq!(v.digest(1), Some(Digest::of([(A, st(1, 4))])));
v.delete(A, Some(st(1, 5)), ms(20));
assert_eq!(v.digest(1), Some(Digest::EMPTY));
assert_eq!(
v.last(A, ms(30)),
Some(Last::Delete(Duration::from_millis(10)))
);
v.put(A, Some(st(2, 0)), ms(40));
assert_eq!(v.digest(1), Some(Digest::of([(A, st(2, 0))])));
v.put(B, None, ms(50));
assert_eq!(v.digest(1), None);
v.put("zk2/lab/n1/hb.v1/state/other", Some(st(1, 1)), ms(60));
assert_eq!(v.last("zk2/lab/n1/hb.v1/state/other", ms(70)), None);
}
#[test]
fn a_gap_is_a_heartbeat_lost_and_the_tag_and_the_order_guard() {
let l = layout();
let mut v = view();
v.put(LINK, Some(st(1, 1)), ms(0));
let link = || {
Some(Section {
digest: Digest::of([(LINK, st(1, 1))]),
members: Members::One { vouched: true },
})
};
let b = body(&l, link(), None);
let other = Tag::new((l.tag.get() + 1) % 16).unwrap();
assert_eq!(v.apply(other, st(9, 0), &b, ms(100)), Applied::Revision);
assert!(matches!(
v.apply(l.tag, st(9, 0), &b, ms(100)),
Applied::Read { gap: false, .. }
));
assert!(matches!(
v.apply(l.tag, st(9, 3), &b, ms(200)),
Applied::Read { gap: true, .. }
));
assert!(v.gap());
let o = v.observation(LINK, ms(5000), Duration::from_secs(5), true);
assert_eq!(
judge(&Horizon::Within(Duration::from_secs(2)), &o).reason,
Reason::Incomplete
);
assert_eq!(v.apply(l.tag, st(9, 3), &b, ms(300)), Applied::Older);
assert_eq!(v.apply(l.tag, st(9, 1), &b, ms(300)), Applied::Older);
assert!(matches!(
v.apply(l.tag, st(9, 4), &b, ms(400)),
Applied::Read { gap: false, .. }
));
assert!(!v.gap());
assert!(matches!(
v.apply(l.tag, st(10, 0), &b, ms(500)),
Applied::Read { gap: false, .. }
));
assert!(matches!(
v.apply(l.tag, st(10, 1), &b[..2], ms(600)),
Applied::Refused(_)
));
assert_eq!(v.heartbeats(), 4);
}
}
mod views {
use super::super::*;
use crate::catalog::Catalog;
use crate::contract::load_str;
use crate::heartbeat::{
Class, Digest, Group, GroupRefusal, Layout, Members, OwnerHeartbeat, Section, Time,
};
use crate::timing::Mono;
use crate::wire::{Run, Seq, Tag};
const MIXED: &str = r#"
[interface]
name = "mixed"
major = 1
minor = 0
uses = ["freshness.v2", "link.v1"]
[resources."peer/{peer}"]
kind = "state"
type = { raw = "text/plain" }
params = { peer = "string" }
cardinality = 8
annotations = { "freshness.ttl_s" = 120 }
[resources.status]
kind = "state"
type = { raw = "text/plain" }
annotations = { "freshness.ttl_s" = 60, "link.exposure" = "link" }
"#;
const VITAL: &str = r#"
[interface]
name = "vital"
major = 1
minor = 0
uses = ["freshness.v2"]
[resources.status]
kind = "state"
type = { raw = "text/plain" }
annotations = { "freshness.ttl_s" = 60 }
"#;
const PEER: &str = "zk2/lab/n1/mixed.v1/state/peer/p1";
const STATUS: &str = "zk2/lab/n1/mixed.v1/state/status";
const VITALS: &str = "zk2/lab/n1/vital.v1/state/status";
fn layout(text: &str) -> Layout {
Layout::of(
&load_str(text, std::path::Path::new("."), None)
.contract
.unwrap(),
)
}
fn st(run: u16, seq: u32) -> Stamp {
Stamp {
run: Run::U16(run),
seq: Seq::new(seq).unwrap(),
}
}
fn ms(n: u64) -> Mono {
Mono::after(Duration::from_millis(n))
}
fn catalog(mixed: &Layout, vital: &Layout) -> Catalog {
let mut c = Catalog::new(0).unwrap();
c.push(mixed.iface.clone(), mixed.fingerprint.clone())
.unwrap();
c.push(vital.iface.clone(), vital.fingerprint.clone())
.unwrap();
c
}
fn one(key: &str, stamp: Stamp) -> Option<Section> {
Some(Section {
digest: Digest::of([(key, stamp)]),
members: Members::One { vouched: true },
})
}
fn mixed_host(l: &Layout) -> Group {
let peers = Section {
digest: Digest::of([(PEER, st(1, 1))]),
members: Members::templated(1, [0]),
};
Group::of(0, l, &[Some(peers), None]).unwrap()
}
fn vital_host(l: &Layout) -> Group {
Group::of(1, l, &[one(VITALS, st(1, 3))]).unwrap()
}
fn body(groups: Vec<Group>) -> Vec<u8> {
OwnerHeartbeat {
time: Time::Unknown,
groups,
}
.write()
.unwrap()
}
fn views(mixed: &Layout, vital: &Layout) -> Views<Mono> {
let mut vs = Views::new();
for l in [mixed, vital] {
let mut v = View::new(l.clone());
for i in 0..l.collections.len() {
assert!(v.follow(i));
}
assert!(vs.insert(v).is_none());
}
vs.view_of_mut(PEER)
.unwrap()
.put(PEER, Some(st(1, 1)), ms(0));
vs.view_of_mut(STATUS)
.unwrap()
.put(STATUS, Some(st(1, 2)), ms(0));
vs.view_of_mut(VITALS)
.unwrap()
.put(VITALS, Some(st(1, 3)), ms(0));
vs
}
#[test]
fn a_class_is_the_exposure_and_a_key_is_one_classs() {
let (mixed, vital) = (layout(MIXED), layout(VITAL));
assert_eq!(
mixed
.collections
.iter()
.map(|c| c.class)
.collect::<Vec<_>>(),
vec![Class::Host, Class::Link]
);
assert_eq!(mixed.classes(), vec![Class::Link, Class::Host]);
assert_eq!(vital.classes(), vec![Class::Host]);
assert_eq!(
mixed.class_horizon(Class::Link),
Some(Duration::from_secs(60))
);
assert_eq!(
mixed.class_horizon(Class::Host),
Some(Duration::from_secs(120))
);
assert_eq!(vital.class_horizon(Class::Link), None);
let mut v = View::<Mono>::new(mixed.clone());
assert!(v.classes().is_empty());
assert!(v.follow_resource("state/status"));
assert_eq!(v.classes(), vec![Class::Link]);
let vs = views(&mixed, &vital);
assert_eq!(vs.classes(), vec![Class::Link, Class::Host]);
}
#[test]
fn a_group_on_the_other_classs_key_is_no_heartbeat_applied() {
let (mixed, vital) = (layout(MIXED), layout(VITAL));
let cat = catalog(&mixed, &vital);
let through = Catalogs {
held: std::slice::from_ref(&cat),
named: Some(cat.id()),
};
let mut v = View::new(mixed.clone());
assert!(v.follow_resource("state/status"));
v.put(STATUS, Some(st(1, 2)), ms(0));
let mut vs = Views::new();
vs.insert(v);
let known = Time::At { secs: 7, ms: 0 };
let put = |g: Group| {
OwnerHeartbeat {
time: known,
groups: vec![g],
}
.write()
.unwrap()
};
let host = vs.apply_owner(
Class::Host,
Tag::new(0).unwrap(),
st(9, 0),
&put(mixed_host(&mixed)),
through,
ms(10),
);
let OwnerApplied::Read { groups, .. } = host else {
panic!("read: {host:?}");
};
assert_eq!(
groups[0].read,
GroupRead::Read(vec![SectionRead::NotFollowed, SectionRead::OtherClass])
);
let view = vs.view(&mixed.iface).unwrap();
assert_eq!(view.heartbeats(), 0, "no section read, none applied");
assert_eq!(view.owner_time(), None);
assert_eq!(vs.owner_heartbeats(Class::Host), 1, "read on its key");
let link = Group::of(0, &mixed, &[None, one(STATUS, st(1, 2))]).unwrap();
let applied = vs.apply_owner(
Class::Link,
Tag::new(0).unwrap(),
st(9, 0),
&put(link),
through,
ms(20),
);
let OwnerApplied::Read { groups, .. } = applied else {
panic!("read: {applied:?}");
};
assert_eq!(
groups[0].read,
GroupRead::Read(vec![
SectionRead::NotFollowed,
SectionRead::Confirmed(vec![STATUS.to_owned()])
])
);
let view = vs.view(&mixed.iface).unwrap();
assert_eq!(view.heartbeats(), 1);
assert_eq!(view.owner_time(), Some(known));
let absent = Group::of(0, &mixed, &[None, None]).unwrap();
vs.apply_owner(
Class::Link,
Tag::new(0).unwrap(),
st(9, 1),
&put(absent),
through,
ms(30),
);
assert_eq!(vs.view(&mixed.iface).unwrap().heartbeats(), 2);
}
#[test]
fn a_sequence_is_its_keys_alone() {
let mut s = Sequence::default();
let first = s.read(st(9, 5)).unwrap();
assert!(!first.gap && !first.run);
assert_eq!(s.read(st(9, 5)), None, "the same seq");
assert_eq!(s.read(st(9, 4)), None, "an earlier one");
assert_eq!(s.read(st(9, 5 + (1 << 23))), None, "2^23 ahead, unordered");
assert_eq!(s.last(), Some(st(9, 5)), "an older one moves nothing");
assert!(!s.read(st(9, 6)).unwrap().gap);
assert!(s.read(st(9, 8)).unwrap().gap);
assert!(s.gap());
let other = s.read(st(10, 3)).unwrap();
assert!(other.run && !other.gap, "another run starts it again");
assert!(!s.gap());
let mut s = Sequence::default();
s.read(st(9, Seq::MAX.get())).unwrap();
assert!(!s.read(st(9, 0)).unwrap().gap);
}
#[test]
fn a_gap_loses_what_a_group_on_the_key_named_within_the_run() {
let (mixed, vital) = (layout(MIXED), layout(VITAL));
let held = [catalog(&mixed, &vital)];
let named = Some(held[0].id());
let mut vs = views(&mixed, &vital);
let alone = body(vec![mixed_host(&mixed)]);
let both = body(vec![mixed_host(&mixed), vital_host(&vital)]);
let through = Catalogs { held: &held, named };
let host = |vs: &mut Views<Mono>, stamp, body: &[u8], at| match vs.apply_owner(
Class::Host,
Tag::NONE,
stamp,
body,
through,
ms(at),
) {
OwnerApplied::Read { gap, .. } => gap,
other => panic!("{other:?}"),
};
let lost = |vs: &Views<Mono>| -> Vec<(String, usize)> {
vs.lost()
.into_iter()
.map(|(i, c)| (i.to_string(), c))
.collect()
};
assert!(!host(&mut vs, st(9, 0), &alone, 100));
assert!(host(&mut vs, st(9, 2), &alone, 200));
assert_eq!(lost(&vs), vec![("mixed.v1".to_owned(), 0)]);
assert!(vs.is_lost(&mixed.iface, 0));
assert!(!vs.is_lost(&mixed.iface, 1), "a `link` collection");
assert!(!vs.is_lost(&vital.iface, 0), "not named on the key");
let o = |vs: &Views<Mono>, key| {
let o = vs
.observation(key, ms(250), Duration::from_secs(1), true)
.unwrap();
matches!(o, Observation::Subscribed { complete: true, .. })
};
assert!(!o(&vs, PEER));
assert!(o(&vs, STATUS));
assert!(o(&vs, VITALS));
assert_eq!(vs.gap(Class::Host), Some(true));
assert_eq!(vs.gap(Class::Link), None, "nothing read on the `link` key");
assert!(!host(&mut vs, st(9, 3), &both, 300));
assert!(lost(&vs).is_empty());
assert!(host(&mut vs, st(9, 5), &alone, 400));
assert_eq!(
lost(&vs),
vec![("mixed.v1".to_owned(), 0), ("vital.v1".to_owned(), 0)]
);
assert!(!host(&mut vs, st(10, 0), &alone, 500));
assert!(lost(&vs).is_empty());
assert!(host(&mut vs, st(10, 2), &alone, 600));
assert_eq!(lost(&vs), vec![("mixed.v1".to_owned(), 0)]);
assert_eq!(vs.owner_heartbeats(Class::Host), 6);
assert_eq!(vs.last(Class::Host), Some(st(10, 2)));
assert!(
vs.observation(
"zk2/lab/n1/other.v1/state/x",
ms(700),
Duration::from_secs(1),
true
)
.is_none()
);
}
#[test]
fn a_group_stops_at_the_first_step_that_answers() {
let (mixed, vital) = (layout(MIXED), layout(VITAL));
let cat = catalog(&mixed, &vital);
let (e_mixed, e_vital) = (cat.entry(0).unwrap(), cat.entry(1).unwrap());
let mut v = View::<Mono>::new(vital.clone());
let g = vital_host(&vital);
assert_eq!(
v.apply_group(Class::Host, e_vital, &g, Time::Unknown, ms(1)),
GroupRead::NotFollowed
);
assert!(v.follow(0));
v.put(VITALS, Some(st(1, 3)), ms(0));
assert_eq!(
v.apply_group(Class::Host, e_mixed, &g, Time::Unknown, ms(1)),
GroupRead::NotFollowed
);
let elsewhere = crate::catalog::Entry {
iface: vital.iface.clone(),
contract: mixed.fingerprint.clone(),
};
assert_eq!(
v.apply_group(Class::Host, &elsewhere, &g, Time::Unknown, ms(1)),
GroupRead::Revision
);
let mut retagged = g.clone();
retagged.tag = Tag::new((vital.tag.get() + 1) % 16).unwrap();
assert_eq!(
v.apply_group(Class::Host, e_vital, &retagged, Time::Unknown, ms(1)),
GroupRead::Revision
);
let diverged = Group::of(1, &vital, &[one(VITALS, st(1, 4))]).unwrap();
assert_eq!(
v.apply_group(Class::Host, e_vital, &diverged, Time::Unknown, ms(2)),
GroupRead::Read(vec![SectionRead::Diverged])
);
let mut short = g.clone();
short.sections.bits -= 1;
assert_eq!(
v.apply_group(Class::Host, e_vital, &short, Time::Unknown, ms(3)),
GroupRead::Refused(GroupRefusal::Short)
);
assert!(v.reread_due().is_empty());
assert_eq!(
v.apply_group(Class::Host, e_vital, &diverged, Time::Unknown, ms(4)),
GroupRead::Read(vec![SectionRead::Diverged])
);
assert_eq!(v.reread_due(), vec![0]);
assert_eq!(
v.apply_group(Class::Link, e_vital, &g, Time::Unknown, ms(5)),
GroupRead::Read(vec![SectionRead::OtherClass])
);
assert_eq!(v.reread_due(), vec![0]);
assert_eq!(v.confirmed(VITALS), None);
assert_eq!(
v.apply_group(Class::Host, e_vital, &g, Time::Unknown, ms(6)),
GroupRead::Read(vec![SectionRead::Confirmed(vec![VITALS.to_owned()])])
);
assert_eq!(v.confirmed(VITALS), Some(ms(6)));
assert!(v.reread_due().is_empty());
assert_eq!(v.last_heartbeat(), None);
assert!(!v.gap());
}
#[test]
fn an_owner_heartbeat_key_names_its_class() {
use crate::heartbeat::{covered, owner_class, owner_key};
let k = owner_key("lab", "n1", Class::Link);
assert_eq!(k, "zk2/lab/n1/freshness.v2/stream/heartbeats/link");
let (addr, class) = owner_class(&format!("ns/{k}")).unwrap();
assert_eq!((addr.to_string().as_str(), class), ("lab/n1", Class::Link));
assert_eq!(
owner_class("zk2/lab/n1/freshness.v2/stream/heartbeats/host").map(|x| x.1),
Some(Class::Host)
);
assert!(owner_class("zk2/lab/n1/freshness.v2/stream/heartbeats/near").is_none());
assert!(owner_class("zk2/lab/n1/freshness.v2/stream/heartbeat/link.v1").is_none());
assert!(covered(&k).is_none());
}
}
#[test]
fn a_measured_offset_trusts_within_the_delta_either_way() {
let d = DEFAULT_DELTA;
assert!(matches!(
ClockTrust::measured(StampAge::ahead(d), d),
ClockTrust::Trusted { .. }
));
assert_eq!(
ClockTrust::measured(StampAge::behind(Duration::from_millis(501)), d),
ClockTrust::Untrusted
);
}
}