Skip to main content

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

1use std::{
2    io,
3    marker::PhantomData,
4    path::{Path, PathBuf},
5    sync::Arc,
6};
7
8use fs4::{available_space, total_space};
9use rand::RngExt as _;
10use saluki_common::time::{parse_compact_utc_nanos, Timestamp, TimestampFormat};
11use saluki_error::{generic_error, ErrorContext as _, GenericError};
12use serde::de::DeserializeOwned;
13use tracing::{debug, error, info, warn};
14
15use super::{PushResult, Retryable};
16
17/// A persisted entry.
18///
19/// Represents the high-level metadata of a persisted entry, including the path to and size of the entry.
20struct PersistedEntry {
21    path: PathBuf,
22    timestamp: u128,
23    size_bytes: u64,
24}
25
26impl PersistedEntry {
27    /// Attempts to create a `PersistedEntry` from the given path.
28    ///
29    /// If the given path isn't recognized as the path to a valid persisted entry, `None` is returned.
30    fn try_from_path(path: PathBuf, size_bytes: u64) -> Option<Self> {
31        let timestamp = decode_timestamped_filename(&path)?;
32        Some(Self {
33            path,
34            timestamp,
35            size_bytes,
36        })
37    }
38
39    fn from_parts(path: PathBuf, timestamp: u128, size_bytes: u64) -> Self {
40        Self {
41            path,
42            timestamp,
43            size_bytes,
44        }
45    }
46}
47
48pub trait DiskUsageRetriever {
49    fn total_space(&self) -> Result<u64, GenericError>;
50    fn available_space(&self) -> Result<u64, GenericError>;
51}
52
53pub struct DiskUsageRetrieverImpl {
54    root_path: PathBuf,
55}
56
57impl DiskUsageRetrieverImpl {
58    pub fn new(root_path: PathBuf) -> Self {
59        Self { root_path }
60    }
61}
62
63impl DiskUsageRetriever for DiskUsageRetrieverImpl {
64    fn total_space(&self) -> Result<u64, GenericError> {
65        total_space(&self.root_path)
66            .with_error_context(|| format!("Failed to get total space for '{}'.", self.root_path.display()))
67    }
68
69    fn available_space(&self) -> Result<u64, GenericError> {
70        available_space(&self.root_path)
71            .with_error_context(|| format!("Failed to get available space for '{}'.", self.root_path.display()))
72    }
73}
74
75#[derive(Clone)]
76pub struct DiskUsageRetrieverWrapper {
77    inner: Arc<dyn DiskUsageRetriever + Send + Sync>,
78}
79
80impl DiskUsageRetrieverWrapper {
81    pub fn new(disk_usage_retriever: Arc<dyn DiskUsageRetriever + Send + Sync>) -> Self {
82        Self {
83            inner: disk_usage_retriever,
84        }
85    }
86}
87
88/// Arguments for constructing a persisted retry queue.
89pub struct PersistedQueueArgs {
90    /// Root path under which the queue directory is created.
91    pub root_path: PathBuf,
92    /// Maximum total bytes the queue may occupy on disk.
93    pub max_on_disk_bytes: u64,
94    /// Maximum fraction of the disk that may be used before writes stop.
95    pub storage_max_disk_ratio: f64,
96    /// Provider for total- and available-disk-space queries.
97    pub disk_usage_retriever: Arc<dyn DiskUsageRetriever + Send + Sync>,
98    /// Maximum age of retry files in days; files older than this are removed on startup.
99    ///
100    /// Setting this to `0` removes all retry files (cutoff = now), matching the behavior of the
101    /// core Agent's `FileRemovalPolicy` with `outdatedFileDayCount = 0`.
102    pub max_age_days: u32,
103}
104
105pub struct PersistedQueue<T> {
106    root_path: PathBuf,
107    entries: Vec<PersistedEntry>,
108    total_on_disk_bytes: u64,
109    max_on_disk_bytes: u64,
110    storage_max_disk_ratio: f64,
111    disk_usage_retriever: DiskUsageRetrieverWrapper,
112    max_age_days: u32,
113    entries_dropped: u64,
114    _entry: PhantomData<T>,
115}
116
117impl<T> PersistedQueue<T>
118where
119    T: Retryable,
120{
121    /// Creates a new `PersistedQueue` instance from the given arguments.
122    ///
123    /// The root path is created if it doesn't already exist, and is scanned for existing persisted entries. Entries
124    /// are removed (oldest first) until the total size of all scanned entries is within the given maximum size.
125    ///
126    /// To remove stale retry files on startup, call [`remove_stale_files`][Self::remove_stale_files] after construction.
127    ///
128    /// # Errors
129    ///
130    /// If there is an error creating the root directory, or scanning it for existing entries, or deleting entries to
131    /// shrink the directory to fit the given maximum size, an error is returned.
132    pub async fn from_root_path(args: PersistedQueueArgs) -> Result<Self, GenericError> {
133        let PersistedQueueArgs {
134            root_path,
135            max_on_disk_bytes,
136            storage_max_disk_ratio,
137            disk_usage_retriever,
138            max_age_days,
139        } = args;
140
141        // Make sure the directory exists first.
142        create_directory_recursive(root_path.clone())
143            .await
144            .with_error_context(|| format!("Failed to create retry directory '{}'.", root_path.display()))?;
145
146        let mut persisted_requests = Self {
147            root_path: root_path.clone(),
148            entries: Vec::new(),
149            total_on_disk_bytes: 0,
150            max_on_disk_bytes,
151            storage_max_disk_ratio,
152            disk_usage_retriever: DiskUsageRetrieverWrapper::new(disk_usage_retriever),
153            max_age_days,
154            entries_dropped: 0,
155            _entry: PhantomData,
156        };
157
158        persisted_requests.refresh_entry_state().await?;
159
160        info!(
161            "Persisted retry queue initialized. Transactions will be stored in '{}'.",
162            root_path.display()
163        );
164
165        Ok(persisted_requests)
166    }
167
168    /// Returns `true` if the queue is empty.
169    pub fn is_empty(&self) -> bool {
170        self.entries.is_empty()
171    }
172
173    /// Returns the number of entries in the queue.
174    pub fn len(&self) -> usize {
175        self.entries.len()
176    }
177
178    /// Returns the available on-disk capacity, in bytes.
179    ///
180    /// This reflects the lower of the configured queue limit and disk-usage-ratio limit, minus the bytes currently used
181    /// by persisted entries.
182    ///
183    /// # Errors
184    ///
185    /// If there is an error while retrieving the total or available space of the underlying volume, an error is returned.
186    pub async fn available_capacity_bytes(&self) -> Result<u64, GenericError> {
187        let disk_usage_retriever = self.disk_usage_retriever.clone();
188        let storage_max_disk_ratio = self.storage_max_disk_ratio;
189        let max_on_disk_bytes = self.max_on_disk_bytes;
190        let total_on_disk_bytes = self.total_on_disk_bytes;
191
192        let limit = tokio::task::spawn_blocking(move || {
193            on_disk_bytes_limit(
194                disk_usage_retriever,
195                storage_max_disk_ratio,
196                max_on_disk_bytes,
197                total_on_disk_bytes,
198            )
199        })
200        .await
201        .error_context("Failed to run disk size limit check to completion.")??;
202
203        Ok(limit.saturating_sub(total_on_disk_bytes))
204    }
205
206    /// Returns the number of entries that have been permanently dropped due to errors since the last call to this
207    /// method, resetting the counter.
208    pub fn take_entries_dropped(&mut self) -> u64 {
209        std::mem::take(&mut self.entries_dropped)
210    }
211
212    /// Removes retry files older than `max_age_days` (from [`PersistedQueueArgs`]) from the queue directory and
213    /// reloads entry state.
214    ///
215    /// # Errors
216    ///
217    /// Returns an error if the queue directory cannot be opened or scanned. Individual file removal failures are
218    /// logged as warnings and do not stop the cleanup.
219    pub async fn remove_stale_files(&mut self) -> Result<u32, GenericError> {
220        let removed = remove_outdated_retry_files(&self.root_path, self.max_age_days).await?;
221        self.refresh_entry_state().await.map_err(GenericError::from)?;
222        Ok(removed)
223    }
224
225    /// Enqueues an entry and persists it to disk.
226    ///
227    /// # Errors
228    ///
229    /// If there is an error serializing the entry, or writing it to disk, or removing older entries to make space for
230    /// the new entry, an error is returned.
231    pub async fn push(&mut self, entry: T) -> Result<PushResult, GenericError> {
232        // Serialize the entry to a temporary file.
233        let (filename, timestamp) = generate_timestamped_filename()?;
234        let entry_path = self.root_path.join(filename);
235        let serialized = serde_json::to_vec(&entry)
236            .with_error_context(|| format!("Failed to serialize entry for '{}'.", entry_path.display()))?;
237
238        if serialized.len() as u64 > self.max_on_disk_bytes {
239            return Err(generic_error!("Entry is too large to persist."));
240        }
241
242        // Make sure we have enough space to persist the entry.
243        let push_result = self
244            .remove_until_available_space(serialized.len() as u64)
245            .await
246            .error_context(
247                "Failed to remove older persisted entries to make space for the incoming persisted entry.",
248            )?;
249
250        // Actually persist it.
251        tokio::fs::write(&entry_path, &serialized)
252            .await
253            .with_error_context(|| format!("Failed to write entry to '{}'.", entry_path.display()))?;
254
255        // Add a new persisted entry to our state.
256        self.entries.push(PersistedEntry::from_parts(
257            entry_path,
258            timestamp,
259            serialized.len() as u64,
260        ));
261        self.total_on_disk_bytes += serialized.len() as u64;
262
263        debug!(entry.len = serialized.len(), "Enqueued persisted entry.");
264
265        Ok(push_result)
266    }
267
268    /// Consumes the oldest persisted entry on disk, if one exists.
269    ///
270    /// # Errors
271    ///
272    /// If there is an error reading or deserializing the entry, an error is returned.
273    pub async fn pop(&mut self) -> Result<Option<T>, GenericError> {
274        loop {
275            if self.entries.is_empty() {
276                return Ok(None);
277            }
278
279            let entry = self.entries.remove(0);
280            match try_deserialize_entry(&entry).await {
281                Ok(Some(deserialized)) => {
282                    // We got the deserialized entry, so remove it from our state and return it.
283                    self.total_on_disk_bytes -= entry.size_bytes;
284                    debug!(entry.len = entry.size_bytes, "Dequeued persisted entry.");
285
286                    return Ok(Some(deserialized));
287                }
288                Ok(None) => {
289                    // We couldn't read the entry from disk, which points to us potentially having invalid state about
290                    // what entries _are_ on disk, so we'll refresh our entry state and try again.
291                    self.refresh_entry_state().await?;
292                    continue;
293                }
294                Err(e) => {
295                    // The entry is corrupt or unreadable. Drop it permanently to avoid a poison pill scenario
296                    // where the same entry is retried indefinitely, blocking all other work.
297                    warn!(
298                        entry.path = %entry.path.display(),
299                        entry.len = entry.size_bytes,
300                        error = %e,
301                        "Permanently dropping persisted entry that could not be consumed.",
302                    );
303
304                    self.total_on_disk_bytes -= entry.size_bytes;
305                    self.entries_dropped += 1;
306
307                    continue;
308                }
309            }
310        }
311    }
312
313    async fn refresh_entry_state(&mut self) -> io::Result<()> {
314        // Scan the root path for persisted entries.
315        let mut entries = Vec::new();
316
317        let mut dir_reader = tokio::fs::read_dir(&self.root_path).await?;
318        while let Some(entry) = dir_reader.next_entry().await? {
319            let metadata = entry.metadata().await?;
320            if metadata.is_file() {
321                match PersistedEntry::try_from_path(entry.path(), metadata.len()) {
322                    Some(entry) => entries.push(entry),
323                    None => {
324                        warn!(
325                            file_size = metadata.len(),
326                            "Ignoring unrecognized file '{}' in retry directory.",
327                            entry.path().display()
328                        );
329                        continue;
330                    }
331                }
332            }
333        }
334
335        // Sort the entries by their inherent timestamp.
336        entries.sort_by_key(|entry| entry.timestamp);
337        self.total_on_disk_bytes = entries.iter().map(|entry| entry.size_bytes).sum();
338        self.entries = entries;
339
340        Ok(())
341    }
342
343    /// Removes persisted entries (oldest first) until there is at least the required number of bytes in free space
344    /// (maximum - total).
345    ///
346    /// # Errors
347    ///
348    /// If there is an error while deleting persisted entries, an error is returned.
349    async fn remove_until_available_space(&mut self, required_bytes: u64) -> Result<PushResult, GenericError> {
350        let mut push_result = PushResult::default();
351
352        let disk_usage_retriever = self.disk_usage_retriever.clone();
353        let storage_max_disk_ratio = self.storage_max_disk_ratio;
354        let max_on_disk_bytes = self.max_on_disk_bytes;
355        let total_on_disk_bytes = self.total_on_disk_bytes;
356
357        // TODO: Evaluate the possible failures scenarios a little more thoroughly, and see if we can improve
358        // how we handle them instead of just bailing out.
359        //
360        // Essentially, it's not clear to me if we would expect this to fail in a way where we could actually
361        // still write the persistent entries to disk, and if it's worth it to do something like trying to
362        // cache the last known good value we get here to use if we fail to get a new value, etc.
363        let limit = tokio::task::spawn_blocking(move || {
364            on_disk_bytes_limit(
365                disk_usage_retriever,
366                storage_max_disk_ratio,
367                max_on_disk_bytes,
368                total_on_disk_bytes,
369            )
370        })
371        .await
372        .error_context("Failed to run disk size limit check to completion.")??;
373
374        while !self.entries.is_empty() && self.total_on_disk_bytes + required_bytes > limit {
375            let entry = self.entries.remove(0);
376
377            // Deserialize the entry, which gives us back the original event and removes the file from disk.
378            let deserialized = match try_deserialize_entry::<T>(&entry).await {
379                Ok(Some(deserialized)) => deserialized,
380                Ok(None) => {
381                    warn!(entry.path = %entry.path.display(), "Failed to find entry on disk. Persisted entry state may be inconsistent.");
382                    continue;
383                }
384                Err(e) => {
385                    // The entry is corrupt or unreadable. Drop it permanently to avoid blocking subsequent
386                    // entries from being evicted.
387                    warn!(
388                        entry.path = %entry.path.display(),
389                        entry.len = entry.size_bytes,
390                        error = %e,
391                        "Permanently dropping persisted entry that could not be consumed during eviction.",
392                    );
393
394                    self.total_on_disk_bytes -= entry.size_bytes;
395                    self.entries_dropped += 1;
396
397                    continue;
398                }
399            };
400
401            // Update our statistics.
402            self.total_on_disk_bytes -= entry.size_bytes;
403            push_result.track_dropped_item(&deserialized);
404
405            // The message text here is kept in sync with an equivalent log emitted by another implementation of
406            // this queue, so that log-based alerting on this condition matches regardless of which implementation
407            // is deployed.
408            error!(
409                entry.path = %entry.path.display(),
410                entry.len = entry.size_bytes,
411                "Maximum disk space for retry transactions is reached. Removing {}.",
412                entry.path.display()
413            );
414        }
415
416        Ok(push_result)
417    }
418}
419
420/// Determines the total number of bytes the queue may occupy on disk without causing the underlying volume to end up
421/// with more than `storage_max_disk_ratio` in terms of used space. The minimum of `max_on_disk_bytes` and the result
422/// of this calculation is returned.
423///
424/// The available space reported by the volume already excludes the queue's own files, so `total_on_disk_bytes` is
425/// added back in: the result is the queue's total allowance, not the space left on top of what it already uses.
426///
427/// # Errors
428///
429/// If there is an error while retrieving the total or available space of the underlying volume, an error is returned.
430fn on_disk_bytes_limit(
431    disk_usage_retriever: DiskUsageRetrieverWrapper, storage_max_disk_ratio: f64, max_on_disk_bytes: u64,
432    total_on_disk_bytes: u64,
433) -> Result<u64, GenericError> {
434    let total_space = disk_usage_retriever.inner.total_space()? as f64;
435    let available_space = disk_usage_retriever.inner.available_space()? as f64;
436    let disk_reserved = total_space * (1.0 - storage_max_disk_ratio);
437
438    // When the volume is already past the ratio, this goes negative and pulls the allowance below what the queue
439    // currently uses, so that existing entries get evicted. Casting to `u64` saturates the final result at zero.
440    let available_disk_usage = (total_on_disk_bytes as f64 + available_space - disk_reserved).ceil() as u64;
441    Ok(max_on_disk_bytes.min(available_disk_usage))
442}
443
444async fn try_deserialize_entry<T: DeserializeOwned>(entry: &PersistedEntry) -> Result<Option<T>, GenericError> {
445    let serialized = match tokio::fs::read(&entry.path).await {
446        Ok(serialized) => serialized,
447        Err(e) => match e.kind() {
448            io::ErrorKind::NotFound => {
449                // We tried to delete an entry that no longer exists on disk, which means our internal entry state
450                // is corrupted for some reason.
451                //
452                // Tell the caller that we couldn't find the entry on disk, so that they need to refresh the entry state
453                // to make sure it's up-to-date before trying again.
454                return Ok(None);
455            }
456            _ => {
457                return Err(e)
458                    .with_error_context(|| format!("Failed to read persisted entry '{}'.", entry.path.display()))
459            }
460        },
461    };
462
463    let deserialized = match serde_json::from_slice(&serialized) {
464        Ok(deserialized) => deserialized,
465        Err(e) => {
466            // Deserialization failed, which means the payload is corrupt or invalid. Attempt to clean up the
467            // file from disk so it doesn't accumulate, but don't fail if we can't.
468            if let Err(remove_err) = tokio::fs::remove_file(&entry.path).await {
469                warn!(
470                    entry.path = %entry.path.display(),
471                    error = %remove_err,
472                    "Failed to remove corrupt persisted entry from disk.",
473                );
474            }
475
476            return Err(e)
477                .with_error_context(|| format!("Failed to deserialize persisted entry '{}'.", entry.path.display()));
478        }
479    };
480
481    // Delete the entry from disk before returning, so that we don't risk sending duplicates.
482    tokio::fs::remove_file(&entry.path)
483        .await
484        .with_error_context(|| format!("Failed to delete persisted entry '{}'.", entry.path.display()))?;
485
486    debug!(entry.path = %entry.path.display(), entry.len = entry.size_bytes, "Consumed persisted entry and removed from disk.");
487    Ok(Some(deserialized))
488}
489
490fn generate_timestamped_filename() -> Result<(PathBuf, u128), GenericError> {
491    let now = Timestamp::now()?;
492    let now_ts = u128::try_from(now.as_unix_nanos())
493        .map_err(|_| generic_error!("System clock is set to before the Unix epoch."))?;
494    let nonce = rand::rng().random_range(100000000..999999999);
495
496    let filename = format!("retry-{}-{}.json", now.format(TimestampFormat::CompactUtcNanos), nonce).into();
497
498    Ok((filename, now_ts))
499}
500
501fn decode_timestamped_filename(path: &Path) -> Option<u128> {
502    let filename = path.file_stem()?.to_str()?;
503    let mut filename_parts = filename.split('-');
504
505    let prefix = filename_parts.next()?;
506    let timestamp_str = filename_parts.next()?;
507    let nonce = filename_parts.next()?;
508
509    // Make sure the filename matches our expected format by first checking the prefix and nonce portions.
510    if prefix != "retry" || nonce.parse::<u64>().is_err() {
511        return None;
512    }
513
514    // Every version has written the timestamp in `TimestampFormat::CompactUtcNanos`. Dates before the Unix epoch aren't
515    // recognized.
516    parse_compact_utc_nanos(timestamp_str).and_then(|nanos| u128::try_from(nanos).ok())
517}
518
519async fn create_directory_recursive(path: PathBuf) -> Result<(), GenericError> {
520    let mut dir_builder = std::fs::DirBuilder::new();
521    dir_builder.recursive(true);
522
523    // When on Unix platforms, adjust the permissions of the directory to be RWX for the owner only, and nothing for
524    // group/world.
525    #[cfg(unix)]
526    {
527        use std::os::unix::fs::DirBuilderExt;
528        dir_builder.mode(0o700);
529    }
530
531    tokio::task::spawn_blocking(move || {
532        dir_builder
533            .create(&path)
534            .with_error_context(|| format!("Failed to create directory '{}'.", path.display()))
535    })
536    .await
537    .error_context("Failed to spawn directory creation blocking task.")?
538}
539
540/// Deletes files in `queue_path` whose filename-embedded creation timestamp is older than
541/// `max_age_days`. Does nothing if the directory does not exist.
542///
543/// Setting `max_age_days` to `0` deletes all retry files (cutoff = now), matching the behavior
544/// of the core Agent's `FileRemovalPolicy` with `outdatedFileDayCount = 0`.
545async fn remove_outdated_retry_files(queue_path: &Path, max_age_days: u32) -> Result<u32, GenericError> {
546    let mut dir = match tokio::fs::read_dir(queue_path).await {
547        Ok(d) => d,
548        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),
549        Err(e) => {
550            return Err(e).with_error_context(|| {
551                format!(
552                    "Failed to open retry queue directory '{}' for age-based cleanup.",
553                    queue_path.display()
554                )
555            });
556        }
557    };
558    let now_ns = std::time::SystemTime::now()
559        .duration_since(std::time::UNIX_EPOCH)
560        .unwrap_or_default() // clock before epoch: treat cutoff as 0, skipping all deletions
561        .as_nanos();
562    let cutoff_ns = now_ns.saturating_sub(max_age_days as u128 * 24 * 3600 * 1_000_000_000);
563    let mut removed = 0u32;
564    loop {
565        let entry = match dir.next_entry().await {
566            Ok(Some(e)) => e,
567            Ok(None) => break,
568            Err(e) => {
569                return Err(e).with_error_context(|| "Error reading retry queue directory during age-based cleanup.");
570            }
571        };
572        let file_ts = match decode_timestamped_filename(&entry.path()) {
573            Some(ts) => ts,
574            None => continue,
575        };
576        if file_ts < cutoff_ns {
577            let name_str = entry.file_name();
578            let name = name_str.to_string_lossy();
579            match tokio::fs::remove_file(entry.path()).await {
580                Ok(()) => {
581                    debug!(file = %name, "Removed outdated retry file.");
582                    removed += 1;
583                }
584                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
585                    debug!(file = %name, "Retry file already removed by concurrent cleanup.");
586                }
587                Err(e) => {
588                    warn!(file = %name, error = %e, "Failed to remove outdated retry file.");
589                }
590            }
591        }
592    }
593    Ok(removed)
594}
595
596#[cfg(test)]
597mod tests {
598    use rand::RngExt as _;
599    use rand_distr::Alphanumeric;
600    use serde::{Deserialize, Serialize};
601
602    use super::*;
603    use crate::net::util::retry::EventContainer;
604
605    #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
606    struct FakeData {
607        name: String,
608        value: u32,
609    }
610
611    impl FakeData {
612        fn random() -> Self {
613            Self {
614                name: rand::rng().sample_iter(&Alphanumeric).take(8).map(char::from).collect(),
615                value: rand::rng().random_range(0..100),
616            }
617        }
618    }
619
620    impl EventContainer for FakeData {
621        fn event_count(&self) -> u64 {
622            1
623        }
624    }
625
626    impl Retryable for FakeData {
627        fn size_bytes(&self) -> u64 {
628            (self.name.len() + std::mem::size_of::<String>() + 4) as u64
629        }
630    }
631
632    struct MockDiskUsageRetriever {}
633
634    impl DiskUsageRetriever for MockDiskUsageRetriever {
635        fn total_space(&self) -> Result<u64, GenericError> {
636            Ok(100)
637        }
638        fn available_space(&self) -> Result<u64, GenericError> {
639            Ok(100)
640        }
641    }
642
643    /// A fake volume holding `other_used_bytes` of unrelated data plus whatever files are in `dir`.
644    ///
645    /// Like a real volume, the available space it reports shrinks as the queue writes entries.
646    struct DirBackedDiskUsageRetriever {
647        dir: PathBuf,
648        total_bytes: u64,
649        other_used_bytes: u64,
650    }
651
652    impl DiskUsageRetriever for DirBackedDiskUsageRetriever {
653        fn total_space(&self) -> Result<u64, GenericError> {
654            Ok(self.total_bytes)
655        }
656
657        fn available_space(&self) -> Result<u64, GenericError> {
658            let mut queue_bytes = 0;
659            for entry in std::fs::read_dir(&self.dir)? {
660                let metadata = entry?.metadata()?;
661                if metadata.is_file() {
662                    queue_bytes += metadata.len();
663                }
664            }
665            Ok(self.total_bytes - self.other_used_bytes - queue_bytes)
666        }
667    }
668
669    async fn files_in_dir(path: &Path) -> usize {
670        let mut file_count = 0;
671        let mut dir_reader = tokio::fs::read_dir(path).await.unwrap();
672        while let Some(entry) = dir_reader.next_entry().await.unwrap() {
673            if entry.metadata().await.unwrap().is_file() {
674                file_count += 1;
675            }
676        }
677        file_count
678    }
679
680    #[tokio::test]
681    async fn basic_push_pop() {
682        let data = FakeData::random();
683
684        // Create our temporary directory and point our persisted queue at it.
685        let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
686        let root_path = temp_dir.path().to_path_buf();
687
688        let mut persisted_queue = PersistedQueue::<FakeData>::from_root_path(PersistedQueueArgs {
689            root_path: root_path.clone(),
690            max_on_disk_bytes: 1024,
691            storage_max_disk_ratio: 0.8,
692            disk_usage_retriever: Arc::new(DiskUsageRetrieverImpl::new(root_path.clone())),
693            max_age_days: 10,
694        })
695        .await
696        .expect("should not fail to create persisted queue");
697
698        // Ensure the directory is empty.
699        assert_eq!(0, files_in_dir(&root_path).await);
700
701        // Push our data to the queue and ensure it persisted it to disk.
702        let push_result = persisted_queue
703            .push(data.clone())
704            .await
705            .expect("should not fail to push data");
706        assert_eq!(1, files_in_dir(&root_path).await);
707        assert_eq!(0, push_result.items_dropped);
708        assert_eq!(0, push_result.events_dropped);
709
710        // Now pop the data back out and ensure it matches what we pushed, and that the file has been removed from disk.
711        let actual = persisted_queue
712            .pop()
713            .await
714            .expect("should not fail to pop data")
715            .expect("should not be empty");
716        assert_eq!(data, actual);
717        assert_eq!(0, files_in_dir(&root_path).await);
718    }
719
720    #[tokio::test]
721    async fn entry_too_large() {
722        let data = FakeData::random();
723
724        // Create our temporary directory and point our persisted queue at it.
725        let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
726        let root_path = temp_dir.path().to_path_buf();
727
728        let mut persisted_queue = PersistedQueue::<FakeData>::from_root_path(PersistedQueueArgs {
729            root_path: root_path.clone(),
730            max_on_disk_bytes: 1,
731            storage_max_disk_ratio: 0.8,
732            disk_usage_retriever: Arc::new(DiskUsageRetrieverImpl::new(root_path.clone())),
733            max_age_days: 10,
734        })
735        .await
736        .expect("should not fail to create persisted queue");
737
738        // Ensure the directory is empty.
739        assert_eq!(0, files_in_dir(&root_path).await);
740
741        // Attempt to push our data into the queue, which should fail because it's too large.
742        assert!(persisted_queue.push(data).await.is_err());
743
744        // Ensure the directory is (still) empty.
745        assert_eq!(0, files_in_dir(&root_path).await);
746    }
747
748    #[tokio::test]
749    async fn remove_oldest_entry_on_push() {
750        let data1 = FakeData::random();
751        let data2 = FakeData::random();
752
753        // Create our temporary directory and point our persisted queue at it.
754        //
755        // Our queue is sized such that only one entry can be persisted at a time.
756        let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
757        let root_path = temp_dir.path().to_path_buf();
758
759        let mut persisted_queue = PersistedQueue::<FakeData>::from_root_path(PersistedQueueArgs {
760            root_path: root_path.clone(),
761            max_on_disk_bytes: 32,
762            storage_max_disk_ratio: 0.8,
763            disk_usage_retriever: Arc::new(DiskUsageRetrieverImpl::new(root_path.clone())),
764            max_age_days: 10,
765        })
766        .await
767        .expect("should not fail to create persisted queue");
768
769        // Ensure the directory is empty.
770        assert_eq!(0, files_in_dir(&root_path).await);
771
772        // Push our data to the queue and ensure it persisted it to disk.
773        let data1_size = data1.size_bytes();
774        let push_result = persisted_queue.push(data1).await.expect("should not fail to push data");
775        assert_eq!(1, files_in_dir(&root_path).await);
776        assert_eq!(0, push_result.items_dropped);
777        assert_eq!(0, push_result.events_dropped);
778        assert_eq!(0, push_result.bytes_dropped);
779
780        // Push a second data entry, which should cause the first entry to be removed.
781        let push_result = persisted_queue
782            .push(data2.clone())
783            .await
784            .expect("should not fail to push data");
785        assert_eq!(1, files_in_dir(&root_path).await);
786        assert_eq!(1, push_result.items_dropped);
787        assert_eq!(1, push_result.events_dropped);
788        assert_eq!(data1_size, push_result.bytes_dropped);
789
790        // Now pop the data back out and ensure it matches the second item we pushed -- indicating the first item was
791        // removed -- and that we've consumed it, leaving no files on disk.
792        let actual = persisted_queue
793            .pop()
794            .await
795            .expect("should not fail to pop data")
796            .expect("should not be empty");
797        assert_eq!(data2, actual);
798        assert_eq!(0, files_in_dir(&root_path).await);
799    }
800
801    #[tokio::test]
802    async fn storage_ratio_exceeded() {
803        let data1 = FakeData::random();
804        let data2 = FakeData::random();
805
806        // Create our temporary directory and point our persisted queue at it.
807        //
808        // Our queue is sized such that two entries can be persisted at a time.
809        let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
810        let root_path = temp_dir.path().to_path_buf();
811
812        let mut persisted_queue = PersistedQueue::<FakeData>::from_root_path(PersistedQueueArgs {
813            root_path: root_path.clone(),
814            max_on_disk_bytes: 80,
815            storage_max_disk_ratio: 0.35,
816            disk_usage_retriever: Arc::new(DirBackedDiskUsageRetriever {
817                dir: root_path.clone(),
818                total_bytes: 100,
819                other_used_bytes: 0,
820            }),
821            max_age_days: 10,
822        })
823        .await
824        .expect("should not fail to create persisted queue");
825
826        // Ensure the directory is empty.
827        assert_eq!(0, files_in_dir(&root_path).await);
828
829        // The `storage_max_disk_ratio` is 0.35 and the volume is 100 bytes with nothing else on it, so
830        // `on_disk_bytes_limit()` returns min(80, 35) = 35 regardless of how much the queue has written.
831        //
832        // First entry: total_on_disk_bytes(0) + required_bytes(30) < on_disk_bytes_limit(35)
833        let push_result = persisted_queue.push(data1).await.expect("should not fail to push data");
834
835        assert_eq!(1, files_in_dir(&root_path).await);
836        assert_eq!(0, push_result.items_dropped);
837        assert_eq!(0, push_result.events_dropped);
838
839        // Second entry: total_on_disk_bytes(30) + required_bytes(30) > on_disk_bytes_limit(35) so the first entry is dropped.
840        let push_result = persisted_queue
841            .push(data2.clone())
842            .await
843            .expect("should not fail to push data");
844        assert_eq!(1, files_in_dir(&root_path).await);
845        assert_eq!(1, push_result.items_dropped);
846        assert_eq!(1, push_result.events_dropped);
847
848        // Now pop the data back out and ensure it matches the second item we pushed -- indicating the first item was
849        // removed -- and that we've consumed it, leaving no files on disk.
850        let actual = persisted_queue
851            .pop()
852            .await
853            .expect("should not fail to pop data")
854            .expect("should not be empty");
855        assert_eq!(data2, actual);
856        assert_eq!(0, files_in_dir(&root_path).await);
857    }
858
859    #[tokio::test]
860    async fn storage_ratio_does_not_double_count_queue_bytes() {
861        let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
862        let root_path = temp_dir.path().to_path_buf();
863
864        // The volume is 1000 bytes with 400 bytes of unrelated data, and the ratio reserves 500 bytes, so the queue may
865        // occupy 100 bytes in total. Entries serialize to about 30 bytes each, so three fit.
866        let mut persisted_queue = PersistedQueue::<FakeData>::from_root_path(PersistedQueueArgs {
867            root_path: root_path.clone(),
868            max_on_disk_bytes: 1024,
869            storage_max_disk_ratio: 0.5,
870            disk_usage_retriever: Arc::new(DirBackedDiskUsageRetriever {
871                dir: root_path.clone(),
872                total_bytes: 1000,
873                other_used_bytes: 400,
874            }),
875            max_age_days: 10,
876        })
877        .await
878        .expect("should not fail to create persisted queue");
879
880        // Counting the queue's files twice would leave room for only two entries, evicting one on the third push.
881        for _ in 0..3 {
882            let push_result = persisted_queue
883                .push(FakeData::random())
884                .await
885                .expect("should not fail to push data");
886            assert_eq!(0, push_result.items_dropped);
887
888            let available = persisted_queue
889                .available_capacity_bytes()
890                .await
891                .expect("should not fail to get available capacity");
892            assert_eq!(100 - persisted_queue.total_on_disk_bytes, available);
893        }
894        assert_eq!(3, files_in_dir(&root_path).await);
895
896        // A fourth entry exceeds the 100-byte allowance, so the oldest entry is evicted.
897        let push_result = persisted_queue
898            .push(FakeData::random())
899            .await
900            .expect("should not fail to push data");
901        assert_eq!(1, push_result.items_dropped);
902        assert_eq!(3, files_in_dir(&root_path).await);
903    }
904
905    /// Writes a corrupt (non-JSON) file with a valid retry filename to the given directory, using a timestamp
906    /// that sorts before any real entries (so it will be popped first).
907    async fn write_corrupt_entry(dir: &Path) -> PathBuf {
908        let filename = "retry-20000101000000000000000-100000000.json";
909        let path = dir.join(filename);
910        tokio::fs::write(&path, b"this is not valid json").await.unwrap();
911        path
912    }
913
914    #[tokio::test]
915    async fn corrupt_entry_is_skipped_on_pop() {
916        let data = FakeData::random();
917
918        let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
919        let root_path = temp_dir.path().to_path_buf();
920
921        let mut persisted_queue = PersistedQueue::<FakeData>::from_root_path(PersistedQueueArgs {
922            root_path: root_path.clone(),
923            max_on_disk_bytes: 1024,
924            storage_max_disk_ratio: 0.8,
925            disk_usage_retriever: Arc::new(MockDiskUsageRetriever {}),
926            max_age_days: 10,
927        })
928        .await
929        .expect("should not fail to create persisted queue");
930
931        // Write a corrupt file before pushing valid data, so it sorts first.
932        let corrupt_path = write_corrupt_entry(&root_path).await;
933
934        // Push a valid entry.
935        let _ = persisted_queue
936            .push(data.clone())
937            .await
938            .expect("should not fail to push data");
939
940        // Refresh state so the queue picks up the corrupt file.
941        persisted_queue.refresh_entry_state().await.unwrap();
942
943        // Pop should skip the corrupt entry and return the valid one.
944        let actual = persisted_queue
945            .pop()
946            .await
947            .expect("should not fail to pop data")
948            .expect("should have a valid entry");
949        assert_eq!(data, actual);
950
951        // The corrupt file should have been cleaned up from disk.
952        assert!(!corrupt_path.exists());
953
954        // The dropped counter should reflect the corrupt entry.
955        assert_eq!(1, persisted_queue.take_entries_dropped());
956
957        // No files should remain.
958        assert_eq!(0, files_in_dir(&root_path).await);
959    }
960
961    #[tokio::test]
962    async fn corrupt_entry_does_not_block_queue() {
963        let data1 = FakeData::random();
964        let data2 = FakeData::random();
965
966        let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
967        let root_path = temp_dir.path().to_path_buf();
968
969        // Use MockDiskUsageRetriever to avoid disk space ratio causing eviction during push.
970        let mut persisted_queue = PersistedQueue::<FakeData>::from_root_path(PersistedQueueArgs {
971            root_path: root_path.clone(),
972            max_on_disk_bytes: 1024,
973            storage_max_disk_ratio: 0.8,
974            disk_usage_retriever: Arc::new(MockDiskUsageRetriever {}),
975            max_age_days: 10,
976        })
977        .await
978        .expect("should not fail to create persisted queue");
979
980        // Push two valid entries, then corrupt the first one on disk.
981        let _ = persisted_queue.push(data1).await.expect("should not fail to push data");
982        let _ = persisted_queue
983            .push(data2.clone())
984            .await
985            .expect("should not fail to push data");
986        assert_eq!(2, persisted_queue.entries.len());
987
988        // Corrupt the oldest entry file on disk.
989        let oldest_path = persisted_queue.entries[0].path.clone();
990        tokio::fs::write(&oldest_path, b"corrupted").await.unwrap();
991
992        // Pop should skip the corrupt entry and return the second valid one.
993        let actual = persisted_queue
994            .pop()
995            .await
996            .expect("should not fail to pop data")
997            .expect("should have a valid entry");
998        assert_eq!(data2, actual);
999
1000        assert_eq!(1, persisted_queue.take_entries_dropped());
1001        assert_eq!(0, files_in_dir(&root_path).await);
1002    }
1003
1004    #[tokio::test]
1005    async fn pop_returns_none_when_all_entries_corrupt() {
1006        let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
1007        let root_path = temp_dir.path().to_path_buf();
1008
1009        let mut persisted_queue = PersistedQueue::<FakeData>::from_root_path(PersistedQueueArgs {
1010            root_path: root_path.clone(),
1011            max_on_disk_bytes: 1024,
1012            storage_max_disk_ratio: 0.8,
1013            disk_usage_retriever: Arc::new(MockDiskUsageRetriever {}),
1014            max_age_days: 10,
1015        })
1016        .await
1017        .expect("should not fail to create persisted queue");
1018
1019        // Write a corrupt entry and refresh state.
1020        write_corrupt_entry(&root_path).await;
1021        persisted_queue.refresh_entry_state().await.unwrap();
1022
1023        // Pop should skip the corrupt entry and return None (no valid entries).
1024        let result = persisted_queue.pop().await.expect("should not fail to pop data");
1025        assert!(result.is_none());
1026
1027        assert_eq!(1, persisted_queue.take_entries_dropped());
1028        assert_eq!(0, files_in_dir(&root_path).await);
1029    }
1030
1031    #[tokio::test]
1032    async fn corrupt_entry_dropped_during_eviction() {
1033        let data = FakeData::random();
1034
1035        let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
1036        let root_path = temp_dir.path().to_path_buf();
1037
1038        // Queue sized to hold only one entry.
1039        let mut persisted_queue = PersistedQueue::<FakeData>::from_root_path(PersistedQueueArgs {
1040            root_path: root_path.clone(),
1041            max_on_disk_bytes: 32,
1042            storage_max_disk_ratio: 0.8,
1043            disk_usage_retriever: Arc::new(MockDiskUsageRetriever {}),
1044            max_age_days: 10,
1045        })
1046        .await
1047        .expect("should not fail to create persisted queue");
1048
1049        // Push a valid entry, then corrupt it on disk.
1050        let _ = persisted_queue
1051            .push(FakeData::random())
1052            .await
1053            .expect("should not fail to push data");
1054        let first_path = persisted_queue.entries[0].path.clone();
1055        tokio::fs::write(&first_path, b"corrupted").await.unwrap();
1056
1057        // Push another entry, which needs to evict the first (corrupt) one to make space.
1058        // This should succeed without error -- the corrupt entry is dropped during eviction.
1059        let _ = persisted_queue
1060            .push(data.clone())
1061            .await
1062            .expect("should not fail to push data");
1063
1064        // The corrupt entry was dropped during eviction, not via normal eviction tracking.
1065        assert_eq!(1, persisted_queue.take_entries_dropped());
1066
1067        // The valid entry should be poppable.
1068        let actual = persisted_queue
1069            .pop()
1070            .await
1071            .expect("should not fail to pop data")
1072            .expect("should have a valid entry");
1073        assert_eq!(data, actual);
1074        assert_eq!(0, files_in_dir(&root_path).await);
1075    }
1076
1077    #[tokio::test]
1078    async fn persisted_queue_removes_outdated_files_on_initialization() {
1079        let data = FakeData::random();
1080
1081        let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
1082        let root_path = temp_dir.path().to_path_buf();
1083
1084        // Pre-seed a year-2000 retry file containing valid data that would be loaded as an entry
1085        // if it were not cleaned up first.
1086        let stale_content = serde_json::to_vec(&data).unwrap();
1087        tokio::fs::write(
1088            root_path.join("retry-20000101000000000000000-100000000.json"),
1089            &stale_content,
1090        )
1091        .await
1092        .unwrap();
1093
1094        assert_eq!(1, files_in_dir(&root_path).await);
1095
1096        // Initialize the queue and remove stale files with a 10-day age limit.
1097        let mut queue = PersistedQueue::<FakeData>::from_root_path(PersistedQueueArgs {
1098            root_path: root_path.clone(),
1099            max_on_disk_bytes: 1024 * 1024,
1100            storage_max_disk_ratio: 0.8,
1101            disk_usage_retriever: Arc::new(DiskUsageRetrieverImpl::new(root_path.clone())),
1102            max_age_days: 10,
1103        })
1104        .await
1105        .expect("should not fail to create persisted queue");
1106        queue
1107            .remove_stale_files()
1108            .await
1109            .expect("should not fail to remove stale files");
1110
1111        assert_eq!(0, files_in_dir(&root_path).await);
1112        assert!(queue.is_empty());
1113    }
1114
1115    #[tokio::test]
1116    async fn persisted_queue_zero_age_removes_all_retry_files_on_initialization() {
1117        // max_age_days=0 sets cutoff=now, matching the core Agent's FileRemovalPolicy behavior
1118        // with outdatedFileDayCount=0 — all retry files are removed on startup.
1119        let data = FakeData::random();
1120
1121        let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
1122        let root_path = temp_dir.path().to_path_buf();
1123
1124        // Seed with a freshly-written entry via a normal queue.
1125        let mut seeding_queue = PersistedQueue::<FakeData>::from_root_path(PersistedQueueArgs {
1126            root_path: root_path.clone(),
1127            max_on_disk_bytes: 1024 * 1024,
1128            storage_max_disk_ratio: 0.8,
1129            disk_usage_retriever: Arc::new(DiskUsageRetrieverImpl::new(root_path.clone())),
1130            max_age_days: 10,
1131        })
1132        .await
1133        .expect("should not fail to create persisted queue");
1134        let _ = seeding_queue.push(data).await.expect("should not fail to push data");
1135        assert_eq!(1, files_in_dir(&root_path).await);
1136
1137        // Re-open and remove stale files with max_age_days=0: the just-written file must also be deleted.
1138        let mut queue = PersistedQueue::<FakeData>::from_root_path(PersistedQueueArgs {
1139            root_path: root_path.clone(),
1140            max_on_disk_bytes: 1024 * 1024,
1141            storage_max_disk_ratio: 0.8,
1142            disk_usage_retriever: Arc::new(DiskUsageRetrieverImpl::new(root_path.clone())),
1143            max_age_days: 0,
1144        })
1145        .await
1146        .expect("should not fail to create persisted queue");
1147        queue
1148            .remove_stale_files()
1149            .await
1150            .expect("should not fail to remove stale files");
1151
1152        assert_eq!(0, files_in_dir(&root_path).await);
1153        assert!(queue.is_empty());
1154    }
1155
1156    fn at(secs: i64, nanos: u32) -> Timestamp {
1157        Timestamp::from_unix_nanos(i128::from(secs) * 1_000_000_000 + i128::from(nanos))
1158            .expect("test timestamp should be valid")
1159    }
1160
1161    fn filename_timestamp(timestamp: Timestamp) -> String {
1162        timestamp.format(TimestampFormat::CompactUtcNanos).to_string()
1163    }
1164
1165    // Retry files persist across upgrades and downgrades, so these names and values must never change: every version
1166    // has to read the names that every other version writes.
1167    const FILENAME_TIMESTAMPS: &[(&str, u128)] = &[
1168        ("19700101000000000000000", 0),
1169        ("20000101000000000000000", 946_684_800_000_000_000),
1170        ("20240229000000000000000", 1_709_164_800_000_000_000),
1171        ("20261118134530000000000", 1_795_009_530_000_000_000),
1172        ("20261118134530000000001", 1_795_009_530_000_000_001),
1173        ("20261118134530000007000", 1_795_009_530_000_007_000),
1174        ("20261118134530100000000", 1_795_009_530_100_000_000),
1175        ("20261118134530123456789", 1_795_009_530_123_456_789),
1176        ("20261118134530999999999", 1_795_009_530_999_999_999),
1177        ("99991231235959999999999", 253_402_300_799_999_999_999),
1178    ];
1179
1180    #[test]
1181    fn filename_timestamps_decode_to_unix_nanoseconds() {
1182        for (timestamp, expected) in FILENAME_TIMESTAMPS {
1183            let path = PathBuf::from(format!("/queue/retry-{}-123456789.json", timestamp));
1184            assert_eq!(decode_timestamped_filename(&path), Some(*expected), "{}", timestamp);
1185        }
1186    }
1187
1188    #[test]
1189    fn filename_timestamps_are_written_with_nine_fraction_digits() {
1190        let cases = [
1191            (at(0, 0), "19700101000000000000000"),
1192            (at(946_684_800, 0), "20000101000000000000000"),
1193            (at(1_795_009_530, 0), "20261118134530000000000"),
1194            (at(1_795_009_530, 1), "20261118134530000000001"),
1195            (at(1_795_009_530, 7_000), "20261118134530000007000"),
1196            (at(1_795_009_530, 100_000_000), "20261118134530100000000"),
1197            (at(1_795_009_530, 123_456_789), "20261118134530123456789"),
1198            (at(1_795_009_530, 999_999_999), "20261118134530999999999"),
1199        ];
1200
1201        for (timestamp, expected) in cases {
1202            let formatted = filename_timestamp(timestamp);
1203            assert_eq!(formatted, expected);
1204
1205            let path = PathBuf::from(format!("retry-{}-123456789.json", formatted));
1206            assert_eq!(
1207                decode_timestamped_filename(&path),
1208                u128::try_from(timestamp.as_unix_nanos()).ok()
1209            );
1210        }
1211    }
1212
1213    #[test]
1214    fn filenames_that_dont_match_the_retry_format_are_ignored() {
1215        for filename in [
1216            "other-20261118134530000000000-123456789.json",
1217            "retry-20261118134530000000000-nonce.json",
1218            "retry-20261118134530000000000.json",
1219            "retry--123456789.json",
1220            "retry-2026111813453000000000a-123456789.json",
1221            // February 30th.
1222            "retry-20260230000000000000000-123456789.json",
1223        ] {
1224            assert_eq!(decode_timestamped_filename(Path::new(filename)), None, "{}", filename);
1225        }
1226    }
1227
1228    #[tokio::test]
1229    async fn existing_entries_are_ordered_by_their_filename_timestamp() {
1230        let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
1231        let root_path = temp_dir.path().to_path_buf();
1232
1233        let mut expected = Vec::new();
1234        for (timestamp, value) in FILENAME_TIMESTAMPS.iter().rev() {
1235            let path = root_path.join(format!("retry-{}-123456789.json", timestamp));
1236            tokio::fs::write(&path, b"{}").await.unwrap();
1237            expected.push(*value);
1238        }
1239        expected.sort_unstable();
1240
1241        let queue = PersistedQueue::<FakeData>::from_root_path(PersistedQueueArgs {
1242            root_path: root_path.clone(),
1243            max_on_disk_bytes: 1024 * 1024,
1244            storage_max_disk_ratio: 0.8,
1245            disk_usage_retriever: Arc::new(MockDiskUsageRetriever {}),
1246            max_age_days: 10,
1247        })
1248        .await
1249        .expect("should not fail to create persisted queue");
1250
1251        let actual = queue.entries.iter().map(|entry| entry.timestamp).collect::<Vec<_>>();
1252        assert_eq!(actual, expected);
1253    }
1254
1255    #[test]
1256    fn filename_timestamps_that_no_version_writes_are_ignored() {
1257        // chrono, which earlier versions used, read some of these differently: fewer than nine fraction digits as
1258        // whole nanoseconds, a leap second as the following second, and a date before the epoch not at all (it
1259        // panicked or overflowed).
1260        for timestamp in [
1261            "2026111813453012345678",
1262            "202611181345301234567890",
1263            "20161231235960000000000",
1264            "19691231235959000000000",
1265            " 2026111813453000000000",
1266            "+2026111813453000000000",
1267        ] {
1268            let path = PathBuf::from(format!("retry-{}-123456789.json", timestamp));
1269            assert_eq!(decode_timestamped_filename(&path), None, "{}", timestamp);
1270        }
1271    }
1272
1273    #[tokio::test]
1274    async fn files_dated_before_the_epoch_are_left_alone() {
1275        let temp_dir = tempfile::tempdir().expect("should not fail to create temporary directory");
1276        let root_path = temp_dir.path().to_path_buf();
1277        let before_epoch = root_path.join("retry-19691231235959000000000-123456789.json");
1278        tokio::fs::write(&before_epoch, b"{}").await.unwrap();
1279        tokio::fs::write(root_path.join("retry-20000101000000000000000-123456789.json"), b"{}")
1280            .await
1281            .unwrap();
1282
1283        let queue = PersistedQueue::<FakeData>::from_root_path(PersistedQueueArgs {
1284            root_path: root_path.clone(),
1285            max_on_disk_bytes: 1024 * 1024,
1286            storage_max_disk_ratio: 0.8,
1287            disk_usage_retriever: Arc::new(MockDiskUsageRetriever {}),
1288            max_age_days: 10,
1289        })
1290        .await
1291        .expect("should not fail to create persisted queue");
1292        assert_eq!(queue.len(), 1);
1293
1294        let removed = remove_outdated_retry_files(&root_path, 0)
1295            .await
1296            .expect("should not fail to remove outdated files");
1297        assert_eq!(removed, 1);
1298        assert!(before_epoch.exists());
1299    }
1300
1301    proptest::proptest! {
1302        #[test]
1303        // Up to 9999-12-30T22:00:00.999999999Z, the latest `Timestamp`.
1304        fn property_test_filename_timestamps_round_trip(nanos in 0..=253_402_207_200_999_999_999i128) {
1305            let timestamp = Timestamp::from_unix_nanos(nanos).expect("timestamp should be valid");
1306            let formatted = filename_timestamp(timestamp);
1307
1308            proptest::prop_assert_eq!(formatted.len(), 23);
1309            proptest::prop_assert!(formatted.bytes().all(|b| b.is_ascii_digit()));
1310            let path = PathBuf::from(format!("retry-{}-123456789.json", formatted));
1311            proptest::prop_assert_eq!(decode_timestamped_filename(&path), u128::try_from(nanos).ok());
1312        }
1313    }
1314}