rivven-cdc 0.0.2

Change Data Capture for Rivven - PostgreSQL, MySQL, MariaDB
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
//! Resilience primitives for CDC operations
//!
//! Production-grade fault tolerance:
//! - Token bucket rate limiter
//! - Circuit breaker pattern
//! - Backoff strategies
//! - Retry configuration
//! - Operational guardrails

use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use tokio::time::sleep;
use tracing::{debug, info, warn};

// ============================================================================
// Retry Configuration
// ============================================================================

/// Error types that can be automatically retried.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RetriableErrorType {
    /// Connection was lost unexpectedly
    ConnectionLost,
    /// Connection was refused by the server
    ConnectionRefused,
    /// Operation timed out
    Timeout,
    /// Database deadlock detected
    DeadlockDetected,
    /// Replication slot is in use by another process
    ReplicationSlotInUse,
    /// Temporary server failure (5xx errors)
    TemporaryFailure,
    /// Server is overloaded
    ServerOverloaded,
    /// Network unreachable
    NetworkUnreachable,
    /// DNS resolution failed
    DnsResolutionFailed,
    /// TLS handshake failed
    TlsHandshakeFailed,
}

impl RetriableErrorType {
    /// Get all default retriable error types.
    pub fn defaults() -> HashSet<Self> {
        [
            Self::ConnectionLost,
            Self::ConnectionRefused,
            Self::Timeout,
            Self::DeadlockDetected,
            Self::ReplicationSlotInUse,
            Self::TemporaryFailure,
            Self::ServerOverloaded,
        ]
        .into_iter()
        .collect()
    }
}

/// Configuration for retry behavior.
///
/// Compatible with Debezium's `errors.*` configuration options.
///
/// # Example
///
/// ```rust
/// use rivven_cdc::{RetryConfig, RetriableErrorType};
/// use std::time::Duration;
///
/// let config = RetryConfig::builder()
///     .max_retries(10)
///     .retry_delay(Duration::from_secs(1))
///     .max_delay(Duration::from_secs(60))
///     .jitter(0.25)
///     .build();
///
/// assert_eq!(config.max_retries(), 10);
/// assert!(config.is_retriable(&RetriableErrorType::ConnectionLost));
/// ```
#[derive(Debug, Clone)]
pub struct RetryConfig {
    /// Maximum retry attempts.
    /// - `-1` = infinite retries (use with caution)
    /// - `0` = retries disabled
    /// - `n` = retry up to n times
    max_retries: i32,
    /// Base delay between retries (before exponential backoff).
    retry_delay: Duration,
    /// Maximum delay cap (prevents excessive backoff).
    max_delay: Duration,
    /// Jitter factor (0.0 - 1.0) to randomize delays.
    /// Helps prevent thundering herd problems.
    jitter: f64,
    /// Error types considered retriable.
    retriable_errors: HashSet<RetriableErrorType>,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_retries: 10,
            retry_delay: Duration::from_secs(1),
            max_delay: Duration::from_secs(60),
            jitter: 0.25,
            retriable_errors: RetriableErrorType::defaults(),
        }
    }
}

impl RetryConfig {
    /// Create a builder for RetryConfig.
    pub fn builder() -> RetryConfigBuilder {
        RetryConfigBuilder::default()
    }

    /// Create a disabled retry config (no retries).
    pub fn disabled() -> Self {
        Self {
            max_retries: 0,
            ..Default::default()
        }
    }

    /// Create an infinite retry config.
    pub fn infinite() -> Self {
        Self {
            max_retries: -1,
            ..Default::default()
        }
    }

    /// Get maximum retries (-1 = infinite, 0 = disabled).
    pub fn max_retries(&self) -> i32 {
        self.max_retries
    }

    /// Get base retry delay.
    pub fn retry_delay(&self) -> Duration {
        self.retry_delay
    }

    /// Get maximum delay cap.
    pub fn max_delay(&self) -> Duration {
        self.max_delay
    }

    /// Get jitter factor.
    pub fn jitter(&self) -> f64 {
        self.jitter
    }

    /// Check if retries are enabled.
    pub fn is_enabled(&self) -> bool {
        self.max_retries != 0
    }

    /// Check if infinite retries are configured.
    pub fn is_infinite(&self) -> bool {
        self.max_retries == -1
    }

    /// Check if an error type is retriable.
    pub fn is_retriable(&self, error_type: &RetriableErrorType) -> bool {
        self.retriable_errors.contains(error_type)
    }

    /// Check if we should retry given the current attempt.
    pub fn should_retry(&self, attempt: u32) -> bool {
        if self.max_retries == -1 {
            true
        } else if self.max_retries == 0 {
            false
        } else {
            attempt < self.max_retries as u32
        }
    }

    /// Calculate delay for a given attempt (with exponential backoff and jitter).
    pub fn delay_for_attempt(&self, attempt: u32) -> Duration {
        let base = self
            .retry_delay
            .saturating_mul(2u32.saturating_pow(attempt));
        let capped = base.min(self.max_delay);

        // Apply jitter
        if self.jitter > 0.0 {
            let jitter_range = capped.as_secs_f64() * self.jitter;
            // Simple deterministic jitter based on attempt (for reproducibility)
            let jitter_offset = (attempt as f64 * 0.618033988749895) % 1.0; // Golden ratio
            let jitter_amount = jitter_range * (jitter_offset * 2.0 - 1.0);
            let adjusted = capped.as_secs_f64() + jitter_amount;
            Duration::from_secs_f64(adjusted.max(0.0))
        } else {
            capped
        }
    }
}

/// Builder for RetryConfig.
#[derive(Debug, Clone, Default)]
pub struct RetryConfigBuilder {
    max_retries: Option<i32>,
    retry_delay: Option<Duration>,
    max_delay: Option<Duration>,
    jitter: Option<f64>,
    retriable_errors: Option<HashSet<RetriableErrorType>>,
}

impl RetryConfigBuilder {
    /// Set maximum retry attempts.
    pub fn max_retries(mut self, value: i32) -> Self {
        self.max_retries = Some(value);
        self
    }

    /// Set base retry delay.
    pub fn retry_delay(mut self, value: Duration) -> Self {
        self.retry_delay = Some(value);
        self
    }

    /// Set maximum delay cap.
    pub fn max_delay(mut self, value: Duration) -> Self {
        self.max_delay = Some(value);
        self
    }

    /// Set jitter factor (0.0 - 1.0).
    pub fn jitter(mut self, value: f64) -> Self {
        self.jitter = Some(value.clamp(0.0, 1.0));
        self
    }

    /// Set retriable error types.
    pub fn retriable_errors(mut self, errors: HashSet<RetriableErrorType>) -> Self {
        self.retriable_errors = Some(errors);
        self
    }

    /// Add a retriable error type.
    pub fn add_retriable_error(mut self, error: RetriableErrorType) -> Self {
        self.retriable_errors
            .get_or_insert_with(RetriableErrorType::defaults)
            .insert(error);
        self
    }

    /// Build the RetryConfig.
    pub fn build(self) -> RetryConfig {
        let defaults = RetryConfig::default();
        RetryConfig {
            max_retries: self.max_retries.unwrap_or(defaults.max_retries),
            retry_delay: self.retry_delay.unwrap_or(defaults.retry_delay),
            max_delay: self.max_delay.unwrap_or(defaults.max_delay),
            jitter: self.jitter.unwrap_or(defaults.jitter),
            retriable_errors: self.retriable_errors.unwrap_or(defaults.retriable_errors),
        }
    }
}

// ============================================================================
// Guardrails Configuration
// ============================================================================

/// Action to take when a guardrail limit is exceeded.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GuardrailAction {
    /// Log a warning and continue operation.
    #[default]
    Warn,
    /// Skip the excess items and continue.
    Skip,
    /// Stop the connector with an error.
    Fail,
}

/// Operational guardrails to prevent runaway connectors.
///
/// These limits help protect against:
/// - Memory exhaustion from large transactions
/// - Resource exhaustion from too many tables
/// - Hanging snapshots
/// - Queue overflow
///
/// # Example
///
/// ```rust
/// use rivven_cdc::{GuardrailsConfig, GuardrailAction};
/// use std::time::Duration;
///
/// let config = GuardrailsConfig::builder()
///     .max_tables(100)
///     .max_tables_action(GuardrailAction::Fail)
///     .max_transaction_size(50_000)
///     .max_queue_depth(10_000)
///     .build();
///
/// assert_eq!(config.max_tables(), 100);
/// assert!(!config.check_tables(50).is_exceeded());
/// assert!(config.check_tables(150).is_exceeded());
/// ```
#[derive(Debug, Clone)]
pub struct GuardrailsConfig {
    /// Maximum number of tables to capture.
    max_tables: usize,
    /// Action when max_tables is exceeded.
    max_tables_action: GuardrailAction,
    /// Maximum events per transaction before flush.
    max_transaction_size: usize,
    /// Maximum memory for transaction buffer (bytes).
    max_transaction_memory: usize,
    /// Maximum queue depth before backpressure.
    max_queue_depth: usize,
    /// Maximum snapshot duration before timeout.
    max_snapshot_duration: Duration,
}

impl Default for GuardrailsConfig {
    fn default() -> Self {
        Self {
            max_tables: 10_000,
            max_tables_action: GuardrailAction::Warn,
            max_transaction_size: 100_000,
            max_transaction_memory: 256 * 1024 * 1024, // 256 MB
            max_queue_depth: 10_000,
            max_snapshot_duration: Duration::from_secs(24 * 60 * 60), // 24 hours
        }
    }
}

impl GuardrailsConfig {
    /// Create a builder for GuardrailsConfig.
    pub fn builder() -> GuardrailsConfigBuilder {
        GuardrailsConfigBuilder::default()
    }

    /// Create a permissive config (high limits).
    pub fn permissive() -> Self {
        Self {
            max_tables: usize::MAX,
            max_tables_action: GuardrailAction::Warn,
            max_transaction_size: usize::MAX,
            max_transaction_memory: usize::MAX,
            max_queue_depth: usize::MAX,
            max_snapshot_duration: Duration::from_secs(u64::MAX),
        }
    }

    /// Create a strict config (low limits).
    pub fn strict() -> Self {
        Self {
            max_tables: 100,
            max_tables_action: GuardrailAction::Fail,
            max_transaction_size: 10_000,
            max_transaction_memory: 64 * 1024 * 1024, // 64 MB
            max_queue_depth: 1_000,
            max_snapshot_duration: Duration::from_secs(60 * 60), // 1 hour
        }
    }

    /// Get max tables limit.
    pub fn max_tables(&self) -> usize {
        self.max_tables
    }

    /// Get action for max_tables exceeded.
    pub fn max_tables_action(&self) -> GuardrailAction {
        self.max_tables_action
    }

    /// Get max transaction size.
    pub fn max_transaction_size(&self) -> usize {
        self.max_transaction_size
    }

    /// Get max transaction memory.
    pub fn max_transaction_memory(&self) -> usize {
        self.max_transaction_memory
    }

    /// Get max queue depth.
    pub fn max_queue_depth(&self) -> usize {
        self.max_queue_depth
    }

    /// Get max snapshot duration.
    pub fn max_snapshot_duration(&self) -> Duration {
        self.max_snapshot_duration
    }

    /// Check if table count exceeds limit.
    pub fn check_tables(&self, count: usize) -> GuardrailCheck {
        GuardrailCheck {
            limit: self.max_tables,
            current: count,
            action: self.max_tables_action,
        }
    }

    /// Check if transaction size exceeds limit.
    pub fn check_transaction_size(&self, count: usize) -> GuardrailCheck {
        GuardrailCheck {
            limit: self.max_transaction_size,
            current: count,
            action: GuardrailAction::Warn,
        }
    }

    /// Check if transaction memory exceeds limit.
    pub fn check_transaction_memory(&self, bytes: usize) -> GuardrailCheck {
        GuardrailCheck {
            limit: self.max_transaction_memory,
            current: bytes,
            action: GuardrailAction::Warn,
        }
    }

    /// Check if queue depth exceeds limit.
    pub fn check_queue_depth(&self, depth: usize) -> GuardrailCheck {
        GuardrailCheck {
            limit: self.max_queue_depth,
            current: depth,
            action: GuardrailAction::Warn,
        }
    }

    /// Check if snapshot duration exceeds limit.
    pub fn check_snapshot_duration(&self, duration: Duration) -> bool {
        duration > self.max_snapshot_duration
    }
}

/// Result of a guardrail check.
#[derive(Debug, Clone, Copy)]
pub struct GuardrailCheck {
    /// The configured limit.
    pub limit: usize,
    /// The current value.
    pub current: usize,
    /// The action to take if exceeded.
    pub action: GuardrailAction,
}

impl GuardrailCheck {
    /// Check if the limit is exceeded.
    pub fn is_exceeded(&self) -> bool {
        self.current > self.limit
    }

    /// Get the excess amount (0 if not exceeded).
    pub fn excess(&self) -> usize {
        self.current.saturating_sub(self.limit)
    }

    /// Execute the configured action.
    pub fn execute(&self) -> Result<()> {
        if !self.is_exceeded() {
            return Ok(());
        }

        match self.action {
            GuardrailAction::Warn => {
                warn!(
                    "Guardrail exceeded: {} > {} (limit)",
                    self.current, self.limit
                );
                Ok(())
            }
            GuardrailAction::Skip => {
                info!(
                    "Guardrail exceeded: {} > {} (skipping excess)",
                    self.current, self.limit
                );
                Ok(())
            }
            GuardrailAction::Fail => Err(anyhow!(
                "Guardrail exceeded: {} > {} (failing)",
                self.current,
                self.limit
            )),
        }
    }
}

/// Builder for GuardrailsConfig.
#[derive(Debug, Clone, Default)]
pub struct GuardrailsConfigBuilder {
    max_tables: Option<usize>,
    max_tables_action: Option<GuardrailAction>,
    max_transaction_size: Option<usize>,
    max_transaction_memory: Option<usize>,
    max_queue_depth: Option<usize>,
    max_snapshot_duration: Option<Duration>,
}

impl GuardrailsConfigBuilder {
    /// Set max tables limit.
    pub fn max_tables(mut self, value: usize) -> Self {
        self.max_tables = Some(value);
        self
    }

    /// Set action when max_tables is exceeded.
    pub fn max_tables_action(mut self, action: GuardrailAction) -> Self {
        self.max_tables_action = Some(action);
        self
    }

    /// Set max transaction size.
    pub fn max_transaction_size(mut self, value: usize) -> Self {
        self.max_transaction_size = Some(value);
        self
    }

    /// Set max transaction memory.
    pub fn max_transaction_memory(mut self, value: usize) -> Self {
        self.max_transaction_memory = Some(value);
        self
    }

    /// Set max queue depth.
    pub fn max_queue_depth(mut self, value: usize) -> Self {
        self.max_queue_depth = Some(value);
        self
    }

    /// Set max snapshot duration.
    pub fn max_snapshot_duration(mut self, value: Duration) -> Self {
        self.max_snapshot_duration = Some(value);
        self
    }

    /// Build the GuardrailsConfig.
    pub fn build(self) -> GuardrailsConfig {
        let defaults = GuardrailsConfig::default();
        GuardrailsConfig {
            max_tables: self.max_tables.unwrap_or(defaults.max_tables),
            max_tables_action: self.max_tables_action.unwrap_or(defaults.max_tables_action),
            max_transaction_size: self
                .max_transaction_size
                .unwrap_or(defaults.max_transaction_size),
            max_transaction_memory: self
                .max_transaction_memory
                .unwrap_or(defaults.max_transaction_memory),
            max_queue_depth: self.max_queue_depth.unwrap_or(defaults.max_queue_depth),
            max_snapshot_duration: self
                .max_snapshot_duration
                .unwrap_or(defaults.max_snapshot_duration),
        }
    }
}

// ============================================================================
// Token Bucket Rate Limiter
// ============================================================================

/// Token bucket rate limiter for CDC event processing
///
/// Prevents resource exhaustion by limiting events/sec per connection.
///
/// # Example
///
/// ```rust
/// use rivven_cdc::RateLimiter;
///
/// # tokio_test::block_on(async {
/// let limiter = RateLimiter::new(100, 1000); // 100 burst, 1000/sec refill
///
/// if limiter.try_acquire().await.is_ok() {
///     // Process event
/// }
/// # });
/// ```
pub struct RateLimiter {
    /// Maximum tokens (burst capacity)
    capacity: u32,
    /// Current token count
    tokens: AtomicU32,
    /// Refill rate (tokens per second)
    refill_rate: u32,
    /// Last refill timestamp
    last_refill: RwLock<Instant>,
}

impl RateLimiter {
    /// Create a new rate limiter
    ///
    /// # Arguments
    /// * `capacity` - Maximum burst size (e.g., 1000 events)
    /// * `refill_rate` - Events per second (e.g., 10000 events/sec)
    pub fn new(capacity: u32, refill_rate: u32) -> Self {
        Self {
            capacity,
            tokens: AtomicU32::new(capacity),
            refill_rate,
            last_refill: RwLock::new(Instant::now()),
        }
    }

    /// Acquire a token (non-blocking)
    ///
    /// Returns `Ok(())` if token acquired, `Err` if rate limit exceeded.
    pub async fn try_acquire(&self) -> Result<()> {
        self.refill().await;

        loop {
            let current = self.tokens.load(Ordering::SeqCst);
            if current == 0 {
                return Err(anyhow!("Rate limit exceeded"));
            }

            if self
                .tokens
                .compare_exchange(current, current - 1, Ordering::SeqCst, Ordering::SeqCst)
                .is_ok()
            {
                return Ok(());
            }
        }
    }

    /// Acquire a token (blocking with timeout)
    pub async fn acquire_timeout(&self, timeout: Duration) -> Result<()> {
        let start = Instant::now();

        loop {
            if self.try_acquire().await.is_ok() {
                return Ok(());
            }

            if start.elapsed() > timeout {
                return Err(anyhow!("Rate limiter timeout after {:?}", timeout));
            }

            // Wait a bit before retrying
            sleep(Duration::from_millis(10)).await;
        }
    }

    /// Refill tokens based on elapsed time
    async fn refill(&self) {
        let mut last_refill = self.last_refill.write().await;
        let now = Instant::now();
        let elapsed = now.duration_since(*last_refill);

        // Calculate tokens to add
        let tokens_to_add = (elapsed.as_secs_f64() * self.refill_rate as f64) as u32;

        if tokens_to_add > 0 {
            let current = self.tokens.load(Ordering::SeqCst);
            let new_tokens = (current + tokens_to_add).min(self.capacity);
            self.tokens.store(new_tokens, Ordering::SeqCst);
            *last_refill = now;
        }
    }

    /// Get current token count (for monitoring)
    pub fn available_tokens(&self) -> u32 {
        self.tokens.load(Ordering::SeqCst)
    }
}

/// Circuit breaker states
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CircuitState {
    /// Normal operation - requests allowed
    Closed,
    /// Too many failures - requests rejected
    Open,
    /// Testing if service recovered
    HalfOpen,
}

/// Circuit breaker for fault tolerance
///
/// Prevents cascading failures by stopping requests to failing services.
///
/// # Example
///
/// ```rust
/// use rivven_cdc::CircuitBreaker;
/// use std::time::Duration;
///
/// # tokio_test::block_on(async {
/// let cb = CircuitBreaker::new(5, Duration::from_secs(30), 2);
///
/// if cb.allow_request().await {
///     // Make request
///     // On success:
///     cb.record_success().await;
///     // On failure:
///     // cb.record_failure().await;
/// }
/// # });
/// ```
pub struct CircuitBreaker {
    /// Failure threshold before opening circuit
    failure_threshold: u32,
    /// Current failure count
    failure_count: AtomicU32,
    /// Current circuit state (0=Closed, 1=Open, 2=HalfOpen)
    state: AtomicU32,
    /// Time when circuit was opened
    open_time: RwLock<Option<Instant>>,
    /// How long to wait before trying half-open
    timeout: Duration,
    /// Success count in half-open state
    half_open_success_count: AtomicU32,
    /// Required successes to close circuit
    success_threshold: u32,
}

impl CircuitBreaker {
    /// Create a new circuit breaker
    ///
    /// # Arguments
    /// * `failure_threshold` - Number of failures before opening circuit
    /// * `timeout` - How long to wait in Open state before trying HalfOpen
    /// * `success_threshold` - Number of successes in HalfOpen to close circuit
    pub fn new(failure_threshold: u32, timeout: Duration, success_threshold: u32) -> Self {
        Self {
            failure_threshold,
            failure_count: AtomicU32::new(0),
            state: AtomicU32::new(0), // Closed
            open_time: RwLock::new(None),
            timeout,
            half_open_success_count: AtomicU32::new(0),
            success_threshold,
        }
    }

    /// Check if request is allowed
    pub async fn allow_request(&self) -> bool {
        let state = self.get_state();

        match state {
            CircuitState::Closed => true,
            CircuitState::Open => {
                // Check if timeout elapsed
                let open_time = self.open_time.read().await;
                if let Some(t) = *open_time {
                    if t.elapsed() > self.timeout {
                        drop(open_time); // Release read lock
                        self.transition_to_half_open().await;
                        return true;
                    }
                }
                false
            }
            CircuitState::HalfOpen => true,
        }
    }

    /// Record a successful request
    pub async fn record_success(&self) {
        let state = self.get_state();

        match state {
            CircuitState::Closed => {
                self.failure_count.store(0, Ordering::SeqCst);
            }
            CircuitState::HalfOpen => {
                let successes = self.half_open_success_count.fetch_add(1, Ordering::SeqCst) + 1;
                if successes >= self.success_threshold {
                    self.transition_to_closed().await;
                }
            }
            CircuitState::Open => {}
        }
    }

    /// Record a failed request
    pub async fn record_failure(&self) {
        let state = self.get_state();

        match state {
            CircuitState::Closed => {
                let failures = self.failure_count.fetch_add(1, Ordering::SeqCst) + 1;
                if failures >= self.failure_threshold {
                    self.transition_to_open().await;
                }
            }
            CircuitState::HalfOpen => {
                self.transition_to_open().await;
            }
            CircuitState::Open => {}
        }
    }

    /// Get current state
    pub fn get_state(&self) -> CircuitState {
        match self.state.load(Ordering::SeqCst) {
            0 => CircuitState::Closed,
            1 => CircuitState::Open,
            2 => CircuitState::HalfOpen,
            _ => CircuitState::Closed,
        }
    }

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

    async fn transition_to_open(&self) {
        warn!("Circuit breaker transitioning to OPEN state");
        self.state.store(1, Ordering::SeqCst);
        let mut open_time = self.open_time.write().await;
        *open_time = Some(Instant::now());
    }

    async fn transition_to_half_open(&self) {
        debug!("Circuit breaker transitioning to HALF_OPEN state");
        self.state.store(2, Ordering::SeqCst);
        self.half_open_success_count.store(0, Ordering::SeqCst);
    }

    async fn transition_to_closed(&self) {
        debug!("Circuit breaker transitioning to CLOSED state");
        self.state.store(0, Ordering::SeqCst);
        self.failure_count.store(0, Ordering::SeqCst);
        self.half_open_success_count.store(0, Ordering::SeqCst);
    }
}

/// Exponential backoff with jitter
pub struct ExponentialBackoff {
    base: Duration,
    max: Duration,
    attempt: u32,
}

impl ExponentialBackoff {
    /// Create a new exponential backoff
    pub fn new(base: Duration, max: Duration) -> Self {
        Self {
            base,
            max,
            attempt: 0,
        }
    }

    /// Get the next backoff duration
    pub fn next_backoff(&mut self) -> Duration {
        let backoff = self.base.saturating_mul(2u32.saturating_pow(self.attempt));
        self.attempt += 1;
        backoff.min(self.max)
    }

    /// Reset the backoff
    pub fn reset(&mut self) {
        self.attempt = 0;
    }

    /// Get current attempt number
    pub fn attempt(&self) -> u32 {
        self.attempt
    }
}

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

    // ========================================================================
    // RetryConfig Tests
    // ========================================================================

    #[test]
    fn test_retry_config_default() {
        let config = RetryConfig::default();
        assert_eq!(config.max_retries(), 10);
        assert_eq!(config.retry_delay(), Duration::from_secs(1));
        assert_eq!(config.max_delay(), Duration::from_secs(60));
        assert!((config.jitter() - 0.25).abs() < f64::EPSILON);
        assert!(config.is_enabled());
        assert!(!config.is_infinite());
    }

    #[test]
    fn test_retry_config_disabled() {
        let config = RetryConfig::disabled();
        assert_eq!(config.max_retries(), 0);
        assert!(!config.is_enabled());
        assert!(!config.is_infinite());
        assert!(!config.should_retry(0));
    }

    #[test]
    fn test_retry_config_infinite() {
        let config = RetryConfig::infinite();
        assert_eq!(config.max_retries(), -1);
        assert!(config.is_enabled());
        assert!(config.is_infinite());
        assert!(config.should_retry(1000));
    }

    #[test]
    fn test_retry_config_builder() {
        let config = RetryConfig::builder()
            .max_retries(5)
            .retry_delay(Duration::from_millis(500))
            .max_delay(Duration::from_secs(30))
            .jitter(0.1)
            .build();

        assert_eq!(config.max_retries(), 5);
        assert_eq!(config.retry_delay(), Duration::from_millis(500));
        assert_eq!(config.max_delay(), Duration::from_secs(30));
        assert!((config.jitter() - 0.1).abs() < f64::EPSILON);
    }

    #[test]
    fn test_retry_config_should_retry() {
        let config = RetryConfig::builder().max_retries(3).build();

        assert!(config.should_retry(0));
        assert!(config.should_retry(1));
        assert!(config.should_retry(2));
        assert!(!config.should_retry(3));
        assert!(!config.should_retry(4));
    }

    #[test]
    fn test_retry_config_is_retriable() {
        let config = RetryConfig::default();

        assert!(config.is_retriable(&RetriableErrorType::ConnectionLost));
        assert!(config.is_retriable(&RetriableErrorType::Timeout));
        assert!(config.is_retriable(&RetriableErrorType::DeadlockDetected));
        // Not in defaults
        assert!(!config.is_retriable(&RetriableErrorType::NetworkUnreachable));
    }

    #[test]
    fn test_retry_config_delay_for_attempt() {
        let config = RetryConfig::builder()
            .retry_delay(Duration::from_millis(100))
            .max_delay(Duration::from_secs(5))
            .jitter(0.0) // Disable jitter for predictable testing
            .build();

        assert_eq!(config.delay_for_attempt(0), Duration::from_millis(100));
        assert_eq!(config.delay_for_attempt(1), Duration::from_millis(200));
        assert_eq!(config.delay_for_attempt(2), Duration::from_millis(400));
        assert_eq!(config.delay_for_attempt(3), Duration::from_millis(800));

        // Should cap at max_delay
        assert_eq!(config.delay_for_attempt(10), Duration::from_secs(5));
    }

    #[test]
    fn test_retriable_error_type_defaults() {
        let defaults = RetriableErrorType::defaults();

        assert!(defaults.contains(&RetriableErrorType::ConnectionLost));
        assert!(defaults.contains(&RetriableErrorType::Timeout));
        assert!(defaults.contains(&RetriableErrorType::DeadlockDetected));
        assert!(!defaults.contains(&RetriableErrorType::NetworkUnreachable));
    }

    // ========================================================================
    // GuardrailsConfig Tests
    // ========================================================================

    #[test]
    fn test_guardrails_config_default() {
        let config = GuardrailsConfig::default();

        assert_eq!(config.max_tables(), 10_000);
        assert_eq!(config.max_tables_action(), GuardrailAction::Warn);
        assert_eq!(config.max_transaction_size(), 100_000);
        assert_eq!(config.max_transaction_memory(), 256 * 1024 * 1024);
        assert_eq!(config.max_queue_depth(), 10_000);
        assert_eq!(
            config.max_snapshot_duration(),
            Duration::from_secs(24 * 60 * 60)
        );
    }

    #[test]
    fn test_guardrails_config_permissive() {
        let config = GuardrailsConfig::permissive();

        assert_eq!(config.max_tables(), usize::MAX);
        assert!(!config.check_tables(1_000_000).is_exceeded());
    }

    #[test]
    fn test_guardrails_config_strict() {
        let config = GuardrailsConfig::strict();

        assert_eq!(config.max_tables(), 100);
        assert_eq!(config.max_tables_action(), GuardrailAction::Fail);
        assert!(config.check_tables(150).is_exceeded());
    }

    #[test]
    fn test_guardrails_config_builder() {
        let config = GuardrailsConfig::builder()
            .max_tables(500)
            .max_tables_action(GuardrailAction::Skip)
            .max_transaction_size(50_000)
            .build();

        assert_eq!(config.max_tables(), 500);
        assert_eq!(config.max_tables_action(), GuardrailAction::Skip);
        assert_eq!(config.max_transaction_size(), 50_000);
    }

    #[test]
    fn test_guardrail_check_not_exceeded() {
        let config = GuardrailsConfig::builder().max_tables(100).build();

        let check = config.check_tables(50);
        assert!(!check.is_exceeded());
        assert_eq!(check.excess(), 0);
        assert!(check.execute().is_ok());
    }

    #[test]
    fn test_guardrail_check_exceeded_warn() {
        let config = GuardrailsConfig::builder()
            .max_tables(100)
            .max_tables_action(GuardrailAction::Warn)
            .build();

        let check = config.check_tables(150);
        assert!(check.is_exceeded());
        assert_eq!(check.excess(), 50);
        assert!(check.execute().is_ok()); // Warn doesn't fail
    }

    #[test]
    fn test_guardrail_check_exceeded_fail() {
        let config = GuardrailsConfig::builder()
            .max_tables(100)
            .max_tables_action(GuardrailAction::Fail)
            .build();

        let check = config.check_tables(150);
        assert!(check.is_exceeded());
        assert!(check.execute().is_err()); // Fail returns error
    }

    #[test]
    fn test_guardrails_check_transaction_size() {
        let config = GuardrailsConfig::builder()
            .max_transaction_size(1000)
            .build();

        assert!(!config.check_transaction_size(500).is_exceeded());
        assert!(config.check_transaction_size(1500).is_exceeded());
    }

    #[test]
    fn test_guardrails_check_queue_depth() {
        let config = GuardrailsConfig::builder().max_queue_depth(100).build();

        assert!(!config.check_queue_depth(50).is_exceeded());
        assert!(config.check_queue_depth(150).is_exceeded());
    }

    #[test]
    fn test_guardrails_check_snapshot_duration() {
        let config = GuardrailsConfig::builder()
            .max_snapshot_duration(Duration::from_secs(60))
            .build();

        assert!(!config.check_snapshot_duration(Duration::from_secs(30)));
        assert!(config.check_snapshot_duration(Duration::from_secs(90)));
    }

    // ========================================================================
    // Rate Limiter Tests
    // ========================================================================

    #[tokio::test]
    async fn test_rate_limiter_burst() {
        let limiter = RateLimiter::new(10, 100);

        // Should allow 10 immediate requests
        for _ in 0..10 {
            assert!(limiter.try_acquire().await.is_ok());
        }

        // 11th should fail
        assert!(limiter.try_acquire().await.is_err());
    }

    #[tokio::test]
    async fn test_rate_limiter_refill() {
        let limiter = RateLimiter::new(10, 10); // 10 tokens/sec

        // Exhaust tokens
        for _ in 0..10 {
            limiter.try_acquire().await.ok();
        }

        // Wait for refill
        sleep(Duration::from_millis(1100)).await;

        // Should have ~10 tokens available
        assert!(limiter.try_acquire().await.is_ok());
    }

    // ========================================================================
    // Circuit Breaker Tests
    // ========================================================================

    #[tokio::test]
    async fn test_circuit_breaker_open() {
        let cb = CircuitBreaker::new(3, Duration::from_secs(1), 2);

        // Initial state: closed
        assert_eq!(cb.get_state(), CircuitState::Closed);
        assert!(cb.allow_request().await);

        // Record failures
        for _ in 0..3 {
            cb.record_failure().await;
        }

        // Should be open now
        assert_eq!(cb.get_state(), CircuitState::Open);
        assert!(!cb.allow_request().await);
    }

    #[tokio::test]
    async fn test_circuit_breaker_recovery() {
        let cb = CircuitBreaker::new(2, Duration::from_millis(100), 2);

        // Open the circuit
        cb.record_failure().await;
        cb.record_failure().await;
        assert_eq!(cb.get_state(), CircuitState::Open);

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

        // Should allow request (half-open)
        assert!(cb.allow_request().await);
        assert_eq!(cb.get_state(), CircuitState::HalfOpen);

        // Record successes
        cb.record_success().await;
        cb.record_success().await;

        // Should be closed now
        assert_eq!(cb.get_state(), CircuitState::Closed);
    }

    // ========================================================================
    // Exponential Backoff Tests
    // ========================================================================

    #[test]
    fn test_exponential_backoff() {
        let mut backoff =
            ExponentialBackoff::new(Duration::from_millis(100), Duration::from_secs(10));

        assert_eq!(backoff.next_backoff(), Duration::from_millis(100));
        assert_eq!(backoff.next_backoff(), Duration::from_millis(200));
        assert_eq!(backoff.next_backoff(), Duration::from_millis(400));

        backoff.reset();
        assert_eq!(backoff.next_backoff(), Duration::from_millis(100));
    }

    #[test]
    fn test_exponential_backoff_max() {
        let mut backoff = ExponentialBackoff::new(Duration::from_secs(1), Duration::from_secs(5));

        for _ in 0..10 {
            let d = backoff.next_backoff();
            assert!(d <= Duration::from_secs(5));
        }
    }
}