1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Circuit Breaker pattern for fault tolerance
//!
//! Prevents cascading failures by detecting unhealthy services and temporarily
//! blocking requests until the service recovers. Useful for external backends
//! like S3, IPFS gateways, and distributed storage nodes.
//!
//! ## States
//! - **Closed**: Normal operation, requests pass through
//! - **Open**: Service is unhealthy, requests fail fast
//! - **Half-Open**: Testing if service has recovered
//!
//! ## Example
//! ```no_run
//! use ipfrs_storage::CircuitBreaker;
//! use std::time::Duration;
//!
//! async fn call_external_service() -> Result<String, std::io::Error> {
//! // Your external service call
//! Ok("success".to_string())
//! }
//!
//! #[tokio::main]
//! async fn main() {
//! let cb = CircuitBreaker::new(5, Duration::from_secs(30));
//!
//! match cb.call(call_external_service()).await {
//! Ok(result) => println!("Success: {}", result),
//! Err(e) => eprintln!("Failed: {}", e),
//! }
//! }
//! ```
use anyhow::{anyhow, Result};
use parking_lot::RwLock;
use std::future::Future;
use std::sync::Arc;
use std::time::{Duration, Instant};
/// Circuit breaker state
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CircuitState {
/// Normal operation - requests pass through
Closed,
/// Service is unhealthy - fail fast
Open,
/// Testing recovery - allow limited requests
HalfOpen,
}
/// Circuit breaker statistics
#[derive(Debug, Clone, Default)]
pub struct CircuitStats {
/// Total requests attempted
pub total_requests: u64,
/// Successful requests
pub successful_requests: u64,
/// Failed requests
pub failed_requests: u64,
/// Requests rejected by circuit breaker
pub rejected_requests: u64,
/// Number of times circuit opened
pub circuit_opened_count: u64,
/// Current consecutive failures
pub consecutive_failures: u32,
}
/// Internal state of the circuit breaker
#[derive(Debug)]
struct CircuitBreakerState {
/// Current state
state: CircuitState,
/// Number of consecutive failures
consecutive_failures: u32,
/// When the circuit was opened
opened_at: Option<Instant>,
/// Statistics
stats: CircuitStats,
}
/// Circuit Breaker for fault-tolerant external service calls
///
/// Automatically opens when failure threshold is exceeded, preventing
/// cascading failures. After a timeout, enters half-open state to test
/// if the service has recovered.
#[derive(Debug, Clone)]
pub struct CircuitBreaker {
/// Failure threshold before opening circuit
failure_threshold: u32,
/// Timeout before attempting recovery
timeout: Duration,
/// Half-open success threshold before closing
#[allow(dead_code)]
half_open_threshold: u32,
/// Internal state
state: Arc<RwLock<CircuitBreakerState>>,
}
impl CircuitBreaker {
/// Create a new circuit breaker
///
/// # Arguments
/// * `failure_threshold` - Consecutive failures before opening
/// * `timeout` - Duration to wait before trying half-open
pub fn new(failure_threshold: u32, timeout: Duration) -> Self {
Self::with_half_open_threshold(failure_threshold, timeout, 1)
}
/// Create a circuit breaker with custom half-open threshold
///
/// # Arguments
/// * `failure_threshold` - Consecutive failures before opening
/// * `timeout` - Duration to wait before trying half-open
/// * `half_open_threshold` - Successes needed in half-open to close
pub fn with_half_open_threshold(
failure_threshold: u32,
timeout: Duration,
half_open_threshold: u32,
) -> Self {
Self {
failure_threshold,
timeout,
half_open_threshold,
state: Arc::new(RwLock::new(CircuitBreakerState {
state: CircuitState::Closed,
consecutive_failures: 0,
opened_at: None,
stats: CircuitStats::default(),
})),
}
}
/// Execute a function through the circuit breaker
///
/// # Arguments
/// * `f` - Future to execute
///
/// # Returns
/// Result of the function or circuit breaker error
pub async fn call<F, T, E>(&self, f: F) -> Result<T>
where
F: Future<Output = Result<T, E>>,
E: std::error::Error + Send + Sync + 'static,
{
// Check if we can proceed
if !self.can_proceed() {
let mut state = self.state.write();
state.stats.rejected_requests += 1;
return Err(anyhow!("Circuit breaker is OPEN"));
}
// Increment total requests
self.state.write().stats.total_requests += 1;
// Execute the function
match f.await {
Ok(result) => {
self.on_success();
Ok(result)
}
Err(e) => {
self.on_failure();
Err(anyhow!("Circuit breaker call failed: {e}"))
}
}
}
/// Check if a request can proceed
fn can_proceed(&self) -> bool {
let mut state = self.state.write();
match state.state {
CircuitState::Closed => true,
CircuitState::Open => {
// Check if timeout has elapsed
if let Some(opened_at) = state.opened_at {
if opened_at.elapsed() >= self.timeout {
// Transition to half-open
state.state = CircuitState::HalfOpen;
state.consecutive_failures = 0;
true
} else {
false
}
} else {
false
}
}
CircuitState::HalfOpen => true,
}
}
/// Handle successful request
fn on_success(&self) {
let mut state = self.state.write();
state.stats.successful_requests += 1;
match state.state {
CircuitState::Closed => {
state.consecutive_failures = 0;
}
CircuitState::HalfOpen => {
// Check if we've had enough successes to close
if state.consecutive_failures == 0 {
// First success in half-open, need more
state.consecutive_failures = 0;
}
// For simplicity, close on first success
// In production, you might want to require multiple successes
state.state = CircuitState::Closed;
state.consecutive_failures = 0;
state.opened_at = None;
}
CircuitState::Open => {
// Shouldn't happen, but reset if it does
state.consecutive_failures = 0;
}
}
}
/// Handle failed request
fn on_failure(&self) {
let mut state = self.state.write();
state.stats.failed_requests += 1;
state.consecutive_failures += 1;
match state.state {
CircuitState::Closed => {
if state.consecutive_failures >= self.failure_threshold {
// Open the circuit
state.state = CircuitState::Open;
state.opened_at = Some(Instant::now());
state.stats.circuit_opened_count += 1;
}
}
CircuitState::HalfOpen => {
// Failure in half-open means we're still unhealthy
state.state = CircuitState::Open;
state.opened_at = Some(Instant::now());
state.stats.circuit_opened_count += 1;
}
CircuitState::Open => {
// Already open, just count the failure
}
}
state.stats.consecutive_failures = state.consecutive_failures;
}
/// Get current circuit state
pub fn state(&self) -> CircuitState {
self.state.read().state
}
/// Get circuit breaker statistics
pub fn stats(&self) -> CircuitStats {
self.state.read().stats.clone()
}
/// Manually reset the circuit breaker to closed state
pub fn reset(&self) {
let mut state = self.state.write();
state.state = CircuitState::Closed;
state.consecutive_failures = 0;
state.opened_at = None;
state.stats.consecutive_failures = 0;
}
/// Check if circuit is closed (healthy)
pub fn is_closed(&self) -> bool {
self.state() == CircuitState::Closed
}
/// Check if circuit is open (unhealthy)
pub fn is_open(&self) -> bool {
self.state() == CircuitState::Open
}
/// Check if circuit is half-open (testing recovery)
pub fn is_half_open(&self) -> bool {
self.state() == CircuitState::HalfOpen
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::time::sleep;
async fn succeeding_operation() -> Result<&'static str, std::io::Error> {
Ok("success")
}
async fn failing_operation() -> Result<&'static str, std::io::Error> {
Err(std::io::Error::new(std::io::ErrorKind::Other, "failure"))
}
#[tokio::test]
async fn test_circuit_breaker_closed_state() {
let cb = CircuitBreaker::new(3, Duration::from_secs(1));
assert!(cb.is_closed());
let result = cb.call(succeeding_operation()).await;
assert!(result.is_ok());
assert!(cb.is_closed());
}
#[tokio::test]
async fn test_circuit_breaker_opens_on_failures() {
let cb = CircuitBreaker::new(3, Duration::from_secs(1));
// Trigger 3 failures to open circuit
for _ in 0..3 {
let _ = cb.call(failing_operation()).await;
}
assert!(cb.is_open());
let stats = cb.stats();
assert_eq!(stats.failed_requests, 3);
assert_eq!(stats.circuit_opened_count, 1);
}
#[tokio::test]
async fn test_circuit_breaker_rejects_when_open() {
let cb = CircuitBreaker::new(2, Duration::from_secs(1));
// Open the circuit
for _ in 0..2 {
let _ = cb.call(failing_operation()).await;
}
assert!(cb.is_open());
// Next request should be rejected
let result = cb.call(succeeding_operation()).await;
assert!(result.is_err());
let stats = cb.stats();
assert_eq!(stats.rejected_requests, 1);
}
#[tokio::test]
async fn test_circuit_breaker_half_open() {
let cb = CircuitBreaker::new(2, Duration::from_millis(100));
// Open the circuit
for _ in 0..2 {
let _ = cb.call(failing_operation()).await;
}
assert!(cb.is_open());
// Wait for timeout
sleep(Duration::from_millis(150)).await;
// Next request should transition to half-open
let result = cb.call(succeeding_operation()).await;
assert!(result.is_ok());
// Should be closed now after success
assert!(cb.is_closed());
}
#[tokio::test]
async fn test_circuit_breaker_stats() {
let cb = CircuitBreaker::new(5, Duration::from_secs(1));
// Make some successful calls
for _ in 0..3 {
let _ = cb.call(succeeding_operation()).await;
}
// Make some failed calls
for _ in 0..2 {
let _ = cb.call(failing_operation()).await;
}
let stats = cb.stats();
assert_eq!(stats.total_requests, 5);
assert_eq!(stats.successful_requests, 3);
assert_eq!(stats.failed_requests, 2);
assert_eq!(stats.consecutive_failures, 2);
}
#[tokio::test]
async fn test_circuit_breaker_reset() {
let cb = CircuitBreaker::new(2, Duration::from_secs(1));
// Open the circuit
for _ in 0..2 {
let _ = cb.call(failing_operation()).await;
}
assert!(cb.is_open());
// Manual reset
cb.reset();
assert!(cb.is_closed());
assert_eq!(cb.stats().consecutive_failures, 0);
}
}