use serde::{Deserialize, Serialize};
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MailHooksState {
Outgoing,
Sent,
Received,
Exception,
Cancel,
}
impl Default for MailHooksState {
fn default() -> Self {
Self::Outgoing
}
}
impl std::fmt::Display for MailHooksState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Outgoing => write!(f, "outgoing"),
Self::Sent => write!(f, "sent"),
Self::Received => write!(f, "received"),
Self::Exception => write!(f, "exception"),
Self::Cancel => write!(f, "cancel"),
}
}
}
impl FromStr for MailHooksState {
type Err = StateMachineError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"outgoing" => Ok(Self::Outgoing),
"sent" => Ok(Self::Sent),
"received" => Ok(Self::Received),
"exception" => Ok(Self::Exception),
"cancel" => Ok(Self::Cancel),
_ => Err(StateMachineError::InvalidState(s.to_string())),
}
}
}
impl MailHooksState {
pub fn is_initial(&self) -> bool {
matches!(self, Self::Outgoing)
}
pub fn is_final(&self) -> bool {
matches!(self, Self::Sent | Self::Received | Self::Cancel)
}
pub fn all() -> Vec<Self> {
vec![
Self::Outgoing,
Self::Sent,
Self::Received,
Self::Exception,
Self::Cancel,
]
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MailHooksTransition {
SmtpAccepted,
SmtpFailed,
InboundAcknowledged,
Requeued,
Cancelled,
}
impl std::fmt::Display for MailHooksTransition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::SmtpAccepted => write!(f, "smtp_accepted"),
Self::SmtpFailed => write!(f, "smtp_failed"),
Self::InboundAcknowledged => write!(f, "inbound_acknowledged"),
Self::Requeued => write!(f, "requeued"),
Self::Cancelled => write!(f, "cancelled"),
}
}
}
impl FromStr for MailHooksTransition {
type Err = StateMachineError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"smtp_accepted" => Ok(Self::SmtpAccepted),
"smtp_failed" => Ok(Self::SmtpFailed),
"inbound_acknowledged" => Ok(Self::InboundAcknowledged),
"requeued" => Ok(Self::Requeued),
"cancelled" => Ok(Self::Cancelled),
_ => Err(StateMachineError::InvalidTransition(s.to_string())),
}
}
}
impl MailHooksTransition {
pub fn target_state(&self) -> MailHooksState {
match self {
Self::SmtpAccepted => MailHooksState::Sent,
Self::SmtpFailed => MailHooksState::Exception,
Self::InboundAcknowledged => MailHooksState::Received,
Self::Requeued => MailHooksState::Outgoing,
Self::Cancelled => MailHooksState::Cancel,
}
}
pub fn all() -> Vec<Self> {
vec![
Self::SmtpAccepted,
Self::SmtpFailed,
Self::InboundAcknowledged,
Self::Requeued,
Self::Cancelled,
]
}
pub fn allowed_roles(&self) -> &'static [&'static str] {
match self {
Self::SmtpAccepted => &[],
Self::SmtpFailed => &[],
Self::InboundAcknowledged => &[],
Self::Requeued => &[],
Self::Cancelled => &[],
}
}
}
use super::StateMachineError;
#[derive(Debug, Clone)]
pub struct MailHooksStateMachine {
current_state: MailHooksState,
}
impl MailHooksStateMachine {
pub fn new() -> Self {
Self {
current_state: MailHooksState::default(),
}
}
pub fn from_state(state: MailHooksState) -> Self {
Self { current_state: state }
}
pub fn current_state(&self) -> MailHooksState {
self.current_state
}
pub fn can_transition(&self, transition: MailHooksTransition) -> bool {
if matches!(self.current_state, MailHooksState::Received | MailHooksState::Cancel) {
return false;
}
match (self.current_state, transition) {
(MailHooksState::Outgoing, MailHooksTransition::SmtpAccepted) => true,
(MailHooksState::Outgoing, MailHooksTransition::SmtpFailed) => true,
(MailHooksState::Sent, MailHooksTransition::InboundAcknowledged) => true,
(MailHooksState::Exception, MailHooksTransition::Requeued) => true,
(MailHooksState::Outgoing, MailHooksTransition::Cancelled) => true,
(MailHooksState::Exception, MailHooksTransition::Cancelled) => true,
_ => false,
}
}
pub fn can_transition_with_role(&self, transition: MailHooksTransition, role: &str) -> bool {
if !self.can_transition(transition) {
return false;
}
let allowed_roles = transition.allowed_roles();
if allowed_roles.is_empty() {
return true; }
allowed_roles.iter().any(|r| *r == role || *r == "*")
}
pub fn transition(&mut self, transition: MailHooksTransition) -> Result<MailHooksState, StateMachineError> {
if !self.can_transition(transition) {
return Err(StateMachineError::TransitionNotAllowed {
transition: transition.to_string(),
from: self.current_state.to_string(),
});
}
self.current_state = transition.target_state();
Ok(self.current_state)
}
pub fn transition_with_role(&mut self, transition: MailHooksTransition, role: &str) -> Result<MailHooksState, StateMachineError> {
if !self.can_transition(transition) {
return Err(StateMachineError::TransitionNotAllowed {
transition: transition.to_string(),
from: self.current_state.to_string(),
});
}
if !self.can_transition_with_role(transition, role) {
return Err(StateMachineError::RoleNotAuthorized {
role: role.to_string(),
transition: transition.to_string(),
});
}
self.current_state = transition.target_state();
Ok(self.current_state)
}
pub fn available_transitions(&self) -> Vec<MailHooksTransition> {
MailHooksTransition::all()
.into_iter()
.filter(|t| self.can_transition(*t))
.collect()
}
pub fn available_transitions_for_role(&self, role: &str) -> Vec<MailHooksTransition> {
MailHooksTransition::all()
.into_iter()
.filter(|t| self.can_transition_with_role(*t, role))
.collect()
}
pub fn transition_to_state(&mut self, target: MailHooksState) -> Result<MailHooksState, StateMachineError> {
let valid = MailHooksTransition::all().into_iter()
.filter(|t| self.can_transition(*t))
.find(|t| t.target_state() == target);
match valid {
Some(t) => self.transition(t),
None => Err(StateMachineError::TransitionNotAllowed {
transition: target.to_string(),
from: self.current_state.to_string(),
}),
}
}
}
impl Default for MailHooksStateMachine {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_initial_state() {
let sm = MailHooksStateMachine::new();
assert_eq!(sm.current_state(), MailHooksState::Outgoing);
assert!(sm.current_state().is_initial());
}
#[test]
fn test_valid_transition() {
let mut sm = MailHooksStateMachine::from_state(MailHooksState::Outgoing);
assert!(sm.can_transition(MailHooksTransition::SmtpAccepted));
let result = sm.transition(MailHooksTransition::SmtpAccepted);
assert!(result.is_ok());
assert_eq!(sm.current_state(), MailHooksState::Sent);
}
#[test]
fn test_invalid_transition() {
let mut sm = MailHooksStateMachine::from_state(MailHooksState::Outgoing);
let result = sm.transition(MailHooksTransition::InboundAcknowledged);
assert!(result.is_err());
}
#[test]
fn test_state_parsing() {
let state: MailHooksState = "outgoing".parse().unwrap();
assert_eq!(state, MailHooksState::Outgoing);
}
#[test]
fn test_available_transitions() {
let sm = MailHooksStateMachine::new();
let available = sm.available_transitions();
assert!(!available.is_empty() || sm.current_state().is_final());
}
}