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 receive pipeline, in one call.

use jiff::{SignedDuration, Timestamp};

use crate::directory::{IntoKeys, KeyLookupError};
use crate::envelope::{OpenOptions, Opened, open};
use crate::error::Rejection;
use crate::flow::Market;
use crate::msg::Message;
use crate::outbox::Outbox;
use crate::replay::ReplayGuard;
use crate::types::{InternetDomain, Role};

/// A receiver: every check the library knows, in the order the specification needs.
///
/// [`receive`](Self::receive) runs:
/// 1. [`open`]: wrapper, key lookup, strict signature check, schema, sender binding,
///    role, the rules of the message type, recipient;
/// 2. [`Market::check`], if a market is set;
/// 3. [`Message::check_time`](crate::Message::check_time) at `now`;
/// 4. [`Outbox::check`], if an outbox is set: a response must answer a request this
///    endpoint [`sent`](Self::sent);
/// 5. [`ReplayGuard::check`].
///
/// The replay guard runs last, so it remembers only messages the endpoint accepted. A
/// refused message's correction, sent with the same MessageID, is judged afresh, not
/// answered `Duplicate Identifier`. Every refusal after step 1 carries the message, so
/// [`Rejection::response`] gives the Rejected response to send.
///
/// ```
/// # use uftp::*;
/// # use uftp::jiff::{SignedDuration, Timestamp};
/// # fn handle(body: &[u8], directory: &Directory, now: Timestamp, id: MessageUuid) -> Result<(), Rejection> {
/// let mut endpoint = Endpoint::new(OpenOptions::for_recipient("agr.example".parse()?), SignedDuration::from_mins(15))
///     .with_market(Market { isp_duration: IspDuration::PT15M, time_zone: "Europe/Amsterdam".parse()? });
/// match endpoint.receive(body, now, directory.lookup()) {
///     Ok(opened) => { /* the application's turn */ }
///     Err(e) => {
///         // e.http_status() answers the POST; a Rejected response may follow.
///         if let Some(_answer) = e.response(id, now) { /* seal and send */ }
///     }
/// }
/// # Ok(()) }
/// ```
#[derive(Debug, Clone)]
pub struct Endpoint {
    options: OpenOptions,
    guard: ReplayGuard,
    market: Option<Market>,
    outbox: Option<Outbox>,
}

impl Endpoint {
    /// A receiver with these options and a replay window: TimeStamps further than
    /// `replay_window` from `now` are refused, and ids are remembered for as long.
    #[must_use]
    pub fn new(options: OpenOptions, replay_window: SignedDuration) -> Self {
        Self {
            options,
            guard: ReplayGuard::new(replay_window),
            market: None,
            outbox: None,
        }
    }

    /// Adds the market's ISP duration and time zone rules.
    #[must_use]
    pub fn with_market(mut self, market: Market) -> Self {
        self.market = Some(market);
        self
    }

    /// Adds an [`Outbox`]: a response is accepted only if it answers a request recorded
    /// with [`sent`](Self::sent).
    #[must_use]
    pub fn with_outbox(mut self, outbox: Outbox) -> Self {
        self.outbox = Some(outbox);
        self
    }

    /// Records a message this endpoint sends, if it has an outbox.
    pub fn sent(&mut self, message: &Message, now: Timestamp) {
        if let Some(outbox) = &mut self.outbox {
            outbox.record(message, now);
        }
    }

    /// The outbox, to find the request a response answers.
    #[must_use]
    pub fn outbox(&self) -> Option<&Outbox> {
        self.outbox.as_ref()
    }

    /// Sets how many messages are remembered per sender; more is refused with 429.
    #[must_use]
    pub fn with_replay_capacity(mut self, per_sender: usize) -> Self {
        self.guard = self.guard.with_capacity(per_sender);
        self
    }

    /// The options `open` runs with.
    #[must_use]
    pub fn options(&self) -> &OpenOptions {
        &self.options
    }

    /// Receives a SignedMessage document: see [`Endpoint`] for the checks and their order.
    ///
    /// # Errors
    /// The first check that fails, as its [`Rejection`]: a transport error (400, 401,
    /// 411, 419, 429), or a rule (200, answered with [`Rejection::response`]).
    pub fn receive<F, K>(
        &mut self,
        document: &[u8],
        now: Timestamp,
        lookup: F,
    ) -> Result<Opened, Rejection>
    where
        F: FnOnce(&InternetDomain, Role) -> Result<K, KeyLookupError>,
        K: IntoKeys,
    {
        let opened = open(document, &self.options, lookup)?;
        if let Some(market) = &self.market {
            market
                .check(opened.message())
                .map_err(|e| opened.reject(e))?;
        }
        opened
            .message()
            .check_time(now)
            .map_err(|e| opened.reject(e))?;
        if let Some(outbox) = &mut self.outbox {
            outbox.check(&opened, now)?;
        }
        self.guard.check(&opened, now)?;
        Ok(opened)
    }
}