Skip to main content

viser_encoding/
cleanup.rs

1use std::fs;
2use std::path::Path;
3use std::time::{Duration, SystemTime};
4use tracing::debug;
5
6/// Removes orphaned viser temp directories older than `max_age`.
7/// Called at startup to clean up after crashes or SIGKILL.
8pub fn clean_stale_temp_dirs(max_age: Duration) {
9    let tmp = std::env::temp_dir();
10    clean_temp_dirs_in_root(&tmp, max_age);
11}
12
13fn clean_temp_dirs_in_root(root: &Path, max_age: Duration) {
14    let entries = match fs::read_dir(root) {
15        Ok(e) => e,
16        Err(_) => return,
17    };
18
19    let now = SystemTime::now();
20
21    for entry in entries.flatten() {
22        let Ok(file_type) = entry.file_type() else { continue };
23        if !file_type.is_dir() {
24            continue;
25        }
26        let name = entry.file_name();
27        let name = name.to_string_lossy();
28        if !name.starts_with("viser-") {
29            continue;
30        }
31        let Ok(metadata) = entry.metadata() else { continue };
32        let Ok(modified) = metadata.modified() else { continue };
33        if let Ok(age) = now.duration_since(modified)
34            && age > max_age
35        {
36            let path = entry.path();
37            debug!("cleaning stale temp dir: {}", path.display());
38            let _ = fs::remove_dir_all(&path);
39        }
40    }
41}