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
17struct PersistedEntry {
21 path: PathBuf,
22 timestamp: u128,
23 size_bytes: u64,
24}
25
26impl PersistedEntry {
27 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
88pub struct PersistedQueueArgs {
90 pub root_path: PathBuf,
92 pub max_on_disk_bytes: u64,
94 pub storage_max_disk_ratio: f64,
96 pub disk_usage_retriever: Arc<dyn DiskUsageRetriever + Send + Sync>,
98 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 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 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 pub fn is_empty(&self) -> bool {
170 self.entries.is_empty()
171 }
172
173 pub fn len(&self) -> usize {
175 self.entries.len()
176 }
177
178 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 pub fn take_entries_dropped(&mut self) -> u64 {
209 std::mem::take(&mut self.entries_dropped)
210 }
211
212 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 pub async fn push(&mut self, entry: T) -> Result<PushResult, GenericError> {
232 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 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 tokio::fs::write(&entry_path, &serialized)
252 .await
253 .with_error_context(|| format!("Failed to write entry to '{}'.", entry_path.display()))?;
254
255 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 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 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 self.refresh_entry_state().await?;
292 continue;
293 }
294 Err(e) => {
295 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 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 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 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 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 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 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 self.total_on_disk_bytes -= entry.size_bytes;
403 push_result.track_dropped_item(&deserialized);
404
405 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
420fn 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 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 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 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 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 if prefix != "retry" || nonce.parse::<u64>().is_err() {
511 return None;
512 }
513
514 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 #[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
540async 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() .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 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 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 assert_eq!(0, files_in_dir(&root_path).await);
700
701 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 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 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 assert_eq!(0, files_in_dir(&root_path).await);
740
741 assert!(persisted_queue.push(data).await.is_err());
743
744 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 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 assert_eq!(0, files_in_dir(&root_path).await);
771
772 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 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 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 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 assert_eq!(0, files_in_dir(&root_path).await);
828
829 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 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 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 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 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 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 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 let corrupt_path = write_corrupt_entry(&root_path).await;
933
934 let _ = persisted_queue
936 .push(data.clone())
937 .await
938 .expect("should not fail to push data");
939
940 persisted_queue.refresh_entry_state().await.unwrap();
942
943 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 assert!(!corrupt_path.exists());
953
954 assert_eq!(1, persisted_queue.take_entries_dropped());
956
957 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 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 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 let oldest_path = persisted_queue.entries[0].path.clone();
990 tokio::fs::write(&oldest_path, b"corrupted").await.unwrap();
991
992 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_corrupt_entry(&root_path).await;
1021 persisted_queue.refresh_entry_state().await.unwrap();
1022
1023 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 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 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 let _ = persisted_queue
1060 .push(data.clone())
1061 .await
1062 .expect("should not fail to push data");
1063
1064 assert_eq!(1, persisted_queue.take_entries_dropped());
1066
1067 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 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 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 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 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 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 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 "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 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 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}