yang_base/http/
circuit_breaker.rs1use crate::error::BaseError;
20use std::collections::HashMap;
21use std::sync::{Arc, Mutex};
22use std::time::{Duration, Instant};
23
24#[derive(Debug, Clone)]
27#[non_exhaustive]
28pub struct CircuitBreakerConfig {
29 pub failure_threshold: u32,
31 pub cooldown_secs: u64,
33 pub success_threshold: u32,
35}
36
37impl Default for CircuitBreakerConfig {
38 fn default() -> Self {
39 Self {
40 failure_threshold: 5,
41 cooldown_secs: 30,
42 success_threshold: 1,
43 }
44 }
45}
46
47impl CircuitBreakerConfig {
48 pub fn validate(&self) -> Result<(), BaseError> {
52 if self.failure_threshold == 0 {
53 return Err(BaseError::ParamInvalid(
54 "http.circuit_breaker.failure_threshold".to_string(),
55 "熔断器失败阈值必须大于 0".to_string(),
56 ));
57 }
58 if self.cooldown_secs == 0 {
59 return Err(BaseError::ParamInvalid(
60 "http.circuit_breaker.cooldown_secs".to_string(),
61 "熔断器冷却时间必须大于 0 秒".to_string(),
62 ));
63 }
64 if self.success_threshold == 0 {
65 return Err(BaseError::ParamInvalid(
66 "http.circuit_breaker.success_threshold".to_string(),
67 "熔断器恢复成功阈值必须大于 0".to_string(),
68 ));
69 }
70
71 Ok(())
72 }
73}
74
75#[cfg(test)]
76mod config_tests {
77 use super::*;
78 use crate::error::BaseError;
79
80 #[test]
81 fn test_circuit_breaker_config_validate_rejects_zero_values() {
82 let invalid_configs = [
83 (
84 "http.circuit_breaker.failure_threshold",
85 CircuitBreakerConfig {
86 failure_threshold: 0,
87 ..CircuitBreakerConfig::default()
88 },
89 ),
90 (
91 "http.circuit_breaker.cooldown_secs",
92 CircuitBreakerConfig {
93 cooldown_secs: 0,
94 ..CircuitBreakerConfig::default()
95 },
96 ),
97 (
98 "http.circuit_breaker.success_threshold",
99 CircuitBreakerConfig {
100 success_threshold: 0,
101 ..CircuitBreakerConfig::default()
102 },
103 ),
104 ];
105
106 for (expected_field, config) in invalid_configs {
107 let err = config.validate().expect_err("熔断器零值配置应被拒绝");
108
109 assert!(matches!(
110 err,
111 BaseError::ParamInvalid(field, _) if field == expected_field
112 ));
113 }
114 }
115
116 #[test]
117 fn test_circuit_breaker_new_rejects_invalid_config() {
118 let err = CircuitBreaker::new(CircuitBreakerConfig {
119 failure_threshold: 0,
120 ..CircuitBreakerConfig::default()
121 })
122 .expect_err("公开构造器应拒绝非法熔断器配置");
123
124 assert!(matches!(
125 err,
126 BaseError::ParamInvalid(field, _) if field == "http.circuit_breaker.failure_threshold"
127 ));
128 }
129}
130
131#[derive(Debug)]
134enum Phase {
135 Closed { failures: u32 },
137 Open { opened_at: Instant },
139 HalfOpen { successes: u32 },
141}
142
143#[derive(Debug, Clone)]
145pub struct CircuitBreaker {
146 config: CircuitBreakerConfig,
147 states: Arc<Mutex<HashMap<String, Phase>>>,
149}
150
151impl CircuitBreaker {
152 pub fn new(config: CircuitBreakerConfig) -> Result<Self, BaseError> {
154 config.validate()?;
155
156 Ok(Self {
157 config,
158 states: Arc::new(Mutex::new(HashMap::new())),
159 })
160 }
161
162 pub fn allow(&self, host: &str) -> bool {
165 self.allow_at(host, Instant::now())
166 }
167
168 pub fn on_success(&self, host: &str) {
170 let mut map = self.states.lock().unwrap_or_else(|p| p.into_inner());
171 match map.get_mut(host) {
172 Some(Phase::Closed { .. }) => {
174 map.remove(host);
175 }
176 Some(Phase::HalfOpen { successes }) => {
177 *successes += 1;
178 if *successes >= self.config.success_threshold {
179 map.remove(host); }
181 }
182 _ => {}
184 }
185 }
186
187 pub fn on_failure(&self, host: &str) {
189 self.on_failure_at(host, Instant::now());
190 }
191
192 pub(crate) fn allow_at(&self, host: &str, now: Instant) -> bool {
194 let mut map = self.states.lock().unwrap_or_else(|p| p.into_inner());
195 match map.get(host) {
196 None | Some(Phase::Closed { .. }) | Some(Phase::HalfOpen { .. }) => true,
197 Some(Phase::Open { opened_at }) => {
198 let cooled = now.duration_since(*opened_at)
199 >= Duration::from_secs(self.config.cooldown_secs);
200 if cooled {
201 map.insert(host.to_string(), Phase::HalfOpen { successes: 0 });
202 true } else {
204 false
205 }
206 }
207 }
208 }
209
210 pub(crate) fn on_failure_at(&self, host: &str, now: Instant) {
212 let mut map = self.states.lock().unwrap_or_else(|p| p.into_inner());
213 match map.get_mut(host) {
214 None => {
215 let phase = if self.config.failure_threshold <= 1 {
216 Phase::Open { opened_at: now }
217 } else {
218 Phase::Closed { failures: 1 }
219 };
220 map.insert(host.to_string(), phase);
221 }
222 Some(Phase::Closed { failures }) => {
223 *failures += 1;
224 if *failures >= self.config.failure_threshold {
225 map.insert(host.to_string(), Phase::Open { opened_at: now });
226 }
227 }
228 Some(Phase::HalfOpen { .. }) | Some(Phase::Open { .. }) => {
230 map.insert(host.to_string(), Phase::Open { opened_at: now });
231 }
232 }
233 }
234}