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};
#[derive(Debug, Clone)]
pub struct Endpoint {
options: OpenOptions,
guard: ReplayGuard,
market: Option<Market>,
outbox: Option<Outbox>,
}
impl Endpoint {
#[must_use]
pub fn new(options: OpenOptions, replay_window: SignedDuration) -> Self {
Self {
options,
guard: ReplayGuard::new(replay_window),
market: None,
outbox: None,
}
}
#[must_use]
pub fn with_market(mut self, market: Market) -> Self {
self.market = Some(market);
self
}
#[must_use]
pub fn with_outbox(mut self, outbox: Outbox) -> Self {
self.outbox = Some(outbox);
self
}
pub fn sent(&mut self, message: &Message, now: Timestamp) {
if let Some(outbox) = &mut self.outbox {
outbox.record(message, now);
}
}
#[must_use]
pub fn outbox(&self) -> Option<&Outbox> {
self.outbox.as_ref()
}
#[must_use]
pub fn with_replay_capacity(mut self, per_sender: usize) -> Self {
self.guard = self.guard.with_capacity(per_sender);
self
}
#[must_use]
pub fn options(&self) -> &OpenOptions {
&self.options
}
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)
}
}