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
//! What this endpoint sent, so a response can be matched to its request `[UFTP §3.5]`.

use std::collections::{BTreeSet, HashMap};

use jiff::{SignedDuration, Timestamp};

use crate::envelope::Opened;
use crate::error::Rejection;
use crate::msg::{Message, Reply};
use crate::reason::RejectionReason;
use crate::types::MessageUuid;

/// The requests this endpoint sent, kept for a retention, so a response can be checked
/// against them and matched to them.
///
/// A response is accepted only if it answers a recorded request:
/// - of the type it answers (a FlexOfferResponse answers a FlexOffer);
/// - sent to the response's verified sender;
/// - from the domain the response is addressed to.
///
/// Anything else is `Unknown reference <attribute>` (§3.5). Without that check, any
/// participant could answer a request that was never sent, or one sent to someone else.
///
/// ```
/// # use uftp::*;
/// # use uftp::jiff::{SignedDuration, Timestamp};
/// # fn demo(request: FlexRequest, opened: Opened, now: Timestamp) -> Result<(), Rejection> {
/// let mut outbox = Outbox::new(SignedDuration::from_hours(24));
/// outbox.record(&request.into(), now); // when sending
/// outbox.check(&opened, now)?; // when a response arrives
/// let _request = outbox.request_for(opened.message());
/// # Ok(()) }
/// ```
#[derive(Debug, Clone)]
pub struct Outbox {
    retention: SignedDuration,
    sent: HashMap<MessageUuid, (Message, Timestamp)>,
    order: BTreeSet<(Timestamp, MessageUuid)>,
}

impl Outbox {
    /// An outbox that keeps each request for `retention` after it was recorded.
    #[must_use]
    pub fn new(retention: SignedDuration) -> Self {
        Self {
            retention: retention.abs(),
            sent: HashMap::new(),
            order: BTreeSet::new(),
        }
    }

    /// Records a message this endpoint sends. Responses are ignored: nothing answers them.
    pub fn record(&mut self, message: &Message, now: Timestamp) {
        self.evict(now);
        if message.is_response() {
            return;
        }
        let id = message.meta().message_id;
        if let Some((_, at)) = self.sent.insert(id, (message.clone(), now)) {
            self.order.remove(&(at, id));
        }
        self.order.insert((now, id));
    }

    /// The recorded request that `response` answers, if any.
    #[must_use]
    pub fn request_for(&self, response: &Message) -> Option<&Message> {
        let (request, _) = self.sent.get(&response.in_reply_to()?)?;
        answers(response, request).then_some(request)
    }

    /// Checks that a received response answers a recorded request; other messages pass.
    ///
    /// # Errors
    /// `Unknown reference <attribute>` ([`RejectionReason::UnknownReference`]) for a response
    /// to an unrecorded or expired request, to one sent to or from another domain, or to one
    /// of another type. It carries the message but produces no response to it.
    pub fn check(&mut self, opened: &Opened, now: Timestamp) -> Result<(), Rejection> {
        self.evict(now);
        let response = opened.message();
        let (Some(id), Some(attribute)) = (response.in_reply_to(), response.reference_attribute())
        else {
            return Ok(());
        };
        if self.request_for(response).is_some() {
            return Ok(());
        }
        Err(opened.reject(Rejection::because(
            RejectionReason::UnknownReference(attribute),
            format!(
                "{attribute} {id} names no {} this endpoint sent to {} in the last {:#}.",
                request_type(response),
                opened.sender_domain(),
                self.retention
            ),
        )))
    }

    /// How many requests are recorded.
    #[must_use]
    pub fn len(&self) -> usize {
        self.sent.len()
    }

    /// Whether no request is recorded.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.sent.is_empty()
    }

    fn evict(&mut self, now: Timestamp) {
        while let Some(&(at, id)) = self.order.first() {
            if now.duration_since(at) <= self.retention {
                break;
            }
            self.order.pop_first();
            self.sent.remove(&id);
        }
    }
}

/// Whether `response` answers `request`: the type the request's reply has, sent back
/// between the same two domains.
fn answers(response: &Message, request: &Message) -> bool {
    let (rq, rs) = (request.meta(), response.meta());
    rq.recipient_domain == rs.sender_domain
        && rq.sender_domain == rs.recipient_domain
        && reply_type(request) == Some(response.type_name())
}

/// The type of the response a request gets. Accepted where that exists, rejected
/// otherwise (a TestMessage has no rejected reply, an AGRPortfolioQuery no generic
/// accepted one).
fn reply_type(request: &Message) -> Option<&'static str> {
    let at = request.meta().timestamp;
    let id = request.meta().message_id;
    request
        .reply(Reply::accepted(id, at))
        .or_else(|| request.reply(Reply::rejected(id, at, RejectionReason::InvalidSender)))
        .map(|r| r.type_name())
}

/// For the refusal text: "FlexRequest" for a FlexRequestResponse.
fn request_type(response: &Message) -> &'static str {
    let name = response.type_name();
    Message::TYPE_NAMES
        .iter()
        .copied()
        .find(|n| name.strip_suffix("Response") == Some(*n))
        .unwrap_or("request")
}