Skip to content

Commit eb80332

Browse files
committed
feat(storcaching): Implement cleanup
For now there is no hysteresis even, but thats fine for now, at least we will not crash on no disk space. Signed-off-by: Denys Fedoryshchenko <denys.f@collabora.com>
1 parent 73762f7 commit eb80332

1 file changed

Lines changed: 46 additions & 4 deletions

File tree

src/storcaching.rs

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,20 @@ struct Files {
88
last_update: SystemTime,
99
}
1010

11-
async fn read_files() -> Vec<Files> {
11+
async fn read_filesinfo(cache_dir: String) -> Vec<Files> {
1212
let mut files = Vec::new();
13-
let paths = fs::read_dir(".");
13+
let paths = fs::read_dir(&cache_dir);
1414
match paths {
1515
Ok(paths) => {
1616
for path in paths {
1717
let path = path.unwrap().path();
1818
let file = path.to_str().unwrap().to_string();
1919
let metadata = fs::metadata(&file).unwrap();
2020
let last_update = metadata.modified().unwrap();
21+
// is this file ending with ".content"?
22+
if !file.ends_with(".content") {
23+
continue;
24+
}
2125
files.push(Files { file, last_update });
2226
}
2327
files
@@ -51,15 +55,53 @@ async fn freediskspace_percent(cache_dir: String) -> u64 {
5155
percent as u64
5256
}
5357

58+
fn delete_cache_file(file: String) {
59+
// Truncate from filename .content, and add .headers, delete both files
60+
let content_filename = file.clone();
61+
let headers_filename = file.replace(".content", ".headers");
62+
println!("Deleting files: {} {}", &content_filename, &headers_filename);
63+
let res = fs::remove_file(&content_filename);
64+
match res {
65+
Ok(_) => {}
66+
Err(_) => {
67+
println!("Error deleting file: {}", content_filename);
68+
}
69+
}
70+
let res = fs::remove_file(&headers_filename);
71+
match res {
72+
Ok(_) => {}
73+
Err(_) => {
74+
println!("Error deleting file: {}", headers_filename);
75+
}
76+
}
77+
}
78+
79+
async fn clean_disk(cache_dir: String) {
80+
let files = read_filesinfo(cache_dir).await;
81+
let mut oldest_file = Files {
82+
file: "".to_string(),
83+
last_update: SystemTime::now(),
84+
};
85+
for file in files {
86+
if file.last_update < oldest_file.last_update {
87+
oldest_file = file;
88+
}
89+
}
90+
delete_cache_file(oldest_file.file);
91+
}
92+
5493
pub async fn cache_loop(cache_dir: &str) {
5594
loop {
5695
let free_space = freediskspace_percent(cache_dir.to_string()).await;
5796
if free_space < 10 {
5897
println!("Low disk space: {}%", free_space);
98+
clean_disk(cache_dir.to_string()).await;
99+
// critical mode, sleep only 100ms
100+
tokio::time::sleep(Duration::from_millis(100)).await;
59101
} else {
60102
println!("Free disk space: {}%", free_space);
103+
// sleep for 10 seconds before checking again
104+
tokio::time::sleep(Duration::from_secs(10)).await;
61105
}
62-
// sleep for 10 seconds
63-
tokio::time::sleep(Duration::from_secs(10)).await;
64106
}
65107
}

0 commit comments

Comments
 (0)