saluki_io/net/util/retry/queue/
mod.rs1use std::collections::VecDeque;
2
3use saluki_error::{generic_error, GenericError};
4use serde::{de::DeserializeOwned, Serialize};
5use tracing::{debug, info, warn};
6
7mod persisted;
8use self::persisted::PersistedQueue;
9pub use self::persisted::{DiskUsageRetriever, DiskUsageRetrieverImpl, PersistedQueueArgs};
10
11const DEFAULT_FLUSH_TO_DISK_MEM_RATIO: f64 = 0.5;
12
13pub trait EventContainer {
19 fn event_count(&self) -> u64;
21
22 fn data_point_count(&self) -> u64 {
24 0
25 }
26}
27
28pub trait Retryable: EventContainer + DeserializeOwned + Serialize {
30 fn size_bytes(&self) -> u64;
32}
33
34impl EventContainer for String {
35 fn event_count(&self) -> u64 {
36 1
37 }
38}
39
40impl Retryable for String {
41 fn size_bytes(&self) -> u64 {
42 self.len() as u64
43 }
44}
45
46#[derive(Default)]
51#[must_use = "`PushResult` carries information about potentially dropped items/events and should not be ignored"]
52pub struct PushResult {
53 pub items_dropped: u64,
55
56 pub events_dropped: u64,
58
59 pub data_points_dropped: u64,
61
62 pub bytes_dropped: u64,
64}
65
66impl PushResult {
67 pub fn had_drops(&self) -> bool {
69 self.items_dropped > 0
70 }
71
72 pub fn merge(&mut self, other: Self) {
74 self.items_dropped += other.items_dropped;
75 self.events_dropped += other.events_dropped;
76 self.data_points_dropped += other.data_points_dropped;
77 self.bytes_dropped += other.bytes_dropped;
78 }
79
80 pub fn track_dropped_item<T: Retryable>(&mut self, item: &T) {
82 self.items_dropped += 1;
83 self.events_dropped += item.event_count();
84 self.data_points_dropped += item.data_point_count();
85 self.bytes_dropped += item.size_bytes();
86 }
87}
88
89pub struct RetryQueue<T> {
91 queue_name: String,
92 pending: VecDeque<T>,
93 persisted_pending: Option<PersistedQueue<T>>,
94 total_in_memory_bytes: u64,
95 max_in_memory_bytes: u64,
96 flush_to_disk_mem_ratio: f64,
97}
98
99impl<T> RetryQueue<T>
100where
101 T: Retryable,
102{
103 pub fn new(queue_name: String, max_in_memory_bytes: u64) -> Self {
109 Self {
110 queue_name,
111 pending: VecDeque::new(),
112 persisted_pending: None,
113 total_in_memory_bytes: 0,
114 max_in_memory_bytes,
115 flush_to_disk_mem_ratio: DEFAULT_FLUSH_TO_DISK_MEM_RATIO,
116 }
117 }
118
119 pub fn with_flush_to_disk_mem_ratio(mut self, flush_to_disk_mem_ratio: f64) -> Self {
126 self.flush_to_disk_mem_ratio = flush_to_disk_mem_ratio;
127 self
128 }
129
130 pub async fn with_disk_persistence(mut self, mut args: PersistedQueueArgs) -> Result<Self, GenericError> {
146 if args.root_path.as_os_str().is_empty() {
149 return Err(generic_error!("Storage path cannot be empty."));
150 }
151
152 args.root_path = args.root_path.join(&self.queue_name);
153 let mut persisted_pending = PersistedQueue::from_root_path(args).await?;
154 match persisted_pending.remove_stale_files().await {
155 Ok(removed) if removed > 0 => {
156 info!(count = removed, "Removed outdated retry files from disk.");
157 }
158 Ok(_) => {}
159 Err(e) => warn!(error = %e, "Failed to remove stale retry files."),
160 }
161 self.persisted_pending = Some(persisted_pending);
162 Ok(self)
163 }
164
165 pub fn is_empty(&self) -> bool {
169 self.pending.is_empty() && self.persisted_pending.as_ref().is_none_or(|p| p.is_empty())
170 }
171
172 pub fn len(&self) -> usize {
176 self.pending.len() + self.persisted_pending.as_ref().map_or(0, |p| p.len())
177 }
178
179 pub const fn max_in_memory_bytes(&self) -> u64 {
181 self.max_in_memory_bytes
182 }
183
184 pub const fn available_in_memory_capacity_bytes(&self) -> u64 {
186 self.max_in_memory_bytes.saturating_sub(self.total_in_memory_bytes)
187 }
188
189 pub async fn available_on_disk_capacity_bytes(&self) -> Result<u64, GenericError> {
198 match &self.persisted_pending {
199 Some(persisted_pending) => persisted_pending.available_capacity_bytes().await,
200 None => Ok(0),
201 }
202 }
203
204 pub fn take_persisted_entries_dropped(&mut self) -> u64 {
209 self.persisted_pending.as_mut().map_or(0, |p| p.take_entries_dropped())
210 }
211
212 pub async fn push(&mut self, entry: T) -> Result<PushResult, GenericError> {
225 let mut push_result = PushResult::default();
226
227 let current_entry_size = entry.size_bytes();
229 if current_entry_size > self.max_in_memory_bytes {
230 return Err(generic_error!(
231 "Entry too large to fit into retry queue. ({} > {})",
232 current_entry_size,
233 self.max_in_memory_bytes
234 ));
235 }
236
237 let required_bytes = self
240 .total_in_memory_bytes
241 .saturating_add(current_entry_size)
242 .saturating_sub(self.max_in_memory_bytes);
243 let using_disk = self.persisted_pending.is_some();
244 let bytes_to_remove = if using_disk && required_bytes > 0 {
245 required_bytes.max(flush_to_disk_bytes(
246 self.max_in_memory_bytes,
247 self.flush_to_disk_mem_ratio,
248 ))
249 } else {
250 required_bytes
251 };
252 let mut bytes_removed = 0;
253
254 while !self.pending.is_empty() && bytes_removed < bytes_to_remove {
255 let oldest_entry = self.pending.pop_front().expect("queue is not empty");
256 let oldest_entry_size = oldest_entry.size_bytes();
257
258 if using_disk {
259 let oldest_entry_events = oldest_entry.event_count();
262 let oldest_entry_data_points = oldest_entry.data_point_count();
263 let persisted_pending = self.persisted_pending.as_mut().expect("disk persistence is enabled");
264 match persisted_pending.push(oldest_entry).await {
265 Ok(persist_result) => {
266 push_result.merge(persist_result);
267 debug!(entry.len = oldest_entry_size, "Moved in-memory entry to disk.");
268 }
269 Err(e) => {
270 warn!(
274 error = %e,
275 entry.len = oldest_entry_size,
276 "Failed to persist in-memory entry to disk; dropping entry to make room."
277 );
278 push_result.items_dropped += 1;
279 push_result.events_dropped += oldest_entry_events;
280 push_result.data_points_dropped += oldest_entry_data_points;
281 push_result.bytes_dropped += oldest_entry_size;
282 }
283 }
284 } else {
285 debug!(
286 entry.len = oldest_entry_size,
287 "Dropped in-memory entry to increase available capacity."
288 );
289
290 push_result.track_dropped_item(&oldest_entry);
291
292 saluki_antithesis::sometimes!(true, "retry queue dropped oldest in-memory entry on overflow");
295 }
296
297 self.total_in_memory_bytes -= oldest_entry_size;
298 bytes_removed += oldest_entry_size;
299 }
300
301 self.pending.push_back(entry);
302 self.total_in_memory_bytes += current_entry_size;
303
304 saluki_antithesis::always_le!(
307 self.total_in_memory_bytes,
308 self.max_in_memory_bytes,
309 "retry queue in-memory bytes within cap",
310 { "bytes": self.total_in_memory_bytes, "cap": self.max_in_memory_bytes }
311 );
312
313 debug!(entry.len = current_entry_size, "Enqueued in-memory entry.");
314
315 Ok(push_result)
316 }
317
318 pub async fn pop(&mut self) -> Result<Option<T>, GenericError> {
329 if let Some(entry) = self.pending.pop_front() {
331 self.total_in_memory_bytes -= entry.size_bytes();
332 debug!(entry.len = entry.size_bytes(), "Dequeued in-memory entry.");
333
334 return Ok(Some(entry));
335 }
336
337 if let Some(persisted_pending) = &mut self.persisted_pending {
339 if let Some(entry) = persisted_pending.pop().await? {
340 return Ok(Some(entry));
341 }
342 }
343
344 Ok(None)
345 }
346
347 pub async fn flush(mut self) -> Result<PushResult, GenericError> {
357 let mut push_result = PushResult::default();
358
359 while let Some(entry) = self.pending.pop_front() {
360 let entry_size = entry.size_bytes();
361
362 if let Some(persisted_pending) = &mut self.persisted_pending {
363 let persist_result = persisted_pending.push(entry).await?;
364 push_result.merge(persist_result);
365
366 debug!(entry.len = entry_size, "Flushed in-memory entry to disk.");
367 } else {
368 debug!(entry.len = entry_size, "Dropped in-memory entry during flush.");
369
370 push_result.track_dropped_item(&entry);
371 }
372 }
373
374 Ok(push_result)
375 }
376}
377
378fn flush_to_disk_bytes(max_in_memory_bytes: u64, flush_to_disk_mem_ratio: f64) -> u64 {
379 if flush_to_disk_mem_ratio <= 0.0 || flush_to_disk_mem_ratio.is_nan() {
380 0
381 } else if flush_to_disk_mem_ratio.is_infinite() {
382 u64::MAX
383 } else {
384 ((max_in_memory_bytes as f64) * flush_to_disk_mem_ratio) as u64
386 }
387}
388
389#[cfg(test)]
390mod tests {
391 use std::{path::Path, sync::Arc};
392
393 use rand::RngExt as _;
394 use rand_distr::Alphanumeric;
395 use serde::Deserialize;
396
397 use super::*;
398
399 #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
400 struct FakeData {
401 name: String,
402 value: u32,
403 }
404
405 impl FakeData {
406 fn random() -> Self {
407 Self {
408 name: rand::rng().sample_iter(&Alphanumeric).take(8).map(char::from).collect(),
409 value: rand::rng().random_range(0..100),
410 }
411 }
412 }
413
414 impl EventContainer for FakeData {
415 fn event_count(&self) -> u64 {
416 1
417 }
418 }
419
420 impl Retryable for FakeData {
421 fn size_bytes(&self) -> u64 {
422 (self.name.len() + std::mem::size_of::<String>() + 4) as u64
423 }
424 }
425
426 fn file_count_recursive<P: AsRef<Path>>(path: P) -> u64 {
427 let mut count = 0;
428 let entries = std::fs::read_dir(path).expect("should not fail to read directory");
429 for maybe_entry in entries {
430 let entry = maybe_entry.expect("should not fail to read directory entry");
431 if entry.file_type().expect("should not fail to get file type").is_file() {
432 count += 1;
433 } else if entry.file_type().expect("should not fail to get file type").is_dir() {
434 count += file_count_recursive(entry.path());
435 }
436 }
437 count
438 }
439
440 #[tokio::test]
441 async fn basic_push_pop() {
442 let data = FakeData::random();
443
444 let mut retry_queue = RetryQueue::<FakeData>::new("test".to_string(), 1024);
445
446 let push_result = retry_queue
448 .push(data.clone())
449 .await
450 .expect("should not fail to push data");
451 assert_eq!(0, push_result.items_dropped);
452 assert_eq!(0, push_result.events_dropped);
453
454 let actual = retry_queue
456 .pop()
457 .await
458 .expect("should not fail to pop data")
459 .expect("should not be empty");
460 assert_eq!(data, actual);
461 }
462
463 #[tokio::test]
464 async fn capacity_accessors_report_memory_and_disk_capacity() {
465 let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
466 let root_path = temp_dir.path().to_path_buf();
467 let mut retry_queue = RetryQueue::<FakeData>::new("test".to_string(), 36)
468 .with_disk_persistence(PersistedQueueArgs {
469 root_path: root_path.clone(),
470 max_on_disk_bytes: 1024,
471 storage_max_disk_ratio: 1.0,
472 disk_usage_retriever: Arc::new(DiskUsageRetrieverImpl::new(root_path)),
473 max_age_days: 10,
474 })
475 .await
476 .expect("should not fail to create retry queue with disk persistence");
477
478 assert_eq!(retry_queue.max_in_memory_bytes(), 36);
479 assert_eq!(retry_queue.available_in_memory_capacity_bytes(), 36);
480 assert_eq!(
481 retry_queue
482 .available_on_disk_capacity_bytes()
483 .await
484 .expect("should not fail to calculate disk capacity"),
485 1024
486 );
487
488 let push_result = retry_queue
489 .push(FakeData::random())
490 .await
491 .expect("first push should succeed");
492 assert!(!push_result.had_drops());
493 assert_eq!(retry_queue.available_in_memory_capacity_bytes(), 0);
494 let push_result = retry_queue
495 .push(FakeData::random())
496 .await
497 .expect("second push should persist the oldest entry");
498 assert!(!push_result.had_drops());
499 assert_eq!(retry_queue.available_in_memory_capacity_bytes(), 0);
500
501 assert!(
502 retry_queue
503 .available_on_disk_capacity_bytes()
504 .await
505 .expect("should not fail to calculate disk capacity")
506 < 1024
507 );
508
509 let _ = retry_queue.pop().await.expect("pop should succeed");
510 assert_eq!(retry_queue.available_in_memory_capacity_bytes(), 36);
511 }
512
513 #[tokio::test]
514 async fn entry_too_large() {
515 let data = FakeData::random();
516
517 let mut retry_queue = RetryQueue::<FakeData>::new("test".to_string(), 1);
518
519 assert!(retry_queue.push(data).await.is_err());
521 }
522
523 #[tokio::test]
524 async fn remove_oldest_entry_on_push() {
525 let data1 = FakeData::random();
526 let data2 = FakeData::random();
527
528 let mut retry_queue = RetryQueue::<FakeData>::new("test".to_string(), 36);
530
531 let data1_size = data1.size_bytes();
533 let push_result = retry_queue.push(data1).await.expect("should not fail to push data");
534 assert_eq!(0, push_result.items_dropped);
535 assert_eq!(0, push_result.events_dropped);
536 assert_eq!(0, push_result.bytes_dropped);
537
538 let push_result = retry_queue
540 .push(data2.clone())
541 .await
542 .expect("should not fail to push data");
543 assert_eq!(1, push_result.items_dropped);
544 assert_eq!(1, push_result.events_dropped);
545 assert_eq!(data1_size, push_result.bytes_dropped);
546
547 let actual = retry_queue
550 .pop()
551 .await
552 .expect("should not fail to pop data")
553 .expect("should not be empty");
554 assert_eq!(data2, actual);
555 }
556
557 #[tokio::test]
558 async fn flush_no_disk() {
559 let data1 = FakeData::random();
560 let data2 = FakeData::random();
561
562 let mut retry_queue = RetryQueue::<FakeData>::new("test".to_string(), u64::MAX);
564 let total_size = data1.size_bytes() + data2.size_bytes();
565
566 let push_result1 = retry_queue.push(data1).await.expect("should not fail to push data");
568 assert_eq!(0, push_result1.items_dropped);
569 assert_eq!(0, push_result1.events_dropped);
570 let push_result2 = retry_queue.push(data2).await.expect("should not fail to push data");
571 assert_eq!(0, push_result2.items_dropped);
572 assert_eq!(0, push_result2.events_dropped);
573
574 let flush_result = retry_queue.flush().await.expect("should not fail to flush");
576 assert_eq!(2, flush_result.items_dropped);
577 assert_eq!(2, flush_result.events_dropped);
578 assert_eq!(total_size, flush_result.bytes_dropped);
579 }
580
581 #[tokio::test]
582 async fn flush_disk() {
583 let data1 = FakeData::random();
584 let data2 = FakeData::random();
585
586 let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
588 let root_path = temp_dir.path().to_path_buf();
589
590 assert_eq!(0, file_count_recursive(&root_path));
592
593 let mut retry_queue = RetryQueue::<FakeData>::new("test".to_string(), u64::MAX)
594 .with_disk_persistence(PersistedQueueArgs {
595 root_path: root_path.clone(),
596 max_on_disk_bytes: u64::MAX,
597 storage_max_disk_ratio: 1.0,
598 disk_usage_retriever: Arc::new(DiskUsageRetrieverImpl::new(root_path.clone())),
599 max_age_days: 10,
600 })
601 .await
602 .expect("should not fail to create retry queue with disk persistence");
603
604 let push_result1 = retry_queue.push(data1).await.expect("should not fail to push data");
606 assert_eq!(0, push_result1.items_dropped);
607 assert_eq!(0, push_result1.events_dropped);
608 let push_result2 = retry_queue.push(data2).await.expect("should not fail to push data");
609 assert_eq!(0, push_result2.items_dropped);
610 assert_eq!(0, push_result2.events_dropped);
611
612 let flush_result = retry_queue.flush().await.expect("should not fail to flush");
614 assert_eq!(0, flush_result.items_dropped);
615 assert_eq!(0, flush_result.events_dropped);
616
617 assert_eq!(2, file_count_recursive(&root_path));
619 }
620
621 #[tokio::test]
622 async fn disk_overflow_flushes_configured_memory_ratio() {
623 let data1 = FakeData::random();
624 let data2 = FakeData::random();
625 let data3 = FakeData::random();
626 let data4 = FakeData::random();
627
628 let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
629 let root_path = temp_dir.path().to_path_buf();
630
631 let mut retry_queue = RetryQueue::<FakeData>::new("test".to_string(), 120)
632 .with_flush_to_disk_mem_ratio(0.5)
633 .with_disk_persistence(PersistedQueueArgs {
634 root_path: root_path.clone(),
635 max_on_disk_bytes: u64::MAX,
636 storage_max_disk_ratio: 1.0,
637 disk_usage_retriever: Arc::new(DiskUsageRetrieverImpl::new(root_path.clone())),
638 max_age_days: 10,
639 })
640 .await
641 .expect("should not fail to create retry queue with disk persistence");
642
643 let push_result = retry_queue
644 .push(data1.clone())
645 .await
646 .expect("should not fail to push data");
647 assert_eq!(0, push_result.items_dropped);
648 assert_eq!(0, push_result.events_dropped);
649 let push_result = retry_queue
650 .push(data2.clone())
651 .await
652 .expect("should not fail to push data");
653 assert_eq!(0, push_result.items_dropped);
654 assert_eq!(0, push_result.events_dropped);
655 let push_result = retry_queue
656 .push(data3.clone())
657 .await
658 .expect("should not fail to push data");
659 assert_eq!(0, push_result.items_dropped);
660 assert_eq!(0, push_result.events_dropped);
661
662 let push_result = retry_queue
663 .push(data4.clone())
664 .await
665 .expect("should not fail to push data");
666 assert_eq!(0, push_result.items_dropped);
667 assert_eq!(0, push_result.events_dropped);
668 assert!(file_count_recursive(&root_path) >= 2);
669
670 let actual = retry_queue
673 .pop()
674 .await
675 .expect("should not fail to pop data")
676 .expect("should not be empty");
677 assert_eq!(data3, actual);
678
679 let actual = retry_queue
680 .pop()
681 .await
682 .expect("should not fail to pop data")
683 .expect("should not be empty");
684 assert_eq!(data4, actual);
685
686 let actual = retry_queue
687 .pop()
688 .await
689 .expect("should not fail to pop data")
690 .expect("should not be empty");
691 assert_eq!(data1, actual);
692
693 let actual = retry_queue
694 .pop()
695 .await
696 .expect("should not fail to pop data")
697 .expect("should not be empty");
698 assert_eq!(data2, actual);
699 }
700
701 #[tokio::test]
702 async fn zero_disk_flush_ratio_persists_required_entries() {
703 let data1 = FakeData::random();
704 let data2 = FakeData::random();
705 let data3 = FakeData::random();
706
707 let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
708 let root_path = temp_dir.path().to_path_buf();
709
710 let mut retry_queue = RetryQueue::<FakeData>::new("test".to_string(), 72)
711 .with_flush_to_disk_mem_ratio(0.0)
712 .with_disk_persistence(PersistedQueueArgs {
713 root_path: root_path.clone(),
714 max_on_disk_bytes: u64::MAX,
715 storage_max_disk_ratio: 1.0,
716 disk_usage_retriever: Arc::new(DiskUsageRetrieverImpl::new(root_path.clone())),
717 max_age_days: 10,
718 })
719 .await
720 .expect("should not fail to create retry queue with disk persistence");
721
722 let push_result = retry_queue
723 .push(data1.clone())
724 .await
725 .expect("should not fail to push data");
726 assert_eq!(0, push_result.items_dropped);
727 assert_eq!(0, push_result.events_dropped);
728 let push_result = retry_queue
729 .push(data2.clone())
730 .await
731 .expect("should not fail to push data");
732 assert_eq!(0, push_result.items_dropped);
733 assert_eq!(0, push_result.events_dropped);
734
735 let push_result = retry_queue
736 .push(data3.clone())
737 .await
738 .expect("should not fail to push data");
739 assert_eq!(0, push_result.items_dropped);
740 assert_eq!(0, push_result.events_dropped);
741 assert_eq!(1, file_count_recursive(&root_path));
742
743 let actual = retry_queue
744 .pop()
745 .await
746 .expect("should not fail to pop data")
747 .expect("should not be empty");
748 assert_eq!(data2, actual);
749
750 let actual = retry_queue
751 .pop()
752 .await
753 .expect("should not fail to pop data")
754 .expect("should not be empty");
755 assert_eq!(data3, actual);
756
757 let actual = retry_queue
758 .pop()
759 .await
760 .expect("should not fail to pop data")
761 .expect("should not be empty");
762 assert_eq!(data1, actual);
763 }
764}