legit-streams 0.1.3

A Redis Streams work contract for task and result envelopes, with a worker loop that leases, reclaims and replies, a producer and a result reader
Documentation
//! Time for the worker and the in-memory double: the system's, or a manual clock tests move.

use std::collections::HashMap;
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::thread::{self, ThreadId};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

/// How long [`Clock::settle`] and [`Clock::advance`] wait, in real time, for the threads that
/// run on a manual clock to go idle before they give up.
const SETTLE_LIMIT: Duration = Duration::from_secs(10);

/// The time a [`Worker`](crate::Worker) and a [`MemoryStreams`](crate::MemoryStreams) run on: the
/// system's, or a manual clock that only a test moves.
///
/// On a manual clock, time stands still until [`Clock::advance`]. The worker's own threads, its
/// read loop and its lease heartbeat, take part in the clock: `advance` moves time forward one
/// timer at a time and lets each thread that wakes finish what it does before it moves on, so a
/// heartbeat due at 60 s runs before a claim due at 300 s, every time. [`Clock::settle`] waits for
/// the same threads to go idle without moving time. A handler runs on a thread of its own, which
/// doesn't take part: a test waits for it with a channel or similar.
///
/// The clock is a cheap handle; clones share one time.
///
/// ```
/// use std::time::Duration;
/// use legit_streams::Clock;
///
/// let clock = Clock::manual(1_700_000_000_000);
/// clock.advance(Duration::from_secs(5));
/// assert_eq!(clock.now_ms(), 1_700_000_005_000);
/// ```
#[derive(Clone)]
pub struct Clock {
    inner: Arc<Inner>,
}

struct Inner {
    origin: Option<Instant>,
    state: Mutex<State>,
    changed: Condvar,
}

#[derive(Default)]
struct State {
    now_ms: u64,
    next_id: u64,
    waiters: HashMap<u64, Waiter>,
    parties: HashMap<u64, Option<ThreadId>>,
}

struct Waiter {
    thread: ThreadId,
    deadline: Option<Duration>,
    signal: Option<(Arc<AtomicU64>, u64)>,
}

impl Waiter {
    fn is_due(&self, now: Duration) -> bool {
        self.signal
            .as_ref()
            .is_some_and(|(generation, seen)| generation.load(Ordering::SeqCst) != *seen)
            || self.deadline.is_some_and(|deadline| deadline <= now)
    }
}

impl Clock {
    /// The system clock.
    ///
    /// ```
    /// use legit_streams::Clock;
    ///
    /// assert!(!Clock::system().is_manual());
    /// ```
    #[must_use]
    pub fn system() -> Self {
        Self::with_origin(Some(Instant::now()), 0)
    }

    /// A manual clock that reads `start_ms`, milliseconds since the Unix epoch, until moved.
    ///
    /// ```
    /// use legit_streams::Clock;
    ///
    /// assert_eq!(Clock::manual(42).now_ms(), 42);
    /// ```
    #[must_use]
    pub fn manual(start_ms: u64) -> Self {
        Self::with_origin(None, start_ms)
    }

    fn with_origin(origin: Option<Instant>, now_ms: u64) -> Self {
        Self {
            inner: Arc::new(Inner {
                origin,
                state: Mutex::new(State {
                    now_ms,
                    ..State::default()
                }),
                changed: Condvar::new(),
            }),
        }
    }

    /// Whether this is a manual clock.
    ///
    /// ```
    /// use legit_streams::Clock;
    ///
    /// assert!(Clock::manual(0).is_manual());
    /// ```
    #[must_use]
    pub fn is_manual(&self) -> bool {
        self.inner.origin.is_none()
    }

    /// The time, in milliseconds since the Unix epoch.
    ///
    /// ```
    /// use legit_streams::Clock;
    ///
    /// assert!(Clock::system().now_ms() > 1_600_000_000_000);
    /// ```
    #[must_use]
    pub fn now_ms(&self) -> u64 {
        if self.is_manual() {
            self.lock().now_ms
        } else {
            let since_epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
            u64::try_from(since_epoch.as_millis()).unwrap_or(u64::MAX)
        }
    }

    /// Time for measuring how long something took: monotonic on the system clock, the manual
    /// time on a manual one.
    ///
    /// ```
    /// use std::time::Duration;
    /// use legit_streams::Clock;
    ///
    /// let clock = Clock::manual(1_000);
    /// let start = clock.monotonic();
    /// clock.advance(Duration::from_millis(250));
    /// assert_eq!(clock.monotonic() - start, Duration::from_millis(250));
    /// ```
    #[must_use]
    pub fn monotonic(&self) -> Duration {
        match self.inner.origin {
            Some(origin) => origin.elapsed(),
            None => Duration::from_millis(self.lock().now_ms),
        }
    }

    /// Wait until every thread taking part in this manual clock is idle: waiting for time to pass
    /// or for something that hasn't happened. Does nothing on the system clock.
    ///
    /// # Panics
    ///
    /// When a thread hasn't gone idle after 10 s of real time, which means it's blocked on
    /// something that only the caller can release.
    ///
    /// ```
    /// use legit_streams::Clock;
    ///
    /// Clock::manual(0).settle();
    /// ```
    pub fn settle(&self) {
        if self.is_manual() {
            let state = self.lock();
            drop(self.settle_locked(state));
        }
    }

    /// Move a manual clock forward by `by`, one due timer at a time, settling after each.
    ///
    /// # Panics
    ///
    /// On the system clock, and when a thread doesn't settle, as [`Clock::settle`] says.
    ///
    /// ```
    /// use std::time::Duration;
    /// use legit_streams::Clock;
    ///
    /// let clock = Clock::manual(0);
    /// clock.advance(Duration::from_millis(1_500));
    /// assert_eq!(clock.now_ms(), 1_500);
    /// ```
    #[track_caller]
    pub fn advance(&self, by: Duration) {
        assert!(self.is_manual(), "only a manual clock can be advanced");
        let mut state = self.lock();
        let target = state.now_ms.saturating_add(millis(by));
        loop {
            state = self.settle_locked(state);
            let now = Duration::from_millis(state.now_ms);
            let next = state
                .waiters
                .values()
                .filter_map(|waiter| waiter.deadline)
                .filter(|&d| d > now)
                .min();
            match next {
                Some(deadline) if millis(deadline) <= target => state.now_ms = millis(deadline),
                _ => {
                    state.now_ms = target;
                    self.inner.changed.notify_all();
                    drop(self.settle_locked(state));
                    return;
                }
            }
            self.inner.changed.notify_all();
        }
    }

    fn settle_locked<'a>(&'a self, mut state: MutexGuard<'a, State>) -> MutexGuard<'a, State> {
        let started = Instant::now();
        while !is_quiet(&state) {
            assert!(
                started.elapsed() < SETTLE_LIMIT,
                "a thread on the manual clock didn't go idle within {SETTLE_LIMIT:?}; is it blocked on the test?"
            );
            state = self
                .inner
                .changed
                .wait_timeout(state, Duration::from_millis(20))
                .unwrap_or_else(PoisonError::into_inner)
                .0;
        }
        state
    }

    /// Register a thread that takes part in a manual clock: [`Clock::settle`] waits for it until
    /// it's idle. Until [`Party::bind`] it counts as busy, so a thread being started counts too.
    pub(crate) fn party(&self) -> Party {
        let id = if self.is_manual() {
            let mut state = self.lock();
            state.next_id += 1;
            let id = state.next_id;
            state.parties.insert(id, None);
            Some(id)
        } else {
            None
        };
        Party {
            clock: self.clone(),
            id,
        }
    }

    /// Block until `signal` changes from `seen`, or until `deadline`, a time on the
    /// [`Clock::monotonic`] scale, passes. Returns at once when either already has.
    pub(crate) fn wait(&self, signal: Option<(&Signal, u64)>, deadline: Option<Duration>) {
        let mut state = self.lock();
        state.next_id += 1;
        let id = state.next_id;
        let waiter = Waiter {
            thread: thread::current().id(),
            deadline,
            signal: signal.map(|(signal, seen)| (Arc::clone(&signal.generation), seen)),
        };
        state.waiters.insert(id, waiter);
        loop {
            let now = self.now_locked(&state);
            if state.waiters[&id].is_due(now) {
                break;
            }
            state = match (self.inner.origin, deadline) {
                (Some(_), Some(deadline)) => {
                    self.inner
                        .changed
                        .wait_timeout(state, deadline.saturating_sub(now))
                        .unwrap_or_else(PoisonError::into_inner)
                        .0
                }
                _ => self.inner.changed.wait(state).unwrap_or_else(PoisonError::into_inner),
            };
        }
        state.waiters.remove(&id);
        self.inner.changed.notify_all();
    }

    /// Sleep for `duration` on this clock.
    pub(crate) fn sleep(&self, duration: Duration) {
        let deadline = self.monotonic().saturating_add(duration);
        self.wait(None, Some(deadline));
    }

    fn now_locked(&self, state: &State) -> Duration {
        match self.inner.origin {
            Some(origin) => origin.elapsed(),
            None => Duration::from_millis(state.now_ms),
        }
    }

    fn lock(&self) -> MutexGuard<'_, State> {
        self.inner.state.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

impl fmt::Debug for Clock {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_manual() {
            f.debug_struct("Clock").field("manual_ms", &self.now_ms()).finish()
        } else {
            f.debug_struct("Clock").field("system", &true).finish()
        }
    }
}

/// Whether every party is waiting on something that hasn't happened.
fn is_quiet(state: &State) -> bool {
    let now = Duration::from_millis(state.now_ms);
    state.parties.values().all(|thread| {
        thread.is_some_and(|thread| {
            state
                .waiters
                .values()
                .any(|waiter| waiter.thread == thread && !waiter.is_due(now))
        })
    })
}

fn millis(duration: Duration) -> u64 {
    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}

/// A thread taking part in a manual clock; see [`Clock::party`]. Dropping it ends the part.
pub(crate) struct Party {
    clock: Clock,
    id: Option<u64>,
}

impl Party {
    /// Bind the party to the calling thread, the one whose waits [`Clock::settle`] watches.
    pub(crate) fn bind(&self) {
        if let Some(id) = self.id {
            self.clock.lock().parties.insert(id, Some(thread::current().id()));
            self.clock.inner.changed.notify_all();
        }
    }
}

impl Drop for Party {
    fn drop(&mut self) {
        if let Some(id) = self.id {
            self.clock.lock().parties.remove(&id);
            self.clock.inner.changed.notify_all();
        }
    }
}

impl fmt::Debug for Party {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Party").field("id", &self.id).finish_non_exhaustive()
    }
}

/// Something threads wait for on a [`Clock`]: [`Signal::raise`] wakes every [`Clock::wait`] on it
/// that saw the generation before the raise.
#[derive(Clone)]
pub(crate) struct Signal {
    generation: Arc<AtomicU64>,
    clock: Clock,
}

impl Signal {
    pub(crate) fn new(clock: &Clock) -> Self {
        Self {
            generation: Arc::new(AtomicU64::new(0)),
            clock: clock.clone(),
        }
    }

    /// The generation to pass to [`Clock::wait`]: read it before checking for what the wait is
    /// for, so a raise in between isn't missed.
    pub(crate) fn seen(&self) -> u64 {
        self.generation.load(Ordering::SeqCst)
    }

    pub(crate) fn raise(&self) {
        self.generation.fetch_add(1, Ordering::SeqCst);
        // Taking the lock orders this after any waiter's check of the generation...
        let _state = self.clock.lock();
        self.clock.inner.changed.notify_all();
    }
}

impl fmt::Debug for Signal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Signal")
            .field("generation", &self.seen())
            .finish_non_exhaustive()
    }
}