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
//! # CDC Health Monitoring
//!
//! Health checks and auto-recovery for CDC sources.
//!
//! ## Features
//!
//! - **Connection Monitoring**: Detect disconnections
//! - **Lag Monitoring**: Track replication lag
//! - **Auto-Recovery**: Automatic reconnection with backoff
//! - **Health Checks**: Liveness and readiness probes
//!
//! ## Usage
//!
//! ```ignore
//! use rivven_cdc::common::{HealthMonitor, HealthConfig};
//!
//! let config = HealthConfig::default();
//! let monitor = HealthMonitor::new(config);
//!
//! // Register health check
//! monitor.register_check("database", || async {
//!     // Check database connection
//!     Ok(())
//! });
//!
//! // Start monitoring
//! monitor.start().await;
//!
//! // Check health
//! let status = monitor.status().await;
//! println!("Healthy: {}", status.is_healthy);
//! ```

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use tokio::time::interval;
use tracing::{debug, info, warn};

/// Health check result.
#[derive(Debug, Clone)]
pub enum HealthCheckResult {
    /// Check passed
    Healthy,
    /// Check passed with warning
    Degraded(String),
    /// Check failed
    Unhealthy(String),
}

impl HealthCheckResult {
    pub fn is_healthy(&self) -> bool {
        matches!(self, HealthCheckResult::Healthy)
    }

    pub fn is_degraded(&self) -> bool {
        matches!(self, HealthCheckResult::Degraded(_))
    }

    pub fn is_unhealthy(&self) -> bool {
        matches!(self, HealthCheckResult::Unhealthy(_))
    }
}

/// Type alias for async health check functions.
pub type HealthCheckFn =
    Box<dyn Fn() -> Pin<Box<dyn Future<Output = HealthCheckResult> + Send>> + Send + Sync>;

/// Configuration for health monitoring.
#[derive(Debug, Clone)]
pub struct HealthConfig {
    /// Interval between health checks
    pub check_interval: Duration,
    /// Maximum allowed replication lag
    pub max_lag_ms: u64,
    /// Number of failed checks before unhealthy
    pub failure_threshold: u32,
    /// Number of successful checks to recover
    pub success_threshold: u32,
    /// Timeout for individual health checks
    pub check_timeout: Duration,
    /// Enable auto-recovery
    pub auto_recovery: bool,
    /// Initial recovery delay
    pub recovery_delay: Duration,
    /// Maximum recovery delay
    pub max_recovery_delay: Duration,
}

impl Default for HealthConfig {
    fn default() -> Self {
        Self {
            check_interval: Duration::from_secs(10),
            max_lag_ms: 30_000, // 30 seconds
            failure_threshold: 3,
            success_threshold: 2,
            check_timeout: Duration::from_secs(5),
            auto_recovery: true,
            recovery_delay: Duration::from_secs(1),
            max_recovery_delay: Duration::from_secs(60),
        }
    }
}

impl HealthConfig {
    pub fn strict() -> Self {
        Self {
            check_interval: Duration::from_secs(5),
            max_lag_ms: 10_000,
            failure_threshold: 2,
            success_threshold: 3,
            ..Default::default()
        }
    }

    pub fn relaxed() -> Self {
        Self {
            check_interval: Duration::from_secs(30),
            max_lag_ms: 60_000,
            failure_threshold: 5,
            success_threshold: 1,
            ..Default::default()
        }
    }
}

/// Overall health status.
#[derive(Debug, Clone)]
pub struct HealthStatus {
    /// Whether the system is healthy
    pub is_healthy: bool,
    /// Whether the system is ready to serve
    pub is_ready: bool,
    /// Individual check results
    pub checks: HashMap<String, CheckStatus>,
    /// Current replication lag
    pub lag_ms: u64,
    /// Last successful check time
    pub last_healthy: Option<Instant>,
    /// Number of consecutive failures
    pub consecutive_failures: u32,
    /// Number of consecutive successes
    pub consecutive_successes: u32,
    /// Uptime
    pub uptime: Duration,
}

/// Status of an individual health check.
#[derive(Debug, Clone)]
pub struct CheckStatus {
    pub name: String,
    pub result: HealthCheckResult,
    pub last_check: Instant,
    pub duration: Duration,
}

/// Health monitor that tracks system health and coordinates recovery.
pub struct HealthMonitor {
    config: HealthConfig,
    checks: RwLock<HashMap<String, HealthCheckFn>>,
    state: Arc<MonitorState>,
    start_time: Instant,
}

struct MonitorState {
    healthy: AtomicBool,
    ready: AtomicBool,
    lag_ms: AtomicU64,
    consecutive_failures: AtomicU64,
    consecutive_successes: AtomicU64,
    last_healthy: RwLock<Option<Instant>>,
    check_results: RwLock<HashMap<String, CheckStatus>>,
    #[allow(dead_code)] // Reserved for recovery coordinator integration
    recovery_in_progress: AtomicBool,
}

impl HealthMonitor {
    /// Create a new health monitor.
    pub fn new(config: HealthConfig) -> Self {
        Self {
            config,
            checks: RwLock::new(HashMap::new()),
            state: Arc::new(MonitorState {
                healthy: AtomicBool::new(false),
                ready: AtomicBool::new(false),
                lag_ms: AtomicU64::new(0),
                consecutive_failures: AtomicU64::new(0),
                consecutive_successes: AtomicU64::new(0),
                last_healthy: RwLock::new(None),
                check_results: RwLock::new(HashMap::new()),
                recovery_in_progress: AtomicBool::new(false),
            }),
            start_time: Instant::now(),
        }
    }

    /// Register a health check.
    pub async fn register_check<F, Fut>(&self, name: &str, check: F)
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = HealthCheckResult> + Send + 'static,
    {
        let mut checks = self.checks.write().await;
        checks.insert(name.to_string(), Box::new(move || Box::pin(check())));
        debug!("Registered health check: {}", name);
    }

    /// Unregister a health check.
    pub async fn unregister_check(&self, name: &str) {
        let mut checks = self.checks.write().await;
        checks.remove(name);
    }

    /// Run all health checks once.
    pub async fn check(&self) -> HealthStatus {
        let checks = self.checks.read().await;
        let mut results = HashMap::new();
        let mut all_healthy = true;

        for (name, check_fn) in checks.iter() {
            let start = Instant::now();

            let result = tokio::time::timeout(self.config.check_timeout, check_fn())
                .await
                .unwrap_or_else(|_| HealthCheckResult::Unhealthy("Timeout".to_string()));

            let duration = start.elapsed();

            if !result.is_healthy() {
                all_healthy = false;
                if result.is_unhealthy() {
                    warn!("Health check '{}' failed: {:?}", name, result);
                }
            }

            let status = CheckStatus {
                name: name.clone(),
                result: result.clone(),
                last_check: Instant::now(),
                duration,
            };

            results.insert(name.clone(), status);
        }

        // Check lag threshold
        let lag_ms = self.state.lag_ms.load(Ordering::Relaxed);
        if lag_ms > self.config.max_lag_ms {
            all_healthy = false;
            results.insert(
                "replication_lag".to_string(),
                CheckStatus {
                    name: "replication_lag".to_string(),
                    result: HealthCheckResult::Unhealthy(format!(
                        "Lag {}ms exceeds threshold {}ms",
                        lag_ms, self.config.max_lag_ms
                    )),
                    last_check: Instant::now(),
                    duration: Duration::ZERO,
                },
            );
        }

        // Update state
        if all_healthy {
            self.state
                .consecutive_successes
                .fetch_add(1, Ordering::Relaxed);
            self.state.consecutive_failures.store(0, Ordering::Relaxed);

            let successes = self.state.consecutive_successes.load(Ordering::Relaxed);
            if successes >= self.config.success_threshold as u64 {
                self.state.healthy.store(true, Ordering::Relaxed);
                self.state.ready.store(true, Ordering::Relaxed);
                *self.state.last_healthy.write().await = Some(Instant::now());
            }
        } else {
            self.state
                .consecutive_failures
                .fetch_add(1, Ordering::Relaxed);
            self.state.consecutive_successes.store(0, Ordering::Relaxed);

            let failures = self.state.consecutive_failures.load(Ordering::Relaxed);
            if failures >= self.config.failure_threshold as u64 {
                self.state.healthy.store(false, Ordering::Relaxed);
            }
        }

        // Store results
        *self.state.check_results.write().await = results.clone();

        HealthStatus {
            is_healthy: self.state.healthy.load(Ordering::Relaxed),
            is_ready: self.state.ready.load(Ordering::Relaxed),
            checks: results,
            lag_ms,
            last_healthy: *self.state.last_healthy.read().await,
            consecutive_failures: self.state.consecutive_failures.load(Ordering::Relaxed) as u32,
            consecutive_successes: self.state.consecutive_successes.load(Ordering::Relaxed) as u32,
            uptime: self.start_time.elapsed(),
        }
    }

    /// Get current health status without running checks.
    pub async fn status(&self) -> HealthStatus {
        let results = self.state.check_results.read().await.clone();
        HealthStatus {
            is_healthy: self.state.healthy.load(Ordering::Relaxed),
            is_ready: self.state.ready.load(Ordering::Relaxed),
            checks: results,
            lag_ms: self.state.lag_ms.load(Ordering::Relaxed),
            last_healthy: *self.state.last_healthy.read().await,
            consecutive_failures: self.state.consecutive_failures.load(Ordering::Relaxed) as u32,
            consecutive_successes: self.state.consecutive_successes.load(Ordering::Relaxed) as u32,
            uptime: self.start_time.elapsed(),
        }
    }

    /// Update replication lag.
    pub fn set_lag(&self, lag_ms: u64) {
        self.state.lag_ms.store(lag_ms, Ordering::Relaxed);
    }

    /// Check if system is healthy.
    pub fn is_healthy(&self) -> bool {
        self.state.healthy.load(Ordering::Relaxed)
    }

    /// Check if system is ready.
    pub fn is_ready(&self) -> bool {
        self.state.ready.load(Ordering::Relaxed)
    }

    /// Mark system as connected (healthy).
    pub fn mark_connected(&self) {
        self.state.healthy.store(true, Ordering::Relaxed);
        self.state.ready.store(true, Ordering::Relaxed);
        self.state.consecutive_failures.store(0, Ordering::Relaxed);
        info!("System marked as connected and healthy");
    }

    /// Mark system as disconnected (unhealthy).
    pub fn mark_disconnected(&self) {
        self.state.healthy.store(false, Ordering::Relaxed);
        warn!("System marked as disconnected");
    }

    /// Spawn background health check task.
    pub fn spawn_monitor(self: Arc<Self>) -> tokio::task::JoinHandle<()> {
        let config = self.config.clone();
        tokio::spawn(async move {
            let mut interval = interval(config.check_interval);
            loop {
                interval.tick().await;
                self.check().await;
            }
        })
    }
}

/// Recovery coordinator for handling reconnection with exponential backoff.
pub struct RecoveryCoordinator {
    config: HealthConfig,
    current_delay: RwLock<Duration>,
    attempts: AtomicU64,
    in_progress: AtomicBool,
}

impl RecoveryCoordinator {
    pub fn new(config: HealthConfig) -> Self {
        Self {
            current_delay: RwLock::new(config.recovery_delay),
            config,
            attempts: AtomicU64::new(0),
            in_progress: AtomicBool::new(false),
        }
    }

    /// Attempt recovery with a recovery function.
    pub async fn recover<F, Fut>(&self, recover_fn: F) -> bool
    where
        F: Fn() -> Fut,
        Fut: Future<Output = bool>,
    {
        if self
            .in_progress
            .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
            .is_err()
        {
            debug!("Recovery already in progress");
            return false;
        }

        let attempt = self.attempts.fetch_add(1, Ordering::Relaxed) + 1;
        let delay = *self.current_delay.read().await;

        info!(
            "Starting recovery attempt {} after {:?} delay",
            attempt, delay
        );

        tokio::time::sleep(delay).await;

        let success = recover_fn().await;

        if success {
            info!("Recovery successful on attempt {}", attempt);
            self.reset().await;
        } else {
            warn!("Recovery failed on attempt {}", attempt);
            self.increase_delay().await;
        }

        self.in_progress.store(false, Ordering::Release);
        success
    }

    /// Increase delay with exponential backoff.
    async fn increase_delay(&self) {
        let mut delay = self.current_delay.write().await;
        let new_delay = (*delay * 2).min(self.config.max_recovery_delay);
        *delay = new_delay;
    }

    /// Reset recovery state after success.
    async fn reset(&self) {
        *self.current_delay.write().await = self.config.recovery_delay;
        self.attempts.store(0, Ordering::Relaxed);
    }

    /// Get current attempt count.
    pub fn attempts(&self) -> u64 {
        self.attempts.load(Ordering::Relaxed)
    }

    /// Check if recovery is in progress.
    pub fn is_recovering(&self) -> bool {
        self.in_progress.load(Ordering::Relaxed)
    }
}

/// Kubernetes-compatible health endpoint responses.
impl HealthStatus {
    /// Liveness probe (is the process alive?).
    pub fn liveness(&self) -> (u16, &'static str) {
        if self.consecutive_failures < 10 {
            (200, "OK")
        } else {
            (503, "Service Unavailable")
        }
    }

    /// Readiness probe (can we serve traffic?).
    pub fn readiness(&self) -> (u16, &'static str) {
        if self.is_ready {
            (200, "OK")
        } else {
            (503, "Service Unavailable")
        }
    }

    /// Format as JSON for health endpoints.
    pub fn to_json(&self) -> String {
        let checks: HashMap<String, String> = self
            .checks
            .iter()
            .map(|(k, v)| {
                (
                    k.clone(),
                    match &v.result {
                        HealthCheckResult::Healthy => "healthy".to_string(),
                        HealthCheckResult::Degraded(msg) => format!("degraded: {}", msg),
                        HealthCheckResult::Unhealthy(msg) => format!("unhealthy: {}", msg),
                    },
                )
            })
            .collect();

        serde_json::json!({
            "status": if self.is_healthy { "healthy" } else { "unhealthy" },
            "ready": self.is_ready,
            "lag_ms": self.lag_ms,
            "uptime_secs": self.uptime.as_secs(),
            "consecutive_failures": self.consecutive_failures,
            "checks": checks
        })
        .to_string()
    }
}

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

    #[test]
    fn test_health_check_result() {
        assert!(HealthCheckResult::Healthy.is_healthy());
        assert!(!HealthCheckResult::Healthy.is_degraded());
        assert!(!HealthCheckResult::Healthy.is_unhealthy());

        assert!(!HealthCheckResult::Degraded("test".into()).is_healthy());
        assert!(HealthCheckResult::Degraded("test".into()).is_degraded());

        assert!(HealthCheckResult::Unhealthy("test".into()).is_unhealthy());
    }

    #[test]
    fn test_health_config_presets() {
        let strict = HealthConfig::strict();
        assert_eq!(strict.failure_threshold, 2);

        let relaxed = HealthConfig::relaxed();
        assert_eq!(relaxed.failure_threshold, 5);
    }

    #[tokio::test]
    async fn test_health_monitor_basic() {
        let monitor = HealthMonitor::new(HealthConfig::default());

        // Initially not healthy (no successful checks)
        assert!(!monitor.is_healthy());

        // Register a healthy check
        monitor
            .register_check("test", || async { HealthCheckResult::Healthy })
            .await;

        // Run checks multiple times to pass threshold
        for _ in 0..3 {
            monitor.check().await;
        }

        assert!(monitor.is_healthy());
    }

    #[tokio::test]
    async fn test_health_monitor_failure() {
        let config = HealthConfig {
            failure_threshold: 2,
            success_threshold: 1,
            ..Default::default()
        };
        let monitor = HealthMonitor::new(config);

        // Start healthy
        monitor.mark_connected();
        assert!(monitor.is_healthy());

        // Register failing check
        monitor
            .register_check("failing", || async {
                HealthCheckResult::Unhealthy("test failure".into())
            })
            .await;

        // Run until threshold
        monitor.check().await;
        assert!(monitor.is_healthy()); // Still healthy after 1 failure

        monitor.check().await;
        assert!(!monitor.is_healthy()); // Unhealthy after 2 failures
    }

    #[tokio::test]
    async fn test_lag_monitoring() {
        let config = HealthConfig {
            max_lag_ms: 1000,
            failure_threshold: 1,
            ..Default::default()
        };
        let monitor = HealthMonitor::new(config);
        monitor.mark_connected();

        // Set acceptable lag
        monitor.set_lag(500);
        let status = monitor.check().await;
        assert!(status.is_healthy);

        // Set excessive lag
        monitor.set_lag(2000);
        let status = monitor.check().await;
        assert!(!status.is_healthy);
        assert!(status.checks.contains_key("replication_lag"));
    }

    #[tokio::test]
    async fn test_recovery_coordinator() {
        let config = HealthConfig {
            recovery_delay: Duration::from_millis(10),
            max_recovery_delay: Duration::from_millis(100),
            ..Default::default()
        };
        let coordinator = RecoveryCoordinator::new(config);

        // Successful recovery
        let success = coordinator.recover(|| async { true }).await;
        assert!(success);
        assert_eq!(coordinator.attempts(), 0); // Reset after success

        // Failed recovery
        let success = coordinator.recover(|| async { false }).await;
        assert!(!success);
    }

    #[tokio::test]
    async fn test_health_status_probes() {
        let status = HealthStatus {
            is_healthy: true,
            is_ready: true,
            checks: HashMap::new(),
            lag_ms: 100,
            last_healthy: Some(Instant::now()),
            consecutive_failures: 0,
            consecutive_successes: 5,
            uptime: Duration::from_secs(3600),
        };

        assert_eq!(status.liveness(), (200, "OK"));
        assert_eq!(status.readiness(), (200, "OK"));

        let not_ready = HealthStatus {
            is_ready: false,
            ..status.clone()
        };
        assert_eq!(not_ready.readiness(), (503, "Service Unavailable"));
    }

    #[test]
    fn test_health_status_json() {
        let status = HealthStatus {
            is_healthy: true,
            is_ready: true,
            checks: HashMap::new(),
            lag_ms: 100,
            last_healthy: Some(Instant::now()),
            consecutive_failures: 0,
            consecutive_successes: 5,
            uptime: Duration::from_secs(60),
        };

        let json = status.to_json();
        assert!(json.contains("\"status\":\"healthy\""));
        assert!(json.contains("\"ready\":true"));
    }

    #[tokio::test]
    async fn test_mark_connected_disconnected() {
        let monitor = HealthMonitor::new(HealthConfig::default());

        monitor.mark_connected();
        assert!(monitor.is_healthy());
        assert!(monitor.is_ready());

        monitor.mark_disconnected();
        assert!(!monitor.is_healthy());
    }
}