decrust-core 1.2.6

Core error handling framework for Decrust
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
/* src/circuit_breaker.rs */
#![warn(missing_docs)]
//! **Brief:** Circuit breaker implementation for resilience.
// ~=####====A===r===c===M===o===o===n====S===t===u===d===i===o===s====X|0|$>
//! + [Error Handling Framework]
//!  - [Circuit Breaker Pattern]
//!  - [Fault Tolerance]
//!  - [Service Resilience]
//!  - [Adaptive Thresholds]
//!  - [Performance Monitoring]
// ~=####====A===r===c===M===o===o===n====S===t===u===d===i===o===s====X|0|$>
// **GitHub:** [ArcMoon Studios](https://github.com/arcmoonstudios)
// **Copyright:** (c) 2025 ArcMoon Studios
// **Author:** Lord Xyn
// **License:** Business Source License 1.1 (BSL-1.1)
// **License File:** /LICENSE
// **License Terms:** Non-production use only; commercial/production use requires a paid license.
// **Change Date:** 2029-05-25 | **Change License:** GPL v3
// **Contact:** LordXyn@proton.me

//! This module provides a CircuitBreaker struct that helps protect the system
//! from cascading failures when interacting with external services or performing
//! operations prone to repeated errors.

use super::backtrace::DecrustBacktrace as Backtrace;
use super::{DecrustError, Result};
use std::collections::VecDeque;
use std::fmt;
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime};
use tracing::info;

/// A wrapper for types that don't implement Debug
pub struct DebugIgnore<T: ?Sized>(pub T);

impl<T: ?Sized> fmt::Debug for DebugIgnore<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "<function>")
    }
}

impl<T: Clone> Clone for DebugIgnore<T> {
    fn clone(&self) -> Self {
        DebugIgnore(self.0.clone())
    }
}

#[cfg(feature = "rand")]
#[allow(unused_imports)]
use rand::Rng;
#[cfg(feature = "tokio")]
use tokio::time;

/// Represents the state of the circuit breaker.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum CircuitBreakerState {
    /// The circuit is closed, operations are allowed.
    #[default]
    Closed,
    /// The circuit is open, operations are rejected immediately.
    Open,
    /// The circuit is partially open, allowing a limited number of test operations.
    HalfOpen,
}

impl fmt::Display for CircuitBreakerState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

/// Type of operation outcome.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CircuitOperationType {
    /// Operation completed successfully
    Success,
    /// Operation failed with an error
    Failure,
    /// Operation was rejected by the circuit breaker (e.g., when Open or HalfOpen limit reached)
    Rejected,
    /// Operation timed out
    Timeout,
}

/// Represents an event of state transition
#[derive(Debug, Clone)]
pub struct CircuitTransitionEvent {
    /// The state the circuit breaker is transitioning from
    pub from_state: CircuitBreakerState,
    /// The state the circuit breaker is transitioning to
    pub to_state: CircuitBreakerState,
    /// When the transition occurred
    pub timestamp: SystemTime,
    /// The reason for the state transition
    pub reason: String,
}

/// Observer trait for circuit breaker events.
///
/// Implement this trait to react to state changes, operation results,
/// and other significant events from the circuit breaker.
pub trait CircuitBreakerObserver: Send + Sync {
    /// Called when the circuit breaker's state changes.
    fn on_state_change(&self, name: &str, event: &CircuitTransitionEvent);
    /// Called before an operation is attempted (if not rejected immediately).
    fn on_operation_attempt(&self, name: &str, state: CircuitBreakerState);
    /// Called after an operation completes or is rejected/timed out.
    fn on_operation_result(
        &self,
        name: &str,
        op_type: CircuitOperationType,
        duration: Duration,
        error: Option<&DecrustError>,
    );
    /// Called when the circuit breaker is manually reset.
    fn on_reset(&self, name: &str);
}

/// Metrics collected by the circuit breaker
#[derive(Debug, Clone, Default)]
pub struct CircuitMetrics {
    /// Current state of the circuit breaker
    pub state: CircuitBreakerState,
    /// Total number of requests processed by the circuit breaker
    pub total_requests: u64,
    /// Number of successful requests
    pub successful_requests: u64,
    /// Number of failed requests
    pub failed_requests: u64,
    /// Number of requests rejected due to circuit breaker being open
    pub rejected_requests: u64,
    /// Number of requests that timed out
    pub timeout_requests: u64,
    /// Current count of consecutive failures
    pub consecutive_failures: u32,
    /// Current count of consecutive successes
    pub consecutive_successes: u32,
    /// Timestamp of the last error that occurred
    pub last_error_timestamp: Option<SystemTime>,
    /// Timestamp of the last state transition
    pub last_transition_timestamp: Option<SystemTime>,
    /// Current failure rate calculated over the sliding window (0.0 to 1.0)
    pub failure_rate_in_window: Option<f64>,
    /// Current rate of slow calls calculated over the sliding window (0.0 to 1.0)
    pub slow_call_rate_in_window: Option<f64>,
}

/// Type alias for error predicate function
pub type ErrorPredicate = Arc<dyn Fn(&DecrustError) -> bool + Send + Sync>;

/// Configuration for the CircuitBreaker.
///
/// Defines thresholds and timeouts that control the behavior of the circuit breaker.
#[derive(Clone)]
pub struct CircuitBreakerConfig {
    /// The number of consecutive failures after which the circuit opens.
    pub failure_threshold: usize,
    /// The failure rate (0.0 to 1.0) within the sliding window that causes the circuit to open.
    pub failure_rate_threshold: f64,
    /// The minimum number of requests in the sliding window before the failure rate is considered.
    pub minimum_request_threshold_for_rate: usize,
    /// The number of consecutive successes required in HalfOpen state to transition to Closed.
    pub success_threshold_to_close: usize,
    /// The duration the circuit stays Open before transitioning to HalfOpen.
    pub reset_timeout: Duration,
    /// The maximum number of operations allowed to execute concurrently when in HalfOpen state.
    pub half_open_max_concurrent_operations: usize,
    /// Optional timeout for individual operations executed through the circuit breaker.
    pub operation_timeout: Option<Duration>,
    /// The size of the sliding window used for calculating failure rates.
    pub sliding_window_size: usize,
    /// An optional predicate to determine if a specific `DecrustError` should be considered a failure.
    /// If `None`, all `Err` results are considered failures.
    pub error_predicate: Option<ErrorPredicate>,
    /// The size of the history window for detailed metrics (not fully implemented in this version).
    pub metrics_window_size: usize, // Currently used for result_window and slow_call_window size logic
    /// Whether to track detailed metrics.
    pub track_metrics: bool,
    /// Threshold for an operation to be considered a "slow call".
    pub slow_call_duration_threshold: Option<Duration>,
    /// Rate of slow calls (0.0 to 1.0) in the window that can cause the circuit to open.
    pub slow_call_rate_threshold: Option<f64>,
    /// Number of consecutive failures before opening the circuit breaker.
    pub circuit_breaker_threshold: u32,
    /// Duration the circuit breaker stays open after tripping.
    pub circuit_breaker_cooldown: Duration,
}

impl Default for CircuitBreakerConfig {
    fn default() -> Self {
        Self {
            failure_threshold: 5,
            failure_rate_threshold: 0.5,
            minimum_request_threshold_for_rate: 10,
            success_threshold_to_close: 3,
            reset_timeout: Duration::from_secs(30),
            half_open_max_concurrent_operations: 1,
            operation_timeout: Some(Duration::from_secs(5)),
            sliding_window_size: 100,
            error_predicate: None,
            metrics_window_size: 100, // This could influence window sizes if not for fixed `sliding_window_size`
            track_metrics: true,
            slow_call_duration_threshold: None, // e.g., Some(Duration::from_millis(500))
            slow_call_rate_threshold: None,     // e.g., Some(0.3) for 30% slow calls
            circuit_breaker_threshold: 3,       // Default to 3 consecutive failures
            circuit_breaker_cooldown: Duration::from_secs(60), // Default to 60 seconds cooldown
        }
    }
}

impl fmt::Debug for CircuitBreakerConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CircuitBreakerConfig")
            .field("failure_threshold", &self.failure_threshold)
            .field("failure_rate_threshold", &self.failure_rate_threshold)
            .field(
                "minimum_request_threshold_for_rate",
                &self.minimum_request_threshold_for_rate,
            )
            .field(
                "success_threshold_to_close",
                &self.success_threshold_to_close,
            )
            .field("reset_timeout", &self.reset_timeout)
            .field(
                "half_open_max_concurrent_operations",
                &self.half_open_max_concurrent_operations,
            )
            .field("operation_timeout", &self.operation_timeout)
            .field("sliding_window_size", &self.sliding_window_size)
            .field(
                "error_predicate",
                &if self.error_predicate.is_some() {
                    "Some(<function>)"
                } else {
                    "None"
                },
            )
            .field("metrics_window_size", &self.metrics_window_size)
            .field("track_metrics", &self.track_metrics)
            .field(
                "slow_call_duration_threshold",
                &self.slow_call_duration_threshold,
            )
            .field("slow_call_rate_threshold", &self.slow_call_rate_threshold)
            .field("circuit_breaker_threshold", &self.circuit_breaker_threshold)
            .field("circuit_breaker_cooldown", &self.circuit_breaker_cooldown)
            .finish()
    }
}

#[derive(Debug)] // Added Debug derive for InnerState
struct InnerState {
    state: CircuitBreakerState,
    opened_at: Option<Instant>,
    half_open_entered_at: Option<Instant>,
    consecutive_failures: usize,
    consecutive_successes: usize,
    half_open_concurrency_count: usize,
    results_window: VecDeque<bool>, // true for success, false for failure
    slow_call_window: VecDeque<bool>, // true if call was slow
    metrics: CircuitMetrics,
}

impl Default for InnerState {
    fn default() -> Self {
        Self {
            state: CircuitBreakerState::Closed,
            opened_at: None,
            half_open_entered_at: None,
            consecutive_failures: 0,
            consecutive_successes: 0,
            half_open_concurrency_count: 0,
            results_window: VecDeque::with_capacity(100),
            slow_call_window: VecDeque::with_capacity(100),
            metrics: CircuitMetrics::default(),
        }
    }
}

/// A circuit breaker implementation to prevent cascading failures.
pub struct CircuitBreaker {
    name: String,
    config: CircuitBreakerConfig,
    inner: RwLock<InnerState>,
    observers: Mutex<Vec<Arc<dyn CircuitBreakerObserver>>>,
}

impl CircuitBreaker {
    /// Creates a new CircuitBreaker instance
    pub fn new(name: impl Into<String>, config: CircuitBreakerConfig) -> Arc<Self> {
        Arc::new(Self {
            name: name.into(),
            config,
            inner: RwLock::new(InnerState::default()),
            observers: Mutex::new(Vec::new()),
        })
    }

    /// Add an observer to the circuit breaker
    pub fn add_observer(&self, observer: Arc<dyn CircuitBreakerObserver>) {
        let mut observers = self.observers.lock().unwrap();
        observers.push(observer);
    }

    /// Get the current state of the circuit breaker
    pub fn state(&self) -> CircuitBreakerState {
        let inner = self.inner.read().unwrap();
        inner.state
    }

    /// Get the current metrics of the circuit breaker
    pub fn metrics(&self) -> CircuitMetrics {
        let inner = self.inner.read().unwrap();
        inner.metrics.clone()
    }

    /// Trip the circuit breaker manually
    pub fn trip(&self) {
        let mut inner = self.inner.write().unwrap();
        let prev_state = inner.state;
        inner.state = CircuitBreakerState::Open;
        inner.opened_at = Some(Instant::now());
        inner.consecutive_failures = self.config.failure_threshold;
        inner.consecutive_successes = 0;

        let event = CircuitTransitionEvent {
            from_state: prev_state,
            to_state: CircuitBreakerState::Open,
            timestamp: SystemTime::now(),
            reason: "Manual trip".to_string(),
        };

        // Update metrics
        inner.metrics.state = CircuitBreakerState::Open;
        inner.metrics.consecutive_failures = inner.consecutive_failures as u32;
        inner.metrics.consecutive_successes = 0;
        inner.metrics.last_transition_timestamp = Some(SystemTime::now());

        // Drop the lock before calling observers
        drop(inner);

        // Notify observers
        self.notify_state_change(&event);
    }

    /// Reset the circuit breaker to closed state
    pub fn reset(&self) {
        let mut inner = self.inner.write().unwrap();
        let prev_state = inner.state;
        inner.state = CircuitBreakerState::Closed;
        inner.opened_at = None;
        inner.half_open_entered_at = None;
        inner.consecutive_failures = 0;
        inner.consecutive_successes = 0;
        inner.half_open_concurrency_count = 0;

        // Update metrics
        inner.metrics.state = CircuitBreakerState::Closed;
        inner.metrics.consecutive_failures = 0;
        inner.metrics.consecutive_successes = 0;
        inner.metrics.last_transition_timestamp = Some(SystemTime::now());

        // Clear windows
        inner.results_window.clear();
        inner.slow_call_window.clear();

        let event = CircuitTransitionEvent {
            from_state: prev_state,
            to_state: CircuitBreakerState::Closed,
            timestamp: SystemTime::now(),
            reason: "Manual reset".to_string(),
        };

        // Drop the lock before calling observers
        drop(inner);

        // Notify observers
        self.notify_state_change(&event);
        self.notify_reset();
    }

    /// Execute an operation through the circuit breaker
    #[cfg(not(feature = "std-thread"))]
    pub fn execute<F, Ret>(&self, operation: F) -> Result<Ret>
    where
        F: FnOnce() -> Result<Ret>,
    {
        let start_time = Instant::now();
        let state = self.state();

        self.notify_operation_attempt(state);

        match state {
            CircuitBreakerState::Open => {
                // Check if reset timeout has elapsed
                let inner = self.inner.read().unwrap();
                let should_transition = if let Some(opened_at) = inner.opened_at {
                    opened_at.elapsed() >= self.config.reset_timeout
                } else {
                    false
                };
                drop(inner);

                if should_transition {
                    self.transition_to_half_open("Reset timeout elapsed");
                    // Continue with half-open logic
                    self.execute_half_open(operation, start_time)
                } else {
                    // Still open, reject the operation
                    self.record_rejected();
                    Err(DecrustError::CircuitBreakerOpen {
                        name: self.name.clone(),
                        retry_after: Some(
                            self.config
                                .reset_timeout
                                .checked_sub(
                                    self.inner.read().unwrap().opened_at.unwrap().elapsed(),
                                )
                                .unwrap_or_default(),
                        ),
                        failure_count: None,
                        last_error: None,
                        backtrace: Backtrace::generate(),
                    })
                }
            }
            CircuitBreakerState::HalfOpen => self.execute_half_open(operation, start_time),
            CircuitBreakerState::Closed => self.execute_closed(operation, start_time),
        }
    }

    /// Execute an operation through the circuit breaker
    #[cfg(feature = "std-thread")]
    pub fn execute<F, Ret>(&self, operation: F) -> Result<Ret>
    where
        F: FnOnce() -> Result<Ret> + Send + 'static,
        Ret: Send + 'static,
    {
        let start_time = Instant::now();
        let state = self.state();

        self.notify_operation_attempt(state);

        match state {
            CircuitBreakerState::Open => {
                // Check if reset timeout has elapsed
                let inner = self.inner.read().unwrap();
                let should_transition = if let Some(opened_at) = inner.opened_at {
                    opened_at.elapsed() >= self.config.reset_timeout
                } else {
                    false
                };
                drop(inner);

                if should_transition {
                    self.transition_to_half_open("Reset timeout elapsed");
                    // Continue with half-open logic
                    self.execute_half_open(operation, start_time)
                } else {
                    // Still open, reject the operation
                    self.record_rejected();
                    Err(DecrustError::CircuitBreakerOpen {
                        name: self.name.clone(),
                        retry_after: Some(
                            self.config
                                .reset_timeout
                                .checked_sub(
                                    self.inner.read().unwrap().opened_at.unwrap().elapsed(),
                                )
                                .unwrap_or_default(),
                        ),
                        failure_count: Some(self.inner.read().unwrap().consecutive_failures as u32),
                        last_error: None, // InnerState doesn't track last_error
                        backtrace: Backtrace::generate(),
                    })
                }
            }
            CircuitBreakerState::HalfOpen => self.execute_half_open(operation, start_time),
            CircuitBreakerState::Closed => self.execute_closed(operation, start_time),
        }
    }

    /// Execute an async operation through the circuit breaker
    #[cfg(feature = "tokio")]
    pub async fn execute_async<F, Fut, Ret>(&self, operation: F) -> Result<Ret>
    where
        F: FnOnce() -> Fut,
        Fut: std::future::Future<Output = Result<Ret>>,
    {
        let start_time = Instant::now();
        let state = self.state();

        self.notify_operation_attempt(state);

        match state {
            CircuitBreakerState::Open => {
                // Check if reset timeout has elapsed
                let inner = self.inner.read().unwrap();
                let should_transition = if let Some(opened_at) = inner.opened_at {
                    opened_at.elapsed() >= self.config.reset_timeout
                } else {
                    false
                };
                drop(inner);

                if should_transition {
                    self.transition_to_half_open("Reset timeout elapsed");
                    // Continue with half-open logic
                    self.execute_half_open_async(operation, start_time).await
                } else {
                    // Still open, reject the operation
                    self.record_rejected();
                    Err(DecrustError::CircuitBreakerOpen {
                        name: self.name.clone(),
                        retry_after: Some(
                            self.config
                                .reset_timeout
                                .checked_sub(
                                    self.inner.read().unwrap().opened_at.unwrap().elapsed(),
                                )
                                .unwrap_or_default(),
                        ),
                        failure_count: Some(self.inner.read().unwrap().consecutive_failures as u32),
                        last_error: None, // InnerState doesn't track last_error
                        backtrace: Backtrace::generate(),
                    })
                }
            }
            CircuitBreakerState::HalfOpen => {
                self.execute_half_open_async(operation, start_time).await
            }
            CircuitBreakerState::Closed => self.execute_closed_async(operation, start_time).await,
        }
    }

    // Private helper methods

    // Execute operation in Closed state
    #[cfg(not(feature = "std-thread"))]
    fn execute_closed<F, Ret>(&self, operation: F, start_time: Instant) -> Result<Ret>
    where
        F: FnOnce() -> Result<Ret>,
    {
        let result = if let Some(timeout) = self.config.operation_timeout {
            self.execute_with_timeout(operation, timeout)
        } else {
            operation()
        };

        let duration = start_time.elapsed();

        match &result {
            Ok(_) => {
                self.record_success(duration);
            }
            Err(e) => {
                if self.should_count_as_failure(e) {
                    self.record_failure(e, duration);

                    // Check if we need to open the circuit
                    if self.should_open_circuit() {
                        self.transition_to_open("Failure threshold reached");
                    }
                } else {
                    // Error not counted as failure for circuit breaking
                    self.record_success(duration);
                }
            }
        }

        result
    }

    #[cfg(feature = "std-thread")]
    fn execute_closed<F, Ret>(&self, operation: F, start_time: Instant) -> Result<Ret>
    where
        F: FnOnce() -> Result<Ret> + Send + 'static,
        Ret: Send + 'static,
    {
        let result = if let Some(timeout) = self.config.operation_timeout {
            self.execute_with_timeout(operation, timeout)
        } else {
            operation()
        };

        let duration = start_time.elapsed();

        match &result {
            Ok(_) => {
                self.record_success(duration);
            }
            Err(e) => {
                if self.should_count_as_failure(e) {
                    self.record_failure(e, duration);

                    // Check if we need to open the circuit
                    if self.should_open_circuit() {
                        self.transition_to_open("Failure threshold reached");
                    }
                } else {
                    // Error not counted as failure for circuit breaking
                    self.record_success(duration);
                }
            }
        }

        result
    }

    // Execute operation in HalfOpen state
    #[cfg(not(feature = "std-thread"))]
    fn execute_half_open<F, Ret>(&self, operation: F, start_time: Instant) -> Result<Ret>
    where
        F: FnOnce() -> Result<Ret>,
    {
        // Check if we can proceed with the operation
        {
            let mut inner = self.inner.write().unwrap();
            if inner.half_open_concurrency_count >= self.config.half_open_max_concurrent_operations
            {
                // Too many concurrent operations in half-open state
                self.record_rejected();
                return Err(DecrustError::CircuitBreakerOpen {
                    name: self.name.clone(),
                    retry_after: Some(Duration::from_millis(100)),
                    failure_count: None,
                    last_error: None,
                    backtrace: Backtrace::generate(),
                });
            }

            // Increment concurrency count
            inner.half_open_concurrency_count += 1;
        }

        // Execute the operation
        let result = if let Some(timeout) = self.config.operation_timeout {
            self.execute_with_timeout(operation, timeout)
        } else {
            operation()
        };

        let duration = start_time.elapsed();

        // Decrement concurrency count
        {
            let mut inner = self.inner.write().unwrap();
            inner.half_open_concurrency_count = inner.half_open_concurrency_count.saturating_sub(1);
        }

        match &result {
            Ok(_) => {
                self.record_success(duration);

                // Check if we can close the circuit
                let close_circuit = {
                    let inner = self.inner.read().unwrap();
                    inner.consecutive_successes >= self.config.success_threshold_to_close
                };

                if close_circuit {
                    self.transition_to_closed("Success threshold reached");
                }
            }
            Err(e) => {
                if self.should_count_as_failure(e) {
                    self.record_failure(e, duration);

                    // Any failure in half-open should open the circuit again
                    self.transition_to_open("Failure in half-open state");
                } else {
                    // Error not counted as failure for circuit breaking
                    self.record_success(duration);
                }
            }
        }

        result
    }

    #[cfg(feature = "std-thread")]
    fn execute_half_open<F, Ret>(&self, operation: F, start_time: Instant) -> Result<Ret>
    where
        F: FnOnce() -> Result<Ret> + Send + 'static,
        Ret: Send + 'static,
    {
        // Check if we can proceed with the operation
        {
            let mut inner = self.inner.write().unwrap();
            if inner.half_open_concurrency_count >= self.config.half_open_max_concurrent_operations
            {
                // Too many concurrent operations in half-open state
                self.record_rejected();
                return Err(DecrustError::CircuitBreakerOpen {
                    name: self.name.clone(),
                    retry_after: Some(Duration::from_millis(100)),
                    failure_count: Some(self.inner.read().unwrap().consecutive_failures as u32),
                    last_error: None, // InnerState doesn't track last_error
                    backtrace: Backtrace::generate(),
                });
            }

            // Increment concurrency count
            inner.half_open_concurrency_count += 1;
        }

        // Execute the operation
        let result = if let Some(timeout) = self.config.operation_timeout {
            self.execute_with_timeout(operation, timeout)
        } else {
            operation()
        };

        let duration = start_time.elapsed();

        // Decrement concurrency count
        {
            let mut inner = self.inner.write().unwrap();
            inner.half_open_concurrency_count = inner.half_open_concurrency_count.saturating_sub(1);
        }

        match &result {
            Ok(_) => {
                self.record_success(duration);

                // Check if we can close the circuit
                let close_circuit = {
                    let inner = self.inner.read().unwrap();
                    inner.consecutive_successes >= self.config.success_threshold_to_close
                };

                if close_circuit {
                    self.transition_to_closed("Success threshold reached");
                }
            }
            Err(e) => {
                if self.should_count_as_failure(e) {
                    self.record_failure(e, duration);

                    // Any failure in half-open should open the circuit again
                    self.transition_to_open("Failure in half-open state");
                } else {
                    // Error not counted as failure for circuit breaking
                    self.record_success(duration);
                }
            }
        }

        result
    }

    // Async versions

    #[cfg(feature = "tokio")]
    async fn execute_closed_async<F, Fut, Ret>(
        &self,
        operation: F,
        start_time: Instant,
    ) -> Result<Ret>
    where
        F: FnOnce() -> Fut,
        Fut: std::future::Future<Output = Result<Ret>>,
    {
        let result = if let Some(timeout) = self.config.operation_timeout {
            self.execute_with_timeout_async(operation, timeout).await
        } else {
            operation().await
        };

        let duration = start_time.elapsed();

        match &result {
            Ok(_) => {
                self.record_success(duration);
            }
            Err(e) => {
                if self.should_count_as_failure(e) {
                    self.record_failure(e, duration);

                    // Check if we need to open the circuit
                    if self.should_open_circuit() {
                        self.transition_to_open("Failure threshold reached");
                    }
                } else {
                    // Error not counted as failure for circuit breaking
                    self.record_success(duration);
                }
            }
        }

        result
    }

    #[cfg(feature = "tokio")]
    async fn execute_half_open_async<F, Fut, Ret>(
        &self,
        operation: F,
        start_time: Instant,
    ) -> Result<Ret>
    where
        F: FnOnce() -> Fut,
        Fut: std::future::Future<Output = Result<Ret>>,
    {
        // Check if we can proceed with the operation
        {
            let mut inner = self.inner.write().unwrap();
            if inner.half_open_concurrency_count >= self.config.half_open_max_concurrent_operations
            {
                // Too many concurrent operations in half-open state
                self.record_rejected();
                return Err(DecrustError::CircuitBreakerOpen {
                    name: self.name.clone(),
                    retry_after: Some(Duration::from_millis(100)),
                    failure_count: Some(self.inner.read().unwrap().consecutive_failures as u32),
                    last_error: None, // InnerState doesn't track last_error
                    backtrace: Backtrace::generate(),
                });
            }

            // Increment concurrency count
            inner.half_open_concurrency_count += 1;
        }

        // Execute the operation
        let result = if let Some(timeout) = self.config.operation_timeout {
            self.execute_with_timeout_async(operation, timeout).await
        } else {
            operation().await
        };

        let duration = start_time.elapsed();

        // Decrement concurrency count
        {
            let mut inner = self.inner.write().unwrap();
            inner.half_open_concurrency_count = inner.half_open_concurrency_count.saturating_sub(1);
        }

        match &result {
            Ok(_) => {
                self.record_success(duration);

                // Check if we can close the circuit
                let close_circuit = {
                    let inner = self.inner.read().unwrap();
                    inner.consecutive_successes >= self.config.success_threshold_to_close
                };

                if close_circuit {
                    self.transition_to_closed("Success threshold reached");
                }
            }
            Err(e) => {
                if self.should_count_as_failure(e) {
                    self.record_failure(e, duration);

                    // Any failure in half-open should open the circuit again
                    self.transition_to_open("Failure in half-open state");
                } else {
                    // Error not counted as failure for circuit breaking
                    self.record_success(duration);
                }
            }
        }

        result
    }

    // Timeout helpers

    // Non-threaded timeout implementation
    #[cfg(not(feature = "std-thread"))]
    fn execute_with_timeout<F, Ret>(&self, operation: F, timeout: Duration) -> Result<Ret>
    where
        F: FnOnce() -> Result<Ret>,
    {
        // Fallback implementation without threads
        let start = Instant::now();
        let result = operation();
        if start.elapsed() > timeout {
            self.record_timeout();
            Err(DecrustError::Timeout {
                operation: format!("Operation in circuit breaker '{}'", self.name),
                duration: timeout,
                backtrace: Backtrace::generate(),
            })
        } else {
            result
        }
    }

    // Threaded timeout implementation
    #[cfg(feature = "std-thread")]
    fn execute_with_timeout<F, Ret>(&self, operation: F, timeout: Duration) -> Result<Ret>
    where
        F: FnOnce() -> Result<Ret> + Send + 'static,
        Ret: Send + 'static,
    {
        use std::sync::mpsc;
        use std::thread;

        let (tx, rx) = mpsc::channel();

        let handle = thread::spawn(move || {
            let result = operation();
            let _ = tx.send(result);
        });

        match rx.recv_timeout(timeout) {
            Ok(result) => {
                // Operation completed within timeout
                let _ = handle.join();
                result
            }
            Err(_) => {
                // Operation timed out
                self.record_timeout();
                Err(DecrustError::Timeout {
                    operation: format!("Operation in circuit breaker '{}'", self.name),
                    duration: timeout,
                    backtrace: Backtrace::generate(),
                })
            }
        }
    }

    #[cfg(feature = "tokio")]
    async fn execute_with_timeout_async<F, Fut, Ret>(
        &self,
        operation: F,
        timeout: Duration,
    ) -> Result<Ret>
    where
        F: FnOnce() -> Fut,
        Fut: std::future::Future<Output = Result<Ret>>,
    {
        match time::timeout(timeout, operation()).await {
            Ok(result) => result,
            Err(_) => {
                self.record_timeout();
                Err(DecrustError::Timeout {
                    operation: format!("Operation in circuit breaker '{}'", self.name),
                    duration: timeout,
                    backtrace: Backtrace::generate(),
                })
            }
        }
    }

    // State transition helpers

    fn transition_to_open(&self, reason: &str) {
        let mut inner = self.inner.write().unwrap();
        let prev_state = inner.state;
        inner.state = CircuitBreakerState::Open;
        inner.opened_at = Some(Instant::now());
        inner.consecutive_successes = 0;

        let event = CircuitTransitionEvent {
            from_state: prev_state,
            to_state: CircuitBreakerState::Open,
            timestamp: SystemTime::now(),
            reason: reason.to_string(),
        };

        // Update metrics
        inner.metrics.state = CircuitBreakerState::Open;
        inner.metrics.last_transition_timestamp = Some(SystemTime::now());

        // Drop the lock before calling observers
        drop(inner);

        info!(
            "Circuit breaker '{}' transitioning to Open: {}",
            self.name, reason
        );
        self.notify_state_change(&event);
    }

    fn transition_to_half_open(&self, reason: &str) {
        let mut inner = self.inner.write().unwrap();
        let prev_state = inner.state;
        inner.state = CircuitBreakerState::HalfOpen;
        inner.half_open_entered_at = Some(Instant::now());
        inner.consecutive_successes = 0;
        inner.half_open_concurrency_count = 0;

        let event = CircuitTransitionEvent {
            from_state: prev_state,
            to_state: CircuitBreakerState::HalfOpen,
            timestamp: SystemTime::now(),
            reason: reason.to_string(),
        };

        // Update metrics
        inner.metrics.state = CircuitBreakerState::HalfOpen;
        inner.metrics.last_transition_timestamp = Some(SystemTime::now());

        // Drop the lock before calling observers
        drop(inner);

        info!(
            "Circuit breaker '{}' transitioning to HalfOpen: {}",
            self.name, reason
        );
        self.notify_state_change(&event);
    }

    fn transition_to_closed(&self, reason: &str) {
        let mut inner = self.inner.write().unwrap();
        let prev_state = inner.state;
        inner.state = CircuitBreakerState::Closed;
        inner.opened_at = None;
        inner.half_open_entered_at = None;
        inner.consecutive_failures = 0;

        let event = CircuitTransitionEvent {
            from_state: prev_state,
            to_state: CircuitBreakerState::Closed,
            timestamp: SystemTime::now(),
            reason: reason.to_string(),
        };

        // Update metrics
        inner.metrics.state = CircuitBreakerState::Closed;
        inner.metrics.last_transition_timestamp = Some(SystemTime::now());

        // Drop the lock before calling observers
        drop(inner);

        info!(
            "Circuit breaker '{}' transitioning to Closed: {}",
            self.name, reason
        );
        self.notify_state_change(&event);
    }

    // Result recording helpers

    fn record_success(&self, duration: Duration) {
        let mut inner = self.inner.write().unwrap();
        inner.consecutive_successes += 1;
        inner.consecutive_failures = 0;

        // Update sliding window
        if inner.results_window.len() >= self.config.sliding_window_size {
            inner.results_window.pop_front();
        }
        inner.results_window.push_back(true);

        // Check if the call was slow
        let was_slow = if let Some(threshold) = self.config.slow_call_duration_threshold {
            duration >= threshold
        } else {
            false
        };

        // Update slow call window
        if inner.slow_call_window.len() >= self.config.sliding_window_size {
            inner.slow_call_window.pop_front();
        }
        inner.slow_call_window.push_back(was_slow);

        // Update metrics
        inner.metrics.total_requests += 1;
        inner.metrics.successful_requests += 1;
        inner.metrics.consecutive_successes = inner.consecutive_successes as u32;
        inner.metrics.consecutive_failures = 0;

        // Calculate rates
        self.update_rates(&mut inner);

        drop(inner);

        self.notify_operation_result(CircuitOperationType::Success, duration, None);
    }

    fn record_failure(&self, error: &DecrustError, duration: Duration) {
        let mut inner = self.inner.write().unwrap();
        inner.consecutive_failures += 1;
        inner.consecutive_successes = 0;

        // Update sliding window
        if inner.results_window.len() >= self.config.sliding_window_size {
            inner.results_window.pop_front();
        }
        inner.results_window.push_back(false);

        // Check if the call was slow (although it failed)
        let was_slow = if let Some(threshold) = self.config.slow_call_duration_threshold {
            duration >= threshold
        } else {
            false
        };

        // Update slow call window
        if inner.slow_call_window.len() >= self.config.sliding_window_size {
            inner.slow_call_window.pop_front();
        }
        inner.slow_call_window.push_back(was_slow);

        // Update metrics
        inner.metrics.total_requests += 1;
        inner.metrics.failed_requests += 1;
        inner.metrics.consecutive_failures = inner.consecutive_failures as u32;
        inner.metrics.consecutive_successes = 0;
        inner.metrics.last_error_timestamp = Some(SystemTime::now());

        // Calculate rates
        self.update_rates(&mut inner);

        let error_clone = error.clone(); // This requires Clone for DecrustError
        drop(inner);

        self.notify_operation_result(CircuitOperationType::Failure, duration, Some(&error_clone));
    }

    fn record_rejected(&self) {
        let mut inner = self.inner.write().unwrap();
        inner.metrics.total_requests += 1;
        inner.metrics.rejected_requests += 1;
        drop(inner);

        // Zero duration since operation was rejected
        self.notify_operation_result(CircuitOperationType::Rejected, Duration::from_secs(0), None);
    }

    fn record_timeout(&self) {
        let mut inner = self.inner.write().unwrap();
        inner.consecutive_failures += 1;
        inner.consecutive_successes = 0;

        // Update sliding window
        if inner.results_window.len() >= self.config.sliding_window_size {
            inner.results_window.pop_front();
        }
        inner.results_window.push_back(false);

        // Update metrics
        inner.metrics.total_requests += 1;
        inner.metrics.timeout_requests += 1;
        inner.metrics.consecutive_failures = inner.consecutive_failures as u32;
        inner.metrics.consecutive_successes = 0;
        inner.metrics.last_error_timestamp = Some(SystemTime::now());

        // Calculate rates
        self.update_rates(&mut inner);

        drop(inner);

        let timeout_error = DecrustError::Timeout {
            operation: format!("Operation in circuit breaker '{}'", self.name),
            duration: self.config.operation_timeout.unwrap_or_default(),
            backtrace: Backtrace::generate(),
        };

        self.notify_operation_result(
            CircuitOperationType::Timeout,
            self.config.operation_timeout.unwrap_or_default(),
            Some(&timeout_error),
        );
    }

    // Helper methods

    fn should_open_circuit(&self) -> bool {
        let inner = self.inner.read().unwrap();

        // Open if consecutive failures exceed threshold
        if inner.consecutive_failures >= self.config.failure_threshold {
            return true;
        }

        // Check failure rate if we have enough samples
        if inner.results_window.len() >= self.config.minimum_request_threshold_for_rate {
            let failure_count = inner
                .results_window
                .iter()
                .filter(|&&success| !success)
                .count();
            let failure_rate = failure_count as f64 / inner.results_window.len() as f64;

            if failure_rate >= self.config.failure_rate_threshold {
                return true;
            }
        }

        // Check slow call rate if configured
        if let (Some(threshold), true) = (
            self.config.slow_call_rate_threshold,
            !inner.slow_call_window.is_empty(),
        ) {
            let slow_count = inner.slow_call_window.iter().filter(|&&slow| slow).count();
            let slow_rate = slow_count as f64 / inner.slow_call_window.len() as f64;

            if slow_rate >= threshold {
                return true;
            }
        }

        false
    }

    fn should_count_as_failure(&self, error: &DecrustError) -> bool {
        // If there's a custom predicate, use that
        if let Some(predicate) = &self.config.error_predicate {
            return (predicate.as_ref())(error);
        }

        // By default, all errors count as failures
        true
    }

    fn update_rates(&self, inner: &mut InnerState) {
        if inner.results_window.is_empty() {
            inner.metrics.failure_rate_in_window = None;
        } else {
            let failure_count = inner
                .results_window
                .iter()
                .filter(|&&success| !success)
                .count();
            let failure_rate = failure_count as f64 / inner.results_window.len() as f64;
            inner.metrics.failure_rate_in_window = Some(failure_rate);
        }

        if inner.slow_call_window.is_empty() {
            inner.metrics.slow_call_rate_in_window = None;
        } else {
            let slow_count = inner.slow_call_window.iter().filter(|&&slow| slow).count();
            let slow_rate = slow_count as f64 / inner.slow_call_window.len() as f64;
            inner.metrics.slow_call_rate_in_window = Some(slow_rate);
        }
    }

    // Observer notification methods

    fn notify_state_change(&self, event: &CircuitTransitionEvent) {
        let observers = self.observers.lock().unwrap();
        for observer in &*observers {
            observer.on_state_change(&self.name, event);
        }
    }

    fn notify_operation_attempt(&self, state: CircuitBreakerState) {
        let observers = self.observers.lock().unwrap();
        for observer in &*observers {
            observer.on_operation_attempt(&self.name, state);
        }
    }

    fn notify_operation_result(
        &self,
        op_type: CircuitOperationType,
        duration: Duration,
        error: Option<&DecrustError>,
    ) {
        let observers = self.observers.lock().unwrap();
        for observer in &*observers {
            observer.on_operation_result(&self.name, op_type, duration, error);
        }
    }
    fn notify_reset(&self) {
        let observers = self.observers.lock().unwrap();
        for observer in &*observers {
            observer.on_reset(&self.name);
        }
    }
}