use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::Arc;
use std::time::Duration;
#[derive(Debug, Clone)]
pub struct WorkflowTime {
started_at_ms: i64,
now_ms: Arc<AtomicI64>,
}
impl WorkflowTime {
pub fn new(started_at: i64) -> Self {
Self::from_millis(started_at.saturating_mul(1000))
}
pub(crate) fn from_millis(started_at_ms: i64) -> Self {
Self {
started_at_ms,
now_ms: Arc::new(AtomicI64::new(started_at_ms)),
}
}
pub(crate) fn advance_to(&self, at_ms: i64) {
self.now_ms.fetch_max(at_ms, Ordering::SeqCst);
}
fn now_millis(&self) -> i64 {
self.now_ms.load(Ordering::SeqCst)
}
pub fn now(&self) -> i64 {
self.now_millis().div_euclid(1000)
}
pub fn started_at(&self) -> i64 {
self.started_at_ms.div_euclid(1000)
}
pub fn elapsed(&self) -> Duration {
let elapsed_ms = self.now_millis().saturating_sub(self.started_at_ms);
Duration::from_millis(elapsed_ms.max(0) as u64)
}
pub fn elapsed_secs(&self) -> u64 {
self.elapsed().as_secs()
}
pub fn elapsed_millis(&self) -> u128 {
self.elapsed().as_millis()
}
}
#[cfg(test)]
mod tests {
use super::*;
const START: i64 = 1_704_067_200;
#[test]
fn a_new_clock_reads_its_start() {
let time = WorkflowTime::new(START);
assert_eq!(time.now(), START);
assert_eq!(time.started_at(), START);
assert_eq!(time.elapsed(), Duration::ZERO);
}
#[test]
fn the_clock_does_not_follow_the_wall_clock() {
let time = WorkflowTime::new(START);
std::thread::sleep(Duration::from_millis(1_100));
assert_eq!(time.now(), START);
assert_eq!(time.elapsed(), Duration::ZERO);
}
#[test]
fn advancing_moves_now_and_elapsed_but_not_the_start() {
let time = WorkflowTime::new(START);
time.advance_to((START + 90) * 1000 + 250);
assert_eq!(time.now(), START + 90);
assert_eq!(time.started_at(), START);
assert_eq!(time.elapsed(), Duration::from_millis(90_250));
assert_eq!(time.elapsed_secs(), 90);
assert_eq!(time.elapsed_millis(), 90_250);
}
#[test]
fn the_clock_never_moves_back() {
let time = WorkflowTime::new(START);
time.advance_to((START + 60) * 1000);
time.advance_to((START + 10) * 1000);
time.advance_to((START - 10) * 1000);
assert_eq!(time.now(), START + 60);
}
#[test]
fn clones_share_one_clock() {
let time = WorkflowTime::new(START);
let clone = time.clone();
time.advance_to((START + 5) * 1000);
assert_eq!(clone.now(), START + 5);
}
#[test]
fn times_before_the_epoch_round_down() {
let time = WorkflowTime::from_millis(-1_500);
assert_eq!(time.now(), -2);
assert_eq!(time.started_at(), -2);
}
#[test]
fn debug_names_the_start() {
let debug = format!("{:?}", WorkflowTime::new(START));
assert!(debug.contains("WorkflowTime"));
assert!(debug.contains("started_at"));
}
}