use crate::http::{CircuitBreaker, CircuitBreakerConfig};
use std::sync::Arc;
use std::thread;
fn cb(failure_threshold: u32, cooldown_secs: u64, success_threshold: u32) -> CircuitBreaker {
CircuitBreaker::new(CircuitBreakerConfig {
failure_threshold,
cooldown_secs,
success_threshold,
..CircuitBreakerConfig::default()
})
.expect("测试熔断器配置应合法")
}
#[test]
fn concurrent_failures_reach_threshold_without_loss() {
const N: u32 = 64;
let breaker = Arc::new(cb(N, 30, 1));
let host = "api.example.com";
let mut handles = Vec::new();
for _ in 0..N {
let b = Arc::clone(&breaker);
handles.push(thread::spawn(move || {
b.on_failure(host);
}));
}
for h in handles {
h.join().expect("线程不应 panic");
}
assert!(
!breaker.allow(host),
"并发累计 {} 次失败达阈值后熔断应打开(计数未丢失)",
N
);
}
#[test]
fn concurrent_failures_below_threshold_stay_closed() {
const N: u32 = 32;
let breaker = Arc::new(cb(N + 1, 30, 1));
let host = "h";
let mut handles = Vec::new();
for _ in 0..N {
let b = Arc::clone(&breaker);
handles.push(thread::spawn(move || b.on_failure(host)));
}
for h in handles {
h.join().unwrap();
}
assert!(
breaker.allow(host),
"{} 次失败 < 阈值 {},不应熔断(计数未虚增)",
N,
N + 1
);
}
#[test]
fn concurrent_mixed_calls_do_not_deadlock_or_panic() {
let breaker = Arc::new(cb(5, 1, 2));
let hosts = ["a", "b", "c", "d"];
let mut handles = Vec::new();
for t in 0..32 {
let b = Arc::clone(&breaker);
handles.push(thread::spawn(move || {
for i in 0..500 {
let host = hosts[(t + i) % hosts.len()];
match i % 3 {
0 => {
let _ = b.allow(host);
}
1 => b.on_success(host),
_ => b.on_failure(host),
}
}
}));
}
for h in handles {
h.join().expect("混合并发调用不应 panic");
}
let _ = breaker.allow("a");
}
#[test]
fn cloned_handles_share_state_across_threads() {
let breaker = cb(2, 30, 1);
let clone_a = breaker.clone();
let clone_b = breaker.clone();
let host = "shared";
let a = thread::spawn(move || {
clone_a.on_failure(host);
clone_a.on_failure(host);
});
a.join().unwrap();
let b = thread::spawn(move || clone_b.allow(host));
let allowed = b.join().unwrap();
assert!(!allowed, "另一个 clone 句柄应观察到已打开的熔断状态");
}