uftp 0.2.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
//! Metering data from aggregator to DSO `[XSD UFTP-metering.xsd]`.
//!
//! No role schema of 3.1.0 includes this schema (SS-13); the messages are UFTP 3.1.0 all
//! the same (`[UFTP §4.2.26]`).

use jiff::civil::Date;
use rust_decimal::Decimal;

use crate::error::Rejection;
use crate::isp::DayGrid;
use crate::msg::agr_dso::nonempty;
use crate::msg::meta::{Metadata, Reply, ResponseHeader, XsDate, child_path, named};
use crate::msg::{DecodeOptions, Message, Wire, simple_response, wire_meta};
use crate::reason::RejectionReason as R;
use crate::types::{
    Currency, Ean, IspDuration, MessageUuid, MeteringProfileType, MeteringUnit, TimeZoneName,
};
use crate::xml::attrs::{Attrs, XsInteger, children, require_one};
use crate::xml::reader::Element;
use crate::xml::writer::Writer;

/// One metering value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MeteringIsp {
    /// The ISP number; `xs:integer` in the XSD, checked against the day by
    /// [`Message::validate`].
    pub start: i64,
    /// The value at the end of the ISP, in the profile's unit; `xs:decimal` in the XSD, an
    /// integer in the PDF (SS-14).
    pub value: Decimal,
}

/// A sequence of ISP values of one kind.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MeteringProfile {
    /// What the values are.
    pub profile_type: MeteringProfileType,
    /// Their unit: kW for Power, kWh otherwise (checked).
    pub unit: MeteringUnit,
    /// The values; at least one.
    pub isps: Vec<MeteringIsp>,
}

/// The aggregator's metering data for one connection and day `[XSD MeteringMessageType]`.
/// Sent by the AGR.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Metering {
    /// The common metadata.
    pub meta: Metadata,
    /// Incremented with each new revision.
    pub revision: i64,
    /// The ISP length.
    pub isp_duration: IspDuration,
    /// The zone in which `period` and its ISP numbers are read.
    pub time_zone: TimeZoneName,
    /// No longer used, per the PDF.
    pub currency: Option<Currency>,
    /// The day.
    pub period: Date,
    /// The connection.
    pub ean: Ean,
    /// The profiles; all the types agreed with the DSO.
    pub profiles: Vec<MeteringProfile>,
}

impl Metering {
    /// The ISP grid of this message's day.
    ///
    /// # Errors
    /// If the day is not a whole number of ISPs in the zone.
    pub fn grid(&self) -> Result<DayGrid, Rejection> {
        DayGrid::new(self.period, self.time_zone.clone(), self.isp_duration)
    }
}

impl Wire for Metering {
    const NAME: &'static str = "Metering";
    wire_meta!(meta);
    fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
        children(el, Self::NAME, &["Profile"])?;
        require_one(el, Self::NAME, "Profile")?;
        let mut a = Attrs::new(el, Self::NAME);
        let meta = Metadata::read(&mut a)?;
        let revision = a.req::<XsInteger>("Revision")?.0;
        let isp_duration = a.req("ISP-Duration")?;
        let time_zone = a.req("TimeZone")?;
        let currency = a.opt("Currency")?;
        let period = a.req::<XsDate>("Period")?.0;
        let ean = a.req("EAN")?;
        a.finish()?;
        let profiles = named(el, Self::NAME, "Profile")
            .map(|(p, c)| {
                children(c, &p, &["ISP"])?;
                require_one(c, &p, "ISP")?;
                let mut a = Attrs::new(c, p.clone());
                let profile_type = a.req("ProfileType")?;
                let unit = a.req("Unit")?;
                a.finish()?;
                let isps = named(c, &p, "ISP")
                    .map(|(pp, i)| {
                        children(i, &pp, &[])?;
                        let mut a = Attrs::new(i, pp);
                        let v = MeteringIsp {
                            start: a.req::<XsInteger>("Start")?.0,
                            value: a.req::<XsDecimal>("Value")?.0,
                        };
                        a.finish()?;
                        Ok(v)
                    })
                    .collect::<Result<_, Rejection>>()?;
                Ok(MeteringProfile {
                    profile_type,
                    unit,
                    isps,
                })
            })
            .collect::<Result<_, Rejection>>()?;
        Ok(Self {
            meta,
            revision,
            isp_duration,
            time_zone,
            currency,
            period,
            ean,
            profiles,
        })
    }
    fn validate(&self) -> Result<(), Rejection> {
        let grid = self.grid().map_err(|e| e.at(Self::NAME))?;
        for (i, p) in self.profiles.iter().enumerate() {
            let path = child_path(Self::NAME, "Profile", i);
            if p.unit != p.profile_type.unit() {
                return Err(Rejection::rule(
                    R::InvalidSender,
                    "[UFTP §4.2.26] kW for Power, kWh for energy profile types",
                    format!(
                        "A {} profile is in {}, not {}.",
                        p.profile_type,
                        p.profile_type.unit(),
                        p.unit
                    ),
                )
                .at(format!("{path}/@Unit")));
            }
            let mut seen = vec![false; grid.count() as usize];
            for (j, isp) in p.isps.iter().enumerate() {
                let at = || child_path(&path, "ISP", j);
                let n = usize::try_from(isp.start)
                    .ok()
                    .filter(|&n| (1..=seen.len()).contains(&n))
                    .ok_or_else(|| {
                        Rejection::rule(
                            R::IspsOutOfBounds,
                            "[UFTP §4.2.1]",
                            format!(
                                "ISP {} is not in {} ({} ISPs).",
                                isp.start,
                                self.period,
                                grid.count()
                            ),
                        )
                        .at(at())
                    })?;
                if std::mem::replace(&mut seen[n - 1], true) {
                    return Err(Rejection::rule(
                        R::IspConflict,
                        "[UFTP §4.2.1] each ISP in a period may only be addressed once",
                        format!("ISP {n} is addressed twice."),
                    )
                    .at(at()));
                }
            }
        }
        Ok(())
    }
    fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
        nonempty(&self.profiles, Self::NAME, "Profile")?;
        for (i, p) in self.profiles.iter().enumerate() {
            nonempty(&p.isps, &child_path(Self::NAME, "Profile", i), "ISP")?;
        }
        w.start(Self::NAME);
        self.meta.write(w);
        w.attr("Revision", self.revision)
            .attr("ISP-Duration", self.isp_duration)
            .attr("TimeZone", &self.time_zone)
            .opt_attr("Currency", self.currency.as_ref())
            .attr("Period", self.period)
            .attr("EAN", &self.ean);
        for p in &self.profiles {
            w.start("Profile")
                .attr("ProfileType", p.profile_type)
                .attr("Unit", p.unit);
            for i in &p.isps {
                w.start("ISP")
                    .attr("Start", i.start)
                    .attr("Value", i.value)
                    .end();
            }
            w.end();
        }
        w.end();
        Ok(())
    }
    fn answer(&self, reply: Reply) -> Option<Message> {
        Some(self.reply(reply).into())
    }
}

simple_response!(
    /// The DSO's answer to a Metering message `[XSD MeteringResponseType]`.
    MeteringResponse,
    "MeteringResponse",
    "MeteringMessageID",
    metering_message_id,
    Metering
);

/// An `xs:decimal`: optional sign, digits, optional fraction; no exponent.
struct XsDecimal(Decimal);

impl std::str::FromStr for XsDecimal {
    type Err = Rejection;
    fn from_str(s: &str) -> Result<Self, Rejection> {
        let body = s.strip_prefix(['+', '-']).unwrap_or(s);
        let (int, frac) = body.split_once('.').unwrap_or((body, ""));
        let digits = |p: &str| p.bytes().all(|b| b.is_ascii_digit());
        if (int.is_empty() && frac.is_empty()) || !digits(int) || !digits(frac) {
            return Err(Rejection::schema(
                "[XSD xs:decimal]",
                format!("{s} is not a decimal number.", s = crate::error::quote(&s)),
            ));
        }
        s.trim_start_matches('+')
            .parse::<Decimal>()
            .map(Self)
            .map_err(|_| {
                Rejection::schema(
                    "[XSD xs:decimal]",
                    format!(
                        "{s} has more digits than this library keeps (28).",
                        s = crate::error::quote(&s)
                    ),
                )
            })
    }
}