phytrace_sdk/reliability/
batch.rs1use 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#[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 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 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 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 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 pub async fn should_flush(&self) -> bool {
78 let events = self.events.lock().await;
79 self.should_flush_inner(&events).await
80 }
81
82 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 pub async fn len(&self) -> usize {
92 self.events.lock().await.len()
93 }
94
95 pub async fn is_empty(&self) -> bool {
97 self.events.lock().await.is_empty()
98 }
99
100 pub async fn age(&self) -> Duration {
102 self.created_at.lock().await.elapsed()
103 }
104
105 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 async fn should_flush_inner(&self, events: &[UdmEvent]) -> bool {
121 if events.len() >= self.max_size {
123 return true;
124 }
125
126 let age = self.created_at.lock().await.elapsed();
128 !events.is_empty() && age >= self.max_age
129 }
130}
131
132pub struct BatchFlusher<T: Transport> {
134 processor: Arc<BatchProcessor>,
135 transport: Arc<T>,
136 interval: Duration,
137}
138
139impl<T: Transport + 'static> BatchFlusher<T> {
140 pub fn new(processor: Arc<BatchProcessor>, transport: Arc<T>, interval: Duration) -> Self {
142 Self {
143 processor,
144 transport,
145 interval,
146 }
147 }
148
149 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 drop(processor.send_batch(transport.as_ref()).await);
172 break;
173 }
174 }
175 }
176 });
177
178 FlushHandle { stop_tx: Some(tx) }
179 }
180}
181
182pub struct FlushHandle {
184 stop_tx: Option<tokio::sync::oneshot::Sender<()>>,
185}
186
187impl FlushHandle {
188 pub fn stop(mut self) {
190 if let Some(tx) = self.stop_tx.take() {
191 #[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 assert_eq!(batches.len(), 1);
268 assert_eq!(batches[0].len(), 3);
269 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 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 tokio::time::sleep(Duration::from_millis(5)).await;
304
305 assert!(!processor.should_flush().await);
306 }
307
308 #[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 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 let age = processor.age().await;
336 assert!(age < Duration::from_secs(1));
337
338 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 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 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 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 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 tokio::time::sleep(Duration::from_millis(60)).await;
448 assert!(processor.should_flush().await);
449
450 processor.flush().await;
452
453 Box::pin(processor.add(test_event("2"))).await;
455
456 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 tokio::time::sleep(Duration::from_millis(50)).await;
477
478 handle.stop();
479
480 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), );
496
497 let handle = flusher.start();
498
499 tokio::time::sleep(Duration::from_millis(10)).await;
501 handle.stop();
502
503 tokio::time::sleep(Duration::from_millis(50)).await;
505
506 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 }
527
528 tokio::time::sleep(Duration::from_millis(50)).await;
530
531 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 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}