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 attributes every message carries, and the extra ones of flex messages and responses.

use std::str::FromStr;

use jiff::Timestamp;
use jiff::civil::Date;

use crate::error::Rejection;
use crate::isp::{DayGrid, IspSpan};
use crate::types::{
    AcceptedRejected, EntityAddress, InternetDomain, IspDuration, MessageUuid, SpecVersion,
    TimeZoneName,
};
use crate::xml::attrs::{Attrs, XsPositive};
use crate::xml::reader::Element;
use crate::xml::writer::Writer;

/// An `xs:dateTime` with a time-zone offset, as the specification requires for every
/// timestamp.
pub(crate) struct XsDateTime(pub Timestamp);

impl FromStr for XsDateTime {
    type Err = Rejection;
    fn from_str(s: &str) -> Result<Self, Rejection> {
        s.parse::<Timestamp>().map(Self).map_err(|_| {
            Rejection::schema(
                "[UFTP §4.2.2] date and time including the time zone",
                format!(
                    "{s} is not a date and time with an offset, such as 2026-12-01T10:00:00+01:00.",
                    s = crate::error::quote(&s)
                ),
            )
        })
    }
}

/// An `xs:date` without an offset (`PeriodType`). A Period's time zone is the message's
/// `TimeZone` attribute, so an offset on the date itself is refused.
pub(crate) struct XsDate(pub Date);

impl FromStr for XsDate {
    type Err = Rejection;
    fn from_str(s: &str) -> Result<Self, Rejection> {
        if s.len() == 10
            && let Ok(d) = s.parse::<Date>()
        {
            return Ok(Self(d));
        }
        Err(Rejection::schema(
            "[XSD PeriodType]",
            format!(
                "{s} is not a day in the form yyyy-mm-dd.",
                s = crate::error::quote(&s)
            ),
        ))
    }
}

/// The metadata of every non-wrapper message `[UFTP §4.2.2]`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Metadata {
    /// The Shapeshifter version the sender implements.
    pub version: SpecVersion,
    /// The sender's domain. It must equal the `SignedMessage` wrapper's.
    pub sender_domain: InternetDomain,
    /// The recipient's domain.
    pub recipient_domain: InternetDomain,
    /// When the message was created. The caller supplies it; the library reads no clock.
    pub timestamp: Timestamp,
    /// The message's own id. The caller supplies it; the library has no random source.
    pub message_id: MessageUuid,
    /// The conversation this message belongs to, copied into every reply.
    pub conversation_id: MessageUuid,
}

impl Metadata {
    /// Metadata for a new message in version 3.1.0 that starts a conversation: the
    /// conversation id is the message id `[UFTP §4.2.2]`. To continue another
    /// conversation, add [`in_conversation`](Self::in_conversation); a reply gets its
    /// metadata from [`reply`](Self::reply).
    ///
    /// ```
    /// # use uftp::*;
    /// let id = MessageUuid::from_bytes([1; 16]);
    /// let now = "2026-11-30T12:00:00Z".parse()?;
    /// let meta = Metadata::new("dso.example".parse()?, "agr.example".parse()?, now, id);
    /// assert_eq!(meta.conversation_id, id);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use]
    pub fn new(
        sender_domain: InternetDomain,
        recipient_domain: InternetDomain,
        timestamp: Timestamp,
        message_id: MessageUuid,
    ) -> Self {
        Self {
            version: SpecVersion::current(),
            sender_domain,
            recipient_domain,
            timestamp,
            message_id,
            conversation_id: message_id,
        }
    }

    /// The same metadata in an existing conversation.
    #[must_use]
    pub fn in_conversation(mut self, conversation_id: MessageUuid) -> Self {
        self.conversation_id = conversation_id;
        self
    }

    /// Metadata for a reply to this message: the domains are swapped and the conversation
    /// id is kept.
    #[must_use]
    pub fn reply(&self, message_id: MessageUuid, timestamp: Timestamp) -> Self {
        Self {
            version: SpecVersion::current(),
            sender_domain: self.recipient_domain.clone(),
            recipient_domain: self.sender_domain.clone(),
            timestamp,
            message_id,
            conversation_id: self.conversation_id,
        }
    }

    pub(crate) fn read(a: &mut Attrs<'_>) -> Result<Self, Rejection> {
        let version: SpecVersion = a.req("Version")?;
        if version.major() != 3 {
            return Err(Rejection::schema(
                "[UFTP §4.2.2 Version]",
                format!("Version {version} is not a 3.x version; this library implements 3.1.0."),
            )
            .at(format!("{}/@Version", a.path())));
        }
        Ok(Self {
            version,
            sender_domain: a.req("SenderDomain")?,
            recipient_domain: a.req("RecipientDomain")?,
            timestamp: a.req::<XsDateTime>("TimeStamp")?.0,
            message_id: a.req("MessageID")?,
            conversation_id: a.req("ConversationID")?,
        })
    }

    pub(crate) fn write(&self, w: &mut Writer) {
        w.attr("Version", &self.version)
            .attr("SenderDomain", &self.sender_domain)
            .attr("RecipientDomain", &self.recipient_domain)
            .attr("TimeStamp", self.timestamp)
            .attr("MessageID", self.message_id)
            .attr("ConversationID", self.conversation_id);
    }
}

/// The attributes a response adds: the result and, if rejected, why.
///
/// A response header is built only by the `reply` methods of the request it answers, so
/// it always carries the request's conversation id.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResponseHeader {
    meta: Metadata,
    result: AcceptedRejected,
    rejection_reason: Option<String>,
}

impl ResponseHeader {
    pub(crate) fn reply_to(request: &Metadata, reply: Reply) -> Self {
        Self {
            meta: request.reply(reply.message_id, reply.timestamp),
            result: reply.result,
            rejection_reason: reply.rejection_reason,
        }
    }

    /// The response's metadata.
    #[must_use]
    pub fn meta(&self) -> &Metadata {
        &self.meta
    }

    pub(crate) fn meta_mut(&mut self) -> &mut Metadata {
        &mut self.meta
    }

    /// Accepted or Rejected.
    #[must_use]
    pub fn result(&self) -> AcceptedRejected {
        self.result
    }

    /// Why the request was rejected.
    #[must_use]
    pub fn rejection_reason(&self) -> Option<&str> {
        self.rejection_reason.as_deref()
    }

    pub(crate) fn read(a: &mut Attrs<'_>) -> Result<Self, Rejection> {
        Ok(Self {
            meta: Metadata::read(a)?,
            result: a.req("Result")?,
            rejection_reason: a.opt_string("RejectionReason"),
        })
    }

    pub(crate) fn write(&self, w: &mut Writer) {
        self.meta.write(w);
        w.attr("Result", self.result)
            .opt_attr("RejectionReason", self.rejection_reason.as_ref());
    }
}

/// What a reply needs from the caller: its id, its time and the outcome.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reply {
    /// The reply's own message id.
    pub message_id: MessageUuid,
    /// When the reply was created.
    pub timestamp: Timestamp,
    /// Accepted or Rejected.
    pub result: AcceptedRejected,
    /// Why, when rejected. A [`Rejection`]'s message is a good reason.
    pub rejection_reason: Option<String>,
}

impl Reply {
    /// An acceptance.
    #[must_use]
    pub fn accepted(message_id: MessageUuid, timestamp: Timestamp) -> Self {
        Self {
            message_id,
            timestamp,
            result: AcceptedRejected::Accepted,
            rejection_reason: None,
        }
    }

    /// A rejection with a reason.
    #[must_use]
    pub fn rejected(
        message_id: MessageUuid,
        timestamp: Timestamp,
        reason: impl Into<String>,
    ) -> Self {
        Self {
            message_id,
            timestamp,
            result: AcceptedRejected::Rejected,
            rejection_reason: Some(reason.into()),
        }
    }
}

/// The attributes of every Flex* message and the D-Prognosis `[XSD FlexMessageType]`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlexHeader {
    /// The common metadata.
    pub meta: Metadata,
    /// The ISP length, `PT15M` in Europe.
    pub isp_duration: IspDuration,
    /// The zone in which `period` and its ISP numbers are read.
    pub time_zone: TimeZoneName,
    /// The day the ISPs belong to.
    pub period: Date,
    /// The congestion point the message applies to.
    pub congestion_point: EntityAddress,
}

impl FlexHeader {
    /// A header for `period` in `time_zone` at `congestion_point`, with the ISP length of
    /// every European market, `PT15M`. Another length: [`with_isp_duration`](Self::with_isp_duration).
    #[must_use]
    pub fn new(
        meta: Metadata,
        time_zone: TimeZoneName,
        period: Date,
        congestion_point: EntityAddress,
    ) -> Self {
        Self {
            meta,
            isp_duration: IspDuration::PT15M,
            time_zone,
            period,
            congestion_point,
        }
    }

    /// The same header with another ISP length.
    #[must_use]
    pub fn with_isp_duration(mut self, isp_duration: IspDuration) -> Self {
        self.isp_duration = isp_duration;
        self
    }

    /// 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)
    }

    pub(crate) fn read(a: &mut Attrs<'_>) -> Result<Self, Rejection> {
        Ok(Self {
            meta: Metadata::read(a)?,
            isp_duration: a.req("ISP-Duration")?,
            time_zone: a.req("TimeZone")?,
            period: a.req::<XsDate>("Period")?.0,
            congestion_point: a.req("CongestionPoint")?,
        })
    }

    pub(crate) fn write(&self, w: &mut Writer) {
        self.meta.write(w);
        w.attr("ISP-Duration", self.isp_duration)
            .attr("TimeZone", &self.time_zone)
            .attr("Period", self.period)
            .attr("CongestionPoint", &self.congestion_point);
    }
}

/// Reads `Start` and `Duration` (default 1).
pub(crate) fn read_span(a: &mut Attrs<'_>) -> Result<IspSpan, Rejection> {
    let start: XsPositive = a.req("Start")?;
    let duration = a.opt::<XsPositive>("Duration")?.map_or(1, |d| d.0);
    IspSpan::new(start.0, duration).map_err(|e| e.at(a.path().to_owned()))
}

pub(crate) fn write_span(w: &mut Writer, span: IspSpan) {
    w.attr("Start", span.start());
    if span.duration() != 1 {
        w.attr("Duration", span.duration());
    }
}

/// The path of the `i`-th (0-based) child named `name`, for error locations.
pub(crate) fn child_path(parent: &str, name: &str, i: usize) -> String {
    format!("{parent}/{name}[{}]", i + 1)
}

/// Iterates the children of `el` named `name`, with their paths.
pub(crate) fn named<'a>(
    el: &'a Element,
    parent: &'a str,
    name: &'a str,
) -> impl Iterator<Item = (String, &'a Element)> + 'a {
    el.children
        .iter()
        .filter(move |c| c.name == name)
        .enumerate()
        .map(move |(i, c)| (child_path(parent, name, i), c))
}