|
| 1 | +use std::{ |
| 2 | + fs, |
| 3 | + path::{Path, PathBuf}, |
| 4 | +}; |
| 5 | + |
| 6 | +use anyhow::Context; |
| 7 | +use chrono::{DateTime, TimeDelta, Utc}; |
| 8 | +use slog::{debug, info, Logger}; |
| 9 | + |
| 10 | +use mithril_common::StdResult; |
| 11 | + |
| 12 | +const LAST_VACUUM_FILENAME: &str = "last_vacuum_time"; |
| 13 | + |
| 14 | +type LastVacuumTime = DateTime<Utc>; |
| 15 | + |
| 16 | +/// Helper to track when vacuum was last performed |
| 17 | +#[derive(Debug, Clone)] |
| 18 | +pub struct VacuumTracker { |
| 19 | + tracker_file: PathBuf, |
| 20 | + min_interval: TimeDelta, |
| 21 | + logger: Logger, |
| 22 | +} |
| 23 | + |
| 24 | +impl VacuumTracker { |
| 25 | + /// Create a new [VacuumTracker] for the given store directory |
| 26 | + pub fn new(store_dir: &Path, interval: TimeDelta, logger: Logger) -> Self { |
| 27 | + let last_vacuum_file = store_dir.join(LAST_VACUUM_FILENAME); |
| 28 | + |
| 29 | + Self { |
| 30 | + tracker_file: last_vacuum_file, |
| 31 | + min_interval: interval, |
| 32 | + logger, |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + /// Check if enough time has passed since last vacuum (returning the last vacuum timestamp) |
| 37 | + pub fn check_vacuum_needed(&self) -> StdResult<(bool, Option<LastVacuumTime>)> { |
| 38 | + if !self.tracker_file.exists() { |
| 39 | + debug!( |
| 40 | + self.logger, |
| 41 | + "No previous vacuum timestamp found, vacuum can be performed" |
| 42 | + ); |
| 43 | + return Ok((true, None)); |
| 44 | + } |
| 45 | + |
| 46 | + let last_vacuum = fs::read_to_string(&self.tracker_file).with_context(|| { |
| 47 | + format!( |
| 48 | + "Failed to read vacuum timestamp file: {:?}", |
| 49 | + self.tracker_file |
| 50 | + ) |
| 51 | + })?; |
| 52 | + let last_vacuum = DateTime::parse_from_rfc3339(&last_vacuum)?.with_timezone(&Utc); |
| 53 | + |
| 54 | + let duration_since_last = Utc::now() - (last_vacuum); |
| 55 | + |
| 56 | + let should_vacuum = duration_since_last >= self.min_interval; |
| 57 | + |
| 58 | + if should_vacuum { |
| 59 | + info!( |
| 60 | + self.logger, |
| 61 | + "Sufficient time has passed since last vacuum"; |
| 62 | + "last_vacuum" => last_vacuum.to_string(), |
| 63 | + "elapsed_days" => duration_since_last.num_days(), |
| 64 | + "min_interval_days" => self.min_interval.num_days() |
| 65 | + ); |
| 66 | + } else { |
| 67 | + info!( |
| 68 | + self.logger, |
| 69 | + "Not enough time elapsed since last vacuum"; |
| 70 | + "last_vacuum" => last_vacuum.to_string(), |
| 71 | + "elapsed_days" => duration_since_last.num_days(), |
| 72 | + "min_interval_days" => self.min_interval.num_days() |
| 73 | + ); |
| 74 | + }; |
| 75 | + |
| 76 | + Ok((should_vacuum, Some(last_vacuum))) |
| 77 | + } |
| 78 | + |
| 79 | + /// Update the last vacuum time to now |
| 80 | + pub fn update_last_vacuum_time(&self) -> StdResult<LastVacuumTime> { |
| 81 | + let timestamp = Utc::now(); |
| 82 | + |
| 83 | + fs::write(&self.tracker_file, timestamp.to_rfc3339()).with_context(|| { |
| 84 | + format!( |
| 85 | + "Failed to write to last vacuum time file: {:?}", |
| 86 | + self.tracker_file |
| 87 | + ) |
| 88 | + })?; |
| 89 | + |
| 90 | + Ok(timestamp) |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +#[cfg(test)] |
| 95 | +mod tests { |
| 96 | + use std::thread::sleep; |
| 97 | + |
| 98 | + use mithril_common::temp_dir_create; |
| 99 | + |
| 100 | + use crate::test_tools::TestLogger; |
| 101 | + |
| 102 | + use super::*; |
| 103 | + |
| 104 | + const DUMMY_INTERVAL: TimeDelta = TimeDelta::milliseconds(99); |
| 105 | + |
| 106 | + #[test] |
| 107 | + fn update_last_vacuum_time_creates_file_with_current_timestamp() { |
| 108 | + let tracker = VacuumTracker::new(&temp_dir_create!(), DUMMY_INTERVAL, TestLogger::stdout()); |
| 109 | + |
| 110 | + assert!(!tracker.tracker_file.exists()); |
| 111 | + |
| 112 | + let saved_timestamp = tracker.update_last_vacuum_time().unwrap(); |
| 113 | + let approximative_expected_saved_timestamp = Utc::now(); |
| 114 | + |
| 115 | + let vacuum_file_content = fs::read_to_string(tracker.tracker_file).unwrap(); |
| 116 | + let timestamp_retrieved = DateTime::parse_from_rfc3339(&vacuum_file_content).unwrap(); |
| 117 | + let diff = timestamp_retrieved |
| 118 | + .signed_duration_since(approximative_expected_saved_timestamp) |
| 119 | + .num_milliseconds(); |
| 120 | + assert!(diff < 1); |
| 121 | + assert_eq!(timestamp_retrieved, saved_timestamp); |
| 122 | + } |
| 123 | + |
| 124 | + #[test] |
| 125 | + fn update_last_vacuum_time_overwrites_previous_timestamp() { |
| 126 | + let tracker = VacuumTracker::new(&temp_dir_create!(), DUMMY_INTERVAL, TestLogger::stdout()); |
| 127 | + |
| 128 | + let initial_saved_timestamp = tracker.update_last_vacuum_time().unwrap(); |
| 129 | + let last_saved_timestamp = tracker.update_last_vacuum_time().unwrap(); |
| 130 | + |
| 131 | + let vacuum_file_content = fs::read_to_string(tracker.tracker_file).unwrap(); |
| 132 | + let timestamp_retrieved = DateTime::parse_from_rfc3339(&vacuum_file_content).unwrap(); |
| 133 | + assert!(last_saved_timestamp > initial_saved_timestamp); |
| 134 | + assert_eq!(timestamp_retrieved, last_saved_timestamp); |
| 135 | + } |
| 136 | + |
| 137 | + #[test] |
| 138 | + fn update_last_vacuum_time_fails_on_write_error() { |
| 139 | + let dir_not_exist = Path::new("path-does-not-exist"); |
| 140 | + let tracker = VacuumTracker::new(dir_not_exist, DUMMY_INTERVAL, TestLogger::stdout()); |
| 141 | + |
| 142 | + tracker |
| 143 | + .update_last_vacuum_time() |
| 144 | + .expect_err("Update last vacuum time should fail when error while writing to file"); |
| 145 | + } |
| 146 | + |
| 147 | + #[test] |
| 148 | + fn check_vacuum_needed_returns_true_when_no_previous_record() { |
| 149 | + let tracker = VacuumTracker::new(&temp_dir_create!(), DUMMY_INTERVAL, TestLogger::stdout()); |
| 150 | + |
| 151 | + let (is_vacuum_needed, last_timestamp) = tracker.check_vacuum_needed().unwrap(); |
| 152 | + |
| 153 | + assert!(is_vacuum_needed); |
| 154 | + assert!(last_timestamp.is_none()); |
| 155 | + } |
| 156 | + |
| 157 | + #[test] |
| 158 | + fn check_vacuum_needed_returns_true_after_interval_elapsed() { |
| 159 | + let min_interval = TimeDelta::milliseconds(10); |
| 160 | + let tracker = VacuumTracker::new(&temp_dir_create!(), min_interval, TestLogger::stdout()); |
| 161 | + |
| 162 | + let saved_timestamp = tracker.update_last_vacuum_time().unwrap(); |
| 163 | + sleep(min_interval.to_std().unwrap()); |
| 164 | + |
| 165 | + let (is_vacuum_needed, last_timestamp) = tracker.check_vacuum_needed().unwrap(); |
| 166 | + |
| 167 | + assert!(is_vacuum_needed); |
| 168 | + assert_eq!(last_timestamp, Some(saved_timestamp)); |
| 169 | + } |
| 170 | + |
| 171 | + #[test] |
| 172 | + fn check_vacuum_needed_returns_false_within_interval() { |
| 173 | + let min_interval = TimeDelta::minutes(2); |
| 174 | + let tracker = VacuumTracker::new(&temp_dir_create!(), min_interval, TestLogger::stdout()); |
| 175 | + |
| 176 | + let saved_timestamp = tracker.update_last_vacuum_time().unwrap(); |
| 177 | + |
| 178 | + let (is_vacuum_needed, last_timestamp) = tracker.check_vacuum_needed().unwrap(); |
| 179 | + |
| 180 | + assert!(!is_vacuum_needed); |
| 181 | + assert_eq!(last_timestamp, Some(saved_timestamp)); |
| 182 | + } |
| 183 | +} |
0 commit comments