use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use crate::error::{AccountError, Result};
pub trait Clock: Send + Sync + std::fmt::Debug {
fn now_unix(&self) -> Result<u64>;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemClock;
impl Clock for SystemClock {
fn now_unix(&self) -> Result<u64> {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|elapsed| elapsed.as_secs())
.map_err(|_| {
AccountError::PolicyIndeterminate(
"system clock is set before the UNIX epoch".to_string(),
)
})
}
}
#[derive(Debug)]
pub struct FixedClock(AtomicU64);
impl FixedClock {
pub fn new(now: u64) -> Self {
Self(AtomicU64::new(now))
}
pub fn set(&self, now: u64) {
self.0.store(now, Ordering::SeqCst);
}
}
impl Clock for FixedClock {
fn now_unix(&self) -> Result<u64> {
Ok(self.0.load(Ordering::SeqCst))
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct UnreadableClock;
impl Clock for UnreadableClock {
fn now_unix(&self) -> Result<u64> {
Err(AccountError::PolicyIndeterminate(
"clock unavailable".to_string(),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_system_clock_reads_a_plausible_present() {
let now = SystemClock.now_unix().unwrap();
assert!(now > 1_577_836_800, "{now}");
assert!(now < 4_102_444_800, "{now}");
}
#[test]
fn a_fixed_clock_reports_exactly_what_it_was_set_to() {
let clock = FixedClock::new(1_000);
assert_eq!(clock.now_unix().unwrap(), 1_000);
clock.set(2_000);
assert_eq!(clock.now_unix().unwrap(), 2_000);
}
#[test]
fn an_unreadable_clock_is_indeterminate_never_a_fallback_reading() {
let err = UnreadableClock.now_unix().unwrap_err();
assert!(matches!(err, AccountError::PolicyIndeterminate(_)));
}
}