Skip to main content

flexpool_sim/
clock.rs

1//! A forward-only test clock that jumps between the gates the rules define.
2
3use serde::Serialize;
4use time::OffsetDateTime;
5
6/// What happened at an event.
7#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
8#[serde(rename_all = "kebab-case", tag = "kind", content = "id")]
9pub enum EventKind {
10    /// A market gate closed (`da.gate`, `ida1.gate`, …).
11    GateClosed(String),
12    /// Data was published (`da.prices`).
13    Published(String),
14    /// The delivery day began.
15    DayStarted,
16    /// The delivery day ended.
17    DayEnded,
18}
19
20/// An instant at which something happens.
21#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
22pub struct Event {
23    /// When.
24    #[serde(with = "time::serde::rfc3339")]
25    pub at: OffsetDateTime,
26    /// What.
27    #[serde(flatten)]
28    pub kind: EventKind,
29}
30
31/// Why the clock refused to move.
32#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
33pub enum ClockError {
34    /// The clock only moves forward.
35    #[error("the clock only moves forward: it is {now}, {to} is earlier")]
36    Backwards {
37        /// Current instant.
38        now: OffsetDateTime,
39        /// Requested instant.
40        to: OffsetDateTime,
41    },
42}
43
44/// The test clock.
45#[derive(Debug, Clone)]
46pub struct Clock {
47    now: OffsetDateTime,
48    end: OffsetDateTime,
49    events: Vec<Event>,
50}
51
52impl Clock {
53    /// A clock at `start` that stops at `end`, with `events` (sorted on construction).
54    #[must_use]
55    pub fn new(start: OffsetDateTime, end: OffsetDateTime, mut events: Vec<Event>) -> Self {
56        events.sort_by_key(|a| a.at);
57        // Events at or before the start stay in the day's list (they already happened); only events
58        // after the end are dropped.
59        events.retain(|e| e.at <= end);
60        Self {
61            now: start,
62            end,
63            events,
64        }
65    }
66
67    /// The current instant.
68    #[must_use]
69    pub const fn now(&self) -> OffsetDateTime {
70        self.now
71    }
72
73    /// Where the clock stops.
74    #[must_use]
75    pub const fn end(&self) -> OffsetDateTime {
76        self.end
77    }
78
79    /// Every scheduled event of the replay, in time order (past and future).
80    #[must_use]
81    pub fn events(&self) -> &[Event] {
82        &self.events
83    }
84
85    /// The next event after now, if any.
86    #[must_use]
87    pub fn next(&self) -> Option<&Event> {
88        self.events.iter().find(|e| e.at > self.now)
89    }
90
91    /// Whether the clock has reached its end.
92    #[must_use]
93    pub fn finished(&self) -> bool {
94        self.now >= self.end
95    }
96
97    /// Moves to `to` (capped at the end) and returns the events passed, in order.
98    ///
99    /// # Errors
100    /// [`ClockError::Backwards`] if `to` is before now.
101    pub fn advance_to(&mut self, to: OffsetDateTime) -> Result<Vec<Event>, ClockError> {
102        let to = to.to_offset(time::UtcOffset::UTC);
103        if to < self.now {
104            return Err(ClockError::Backwards { now: self.now, to });
105        }
106        let to = to.min(self.end);
107        let fired = self
108            .events
109            .iter()
110            .filter(|e| e.at > self.now && e.at <= to)
111            .cloned()
112            .collect();
113        self.now = to;
114        Ok(fired)
115    }
116
117    /// Moves to the next event (or the end) and returns the events fired there.
118    pub fn advance_next(&mut self) -> Vec<Event> {
119        let to = self.next().map_or(self.end, |e| e.at);
120        self.advance_to(to).unwrap_or_default()
121    }
122}