vce-engine 0.1.1

The generic state substrate of the Virtual Computing Engine (VCE)
Documentation
//! Virtual time.
//!
//! Time in the virtual world is a first-class Engine mechanism. The default
//! [`VirtualClock`] is frozen until explicitly advanced: an idle virtual world
//! does not age. This makes scenarios, tests, and replays deterministic.
//!
//! [`HostClock`] is provided for the rare case where timestamps must
//! correspond to the host wall clock. It is non-deterministic and should not
//! be used by scenarios or tests.

use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

pub use super::timestamp::Timestamp;

/// A source of virtual time.
///
/// Implementations must be shareable across threads ([`Send`] + [`Sync`]).
pub trait Clock: Send + Sync {
    /// The current virtual time.
    fn now(&self) -> Timestamp;

    /// Advances the clock by a duration.
    ///
    /// The default implementation does nothing, for clocks whose time is
    /// externally controlled (such as the host wall clock). Virtual clocks
    /// override this to implement `sleep` and other time-advancing behavior.
    fn advance_by(&self, _duration: Duration) {}

    /// Sets the clock to an absolute point in virtual time.
    ///
    /// The default implementation does nothing, for the same reason as
    /// [`Clock::advance_by`].
    fn set(&self, _timestamp: Timestamp) {}
}

/// A deterministic clock that is frozen until explicitly advanced.
///
/// Starts at [`Timestamp::ZERO`] unless seeded with [`VirtualClock::set`].
/// Scenarios should seed it to a realistic boot date at OS initialization so
/// the virtual world *looks* like real time while remaining deterministic.
#[derive(Debug)]
pub struct VirtualClock {
    current: AtomicU64,
}

impl VirtualClock {
    /// Creates a clock frozen at [`Timestamp::ZERO`].
    pub const fn new() -> Self {
        Self {
            current: AtomicU64::new(0),
        }
    }
}

impl Default for VirtualClock {
    fn default() -> Self {
        Self::new()
    }
}

impl Clock for VirtualClock {
    fn now(&self) -> Timestamp {
        Timestamp::from_nanos(self.current.load(Ordering::Relaxed))
    }

    fn advance_by(&self, duration: Duration) {
        let nanos = u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX);
        // Atomic read-modify-write: two concurrent advances must compose,
        // never overwrite one another (which could move time backwards).
        let _ = self
            .current
            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
                Some(current.saturating_add(nanos))
            });
    }

    fn set(&self, timestamp: Timestamp) {
        let nanos = timestamp.as_nanos();
        // Seeding a fresh clock is the only sanctioned absolute set; an
        // already-running timeline must never move backwards.
        let _ = self
            .current
            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
                debug_assert!(nanos >= current, "virtual time must never move backwards");
                Some(nanos)
            });
    }
}

/// A clock backed by the host wall clock.
///
/// Non-deterministic: two runs of the same scenario produce different
/// timestamps. Use only when wall-clock correspondence is explicitly required.
#[derive(Clone, Copy, Debug)]
pub struct HostClock;

impl HostClock {
    /// Creates a host-backed clock.
    pub const fn new() -> Self {
        Self
    }
}

impl Default for HostClock {
    fn default() -> Self {
        Self::new()
    }
}

impl Clock for HostClock {
    fn now(&self) -> Timestamp {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        Timestamp::from_nanos(u64::try_from(nanos).unwrap_or(u64::MAX))
    }
}