use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::time::Duration;
use serde_json::Value;
use crate::authoring::Kind;
use crate::contract::Resource;
use crate::freshness::{ClockMeasure, StampAge};
pub const PROFILE: &str = "timing.v1";
pub const NAME: &str = "timing";
pub const PERIOD_MS: &str = "timing.period_ms";
pub const DEADLINE_MS: &str = "timing.deadline_ms";
pub const LIFESPAN_MS: &str = "timing.lifespan_ms";
pub const VOCABULARY: &[&str] = &["period_ms", "deadline_ms", "lifespan_ms"];
pub const MAX_MS: u64 = (1 << 53) - 1;
pub const FORGET_AFTER: Duration = Duration::from_secs(3600);
pub const BOUND_FLOOR: Duration = Duration::from_millis(1);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Invalid {
PeriodValue,
DeadlineValue,
LifespanValue,
}
impl Invalid {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::PeriodValue => "period_value",
Self::DeadlineValue => "deadline_value",
Self::LifespanValue => "lifespan_value",
}
}
#[must_use]
pub fn says(self) -> &'static str {
match self {
Self::PeriodValue => {
"timing.period_ms is not a whole number of milliseconds from 1 to 2^53-1"
}
Self::DeadlineValue => {
"timing.deadline_ms is not a whole number of milliseconds from 1 to 2^53-1"
}
Self::LifespanValue => {
"timing.lifespan_ms is not a whole number of milliseconds from 1 to 2^53-1"
}
}
}
}
impl fmt::Display for Invalid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.says())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Declared {
pub period: Option<Duration>,
pub deadline: Option<Duration>,
pub lifespan: Option<Duration>,
}
impl Declared {
#[must_use]
pub fn below_period(&self) -> bool {
matches!((self.period, self.deadline), (Some(p), Some(d)) if d < p)
}
#[must_use]
pub fn judged_deadline(&self) -> Option<Duration> {
if self.below_period() {
None
} else {
self.deadline
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Declaration {
NotThisProfiles,
Ignored,
Invalid(Vec<Invalid>),
Declared(Declared),
}
impl Declaration {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::NotThisProfiles => "not_this_profiles",
Self::Ignored => "ignored",
Self::Invalid(_) => "invalid",
Self::Declared(_) => "declared",
}
}
#[must_use]
pub fn declared(&self) -> Option<&Declared> {
match self {
Self::Declared(d) => Some(d),
_ => None,
}
}
}
fn millis(v: &Value) -> Option<u64> {
let n = v.as_number()?;
if let Some(u) = n.as_u64() {
return (1..=MAX_MS).contains(&u).then_some(u);
}
if n.is_i64() {
return None;
}
let f = n.as_f64()?;
let max = MAX_MS as f64;
(f.is_finite() && f.fract() == 0.0 && f >= 1.0 && f <= max).then_some(f as u64)
}
fn any_key(annotations: &BTreeMap<String, Value>) -> bool {
[PERIOD_MS, DEADLINE_MS, LIFESPAN_MS]
.iter()
.any(|k| annotations.contains_key(*k))
}
#[must_use]
pub fn declaration(kind: Kind, annotations: &BTreeMap<String, Value>) -> Declaration {
if !any_key(annotations) {
return Declaration::NotThisProfiles;
}
if kind != Kind::Stream {
return Declaration::Ignored;
}
let mut why = Vec::new();
let mut read = |key: &str, wrong: Invalid| -> Option<Duration> {
let v = annotations.get(key)?;
let ms = millis(v);
if ms.is_none() {
why.push(wrong);
}
ms.map(Duration::from_millis)
};
let declared = Declared {
period: read(PERIOD_MS, Invalid::PeriodValue),
deadline: read(DEADLINE_MS, Invalid::DeadlineValue),
lifespan: read(LIFESPAN_MS, Invalid::LifespanValue),
};
if why.is_empty() {
Declaration::Declared(declared)
} else {
Declaration::Invalid(why)
}
}
#[must_use]
pub fn declaration_of(r: &Resource) -> Declaration {
declaration(r.kind, &r.annotations)
}
#[must_use]
pub fn requirement_declaration(annotations: &BTreeMap<String, Value>) -> Declaration {
if any_key(annotations) {
Declaration::Ignored
} else {
Declaration::NotThisProfiles
}
}
#[must_use]
pub fn tracker_for<S: Into<String>>(
kind: Kind,
d: &Declaration,
bound: Option<u64>,
known: impl IntoIterator<Item = S>,
) -> Option<Tracker> {
if kind != Kind::Stream {
return None;
}
let deadline = d.declared()?.judged_deadline()?;
Some(Tracker::new(deadline, bound, known))
}
#[must_use]
pub fn detection_bound(deadline: Duration) -> Duration {
(deadline / 50).max(BOUND_FLOOR)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Mono(Duration);
impl Mono {
pub const ZERO: Self = Self(Duration::ZERO);
#[must_use]
pub const fn after(d: Duration) -> Self {
Self(d)
}
#[must_use]
pub const fn from_nanos(ns: u64) -> Self {
Self(Duration::from_nanos(ns))
}
#[must_use]
pub const fn since_origin(self) -> Duration {
self.0
}
#[must_use]
pub fn saturating_add(self, d: Duration) -> Self {
Self(self.0.saturating_add(d))
}
#[must_use]
pub fn saturating_since(self, earlier: Self) -> Duration {
self.0.saturating_sub(earlier.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum OwnerState {
#[default]
Unseen,
Present,
Unconfirmed,
Absent,
}
impl OwnerState {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Unseen => "unseen",
Self::Present => "present",
Self::Unconfirmed => "unconfirmed",
Self::Absent => "absent",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
Some(match s {
"unseen" => Self::Unseen,
"present" => Self::Present,
"unconfirmed" => Self::Unconfirmed,
"absent" => Self::Absent,
_ => return None,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Event<'a> {
Start,
Arrival { member: &'a str, expired: bool },
Owner(OwnerState),
MemberSeen(&'a str),
MemberGone(&'a str),
Tick,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EndReason {
Gone,
Forgotten,
}
impl EndReason {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Gone => "gone",
Self::Forgotten => "forgotten",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Report {
Missed {
at: Mono,
member: String,
due: Mono,
by: Mono,
owner: OwnerState,
},
Met { at: Mono, member: String },
Ended {
at: Mono,
member: String,
reason: EndReason,
},
BeyondBound { at: Mono, member: String },
}
impl Report {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
Self::Missed { .. } => "missed",
Self::Met { .. } => "met",
Self::Ended { .. } => "ended",
Self::BeyondBound { .. } => "beyond_bound",
}
}
#[must_use]
pub fn member(&self) -> &str {
match self {
Self::Missed { member, .. }
| Self::Met { member, .. }
| Self::Ended { member, .. }
| Self::BeyondBound { member, .. } => member,
}
}
#[must_use]
pub fn at(&self) -> Mono {
match self {
Self::Missed { at, .. }
| Self::Met { at, .. }
| Self::Ended { at, .. }
| Self::BeyondBound { at, .. } => *at,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemberState {
Idle { after_end: bool },
Waiting { since: Mono },
Heard { last: Mono },
Missed { last: Option<Mono> },
}
#[derive(Debug, Clone, Copy)]
struct Held {
known: bool,
state: MemberState,
}
#[derive(Debug, Clone)]
pub struct Tracker {
deadline: Duration,
bound: Option<u64>,
start: Option<Mono>,
owner: OwnerState,
owner_since: Option<Mono>,
held: BTreeMap<String, Held>,
epoch: bool,
seen: BTreeMap<String, Mono>,
beyond: BTreeSet<String>,
}
impl Tracker {
pub fn new<S: Into<String>>(
deadline: Duration,
bound: Option<u64>,
known: impl IntoIterator<Item = S>,
) -> Self {
let held = known
.into_iter()
.map(|m| {
(
m.into(),
Held {
known: true,
state: MemberState::Idle { after_end: false },
},
)
})
.collect();
Self {
deadline,
bound,
start: None,
owner: OwnerState::Unseen,
owner_since: None,
held,
epoch: false,
seen: BTreeMap::new(),
beyond: BTreeSet::new(),
}
}
#[must_use]
pub fn with_epoch(mut self) -> Self {
self.epoch = true;
self
}
#[must_use]
pub fn deadline(&self) -> Duration {
self.deadline
}
#[must_use]
pub fn owner(&self) -> OwnerState {
self.owner
}
pub fn held(&self) -> impl Iterator<Item = &str> {
self.held.keys().map(String::as_str)
}
#[must_use]
pub fn state(&self, member: &str) -> Option<MemberState> {
self.held.get(member).map(|h| h.state)
}
#[must_use]
pub fn next_due(&self) -> Option<Mono> {
self.held
.values()
.filter_map(|h| match h.state {
MemberState::Heard { last } => Some(last),
MemberState::Waiting { since } => Some(since),
_ => None,
})
.min()
.map(|t| t.saturating_add(self.deadline))
}
pub fn observe(&mut self, at: Mono, event: Event<'_>) -> Vec<Report> {
let mut out = self.evaluate(at);
self.apply(at, event, &mut out);
out
}
fn evaluate(&mut self, at: Mono) -> Vec<Report> {
let (d, bound, owner) = (self.deadline, detection_bound(self.deadline), self.owner);
let mut out = Vec::new();
let mut forgotten = Vec::new();
for (name, h) in &mut self.held {
let from = match h.state {
MemberState::Heard { last } => Some((last, Some(last))),
MemberState::Waiting { since } => Some((since, None)),
_ => None,
};
if let Some((from, last)) = from {
let due = from.saturating_add(d);
if at > due {
h.state = MemberState::Missed { last };
out.push(Report::Missed {
at,
member: name.clone(),
due,
by: due.saturating_add(bound),
owner,
});
}
}
if !h.known
&& let MemberState::Missed { last: Some(last) } = h.state
&& at.saturating_since(last) >= FORGET_AFTER
{
forgotten.push(name.clone());
out.push(Report::Ended {
at,
member: name.clone(),
reason: EndReason::Forgotten,
});
}
}
for name in forgotten {
self.held.remove(&name);
}
out
}
fn wait_known(&mut self, since: Mono) {
for h in self.held.values_mut() {
if h.known && h.state == (MemberState::Idle { after_end: false }) {
h.state = MemberState::Waiting { since };
}
}
}
fn apply(&mut self, at: Mono, event: Event<'_>, out: &mut Vec<Report>) {
match event {
Event::Start => {
if self.start.is_some() {
return;
}
self.start = Some(at);
if self.epoch {
for (name, h) in &mut self.held {
if let Some(seen) = self.seen.get(name)
&& h.known
&& matches!(h.state, MemberState::Idle { .. })
{
h.state = MemberState::Waiting {
since: (*seen).max(at),
};
}
}
} else if self.owner == OwnerState::Present {
let since = self.owner_since.map_or(at, |s| s.max(at));
self.wait_known(since);
}
}
Event::Arrival { member, expired } => {
if self.start.is_none() || expired {
return;
}
if let Some(h) = self.held.get_mut(member) {
let was_missed = matches!(h.state, MemberState::Missed { .. });
h.state = MemberState::Heard { last: at };
if was_missed {
out.push(Report::Met {
at,
member: member.to_owned(),
});
}
} else if self
.bound
.is_some_and(|b| u64::try_from(self.held.len()).unwrap_or(u64::MAX) >= b)
{
if self.beyond.insert(member.to_owned()) {
out.push(Report::BeyondBound {
at,
member: member.to_owned(),
});
}
} else {
self.beyond.remove(member);
self.held.insert(
member.to_owned(),
Held {
known: false,
state: MemberState::Heard { last: at },
},
);
}
}
Event::Owner(state) => match (self.owner, state) {
(OwnerState::Unseen | OwnerState::Absent, OwnerState::Present) => {
self.owner = OwnerState::Present;
self.owner_since = Some(at);
if let Some(start) = self.start
&& !self.epoch
{
self.wait_known(at.max(start));
}
}
(OwnerState::Unconfirmed, OwnerState::Present)
| (OwnerState::Present, OwnerState::Unconfirmed) => self.owner = state,
(_, OwnerState::Absent) => {
self.owner = OwnerState::Absent;
self.owner_since = None;
if !self.epoch {
for h in self.held.values_mut() {
if matches!(h.state, MemberState::Waiting { .. }) {
h.state = MemberState::Idle { after_end: false };
}
}
}
}
_ => {}
},
Event::MemberSeen(member) => {
if !self.epoch || self.seen.contains_key(member) {
return;
}
self.seen.insert(member.to_owned(), at);
if self.start.is_some()
&& let Some(h) = self.held.get_mut(member)
&& h.known
&& matches!(h.state, MemberState::Idle { .. })
{
h.state = MemberState::Waiting { since: at };
}
}
Event::MemberGone(member) => {
if self.epoch && self.seen.remove(member).is_none() {
return;
}
let Some(h) = self.held.get_mut(member) else {
return;
};
if matches!(
h.state,
MemberState::Heard { .. } | MemberState::Missed { .. }
) {
out.push(Report::Ended {
at,
member: member.to_owned(),
reason: EndReason::Gone,
});
}
if h.known {
h.state = MemberState::Idle { after_end: true };
} else {
self.held.remove(member);
}
}
Event::Tick => {}
}
}
}
#[must_use]
pub fn zid_value(s: &str) -> Option<u128> {
let ok = !s.is_empty() && s.len() <= 32 && s.bytes().all(|b| b.is_ascii_hexdigit());
if ok {
u128::from_str_radix(s, 16).ok()
} else {
None
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Stamped {
pub age: StampAge,
pub id: u128,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SampleVerdict {
Live,
Expired,
Unobservable,
NotAsked,
NotThisProfiles,
}
impl SampleVerdict {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Live => "live",
Self::Expired => "expired",
Self::Unobservable => "unobservable",
Self::NotAsked => "not_asked",
Self::NotThisProfiles => "not_this_profiles",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
Some(match s {
"live" => Self::Live,
"expired" => Self::Expired,
"unobservable" => Self::Unobservable,
"not_asked" => Self::NotAsked,
"not_this_profiles" => Self::NotThisProfiles,
_ => return None,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Reason {
Kind,
Invalid,
NoDeadline,
NoPeriod,
NoLifespan,
BelowPeriod,
AcrossFace,
Lost,
Missed,
OwnerNotPresent,
Ended,
NotHeard,
WindowTooShort,
Met,
Kept,
NotKept,
Expired,
Live,
NoBound,
Unstamped,
Unattributed,
ForeignStamp,
ClockDisagrees,
NoSample,
}
impl Reason {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Kind => "kind",
Self::Invalid => "invalid",
Self::NoDeadline => "no_deadline",
Self::NoPeriod => "no_period",
Self::NoLifespan => "no_lifespan",
Self::BelowPeriod => "below_period",
Self::AcrossFace => "across_face",
Self::Lost => "lost",
Self::Missed => "missed",
Self::OwnerNotPresent => "owner_not_present",
Self::Ended => "ended",
Self::NotHeard => "not_heard",
Self::WindowTooShort => "window_too_short",
Self::Met => "met",
Self::Kept => "kept",
Self::NotKept => "not_kept",
Self::Expired => "expired",
Self::Live => "live",
Self::NoBound => "no_bound",
Self::Unstamped => "unstamped",
Self::Unattributed => "unattributed",
Self::ForeignStamp => "foreign_stamp",
Self::ClockDisagrees => "clock_disagrees",
Self::NoSample => "no_sample",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
[
Self::Kind,
Self::Invalid,
Self::NoDeadline,
Self::NoPeriod,
Self::NoLifespan,
Self::BelowPeriod,
Self::AcrossFace,
Self::Lost,
Self::Missed,
Self::OwnerNotPresent,
Self::Ended,
Self::NotHeard,
Self::WindowTooShort,
Self::Met,
Self::Kept,
Self::NotKept,
Self::Expired,
Self::Live,
Self::NoBound,
Self::Unstamped,
Self::Unattributed,
Self::ForeignStamp,
Self::ClockDisagrees,
Self::NoSample,
]
.into_iter()
.find(|r| r.as_str() == s)
}
#[must_use]
pub fn says(self) -> &'static str {
match self {
Self::Kind => "only a stream has a period, a deadline or a lifespan",
Self::Invalid => "its timing declaration is invalid",
Self::NoDeadline => "no timing.deadline_ms",
Self::NoPeriod => "no timing.period_ms",
Self::NoLifespan => "no timing.lifespan_ms",
Self::BelowPeriod => "its deadline is below its period, so it is no deadline",
Self::AcrossFace => "read across a constrained face, where presence does not cross",
Self::Lost => "this reader lost a delivery, or stalled, in the window",
Self::Missed => "nothing arrived within its deadline while its owner was present",
Self::OwnerNotPresent => "its owner was not present throughout",
Self::Ended => "the member ended in the window",
Self::NotHeard => "the member was not heard in the window",
Self::WindowTooShort => "the window was too short to tell",
Self::Met => "every arrival within its deadline",
Self::Kept => "published at its period",
Self::NotKept => "fewer samples arrived than its period promises",
Self::Expired => "a sample arrived older than its lifespan",
Self::Live => "every sample arrived within its lifespan",
Self::NoBound => {
"the deployment states no bound on its clocks, so nothing is discarded"
}
Self::Unstamped => "the sample carries no stamp",
Self::Unattributed => {
"no meta.zid is held for the provider, so a stamp is unattributable"
}
Self::ForeignStamp => "the stamp is not the owner's: a router's, or another session's",
Self::ClockDisagrees => {
"the stamp's clock was seen ahead of this reader's by more than the stated bound"
}
Self::NoSample => "no sample was read",
}
}
}
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 Sample {
pub verdict: SampleVerdict,
pub reason: Reason,
}
impl Sample {
const fn new(verdict: SampleVerdict, reason: Reason) -> Self {
Self { verdict, reason }
}
#[must_use]
pub fn discarded(&self) -> bool {
self.verdict == SampleVerdict::Expired
}
}
#[derive(Debug, Clone)]
pub struct LifespanReader {
premise: Result<Duration, Sample>,
epsilon: Option<Duration>,
owners: BTreeSet<u128>,
clocks: BTreeMap<u128, ClockMeasure>,
}
impl LifespanReader {
pub fn new(
kind: Kind,
d: &Declaration,
epsilon: Option<Duration>,
owners: impl IntoIterator<Item = u128>,
) -> Self {
let premise = if kind != Kind::Stream {
Err(Sample::new(SampleVerdict::NotThisProfiles, Reason::Kind))
} else {
match d {
Declaration::Invalid(_) => {
Err(Sample::new(SampleVerdict::Unobservable, Reason::Invalid))
}
Declaration::Declared(Declared {
lifespan: Some(l), ..
}) => Ok(*l),
_ => Err(Sample::new(SampleVerdict::NotAsked, Reason::NoLifespan)),
}
};
Self {
premise,
epsilon,
owners: owners.into_iter().collect(),
clocks: BTreeMap::new(),
}
}
pub fn set_owners(&mut self, owners: impl IntoIterator<Item = u128>) {
self.owners = owners.into_iter().collect();
}
pub fn judge(&mut self, stamp: Option<Stamped>) -> Sample {
use Reason as R;
use SampleVerdict as V;
let lifespan = match self.premise {
Ok(l) => l,
Err(s) => return s,
};
let Some(eps) = self.epsilon else {
return Sample::new(V::Unobservable, R::NoBound);
};
let Some(stamp) = stamp else {
return Sample::new(V::Unobservable, R::Unstamped);
};
if self.owners.is_empty() {
return Sample::new(V::Unobservable, R::Unattributed);
}
if !self.owners.contains(&stamp.id) {
return Sample::new(V::Unobservable, R::ForeignStamp);
}
let m = self
.clocks
.entry(stamp.id)
.and_modify(|m| m.record(stamp.age))
.or_insert_with(|| ClockMeasure::new(stamp.age));
let e = eps.as_nanos() as i128;
if m.most_ahead().nanos() < -e {
return Sample::new(V::Unobservable, R::ClockDisagrees);
}
if stamp.age.nanos() - e > lifespan.as_nanos() as i128 {
Sample::new(V::Expired, R::Expired)
} else {
Sample::new(V::Live, R::Live)
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PeriodVerdict {
NotHeard,
TooShort,
Kept,
NotKept,
}
impl PeriodVerdict {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::NotHeard => "not_heard",
Self::TooShort => "too_short",
Self::Kept => "kept",
Self::NotKept => "not_kept",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
Some(match s {
"not_heard" => Self::NotHeard,
"too_short" => Self::TooShort,
"kept" => Self::Kept,
"not_kept" => Self::NotKept,
_ => return None,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PeriodReading {
pub verdict: PeriodVerdict,
pub arrivals: u64,
pub span: Option<Duration>,
}
#[must_use]
pub fn period_window(
period: Duration,
from: Mono,
to: Mono,
known: bool,
ended: Option<Mono>,
arrivals: &[Mono],
) -> PeriodReading {
let start = if known {
Some(from)
} else {
arrivals.iter().copied().find(|t| (from..=to).contains(t))
};
let Some(start) = start else {
return PeriodReading {
verdict: PeriodVerdict::NotHeard,
arrivals: 0,
span: None,
};
};
let end = ended.unwrap_or(to);
let span = end.saturating_since(start);
let n = arrivals
.iter()
.filter(|t| (start..=end).contains(*t))
.count() as u64;
let (p, s) = (period.as_nanos(), span.as_nanos());
let verdict = if s < 3 * p {
PeriodVerdict::TooShort
} else if (u128::from(n) + 2) * p >= s {
PeriodVerdict::Kept
} else {
PeriodVerdict::NotKept
};
PeriodReading {
verdict,
arrivals: n,
span: Some(span),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Answer {
Yes,
No,
Unobservable,
NotAsked,
NotThisProfiles,
}
impl Answer {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Yes => "yes",
Self::No => "no",
Self::Unobservable => "unobservable",
Self::NotAsked => "not_asked",
Self::NotThisProfiles => "not_this_profiles",
}
}
}
impl fmt::Display for Answer {
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 answer: Answer,
pub reason: Reason,
}
impl Judged {
const fn new(answer: Answer, reason: Reason) -> Self {
Self { answer, reason }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Window {
pub across_face: bool,
pub lost: bool,
pub owner_present: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DeadlineAccount {
pub held: Duration,
pub missed_present: u32,
pub missed_not_present: u32,
pub ended: bool,
}
impl DeadlineAccount {
pub fn count(&mut self, r: &Report) {
if let Report::Missed { owner, .. } = r {
if *owner == OwnerState::Present {
self.missed_present += 1;
} else {
self.missed_not_present += 1;
}
}
if matches!(r, Report::Ended { .. }) {
self.ended = true;
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct HeldSpan {
longest: Duration,
from: Option<Mono>,
ended: Option<Mono>,
}
impl HeldSpan {
#[must_use]
pub fn held_to(&self, at: Mono) -> Duration {
self.longest
.max(self.from.map_or(Duration::ZERO, |f| at.saturating_since(f)))
}
#[must_use]
pub fn ended(&self) -> Option<Mono> {
self.ended
}
#[must_use]
pub fn counting(&self) -> bool {
self.from.is_some()
}
fn run(&mut self, at: Mono) {
if self.from.is_none() && self.ended.is_none() {
self.from = Some(at);
}
}
fn stop(&mut self, at: Mono) {
if let Some(f) = self.from.take() {
self.longest = self.longest.max(at.saturating_since(f));
}
}
}
#[derive(Debug, Clone, Default)]
pub struct Holding {
spans: BTreeMap<String, HeldSpan>,
closed: bool,
}
impl Holding {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn observe(&mut self, tracker: &Tracker, event: Event<'_>, reports: &[Report], at: Mono) {
if self.closed {
return;
}
for r in reports {
if let Report::Ended { member, .. } = r {
let s = self.spans.entry(member.clone()).or_default();
s.stop(at);
s.ended.get_or_insert(at);
}
}
let touched = match event {
Event::Arrival { member, .. }
| Event::MemberSeen(member)
| Event::MemberGone(member) => Some(member),
Event::Start | Event::Owner(_) | Event::Tick => None,
};
match touched {
Some(member) => {
let mut names: Vec<&str> = vec![member];
names.extend(reports.iter().map(Report::member));
names.sort_unstable();
names.dedup();
for name in names {
self.move_one(tracker, name, at);
}
}
None => {
for name in tracker.held() {
self.move_one(tracker, name, at);
}
for (name, s) in &mut self.spans {
if s.counting() && tracker.state(name).is_none() {
s.stop(at);
}
}
}
}
}
fn move_one(&mut self, tracker: &Tracker, name: &str, at: Mono) {
let Some(state) = tracker.state(name) else {
if let Some(s) = self.spans.get_mut(name) {
s.stop(at);
}
return;
};
let counts = matches!(
state,
MemberState::Heard { .. } | MemberState::Missed { .. } | MemberState::Waiting { .. }
);
if !counts && !self.spans.contains_key(name) {
self.spans.insert(name.to_owned(), HeldSpan::default());
return;
}
let s = self.spans.entry(name.to_owned()).or_default();
if counts {
s.run(at);
} else {
s.stop(at);
}
}
pub fn close(&mut self, at: Mono) {
for s in self.spans.values_mut() {
s.stop(at);
}
self.closed = true;
}
pub fn spans(&self) -> impl Iterator<Item = (&str, &HeldSpan)> {
self.spans.iter().map(|(k, s)| (k.as_str(), s))
}
#[must_use]
pub fn span(&self, member: &str) -> Option<&HeldSpan> {
self.spans.get(member)
}
}
fn premise(kind: Kind, d: &Declaration) -> Result<Declared, Judged> {
if kind != Kind::Stream {
return Err(Judged::new(Answer::NotThisProfiles, Reason::Kind));
}
match d {
Declaration::Invalid(_) => Err(Judged::new(Answer::Unobservable, Reason::Invalid)),
Declaration::Declared(x) => Ok(*x),
Declaration::NotThisProfiles | Declaration::Ignored => Ok(Declared::default()),
}
}
#[must_use]
pub fn deadline_met(kind: Kind, d: &Declaration, w: &Window, a: &DeadlineAccount) -> Judged {
use Answer as A;
use Reason as R;
let x = match premise(kind, d) {
Ok(x) => x,
Err(j) => return j,
};
let Some(deadline) = x.deadline else {
return Judged::new(A::NotAsked, R::NoDeadline);
};
if x.below_period() {
return Judged::new(A::Unobservable, R::BelowPeriod);
}
if w.across_face {
return Judged::new(A::Unobservable, R::AcrossFace);
}
if a.missed_present > 0 {
return if w.lost {
Judged::new(A::Unobservable, R::Lost)
} else {
Judged::new(A::No, R::Missed)
};
}
if a.missed_not_present > 0 {
return Judged::new(A::Unobservable, R::OwnerNotPresent);
}
if a.ended {
return Judged::new(A::NotAsked, R::Ended);
}
if a.held.is_zero() {
return Judged::new(A::NotAsked, R::NotHeard);
}
if a.held <= deadline {
return Judged::new(A::Unobservable, R::WindowTooShort);
}
Judged::new(A::Yes, R::Met)
}
#[must_use]
pub fn period_kept(kind: Kind, d: &Declaration, w: &Window, p: PeriodVerdict) -> Judged {
use Answer as A;
use Reason as R;
let x = match premise(kind, d) {
Ok(x) => x,
Err(j) => return j,
};
if x.period.is_none() {
return Judged::new(A::NotAsked, R::NoPeriod);
}
if w.across_face {
return Judged::new(A::Unobservable, R::AcrossFace);
}
match p {
PeriodVerdict::NotHeard => Judged::new(A::NotAsked, R::NotHeard),
PeriodVerdict::TooShort => Judged::new(A::Unobservable, R::WindowTooShort),
PeriodVerdict::Kept => Judged::new(A::Yes, R::Kept),
PeriodVerdict::NotKept if w.lost => Judged::new(A::Unobservable, R::Lost),
PeriodVerdict::NotKept if !w.owner_present => {
Judged::new(A::Unobservable, R::OwnerNotPresent)
}
PeriodVerdict::NotKept => Judged::new(A::No, R::NotKept),
}
}
#[must_use]
pub fn lifespan_expired(kind: Kind, d: &Declaration, samples: &[Sample]) -> Judged {
use Answer as A;
use Reason as R;
let x = match premise(kind, d) {
Ok(x) => x,
Err(j) => return j,
};
if x.lifespan.is_none() {
return Judged::new(A::NotAsked, R::NoLifespan);
}
if samples.iter().any(|s| s.verdict == SampleVerdict::Expired) {
return Judged::new(A::Yes, R::Expired);
}
if let Some(s) = samples
.iter()
.find(|s| s.verdict == SampleVerdict::Unobservable)
{
return Judged::new(A::Unobservable, s.reason);
}
if samples.iter().any(|s| s.verdict == SampleVerdict::Live) {
return Judged::new(A::No, R::Live);
}
Judged::new(A::Unobservable, R::NoSample)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Question {
Deadline,
Period,
Lifespan,
}
impl Question {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Deadline => "deadline",
Self::Period => "period",
Self::Lifespan => "lifespan",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
Some(match s {
"deadline" => Self::Deadline,
"period" => Self::Period,
"lifespan" => Self::Lifespan,
_ => return None,
})
}
#[must_use]
pub fn finding(self) -> Answer {
match self {
Self::Deadline | Self::Period => Answer::No,
Self::Lifespan => Answer::Yes,
}
}
}
#[must_use]
pub fn roll_up(question: Question, answers: impl IntoIterator<Item = Answer>) -> Answer {
let finding = question.finding();
let other = if finding == Answer::Yes {
Answer::No
} else {
Answer::Yes
};
let (mut poles, mut unestablished) = (0u64, false);
let (mut aside, mut not_asked) = (0u64, false);
for a in answers {
if a == finding {
return finding;
}
match a {
Answer::NotAsked => {
aside += 1;
not_asked = true;
}
Answer::NotThisProfiles => aside += 1,
a if a == other => poles += 1,
_ => unestablished = true,
}
}
if unestablished {
Answer::Unobservable
} else if poles > 0 {
other
} else if aside == 0 {
Answer::Unobservable
} else if not_asked {
Answer::NotAsked
} else {
Answer::NotThisProfiles
}
}
pub fn roll_up_first<K: AsRef<str>, R>(
question: Question,
members: impl IntoIterator<Item = (K, Answer, R)>,
) -> (Answer, Option<(K, R)>) {
let members: Vec<(K, Answer, R)> = members.into_iter().collect();
let answer = roll_up(question, members.iter().map(|(_, a, _)| *a));
let first = members
.into_iter()
.filter(|(_, a, _)| *a == answer)
.min_by(|(x, _, _), (y, _, _)| x.as_ref().as_bytes().cmp(y.as_ref().as_bytes()))
.map(|(k, _, r)| (k, r));
(answer, first)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn ann(pairs: &[(&str, Value)]) -> BTreeMap<String, Value> {
pairs
.iter()
.map(|(k, v)| ((*k).to_owned(), v.clone()))
.collect()
}
fn ms(n: u64) -> Mono {
Mono::after(Duration::from_millis(n))
}
#[test]
fn a_value_is_a_whole_number_of_milliseconds_above_zero() {
let d = |v: Value| declaration(Kind::Stream, &ann(&[(DEADLINE_MS, v)]));
assert_eq!(
d(json!(100)).declared().and_then(|x| x.deadline),
Some(Duration::from_millis(100))
);
assert_eq!(
d(json!(100.0)).declared().and_then(|x| x.deadline),
Some(Duration::from_millis(100))
);
for bad in [
json!(0),
json!(-0.0),
json!(-1),
json!(1.5),
json!(MAX_MS + 1),
] {
assert_eq!(d(bad), Declaration::Invalid(vec![Invalid::DeadlineValue]));
}
assert_eq!(
declaration(Kind::State, &ann(&[(DEADLINE_MS, json!("x"))])),
Declaration::Ignored,
"the kind first"
);
}
#[test]
fn the_bound_has_a_millisecond_floor() {
assert_eq!(
detection_bound(Duration::from_millis(100)),
Duration::from_millis(2)
);
assert_eq!(detection_bound(Duration::from_millis(30)), BOUND_FLOOR);
assert_eq!(
detection_bound(Duration::from_millis(75)),
Duration::from_micros(1500)
);
}
#[test]
fn a_paused_commander_is_missed_once_then_met() {
let mut t = Tracker::new(Duration::from_millis(100), Some(1), ["cmd"]);
t.observe(ms(0), Event::Owner(OwnerState::Present));
t.observe(ms(0), Event::Start);
let arrive = |t: &mut Tracker, at| {
t.observe(
ms(at),
Event::Arrival {
member: "cmd",
expired: false,
},
)
};
assert!(arrive(&mut t, 10).is_empty());
assert_eq!(t.next_due(), Some(ms(110)));
let r = t.observe(ms(111), Event::Tick);
assert_eq!(r.len(), 1);
assert_eq!(r[0].as_str(), "missed");
assert!(t.observe(ms(500), Event::Tick).is_empty(), "edge-triggered");
let r = arrive(&mut t, 600);
assert_eq!(r.len(), 1);
assert_eq!(r[0].as_str(), "met");
}
#[test]
fn a_clock_ahead_beyond_epsilon_stays_unobservable() {
let d = declaration(Kind::Stream, &ann(&[(LIFESPAN_MS, json!(100))]));
let mut r = LifespanReader::new(Kind::Stream, &d, Some(Duration::from_millis(10)), [7]);
let at = |s: f64| {
Some(Stamped {
age: StampAge::from_secs_f64(s),
id: 7,
})
};
assert_eq!(r.judge(at(0.05)).reason, Reason::Live);
assert_eq!(r.judge(at(-0.05)).reason, Reason::ClockDisagrees);
assert_eq!(r.judge(at(0.05)).reason, Reason::ClockDisagrees);
assert_eq!(
r.judge(Some(Stamped {
age: StampAge::from_secs_f64(0.5),
id: 8
}))
.reason,
Reason::ForeignStamp
);
}
#[test]
fn the_roll_up_reads_each_questions_finding() {
let d = Question::Deadline;
assert_eq!(roll_up(d, [Answer::Yes, Answer::NotAsked]), Answer::Yes);
assert_eq!(
roll_up(d, [Answer::Yes, Answer::Unobservable]),
Answer::Unobservable
);
assert_eq!(roll_up(d, [Answer::Unobservable, Answer::No]), Answer::No);
assert_eq!(roll_up(d, []), Answer::Unobservable);
let l = Question::Lifespan;
assert_eq!(roll_up(l, [Answer::No, Answer::Yes]), Answer::Yes, "F-264");
assert_eq!(roll_up(l, [Answer::No, Answer::No]), Answer::No);
assert_eq!(roll_up(l, [Answer::NotAsked]), Answer::NotAsked);
assert_eq!(
roll_up(l, [Answer::NotThisProfiles, Answer::NotAsked]),
Answer::NotAsked
);
assert_eq!(
roll_up(Question::Period, [Answer::NotThisProfiles]),
Answer::NotThisProfiles
);
assert_eq!(
roll_up(d, [Answer::NotAsked, Answer::Unobservable]),
Answer::Unobservable,
"an unobservable member is never set aside"
);
}
#[test]
fn a_roll_ups_reason_is_its_first_members_in_byte_order() {
let d = Question::Deadline;
let (a, first) = roll_up_first(
d,
[
("axis/a", Answer::Unobservable, Reason::OwnerNotPresent),
("axis/B", Answer::Unobservable, Reason::WindowTooShort),
],
);
assert_eq!(
(a, first),
(
Answer::Unobservable,
Some(("axis/B", Reason::WindowTooShort))
),
"B (0x42) before a (0x61): bytes, never a locale"
);
let (a, first) = roll_up_first(
d,
[
("axis/a", Answer::Unobservable, Reason::Lost),
("cmd", Answer::No, Reason::Missed),
],
);
assert_eq!(
(a, first),
(Answer::No, Some(("cmd", Reason::Missed))),
"the first member giving the answer, not the first member"
);
let (a, first) = roll_up_first(
Question::Lifespan,
[
("a", Answer::NotThisProfiles, Reason::Kind),
("b", Answer::NotAsked, Reason::NoLifespan),
],
);
assert_eq!(
(a, first),
(Answer::NotAsked, Some(("b", Reason::NoLifespan)))
);
let (a, first) = roll_up_first(d, std::iter::empty::<(&str, Answer, Reason)>());
assert_eq!((a, first), (Answer::Unobservable, None));
}
fn holding_of(t: &mut Tracker, h: &mut Holding, at: u64, e: Event<'_>) -> Vec<Report> {
let r = t.observe(ms(at), e);
h.observe(t, e, &r, ms(at));
r
}
#[test]
fn a_known_member_is_held_only_while_it_is_waited_for() {
let mut t = Tracker::new(Duration::from_millis(500), Some(1), ["cmd"]);
let mut h = Holding::new();
holding_of(&mut t, &mut h, 0, Event::Owner(OwnerState::Present));
holding_of(&mut t, &mut h, 0, Event::Start);
holding_of(&mut t, &mut h, 150, Event::Owner(OwnerState::Unconfirmed));
holding_of(&mut t, &mut h, 330, Event::Owner(OwnerState::Absent));
let r = holding_of(&mut t, &mut h, 3000, Event::Tick);
assert!(r.is_empty(), "no miss: the wait stopped before its due");
h.close(ms(3000));
assert_eq!(
h.span("cmd").map(|s| s.held_to(ms(3000))),
Some(Duration::from_millis(330)),
"the unconfirmed while waits on (§2.5), the absence stops it"
);
let mut t = Tracker::new(Duration::from_millis(500), Some(1), ["cmd"]);
let mut h = Holding::new();
holding_of(&mut t, &mut h, 0, Event::Owner(OwnerState::Present));
holding_of(&mut t, &mut h, 0, Event::Start);
holding_of(&mut t, &mut h, 330, Event::Owner(OwnerState::Absent));
holding_of(&mut t, &mut h, 1000, Event::Owner(OwnerState::Present));
let r = holding_of(&mut t, &mut h, 1501, Event::Tick);
assert_eq!(r.len(), 1, "{r:?}");
h.close(ms(2000));
assert_eq!(
h.span("cmd").map(|s| s.held_to(ms(2000))),
Some(Duration::from_millis(1000))
);
}
#[test]
fn two_short_waits_hold_the_longer_never_their_sum() {
let mut t = Tracker::new(Duration::from_millis(500), Some(1), ["cmd"]);
let mut h = Holding::new();
holding_of(&mut t, &mut h, 0, Event::Owner(OwnerState::Present));
holding_of(&mut t, &mut h, 0, Event::Start);
holding_of(&mut t, &mut h, 300, Event::Owner(OwnerState::Absent));
holding_of(&mut t, &mut h, 1000, Event::Owner(OwnerState::Present));
holding_of(&mut t, &mut h, 1400, Event::Owner(OwnerState::Absent));
let r = holding_of(&mut t, &mut h, 3000, Event::Tick);
assert!(r.is_empty(), "no miss in either wait: {r:?}");
h.close(ms(3000));
let held = h.span("cmd").map(|s| s.held_to(ms(3000))).unwrap();
assert_eq!(held, Duration::from_millis(400));
let d = declaration(
Kind::Stream,
&ann(&[(DEADLINE_MS, json!(500)), (PERIOD_MS, json!(100))]),
);
let account = DeadlineAccount {
held,
..DeadlineAccount::default()
};
let j = deadline_met(Kind::Stream, &d, &Window::default(), &account);
assert_eq!(
(j.answer, j.reason),
(Answer::Unobservable, Reason::WindowTooShort)
);
}
#[test]
fn a_member_heard_again_is_held_over_its_first_life() {
let mut t =
Tracker::new(Duration::from_millis(500), Some(4), Vec::<String>::new()).with_epoch();
let mut h = Holding::new();
holding_of(&mut t, &mut h, 0, Event::Owner(OwnerState::Present));
holding_of(&mut t, &mut h, 0, Event::Start);
holding_of(&mut t, &mut h, 0, Event::MemberSeen("axis/x"));
let arrival = Event::Arrival {
member: "axis/x",
expired: false,
};
for at in [100, 500, 900] {
holding_of(&mut t, &mut h, at, arrival);
}
let r = holding_of(&mut t, &mut h, 1100, Event::MemberGone("axis/x"));
assert_eq!(r.len(), 1, "ended, and no miss: {r:?}");
holding_of(&mut t, &mut h, 2000, Event::MemberSeen("axis/x"));
holding_of(&mut t, &mut h, 2000, arrival);
holding_of(&mut t, &mut h, 4000, arrival);
h.close(ms(5000));
let s = h.span("axis/x").copied().expect("held");
assert_eq!(s.ended(), Some(ms(1100)));
assert_eq!(s.held_to(ms(5000)), Duration::from_millis(1000));
}
}