Skip to main content

saluki_io/net/util/retry/queue/
mod.rs

1use 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
13/// A container that holds events.
14///
15/// This trait is used as an incredibly generic way to expose the number of events within a "container," which we
16/// loosely define to be anything that's holding events in some form. This is primarily used to track the number of
17/// events dropped by `RetryQueue` (and `PersistedQueue`) when entries have to be dropped due to size limits.
18pub trait EventContainer {
19    /// Returns the number of events represented by this container.
20    fn event_count(&self) -> u64;
21
22    /// Returns the number of metric data points represented by this container.
23    fn data_point_count(&self) -> u64 {
24        0
25    }
26}
27
28/// A value that can be retried.
29pub trait Retryable: EventContainer + DeserializeOwned + Serialize {
30    /// Returns the in-memory size of this value, in bytes.
31    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/// Result of a push operation.
47///
48/// As pushing items to `RetryQueue` may result in dropping older items to make room for new ones, this struct tracks
49/// the total number of items dropped, the number of events represented by those items, and their size.
50#[derive(Default)]
51#[must_use = "`PushResult` carries information about potentially dropped items/events and should not be ignored"]
52pub struct PushResult {
53    /// Total number of items dropped.
54    pub items_dropped: u64,
55
56    /// Total number of events represented by the dropped items.
57    pub events_dropped: u64,
58
59    /// Total number of metric data points represented by the dropped items.
60    pub data_points_dropped: u64,
61
62    /// Total size of the dropped items, in bytes, as reported by [`Retryable::size_bytes`].
63    pub bytes_dropped: u64,
64}
65
66impl PushResult {
67    /// Returns `true` if any items were dropped.
68    pub fn had_drops(&self) -> bool {
69        self.items_dropped > 0
70    }
71
72    /// Merges `other` into `Self`.
73    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    /// Tracks a single dropped item.
81    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
89/// A queue for storing requests to be retried.
90pub 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    /// Creates a new `RetryQueue` instance with the given name and maximum size.
104    ///
105    /// The queue will only hold as many entries as can fit within the given maximum size. If the queue is full, the
106    /// oldest entries will be removed (or potentially persisted to disk, see
107    /// [`with_disk_persistence`][Self::with_disk_persistence]) to make room for new entries.
108    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    /// Configures the ratio of in-memory queue bytes to flush to disk when the queue is full.
120    ///
121    /// When disk persistence is enabled and the queue does not have enough room for a new entry, this ratio controls how
122    /// much in-memory data is moved to disk. For example, a value of `0.5` moves at least half of
123    /// `max_in_memory_bytes` to disk when the queue overflows. Values less than or equal to zero disable extra batch
124    /// flushing, but entries evicted to make room are still persisted when disk persistence is enabled.
125    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    /// Configures the queue to persist pending entries to disk.
131    ///
132    /// Disk persistence is used as a fallback to in-memory storage when the queue is full. When attempting to add a new
133    /// entry to the queue, and the queue can't fit the entry in-memory, in-memory entries will be persisted to disk,
134    /// oldest first.
135    ///
136    /// When reading entries from the queue, in-memory entries are read first, followed by persisted entries. This
137    /// provides priority to the most recent entries added to the queue, but allows for bursting over the configured
138    /// in-memory size limit without having to immediately discard entries.
139    ///
140    /// Files are stored in a subdirectory, with the same name as the given queue name, within `args.root_path`.
141    ///
142    /// # Errors
143    ///
144    /// If there is an error initializing the disk persistence layer, an error is returned.
145    pub async fn with_disk_persistence(mut self, mut args: PersistedQueueArgs) -> Result<Self, GenericError> {
146        // Make sure the root storage path is non-empty, as otherwise we can't generate a valid path
147        // for the persisted entries in this retry queue.
148        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    /// Returns `true` if the queue is empty.
166    ///
167    /// This includes both in-memory and persisted entries.
168    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    /// Returns the number of entries in the queue
173    ///
174    /// This includes both in-memory and persisted entries.
175    pub fn len(&self) -> usize {
176        self.pending.len() + self.persisted_pending.as_ref().map_or(0, |p| p.len())
177    }
178
179    /// Returns the maximum in-memory capacity, in bytes.
180    pub const fn max_in_memory_bytes(&self) -> u64 {
181        self.max_in_memory_bytes
182    }
183
184    /// Returns the available in-memory capacity, in bytes.
185    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    /// Returns the available on-disk capacity, in bytes.
190    ///
191    /// Returns `0` when disk persistence is not enabled.
192    ///
193    /// # Errors
194    ///
195    /// If disk persistence is enabled and there is an error while retrieving the underlying disk capacity, an error is
196    /// returned.
197    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    /// Returns the number of persisted entries that have been permanently dropped due to errors since the last call
205    /// to this method, resetting the counter.
206    ///
207    /// Always returns 0 if disk persistence isn't enabled.
208    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    /// Enqueues an entry.
213    ///
214    /// If the queue is full and the entry can't be enqueued in-memory, in-memory entries (oldest first) are evicted
215    /// until there is room for the new entry. When disk persistence is enabled, evicted entries are moved to disk. If the
216    /// flush-to-disk ratio is greater than zero, eviction moves at least
217    /// `max_in_memory_bytes * flush_to_disk_mem_ratio` bytes of in-memory data to disk before admitting the new entry. If
218    /// disk persistence is disabled, evicted entries are dropped instead. If an in-memory entry can't be persisted due to
219    /// a disk error, that entry is dropped and counted in the returned `PushResult`; the new entry is still enqueued.
220    ///
221    /// # Errors
222    ///
223    /// If the entry is too large to fit into the queue, an error is returned.
224    pub async fn push(&mut self, entry: T) -> Result<PushResult, GenericError> {
225        let mut push_result = PushResult::default();
226
227        // Make sure the entry, by itself, isn't too big to ever fit into the queue.
228        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        // Make sure we have enough room for this incoming entry, either by persisting older entries to disk or by
238        // simply dropping them.
239        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                // Capture the dropped-event counts before moving `oldest_entry` into the persist call, so we can still
260                // record drop telemetry if the disk write fails.
261                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                        // Match the upstream Agent: on disk persistence failure, drop this entry and continue evicting
271                        // so the new entry can still be admitted to the queue. Propagating the error here would
272                        // permanently lose the incoming transaction at the caller, which the Agent does not do.
273                        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                // Anchor the overflow-drop path: a prolonged outage saturates the queue and sheds the oldest entry
293                // (bounded memory at the cost of counted data loss).
294                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        // The eviction loop above guarantees we stay within the in-memory byte cap. Assert the invariant; numeric form
305        // hands the search the headroom to the cap as a gradient.
306        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    /// Consumes an entry.
319    ///
320    /// In-memory entries are consumed first, followed by persisted entries if disk persistence is enabled.
321    ///
322    /// If no entries are available, `None` is returned.
323    ///
324    /// # Errors
325    ///
326    /// If there is an error when consuming an entry from disk, whether due to reading or deserializing the entry, an
327    /// error is returned.
328    pub async fn pop(&mut self) -> Result<Option<T>, GenericError> {
329        // Pull from in-memory first to prioritize the most recent entries.
330        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 we have disk persistence enabled, pull from disk next.
338        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    /// Flushes all entries, potentially persisting them to disk.
348    ///
349    /// When disk persistence is configured, this will flush all in-memory entries to disk. Flushing to disk still obeys
350    /// the normal limiting behavior in terms of maximum on-disk size. When disk persistence isn't enabled, all
351    /// in-memory entries will be dropped.
352    ///
353    /// # Errors
354    ///
355    /// If an error occurs while persisting an entry to disk, an error is returned.
356    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        // Truncate toward zero to match the upstream Agent's `int(maxMemSizeInBytes * flushToStorageRatio)` semantics.
385        ((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        // Push our data to the queue.
447        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        // Now pop the data back out and ensure it matches what we pushed, and that the file has been removed from disk.
455        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        // Attempt to push our data into the queue, which should fail because it's too large.
520        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        // Create our retry queue such that it is sized to only fit one entry at a time.
529        let mut retry_queue = RetryQueue::<FakeData>::new("test".to_string(), 36);
530
531        // Push our data to the queue.
532        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        // Push a second data entry, which should cause the first entry to be removed.
539        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        // Now pop the data back out and ensure it matches the second item we pushed, indicating the first item was
548        // removed from the queue to make room.
549        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        // Create our retry queue such that it can hold both items.
563        let mut retry_queue = RetryQueue::<FakeData>::new("test".to_string(), u64::MAX);
564        let total_size = data1.size_bytes() + data2.size_bytes();
565
566        // Push our data to the queue.
567        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        // Flush the queue, which should drop all entries as we have no disk persistence layer configured.
575        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        // Create our retry queue such that it can hold both items, and enable disk persistence.
587        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        // Just a sanity check to ensure our temp directory is empty.
591        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        // Push our data to the queue.
605        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        // Flush the queue, which should push all entries to disk.
613        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        // We should now have two files on disk after flushing.
618        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        // In-memory entries are popped first (data3, data4), followed by the entries that were flushed to disk
671        // (data1, data2 in FIFO order).
672        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}