use crate::error::BaseError;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CircuitBreakerConfig {
pub failure_threshold: u32,
pub cooldown_secs: u64,
pub success_threshold: u32,
}
impl Default for CircuitBreakerConfig {
fn default() -> Self {
Self {
failure_threshold: 5,
cooldown_secs: 30,
success_threshold: 1,
}
}
}
impl CircuitBreakerConfig {
pub fn validate(&self) -> Result<(), BaseError> {
if self.failure_threshold == 0 {
return Err(BaseError::ParamInvalid(
"http.circuit_breaker.failure_threshold".to_string(),
"熔断器失败阈值必须大于 0".to_string(),
));
}
if self.cooldown_secs == 0 {
return Err(BaseError::ParamInvalid(
"http.circuit_breaker.cooldown_secs".to_string(),
"熔断器冷却时间必须大于 0 秒".to_string(),
));
}
if self.success_threshold == 0 {
return Err(BaseError::ParamInvalid(
"http.circuit_breaker.success_threshold".to_string(),
"熔断器恢复成功阈值必须大于 0".to_string(),
));
}
Ok(())
}
}
#[cfg(test)]
mod config_tests {
use super::*;
use crate::error::BaseError;
#[test]
fn test_circuit_breaker_config_validate_rejects_zero_values() {
let invalid_configs = [
(
"http.circuit_breaker.failure_threshold",
CircuitBreakerConfig {
failure_threshold: 0,
..CircuitBreakerConfig::default()
},
),
(
"http.circuit_breaker.cooldown_secs",
CircuitBreakerConfig {
cooldown_secs: 0,
..CircuitBreakerConfig::default()
},
),
(
"http.circuit_breaker.success_threshold",
CircuitBreakerConfig {
success_threshold: 0,
..CircuitBreakerConfig::default()
},
),
];
for (expected_field, config) in invalid_configs {
let err = config.validate().expect_err("熔断器零值配置应被拒绝");
assert!(matches!(
err,
BaseError::ParamInvalid(field, _) if field == expected_field
));
}
}
#[test]
fn test_circuit_breaker_new_rejects_invalid_config() {
let err = CircuitBreaker::new(CircuitBreakerConfig {
failure_threshold: 0,
..CircuitBreakerConfig::default()
})
.expect_err("公开构造器应拒绝非法熔断器配置");
assert!(matches!(
err,
BaseError::ParamInvalid(field, _) if field == "http.circuit_breaker.failure_threshold"
));
}
}
#[derive(Debug)]
enum Phase {
Closed { failures: u32 },
Open { opened_at: Instant },
HalfOpen { successes: u32 },
}
#[derive(Debug, Clone)]
pub struct CircuitBreaker {
config: CircuitBreakerConfig,
states: Arc<Mutex<HashMap<String, Phase>>>,
}
impl CircuitBreaker {
pub fn new(config: CircuitBreakerConfig) -> Result<Self, BaseError> {
config.validate()?;
Ok(Self {
config,
states: Arc::new(Mutex::new(HashMap::new())),
})
}
pub fn allow(&self, host: &str) -> bool {
self.allow_at(host, Instant::now())
}
pub fn on_success(&self, host: &str) {
let mut map = self.states.lock().unwrap_or_else(|p| p.into_inner());
match map.get_mut(host) {
Some(Phase::Closed { .. }) => {
map.remove(host);
}
Some(Phase::HalfOpen { successes }) => {
*successes += 1;
if *successes >= self.config.success_threshold {
map.remove(host); }
}
_ => {}
}
}
pub fn on_failure(&self, host: &str) {
self.on_failure_at(host, Instant::now());
}
pub(crate) fn allow_at(&self, host: &str, now: Instant) -> bool {
let mut map = self.states.lock().unwrap_or_else(|p| p.into_inner());
match map.get(host) {
None | Some(Phase::Closed { .. }) | Some(Phase::HalfOpen { .. }) => true,
Some(Phase::Open { opened_at }) => {
let cooled = now.duration_since(*opened_at)
>= Duration::from_secs(self.config.cooldown_secs);
if cooled {
map.insert(host.to_string(), Phase::HalfOpen { successes: 0 });
true } else {
false
}
}
}
}
pub(crate) fn on_failure_at(&self, host: &str, now: Instant) {
let mut map = self.states.lock().unwrap_or_else(|p| p.into_inner());
match map.get_mut(host) {
None => {
let phase = if self.config.failure_threshold <= 1 {
Phase::Open { opened_at: now }
} else {
Phase::Closed { failures: 1 }
};
map.insert(host.to_string(), phase);
}
Some(Phase::Closed { failures }) => {
*failures += 1;
if *failures >= self.config.failure_threshold {
map.insert(host.to_string(), Phase::Open { opened_at: now });
}
}
Some(Phase::HalfOpen { .. }) | Some(Phase::Open { .. }) => {
map.insert(host.to_string(), Phase::Open { opened_at: now });
}
}
}
}