xybrid-core 0.1.0

Core runtime for hybrid cloud-edge AI inference: model execution, pipeline orchestration, and routing primitives.
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
//! Circuit breaker pattern for preventing cascading failures.
//!
//! The circuit breaker prevents hammering failing endpoints by tracking failures
//! and temporarily blocking requests when a threshold is exceeded.

use std::sync::atomic::{AtomicU32, AtomicU64, AtomicU8, Ordering};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

/// Default circuit breaker configuration values.
const DEFAULT_FAILURE_THRESHOLD: u32 = 3;
const DEFAULT_OPEN_DURATION_MS: u64 = 30000;
const DEFAULT_HALF_OPEN_MAX: u32 = 1;

/// Circuit breaker states.
const STATE_CLOSED: u8 = 0;
const STATE_OPEN: u8 = 1;
const STATE_HALF_OPEN: u8 = 2;

/// Configuration for the circuit breaker.
#[derive(Debug, Clone)]
pub struct CircuitConfig {
    /// Number of consecutive failures before opening the circuit.
    pub failure_threshold: u32,
    /// Duration in milliseconds to keep the circuit open before transitioning to half-open.
    pub open_duration_ms: u64,
    /// Maximum number of test requests allowed in half-open state.
    pub half_open_max: u32,
}

impl Default for CircuitConfig {
    fn default() -> Self {
        Self {
            failure_threshold: DEFAULT_FAILURE_THRESHOLD,
            open_duration_ms: DEFAULT_OPEN_DURATION_MS,
            half_open_max: DEFAULT_HALF_OPEN_MAX,
        }
    }
}

impl CircuitConfig {
    /// Create a strict configuration that opens quickly and stays open longer.
    pub fn strict() -> Self {
        Self {
            failure_threshold: 2,
            open_duration_ms: 60000,
            half_open_max: 1,
        }
    }

    /// Create a lenient configuration that tolerates more failures.
    pub fn lenient() -> Self {
        Self {
            failure_threshold: 5,
            open_duration_ms: 15000,
            half_open_max: 2,
        }
    }
}

/// The current state of the circuit breaker.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CircuitState {
    /// Circuit is closed (normal operation). All requests are allowed.
    Closed,
    /// Circuit is open. Requests are blocked until the timeout expires.
    Open {
        /// When the circuit will transition to half-open.
        until: Instant,
    },
    /// Circuit is half-open. A limited number of test requests are allowed.
    HalfOpen,
}

/// A circuit breaker that tracks failures and blocks requests to failing endpoints.
///
/// # State Machine
///
/// ```text
/// CLOSED (normal) ──[failure threshold]──► OPEN (blocking)
//////                                         [timeout]
/////////                                         HALF-OPEN (testing)
//////                               ┌───────────────┴───────────────┐
///                         [success]                        [failure]
///                               │                               │
///                               ▼                               ▼
///                           CLOSED                            OPEN
/// ```
///
/// # Thread Safety
///
/// The circuit breaker uses atomic operations and is safe to use from multiple threads.
///
/// # Example
///
/// ```rust
/// use xybrid_core::http::{CircuitBreaker, CircuitConfig};
///
/// let circuit = CircuitBreaker::new(CircuitConfig::default());
///
/// // Check if we can make a request
/// if circuit.can_execute() {
///     // Make the request...
///     let success = true; // or false
///
///     if success {
///         circuit.record_success();
///     } else {
///         circuit.record_failure();
///     }
/// } else {
///     // Circuit is open, fail fast
///     println!("Circuit breaker is open, skipping request");
/// }
/// ```
pub struct CircuitBreaker {
    /// Current state: 0=CLOSED, 1=OPEN, 2=HALF_OPEN
    state: AtomicU8,
    /// Number of consecutive failures
    failure_count: AtomicU32,
    /// Unix timestamp (ms) when the circuit was opened
    opened_at_ms: AtomicU64,
    /// Number of requests allowed through in half-open state
    half_open_requests: AtomicU32,
    /// Configuration
    config: CircuitConfig,
}

impl CircuitBreaker {
    /// Create a new circuit breaker with the given configuration.
    pub fn new(config: CircuitConfig) -> Self {
        Self {
            state: AtomicU8::new(STATE_CLOSED),
            failure_count: AtomicU32::new(0),
            opened_at_ms: AtomicU64::new(0),
            half_open_requests: AtomicU32::new(0),
            config,
        }
    }

    /// Create a circuit breaker with default configuration.
    pub fn with_defaults() -> Self {
        Self::new(CircuitConfig::default())
    }

    /// Check if a request can be executed.
    ///
    /// Returns `true` if:
    /// - Circuit is CLOSED (normal operation)
    /// - Circuit is HALF-OPEN and hasn't exceeded max test requests
    /// - Circuit is OPEN but timeout has expired (transitions to HALF-OPEN)
    ///
    /// Returns `false` if:
    /// - Circuit is OPEN and timeout hasn't expired
    /// - Circuit is HALF-OPEN and max test requests exceeded
    pub fn can_execute(&self) -> bool {
        let current_state = self.state.load(Ordering::SeqCst);

        match current_state {
            STATE_CLOSED => true,
            STATE_OPEN => {
                // Check if we should transition to half-open
                let opened_at = self.opened_at_ms.load(Ordering::SeqCst);
                let now_ms = current_time_ms();
                let elapsed_ms = now_ms.saturating_sub(opened_at);

                if elapsed_ms >= self.config.open_duration_ms {
                    // Transition to half-open
                    if self
                        .state
                        .compare_exchange(
                            STATE_OPEN,
                            STATE_HALF_OPEN,
                            Ordering::SeqCst,
                            Ordering::SeqCst,
                        )
                        .is_ok()
                    {
                        self.half_open_requests.store(0, Ordering::SeqCst);
                    }
                    // Allow this request as the first half-open test
                    self.half_open_requests.fetch_add(1, Ordering::SeqCst)
                        < self.config.half_open_max
                } else {
                    false
                }
            }
            STATE_HALF_OPEN => {
                // Allow limited requests in half-open state
                self.half_open_requests.fetch_add(1, Ordering::SeqCst) < self.config.half_open_max
            }
            _ => false,
        }
    }

    /// Record a successful operation.
    ///
    /// If the circuit is HALF-OPEN, transitions to CLOSED.
    /// Resets the failure count.
    pub fn record_success(&self) {
        let current_state = self.state.load(Ordering::SeqCst);

        // Reset failure count on any success
        self.failure_count.store(0, Ordering::SeqCst);

        // If half-open, transition to closed
        if current_state == STATE_HALF_OPEN {
            self.state.store(STATE_CLOSED, Ordering::SeqCst);
        }
    }

    /// Record a failed operation.
    ///
    /// If the circuit is CLOSED and failure threshold is exceeded, transitions to OPEN.
    /// If the circuit is HALF-OPEN, immediately transitions back to OPEN.
    pub fn record_failure(&self) {
        let current_state = self.state.load(Ordering::SeqCst);

        match current_state {
            STATE_CLOSED => {
                let failures = self.failure_count.fetch_add(1, Ordering::SeqCst) + 1;

                if failures >= self.config.failure_threshold {
                    self.open_circuit();
                }
            }
            STATE_HALF_OPEN => {
                // Any failure in half-open state reopens the circuit
                self.open_circuit();
            }
            STATE_OPEN => {
                // Already open, nothing to do
            }
            _ => {}
        }
    }

    /// Record a rate limit response (429).
    ///
    /// This immediately opens the circuit regardless of the current state.
    pub fn record_rate_limited(&self) {
        self.open_circuit();
    }

    /// Record a service unavailable response (503).
    ///
    /// This immediately opens the circuit regardless of the current state.
    pub fn record_service_unavailable(&self) {
        self.open_circuit();
    }

    /// Get the current state of the circuit breaker.
    pub fn state(&self) -> CircuitState {
        let current_state = self.state.load(Ordering::SeqCst);

        match current_state {
            STATE_CLOSED => CircuitState::Closed,
            STATE_OPEN => {
                let opened_at = self.opened_at_ms.load(Ordering::SeqCst);
                let now_ms = current_time_ms();
                let remaining_ms = self
                    .config
                    .open_duration_ms
                    .saturating_sub(now_ms.saturating_sub(opened_at));

                CircuitState::Open {
                    until: Instant::now() + Duration::from_millis(remaining_ms),
                }
            }
            STATE_HALF_OPEN => CircuitState::HalfOpen,
            _ => CircuitState::Closed, // Fallback
        }
    }

    /// Check if the circuit is currently open (blocking requests).
    pub fn is_open(&self) -> bool {
        self.state.load(Ordering::SeqCst) == STATE_OPEN
    }

    /// Check if the circuit is currently closed (normal operation).
    pub fn is_closed(&self) -> bool {
        self.state.load(Ordering::SeqCst) == STATE_CLOSED
    }

    /// Get the current failure count.
    pub fn failure_count(&self) -> u32 {
        self.failure_count.load(Ordering::SeqCst)
    }

    /// Manually reset the circuit breaker to closed state.
    pub fn reset(&self) {
        self.state.store(STATE_CLOSED, Ordering::SeqCst);
        self.failure_count.store(0, Ordering::SeqCst);
        self.half_open_requests.store(0, Ordering::SeqCst);
    }

    /// Open the circuit.
    fn open_circuit(&self) {
        self.state.store(STATE_OPEN, Ordering::SeqCst);
        self.opened_at_ms.store(current_time_ms(), Ordering::SeqCst);
        self.half_open_requests.store(0, Ordering::SeqCst);
    }
}

/// Get the current time in milliseconds since Unix epoch.
fn current_time_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

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

    #[test]
    fn test_default_config() {
        let config = CircuitConfig::default();
        assert_eq!(config.failure_threshold, 3);
        assert_eq!(config.open_duration_ms, 30000);
        assert_eq!(config.half_open_max, 1);
    }

    #[test]
    fn test_initial_state_is_closed() {
        let circuit = CircuitBreaker::with_defaults();
        assert!(circuit.is_closed());
        assert!(!circuit.is_open());
        assert!(circuit.can_execute());
    }

    #[test]
    fn test_opens_after_failure_threshold() {
        let circuit = CircuitBreaker::new(CircuitConfig {
            failure_threshold: 3,
            open_duration_ms: 30000,
            half_open_max: 1,
        });

        // First two failures shouldn't open the circuit
        circuit.record_failure();
        assert!(circuit.is_closed());
        assert_eq!(circuit.failure_count(), 1);

        circuit.record_failure();
        assert!(circuit.is_closed());
        assert_eq!(circuit.failure_count(), 2);

        // Third failure should open it
        circuit.record_failure();
        assert!(circuit.is_open());
        assert!(!circuit.can_execute());
    }

    #[test]
    fn test_success_resets_failure_count() {
        let circuit = CircuitBreaker::new(CircuitConfig {
            failure_threshold: 3,
            open_duration_ms: 30000,
            half_open_max: 1,
        });

        circuit.record_failure();
        circuit.record_failure();
        assert_eq!(circuit.failure_count(), 2);

        circuit.record_success();
        assert_eq!(circuit.failure_count(), 0);
        assert!(circuit.is_closed());
    }

    #[test]
    fn test_rate_limited_immediately_opens() {
        let circuit = CircuitBreaker::with_defaults();
        assert!(circuit.is_closed());

        circuit.record_rate_limited();
        assert!(circuit.is_open());
    }

    #[test]
    fn test_service_unavailable_immediately_opens() {
        let circuit = CircuitBreaker::with_defaults();
        assert!(circuit.is_closed());

        circuit.record_service_unavailable();
        assert!(circuit.is_open());
    }

    #[test]
    fn test_transitions_to_half_open_after_timeout() {
        let circuit = CircuitBreaker::new(CircuitConfig {
            failure_threshold: 1,
            open_duration_ms: 50, // Very short for testing
            half_open_max: 1,
        });

        // Open the circuit
        circuit.record_failure();
        assert!(circuit.is_open());
        assert!(!circuit.can_execute());

        // Wait for timeout
        thread::sleep(Duration::from_millis(60));

        // Should be able to execute now (half-open)
        assert!(circuit.can_execute());

        // State should be half-open
        assert!(matches!(circuit.state(), CircuitState::HalfOpen));
    }

    #[test]
    fn test_half_open_success_closes_circuit() {
        let circuit = CircuitBreaker::new(CircuitConfig {
            failure_threshold: 1,
            open_duration_ms: 10,
            half_open_max: 1,
        });

        // Open and wait for half-open
        circuit.record_failure();
        thread::sleep(Duration::from_millis(20));

        // Transition to half-open by trying to execute
        assert!(circuit.can_execute());

        // Record success
        circuit.record_success();

        // Should be closed now
        assert!(circuit.is_closed());
        assert!(circuit.can_execute());
    }

    #[test]
    fn test_half_open_failure_reopens_circuit() {
        let circuit = CircuitBreaker::new(CircuitConfig {
            failure_threshold: 1,
            open_duration_ms: 10,
            half_open_max: 1,
        });

        // Open and wait for half-open
        circuit.record_failure();
        thread::sleep(Duration::from_millis(20));

        // Transition to half-open
        assert!(circuit.can_execute());

        // Record failure in half-open state
        circuit.record_failure();

        // Should be open again
        assert!(circuit.is_open());
    }

    #[test]
    fn test_reset() {
        let circuit = CircuitBreaker::with_defaults();

        // Open the circuit
        circuit.record_rate_limited();
        assert!(circuit.is_open());

        // Reset
        circuit.reset();
        assert!(circuit.is_closed());
        assert_eq!(circuit.failure_count(), 0);
        assert!(circuit.can_execute());
    }

    #[test]
    fn test_half_open_limits_requests() {
        let circuit = CircuitBreaker::new(CircuitConfig {
            failure_threshold: 1,
            open_duration_ms: 10,
            half_open_max: 2,
        });

        // Open and wait for half-open
        circuit.record_failure();
        thread::sleep(Duration::from_millis(20));

        // First two requests should be allowed
        assert!(circuit.can_execute());
        assert!(circuit.can_execute());

        // Third should be blocked
        assert!(!circuit.can_execute());
    }
}