use limiteron::fallback::FallbackStrategy;
#[derive(Clone)]
pub struct FallbackPolicy {
strategy: FallbackStrategy,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FallbackDecision {
Allow,
Deny,
UseDegradedResponse,
}
impl FallbackPolicy {
pub fn new(strategy: FallbackStrategy) -> Self {
Self { strategy }
}
pub fn fail_open() -> Self {
Self::new(FallbackStrategy::FailOpen)
}
pub fn fail_closed() -> Self {
Self::new(FallbackStrategy::FailClosed)
}
pub fn degraded() -> Self {
Self::new(FallbackStrategy::Degraded)
}
pub fn on_failure(&self) -> FallbackDecision {
match &self.strategy {
FallbackStrategy::FailOpen => FallbackDecision::Allow,
FallbackStrategy::FailClosed => FallbackDecision::Deny,
FallbackStrategy::Degraded => FallbackDecision::UseDegradedResponse,
}
}
pub fn strategy(&self) -> &FallbackStrategy {
&self.strategy
}
}
impl std::fmt::Debug for FallbackPolicy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FallbackPolicy")
.field("strategy", &self.strategy)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fail_open_allows_on_failure() {
let policy = FallbackPolicy::fail_open();
assert_eq!(policy.on_failure(), FallbackDecision::Allow);
}
#[test]
fn fail_closed_denies_on_failure() {
let policy = FallbackPolicy::fail_closed();
assert_eq!(policy.on_failure(), FallbackDecision::Deny);
}
#[test]
fn degraded_uses_fallback_response() {
let policy = FallbackPolicy::degraded();
assert_eq!(policy.on_failure(), FallbackDecision::UseDegradedResponse);
}
#[test]
fn debug_contains_strategy() {
let policy = FallbackPolicy::fail_open();
let debug = format!("{:?}", policy);
assert!(debug.contains("FallbackPolicy"));
assert!(debug.contains("FailOpen"));
}
#[test]
fn clone_preserves_strategy() {
let policy = FallbackPolicy::fail_closed();
let cloned = policy.clone();
assert_eq!(cloned.on_failure(), FallbackDecision::Deny);
}
}