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 HTTP mapping of `[UFTP App. 4 §3, §4]`, without an HTTP dependency: constants, a
//! check of a received request before its body is read, and the classification of a
//! status received after sending.
//!
//! ```
//! use uftp::transport::{self, Delivery};
//!
//! // Receiving: refuse early, before reading the body.
//! transport::check_request(Some("text/xml; charset=utf-8"), Some(2048), &uftp::Limits::default())?;
//!
//! // Sending: what to do with the status the recipient answered.
//! assert_eq!(Delivery::of(200), Delivery::Delivered);
//! assert_eq!(Delivery::of(503), Delivery::Retry);
//! assert_eq!(Delivery::of(401), Delivery::Failed);
//! # Ok::<(), uftp::Rejection>(())
//! ```

use crate::error::{RejectKind, Rejection};
use crate::xml::reader::Limits;

/// The Content-Type of every UFTP POST.
pub const CONTENT_TYPE: &str = "text/xml; charset=utf-8";

/// The request path of `[UFTP App. 4 §3]`: `https://<host>/USEF/2019/SignedMessage`.
pub const SPEC_PATH: &str = "/USEF/2019/SignedMessage";

/// The request path of the Shapeshifter reference implementation (spec note SS-07).
pub const SHAPESHIFTER_PATH: &str = "/shapeshifter/api/v3/message";

/// Checks a received request's headers before the body is read `[UFTP App. 4 §4]`.
///
/// # Errors
/// - [`RejectKind::LengthRequired`] (411) without a Content-Length.
/// - [`RejectKind::Header`] (400) for a media type other than `text/xml`, or a
///   charset other than UTF-8.
/// - [`RejectKind::Limits`] (400) when the length is over the byte limit.
pub fn check_request(
    content_type: Option<&str>,
    content_length: Option<u64>,
    limits: &Limits,
) -> Result<(), Rejection> {
    let length = content_length.ok_or_else(|| {
        Rejection::new(
            RejectKind::LengthRequired,
            "[UFTP App. 4 §4] Content-Length",
            "The request has no Content-Length.",
        )
    })?;
    let ct = content_type.unwrap_or("");
    let mut parts = ct.split(';');
    let media = parts.next().unwrap_or("").trim();
    if !media.eq_ignore_ascii_case("text/xml") {
        return Err(content_type_error(&format!(
            "The Content-Type is {ct}; UFTP messages are text/xml.",
            ct = crate::error::quote(&ct)
        )));
    }
    for param in parts {
        if let Some((k, v)) = param.split_once('=')
            && k.trim().eq_ignore_ascii_case("charset")
        {
            let v = v.trim().trim_matches('"');
            if !v.eq_ignore_ascii_case("utf-8") {
                return Err(content_type_error(&format!(
                    "The charset is {v}; UFTP messages are UTF-8.",
                    v = crate::error::quote(&v)
                )));
            }
        }
    }
    if usize::try_from(length).map_or(true, |l| l > limits.max_bytes()) {
        return Err(Rejection::new(
            RejectKind::Limits,
            "[decoder limits]",
            format!(
                "The Content-Length {length} is over the limit of {} bytes.",
                limits.max_bytes()
            ),
        ));
    }
    Ok(())
}

fn content_type_error(message: &str) -> Rejection {
    Rejection::new(
        RejectKind::Header,
        "[UFTP App. 4 §4] Content-Type text/xml, UTF-8",
        message,
    )
}

/// What a sender does with the HTTP status the recipient answered `[UFTP App. 4 §3]`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Delivery {
    /// 2xx: the message is delivered; its business answer comes as a response message.
    Delivered,
    /// Try again later, with exponential back-off, for at least an hour: 3xx not followed
    /// by the client, 404 (ambiguous), 408, 419 (key lookup), 425, 429, 5xx and anything
    /// unknown.
    Retry,
    /// Every other 4xx: the message will never be accepted as it is.
    Failed,
}

impl Delivery {
    /// Classifies an HTTP status code.
    #[must_use]
    pub fn of(status: u16) -> Self {
        match status {
            200..=299 => Self::Delivered,
            404 | 408 | 419 | 425 | 429 => Self::Retry,
            400..=499 => Self::Failed,
            _ => Self::Retry,
        }
    }
}