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;
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)
),
)
})
}
}
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)
),
))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Metadata {
pub version: SpecVersion,
pub sender_domain: InternetDomain,
pub recipient_domain: InternetDomain,
pub timestamp: Timestamp,
pub message_id: MessageUuid,
pub conversation_id: MessageUuid,
}
impl Metadata {
#[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,
}
}
#[must_use]
pub fn in_conversation(mut self, conversation_id: MessageUuid) -> Self {
self.conversation_id = conversation_id;
self
}
#[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);
}
}
#[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,
}
}
#[must_use]
pub fn meta(&self) -> &Metadata {
&self.meta
}
pub(crate) fn meta_mut(&mut self) -> &mut Metadata {
&mut self.meta
}
#[must_use]
pub fn result(&self) -> AcceptedRejected {
self.result
}
#[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());
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reply {
pub message_id: MessageUuid,
pub timestamp: Timestamp,
pub result: AcceptedRejected,
pub rejection_reason: Option<String>,
}
impl Reply {
#[must_use]
pub fn accepted(message_id: MessageUuid, timestamp: Timestamp) -> Self {
Self {
message_id,
timestamp,
result: AcceptedRejected::Accepted,
rejection_reason: None,
}
}
#[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()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlexHeader {
pub meta: Metadata,
pub isp_duration: IspDuration,
pub time_zone: TimeZoneName,
pub period: Date,
pub congestion_point: EntityAddress,
}
impl FlexHeader {
#[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,
}
}
#[must_use]
pub fn with_isp_duration(mut self, isp_duration: IspDuration) -> Self {
self.isp_duration = isp_duration;
self
}
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);
}
}
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());
}
}
pub(crate) fn child_path(parent: &str, name: &str, i: usize) -> String {
format!("{parent}/{name}[{}]", i + 1)
}
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))
}