uftp 0.1.0

UFTP 3.1, the USEF Flex Trading Protocol (LF Energy Shapeshifter), in Rust: all 26 messages, CS1 signing and a receive pipeline for DSOs and aggregators.
Documentation
//! The rejection reasons of `[UFTP §3.5]` and of the use cases in §3.6 to §3.10.

use std::fmt;

/// Why a message is rejected, in the words of the specification: the generic table of
/// `[UFTP §3.5]` and the reasons its use cases name (§3.6 to §3.10).
///
/// `Display` prints the specification's text, which is what goes into a response's
/// `RejectionReason` attribute. Several reasons are joined with `; ` (see
/// [`RejectionReason::join`]).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RejectionReason {
    /// The message is schema-compliant, but its syntax, type or semantics are unacceptable
    /// for the receiving implementation. This is the generic reason.
    InvalidSender,
    /// The SenderDomain or role of the wrapper and the inner message do not match.
    InvalidMessage,
    /// The RecipientDomain is not handled by this endpoint.
    UnknownRecipient,
    /// This endpoint blocks messages from this sender.
    BarredSender,
    /// The MessageID was already used for a message with different content.
    DuplicateIdentifier,
    /// The MessageID was already used for a message with the same content; the copy counts
    /// as submitted (spec note SS-17).
    AlreadySubmitted,
    /// The ISP duration is not the market's agreed value.
    IspDurationRejected,
    /// The time zone's UTC offset differs from the market's agreed value.
    TimeZoneRejected,
    /// The congestion point is unknown, or the recipient is not active there.
    InvalidCongestionPoint,
    /// The message referred to is unknown; the payload names the reference field, such
    /// as `FlexOfferMessageID`.
    UnknownReference(&'static str),
    /// The message referred to has a different Period.
    ReferencePeriodMismatch,
    /// The message referred to has expired.
    ReferenceMessageExpired,
    /// The message referred to was revoked.
    ReferenceMessageRevoked,
    /// One or more ISPs do not exist in the period.
    IspsOutOfBounds,
    /// One or more ISPs are addressed more than once.
    IspConflict,
    /// The Period is inappropriate, such as a FlexRequest for a day in the past.
    PeriodOutOfBounds,
    /// The ExpirationDateTime is in the past or beyond the message's ISPs.
    ExpirationOutOfBounds,
    // --- The use-case reasons of §3.6 to §3.10 ---
    /// The CRO operates in closed mode and the sender is not registered (§3.6.1, §3.6.2, §3.7.1, §3.7.2).
    Unauthorized,
    /// The message's sequence or revision is lower than that of one already received
    /// (§3.6.1, §3.6.2, §3.8.1).
    SubordinateSequence,
    /// The sender has no registered connections at the Common Reference (§3.7.1, §3.7.2).
    NoConnections,
    /// A connection was registered before at another congestion point; name both in the
    /// message (§3.6.1).
    ConnectionConflict,
    /// The deadline to release reserved flexibility has passed (§3.7.3).
    DeadlineExpired,
    /// One or more power values are not plausible (§3.7.3, §3.8.1, §3.8.3).
    PowerValueRejection,
    /// A D-Prognosis does not cover every ISP of its Period (§3.8.1).
    LackingIsps,
    /// A FlexRequest has no ISP with a Requested disposition (§3.8.2).
    LackingRequestedDisposition,
    /// A Requested ISP has no direction: MinPower < 0 and MaxPower > 0 (§3.8.2).
    RequestedPowerDiscrepancy,
    /// An ISP has a higher MinPower than MaxPower (§3.8.2).
    PowerDiscrepancy,
    /// The AGR has no valid baseline, for example no valid D-Prognosis (§3.8.3).
    NoBaseline,
    /// None of the request's Requested ISPs appears in the offer (§3.8.3).
    RequestMismatch,
    /// The offer has mutually exclusive options and the DSO does not support them at this
    /// congestion point (§3.8.3).
    NoMutexOfferSupport,
    /// The offer cannot be revoked: its flexibility was already ordered (§3.8.4).
    FlexibilityProcured,
    /// The order's ISPs are not those of the offer option (§3.8.5).
    IspMismatch,
    /// The ordered power is not the offered power (§3.8.5).
    PowerMismatch,
    /// The order's price is not the offer option's (§3.8.5).
    PriceMismatch,
    /// Flexibility procured in the period is missing from the settlement (§3.10.1).
    MissingSettlementItems,
    /// The settlement period starts too late (§3.10.1).
    PeriodStartRejected,
    /// The settlement period ends too early (§3.10.1).
    PeriodEndRejected,
    /// Any other reasonable cause, explained in words.
    Other(String),
}

impl RejectionReason {
    /// Where the specification defines this reason: `[UFTP §3.5]` for the generic table,
    /// the use case for the reasons of §3.6 to §3.10.
    #[must_use]
    pub fn source(&self) -> &'static str {
        match self {
            Self::Unauthorized => "[UFTP §3.6.1, §3.6.2, §3.7.1, §3.7.2]",
            Self::SubordinateSequence => "[UFTP §3.6.1, §3.6.2, §3.8.1]",
            Self::NoConnections => "[UFTP §3.7.1, §3.7.2]",
            Self::ConnectionConflict => "[UFTP §3.6.1]",
            Self::DeadlineExpired => "[UFTP §3.7.3]",
            Self::PowerValueRejection => "[UFTP §3.7.3, §3.8.1, §3.8.3]",
            Self::LackingIsps => "[UFTP §3.8.1, §3.9.1]",
            Self::LackingRequestedDisposition
            | Self::RequestedPowerDiscrepancy
            | Self::PowerDiscrepancy => "[UFTP §3.8.2]",
            Self::NoBaseline | Self::RequestMismatch | Self::NoMutexOfferSupport => "[UFTP §3.8.3]",
            Self::FlexibilityProcured => "[UFTP §3.8.4, §3.9.2]",
            Self::IspMismatch | Self::PowerMismatch | Self::PriceMismatch => {
                "[UFTP §3.8.5, §3.9.3]"
            }
            Self::MissingSettlementItems | Self::PeriodStartRejected | Self::PeriodEndRejected => {
                "[UFTP §3.10.1]"
            }
            _ => "[UFTP §3.5]",
        }
    }

    /// Joins several reasons with `; `, as `[UFTP §3.5]` allows.
    #[must_use]
    pub fn join(reasons: &[RejectionReason]) -> String {
        reasons
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("; ")
    }
}

impl fmt::Display for RejectionReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::InvalidSender => "Invalid Sender",
            Self::InvalidMessage => "Invalid Message",
            Self::UnknownRecipient => "Unknown Recipient",
            Self::BarredSender => "Barred Sender",
            Self::DuplicateIdentifier => "Duplicate Identifier",
            Self::AlreadySubmitted => "Already Submitted",
            Self::IspDurationRejected => "ISP duration rejected",
            Self::TimeZoneRejected => "Time zone rejected",
            Self::InvalidCongestionPoint => "Invalid congestion point",
            Self::UnknownReference(field) => return write!(f, "Unknown reference {field}"),
            Self::ReferencePeriodMismatch => "Reference Period mismatch",
            Self::ReferenceMessageExpired => "Reference message expired",
            Self::ReferenceMessageRevoked => "Reference message revoked",
            Self::IspsOutOfBounds => "ISPs out of bounds",
            Self::IspConflict => "ISP conflict",
            Self::PeriodOutOfBounds => "Period out of bounds",
            Self::ExpirationOutOfBounds => "ExpirationDateTime out of bounds",
            Self::Unauthorized => "Unauthorized",
            Self::SubordinateSequence => "Subordinate sequence",
            Self::NoConnections => "No connections",
            Self::ConnectionConflict => "Connection conflict",
            Self::DeadlineExpired => "Deadline expired",
            Self::PowerValueRejection => "Power value rejection",
            Self::LackingIsps => "Lacking ISPs",
            Self::LackingRequestedDisposition => "Lacking Requested Disposition",
            Self::RequestedPowerDiscrepancy => "Requested Power discrepancy",
            Self::PowerDiscrepancy => "Power discrepancy",
            Self::NoBaseline => "No baseline",
            Self::RequestMismatch => "Request mismatch",
            Self::NoMutexOfferSupport => "No MutEx offer support",
            Self::FlexibilityProcured => "Flexibility procured",
            Self::IspMismatch => "ISP mismatch",
            Self::PowerMismatch => "Power mismatch",
            Self::PriceMismatch => "Price mismatch",
            Self::MissingSettlementItems => "Missing Settlement Items",
            Self::PeriodStartRejected => "PeriodStart rejected",
            Self::PeriodEndRejected => "PeriodEnd rejected",
            Self::Other(text) => text,
        })
    }
}

impl From<RejectionReason> for String {
    fn from(r: RejectionReason) -> Self {
        r.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::RejectionReason as R;

    #[test]
    fn use_case_reasons_print_the_specification_text() {
        let all = [
            (R::Unauthorized, "Unauthorized"),
            (R::SubordinateSequence, "Subordinate sequence"),
            (R::NoConnections, "No connections"),
            (R::ConnectionConflict, "Connection conflict"),
            (R::DeadlineExpired, "Deadline expired"),
            (R::PowerValueRejection, "Power value rejection"),
            (R::LackingIsps, "Lacking ISPs"),
            (
                R::LackingRequestedDisposition,
                "Lacking Requested Disposition",
            ),
            (R::RequestedPowerDiscrepancy, "Requested Power discrepancy"),
            (R::PowerDiscrepancy, "Power discrepancy"),
            (R::NoBaseline, "No baseline"),
            (R::RequestMismatch, "Request mismatch"),
            (R::NoMutexOfferSupport, "No MutEx offer support"),
            (R::FlexibilityProcured, "Flexibility procured"),
            (R::IspMismatch, "ISP mismatch"),
            (R::PowerMismatch, "Power mismatch"),
            (R::PriceMismatch, "Price mismatch"),
            (R::MissingSettlementItems, "Missing Settlement Items"),
            (R::PeriodStartRejected, "PeriodStart rejected"),
            (R::PeriodEndRejected, "PeriodEnd rejected"),
        ];
        for (reason, text) in all {
            assert_eq!(reason.to_string(), text);
        }
    }

    #[test]
    fn each_reason_cites_its_use_case() {
        for (reason, source) in [
            (R::LackingIsps, "[UFTP §3.8.1, §3.9.1]"),
            (R::LackingRequestedDisposition, "[UFTP §3.8.2]"),
            (R::RequestedPowerDiscrepancy, "[UFTP §3.8.2]"),
            (R::PowerDiscrepancy, "[UFTP §3.8.2]"),
            (R::PriceMismatch, "[UFTP §3.8.5, §3.9.3]"),
            (R::IspConflict, "[UFTP §3.5]"),
        ] {
            assert_eq!(reason.source(), source, "{reason}");
        }
    }
}