inferadb 0.1.5

Official Rust SDK for InferaDB
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
557
558
559
560
561
562
563
564
565
566
567
568
//! Circuit breaker configuration for preventing cascade failures.
//!
//! Circuit breakers prevent cascade failures by temporarily stopping requests
//! to a failing service. Unlike retry, which handles transient failures,
//! circuit breakers protect against sustained outages.
//!
//! ## States
//!
//! - **Closed**: Normal operation, requests flow through
//! - **Open**: Requests fail immediately (circuit tripped)
//! - **HalfOpen**: Testing if service has recovered
//!
//! ## Example
//!
//! ```rust
//! use inferadb::CircuitBreakerConfig;
//! use std::time::Duration;
//!
//! let config = CircuitBreakerConfig::default()
//!     .failure_threshold(5)           // Open after 5 consecutive failures
//!     .success_threshold(2)           // Close after 2 successes in half-open
//!     .timeout(Duration::from_secs(30));  // Try half-open after 30s
//! ```

use std::time::Duration;

use crate::ErrorKind;

/// Circuit breaker configuration.
///
/// Controls when the circuit breaker opens (stops requests) and closes
/// (resumes requests) based on failure patterns.
///
/// ## Example
///
/// ```rust
/// use inferadb::CircuitBreakerConfig;
/// use std::time::Duration;
///
/// let config = CircuitBreakerConfig::default()
///     .failure_threshold(5)
///     .success_threshold(2)
///     .timeout(Duration::from_secs(30))
///     .failure_rate_threshold(0.5)
///     .minimum_requests(10);
/// ```
#[derive(Debug, Clone)]
pub struct CircuitBreakerConfig {
    /// Number of consecutive failures to open the circuit.
    failure_threshold: u32,

    /// Number of successes in half-open state to close the circuit.
    success_threshold: u32,

    /// Duration to wait before transitioning from open to half-open.
    timeout: Duration,

    /// Alternative: Open circuit when failure rate exceeds this threshold.
    failure_rate_threshold: f64,

    /// Minimum number of requests before failure rate is considered.
    minimum_requests: u32,

    /// Which errors count as failures.
    failure_predicate: FailurePredicate,
}

impl Default for CircuitBreakerConfig {
    fn default() -> Self {
        Self {
            failure_threshold: 5,
            success_threshold: 2,
            timeout: Duration::from_secs(30),
            failure_rate_threshold: 0.5,
            minimum_requests: 10,
            failure_predicate: FailurePredicate::default(),
        }
    }
}

impl CircuitBreakerConfig {
    /// Creates a new circuit breaker config with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the consecutive failure threshold.
    ///
    /// The circuit opens after this many consecutive failures.
    #[must_use]
    pub fn failure_threshold(mut self, threshold: u32) -> Self {
        self.failure_threshold = threshold;
        self
    }

    /// Sets the success threshold for closing the circuit.
    ///
    /// In half-open state, after this many successes, the circuit closes.
    #[must_use]
    pub fn success_threshold(mut self, threshold: u32) -> Self {
        self.success_threshold = threshold;
        self
    }

    /// Sets the timeout before transitioning from open to half-open.
    #[must_use]
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Sets the failure rate threshold.
    ///
    /// The circuit opens when the failure rate exceeds this value (0.0 to 1.0).
    /// Only applies after `minimum_requests` have been made.
    #[must_use]
    pub fn failure_rate_threshold(mut self, threshold: f64) -> Self {
        self.failure_rate_threshold = threshold.clamp(0.0, 1.0);
        self
    }

    /// Sets the minimum requests before failure rate applies.
    ///
    /// The failure rate threshold only kicks in after this many requests.
    #[must_use]
    pub fn minimum_requests(mut self, count: u32) -> Self {
        self.minimum_requests = count;
        self
    }

    /// Customizes which errors count as circuit breaker failures.
    #[must_use]
    pub fn failure_predicate(mut self, predicate: FailurePredicate) -> Self {
        self.failure_predicate = predicate;
        self
    }

    /// Returns the failure threshold.
    pub fn get_failure_threshold(&self) -> u32 {
        self.failure_threshold
    }

    /// Returns the success threshold.
    pub fn get_success_threshold(&self) -> u32 {
        self.success_threshold
    }

    /// Returns the timeout.
    pub fn get_timeout(&self) -> Duration {
        self.timeout
    }

    /// Returns the failure rate threshold.
    pub fn get_failure_rate_threshold(&self) -> f64 {
        self.failure_rate_threshold
    }

    /// Returns the minimum requests.
    pub fn get_minimum_requests(&self) -> u32 {
        self.minimum_requests
    }

    /// Returns the failure predicate.
    pub fn get_failure_predicate(&self) -> &FailurePredicate {
        &self.failure_predicate
    }

    /// Returns whether the given error kind counts as a failure.
    pub fn is_failure(&self, kind: ErrorKind) -> bool {
        self.failure_predicate.is_failure(kind)
    }
}

/// Determines which errors count toward circuit breaker failure threshold.
///
/// ## Example
///
/// ```rust
/// use inferadb::{FailurePredicate, ErrorKind};
///
/// // Only count timeouts and connection failures
/// let predicate = FailurePredicate::only([
///     ErrorKind::Timeout,
///     ErrorKind::Connection,
/// ]);
///
/// // Default plus exclude rate limiting
/// let predicate = FailurePredicate::default()
///     .exclude(ErrorKind::RateLimited);
/// ```
#[derive(Debug, Clone)]
pub struct FailurePredicate {
    /// Count these error kinds as failures.
    include: Vec<ErrorKind>,
    /// Exclude these error kinds from failure count.
    exclude: Vec<ErrorKind>,
}

impl Default for FailurePredicate {
    /// Default: Timeout, Connection, Unavailable, Internal are failures.
    fn default() -> Self {
        Self {
            include: vec![
                ErrorKind::Timeout,
                ErrorKind::Connection,
                ErrorKind::Unavailable,
                ErrorKind::Internal,
            ],
            exclude: vec![],
        }
    }
}

impl FailurePredicate {
    /// Creates a predicate that only counts specific error kinds as failures.
    pub fn only(kinds: impl IntoIterator<Item = ErrorKind>) -> Self {
        Self {
            include: kinds.into_iter().collect(),
            exclude: vec![],
        }
    }

    /// Adds an error kind to exclude from failure count.
    #[must_use]
    pub fn exclude(mut self, kind: ErrorKind) -> Self {
        self.exclude.push(kind);
        self
    }

    /// Adds an error kind to include in failure count.
    #[must_use]
    pub fn include(mut self, kind: ErrorKind) -> Self {
        self.include.push(kind);
        self
    }

    /// Returns whether the given error kind counts as a failure.
    pub fn is_failure(&self, kind: ErrorKind) -> bool {
        self.include.contains(&kind) && !self.exclude.contains(&kind)
    }
}

/// Current state of a circuit breaker.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CircuitState {
    /// Normal operation, requests flow through.
    Closed,
    /// Requests fail immediately (circuit tripped).
    Open,
    /// Testing if service has recovered.
    HalfOpen,
}

impl CircuitState {
    /// Returns `true` if the circuit is closed (normal operation).
    pub fn is_closed(&self) -> bool {
        matches!(self, CircuitState::Closed)
    }

    /// Returns `true` if the circuit is open (blocking requests).
    pub fn is_open(&self) -> bool {
        matches!(self, CircuitState::Open)
    }

    /// Returns `true` if the circuit is half-open (testing recovery).
    pub fn is_half_open(&self) -> bool {
        matches!(self, CircuitState::HalfOpen)
    }
}

impl std::fmt::Display for CircuitState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CircuitState::Closed => write!(f, "closed"),
            CircuitState::Open => write!(f, "open"),
            CircuitState::HalfOpen => write!(f, "half-open"),
        }
    }
}

/// Detailed circuit breaker statistics.
///
/// Use this for monitoring and alerting on circuit breaker state.
#[derive(Debug, Clone)]
pub struct CircuitStats {
    /// Current state of the circuit.
    pub state: CircuitState,
    /// Number of consecutive failures.
    pub failure_count: u32,
    /// Number of consecutive successes (in half-open state).
    pub success_count: u32,
    /// Total requests since last state change.
    pub total_requests: u64,
    /// Failed requests since last state change.
    pub failed_requests: u64,
    /// Time when circuit last transitioned to open.
    pub last_open_time: Option<std::time::Instant>,
    /// Time when circuit last transitioned to closed.
    pub last_close_time: Option<std::time::Instant>,
}

impl CircuitStats {
    /// Creates new stats in the closed state.
    pub fn new() -> Self {
        Self {
            state: CircuitState::Closed,
            failure_count: 0,
            success_count: 0,
            total_requests: 0,
            failed_requests: 0,
            last_open_time: None,
            last_close_time: None,
        }
    }

    /// Returns the current state.
    pub fn current_state(&self) -> CircuitState {
        self.state
    }

    /// Returns the failure count.
    pub fn failure_count(&self) -> u32 {
        self.failure_count
    }

    /// Returns the success count.
    pub fn success_count(&self) -> u32 {
        self.success_count
    }

    /// Returns the current failure rate.
    pub fn failure_rate(&self) -> f64 {
        if self.total_requests == 0 {
            0.0
        } else {
            self.failed_requests as f64 / self.total_requests as f64
        }
    }
}

impl Default for CircuitStats {
    fn default() -> Self {
        Self::new()
    }
}

/// Events emitted by the circuit breaker.
#[derive(Debug, Clone)]
pub enum CircuitEvent {
    /// Circuit transitioned to open state.
    Opened {
        /// Number of failures that triggered the open.
        failure_count: u32,
        /// Description of the last error.
        last_error: String,
    },
    /// Circuit transitioned to half-open state.
    HalfOpened,
    /// Circuit transitioned to closed state.
    Closed {
        /// Number of successes that triggered the close.
        success_count: u32,
    },
}

impl std::fmt::Display for CircuitEvent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CircuitEvent::Opened {
                failure_count,
                last_error,
            } => {
                write!(
                    f,
                    "circuit opened after {} failures: {}",
                    failure_count, last_error
                )
            }
            CircuitEvent::HalfOpened => write!(f, "circuit half-opened (testing recovery)"),
            CircuitEvent::Closed { success_count } => {
                write!(f, "circuit closed after {} successes", success_count)
            }
        }
    }
}

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

    #[test]
    fn test_default_config() {
        let config = CircuitBreakerConfig::default();
        assert_eq!(config.failure_threshold, 5);
        assert_eq!(config.success_threshold, 2);
        assert_eq!(config.timeout, Duration::from_secs(30));
        assert_eq!(config.failure_rate_threshold, 0.5);
        assert_eq!(config.minimum_requests, 10);
    }

    #[test]
    fn test_config_builder() {
        let config = CircuitBreakerConfig::new()
            .failure_threshold(10)
            .success_threshold(3)
            .timeout(Duration::from_secs(60))
            .failure_rate_threshold(0.8)
            .minimum_requests(20);

        assert_eq!(config.get_failure_threshold(), 10);
        assert_eq!(config.get_success_threshold(), 3);
        assert_eq!(config.get_timeout(), Duration::from_secs(60));
        assert_eq!(config.get_failure_rate_threshold(), 0.8);
        assert_eq!(config.get_minimum_requests(), 20);
    }

    #[test]
    fn test_failure_rate_threshold_clamped() {
        let config = CircuitBreakerConfig::new().failure_rate_threshold(1.5);
        assert_eq!(config.get_failure_rate_threshold(), 1.0);

        let config = CircuitBreakerConfig::new().failure_rate_threshold(-0.5);
        assert_eq!(config.get_failure_rate_threshold(), 0.0);
    }

    #[test]
    fn test_default_failure_predicate() {
        let predicate = FailurePredicate::default();
        assert!(predicate.is_failure(ErrorKind::Timeout));
        assert!(predicate.is_failure(ErrorKind::Connection));
        assert!(predicate.is_failure(ErrorKind::Unavailable));
        assert!(predicate.is_failure(ErrorKind::Internal));
        assert!(!predicate.is_failure(ErrorKind::Forbidden));
        assert!(!predicate.is_failure(ErrorKind::NotFound));
    }

    #[test]
    fn test_failure_predicate_only() {
        let predicate = FailurePredicate::only([ErrorKind::Timeout]);
        assert!(predicate.is_failure(ErrorKind::Timeout));
        assert!(!predicate.is_failure(ErrorKind::Connection));
    }

    #[test]
    fn test_failure_predicate_exclude() {
        let predicate = FailurePredicate::default().exclude(ErrorKind::Timeout);
        assert!(!predicate.is_failure(ErrorKind::Timeout));
        assert!(predicate.is_failure(ErrorKind::Connection));
    }

    #[test]
    fn test_circuit_state() {
        assert!(CircuitState::Closed.is_closed());
        assert!(!CircuitState::Closed.is_open());
        assert!(!CircuitState::Closed.is_half_open());

        assert!(!CircuitState::Open.is_closed());
        assert!(CircuitState::Open.is_open());
        assert!(!CircuitState::Open.is_half_open());

        assert!(!CircuitState::HalfOpen.is_closed());
        assert!(!CircuitState::HalfOpen.is_open());
        assert!(CircuitState::HalfOpen.is_half_open());
    }

    #[test]
    fn test_circuit_stats() {
        let mut stats = CircuitStats::new();
        assert_eq!(stats.current_state(), CircuitState::Closed);
        assert_eq!(stats.failure_count(), 0);
        assert_eq!(stats.success_count(), 0);
        assert_eq!(stats.failure_rate(), 0.0);

        stats.total_requests = 10;
        stats.failed_requests = 3;
        assert!((stats.failure_rate() - 0.3).abs() < f64::EPSILON);
    }

    #[test]
    fn test_circuit_event_display() {
        let event = CircuitEvent::Opened {
            failure_count: 5,
            last_error: "connection refused".to_string(),
        };
        let display = event.to_string();
        assert!(display.contains("5 failures"));
        assert!(display.contains("connection refused"));

        let event = CircuitEvent::HalfOpened;
        assert!(event.to_string().contains("half-opened"));

        let event = CircuitEvent::Closed { success_count: 2 };
        assert!(event.to_string().contains("2 successes"));
    }

    #[test]
    fn test_circuit_state_display() {
        assert_eq!(format!("{}", CircuitState::Closed), "closed");
        assert_eq!(format!("{}", CircuitState::Open), "open");
        assert_eq!(format!("{}", CircuitState::HalfOpen), "half-open");
    }

    #[test]
    fn test_circuit_stats_default() {
        let stats = CircuitStats::default();
        assert_eq!(stats.state, CircuitState::Closed);
        assert_eq!(stats.failure_count, 0);
    }

    #[test]
    fn test_failure_predicate_include() {
        let predicate = FailurePredicate::only([ErrorKind::Timeout]).include(ErrorKind::Connection);
        assert!(predicate.is_failure(ErrorKind::Timeout));
        assert!(predicate.is_failure(ErrorKind::Connection));
        assert!(!predicate.is_failure(ErrorKind::NotFound));
    }

    #[test]
    fn test_config_is_failure() {
        let config = CircuitBreakerConfig::default();
        assert!(config.is_failure(ErrorKind::Timeout));
        assert!(!config.is_failure(ErrorKind::NotFound));
    }

    #[test]
    fn test_config_custom_predicate() {
        let predicate = FailurePredicate::only([ErrorKind::NotFound]);
        let config = CircuitBreakerConfig::new().failure_predicate(predicate);
        assert!(config.is_failure(ErrorKind::NotFound));
        assert!(!config.is_failure(ErrorKind::Timeout));
    }

    #[test]
    fn test_config_get_failure_predicate() {
        let config = CircuitBreakerConfig::default();
        let predicate = config.get_failure_predicate();
        assert!(predicate.is_failure(ErrorKind::Timeout));
    }

    #[test]
    fn test_circuit_event_clone() {
        let event = CircuitEvent::Opened {
            failure_count: 5,
            last_error: "error".to_string(),
        };
        let cloned = event.clone();
        match cloned {
            CircuitEvent::Opened { failure_count, .. } => assert_eq!(failure_count, 5),
            _ => panic!("Wrong variant"),
        }
    }

    #[test]
    fn test_circuit_state_copy() {
        let state = CircuitState::Open;
        let copied: CircuitState = state;
        assert_eq!(state, copied);
    }

    #[test]
    fn test_circuit_stats_with_times() {
        let mut stats = CircuitStats::new();
        stats.last_open_time = Some(std::time::Instant::now());
        stats.last_close_time = Some(std::time::Instant::now());
        assert!(stats.last_open_time.is_some());
        assert!(stats.last_close_time.is_some());
    }
}