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,
pub max_tracked_hosts: usize,
pub host_idle_ttl_secs: u64,
}
impl Default for CircuitBreakerConfig {
fn default() -> Self {
Self {
failure_threshold: 5,
cooldown_secs: 30,
success_threshold: 1,
max_tracked_hosts: 1024,
host_idle_ttl_secs: 600,
}
}
}
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(),
));
}
if self.max_tracked_hosts == 0 {
return Err(BaseError::ParamInvalid(
"http.circuit_breaker.max_tracked_hosts".to_string(),
"熔断器 host 上限必须大于 0".to_string(),
));
}
if self.host_idle_ttl_secs < self.cooldown_secs {
return Err(BaseError::ParamInvalid(
"http.circuit_breaker.host_idle_ttl_secs".to_string(),
"host 空闲淘汰时间不能小于冷却时间,否则会提前遗忘已打开的熔断".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()
},
),
(
"http.circuit_breaker.max_tracked_hosts",
CircuitBreakerConfig {
max_tracked_hosts: 0,
..CircuitBreakerConfig::default()
},
),
(
"http.circuit_breaker.host_idle_ttl_secs",
CircuitBreakerConfig {
host_idle_ttl_secs: 10, ..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, (Instant, 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 now = Instant::now();
let mut map = self.states.lock().unwrap_or_else(|p| p.into_inner());
match map.get(host) {
Some((_, Phase::Closed { .. })) => {
map.remove(host);
}
Some((_, Phase::HalfOpen { successes })) => {
let next = successes.saturating_add(1);
if next >= self.config.success_threshold {
map.remove(host); } else {
map.insert(host.to_string(), (now, Phase::HalfOpen { successes: next }));
}
}
_ => {}
}
}
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(), (now, 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());
if !map.contains_key(host) {
self.make_room(&mut map, now);
}
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(), (now, phase));
}
Some((last_seen, Phase::Closed { failures })) => {
*last_seen = now;
*failures = failures.saturating_add(1);
if *failures >= self.config.failure_threshold {
map.insert(host.to_string(), (now, Phase::Open { opened_at: now }));
}
}
Some((last_seen, Phase::HalfOpen { .. })) | Some((last_seen, Phase::Open { .. })) => {
*last_seen = now;
map.insert(host.to_string(), (now, Phase::Open { opened_at: now }));
}
}
}
fn make_room(&self, map: &mut HashMap<String, (Instant, Phase)>, now: Instant) {
let ttl = Duration::from_secs(self.config.host_idle_ttl_secs);
map.retain(|_, (last_seen, _)| now.duration_since(*last_seen) < ttl);
while map.len() >= self.config.max_tracked_hosts {
let victim = map
.iter()
.min_by_key(|(_, (last_seen, phase))| {
(matches!(phase, Phase::Open { .. }), *last_seen)
})
.map(|(host, _)| host.clone());
match victim {
Some(host) => {
map.remove(&host);
}
None => break,
}
}
}
#[cfg(test)]
pub(crate) fn tracked_host_count(&self) -> usize {
self.states.lock().unwrap_or_else(|p| p.into_inner()).len()
}
}