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,
Absent,
Diverged,
Confirmed(Vec<String>),
}
impl SectionRead {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::NotFollowed => "not_followed",
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)]
pub struct View<T> {
layout: crate::heartbeat::Layout,
follows: Vec<bool>,
members: BTreeMap<String, Held<T>>,
diverged: Vec<u32>,
last: Option<Stamp>,
gap: bool,
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],
last: None,
gap: false,
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, Members};
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 gap = 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) => {
stamp.seq.get().wrapping_sub(l.seq.get()) & crate::wire::Seq::MAX.get() != 1
}
_ => return Applied::Older,
}
}
_ => false,
};
self.last = Some(stamp);
self.gap = gap;
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() {
if !self.follows[i] {
sections.push(SectionRead::NotFollowed);
continue;
}
let Some(s) = section else {
self.diverged[i] = 0;
sections.push(SectionRead::Absent);
continue;
};
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);
sections.push(SectionRead::Diverged);
continue;
}
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);
}
}
sections.push(SectionRead::Confirmed(vouched));
}
Applied::Read { gap, 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.gap
}
#[must_use]
pub fn owner_time(&self) -> Option<crate::heartbeat::Time> {
self.time
}
#[must_use]
pub fn last_heartbeat(&self) -> Option<Stamp> {
self.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.gap,
}
}
}
#[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);
}
}
#[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
);
}
}