Skip to main content

codeint_git/
result_cache.rs

1use std::fs::OpenOptions;
2use std::io::Write;
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::time::{Duration, SystemTime, UNIX_EPOCH};
6
7use serde::de::DeserializeOwned;
8use serde::{Deserialize, Serialize};
9
10use crate::CommitId;
11
12#[derive(Debug, thiserror::Error)]
13pub enum ResultCacheError {
14    #[error("cannot write the cache entry {}", path.display())]
15    Write {
16        path: PathBuf,
17        #[source]
18        source: std::io::Error,
19    },
20    #[error("cannot describe the settings of the cached result")]
21    Settings(#[source] serde_json::Error),
22    #[error("{failure}, and cannot remove the unfinished file {}", path.display())]
23    Unfinished {
24        path: PathBuf,
25        failure: Box<ResultCacheError>,
26        #[source]
27        source: std::io::Error,
28    },
29    #[error("cannot name the cache entry")]
30    EntryName(#[source] gix::Error),
31    #[error("cannot describe the result to cache")]
32    Result(#[source] serde_json::Error),
33}
34
35pub struct ResultCache {
36    folder: PathBuf,
37}
38
39#[derive(Serialize)]
40struct EntryToStore<'entry, T> {
41    commit: String,
42    settings: &'entry str,
43    result: &'entry T,
44}
45
46#[derive(Deserialize)]
47struct StoredEntry<T> {
48    commit: String,
49    settings: String,
50    result: T,
51}
52
53struct EntryAddress {
54    path: PathBuf,
55    legacy_path: PathBuf,
56    commit: String,
57    settings: String,
58}
59
60static TEMPORARY_FILES_OF_THIS_PROCESS: AtomicU64 = AtomicU64::new(0);
61
62const MAX_ENTRY_AGE: Duration = Duration::from_secs(30 * 24 * 60 * 60);
63const STALE_TEMP_AGE: Duration = Duration::from_secs(60 * 60);
64const MAX_FUTURE_CLOCK_SKEW: Duration = Duration::from_secs(300);
65const MAX_ENTRIES: usize = 5_000;
66const RESULT_FILE_PREFIX: &str = "codeint-result-";
67const TEMPORARY_FILE_PREFIX: &str = ".codeint-result-writing-";
68const TEMPORARY_FILE_SUFFIX: &str = ".tmp";
69
70impl ResultCache {
71    pub fn in_folder(folder: PathBuf) -> ResultCache {
72        ResultCache { folder }
73    }
74
75    pub fn folder(&self) -> &Path {
76        &self.folder
77    }
78
79    pub fn read<T: DeserializeOwned>(
80        &self,
81        commit: CommitId,
82        settings: &impl Serialize,
83    ) -> Option<T> {
84        let address = self.address(commit, settings).ok()?;
85        let (path, bytes) = match std::fs::read(&address.path) {
86            Ok(bytes) => (&address.path, bytes),
87            Err(error) if error.kind() == std::io::ErrorKind::NotFound => (
88                &address.legacy_path,
89                std::fs::read(&address.legacy_path).ok()?,
90            ),
91            Err(_) => return None,
92        };
93        let stored: StoredEntry<T> = serde_json::from_slice(&bytes).ok()?;
94        if stored.commit == address.commit && stored.settings == address.settings {
95            touch_entry(path);
96            Some(stored.result)
97        } else {
98            None
99        }
100    }
101
102    pub fn write<T: Serialize>(
103        &self,
104        commit: CommitId,
105        settings: &impl Serialize,
106        result: &T,
107    ) -> Result<(), ResultCacheError> {
108        let address = self.address(commit, settings)?;
109        let bytes = serde_json::to_vec(&EntryToStore {
110            commit: address.commit,
111            settings: &address.settings,
112            result,
113        })
114        .map_err(ResultCacheError::Result)?;
115        let write_error = |path: &Path| {
116            let path = path.to_path_buf();
117            move |source| ResultCacheError::Write { path, source }
118        };
119        std::fs::create_dir_all(&self.folder).map_err(write_error(&self.folder))?;
120        let temporary = self.temporary_path();
121        let written = OpenOptions::new()
122            .write(true)
123            .create_new(true)
124            .open(&temporary)
125            .and_then(|mut file| file.write_all(&bytes).and_then(|()| file.sync_all()))
126            .map_err(write_error(&temporary))
127            .and_then(|()| {
128                std::fs::rename(&temporary, &address.path).map_err(write_error(&address.path))
129            });
130        let Err(failure) = written else {
131            self.prune(&address.path);
132            return Ok(());
133        };
134        match std::fs::remove_file(&temporary) {
135            Err(cleanup) if cleanup.kind() != std::io::ErrorKind::NotFound => {
136                Err(ResultCacheError::Unfinished {
137                    path: temporary,
138                    failure: Box::new(failure),
139                    source: cleanup,
140                })
141            }
142            _ if address.path.is_file() => {
143                self.prune(&address.path);
144                Ok(())
145            }
146            _ => Err(failure),
147        }
148    }
149
150    fn prune(&self, keep: &Path) {
151        let Ok(entries) = std::fs::read_dir(&self.folder) else {
152            return;
153        };
154        let now = SystemTime::now();
155        let mut live = Vec::new();
156        for entry in entries.flatten() {
157            if let Some(retained) = inspect_cache_entry(&entry, keep, now) {
158                live.push(retained);
159            }
160        }
161        if live.len() <= MAX_ENTRIES {
162            return;
163        }
164        let excess = live.len() - MAX_ENTRIES;
165        let mut evictable: Vec<(PathBuf, SystemTime)> =
166            live.into_iter().filter(|(path, _)| path != keep).collect();
167        evictable.sort_by(|left, right| left.1.cmp(&right.1).then_with(|| left.0.cmp(&right.0)));
168        for (path, _) in evictable.into_iter().take(excess) {
169            let _ = std::fs::remove_file(path);
170        }
171    }
172
173    fn address(
174        &self,
175        commit: CommitId,
176        settings: &impl Serialize,
177    ) -> Result<EntryAddress, ResultCacheError> {
178        let settings = serde_json::to_string(settings).map_err(ResultCacheError::Settings)?;
179        let mut hasher = gix::hash::hasher(gix::hash::Kind::Sha1);
180        hasher.update(settings.as_bytes());
181        let settings_id = hasher.try_finalize().map_err(ResultCacheError::EntryName)?;
182        let commit = commit.to_string();
183        let legacy_name = format!("{commit}-{settings_id}.json");
184        Ok(EntryAddress {
185            path: self
186                .folder
187                .join(format!("{RESULT_FILE_PREFIX}{legacy_name}")),
188            legacy_path: self.folder.join(legacy_name),
189            commit,
190            settings,
191        })
192    }
193
194    fn temporary_path(&self) -> PathBuf {
195        let since_epoch = SystemTime::now()
196            .duration_since(UNIX_EPOCH)
197            .map_or(0, |duration| duration.as_nanos());
198        let sequence = TEMPORARY_FILES_OF_THIS_PROCESS.fetch_add(1, Ordering::Relaxed);
199        self.folder.join(temporary_file_name(
200            std::process::id(),
201            since_epoch,
202            sequence,
203        ))
204    }
205}
206
207fn temporary_file_name(pid: u32, stamp: u128, sequence: u64) -> String {
208    format!("{TEMPORARY_FILE_PREFIX}{pid}-{stamp}-{sequence}{TEMPORARY_FILE_SUFFIX}")
209}
210
211enum CacheFileKind {
212    Entry,
213    Temporary,
214}
215
216fn classify_cache_file(path: &Path) -> Option<CacheFileKind> {
217    let name = path.file_name()?.to_str()?;
218    if let Some(stem) = name
219        .strip_prefix(RESULT_FILE_PREFIX)
220        .and_then(|name| name.strip_suffix(".json"))
221    {
222        let (commit, settings) = stem.split_once('-')?;
223        return (is_hash_hex(commit, &[40, 64]) && is_hash_hex(settings, &[40]))
224            .then_some(CacheFileKind::Entry);
225    }
226    classify_temporary_file(name)
227}
228
229fn classify_temporary_file(name: &str) -> Option<CacheFileKind> {
230    let stem = name
231        .strip_prefix(TEMPORARY_FILE_PREFIX)?
232        .strip_suffix(TEMPORARY_FILE_SUFFIX)?;
233    let (pid, stamp_and_sequence) = stem.split_once('-')?;
234    let (stamp, sequence) = stamp_and_sequence.split_once('-')?;
235    let pid = pid.parse::<u32>().ok()?;
236    let stamp = stamp.parse::<u128>().ok()?;
237    let sequence = sequence.parse::<u64>().ok()?;
238    (pid != 0 && name == temporary_file_name(pid, stamp, sequence))
239        .then_some(CacheFileKind::Temporary)
240}
241
242fn is_hash_hex(value: &str, lengths: &[usize]) -> bool {
243    lengths.contains(&value.len())
244        && value
245            .bytes()
246            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
247}
248
249fn effective_modified(modified: SystemTime, now: SystemTime) -> SystemTime {
250    if modified
251        .duration_since(now)
252        .is_ok_and(|ahead| ahead > MAX_FUTURE_CLOCK_SKEW)
253    {
254        UNIX_EPOCH
255    } else {
256        modified
257    }
258}
259
260fn is_older_than(modified: SystemTime, now: SystemTime, max_age: Duration) -> bool {
261    now.duration_since(modified).is_ok_and(|age| age > max_age)
262}
263
264fn inspect_cache_entry(
265    entry: &std::fs::DirEntry,
266    keep: &Path,
267    now: SystemTime,
268) -> Option<(PathBuf, SystemTime)> {
269    if !entry.file_type().is_ok_and(|file_type| file_type.is_file()) {
270        return None;
271    }
272    let path = entry.path();
273    let kind = classify_cache_file(&path)?;
274    let modified = entry
275        .metadata()
276        .and_then(|metadata| metadata.modified())
277        .ok()?;
278    let effective = effective_modified(modified, now);
279    match kind {
280        CacheFileKind::Temporary => {
281            if is_older_than(effective, now, STALE_TEMP_AGE) {
282                let _ = std::fs::remove_file(&path);
283            }
284            None
285        }
286        CacheFileKind::Entry => {
287            if path != keep && is_older_than(effective, now, MAX_ENTRY_AGE) {
288                let _ = std::fs::remove_file(&path);
289                return None;
290            }
291            Some((path, effective))
292        }
293    }
294}
295
296fn touch_entry(path: &Path) {
297    if let Ok(file) = OpenOptions::new().write(true).open(path) {
298        let _ = file.set_modified(SystemTime::now());
299    }
300}