use std::fmt;
use std::time::Duration;
use crate::relogio::Instant;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct StaleAfter {
window_ms: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("a freshness window must be at least 1ms (got {requested:?})")]
pub struct WindowTooShort {
pub requested: Duration,
}
impl StaleAfter {
pub fn new(window: Duration) -> Result<Self, WindowTooShort> {
let window_ms = u64::try_from(window.as_millis()).unwrap_or(u64::MAX);
if window_ms == 0 {
return Err(WindowTooShort { requested: window });
}
Ok(Self { window_ms })
}
#[must_use]
pub const fn from_secs(secs: std::num::NonZeroU64) -> Self {
Self {
window_ms: secs.get().saturating_mul(1000),
}
}
#[must_use]
pub const fn get(self) -> Duration {
Duration::from_millis(self.window_ms)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Freshness {
NeverObserved,
Fresh,
Stale {
since: Instant,
},
}
impl Freshness {
#[must_use]
pub fn judge(last: Option<Instant>, now: Instant, window: StaleAfter) -> Self {
match last {
None => Self::NeverObserved,
Some(at) => {
let age_ms = now.physical_ms.saturating_sub(at.physical_ms);
if age_ms > window.window_ms {
Self::Stale { since: at }
} else {
Self::Fresh
}
}
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::NeverObserved => "never_observed",
Self::Fresh => "fresh",
Self::Stale { .. } => "stale",
}
}
}
impl fmt::Display for Freshness {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Stale { since } => write!(f, "stale since {since}"),
other => f.write_str(other.as_str()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TaskState {
Running,
Ended,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Liveness {
Unknown,
Alive,
Stalled {
since: Instant,
},
Dead,
}
impl Liveness {
#[must_use]
pub fn judge(
task: TaskState,
last_beat: Option<Instant>,
now: Instant,
window: StaleAfter,
) -> Self {
match task {
TaskState::Ended => Self::Dead,
TaskState::Running => Freshness::judge(last_beat, now, window).into(),
}
}
#[must_use]
pub const fn is_alive(self) -> bool {
matches!(self, Self::Alive)
}
#[must_use]
pub const fn is_observed(self) -> bool {
!matches!(self, Self::Unknown)
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Unknown => "unknown",
Self::Alive => "alive",
Self::Stalled { .. } => "stalled",
Self::Dead => "dead",
}
}
}
impl From<Freshness> for Liveness {
fn from(f: Freshness) -> Self {
match f {
Freshness::NeverObserved => Self::Unknown,
Freshness::Fresh => Self::Alive,
Freshness::Stale { since } => Self::Stalled { since },
}
}
}
impl fmt::Display for Liveness {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Stalled { since } => write!(f, "stalled since {since}"),
other => f.write_str(other.as_str()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::num::NonZeroU64;
fn window(secs: u64) -> StaleAfter {
StaleAfter::from_secs(NonZeroU64::new(secs).expect("test windows are non-zero"))
}
fn at(ms: u64) -> Instant {
Instant::from_ms(ms)
}
#[test]
fn nothing_observed_is_its_own_state_not_fresh_and_not_stale() {
assert_eq!(
Freshness::judge(None, at(1_000_000), window(30)),
Freshness::NeverObserved
);
}
#[test]
fn an_observation_inside_the_window_is_fresh() {
assert_eq!(
Freshness::judge(Some(at(1_000)), at(1_000), window(30)),
Freshness::Fresh
);
assert_eq!(
Freshness::judge(Some(at(1_000)), at(31_000), window(30)),
Freshness::Fresh,
"exactly the window old is still fresh"
);
}
#[test]
fn one_millisecond_past_the_window_is_stale_and_says_since_when() {
assert_eq!(
Freshness::judge(Some(at(1_000)), at(31_001), window(30)),
Freshness::Stale { since: at(1_000) }
);
}
#[test]
fn an_observation_from_the_future_reads_fresh_rather_than_negative() {
assert_eq!(
Freshness::judge(Some(at(50_000)), at(1_000), window(30)),
Freshness::Fresh
);
}
#[test]
fn a_window_under_the_clock_resolution_cannot_be_built() {
assert_eq!(
StaleAfter::new(Duration::ZERO),
Err(WindowTooShort {
requested: Duration::ZERO
})
);
assert!(StaleAfter::new(Duration::from_micros(999)).is_err());
assert_eq!(
StaleAfter::new(Duration::from_millis(1)).map(StaleAfter::get),
Ok(Duration::from_millis(1))
);
assert_eq!(window(30).get(), Duration::from_secs(30));
}
#[test]
fn liveness_follows_freshness_while_the_task_runs() {
let w = window(30);
assert_eq!(
Liveness::judge(TaskState::Running, None, at(5_000), w),
Liveness::Unknown
);
assert_eq!(
Liveness::judge(TaskState::Running, Some(at(5_000)), at(6_000), w),
Liveness::Alive
);
assert_eq!(
Liveness::judge(TaskState::Running, Some(at(5_000)), at(40_000), w),
Liveness::Stalled { since: at(5_000) }
);
}
#[test]
fn an_ended_task_is_dead_whatever_its_last_beat_says() {
let w = window(30);
for last in [None, Some(at(5_000))] {
assert_eq!(
Liveness::judge(TaskState::Ended, last, at(5_001), w),
Liveness::Dead
);
}
}
#[test]
fn only_alive_may_render_as_ok_and_only_unknown_is_unobserved() {
let stalled = Liveness::Stalled { since: at(1) };
let all = [Liveness::Unknown, Liveness::Alive, stalled, Liveness::Dead];
let alive: Vec<bool> = all.iter().map(|l| l.is_alive()).collect();
assert_eq!(alive, [false, true, false, false]);
let observed: Vec<bool> = all.iter().map(|l| l.is_observed()).collect();
assert_eq!(observed, [false, true, true, true]);
}
#[test]
fn display_names_the_state_and_when_a_stall_began() {
assert_eq!(Liveness::Unknown.to_string(), "unknown");
assert_eq!(
Liveness::Stalled { since: at(7) }.to_string(),
"stalled since 7.00000"
);
assert_eq!(
Freshness::Stale { since: at(7) }.to_string(),
"stale since 7.00000"
);
assert_eq!(Freshness::NeverObserved.to_string(), "never_observed");
}
}