flexpool-sim 0.2.1

flexpool replay: bitemporal series with decision-time views, synthetic and imported market days, scenarios and a forward-only test clock. No I/O, no real clock.
Documentation
//! A forward-only test clock that jumps between the gates the rules define.

use serde::Serialize;
use time::OffsetDateTime;

/// What happened at an event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case", tag = "kind", content = "id")]
pub enum EventKind {
    /// A market gate closed (`da.gate`, `ida1.gate`, …).
    GateClosed(String),
    /// Data was published (`da.prices`).
    Published(String),
    /// The delivery day began.
    DayStarted,
    /// The delivery day ended.
    DayEnded,
}

/// An instant at which something happens.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Event {
    /// When.
    #[serde(with = "time::serde::rfc3339")]
    pub at: OffsetDateTime,
    /// What.
    #[serde(flatten)]
    pub kind: EventKind,
}

/// Why the clock refused to move.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ClockError {
    /// The clock only moves forward.
    #[error("the clock only moves forward: it is {now}, {to} is earlier")]
    Backwards {
        /// Current instant.
        now: OffsetDateTime,
        /// Requested instant.
        to: OffsetDateTime,
    },
}

/// The test clock.
#[derive(Debug, Clone)]
pub struct Clock {
    now: OffsetDateTime,
    end: OffsetDateTime,
    events: Vec<Event>,
}

impl Clock {
    /// A clock at `start` that stops at `end`, with `events` (sorted on construction).
    #[must_use]
    pub fn new(start: OffsetDateTime, end: OffsetDateTime, mut events: Vec<Event>) -> Self {
        events.sort_by_key(|a| a.at);
        // Events at or before the start stay in the day's list (they already happened); only events
        // after the end are dropped.
        events.retain(|e| e.at <= end);
        Self {
            now: start,
            end,
            events,
        }
    }

    /// The current instant.
    #[must_use]
    pub const fn now(&self) -> OffsetDateTime {
        self.now
    }

    /// Where the clock stops.
    #[must_use]
    pub const fn end(&self) -> OffsetDateTime {
        self.end
    }

    /// Every scheduled event of the replay, in time order (past and future).
    #[must_use]
    pub fn events(&self) -> &[Event] {
        &self.events
    }

    /// The next event after now, if any.
    #[must_use]
    pub fn next(&self) -> Option<&Event> {
        self.events.iter().find(|e| e.at > self.now)
    }

    /// Whether the clock has reached its end.
    #[must_use]
    pub fn finished(&self) -> bool {
        self.now >= self.end
    }

    /// Moves to `to` (capped at the end) and returns the events passed, in order.
    ///
    /// # Errors
    /// [`ClockError::Backwards`] if `to` is before now.
    pub fn advance_to(&mut self, to: OffsetDateTime) -> Result<Vec<Event>, ClockError> {
        let to = to.to_offset(time::UtcOffset::UTC);
        if to < self.now {
            return Err(ClockError::Backwards { now: self.now, to });
        }
        let to = to.min(self.end);
        let fired = self
            .events
            .iter()
            .filter(|e| e.at > self.now && e.at <= to)
            .cloned()
            .collect();
        self.now = to;
        Ok(fired)
    }

    /// Moves to the next event (or the end) and returns the events fired there.
    pub fn advance_next(&mut self) -> Vec<Event> {
        let to = self.next().map_or(self.end, |e| e.at);
        self.advance_to(to).unwrap_or_default()
    }
}