Skip to main content

flexpool_core/
calendar.rs

1//! The Europe/Berlin quarter-hour calendar.
2//!
3//! A German electricity business day starts at 00:00 local time and lasts 23, 24 or 25 hours —
4//! 92, 96 or 100 quarter-hours. The day boundaries come from the `metering` crate, the stack's
5//! DST-correct calendar; this module only adds the quarter-hour as a type.
6//!
7//! A [`Quarter`] is identified by its UTC start instant, so the two 02:00–02:15 local quarters of
8//! the autumn switch are distinct and ordered.
9//!
10//! `metering` speaks `jiff`; flexpool speaks `time`. This module is the one place the two meet:
11//! [`to_berlin`] and [`BusinessDay`] convert at the boundary, exactly (nanoseconds and civil
12//! dates), so no other crate calls `metering` for the calendar.
13
14use metering::DayBoundary;
15use metering::jiff;
16use serde::Serialize;
17use time::{Date, Duration, Month, OffsetDateTime, UtcOffset};
18
19fn to_jiff_date(date: Date) -> Option<jiff::civil::Date> {
20    jiff::civil::Date::new(
21        i16::try_from(date.year()).ok()?,
22        i8::try_from(u8::from(date.month())).ok()?,
23        i8::try_from(date.day()).ok()?,
24    )
25    .ok()
26}
27
28fn from_jiff_date(date: jiff::civil::Date) -> Option<Date> {
29    let month = Month::try_from(u8::try_from(date.month()).ok()?).ok()?;
30    Date::from_calendar_date(
31        i32::from(date.year()),
32        month,
33        u8::try_from(date.day()).ok()?,
34    )
35    .ok()
36}
37
38fn to_timestamp(instant: OffsetDateTime) -> Option<jiff::Timestamp> {
39    jiff::Timestamp::from_nanosecond(instant.unix_timestamp_nanos()).ok()
40}
41
42fn from_timestamp(instant: jiff::Timestamp) -> Option<OffsetDateTime> {
43    OffsetDateTime::from_unix_timestamp_nanos(instant.as_nanosecond()).ok()
44}
45
46/// `instant` as Europe/Berlin wall-clock time (CET or CEST), the same instant.
47///
48/// Outside the years the calendar knows, the instant is returned unchanged in UTC.
49#[must_use]
50pub fn to_berlin(instant: OffsetDateTime) -> OffsetDateTime {
51    to_timestamp(instant)
52        .map(metering::time::calendar::to_berlin)
53        .and_then(|zoned| {
54            let offset = UtcOffset::from_whole_seconds(zoned.offset().seconds()).ok()?;
55            Some(instant.to_offset(offset))
56        })
57        .unwrap_or_else(|| instant.to_offset(UtcOffset::UTC))
58}
59
60/// Fifteen minutes.
61pub const QUARTER: Duration = Duration::minutes(15);
62
63/// A calendar failure: the date or instant lies outside the supported years.
64#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
65pub enum CalendarError {
66    /// The date is outside the calendar's supported years.
67    #[error("{0} is outside the supported calendar years")]
68    Unsupported(Date),
69    /// The instant is not aligned to a 15-minute boundary.
70    #[error("{0} is not aligned to a quarter-hour")]
71    Misaligned(OffsetDateTime),
72}
73
74/// One Europe/Berlin electricity business day.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub struct BusinessDay {
77    date: Date,
78    start: OffsetDateTime,
79    end: OffsetDateTime,
80}
81
82impl BusinessDay {
83    /// The business day for a local calendar date.
84    ///
85    /// # Errors
86    /// [`CalendarError::Unsupported`] outside the supported years.
87    pub fn new(date: Date) -> Result<Self, CalendarError> {
88        let period = to_jiff_date(date)
89            .and_then(|d| DayBoundary::Strom.day(d))
90            .ok_or(CalendarError::Unsupported(date))?;
91        match (from_timestamp(period.start()), from_timestamp(period.end())) {
92            (Some(start), Some(end)) => Ok(Self { date, start, end }),
93            _ => Err(CalendarError::Unsupported(date)),
94        }
95    }
96
97    /// The business day containing `instant`.
98    ///
99    /// # Errors
100    /// [`CalendarError::Unsupported`] outside the supported years.
101    pub fn containing(instant: OffsetDateTime) -> Result<Self, CalendarError> {
102        let date = to_timestamp(instant)
103            .and_then(|t| DayBoundary::Strom.day_of(t))
104            .and_then(from_jiff_date)
105            .ok_or(CalendarError::Unsupported(instant.date()))?;
106        Self::new(date)
107    }
108
109    /// The local calendar date.
110    #[must_use]
111    pub const fn date(&self) -> Date {
112        self.date
113    }
114
115    /// Start instant (UTC), inclusive.
116    #[must_use]
117    pub const fn start(&self) -> OffsetDateTime {
118        self.start
119    }
120
121    /// End instant (UTC), exclusive.
122    #[must_use]
123    pub const fn end(&self) -> OffsetDateTime {
124        self.end
125    }
126
127    /// Number of quarter-hours: 92, 96 or 100.
128    #[must_use]
129    pub fn len(&self) -> u16 {
130        // Days are 23–25 h; the division is exact and fits u16.
131        let quarters = (self.end() - self.start()).whole_minutes() / 15;
132        u16::try_from(quarters).unwrap_or(u16::MAX)
133    }
134
135    /// Always false: a business day has at least 92 quarters.
136    #[must_use]
137    pub fn is_empty(&self) -> bool {
138        false
139    }
140
141    /// The quarters of this day in time order.
142    pub fn quarters(&self) -> impl Iterator<Item = Quarter> + '_ {
143        (0..self.len()).map(move |index| Quarter {
144            start: self.start() + QUARTER * i32::from(index),
145            date: self.date,
146            index,
147        })
148    }
149
150    /// The following business day.
151    ///
152    /// # Errors
153    /// [`CalendarError::Unsupported`] past the supported years.
154    pub fn next(&self) -> Result<Self, CalendarError> {
155        Self::containing(self.end())
156    }
157}
158
159/// One quarter-hour of a business day, identified by its UTC start instant.
160/// Serialise-only: a quarter is constructed from the calendar, never deserialised into an
161/// inconsistent state.
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
163pub struct Quarter {
164    #[serde(with = "time::serde::rfc3339")]
165    start: OffsetDateTime,
166    date: Date,
167    index: u16,
168}
169
170impl Quarter {
171    /// The quarter whose half-open interval contains `instant`.
172    ///
173    /// # Errors
174    /// [`CalendarError::Unsupported`] outside the supported years.
175    pub fn containing(instant: OffsetDateTime) -> Result<Self, CalendarError> {
176        let day = BusinessDay::containing(instant)?;
177        let offset = (instant - day.start()).whole_minutes() / 15;
178        let index = u16::try_from(offset).unwrap_or(0);
179        Ok(Self {
180            start: day.start() + QUARTER * i32::from(index),
181            date: day.date(),
182            index,
183        })
184    }
185
186    /// The quarter starting exactly at `start`.
187    ///
188    /// # Errors
189    /// [`CalendarError::Misaligned`] if `start` is not on a quarter boundary.
190    pub fn starting_at(start: OffsetDateTime) -> Result<Self, CalendarError> {
191        let quarter = Self::containing(start)?;
192        if quarter.start == start.to_offset(time::UtcOffset::UTC) {
193            Ok(quarter)
194        } else {
195            Err(CalendarError::Misaligned(start))
196        }
197    }
198
199    /// Start instant (UTC), inclusive.
200    #[must_use]
201    pub const fn start(&self) -> OffsetDateTime {
202        self.start
203    }
204
205    /// End instant (UTC), exclusive.
206    #[must_use]
207    pub fn end(&self) -> OffsetDateTime {
208        self.start + QUARTER
209    }
210
211    /// The local business-day date this quarter belongs to.
212    #[must_use]
213    pub const fn date(&self) -> Date {
214        self.date
215    }
216
217    /// Zero-based position in its business day.
218    #[must_use]
219    pub const fn index(&self) -> u16 {
220        self.index
221    }
222
223    /// The next quarter, crossing into the next business day when needed.
224    ///
225    /// # Errors
226    /// [`CalendarError::Unsupported`] past the supported years.
227    pub fn next(&self) -> Result<Self, CalendarError> {
228        Self::containing(self.end())
229    }
230}