Skip to main content

yang_base/http/
circuit_breaker.rs

1//! HTTP 熔断器(circuit breaker,L-4)。
2//!
3//! 经典三态熔断器,**按目标 host 分键**:一个故障上游被熔断时,不影响发往
4//! 其它健康 host 的请求。状态机:
5//!
6//! - **Closed(闭合)**:正常放行,累计连续失败数;达到 `failure_threshold` → Open。
7//! - **Open(断开)**:直接拒绝(返回 `HttpCircuitBreakerOpen`);冷却 `cooldown_secs`
8//!   秒后转 HalfOpen 放行探测。
9//! - **HalfOpen(半开)**:放行探测请求;累计 `success_threshold` 次成功 → Closed,
10//!   任一失败 → 重新 Open。
11//!
12//! 失败的定义由调用方(`RequestBuilder::send`)决定:传输错误与 5xx 视为失败,
13//! 4xx 视为健康(服务端有能力正常拒绝请求)。
14//!
15//! 状态用 `Arc<Mutex<HashMap>>` 共享,随 [`HttpClient`](crate::http::HttpClient)
16//! 的 `clone()` 复用同一份。锁仅在同步的检查/记录期间短暂持有,绝不跨 `.await`。
17//! HalfOpen 不做并发探测限流——多个并发请求都会被放行探测,适合本场景的轻量需求。
18
19use crate::error::BaseError;
20use std::collections::HashMap;
21use std::sync::{Arc, Mutex};
22use std::time::{Duration, Instant};
23
24/// 熔断器策略配置。默认关闭——只有在 [`HttpClientConfig`](crate::http::HttpClientConfig)
25/// 中显式设置 `circuit_breaker: Some(..)` 才启用。
26#[derive(Debug, Clone)]
27#[non_exhaustive]
28pub struct CircuitBreakerConfig {
29    /// 触发熔断的连续失败次数(Closed 状态下)。
30    pub failure_threshold: u32,
31    /// Open 状态的冷却秒数,冷却后放行一次探测(转 HalfOpen)。
32    pub cooldown_secs: u64,
33    /// HalfOpen 状态下恢复 Closed 所需的连续成功次数。
34    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    /// 验证熔断器策略配置。
49    ///
50    /// 阈值和冷却时间为 0 时会破坏状态机语义,因此在构建客户端前 fail-fast。
51    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/// 单个 host 的熔断状态。注意:HashMap 中**无 entry** 等价于「Closed 且零失败」,
132/// 因此健康 host 不占用内存。
133#[derive(Debug)]
134enum Phase {
135    /// 闭合,附带当前连续失败数(>=1;0 失败时直接从 map 移除)。
136    Closed { failures: u32 },
137    /// 断开,记录进入时刻用于判断冷却是否结束。
138    Open { opened_at: Instant },
139    /// 半开,附带当前连续成功数。
140    HalfOpen { successes: u32 },
141}
142
143/// 按 host 分键的熔断器。`clone()` 共享同一份状态(内部 `Arc`)。
144#[derive(Debug, Clone)]
145pub struct CircuitBreaker {
146    config: CircuitBreakerConfig,
147    /// host → 当前状态。无 entry == Closed 且零失败。
148    states: Arc<Mutex<HashMap<String, Phase>>>,
149}
150
151impl CircuitBreaker {
152    /// 用给定策略创建熔断器。
153    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    /// 请求发送前的准入检查。`true` 放行,`false` 表示熔断打开应直接拒绝。
163    /// 冷却结束的 Open 会在此转为 HalfOpen 并放行探测。
164    pub fn allow(&self, host: &str) -> bool {
165        self.allow_at(host, Instant::now())
166    }
167
168    /// 记录一次成功(2xx/3xx/4xx)。HalfOpen 下累计成功,达阈值恢复 Closed。
169    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            // Closed 有失败累计 → 成功即清零(移除 entry 回到健康)。
173            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); // 恢复 Closed
180                }
181            }
182            // None(已健康)或 Open(探测尚未经 allow 放行):无需变更。
183            _ => {}
184        }
185    }
186
187    /// 记录一次失败(传输错误或 5xx)。达阈值/半开失败 → 打开熔断。
188    pub fn on_failure(&self, host: &str) {
189        self.on_failure_at(host, Instant::now());
190    }
191
192    /// `allow` 的可注入时钟版本,供测试模拟冷却。
193    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 // 放行一次探测
203                } else {
204                    false
205                }
206            }
207        }
208    }
209
210    /// `on_failure` 的可注入时钟版本。
211    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            // 半开探测失败 → 立即重新打开;已打开 → 刷新冷却起点。
229            Some(Phase::HalfOpen { .. }) | Some(Phase::Open { .. }) => {
230                map.insert(host.to_string(), Phase::Open { opened_at: now });
231            }
232        }
233    }
234}