azoth 0.2.5

High-performance embedded database for state management and event sourcing with ACID guarantees
Documentation
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! Circuit Breaker Pattern
//!
//! Prevents cascading failures during errors by automatically stopping
//! request processing when failure rate exceeds thresholds.
//!
//! # Example
//!
//! ```no_run
//! use azoth::prelude::*;
//! use azoth::circuit_breaker::{CircuitBreaker, CircuitBreakerConfig};
//! use std::time::Duration;
//! use std::sync::Arc;
//!
//! # async fn example() -> Result<()> {
//! let config = CircuitBreakerConfig {
//!     failure_threshold: 5,
//!     window: Duration::from_secs(60),
//!     timeout: Duration::from_secs(30),
//!     half_open_requests: 3,
//! };
//!
//! let breaker = Arc::new(CircuitBreaker::new("projection-processor".to_string(), config));
//!
//! // Use the circuit breaker to protect operations
//! match breaker.call(|| {
//!     // Your operation that might fail
//!     Ok(())
//! }).await {
//!     Ok(result) => println!("Success: {:?}", result),
//!     Err(e) => println!("Failed or circuit open: {}", e),
//! }
//! # Ok(())
//! # }
//! ```

use crate::{AzothError, Result};
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;

/// Circuit breaker configuration
#[derive(Clone, Debug)]
pub struct CircuitBreakerConfig {
    /// Failure threshold before opening circuit
    pub failure_threshold: usize,

    /// Time window for counting failures
    pub window: Duration,

    /// How long to keep circuit open before trying half-open
    pub timeout: Duration,

    /// Number of test requests in half-open state before closing
    pub half_open_requests: usize,
}

impl Default for CircuitBreakerConfig {
    fn default() -> Self {
        Self {
            failure_threshold: 5,
            window: Duration::from_secs(60),
            timeout: Duration::from_secs(30),
            half_open_requests: 3,
        }
    }
}

/// Circuit breaker state
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BreakerState {
    /// Circuit is closed, requests are allowed
    Closed,
    /// Circuit is open, requests are blocked
    Open,
    /// Circuit is half-open, testing if system recovered
    HalfOpen,
}

/// Internal state for circuit breaker
struct BreakerInternalState {
    state: BreakerState,
    failures: VecDeque<Instant>,
    opened_at: Option<Instant>,
    half_open_successes: usize,
    half_open_failures: usize,
}

impl BreakerInternalState {
    fn new() -> Self {
        Self {
            state: BreakerState::Closed,
            failures: VecDeque::new(),
            opened_at: None,
            half_open_successes: 0,
            half_open_failures: 0,
        }
    }

    fn clean_old_failures(&mut self, window: Duration) {
        let now = Instant::now();
        while let Some(&failure_time) = self.failures.front() {
            if now.duration_since(failure_time) > window {
                self.failures.pop_front();
            } else {
                break;
            }
        }
    }
}

/// Circuit breaker metrics
#[derive(Debug, Default)]
pub struct BreakerMetrics {
    /// Total successful calls
    pub successes: AtomicU64,

    /// Total failed calls
    pub failures: AtomicU64,

    /// Total rejected calls (circuit open)
    pub rejections: AtomicU64,

    /// Number of times circuit opened
    pub opens: AtomicU64,

    /// Number of times circuit closed
    pub closes: AtomicU64,
}

impl BreakerMetrics {
    fn record_success(&self) {
        self.successes.fetch_add(1, Ordering::Relaxed);
    }

    fn record_failure(&self) {
        self.failures.fetch_add(1, Ordering::Relaxed);
    }

    fn record_rejection(&self) {
        self.rejections.fetch_add(1, Ordering::Relaxed);
    }

    fn record_open(&self) {
        self.opens.fetch_add(1, Ordering::Relaxed);
    }

    fn record_close(&self) {
        self.closes.fetch_add(1, Ordering::Relaxed);
    }

    /// Get a snapshot of metrics
    pub fn snapshot(&self) -> BreakerMetricsSnapshot {
        BreakerMetricsSnapshot {
            successes: self.successes.load(Ordering::Relaxed),
            failures: self.failures.load(Ordering::Relaxed),
            rejections: self.rejections.load(Ordering::Relaxed),
            opens: self.opens.load(Ordering::Relaxed),
            closes: self.closes.load(Ordering::Relaxed),
        }
    }
}

/// Snapshot of circuit breaker metrics
#[derive(Debug, Clone)]
pub struct BreakerMetricsSnapshot {
    pub successes: u64,
    pub failures: u64,
    pub rejections: u64,
    pub opens: u64,
    pub closes: u64,
}

impl BreakerMetricsSnapshot {
    /// Get success rate (0.0 - 1.0)
    pub fn success_rate(&self) -> f64 {
        let total = self.successes + self.failures;
        if total == 0 {
            1.0
        } else {
            self.successes as f64 / total as f64
        }
    }

    /// Get failure rate (0.0 - 1.0)
    pub fn failure_rate(&self) -> f64 {
        1.0 - self.success_rate()
    }

    /// Get rejection rate (relative to total attempts)
    pub fn rejection_rate(&self) -> f64 {
        let total = self.successes + self.failures + self.rejections;
        if total == 0 {
            0.0
        } else {
            self.rejections as f64 / total as f64
        }
    }
}

/// Circuit breaker for protecting operations from cascading failures
pub struct CircuitBreaker {
    name: String,
    config: CircuitBreakerConfig,
    state: Arc<Mutex<BreakerInternalState>>,
    metrics: Arc<BreakerMetrics>,
}

impl CircuitBreaker {
    /// Create a new circuit breaker
    pub fn new(name: String, config: CircuitBreakerConfig) -> Self {
        Self {
            name,
            config,
            state: Arc::new(Mutex::new(BreakerInternalState::new())),
            metrics: Arc::new(BreakerMetrics::default()),
        }
    }

    /// Get the breaker name
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the current state
    pub async fn get_state(&self) -> BreakerState {
        let state = self.state.lock().await;
        state.state.clone()
    }

    /// Get metrics
    pub fn metrics(&self) -> &Arc<BreakerMetrics> {
        &self.metrics
    }

    /// Execute a function through the circuit breaker
    pub async fn call<F, T>(&self, f: F) -> Result<T>
    where
        F: FnOnce() -> Result<T>,
    {
        // Check current state and decide whether to allow the call
        let mut state = self.state.lock().await;

        match state.state {
            BreakerState::Closed => {
                // Clean old failures
                state.clean_old_failures(self.config.window);

                // Circuit is closed, allow the call
                drop(state); // Release lock before calling f

                match f() {
                    Ok(result) => {
                        self.on_success().await;
                        Ok(result)
                    }
                    Err(e) => {
                        self.on_failure().await;
                        Err(e)
                    }
                }
            }

            BreakerState::Open => {
                // Check if timeout elapsed
                if let Some(opened_at) = state.opened_at {
                    if opened_at.elapsed() >= self.config.timeout {
                        // Transition to half-open
                        tracing::info!(
                            "Circuit breaker '{}': transitioning to half-open",
                            self.name
                        );
                        state.state = BreakerState::HalfOpen;
                        state.half_open_successes = 0;
                        state.half_open_failures = 0;
                        drop(state);

                        // Try the call in half-open state (inline instead of recursive)
                        match f() {
                            Ok(result) => {
                                self.on_half_open_success().await;
                                Ok(result)
                            }
                            Err(e) => {
                                self.on_half_open_failure().await;
                                Err(e)
                            }
                        }
                    } else {
                        // Circuit still open, reject the call
                        self.metrics.record_rejection();
                        Err(AzothError::CircuitBreakerOpen)
                    }
                } else {
                    // No opened_at timestamp, reject
                    self.metrics.record_rejection();
                    Err(AzothError::CircuitBreakerOpen)
                }
            }

            BreakerState::HalfOpen => {
                // Circuit is half-open, testing recovery
                drop(state);

                match f() {
                    Ok(result) => {
                        self.on_half_open_success().await;
                        Ok(result)
                    }
                    Err(e) => {
                        self.on_half_open_failure().await;
                        Err(e)
                    }
                }
            }
        }
    }

    /// Record a successful operation.
    ///
    /// Use this when the protected operation is async and can't be wrapped
    /// inside [`Self::call`]. For sync operations prefer [`Self::call`] which handles
    /// recording automatically.
    pub async fn record_success(&self) {
        self.on_success_inner().await;
    }

    /// Record a failed operation.
    ///
    /// Use this when the protected operation is async and can't be wrapped
    /// inside [`Self::call`]. For sync operations prefer [`Self::call`] which handles
    /// recording automatically.
    pub async fn record_failure(&self) {
        self.on_failure_inner().await;
    }

    async fn on_success_inner(&self) {
        self.metrics.record_success();
    }

    async fn on_success(&self) {
        self.on_success_inner().await;
    }

    async fn on_failure(&self) {
        self.on_failure_inner().await;
    }

    async fn on_failure_inner(&self) {
        self.metrics.record_failure();

        let mut state = self.state.lock().await;

        // Record failure
        state.failures.push_back(Instant::now());
        state.clean_old_failures(self.config.window);

        // Check if we should open the circuit
        if state.failures.len() >= self.config.failure_threshold {
            tracing::warn!(
                "Circuit breaker '{}': opening circuit ({} failures in {:?})",
                self.name,
                state.failures.len(),
                self.config.window
            );

            state.state = BreakerState::Open;
            state.opened_at = Some(Instant::now());
            self.metrics.record_open();
        }
    }

    async fn on_half_open_success(&self) {
        self.metrics.record_success();

        let mut state = self.state.lock().await;
        state.half_open_successes += 1;

        // Check if we have enough successes to close the circuit
        if state.half_open_successes >= self.config.half_open_requests {
            tracing::info!(
                "Circuit breaker '{}': closing circuit after {} successful requests",
                self.name,
                state.half_open_successes
            );

            state.state = BreakerState::Closed;
            state.failures.clear();
            state.opened_at = None;
            self.metrics.record_close();
        }
    }

    async fn on_half_open_failure(&self) {
        self.metrics.record_failure();

        let mut state = self.state.lock().await;
        state.half_open_failures += 1;

        // Any failure in half-open state reopens the circuit
        tracing::warn!(
            "Circuit breaker '{}': reopening circuit after failure in half-open state",
            self.name
        );

        state.state = BreakerState::Open;
        state.opened_at = Some(Instant::now());
        state.half_open_successes = 0;
        state.half_open_failures = 0;
        self.metrics.record_open();
    }

    /// Manually reset the circuit breaker to closed state
    pub async fn reset(&self) {
        let mut state = self.state.lock().await;
        tracing::info!(
            "Circuit breaker '{}': manually reset to closed state",
            self.name
        );
        state.state = BreakerState::Closed;
        state.failures.clear();
        state.opened_at = None;
        state.half_open_successes = 0;
        state.half_open_failures = 0;
    }

    /// Manually trip (open) the circuit breaker
    pub async fn trip(&self) {
        let mut state = self.state.lock().await;
        tracing::warn!(
            "Circuit breaker '{}': manually tripped to open state",
            self.name
        );
        state.state = BreakerState::Open;
        state.opened_at = Some(Instant::now());
        self.metrics.record_open();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_circuit_breaker_closed() {
        let config = CircuitBreakerConfig {
            failure_threshold: 3,
            window: Duration::from_secs(60),
            timeout: Duration::from_secs(5),
            half_open_requests: 2,
        };

        let breaker = CircuitBreaker::new("test".to_string(), config);

        // Should start closed
        assert_eq!(breaker.get_state().await, BreakerState::Closed);

        // Successful calls should work
        let result = breaker.call(|| Ok::<_, AzothError>(42)).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 42);
    }

    #[tokio::test]
    async fn test_circuit_breaker_opens_on_failures() {
        let config = CircuitBreakerConfig {
            failure_threshold: 3,
            window: Duration::from_secs(60),
            timeout: Duration::from_secs(5),
            half_open_requests: 2,
        };

        let breaker = CircuitBreaker::new("test".to_string(), config);

        // Fail 3 times to open the circuit
        for _ in 0..3 {
            let _ = breaker
                .call(|| Err::<(), _>(AzothError::Projection("test error".to_string())))
                .await;
        }

        // Circuit should now be open
        assert_eq!(breaker.get_state().await, BreakerState::Open);

        // Next call should be rejected
        let result = breaker.call(|| Ok::<_, AzothError>(42)).await;
        assert!(matches!(result, Err(AzothError::CircuitBreakerOpen)));
    }

    #[tokio::test]
    async fn test_circuit_breaker_half_open_recovery() {
        let config = CircuitBreakerConfig {
            failure_threshold: 2,
            window: Duration::from_secs(60),
            timeout: Duration::from_millis(100), // Short timeout for testing
            half_open_requests: 2,
        };

        let breaker = CircuitBreaker::new("test".to_string(), config);

        // Fail to open circuit
        for _ in 0..2 {
            let _ = breaker
                .call(|| Err::<(), _>(AzothError::Projection("test error".to_string())))
                .await;
        }

        assert_eq!(breaker.get_state().await, BreakerState::Open);

        // Wait for timeout
        tokio::time::sleep(Duration::from_millis(150)).await;

        // Next call should transition to half-open
        let _ = breaker.call(|| Ok::<_, AzothError>(1)).await;
        let state = breaker.get_state().await;
        assert!(state == BreakerState::HalfOpen || state == BreakerState::Closed);
    }

    #[tokio::test]
    async fn test_manual_reset() {
        let config = CircuitBreakerConfig::default();
        let breaker = CircuitBreaker::new("test".to_string(), config);

        // Trip the breaker
        breaker.trip().await;
        assert_eq!(breaker.get_state().await, BreakerState::Open);

        // Reset it
        breaker.reset().await;
        assert_eq!(breaker.get_state().await, BreakerState::Closed);
    }

    #[tokio::test]
    async fn test_metrics() {
        let config = CircuitBreakerConfig::default();
        let breaker = CircuitBreaker::new("test".to_string(), config);

        // Record some successes
        for _ in 0..5 {
            let _ = breaker.call(|| Ok::<_, AzothError>(())).await;
        }

        // Record some failures
        for _ in 0..2 {
            let _ = breaker
                .call(|| Err::<(), _>(AzothError::Projection("error".to_string())))
                .await;
        }

        let metrics = breaker.metrics().snapshot();
        assert_eq!(metrics.successes, 5);
        assert_eq!(metrics.failures, 2);
        assert!(metrics.success_rate() > 0.7);
    }
}