use serde::{Deserialize, Serialize};
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum digest_subscription_stateState {
Subscribed,
Unsubscribed,
}
impl Default for digest_subscription_stateState {
fn default() -> Self {
Self::Subscribed
}
}
impl std::fmt::Display for digest_subscription_stateState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Subscribed => write!(f, "subscribed"),
Self::Unsubscribed => write!(f, "unsubscribed"),
}
}
}
impl FromStr for digest_subscription_stateState {
type Err = StateMachineError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"subscribed" => Ok(Self::Subscribed),
"unsubscribed" => Ok(Self::Unsubscribed),
_ => Err(StateMachineError::InvalidState(s.to_string())),
}
}
}
impl digest_subscription_stateState {
pub fn is_initial(&self) -> bool {
matches!(self, Self::Subscribed)
}
pub fn is_final(&self) -> bool {
matches!(self, Self::Unsubscribed)
}
pub fn all() -> Vec<Self> {
vec![
Self::Subscribed,
Self::Unsubscribed,
]
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum digest_subscription_stateTransition {
Unsubscribe,
Resubscribe,
}
impl std::fmt::Display for digest_subscription_stateTransition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Unsubscribe => write!(f, "unsubscribe"),
Self::Resubscribe => write!(f, "resubscribe"),
}
}
}
impl FromStr for digest_subscription_stateTransition {
type Err = StateMachineError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"unsubscribe" => Ok(Self::Unsubscribe),
"resubscribe" => Ok(Self::Resubscribe),
_ => Err(StateMachineError::InvalidTransition(s.to_string())),
}
}
}
impl digest_subscription_stateTransition {
pub fn target_state(&self) -> digest_subscription_stateState {
match self {
Self::Unsubscribe => digest_subscription_stateState::Unsubscribed,
Self::Resubscribe => digest_subscription_stateState::Subscribed,
}
}
pub fn all() -> Vec<Self> {
vec![
Self::Unsubscribe,
Self::Resubscribe,
]
}
pub fn allowed_roles(&self) -> &'static [&'static str] {
match self {
Self::Unsubscribe => &[],
Self::Resubscribe => &[],
}
}
}
use super::StateMachineError;
#[derive(Debug, Clone)]
pub struct digest_subscription_stateStateMachine {
current_state: digest_subscription_stateState,
}
impl digest_subscription_stateStateMachine {
pub fn new() -> Self {
Self {
current_state: digest_subscription_stateState::default(),
}
}
pub fn from_state(state: digest_subscription_stateState) -> Self {
Self { current_state: state }
}
pub fn current_state(&self) -> digest_subscription_stateState {
self.current_state
}
pub fn can_transition(&self, transition: digest_subscription_stateTransition) -> bool {
match (self.current_state, transition) {
(digest_subscription_stateState::Subscribed, digest_subscription_stateTransition::Unsubscribe) => true,
(digest_subscription_stateState::Unsubscribed, digest_subscription_stateTransition::Resubscribe) => true,
_ => false,
}
}
pub fn can_transition_with_role(&self, transition: digest_subscription_stateTransition, 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: digest_subscription_stateTransition) -> Result<digest_subscription_stateState, 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: digest_subscription_stateTransition, role: &str) -> Result<digest_subscription_stateState, 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<digest_subscription_stateTransition> {
digest_subscription_stateTransition::all()
.into_iter()
.filter(|t| self.can_transition(*t))
.collect()
}
pub fn available_transitions_for_role(&self, role: &str) -> Vec<digest_subscription_stateTransition> {
digest_subscription_stateTransition::all()
.into_iter()
.filter(|t| self.can_transition_with_role(*t, role))
.collect()
}
pub fn transition_to_state(&mut self, target: digest_subscription_stateState) -> Result<digest_subscription_stateState, StateMachineError> {
let valid = digest_subscription_stateTransition::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 digest_subscription_stateStateMachine {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_initial_state() {
let sm = digest_subscription_stateStateMachine::new();
assert_eq!(sm.current_state(), digest_subscription_stateState::Subscribed);
assert!(sm.current_state().is_initial());
}
#[test]
fn test_valid_transition() {
let mut sm = digest_subscription_stateStateMachine::from_state(digest_subscription_stateState::Subscribed);
assert!(sm.can_transition(digest_subscription_stateTransition::Unsubscribe));
let result = sm.transition(digest_subscription_stateTransition::Unsubscribe);
assert!(result.is_ok());
assert_eq!(sm.current_state(), digest_subscription_stateState::Unsubscribed);
}
#[test]
fn test_invalid_transition() {
let mut sm = digest_subscription_stateStateMachine::from_state(digest_subscription_stateState::Subscribed);
let result = sm.transition(digest_subscription_stateTransition::Resubscribe);
assert!(result.is_err());
}
#[test]
fn test_state_parsing() {
let state: digest_subscription_stateState = "subscribed".parse().unwrap();
assert_eq!(state, digest_subscription_stateState::Subscribed);
}
#[test]
fn test_available_transitions() {
let sm = digest_subscription_stateStateMachine::new();
let available = sm.available_transitions();
assert!(!available.is_empty() || sm.current_state().is_final());
}
}