Skip to main content

phytrace_sdk/reliability/
batch.rs

1//! Batch processing for efficient event transmission.
2
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5use tokio::sync::Mutex;
6
7use crate::core::config::BufferConfig;
8use crate::error::PhyTraceResult;
9use crate::models::event::UdmEvent;
10use crate::transport::traits::{BatchResult, Transport};
11
12/// Batch processor for aggregating events before transmission.
13#[derive(Debug)]
14pub struct BatchProcessor {
15    events: Arc<Mutex<Vec<UdmEvent>>>,
16    max_size: usize,
17    max_age: Duration,
18    created_at: Arc<Mutex<Instant>>,
19}
20
21impl BatchProcessor {
22    /// Create a new batch processor.
23    pub fn new(max_size: usize, max_age: Duration) -> Self {
24        Self {
25            events: Arc::new(Mutex::new(Vec::new())),
26            max_size,
27            max_age,
28            created_at: Arc::new(Mutex::new(Instant::now())),
29        }
30    }
31
32    /// Create from buffer configuration.
33    pub fn from_config(config: &BufferConfig) -> Self {
34        Self::new(
35            config.batch_size,
36            Duration::from_secs(config.flush_interval_secs),
37        )
38    }
39
40    /// Add an event to the batch.
41    ///
42    /// Returns `Some(events)` if the batch is ready to be sent.
43    pub async fn add(&self, event: UdmEvent) -> Option<Vec<UdmEvent>> {
44        let mut events = self.events.lock().await;
45        events.push(event);
46
47        if self.should_flush_inner(&events).await {
48            let batch = std::mem::take(&mut *events);
49            *self.created_at.lock().await = Instant::now();
50            Some(batch)
51        } else {
52            None
53        }
54    }
55
56    /// Add multiple events.
57    ///
58    /// Returns batches ready to be sent (may return multiple if events exceed batch size).
59    pub async fn add_many(&self, new_events: Vec<UdmEvent>) -> Vec<Vec<UdmEvent>> {
60        let mut events = self.events.lock().await;
61        let mut batches = Vec::new();
62
63        for event in new_events {
64            events.push(event);
65
66            if events.len() >= self.max_size {
67                let batch = std::mem::take(&mut *events);
68                *self.created_at.lock().await = Instant::now();
69                batches.push(batch);
70            }
71        }
72
73        batches
74    }
75
76    /// Check if the batch should be flushed.
77    pub async fn should_flush(&self) -> bool {
78        let events = self.events.lock().await;
79        self.should_flush_inner(&events).await
80    }
81
82    /// Flush the current batch regardless of conditions.
83    pub async fn flush(&self) -> Vec<UdmEvent> {
84        let mut events = self.events.lock().await;
85        let batch = std::mem::take(&mut *events);
86        *self.created_at.lock().await = Instant::now();
87        batch
88    }
89
90    /// Get current batch size.
91    pub async fn len(&self) -> usize {
92        self.events.lock().await.len()
93    }
94
95    /// Check if batch is empty.
96    pub async fn is_empty(&self) -> bool {
97        self.events.lock().await.is_empty()
98    }
99
100    /// Get age of current batch.
101    pub async fn age(&self) -> Duration {
102        self.created_at.lock().await.elapsed()
103    }
104
105    /// Send the batch using a transport.
106    pub async fn send_batch<T: Transport>(
107        &self,
108        transport: &T,
109    ) -> PhyTraceResult<Option<BatchResult>> {
110        let batch = self.flush().await;
111        if batch.is_empty() {
112            return Ok(None);
113        }
114
115        let result = transport.send_batch(&batch).await?;
116        Ok(Some(result))
117    }
118
119    // Private helper
120    async fn should_flush_inner(&self, events: &[UdmEvent]) -> bool {
121        // Check size
122        if events.len() >= self.max_size {
123            return true;
124        }
125
126        // Check age
127        let age = self.created_at.lock().await.elapsed();
128        !events.is_empty() && age >= self.max_age
129    }
130}
131
132/// Background batch flusher that periodically checks and sends batches.
133pub struct BatchFlusher<T: Transport> {
134    processor: Arc<BatchProcessor>,
135    transport: Arc<T>,
136    interval: Duration,
137}
138
139impl<T: Transport + 'static> BatchFlusher<T> {
140    /// Create a new batch flusher.
141    pub fn new(processor: Arc<BatchProcessor>, transport: Arc<T>, interval: Duration) -> Self {
142        Self {
143            processor,
144            transport,
145            interval,
146        }
147    }
148
149    /// Start the background flush loop.
150    ///
151    /// Returns a handle that can be used to stop the flusher.
152    pub fn start(self) -> FlushHandle {
153        let (tx, mut rx) = tokio::sync::oneshot::channel::<()>();
154
155        let processor = self.processor;
156        let transport = self.transport;
157        let interval = self.interval;
158
159        tokio::spawn(async move {
160            let mut interval_timer = tokio::time::interval(interval);
161
162            loop {
163                tokio::select! {
164                    _ = interval_timer.tick() => {
165                        if processor.should_flush().await {
166                            drop(processor.send_batch(transport.as_ref()).await);
167                        }
168                    }
169                    _ = &mut rx => {
170                        // Final flush before stopping
171                        drop(processor.send_batch(transport.as_ref()).await);
172                        break;
173                    }
174                }
175            }
176        });
177
178        FlushHandle { stop_tx: Some(tx) }
179    }
180}
181
182/// Handle to stop a background flusher.
183pub struct FlushHandle {
184    stop_tx: Option<tokio::sync::oneshot::Sender<()>>,
185}
186
187impl FlushHandle {
188    /// Stop the flusher.
189    pub fn stop(mut self) {
190        if let Some(tx) = self.stop_tx.take() {
191            // Receiver may already have been dropped if the flusher task exited;
192            // that's harmless since we just want to signal stop.
193            #[expect(
194                clippy::let_underscore_must_use,
195                reason = "send failure means the flusher task already exited, which is the desired post-condition"
196            )]
197            let _ = tx.send(());
198        }
199    }
200}
201
202impl Drop for FlushHandle {
203    fn drop(&mut self) {
204        if let Some(tx) = self.stop_tx.take() {
205            #[expect(
206                clippy::let_underscore_must_use,
207                reason = "send failure means the flusher task already exited, which is the desired post-condition"
208            )]
209            let _ = tx.send(());
210        }
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use crate::core::config::BufferConfig;
218    use crate::models::domains::IdentityDomain;
219    use crate::models::enums::SourceType;
220    use crate::transport::mock::MockTransport;
221
222    fn test_event(id: &str) -> UdmEvent {
223        UdmEvent::new(SourceType::Amr).with_identity(IdentityDomain {
224            source_id: Some(id.to_string()),
225            ..Default::default()
226        })
227    }
228
229    #[tokio::test]
230    async fn test_batch_add_below_threshold() {
231        let processor = BatchProcessor::new(5, Duration::from_secs(60));
232
233        let result = Box::pin(processor.add(test_event("1"))).await;
234        assert!(result.is_none());
235        assert_eq!(processor.len().await, 1);
236    }
237
238    #[tokio::test]
239    async fn test_batch_add_reaches_threshold() {
240        let processor = BatchProcessor::new(3, Duration::from_secs(60));
241
242        Box::pin(processor.add(test_event("1"))).await;
243        Box::pin(processor.add(test_event("2"))).await;
244        let result = Box::pin(processor.add(test_event("3"))).await;
245
246        assert!(result.is_some());
247        let batch = result.unwrap();
248        assert_eq!(batch.len(), 3);
249        assert!(processor.is_empty().await);
250    }
251
252    #[tokio::test]
253    async fn test_batch_add_many() {
254        let processor = BatchProcessor::new(3, Duration::from_secs(60));
255
256        let events = vec![
257            test_event("1"),
258            test_event("2"),
259            test_event("3"),
260            test_event("4"),
261            test_event("5"),
262        ];
263
264        let batches = processor.add_many(events).await;
265
266        // Should produce one full batch of 3
267        assert_eq!(batches.len(), 1);
268        assert_eq!(batches[0].len(), 3);
269        // Remaining 2 events in processor
270        assert_eq!(processor.len().await, 2);
271    }
272
273    #[tokio::test]
274    async fn test_batch_flush() {
275        let processor = BatchProcessor::new(10, Duration::from_secs(60));
276
277        Box::pin(processor.add(test_event("1"))).await;
278        Box::pin(processor.add(test_event("2"))).await;
279
280        let batch = processor.flush().await;
281
282        assert_eq!(batch.len(), 2);
283        assert!(processor.is_empty().await);
284    }
285
286    #[tokio::test]
287    async fn test_batch_age_trigger() {
288        let processor = BatchProcessor::new(100, Duration::from_millis(10));
289
290        Box::pin(processor.add(test_event("1"))).await;
291
292        // Wait for batch to age
293        tokio::time::sleep(Duration::from_millis(20)).await;
294
295        assert!(processor.should_flush().await);
296    }
297
298    #[tokio::test]
299    async fn test_empty_batch_no_flush() {
300        let processor = BatchProcessor::new(5, Duration::from_millis(1));
301
302        // Even with zero max age, empty batch shouldn't flush
303        tokio::time::sleep(Duration::from_millis(5)).await;
304
305        assert!(!processor.should_flush().await);
306    }
307
308    // Additional tests for improved coverage
309
310    #[tokio::test]
311    async fn test_from_config() {
312        let config = BufferConfig {
313            batch_size: 10,
314            flush_interval_secs: 30,
315            ..Default::default()
316        };
317
318        let processor = BatchProcessor::from_config(&config);
319
320        // Add 10 events - should trigger batch
321        for i in 0..9 {
322            let result = Box::pin(processor.add(test_event(&i.to_string()))).await;
323            assert!(result.is_none());
324        }
325        let result = Box::pin(processor.add(test_event("10"))).await;
326        assert!(result.is_some());
327        assert_eq!(result.unwrap().len(), 10);
328    }
329
330    #[tokio::test]
331    async fn test_batch_age() {
332        let processor = BatchProcessor::new(100, Duration::from_secs(60));
333
334        // Age should be very small initially
335        let age = processor.age().await;
336        assert!(age < Duration::from_secs(1));
337
338        // Wait a bit
339        tokio::time::sleep(Duration::from_millis(50)).await;
340
341        let age2 = processor.age().await;
342        assert!(age2 >= Duration::from_millis(50));
343    }
344
345    #[tokio::test]
346    async fn test_batch_is_empty() {
347        let processor = BatchProcessor::new(5, Duration::from_secs(60));
348
349        assert!(processor.is_empty().await);
350
351        Box::pin(processor.add(test_event("1"))).await;
352        assert!(!processor.is_empty().await);
353
354        processor.flush().await;
355        assert!(processor.is_empty().await);
356    }
357
358    #[tokio::test]
359    async fn test_batch_len() {
360        let processor = BatchProcessor::new(10, Duration::from_secs(60));
361
362        assert_eq!(processor.len().await, 0);
363
364        Box::pin(processor.add(test_event("1"))).await;
365        assert_eq!(processor.len().await, 1);
366
367        Box::pin(processor.add(test_event("2"))).await;
368        Box::pin(processor.add(test_event("3"))).await;
369        assert_eq!(processor.len().await, 3);
370    }
371
372    #[tokio::test]
373    async fn test_add_many_multiple_batches() {
374        let processor = BatchProcessor::new(3, Duration::from_secs(60));
375
376        // Add 7 events - should produce 2 full batches
377        let events: Vec<UdmEvent> = (0..7).map(|i| test_event(&i.to_string())).collect();
378
379        let batches = processor.add_many(events).await;
380
381        assert_eq!(batches.len(), 2);
382        assert_eq!(batches[0].len(), 3);
383        assert_eq!(batches[1].len(), 3);
384        // 1 event remaining
385        assert_eq!(processor.len().await, 1);
386    }
387
388    #[tokio::test]
389    async fn test_add_many_exact_multiple() {
390        let processor = BatchProcessor::new(3, Duration::from_secs(60));
391
392        // Add exactly 6 events - should produce 2 full batches with nothing remaining
393        let events: Vec<UdmEvent> = (0..6).map(|i| test_event(&i.to_string())).collect();
394
395        let batches = processor.add_many(events).await;
396
397        assert_eq!(batches.len(), 2);
398        assert!(processor.is_empty().await);
399    }
400
401    #[tokio::test]
402    async fn test_add_many_less_than_batch() {
403        let processor = BatchProcessor::new(10, Duration::from_secs(60));
404
405        let events: Vec<UdmEvent> = (0..5).map(|i| test_event(&i.to_string())).collect();
406
407        let batches = processor.add_many(events).await;
408
409        // No complete batches
410        assert!(batches.is_empty());
411        assert_eq!(processor.len().await, 5);
412    }
413
414    #[tokio::test]
415    async fn test_send_batch_with_events() {
416        let processor = BatchProcessor::new(10, Duration::from_secs(60));
417        let transport = MockTransport::new();
418
419        Box::pin(processor.add(test_event("1"))).await;
420        Box::pin(processor.add(test_event("2"))).await;
421
422        let result = processor.send_batch(&transport).await.unwrap();
423
424        assert!(result.is_some());
425        let batch_result = result.unwrap();
426        assert_eq!(batch_result.total, 2);
427        assert!(processor.is_empty().await);
428    }
429
430    #[tokio::test]
431    async fn test_send_batch_empty() {
432        let processor = BatchProcessor::new(10, Duration::from_secs(60));
433        let transport = MockTransport::new();
434
435        let result = processor.send_batch(&transport).await.unwrap();
436
437        assert!(result.is_none());
438    }
439
440    #[tokio::test]
441    async fn test_flush_resets_timer() {
442        let processor = BatchProcessor::new(100, Duration::from_millis(50));
443
444        Box::pin(processor.add(test_event("1"))).await;
445
446        // Wait for batch to age
447        tokio::time::sleep(Duration::from_millis(60)).await;
448        assert!(processor.should_flush().await);
449
450        // Flush resets the timer
451        processor.flush().await;
452
453        // Add new event
454        Box::pin(processor.add(test_event("2"))).await;
455
456        // Should not flush yet (timer was reset)
457        assert!(!processor.should_flush().await);
458    }
459
460    #[tokio::test]
461    async fn test_batch_flusher_start_and_stop() {
462        let processor = Arc::new(BatchProcessor::new(100, Duration::from_millis(10)));
463        let transport = Arc::new(MockTransport::new());
464
465        Box::pin(processor.add(test_event("1"))).await;
466
467        let flusher = BatchFlusher::new(
468            processor.clone(),
469            transport.clone(),
470            Duration::from_millis(20),
471        );
472
473        let handle = flusher.start();
474
475        // Wait for at least one flush cycle
476        tokio::time::sleep(Duration::from_millis(50)).await;
477
478        handle.stop();
479
480        // Transport should have received the event
481        assert!(transport.event_count() >= 1);
482    }
483
484    #[tokio::test]
485    async fn test_batch_flusher_final_flush_on_stop() {
486        let processor = Arc::new(BatchProcessor::new(100, Duration::from_secs(60)));
487        let transport = Arc::new(MockTransport::new());
488
489        Box::pin(processor.add(test_event("1"))).await;
490
491        let flusher = BatchFlusher::new(
492            processor.clone(),
493            transport.clone(),
494            Duration::from_secs(60), // Long interval - won't trigger naturally
495        );
496
497        let handle = flusher.start();
498
499        // Immediately stop - should trigger final flush
500        tokio::time::sleep(Duration::from_millis(10)).await;
501        handle.stop();
502
503        // Give time for final flush
504        tokio::time::sleep(Duration::from_millis(50)).await;
505
506        // Event should have been sent during final flush
507        assert_eq!(transport.event_count(), 1);
508    }
509
510    #[tokio::test]
511    async fn test_flush_handle_drop() {
512        let processor = Arc::new(BatchProcessor::new(100, Duration::from_secs(60)));
513        let transport = Arc::new(MockTransport::new());
514
515        Box::pin(processor.add(test_event("1"))).await;
516
517        let flusher = BatchFlusher::new(
518            processor.clone(),
519            transport.clone(),
520            Duration::from_secs(60),
521        );
522
523        {
524            let _handle = flusher.start();
525            // Handle dropped here
526        }
527
528        // Give time for cleanup
529        tokio::time::sleep(Duration::from_millis(50)).await;
530
531        // Event should have been sent during drop
532        assert_eq!(transport.event_count(), 1);
533    }
534
535    #[tokio::test]
536    async fn test_should_flush_size_threshold() {
537        let processor = BatchProcessor::new(3, Duration::from_secs(60));
538
539        Box::pin(processor.add(test_event("1"))).await;
540        assert!(!processor.should_flush().await);
541
542        Box::pin(processor.add(test_event("2"))).await;
543        assert!(!processor.should_flush().await);
544
545        // Note: third add will auto-flush, so we check just before
546        assert_eq!(processor.len().await, 2);
547    }
548
549    #[tokio::test]
550    async fn test_batch_processor_concurrent_access() {
551        let processor = Arc::new(BatchProcessor::new(100, Duration::from_secs(60)));
552
553        let mut handles = vec![];
554
555        for i in 0..10 {
556            let proc = processor.clone();
557            let handle = tokio::spawn(async move {
558                Box::pin(proc.add(test_event(&i.to_string()))).await;
559            });
560            handles.push(handle);
561        }
562
563        for handle in handles {
564            handle.await.unwrap();
565        }
566
567        assert_eq!(processor.len().await, 10);
568    }
569}