flexpool-core 0.3.0

flexpool domain core: exact energy and money units, the Europe/Berlin quarter-hour calendar, portfolio identities and the single quantisation boundary. No I/O, no clock.
Documentation
//! The Europe/Berlin quarter-hour calendar.
//!
//! A German electricity business day starts at 00:00 local time and lasts 23, 24 or 25 hours —
//! 92, 96 or 100 quarter-hours. The day boundaries come from the `metering` crate, the stack's
//! DST-correct calendar; this module only adds the quarter-hour as a type.
//!
//! A [`Quarter`] is identified by its UTC start instant, so the two 02:00–02:15 local quarters of
//! the autumn switch are distinct and ordered.
//!
//! `metering` speaks `jiff`; flexpool speaks `time`. This module is the one place the two meet:
//! [`to_berlin`] and [`BusinessDay`] convert at the boundary, exactly (nanoseconds and civil
//! dates), so no other crate calls `metering` for the calendar.

use metering::DayBoundary;
use metering::jiff;
use serde::Serialize;
use time::{Date, Duration, Month, OffsetDateTime, UtcOffset};

fn to_jiff_date(date: Date) -> Option<jiff::civil::Date> {
    jiff::civil::Date::new(
        i16::try_from(date.year()).ok()?,
        i8::try_from(u8::from(date.month())).ok()?,
        i8::try_from(date.day()).ok()?,
    )
    .ok()
}

fn from_jiff_date(date: jiff::civil::Date) -> Option<Date> {
    let month = Month::try_from(u8::try_from(date.month()).ok()?).ok()?;
    Date::from_calendar_date(
        i32::from(date.year()),
        month,
        u8::try_from(date.day()).ok()?,
    )
    .ok()
}

fn to_timestamp(instant: OffsetDateTime) -> Option<jiff::Timestamp> {
    jiff::Timestamp::from_nanosecond(instant.unix_timestamp_nanos()).ok()
}

fn from_timestamp(instant: jiff::Timestamp) -> Option<OffsetDateTime> {
    OffsetDateTime::from_unix_timestamp_nanos(instant.as_nanosecond()).ok()
}

/// `instant` as Europe/Berlin wall-clock time (CET or CEST), the same instant.
///
/// Outside the years the calendar knows, the instant is returned unchanged in UTC.
#[must_use]
pub fn to_berlin(instant: OffsetDateTime) -> OffsetDateTime {
    to_timestamp(instant)
        .map(metering::time::calendar::to_berlin)
        .and_then(|zoned| {
            let offset = UtcOffset::from_whole_seconds(zoned.offset().seconds()).ok()?;
            Some(instant.to_offset(offset))
        })
        .unwrap_or_else(|| instant.to_offset(UtcOffset::UTC))
}

/// Fifteen minutes.
pub const QUARTER: Duration = Duration::minutes(15);

/// A calendar failure: the date or instant lies outside the supported years.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum CalendarError {
    /// The date is outside the calendar's supported years.
    #[error("{0} is outside the supported calendar years")]
    Unsupported(Date),
    /// The instant is not aligned to a 15-minute boundary.
    #[error("{0} is not aligned to a quarter-hour")]
    Misaligned(OffsetDateTime),
}

/// One Europe/Berlin electricity business day.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BusinessDay {
    date: Date,
    start: OffsetDateTime,
    end: OffsetDateTime,
}

impl BusinessDay {
    /// The business day for a local calendar date.
    ///
    /// # Errors
    /// [`CalendarError::Unsupported`] outside the supported years.
    pub fn new(date: Date) -> Result<Self, CalendarError> {
        let period = to_jiff_date(date)
            .and_then(|d| DayBoundary::Strom.day(d))
            .ok_or(CalendarError::Unsupported(date))?;
        match (from_timestamp(period.start()), from_timestamp(period.end())) {
            (Some(start), Some(end)) => Ok(Self { date, start, end }),
            _ => Err(CalendarError::Unsupported(date)),
        }
    }

    /// The business day containing `instant`.
    ///
    /// # Errors
    /// [`CalendarError::Unsupported`] outside the supported years.
    pub fn containing(instant: OffsetDateTime) -> Result<Self, CalendarError> {
        let date = to_timestamp(instant)
            .and_then(|t| DayBoundary::Strom.day_of(t))
            .and_then(from_jiff_date)
            .ok_or(CalendarError::Unsupported(instant.date()))?;
        Self::new(date)
    }

    /// The local calendar date.
    #[must_use]
    pub const fn date(&self) -> Date {
        self.date
    }

    /// Start instant (UTC), inclusive.
    #[must_use]
    pub const fn start(&self) -> OffsetDateTime {
        self.start
    }

    /// End instant (UTC), exclusive.
    #[must_use]
    pub const fn end(&self) -> OffsetDateTime {
        self.end
    }

    /// Number of quarter-hours: 92, 96 or 100.
    #[must_use]
    pub fn len(&self) -> u16 {
        // Days are 23–25 h; the division is exact and fits u16.
        let quarters = (self.end() - self.start()).whole_minutes() / 15;
        u16::try_from(quarters).unwrap_or(u16::MAX)
    }

    /// Always false: a business day has at least 92 quarters.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        false
    }

    /// The quarters of this day in time order.
    pub fn quarters(&self) -> impl Iterator<Item = Quarter> + '_ {
        (0..self.len()).map(move |index| Quarter {
            start: self.start() + QUARTER * i32::from(index),
            date: self.date,
            index,
        })
    }

    /// The following business day.
    ///
    /// # Errors
    /// [`CalendarError::Unsupported`] past the supported years.
    pub fn next(&self) -> Result<Self, CalendarError> {
        Self::containing(self.end())
    }
}

/// One quarter-hour of a business day, identified by its UTC start instant.
/// Serialise-only: a quarter is constructed from the calendar, never deserialised into an
/// inconsistent state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
pub struct Quarter {
    #[serde(with = "time::serde::rfc3339")]
    start: OffsetDateTime,
    date: Date,
    index: u16,
}

impl Quarter {
    /// The quarter whose half-open interval contains `instant`.
    ///
    /// # Errors
    /// [`CalendarError::Unsupported`] outside the supported years.
    pub fn containing(instant: OffsetDateTime) -> Result<Self, CalendarError> {
        let day = BusinessDay::containing(instant)?;
        let offset = (instant - day.start()).whole_minutes() / 15;
        let index = u16::try_from(offset).unwrap_or(0);
        Ok(Self {
            start: day.start() + QUARTER * i32::from(index),
            date: day.date(),
            index,
        })
    }

    /// The quarter starting exactly at `start`.
    ///
    /// # Errors
    /// [`CalendarError::Misaligned`] if `start` is not on a quarter boundary.
    pub fn starting_at(start: OffsetDateTime) -> Result<Self, CalendarError> {
        let quarter = Self::containing(start)?;
        if quarter.start == start.to_offset(time::UtcOffset::UTC) {
            Ok(quarter)
        } else {
            Err(CalendarError::Misaligned(start))
        }
    }

    /// Start instant (UTC), inclusive.
    #[must_use]
    pub const fn start(&self) -> OffsetDateTime {
        self.start
    }

    /// End instant (UTC), exclusive.
    #[must_use]
    pub fn end(&self) -> OffsetDateTime {
        self.start + QUARTER
    }

    /// The local business-day date this quarter belongs to.
    #[must_use]
    pub const fn date(&self) -> Date {
        self.date
    }

    /// Zero-based position in its business day.
    #[must_use]
    pub const fn index(&self) -> u16 {
        self.index
    }

    /// The next quarter, crossing into the next business day when needed.
    ///
    /// # Errors
    /// [`CalendarError::Unsupported`] past the supported years.
    pub fn next(&self) -> Result<Self, CalendarError> {
        Self::containing(self.end())
    }
}