atomic-circuit-breaker 11.2.0

Zero-dependency, lock-free atomic sliding-window circuit breaker with CAS probe gating, monotonic clock support, and RAII guards.
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
use super::*;

/// Default production-ready configuration (`5` consecutive failures or `50%` over `10` calls in `10s`, `30s` cooldown, `3` probes).
impl Default for CircuitBreakerConfig {
    /// Creates a `CircuitBreakerConfig` with balanced resilience defaults.
    #[inline(always)]
    fn default() -> Self {
        Self::new()
    }
}

/// Builder, validation, and accessor operations for `CircuitBreakerConfig`.
impl CircuitBreakerConfig {
    /// Creates a `CircuitBreakerConfig` initialized with balanced resilience defaults.
    #[inline(always)]
    pub fn new() -> Self {
        Self {
            failure_threshold: None,
            consecutive_failure_threshold: Some(DEFAULT_CONSECUTIVE_FAILURE_THRESHOLD),
            failure_rate_bps: Some(DEFAULT_FAILURE_RATE_BPS),
            minimum_calls: DEFAULT_MINIMUM_CALLS,
            window_ns: DEFAULT_WINDOW_NS,
            cooldown_ns: DEFAULT_COOLDOWN_NS,
            half_open_max_probes: DEFAULT_HALF_OPEN_MAX_PROBES,
            half_open_success_threshold: DEFAULT_HALF_OPEN_MAX_PROBES,
        }
    }

    /// Sets or clears the sliding-window failure count threshold.
    ///
    /// # Arguments
    ///
    /// - `Self` - The configuration value to update.
    /// - `Option<u64>` - Optional failure count threshold within the sliding window.
    #[inline(always)]
    pub fn with_failure_threshold(mut self, threshold: Option<u64>) -> Self {
        self.set_failure_threshold(threshold);
        self
    }

    /// Sets or clears the consecutive failure count threshold.
    ///
    /// # Arguments
    ///
    /// - `Self` - The configuration value to update.
    /// - `Option<u16>` - Optional consecutive failure threshold.
    #[inline(always)]
    pub fn with_consecutive_failure_threshold(mut self, threshold: Option<u16>) -> Self {
        self.set_consecutive_failure_threshold(threshold);
        self
    }

    /// Sets or clears the sliding-window failure rate in basis points (`1..=10_000`).
    ///
    /// # Arguments
    ///
    /// - `Self` - The configuration value to update.
    /// - `Option<u32>` - Optional failure rate in basis points.
    #[inline(always)]
    pub fn with_failure_rate_bps(mut self, bps: Option<u32>) -> Self {
        self.set_failure_rate_bps(bps);
        self
    }

    /// Sets the sliding-window failure rate from a ratio in `(0.0, 1.0]`.
    ///
    /// # Arguments
    ///
    /// - `Self` - The configuration value to update.
    /// - `f64` - Failure ratio in `(0.0, 1.0]` (for example `0.5` for 50%).
    ///
    /// # Returns
    ///
    /// - `Result<Self, CircuitBreakerError>` - Updated configuration or `InvalidFailureRate`.
    #[inline(always)]
    pub fn with_failure_rate(mut self, ratio: f64) -> Result<Self, CircuitBreakerError> {
        if !ratio.is_finite() || ratio <= 0.0 || ratio > 1.0 {
            return Err(CircuitBreakerError::InvalidFailureRate);
        }
        let scaled: f64 = (ratio * (FAILURE_RATE_BPS_SCALE as f64)).round();
        let bps: u32 = (scaled as u32).clamp(1, FAILURE_RATE_BPS_SCALE);
        self.set_failure_rate_bps(Some(bps));
        Ok(self)
    }

    /// Sets the minimum total calls required in the sliding window before window checks can trip.
    ///
    /// # Arguments
    ///
    /// - `Self` - The configuration value to update.
    /// - `u64` - Minimum call count.
    #[inline(always)]
    pub fn with_minimum_calls(mut self, minimum_calls: u64) -> Self {
        self.set_minimum_calls(minimum_calls);
        self
    }

    /// Sets the sliding-window duration in nanoseconds.
    ///
    /// # Arguments
    ///
    /// - `Self` - The configuration value to update.
    /// - `u64` - Window duration in nanoseconds.
    #[inline(always)]
    pub fn with_window_ns(mut self, window_ns: u64) -> Self {
        self.set_window_ns(window_ns);
        self
    }

    /// Sets the sliding-window duration from a `Duration`.
    ///
    /// # Arguments
    ///
    /// - `Self` - The configuration value to update.
    /// - `Duration` - Sliding-window duration.
    ///
    /// # Returns
    ///
    /// - `Result<Self, CircuitBreakerError>` - Updated configuration or duration error.
    #[inline(always)]
    pub fn with_window(mut self, window: Duration) -> Result<Self, CircuitBreakerError> {
        let nanos: u128 = window.as_nanos();
        if nanos == 0 {
            return Err(CircuitBreakerError::ZeroWindow);
        }
        if nanos > u64::MAX as u128 {
            return Err(CircuitBreakerError::DurationOverflow);
        }
        self.set_window_ns(nanos as u64);
        Ok(self)
    }

    /// Sets the `Open` cooldown duration in nanoseconds.
    ///
    /// # Arguments
    ///
    /// - `Self` - The configuration value to update.
    /// - `u64` - Cooldown duration in nanoseconds.
    #[inline(always)]
    pub fn with_cooldown_ns(mut self, cooldown_ns: u64) -> Self {
        self.set_cooldown_ns(cooldown_ns);
        self
    }

    /// Sets the `Open` cooldown duration from a `Duration`.
    ///
    /// # Arguments
    ///
    /// - `Self` - The configuration value to update.
    /// - `Duration` - Cooldown duration.
    ///
    /// # Returns
    ///
    /// - `Result<Self, CircuitBreakerError>` - Updated configuration or duration error.
    #[inline(always)]
    pub fn with_cooldown(mut self, cooldown: Duration) -> Result<Self, CircuitBreakerError> {
        let nanos: u128 = cooldown.as_nanos();
        if nanos == 0 {
            return Err(CircuitBreakerError::ZeroCooldown);
        }
        if nanos > u64::MAX as u128 {
            return Err(CircuitBreakerError::DurationOverflow);
        }
        self.set_cooldown_ns(nanos as u64);
        Ok(self)
    }

    /// Sets the maximum number of probe calls permitted in `HalfOpen` and clamps the success threshold.
    ///
    /// # Arguments
    ///
    /// - `Self` - The configuration value to update.
    /// - `u16` - Maximum probe calls (`>= 1`).
    #[inline(always)]
    pub fn with_half_open_max_probes(mut self, max_probes: u16) -> Self {
        self.set_half_open_max_probes(max_probes);
        if self.get_half_open_success_threshold() > max_probes {
            self.set_half_open_success_threshold(max_probes);
        }
        self
    }

    /// Sets the required successful probes in `HalfOpen` before closing the circuit.
    ///
    /// # Arguments
    ///
    /// - `Self` - The configuration value to update.
    /// - `u16` - Success threshold (`1..=half_open_max_probes`).
    #[inline(always)]
    pub fn with_half_open_success_threshold(mut self, threshold: u16) -> Self {
        self.set_half_open_success_threshold(threshold);
        self
    }

    /// Validates all configuration invariants before constructing a `CircuitBreaker`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration to validate.
    ///
    /// # Returns
    ///
    /// - `Result<(), CircuitBreakerError>` - `Ok(())` when valid or the first violation.
    #[inline(always)]
    pub fn validate(&self) -> Result<(), CircuitBreakerError> {
        if self.get_window_ns() == 0 {
            return Err(CircuitBreakerError::ZeroWindow);
        }
        if self.get_cooldown_ns() == 0 {
            return Err(CircuitBreakerError::ZeroCooldown);
        }
        let max_probes: u16 = self.get_half_open_max_probes();
        let success_threshold: u16 = self.get_half_open_success_threshold();
        if max_probes == 0 || success_threshold == 0 || success_threshold > max_probes {
            return Err(CircuitBreakerError::InvalidHalfOpenConfig);
        }
        if let Some(ft) = self.get_failure_threshold()
            && ft == 0
        {
            return Err(CircuitBreakerError::InvalidThreshold);
        }
        if let Some(cft) = self.get_consecutive_failure_threshold()
            && cft == 0
        {
            return Err(CircuitBreakerError::InvalidThreshold);
        }
        if let Some(bps) = self.get_failure_rate_bps()
            && (bps == 0 || bps > FAILURE_RATE_BPS_SCALE)
        {
            return Err(CircuitBreakerError::InvalidFailureRate);
        }
        if self.get_failure_threshold().is_none()
            && self.get_consecutive_failure_threshold().is_none()
            && self.get_failure_rate_bps().is_none()
        {
            return Err(CircuitBreakerError::NoTripCondition);
        }
        Ok(())
    }

    /// Returns the configured sliding-window failure count threshold.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration.
    ///
    /// # Returns
    ///
    /// - `Option<u64>` - Optional window failure count threshold.
    #[inline(always)]
    pub fn get_failure_threshold(&self) -> Option<u64> {
        self.failure_threshold
    }

    /// Sets the sliding-window failure count threshold.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration.
    /// - `Option<u64>` - New threshold value.
    #[inline(always)]
    pub(crate) fn set_failure_threshold(&mut self, value: Option<u64>) {
        self.failure_threshold = value;
    }

    /// Returns the configured consecutive failure threshold.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration.
    ///
    /// # Returns
    ///
    /// - `Option<u16>` - Optional consecutive failure threshold.
    #[inline(always)]
    pub fn get_consecutive_failure_threshold(&self) -> Option<u16> {
        self.consecutive_failure_threshold
    }

    /// Sets the consecutive failure threshold.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration.
    /// - `Option<u16>` - New threshold value.
    #[inline(always)]
    pub(crate) fn set_consecutive_failure_threshold(&mut self, value: Option<u16>) {
        self.consecutive_failure_threshold = value;
    }

    /// Returns the configured failure rate threshold in basis points (`1..=10_000`).
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration.
    ///
    /// # Returns
    ///
    /// - `Option<u32>` - Optional failure rate in basis points.
    #[inline(always)]
    pub fn get_failure_rate_bps(&self) -> Option<u32> {
        self.failure_rate_bps
    }

    /// Sets the failure rate threshold in basis points.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration.
    /// - `Option<u32>` - New failure rate in basis points.
    #[inline(always)]
    pub(crate) fn set_failure_rate_bps(&mut self, value: Option<u32>) {
        self.failure_rate_bps = value;
    }

    /// Returns the minimum calls required in the sliding window.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration.
    ///
    /// # Returns
    ///
    /// - `u64` - Minimum call volume.
    #[inline(always)]
    pub fn get_minimum_calls(&self) -> u64 {
        self.minimum_calls
    }

    /// Sets the minimum calls required in the sliding window.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration.
    /// - `u64` - New minimum call volume.
    #[inline(always)]
    pub(crate) fn set_minimum_calls(&mut self, value: u64) {
        self.minimum_calls = value;
    }

    /// Returns the sliding-window duration in nanoseconds.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration.
    ///
    /// # Returns
    ///
    /// - `u64` - Window duration in nanoseconds.
    #[inline(always)]
    pub fn get_window_ns(&self) -> u64 {
        self.window_ns
    }

    /// Sets the sliding-window duration in nanoseconds.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration.
    /// - `u64` - New window duration in nanoseconds.
    #[inline(always)]
    pub(crate) fn set_window_ns(&mut self, value: u64) {
        self.window_ns = value;
    }

    /// Returns the open-state cooldown duration in nanoseconds.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration.
    ///
    /// # Returns
    ///
    /// - `u64` - Cooldown duration in nanoseconds.
    #[inline(always)]
    pub fn get_cooldown_ns(&self) -> u64 {
        self.cooldown_ns
    }

    /// Sets the open-state cooldown duration in nanoseconds.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration.
    /// - `u64` - New cooldown duration in nanoseconds.
    #[inline(always)]
    pub(crate) fn set_cooldown_ns(&mut self, value: u64) {
        self.cooldown_ns = value;
    }

    /// Returns the maximum half-open probes permitted per trial cycle.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration.
    ///
    /// # Returns
    ///
    /// - `u16` - Maximum probe permits.
    #[inline(always)]
    pub fn get_half_open_max_probes(&self) -> u16 {
        self.half_open_max_probes
    }

    /// Sets the maximum half-open probes permitted per trial cycle.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration.
    /// - `u16` - New maximum probe permits.
    #[inline(always)]
    pub(crate) fn set_half_open_max_probes(&mut self, value: u16) {
        self.half_open_max_probes = value;
    }

    /// Returns the required successful probes in `HalfOpen` before closing.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration.
    ///
    /// # Returns
    ///
    /// - `u16` - Required probe successes.
    #[inline(always)]
    pub fn get_half_open_success_threshold(&self) -> u16 {
        self.half_open_success_threshold
    }

    /// Sets the required successful probes in `HalfOpen` before closing.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The configuration.
    /// - `u16` - New required probe successes.
    #[inline(always)]
    pub(crate) fn set_half_open_success_threshold(&mut self, value: u16) {
        self.half_open_success_threshold = value;
    }
}