1use crate::error::BaseError;
22use std::collections::HashMap;
23use std::sync::{Arc, Mutex};
24use std::time::{Duration, Instant};
25
26#[derive(Debug, Clone)]
29#[non_exhaustive]
30pub struct CircuitBreakerConfig {
31 pub failure_threshold: u32,
33 pub cooldown_secs: u64,
35 pub success_threshold: u32,
37 pub max_tracked_hosts: usize,
39 pub host_idle_ttl_secs: u64,
42}
43
44impl Default for CircuitBreakerConfig {
45 fn default() -> Self {
46 Self {
47 failure_threshold: 5,
48 cooldown_secs: 30,
49 success_threshold: 1,
50 max_tracked_hosts: 1024,
51 host_idle_ttl_secs: 600,
52 }
53 }
54}
55
56impl CircuitBreakerConfig {
57 pub fn validate(&self) -> Result<(), BaseError> {
61 if self.failure_threshold == 0 {
62 return Err(BaseError::ParamInvalid(
63 "http.circuit_breaker.failure_threshold".to_string(),
64 "熔断器失败阈值必须大于 0".to_string(),
65 ));
66 }
67 if self.cooldown_secs == 0 {
68 return Err(BaseError::ParamInvalid(
69 "http.circuit_breaker.cooldown_secs".to_string(),
70 "熔断器冷却时间必须大于 0 秒".to_string(),
71 ));
72 }
73 if self.success_threshold == 0 {
74 return Err(BaseError::ParamInvalid(
75 "http.circuit_breaker.success_threshold".to_string(),
76 "熔断器恢复成功阈值必须大于 0".to_string(),
77 ));
78 }
79 if self.max_tracked_hosts == 0 {
80 return Err(BaseError::ParamInvalid(
81 "http.circuit_breaker.max_tracked_hosts".to_string(),
82 "熔断器 host 上限必须大于 0".to_string(),
83 ));
84 }
85 if self.host_idle_ttl_secs < self.cooldown_secs {
86 return Err(BaseError::ParamInvalid(
87 "http.circuit_breaker.host_idle_ttl_secs".to_string(),
88 "host 空闲淘汰时间不能小于冷却时间,否则会提前遗忘已打开的熔断".to_string(),
89 ));
90 }
91
92 Ok(())
93 }
94}
95
96#[cfg(test)]
97mod config_tests {
98 use super::*;
99 use crate::error::BaseError;
100
101 #[test]
102 fn test_circuit_breaker_config_validate_rejects_zero_values() {
103 let invalid_configs = [
104 (
105 "http.circuit_breaker.failure_threshold",
106 CircuitBreakerConfig {
107 failure_threshold: 0,
108 ..CircuitBreakerConfig::default()
109 },
110 ),
111 (
112 "http.circuit_breaker.cooldown_secs",
113 CircuitBreakerConfig {
114 cooldown_secs: 0,
115 ..CircuitBreakerConfig::default()
116 },
117 ),
118 (
119 "http.circuit_breaker.success_threshold",
120 CircuitBreakerConfig {
121 success_threshold: 0,
122 ..CircuitBreakerConfig::default()
123 },
124 ),
125 (
126 "http.circuit_breaker.max_tracked_hosts",
127 CircuitBreakerConfig {
128 max_tracked_hosts: 0,
129 ..CircuitBreakerConfig::default()
130 },
131 ),
132 (
133 "http.circuit_breaker.host_idle_ttl_secs",
134 CircuitBreakerConfig {
135 host_idle_ttl_secs: 10, ..CircuitBreakerConfig::default()
137 },
138 ),
139 ];
140
141 for (expected_field, config) in invalid_configs {
142 let err = config.validate().expect_err("熔断器零值配置应被拒绝");
143
144 assert!(matches!(
145 err,
146 BaseError::ParamInvalid(field, _) if field == expected_field
147 ));
148 }
149 }
150
151 #[test]
152 fn test_circuit_breaker_new_rejects_invalid_config() {
153 let err = CircuitBreaker::new(CircuitBreakerConfig {
154 failure_threshold: 0,
155 ..CircuitBreakerConfig::default()
156 })
157 .expect_err("公开构造器应拒绝非法熔断器配置");
158
159 assert!(matches!(
160 err,
161 BaseError::ParamInvalid(field, _) if field == "http.circuit_breaker.failure_threshold"
162 ));
163 }
164}
165
166#[derive(Debug)]
170enum Phase {
171 Closed { failures: u32 },
173 Open { opened_at: Instant },
175 HalfOpen { successes: u32 },
177}
178
179#[derive(Debug, Clone)]
181pub struct CircuitBreaker {
182 config: CircuitBreakerConfig,
183 states: Arc<Mutex<HashMap<String, (Instant, Phase)>>>,
186}
187
188impl CircuitBreaker {
189 pub fn new(config: CircuitBreakerConfig) -> Result<Self, BaseError> {
191 config.validate()?;
192
193 Ok(Self {
194 config,
195 states: Arc::new(Mutex::new(HashMap::new())),
196 })
197 }
198
199 pub fn allow(&self, host: &str) -> bool {
202 self.allow_at(host, Instant::now())
203 }
204
205 pub fn on_success(&self, host: &str) {
207 let now = Instant::now();
208 let mut map = self.states.lock().unwrap_or_else(|p| p.into_inner());
209 match map.get(host) {
210 Some((_, Phase::Closed { .. })) => {
212 map.remove(host);
213 }
214 Some((_, Phase::HalfOpen { successes })) => {
215 let next = successes.saturating_add(1);
216 if next >= self.config.success_threshold {
217 map.remove(host); } else {
219 map.insert(host.to_string(), (now, Phase::HalfOpen { successes: next }));
220 }
221 }
222 _ => {}
224 }
225 }
226
227 pub fn on_failure(&self, host: &str) {
229 self.on_failure_at(host, Instant::now());
230 }
231
232 pub(crate) fn allow_at(&self, host: &str, now: Instant) -> bool {
234 let mut map = self.states.lock().unwrap_or_else(|p| p.into_inner());
235 match map.get(host) {
236 None | Some((_, Phase::Closed { .. })) | Some((_, Phase::HalfOpen { .. })) => true,
237 Some((_, Phase::Open { opened_at })) => {
238 let cooled = now.duration_since(*opened_at)
239 >= Duration::from_secs(self.config.cooldown_secs);
240 if cooled {
241 map.insert(host.to_string(), (now, Phase::HalfOpen { successes: 0 }));
242 true } else {
244 false
245 }
246 }
247 }
248 }
249
250 pub(crate) fn on_failure_at(&self, host: &str, now: Instant) {
252 let mut map = self.states.lock().unwrap_or_else(|p| p.into_inner());
253
254 if !map.contains_key(host) {
256 self.make_room(&mut map, now);
257 }
258
259 match map.get_mut(host) {
260 None => {
261 let phase = if self.config.failure_threshold <= 1 {
262 Phase::Open { opened_at: now }
263 } else {
264 Phase::Closed { failures: 1 }
265 };
266 map.insert(host.to_string(), (now, phase));
267 }
268 Some((last_seen, Phase::Closed { failures })) => {
269 *last_seen = now;
270 *failures = failures.saturating_add(1);
271 if *failures >= self.config.failure_threshold {
272 map.insert(host.to_string(), (now, Phase::Open { opened_at: now }));
273 }
274 }
275 Some((last_seen, Phase::HalfOpen { .. })) | Some((last_seen, Phase::Open { .. })) => {
277 *last_seen = now;
278 map.insert(host.to_string(), (now, Phase::Open { opened_at: now }));
279 }
280 }
281 }
282
283 fn make_room(&self, map: &mut HashMap<String, (Instant, Phase)>, now: Instant) {
290 let ttl = Duration::from_secs(self.config.host_idle_ttl_secs);
291 map.retain(|_, (last_seen, _)| now.duration_since(*last_seen) < ttl);
292
293 while map.len() >= self.config.max_tracked_hosts {
294 let victim = map
295 .iter()
296 .min_by_key(|(_, (last_seen, phase))| {
297 (matches!(phase, Phase::Open { .. }), *last_seen)
298 })
299 .map(|(host, _)| host.clone());
300 match victim {
301 Some(host) => {
302 map.remove(&host);
303 }
304 None => break,
305 }
306 }
307 }
308
309 #[cfg(test)]
310 pub(crate) fn tracked_host_count(&self) -> usize {
311 self.states.lock().unwrap_or_else(|p| p.into_inner()).len()
312 }
313}