Skip to content

Commit

Permalink
fix: Ensure command results are re-cached post-expiration
Browse files Browse the repository at this point in the history
Previously, once the cache expired, command results weren't re-cached,
leading to repeated command executions on every request.

This fix ensures results are properly cached again after the initial cache expiration.
  • Loading branch information
Miyoshi-Ryota committed Feb 19, 2024
1 parent 77cc2c8 commit 49607d3
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/lib.rs
Expand Up @@ -29,6 +29,8 @@ pub fn cache_aware_execute_command(command: &str, ttl: u64, cache_file: &PathBuf
&fs::read(cache_file).expect("Unable to read cache file"),
)
.to_string();
} else {
clean_cache(cache_file);
}
}

Expand All @@ -40,6 +42,11 @@ pub fn cache_aware_execute_command(command: &str, ttl: u64, cache_file: &PathBuf
String::from_utf8_lossy(&output.stdout).to_string()
}

/// This function removes the cache file.
pub fn clean_cache(cache_file: &PathBuf) {
fs::remove_file(cache_file).expect("Unable to remove cache file");
}

#[cfg(test)]
mod tests {
use std::{
Expand Down Expand Up @@ -143,4 +150,37 @@ mod tests {
duration
);
}

#[test]
/// This test case is to check
/// if the cache file is renewed
/// when command is re-executed after the cache is expired.
fn re_cache_execution_after_cache_is_expired() {
let ctx = TestContext::new(&format!("{}{}", file!(), line!()));

let cache_file = ctx.cache_root_path.join("test_cache");
let _ = std::fs::write(&cache_file, "not hello").expect("Unable to write cache file");
let old_cache_file_created = fs::metadata(&cache_file)
.expect("Unable to read metadata of cache file")
.created()
.expect("Unable to read created date of cache file");

let command = "sleep 1 && echo 'hello'";
let ttl = 1;

sleep(Duration::from_secs(2));

let _ = super::cache_aware_execute_command(command, ttl, &cache_file);

let renewed_cache_file_created = fs::metadata(&cache_file)
.expect("Unable to read metadata of cache file")
.created()
.expect("Unable to read created date of cache file");


assert!(
renewed_cache_file_created > old_cache_file_created,
"Cache file is not renewed"
);
}
}

0 comments on commit 49607d3

Please sign in to comment.