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 UFTP 3.1.0 messages: all 26 types of the common, AGR–DSO, AGR–CRO, CRO–DSO and
//! metering schemas.

pub mod agr_cro;
pub mod agr_dso;
pub mod common;
pub mod cro_dso;
pub mod meta;
pub mod metering;

use crate::error::Rejection;
use crate::types::{MessageUuid, Role};
use crate::xml::reader::{self, Element, Limits};
use crate::xml::writer::Writer;

pub use agr_cro::*;
pub use agr_dso::*;
pub use common::*;
pub use cro_dso::*;
pub use meta::{FlexHeader, Metadata, Reply, ResponseHeader};
pub use metering::*;

/// Relaxations of the 3.1.0 XSD where it contradicts the specification's text. All are off
/// by default.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct DecodeOptions {
    /// Accept a FlexSettlement without any ContractSettlement. The XSD requires one; a DSO
    /// without bilateral contracts cannot send a valid settlement (spec note SS-02).
    pub allow_empty_contract_settlement: bool,
}

impl DecodeOptions {
    /// The options with [`DecodeOptions::allow_empty_contract_settlement`] set.
    #[must_use]
    pub fn allow_empty_contract_settlement(mut self) -> Self {
        self.allow_empty_contract_settlement = true;
        self
    }
}

/// One message type on the wire. `read` checks only what the XSD expresses; `validate`
/// checks the specification's rules on top, so a rule failure is known to concern a
/// schema-valid message (research R2).
pub(crate) trait Wire: Sized {
    const NAME: &'static str;
    const RESPONSE: bool = false;
    fn meta(&self) -> &Metadata;
    fn meta_mut(&mut self) -> &mut Metadata;
    fn read(el: &Element, opts: DecodeOptions) -> Result<Self, Rejection>;
    fn validate(&self) -> Result<(), Rejection> {
        Ok(())
    }
    fn write(&self, w: &mut Writer) -> Result<(), Rejection>;
    fn in_reply_to(&self) -> Option<MessageUuid> {
        None
    }
    /// The attribute that holds [`in_reply_to`](Self::in_reply_to), such as
    /// `FlexOfferMessageID`; empty where there is none.
    const REFERENCE: &'static str = "";
    fn answer(&self, _reply: Reply) -> Option<Message> {
        None
    }
}

const ANY: &[Role] = &[Role::Agr, Role::Cro, Role::Dso];
const DSO: &[Role] = &[Role::Dso];
const AGR: &[Role] = &[Role::Agr];
const CRO: &[Role] = &[Role::Cro];

/// A message of another type than the one asked for with `try_into`. It hands the
/// message back.
///
/// ```
/// # use uftp::*;
/// # fn handle(opened: Opened) -> Result<(), UnexpectedMessage> {
/// let request: FlexRequest = opened.into_message().try_into()?;
/// # Ok(()) }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnexpectedMessage {
    /// The type that was expected, such as `FlexRequest`.
    pub expected: &'static str,
    /// The message that arrived instead.
    pub message: Box<Message>,
}

impl std::fmt::Display for UnexpectedMessage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Expected a {}, got a {}.",
            self.expected,
            self.message.type_name()
        )
    }
}

impl std::error::Error for UnexpectedMessage {}

macro_rules! messages {
    ($($variant:ident => $senders:ident),+ $(,)?) => {
        /// Any of the 26 UFTP 3.1.0 messages.
        #[derive(Debug, Clone, PartialEq, Eq)]
        #[allow(clippy::large_enum_variant)]
        pub enum Message {
            $(#[doc = concat!("A ", stringify!($variant), ".")] $variant($variant)),+
        }

        $(impl From<$variant> for Message {
            fn from(m: $variant) -> Self { Self::$variant(m) }
        })+

        $(impl TryFrom<Message> for $variant {
            type Error = UnexpectedMessage;
            fn try_from(m: Message) -> Result<Self, UnexpectedMessage> {
                match m {
                    Message::$variant(v) => Ok(v),
                    other => Err(UnexpectedMessage {
                        expected: <$variant as Wire>::NAME,
                        message: Box::new(other),
                    }),
                }
            }
        })+

        impl Message {
            /// Every XML root element name, in the order of this enum.
            pub const TYPE_NAMES: &'static [&'static str] = &[$(<$variant as Wire>::NAME),+];

            /// The XML root element name, such as `FlexRequest`.
            #[must_use]
            pub fn type_name(&self) -> &'static str {
                match self { $(Self::$variant(_) => <$variant as Wire>::NAME),+ }
            }

            /// The roles that may send this type.
            #[must_use]
            pub fn allowed_senders(&self) -> &'static [Role] {
                match self { $(Self::$variant(_) => $senders),+ }
            }

            /// The common metadata.
            #[must_use]
            pub fn meta(&self) -> &Metadata {
                match self { $(Self::$variant(m) => m.meta()),+ }
            }

            pub(crate) fn meta_mut(&mut self) -> &mut Metadata {
                match self { $(Self::$variant(m) => m.meta_mut()),+ }
            }

            /// Whether this is a response, which is never answered.
            #[must_use]
            pub fn is_response(&self) -> bool {
                match self { $(Self::$variant(_) => <$variant as Wire>::RESPONSE),+ }
            }

            /// For a response, the MessageID of the message it answers, so an outbox can
            /// match it. `None` for requests, and for a TestMessageResponse, which
            /// carries no reference (SS-03).
            #[must_use]
            pub fn in_reply_to(&self) -> Option<MessageUuid> {
                match self { $(Self::$variant(m) => m.in_reply_to()),+ }
            }

            /// The attribute that names the message this one answers, such as
            /// `FlexOfferMessageID` for a FlexOfferResponse: `None` for requests and for
            /// TestMessageResponse, which has no reference (SS-03).
            #[must_use]
            pub fn reference_attribute(&self) -> Option<&'static str> {
                let name = match self { $(Self::$variant(_) => <$variant as Wire>::REFERENCE),+ };
                (!name.is_empty()).then_some(name)
            }

            /// Checks the rules of the specification that the types cannot express: ISPs
            /// addressed once and inside the day, `MinPower ≤ MaxPower`, the references a
            /// solicited offer or order must carry, metering units.
            ///
            /// # Errors
            /// A [`RejectKind::Rule`](crate::RejectKind::Rule) rejection naming the
            /// `[UFTP §3.5]` reason, on the first rule broken.
            pub fn validate(&self) -> Result<(), Rejection> {
                match self { $(Self::$variant(m) => m.validate()),+ }
            }

            /// The response to this message with the given outcome, copying the
            /// conversation and the reference. Lists a response carries (order statuses,
            /// portfolio views) are left empty; a rejected FlexSettlement disputes every
            /// order settlement with the reason, because the XSD requires one status per
            /// order.
            ///
            /// `None` for responses, for a TestMessage unless `reply` accepts it
            /// (TestMessageResponse has no `Result`, SS-03), and for an AGRPortfolioQuery
            /// that `reply` accepts (the accepted answer must carry the CRO's views). The
            /// typed `reply` methods of each request build responses with content. Every
            /// response this returns encodes.
            #[must_use]
            pub fn reply(&self, reply: Reply) -> Option<Message> {
                match self { $(Self::$variant(m) => m.answer(reply)),+ }
            }

            /// Encodes the message as UTF-8 XML, after [`Message::validate`].
            ///
            /// # Errors
            /// If a rule is broken, a list the XSD requires is empty, or a text value holds
            /// a character XML cannot carry.
            pub fn encode(&self) -> Result<String, Rejection> {
                self.validate()?;
                let mut w = Writer::new();
                match self { $(Self::$variant(m) => m.write(&mut w)?),+ }
                w.finish()
            }

            fn read(el: &Element, opts: DecodeOptions) -> Result<Self, Rejection> {
                match el.name.as_str() {
                    $(<$variant as Wire>::NAME => <$variant as Wire>::read(el, opts).map(Self::$variant),)+
                    other => Err(Rejection::schema("[UFTP §4.2] message type by root element", format!("<{other}> is not a UFTP 3.1 message.", other = crate::error::name(other)))),
                }
            }
        }
    };
}

messages! {
    TestMessage => ANY,
    TestMessageResponse => ANY,
    AgrPortfolioUpdate => AGR,
    AgrPortfolioUpdateResponse => CRO,
    AgrPortfolioQuery => AGR,
    AgrPortfolioQueryResponse => CRO,
    DsoPortfolioUpdate => DSO,
    DsoPortfolioUpdateResponse => CRO,
    DsoPortfolioQuery => DSO,
    DsoPortfolioQueryResponse => CRO,
    FlexReservationUpdate => DSO,
    FlexReservationUpdateResponse => AGR,
    DPrognosis => AGR,
    DPrognosisResponse => DSO,
    FlexRequest => DSO,
    FlexRequestResponse => AGR,
    FlexOffer => AGR,
    FlexOfferResponse => DSO,
    FlexOfferRevocation => AGR,
    FlexOfferRevocationResponse => DSO,
    FlexOrder => DSO,
    FlexOrderResponse => AGR,
    Metering => AGR,
    MeteringResponse => DSO,
    FlexSettlement => DSO,
    FlexSettlementResponse => AGR,
}

/// Decodes an inner message by the schema only. Crate-private: the only public path from
/// received bytes to a [`Message`] is [`crate::open`], which verifies the signature first
/// and runs [`Message::validate`] after the sender binding.
pub(crate) fn decode_payload(
    bytes: &[u8],
    limits: &Limits,
    opts: DecodeOptions,
) -> Result<Message, Rejection> {
    let root = reader::parse(bytes, limits)?;
    Message::read(&root, opts)
}

/// Implements `meta`/`meta_mut` for a type whose metadata is at `$($path).+`.
macro_rules! wire_meta {
    ($($path:ident).+) => {
        fn meta(&self) -> &Metadata {
            &self.$($path).+
        }
        fn meta_mut(&mut self) -> &mut Metadata {
            &mut self.$($path).+
        }
    };
}
pub(crate) use wire_meta;

/// A response type that carries only the id of the message it answers, with its `reply`
/// method on the request.
macro_rules! simple_response {
    ($(#[$doc:meta])* $name:ident, $xml:literal, $attr:literal, $field:ident, $request:ident) => {
        $(#[$doc])*
        #[derive(Debug, Clone, PartialEq, Eq)]
        pub struct $name {
            header: ResponseHeader,
            $field: MessageUuid,
        }

        impl $name {
            /// The response metadata and result.
            #[must_use]
            pub fn header(&self) -> &ResponseHeader {
                &self.header
            }

            #[doc = concat!("The `MessageID` of the ", stringify!($request), " this answers.")]
            #[must_use]
            pub fn $field(&self) -> MessageUuid {
                self.$field
            }
        }

        impl $request {
            #[doc = concat!("Answers this message with a ", stringify!($name), ", copying the conversation id.")]
            #[must_use]
            pub fn reply(&self, reply: Reply) -> $name {
                let meta = Wire::meta(self);
                $name { header: ResponseHeader::reply_to(meta, reply), $field: meta.message_id }
            }
        }

        impl Wire for $name {
            const NAME: &'static str = $xml;
            const RESPONSE: bool = true;
            fn meta(&self) -> &Metadata {
                self.header.meta()
            }
            fn meta_mut(&mut self) -> &mut Metadata {
                self.header.meta_mut()
            }
            fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
                children(el, $xml, &[])?;
                let mut a = Attrs::new(el, $xml);
                let v = Self { header: ResponseHeader::read(&mut a)?, $field: a.req($attr)? };
                a.finish()?;
                Ok(v)
            }
            fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
                w.start($xml);
                self.header.write(w);
                w.attr($attr, self.$field).end();
                Ok(())
            }
            fn in_reply_to(&self) -> Option<MessageUuid> {
                Some(self.$field)
            }
            const REFERENCE: &'static str = $attr;
        }
    };
}
pub(crate) use simple_response;