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//! 失败 host 条目受 `max_tracked_hosts` 与 `host_idle_ttl_secs` 约束,防止状态 map
19//! 随不同 host 数无限增长。
20
21use crate::error::BaseError;
22use std::collections::HashMap;
23use std::sync::{Arc, Mutex};
24use std::time::{Duration, Instant};
25
26/// 熔断器策略配置。默认关闭——只有在 [`HttpClientConfig`](crate::http::HttpClientConfig)
27/// 中显式设置 `circuit_breaker: Some(..)` 才启用。
28#[derive(Debug, Clone)]
29#[non_exhaustive]
30pub struct CircuitBreakerConfig {
31    /// 触发熔断的连续失败次数(Closed 状态下)。
32    pub failure_threshold: u32,
33    /// Open 状态的冷却秒数,冷却后放行一次探测(转 HalfOpen)。
34    pub cooldown_secs: u64,
35    /// HalfOpen 状态下恢复 Closed 所需的连续成功次数。
36    pub success_threshold: u32,
37    /// 状态 map 最多保留的 host 数;超出后按最久未活跃淘汰。
38    pub max_tracked_hosts: usize,
39    /// host 条目空闲多久后可被淘汰(秒)。必须 >= cooldown_secs,
40    /// 否则已打开的熔断可能在冷却期结束前被遗忘(fail-open)。
41    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    /// 验证熔断器策略配置。
58    ///
59    /// 阈值和冷却时间为 0 时会破坏状态机语义,因此在构建客户端前 fail-fast。
60    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, // 小于默认 cooldown_secs 30,应被拒绝
136                    ..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/// 单个 host 的熔断状态。注意:HashMap 中**无 entry** 等价于「Closed 且零失败」,
167/// 因此健康 host 不占用内存;失败 host 条目受 `max_tracked_hosts` 与
168/// `host_idle_ttl_secs` 约束,达到容量上限或空闲超时后被淘汰。
169#[derive(Debug)]
170enum Phase {
171    /// 闭合,附带当前连续失败数(>=1;0 失败时直接从 map 移除)。
172    Closed { failures: u32 },
173    /// 断开,记录进入时刻用于判断冷却是否结束。
174    Open { opened_at: Instant },
175    /// 半开,附带当前连续成功数。
176    HalfOpen { successes: u32 },
177}
178
179/// 按 host 分键的熔断器。`clone()` 共享同一份状态(内部 `Arc`)。
180#[derive(Debug, Clone)]
181pub struct CircuitBreaker {
182    config: CircuitBreakerConfig,
183    /// host → (最后活跃时刻, 当前状态)。无 entry == Closed 且零失败。
184    /// 条目受 `max_tracked_hosts` 与 `host_idle_ttl_secs` 约束,防止无界增长。
185    states: Arc<Mutex<HashMap<String, (Instant, Phase)>>>,
186}
187
188impl CircuitBreaker {
189    /// 用给定策略创建熔断器。
190    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    /// 请求发送前的准入检查。`true` 放行,`false` 表示熔断打开应直接拒绝。
200    /// 冷却结束的 Open 会在此转为 HalfOpen 并放行探测。
201    pub fn allow(&self, host: &str) -> bool {
202        self.allow_at(host, Instant::now())
203    }
204
205    /// 记录一次成功(2xx/3xx/4xx)。HalfOpen 下累计成功,达阈值恢复 Closed。
206    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            // Closed 有失败累计 → 成功即清零(移除 entry 回到健康)。
211            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); // 恢复 Closed
218                } else {
219                    map.insert(host.to_string(), (now, Phase::HalfOpen { successes: next }));
220                }
221            }
222            // None(已健康)或 Open(探测尚未经 allow 放行):无需变更。
223            _ => {}
224        }
225    }
226
227    /// 记录一次失败(传输错误或 5xx)。达阈值/半开失败 → 打开熔断。
228    pub fn on_failure(&self, host: &str) {
229        self.on_failure_at(host, Instant::now());
230    }
231
232    /// `allow` 的可注入时钟版本,供测试模拟冷却。
233    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 // 放行一次探测
243                } else {
244                    false
245                }
246            }
247        }
248    }
249
250    /// `on_failure` 的可注入时钟版本。
251    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        // 新 host 首次失败会新增条目:先回收空间,避免 map 随不同 host 数无限增长。
255        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            // 半开探测失败 → 立即重新打开;已打开 → 刷新冷却起点。
276            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    /// 在插入新 host 条目前回收空间:先淘汰空闲超时的条目,
284    /// 仍达上限时淘汰最久未活跃者(优先淘汰非 Open 条目,尽量不遗忘已打开的熔断)。
285    ///
286    /// 权衡:容量压力下淘汰 `Phase::Open` 条目等于遗忘一次已打开的熔断(fail-open),
287    /// 因此 (a) 用 `host_idle_ttl_secs >= cooldown_secs` 的校验保证正常冷却周期内不会
288    /// 被空闲淘汰,(b) 淘汰顺序优先挑非 Open,只有全部为 Open 时才动 Open。
289    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}