use std::fmt;
use std::num::NonZeroU32;
use jiff::SignedDuration;
#[cfg(feature = "cs1")]
use jiff::Timestamp;
#[cfg(feature = "cs1")]
use crate::envelope::Opened;
#[cfg(feature = "cs1")]
use crate::msg::{Message, Reply};
use crate::reason::RejectionReason;
#[cfg(feature = "cs1")]
use crate::types::MessageUuid;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RejectKind {
Schema,
Limits,
Signature,
KeyLookup,
LengthRequired,
Header,
RateLimited,
Rule,
}
impl RejectKind {
#[must_use]
pub fn http_status(self) -> u16 {
match self {
Self::Schema | Self::Limits | Self::Header => 400,
Self::Signature => 401,
Self::LengthRequired => 411,
Self::KeyLookup => 419,
Self::RateLimited => 429,
Self::Rule => 200,
}
}
#[must_use]
pub fn is_temporary(self) -> bool {
matches!(self, Self::KeyLookup | Self::RateLimited)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Disposition {
Transport(u16),
Respond,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rejection {
kind: RejectKind,
rule: &'static str,
reason: Option<RejectionReason>,
location: Option<String>,
message: String,
#[cfg(feature = "cs1")]
bounce: Option<Box<Opened>>,
retry_after: Option<NonZeroU32>,
}
impl Rejection {
pub fn new(kind: RejectKind, rule: &'static str, message: impl Into<String>) -> Self {
Self {
kind,
rule,
reason: None,
location: None,
message: message.into(),
#[cfg(feature = "cs1")]
bounce: None,
retry_after: None,
}
}
pub(crate) fn schema(rule: &'static str, message: impl Into<String>) -> Self {
Self::new(RejectKind::Schema, rule, message)
}
pub(crate) fn rule(
reason: RejectionReason,
rule: &'static str,
message: impl Into<String>,
) -> Self {
let mut r = Self::new(RejectKind::Rule, rule, message);
r.reason = Some(reason);
r
}
pub(crate) fn at(mut self, location: impl Into<String>) -> Self {
let location = location.into();
self.location = Some(match self.location.take() {
Some(inner) => format!("{location}/{inner}"),
None => location,
});
self
}
#[must_use]
pub fn because(reason: RejectionReason, message: impl Into<String>) -> Self {
let rule = reason.source();
Self::rule(reason, rule, message)
}
#[cfg(feature = "cs1")]
pub(crate) fn with_bounce(mut self, opened: Opened) -> Self {
if self.kind == RejectKind::Rule {
self.bounce = Some(Box::new(opened));
}
self
}
#[must_use]
pub fn kind(&self) -> RejectKind {
self.kind
}
#[must_use]
pub fn disposition(&self) -> Disposition {
match self.kind {
RejectKind::Rule => Disposition::Respond,
k => Disposition::Transport(k.http_status()),
}
}
#[must_use]
pub fn rule_ref(&self) -> &'static str {
self.rule
}
#[must_use]
pub fn reason(&self) -> Option<&RejectionReason> {
self.reason.as_ref()
}
#[must_use]
pub fn location(&self) -> Option<&str> {
self.location.as_deref()
}
#[must_use]
pub fn http_status(&self) -> u16 {
self.kind.http_status()
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
#[must_use]
pub fn rejection_reason(&self) -> String {
match &self.reason {
Some(r) => format!("{r}: {}", self.message),
None => self.message.clone(),
}
}
#[must_use]
pub fn retry_after(&self) -> Option<SignedDuration> {
self.retry_after
.map(|s| SignedDuration::from_secs(i64::from(s.get())))
}
pub(crate) fn with_retry_after(mut self, delay: SignedDuration) -> Self {
let ms = u64::try_from(delay.as_millis()).unwrap_or(0);
let seconds = u32::try_from(ms.div_ceil(1000)).unwrap_or(u32::MAX).max(1);
self.retry_after = NonZeroU32::new(seconds);
self
}
#[cfg(feature = "cs1")]
#[cfg_attr(docsrs, doc(cfg(feature = "cs1")))]
#[must_use]
pub fn opened(&self) -> Option<&Opened> {
self.bounce.as_deref()
}
#[cfg(feature = "cs1")]
#[cfg_attr(docsrs, doc(cfg(feature = "cs1")))]
#[must_use]
pub fn response(&self, message_id: MessageUuid, timestamp: Timestamp) -> Option<Message> {
let opened = self.bounce.as_deref()?;
opened.reply(Reply::rejected(message_id, timestamp, self))
}
}
impl fmt::Display for Rejection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(loc) = &self.location {
write!(f, "{loc}: ")?;
}
if let Some(r) = &self.reason {
write!(f, "{r}: ")?;
}
write!(f, "{} {}", self.message, self.rule)
}
}
impl std::error::Error for Rejection {}
impl From<&Rejection> for String {
fn from(r: &Rejection) -> Self {
r.rejection_reason()
}
}
pub(crate) fn quote<S: AsRef<str> + ?Sized>(s: &S) -> Quoted<'_> {
Quoted(s.as_ref(), true)
}
pub(crate) fn name<S: AsRef<str> + ?Sized>(s: &S) -> Quoted<'_> {
Quoted(s.as_ref(), false)
}
pub(crate) const QUOTE_CHARS: usize = 64;
pub(crate) const QUOTE_BYTES: usize = 128;
pub(crate) struct Quoted<'a>(&'a str, bool);
impl fmt::Display for Quoted<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use fmt::Write as _;
let tick = if self.1 { "`" } else { "" };
f.write_str(tick)?;
let mut written = 0;
let mut piece = String::new();
for (i, c) in self.0.chars().enumerate() {
piece.clear();
match c {
'`' => piece.push_str("\\`"),
c if c.is_control() => write!(piece, "{}", c.escape_debug())?,
'\u{061C}'
| '\u{200E}'
| '\u{200F}'
| '\u{2028}'..='\u{202E}'
| '\u{2066}'..='\u{2069}' => write!(piece, "{}", c.escape_unicode())?,
c => piece.push(c),
}
if i == QUOTE_CHARS || written + piece.len() > QUOTE_BYTES {
f.write_str("…")?;
break;
}
written += piece.len();
f.write_str(&piece)?;
}
f.write_str(tick)
}
}
#[cfg(test)]
mod quote_tests {
use super::quote;
#[test]
fn escapes_what_could_forge_or_disguise_text() {
assert_eq!(quote("a\nb\r\tc").to_string(), "`a\\nb\\r\\tc`");
assert_eq!(
quote("\u{0}\u{7f}\u{85}").to_string(),
"`\\0\\u{7f}\\u{85}`"
);
assert_eq!(
quote("x\u{202e}y\u{2066}").to_string(),
"`x\\u{202e}y\\u{2066}`"
);
assert_eq!(
quote("\u{061c}\u{200e}\u{200f}").to_string(),
"`\\u{61c}\\u{200e}\\u{200f}`"
);
assert_eq!(quote("a`b").to_string(), "`a\\`b`");
assert_eq!(
quote("\u{2028}\u{2029}").to_string(),
"`\\u{2028}\\u{2029}`"
);
}
#[test]
fn keeps_printable_text() {
assert_eq!(quote("a\"b\\c'").to_string(), "`a\"b\\c'`");
assert_eq!(
quote("Müller 🔌 \u{fffd}").to_string(),
"`Müller 🔌 \u{fffd}`"
);
}
#[test]
fn cuts_escape_heavy_text_by_bytes() {
for c in ['\u{202e}', '\u{85}', '`', '🔌'] {
let q = quote(&c.to_string().repeat(200)).to_string();
assert!(
q.len() <= super::QUOTE_BYTES + "``…".len(),
"{c:?}: {}",
q.len()
);
assert!(q.ends_with("…`"), "{q}");
}
}
#[test]
fn cuts_after_64_characters_without_splitting_one() {
let exactly = "é".repeat(64);
assert_eq!(quote(&exactly).to_string(), format!("`{exactly}`"));
let longer = format!("{exactly}é");
assert_eq!(quote(&longer).to_string(), format!("`{exactly}…`"));
let newlines = "\n".repeat(100);
assert_eq!(
quote(&newlines).to_string(),
format!("`{}…`", "\\n".repeat(64))
);
}
}