uftp 0.3.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 messages between Common Reference Operator and DSO `[XSD UFTP-cro-dso.xsd]`.

use jiff::civil::Date;

use crate::error::Rejection;
use crate::msg::agr_cro::{PortfolioConnection, check_range};
use crate::msg::agr_dso::nonempty;
use crate::msg::meta::{Metadata, Reply, ResponseHeader, XsDate, named};
use crate::msg::{DecodeOptions, Message, Wire, simple_response, wire_meta};
use crate::types::{EntityAddress, InternetDomain, MessageUuid, RedispatchBy, TimeZoneName};
use crate::xml::attrs::{Attrs, children, require_one};
use crate::xml::reader::Element;
use crate::xml::writer::Writer;

// ---------------------------------------------------------------------------------------
// DSOPortfolioUpdate
// ---------------------------------------------------------------------------------------

/// A congestion point the DSO publishes, with its connections.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DsoCongestionPoint {
    /// The congestion point.
    pub entity_address: EntityAddress,
    /// The first day it exists.
    pub start_period: Date,
    /// The last day, if known. To remove a point, send its current day.
    pub end_period: Option<Date>,
    /// Whether the DSO accepts mutually exclusive offer options here.
    pub mutex_offers_supported: bool,
    /// Who redispatches day-ahead.
    pub day_ahead_redispatch_by: RedispatchBy,
    /// Who redispatches intraday; no intraday trading when absent.
    pub intraday_redispatch_by: Option<RedispatchBy>,
    /// The connections on it; at least one.
    pub connections: Vec<PortfolioConnection>,
}

/// The DSO publishes its congestion points and their connections to the CRO
/// `[XSD DSOPortfolioUpdateType]`. Sent by the DSO.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DsoPortfolioUpdate {
    /// The common metadata.
    pub meta: Metadata,
    /// The zone in which the periods are read.
    pub time_zone: TimeZoneName,
    /// The congestion points; at least one.
    pub congestion_points: Vec<DsoCongestionPoint>,
}

impl Wire for DsoPortfolioUpdate {
    const NAME: &'static str = "DSOPortfolioUpdate";
    wire_meta!(meta);
    fn validate(&self) -> Result<(), Rejection> {
        for (i, cp) in self.congestion_points.iter().enumerate() {
            let path = format!("{}/CongestionPoint[{}]", Self::NAME, i + 1);
            check_range(cp.start_period, cp.end_period, None, &path)?;
            for (j, c) in cp.connections.iter().enumerate() {
                check_range(
                    c.start_period,
                    c.end_period,
                    Some((cp.start_period, cp.end_period)),
                    &format!("{path}/Connection[{}]", j + 1),
                )?;
            }
        }
        Ok(())
    }
    fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
        children(el, Self::NAME, &["CongestionPoint"])?;
        require_one(el, Self::NAME, "CongestionPoint")?;
        let mut a = Attrs::new(el, Self::NAME);
        let meta = Metadata::read(&mut a)?;
        let time_zone = a.req("TimeZone")?;
        a.finish()?;
        let congestion_points = named(el, Self::NAME, "CongestionPoint")
            .map(|(p, c)| {
                children(c, &p, &["Connection"])?;
                require_one(c, &p, "Connection")?;
                let mut a = Attrs::new(c, p.clone());
                let v = DsoCongestionPoint {
                    entity_address: a.req("EntityAddress")?,
                    start_period: a.req::<XsDate>("StartPeriod")?.0,
                    end_period: a.opt::<XsDate>("EndPeriod")?.map(|d| d.0),
                    mutex_offers_supported: a.req_bool("MutexOffersSupported")?,
                    day_ahead_redispatch_by: a.req("DayAheadRedispatchBy")?,
                    intraday_redispatch_by: a.opt("IntradayRedispatchBy")?,
                    connections: named(c, &p, "Connection")
                        .map(|(pp, cc)| PortfolioConnection::read(cc, pp))
                        .collect::<Result<_, _>>()?,
                };
                a.finish()?;
                Ok(v)
            })
            .collect::<Result<_, Rejection>>()?;
        Ok(Self {
            meta,
            time_zone,
            congestion_points,
        })
    }
    fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
        nonempty(&self.congestion_points, Self::NAME, "CongestionPoint")?;
        for (i, c) in self.congestion_points.iter().enumerate() {
            nonempty(
                &c.connections,
                &format!("{}/CongestionPoint[{}]", Self::NAME, i + 1),
                "Connection",
            )?;
        }
        w.start(Self::NAME);
        self.meta.write(w);
        w.attr("TimeZone", &self.time_zone);
        for c in &self.congestion_points {
            w.start("CongestionPoint")
                .attr("EntityAddress", &c.entity_address)
                .attr("StartPeriod", c.start_period)
                .opt_attr("EndPeriod", c.end_period.as_ref())
                .attr("MutexOffersSupported", c.mutex_offers_supported)
                .attr("DayAheadRedispatchBy", c.day_ahead_redispatch_by)
                .opt_attr("IntradayRedispatchBy", c.intraday_redispatch_by.as_ref());
            for conn in &c.connections {
                conn.write(w);
            }
            w.end();
        }
        w.end();
        Ok(())
    }
    fn answer(&self, reply: Reply) -> Option<Message> {
        Some(self.reply(reply).into())
    }
}

simple_response!(
    /// The CRO's answer to a DSOPortfolioUpdate `[XSD DSOPortfolioUpdateResponseType]`.
    ///
    /// On the wire the reference is named `DSOPortfolioUpdateResponseMessageID`, although
    /// it holds the update's id (SS-12, unchanged since UFTP 2.00).
    DsoPortfolioUpdateResponse,
    "DSOPortfolioUpdateResponse",
    "DSOPortfolioUpdateResponseMessageID",
    dso_portfolio_update_message_id,
    DsoPortfolioUpdate
);

// ---------------------------------------------------------------------------------------
// DSOPortfolioQuery
// ---------------------------------------------------------------------------------------

/// The DSO asks the CRO which aggregators are active on a congestion point on a day
/// `[XSD DSOPortfolioQueryType]`. Sent by the DSO.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DsoPortfolioQuery {
    /// The common metadata.
    pub meta: Metadata,
    /// The zone of `period`.
    pub time_zone: TimeZoneName,
    /// The day asked about.
    pub period: Date,
    /// The congestion point asked about.
    pub entity_address: EntityAddress,
}

impl Wire for DsoPortfolioQuery {
    const NAME: &'static str = "DSOPortfolioQuery";
    wire_meta!(meta);
    fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
        children(el, Self::NAME, &[])?;
        let mut a = Attrs::new(el, Self::NAME);
        let v = Self {
            meta: Metadata::read(&mut a)?,
            time_zone: a.req("TimeZone")?,
            period: a.req::<XsDate>("Period")?.0,
            entity_address: a.req("EntityAddress")?,
        };
        a.finish()?;
        Ok(v)
    }
    fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
        w.start(Self::NAME);
        self.meta.write(w);
        w.attr("TimeZone", &self.time_zone)
            .attr("Period", self.period)
            .attr("EntityAddress", &self.entity_address)
            .end();
        Ok(())
    }
    fn answer(&self, reply: Reply) -> Option<Message> {
        Some(self.reply(reply, None).into())
    }
}

/// A connection on the queried congestion point.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QueriedConnection {
    /// The connection.
    pub entity_address: EntityAddress,
    /// The aggregator that represents its prosumer, if any.
    pub agr_domain: Option<InternetDomain>,
}

/// The queried congestion point with its connections.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QueriedCongestionPoint {
    /// The congestion point.
    pub entity_address: EntityAddress,
    /// Its connections; at least one.
    pub connections: Vec<QueriedConnection>,
}

/// The CRO's answer to a DSOPortfolioQuery `[XSD DSOPortfolioQueryResponseType]`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DsoPortfolioQueryResponse {
    header: ResponseHeader,
    dso_portfolio_query_message_id: MessageUuid,
    /// The zone of `period`, copied from the query.
    pub time_zone: TimeZoneName,
    /// The day, copied from the query.
    pub period: Date,
    /// The congestion point, if the CRO knows it.
    pub congestion_point: Option<QueriedCongestionPoint>,
}

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

    /// The `MessageID` of the DSOPortfolioQuery this answers.
    #[must_use]
    pub fn dso_portfolio_query_message_id(&self) -> MessageUuid {
        self.dso_portfolio_query_message_id
    }
}

impl DsoPortfolioQuery {
    /// Answers this query, copying the conversation, time zone and period.
    #[must_use]
    pub fn reply(
        &self,
        reply: Reply,
        congestion_point: Option<QueriedCongestionPoint>,
    ) -> DsoPortfolioQueryResponse {
        DsoPortfolioQueryResponse {
            header: ResponseHeader::reply_to(&self.meta, reply),
            dso_portfolio_query_message_id: self.meta.message_id,
            time_zone: self.time_zone.clone(),
            period: self.period,
            congestion_point,
        }
    }
}

impl Wire for DsoPortfolioQueryResponse {
    const NAME: &'static str = "DSOPortfolioQueryResponse";
    const RESPONSE: bool = true;
    fn meta(&self) -> &Metadata {
        self.header.meta()
    }
    fn meta_mut(&mut self) -> &mut Metadata {
        self.header.meta_mut()
    }
    fn in_reply_to(&self) -> Option<MessageUuid> {
        Some(self.dso_portfolio_query_message_id)
    }
    const REFERENCE: &'static str = "DSOPortfolioQueryMessageID";
    fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
        children(el, Self::NAME, &["CongestionPoint"])?;
        if el.children.len() > 1 {
            return Err(Rejection::schema(
                "[XSD] maxOccurs=1",
                "<DSOPortfolioQueryResponse> has at most one <CongestionPoint>.",
            )
            .at(Self::NAME));
        }
        let mut a = Attrs::new(el, Self::NAME);
        let header = ResponseHeader::read(&mut a)?;
        let dso_portfolio_query_message_id = a.req("DSOPortfolioQueryMessageID")?;
        let time_zone = a.req("TimeZone")?;
        let period = a.req::<XsDate>("Period")?.0;
        a.finish()?;
        let congestion_point = named(el, Self::NAME, "CongestionPoint")
            .map(|(p, c)| {
                children(c, &p, &["Connection"])?;
                require_one(c, &p, "Connection")?;
                let mut a = Attrs::new(c, p.clone());
                let entity_address = a.req("EntityAddress")?;
                a.finish()?;
                let connections = named(c, &p, "Connection")
                    .map(|(pp, cc)| {
                        children(cc, &pp, &[])?;
                        let mut a = Attrs::new(cc, pp);
                        let v = QueriedConnection {
                            entity_address: a.req("EntityAddress")?,
                            agr_domain: a.opt("AGR-Domain")?,
                        };
                        a.finish()?;
                        Ok(v)
                    })
                    .collect::<Result<_, Rejection>>()?;
                Ok(QueriedCongestionPoint {
                    entity_address,
                    connections,
                })
            })
            .next()
            .transpose()?;
        Ok(Self {
            header,
            dso_portfolio_query_message_id,
            time_zone,
            period,
            congestion_point,
        })
    }
    fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
        if let Some(c) = &self.congestion_point {
            nonempty(
                &c.connections,
                &format!("{}/CongestionPoint", Self::NAME),
                "Connection",
            )?;
        }
        w.start(Self::NAME);
        self.header.write(w);
        w.attr(
            "DSOPortfolioQueryMessageID",
            self.dso_portfolio_query_message_id,
        )
        .attr("TimeZone", &self.time_zone)
        .attr("Period", self.period);
        if let Some(c) = &self.congestion_point {
            w.start("CongestionPoint")
                .attr("EntityAddress", &c.entity_address);
            for conn in &c.connections {
                w.start("Connection")
                    .attr("EntityAddress", &conn.entity_address)
                    .opt_attr("AGR-Domain", conn.agr_domain.as_ref())
                    .end();
            }
            w.end();
        }
        w.end();
        Ok(())
    }
}