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
//! # CDC Batch Processing
//!
//! Efficient batch processing for CDC events with configurable batching strategies.
//!
//! ## Features
//!
//! - **Time-based batching**: Flush after duration
//! - **Size-based batching**: Flush after N events
//! - **Byte-based batching**: Flush after N bytes
//! - **Transaction batching**: Keep transaction events together
//!
//! ## Usage
//!
//! ```ignore
//! use rivven_cdc::common::{BatchConfig, EventBatcher};
//!
//! let config = BatchConfig::builder()
//!     .max_events(1000)
//!     .max_bytes(1_000_000)
//!     .max_delay(Duration::from_millis(100))
//!     .build();
//!
//! let batcher = EventBatcher::new(config);
//!
//! // Add events
//! if let Some(batch) = batcher.add(event).await {
//!     process_batch(batch).await;
//! }
//! ```

use crate::common::{CdcEvent, CdcOp};
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
use tokio::time::interval;

/// Configuration for batch processing.
#[derive(Debug, Clone)]
pub struct BatchConfig {
    /// Maximum events per batch
    pub max_events: usize,
    /// Maximum bytes per batch
    pub max_bytes: usize,
    /// Maximum time to wait before flushing
    pub max_delay: Duration,
    /// Keep transaction events together
    pub preserve_transactions: bool,
    /// Minimum events before time-based flush
    pub min_events: usize,
}

impl Default for BatchConfig {
    fn default() -> Self {
        Self {
            max_events: 1000,
            max_bytes: 1_048_576, // 1MB
            max_delay: Duration::from_millis(100),
            preserve_transactions: true,
            min_events: 1,
        }
    }
}

impl BatchConfig {
    /// Create a new builder.
    pub fn builder() -> BatchConfigBuilder {
        BatchConfigBuilder::default()
    }

    /// Create config optimized for throughput.
    pub fn high_throughput() -> Self {
        Self {
            max_events: 10_000,
            max_bytes: 10_485_760, // 10MB
            max_delay: Duration::from_millis(500),
            preserve_transactions: false,
            min_events: 100,
        }
    }

    /// Create config optimized for latency.
    pub fn low_latency() -> Self {
        Self {
            max_events: 100,
            max_bytes: 102_400, // 100KB
            max_delay: Duration::from_millis(10),
            preserve_transactions: true,
            min_events: 1,
        }
    }
}

/// Builder for BatchConfig.
#[derive(Default)]
pub struct BatchConfigBuilder {
    max_events: Option<usize>,
    max_bytes: Option<usize>,
    max_delay: Option<Duration>,
    preserve_transactions: Option<bool>,
    min_events: Option<usize>,
}

impl BatchConfigBuilder {
    pub fn max_events(mut self, n: usize) -> Self {
        self.max_events = Some(n);
        self
    }

    pub fn max_bytes(mut self, n: usize) -> Self {
        self.max_bytes = Some(n);
        self
    }

    pub fn max_delay(mut self, d: Duration) -> Self {
        self.max_delay = Some(d);
        self
    }

    pub fn preserve_transactions(mut self, v: bool) -> Self {
        self.preserve_transactions = Some(v);
        self
    }

    pub fn min_events(mut self, n: usize) -> Self {
        self.min_events = Some(n);
        self
    }

    pub fn build(self) -> BatchConfig {
        let default = BatchConfig::default();
        BatchConfig {
            max_events: self.max_events.unwrap_or(default.max_events),
            max_bytes: self.max_bytes.unwrap_or(default.max_bytes),
            max_delay: self.max_delay.unwrap_or(default.max_delay),
            preserve_transactions: self
                .preserve_transactions
                .unwrap_or(default.preserve_transactions),
            min_events: self.min_events.unwrap_or(default.min_events),
        }
    }
}

/// A batch of CDC events ready for processing.
#[derive(Debug, Clone)]
pub struct EventBatch {
    /// Events in this batch
    pub events: Vec<CdcEvent>,
    /// Total bytes in batch
    pub bytes: usize,
    /// Time batch was created
    pub created_at: Instant,
    /// Time batch was flushed
    pub flushed_at: Instant,
    /// Batch sequence number
    pub sequence: u64,
    /// Transaction IDs in this batch
    pub transaction_ids: Vec<String>,
}

impl EventBatch {
    /// Number of events in batch.
    #[inline]
    pub fn len(&self) -> usize {
        self.events.len()
    }

    /// Check if batch is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }

    /// Time spent waiting before flush.
    pub fn wait_time(&self) -> Duration {
        self.flushed_at.duration_since(self.created_at)
    }

    /// Count events by operation type.
    pub fn counts(&self) -> BatchCounts {
        let mut counts = BatchCounts::default();
        for event in &self.events {
            match event.op {
                CdcOp::Insert => counts.inserts += 1,
                CdcOp::Update => counts.updates += 1,
                CdcOp::Delete => counts.deletes += 1,
                CdcOp::Tombstone => counts.tombstones += 1,
                CdcOp::Snapshot => counts.snapshots += 1,
                CdcOp::Truncate => counts.truncates += 1,
                CdcOp::Schema => counts.schemas += 1,
            }
        }
        counts
    }
}

/// Counts of events by operation type.
#[derive(Debug, Clone, Default)]
pub struct BatchCounts {
    pub inserts: usize,
    pub updates: usize,
    pub deletes: usize,
    pub tombstones: usize,
    pub snapshots: usize,
    pub truncates: usize,
    pub schemas: usize,
}

impl BatchCounts {
    pub fn total(&self) -> usize {
        self.inserts
            + self.updates
            + self.deletes
            + self.tombstones
            + self.snapshots
            + self.truncates
            + self.schemas
    }
}

/// Event batcher that accumulates events and flushes based on configuration.
pub struct EventBatcher {
    config: BatchConfig,
    state: Mutex<BatcherState>,
}

struct BatcherState {
    events: Vec<CdcEvent>,
    bytes: usize,
    batch_start: Instant,
    sequence: u64,
    in_transaction: bool,
    #[allow(dead_code)] // Reserved for transaction-aware batching
    transaction_id: Option<String>,
}

impl EventBatcher {
    /// Create a new event batcher.
    pub fn new(config: BatchConfig) -> Self {
        let max_events = config.max_events;
        Self {
            config,
            state: Mutex::new(BatcherState {
                events: Vec::with_capacity(max_events),
                bytes: 0,
                batch_start: Instant::now(),
                sequence: 0,
                in_transaction: false,
                transaction_id: None,
            }),
        }
    }

    /// Add an event to the batcher.
    ///
    /// Returns a batch if the batch is ready to be flushed.
    pub async fn add(&self, event: CdcEvent) -> Option<EventBatch> {
        let mut state = self.state.lock().await;

        // Estimate event size (approximation)
        let event_bytes = estimate_event_size(&event);

        // Track transaction boundaries if enabled
        if self.config.preserve_transactions {
            // Transaction start (first event after commit/start)
            if !state.in_transaction && event.is_dml() {
                state.in_transaction = true;
            }
        }

        state.events.push(event);
        state.bytes += event_bytes;

        // Check if we should flush
        let should_flush = self.should_flush(&state);

        if should_flush {
            Some(self.create_batch(&mut state))
        } else {
            None
        }
    }

    /// Force flush the current batch.
    pub async fn flush(&self) -> Option<EventBatch> {
        let mut state = self.state.lock().await;
        if state.events.is_empty() {
            return None;
        }
        Some(self.create_batch(&mut state))
    }

    /// Check if batch should be flushed.
    pub async fn check_timeout(&self) -> Option<EventBatch> {
        let mut state = self.state.lock().await;

        if state.events.len() >= self.config.min_events
            && state.batch_start.elapsed() >= self.config.max_delay
        {
            // Don't flush mid-transaction if preserving transactions
            if self.config.preserve_transactions && state.in_transaction {
                return None;
            }
            return Some(self.create_batch(&mut state));
        }

        None
    }

    /// Get current batch size.
    pub async fn pending_count(&self) -> usize {
        let state = self.state.lock().await;
        state.events.len()
    }

    /// Get current batch bytes.
    pub async fn pending_bytes(&self) -> usize {
        let state = self.state.lock().await;
        state.bytes
    }

    fn should_flush(&self, state: &BatcherState) -> bool {
        // Size limits
        if state.events.len() >= self.config.max_events {
            return true;
        }
        if state.bytes >= self.config.max_bytes {
            return true;
        }

        // Transaction boundary (preserve_transactions = true means flush at commit)
        // This is handled by detecting transaction end events

        false
    }

    fn create_batch(&self, state: &mut BatcherState) -> EventBatch {
        let events = std::mem::take(&mut state.events);
        let bytes = state.bytes;

        state.events = Vec::with_capacity(self.config.max_events);
        state.bytes = 0;
        state.batch_start = Instant::now();
        state.sequence += 1;
        state.in_transaction = false;

        EventBatch {
            events,
            bytes,
            created_at: state.batch_start,
            flushed_at: Instant::now(),
            sequence: state.sequence,
            transaction_ids: Vec::new(),
        }
    }
}

/// Estimate the size of an event in bytes.
fn estimate_event_size(event: &CdcEvent) -> usize {
    let mut size = 0;

    // Fixed overhead
    size += 64; // source_type, database, schema, table, op, timestamp

    // Variable size
    if let Some(ref before) = event.before {
        size += before.to_string().len();
    }
    if let Some(ref after) = event.after {
        size += after.to_string().len();
    }

    size
}

/// Batch processor that runs in a background task.
pub struct BatchProcessor<F>
where
    F: FnMut(EventBatch) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> + Send,
{
    batcher: EventBatcher,
    handler: F,
}

impl<F> BatchProcessor<F>
where
    F: FnMut(EventBatch) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> + Send,
{
    pub fn new(config: BatchConfig, handler: F) -> Self {
        Self {
            batcher: EventBatcher::new(config.clone()),
            handler,
        }
    }

    /// Process an event, calling handler if batch is ready.
    pub async fn process(&mut self, event: CdcEvent) {
        if let Some(batch) = self.batcher.add(event).await {
            (self.handler)(batch).await;
        }
    }

    /// Flush any pending events.
    pub async fn flush(&mut self) {
        if let Some(batch) = self.batcher.flush().await {
            (self.handler)(batch).await;
        }
    }
}

/// Create a background task that periodically checks for timeout flushes.
pub fn spawn_timeout_flusher(
    batcher: std::sync::Arc<EventBatcher>,
    flush_interval: Duration,
) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        let mut interval = interval(flush_interval);
        loop {
            interval.tick().await;
            if let Some(_batch) = batcher.check_timeout().await {
                // In real usage, would send batch somewhere
            }
        }
    })
}

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

    fn make_event(op: CdcOp) -> CdcEvent {
        CdcEvent {
            source_type: "postgres".to_string(),
            database: "testdb".to_string(),
            schema: "public".to_string(),
            table: "users".to_string(),
            op,
            before: None,
            after: Some(json!({"id": 1, "name": "Alice"})),
            timestamp: 1234567890,
            transaction: None,
        }
    }

    #[test]
    fn test_batch_config_builder() {
        let config = BatchConfig::builder()
            .max_events(500)
            .max_bytes(500_000)
            .max_delay(Duration::from_millis(50))
            .build();

        assert_eq!(config.max_events, 500);
        assert_eq!(config.max_bytes, 500_000);
        assert_eq!(config.max_delay, Duration::from_millis(50));
    }

    #[test]
    fn test_batch_config_presets() {
        let high = BatchConfig::high_throughput();
        assert_eq!(high.max_events, 10_000);

        let low = BatchConfig::low_latency();
        assert_eq!(low.max_events, 100);
    }

    #[tokio::test]
    async fn test_batcher_size_limit() {
        let config = BatchConfig::builder().max_events(3).build();
        let batcher = EventBatcher::new(config);

        // First two events should not flush
        assert!(batcher.add(make_event(CdcOp::Insert)).await.is_none());
        assert!(batcher.add(make_event(CdcOp::Update)).await.is_none());

        // Third event should trigger flush
        let batch = batcher.add(make_event(CdcOp::Delete)).await;
        assert!(batch.is_some());
        assert_eq!(batch.unwrap().len(), 3);
    }

    #[tokio::test]
    async fn test_batcher_force_flush() {
        let config = BatchConfig::default();
        let batcher = EventBatcher::new(config);

        batcher.add(make_event(CdcOp::Insert)).await;
        batcher.add(make_event(CdcOp::Insert)).await;

        let batch = batcher.flush().await;
        assert!(batch.is_some());
        assert_eq!(batch.unwrap().len(), 2);

        // Flush empty batcher returns None
        assert!(batcher.flush().await.is_none());
    }

    #[tokio::test]
    async fn test_batch_counts() {
        let config = BatchConfig::builder().max_events(10).build();
        let batcher = EventBatcher::new(config);

        batcher.add(make_event(CdcOp::Insert)).await;
        batcher.add(make_event(CdcOp::Insert)).await;
        batcher.add(make_event(CdcOp::Update)).await;
        batcher.add(make_event(CdcOp::Delete)).await;

        let batch = batcher.flush().await.unwrap();
        let counts = batch.counts();

        assert_eq!(counts.inserts, 2);
        assert_eq!(counts.updates, 1);
        assert_eq!(counts.deletes, 1);
        assert_eq!(counts.total(), 4);
    }

    #[tokio::test]
    async fn test_pending_counts() {
        let config = BatchConfig::default();
        let batcher = EventBatcher::new(config);

        assert_eq!(batcher.pending_count().await, 0);

        batcher.add(make_event(CdcOp::Insert)).await;
        batcher.add(make_event(CdcOp::Insert)).await;

        assert_eq!(batcher.pending_count().await, 2);
        assert!(batcher.pending_bytes().await > 0);
    }

    #[tokio::test]
    async fn test_batch_sequence_numbers() {
        let config = BatchConfig::builder().max_events(1).build();
        let batcher = EventBatcher::new(config);

        let batch1 = batcher.add(make_event(CdcOp::Insert)).await.unwrap();
        let batch2 = batcher.add(make_event(CdcOp::Insert)).await.unwrap();
        let batch3 = batcher.add(make_event(CdcOp::Insert)).await.unwrap();

        assert_eq!(batch1.sequence, 1);
        assert_eq!(batch2.sequence, 2);
        assert_eq!(batch3.sequence, 3);
    }

    #[test]
    fn test_estimate_event_size() {
        let event = make_event(CdcOp::Insert);
        let size = estimate_event_size(&event);

        // Should be > 64 (overhead) + JSON size
        assert!(size > 64);
    }

    #[test]
    fn test_batch_wait_time() {
        let batch = EventBatch {
            events: vec![],
            bytes: 0,
            created_at: Instant::now(),
            flushed_at: Instant::now(),
            sequence: 1,
            transaction_ids: vec![],
        };

        // Wait time should be very small (same instant)
        assert!(batch.wait_time() < Duration::from_millis(10));
    }
}