use crate::error::PolicyError;
pub trait SendPolicy: Send + Sync {
fn check_sender(&self, from: &str) -> Result<(), PolicyError>;
fn check_recipients(&self, recipients: &[&str]) -> Result<(), PolicyError>;
fn check_message_size(&self, bytes: usize) -> Result<(), PolicyError>;
}
#[derive(Debug, Default, Clone, Copy)]
pub struct DefaultPolicy;
impl SendPolicy for DefaultPolicy {
fn check_sender(&self, _from: &str) -> Result<(), PolicyError> {
Ok(())
}
fn check_recipients(&self, _recipients: &[&str]) -> Result<(), PolicyError> {
Ok(())
}
fn check_message_size(&self, _bytes: usize) -> Result<(), PolicyError> {
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct BoundedPolicy {
max_recipients: Option<usize>,
max_message_bytes: Option<usize>,
}
impl BoundedPolicy {
#[must_use]
pub const fn new() -> Self {
Self {
max_recipients: None,
max_message_bytes: None,
}
}
#[must_use]
pub const fn max_recipients(mut self, n: usize) -> Self {
self.max_recipients = Some(n);
self
}
#[must_use]
pub const fn max_message_bytes(mut self, bytes: usize) -> Self {
self.max_message_bytes = Some(bytes);
self
}
}
impl Default for BoundedPolicy {
fn default() -> Self {
Self::new()
}
}
impl SendPolicy for BoundedPolicy {
fn check_sender(&self, _from: &str) -> Result<(), PolicyError> {
Ok(())
}
fn check_recipients(&self, recipients: &[&str]) -> Result<(), PolicyError> {
if let Some(max) = self.max_recipients {
if recipients.len() > max {
return Err(PolicyError::new(format!(
"too many recipients: {actual} exceeds limit of {max}",
actual = recipients.len(),
)));
}
}
Ok(())
}
fn check_message_size(&self, bytes: usize) -> Result<(), PolicyError> {
if let Some(max) = self.max_message_bytes {
if bytes > max {
return Err(PolicyError::new(format!(
"message too large: {bytes} bytes exceeds limit of {max} bytes",
)));
}
}
Ok(())
}
}