codeint_git/
result_cache.rs1use 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 commit: String,
56 settings: String,
57}
58
59static TEMPORARY_FILES_OF_THIS_PROCESS: AtomicU64 = AtomicU64::new(0);
60
61const MAX_ENTRY_AGE: Duration = Duration::from_secs(30 * 24 * 60 * 60);
62const STALE_TEMP_AGE: Duration = Duration::from_secs(60 * 60);
63const MAX_FUTURE_CLOCK_SKEW: Duration = Duration::from_secs(300);
64const MAX_ENTRIES: usize = 5_000;
65
66impl ResultCache {
67 pub fn in_folder(folder: PathBuf) -> ResultCache {
68 ResultCache { folder }
69 }
70
71 pub fn folder(&self) -> &Path {
72 &self.folder
73 }
74
75 pub fn read<T: DeserializeOwned>(
76 &self,
77 commit: CommitId,
78 settings: &impl Serialize,
79 ) -> Option<T> {
80 let address = self.address(commit, settings).ok()?;
81 let bytes = std::fs::read(&address.path).ok()?;
82 let stored: StoredEntry<T> = serde_json::from_slice(&bytes).ok()?;
83 if stored.commit == address.commit && stored.settings == address.settings {
84 touch_entry(&address.path);
85 Some(stored.result)
86 } else {
87 None
88 }
89 }
90
91 pub fn write<T: Serialize>(
92 &self,
93 commit: CommitId,
94 settings: &impl Serialize,
95 result: &T,
96 ) -> Result<(), ResultCacheError> {
97 let address = self.address(commit, settings)?;
98 let bytes = serde_json::to_vec(&EntryToStore {
99 commit: address.commit,
100 settings: &address.settings,
101 result,
102 })
103 .map_err(ResultCacheError::Result)?;
104 let write_error = |path: &Path| {
105 let path = path.to_path_buf();
106 move |source| ResultCacheError::Write { path, source }
107 };
108 std::fs::create_dir_all(&self.folder).map_err(write_error(&self.folder))?;
109 let temporary = self.temporary_path();
110 let written = OpenOptions::new()
111 .write(true)
112 .create_new(true)
113 .open(&temporary)
114 .and_then(|mut file| file.write_all(&bytes).and_then(|()| file.sync_all()))
115 .map_err(write_error(&temporary))
116 .and_then(|()| {
117 std::fs::rename(&temporary, &address.path).map_err(write_error(&address.path))
118 });
119 let Err(failure) = written else {
120 self.prune(&address.path);
121 return Ok(());
122 };
123 match std::fs::remove_file(&temporary) {
124 Err(cleanup) if cleanup.kind() != std::io::ErrorKind::NotFound => {
125 Err(ResultCacheError::Unfinished {
126 path: temporary,
127 failure: Box::new(failure),
128 source: cleanup,
129 })
130 }
131 _ if address.path.is_file() => {
132 self.prune(&address.path);
133 Ok(())
134 }
135 _ => Err(failure),
136 }
137 }
138
139 fn prune(&self, keep: &Path) {
140 let Ok(entries) = std::fs::read_dir(&self.folder) else {
141 return;
142 };
143 let now = SystemTime::now();
144 let mut live = Vec::new();
145 for entry in entries.flatten() {
146 if let Some(retained) = inspect_cache_entry(&entry, keep, now) {
147 live.push(retained);
148 }
149 }
150 if live.len() <= MAX_ENTRIES {
151 return;
152 }
153 let excess = live.len() - MAX_ENTRIES;
154 let mut evictable: Vec<(PathBuf, SystemTime)> =
155 live.into_iter().filter(|(path, _)| path != keep).collect();
156 evictable.sort_by(|left, right| left.1.cmp(&right.1).then_with(|| left.0.cmp(&right.0)));
157 for (path, _) in evictable.into_iter().take(excess) {
158 let _ = std::fs::remove_file(path);
159 }
160 }
161
162 fn address(
163 &self,
164 commit: CommitId,
165 settings: &impl Serialize,
166 ) -> Result<EntryAddress, ResultCacheError> {
167 let settings = serde_json::to_string(settings).map_err(ResultCacheError::Settings)?;
168 let mut hasher = gix::hash::hasher(gix::hash::Kind::Sha1);
169 hasher.update(settings.as_bytes());
170 let settings_id = hasher.try_finalize().map_err(ResultCacheError::EntryName)?;
171 let commit = commit.to_string();
172 Ok(EntryAddress {
173 path: self.folder.join(format!("{commit}-{settings_id}.json")),
174 commit,
175 settings,
176 })
177 }
178
179 fn temporary_path(&self) -> PathBuf {
180 let since_epoch = SystemTime::now()
181 .duration_since(UNIX_EPOCH)
182 .map_or(0, |duration| duration.as_nanos());
183 let sequence = TEMPORARY_FILES_OF_THIS_PROCESS.fetch_add(1, Ordering::Relaxed);
184 self.folder.join(format!(
185 ".writing-{}-{since_epoch}-{sequence}.tmp",
186 std::process::id()
187 ))
188 }
189}
190
191enum CacheFileKind {
192 Entry,
193 Temporary,
194}
195
196fn classify_cache_file(path: &Path) -> Option<CacheFileKind> {
197 if is_temporary_file(path) {
198 Some(CacheFileKind::Temporary)
199 } else if path.extension().and_then(|ext| ext.to_str()) == Some("json") {
200 Some(CacheFileKind::Entry)
201 } else {
202 None
203 }
204}
205
206fn is_temporary_file(path: &Path) -> bool {
207 path.file_name()
208 .and_then(|name| name.to_str())
209 .is_some_and(|name| name.starts_with(".writing-") && name.ends_with(".tmp"))
210}
211
212fn effective_modified(modified: SystemTime, now: SystemTime) -> SystemTime {
213 if modified
214 .duration_since(now)
215 .is_ok_and(|ahead| ahead > MAX_FUTURE_CLOCK_SKEW)
216 {
217 UNIX_EPOCH
218 } else {
219 modified
220 }
221}
222
223fn is_older_than(modified: SystemTime, now: SystemTime, max_age: Duration) -> bool {
224 now.duration_since(modified).is_ok_and(|age| age > max_age)
225}
226
227fn inspect_cache_entry(
228 entry: &std::fs::DirEntry,
229 keep: &Path,
230 now: SystemTime,
231) -> Option<(PathBuf, SystemTime)> {
232 if !entry.file_type().is_ok_and(|file_type| file_type.is_file()) {
233 return None;
234 }
235 let path = entry.path();
236 let kind = classify_cache_file(&path)?;
237 let modified = entry
238 .metadata()
239 .and_then(|metadata| metadata.modified())
240 .ok()?;
241 let effective = effective_modified(modified, now);
242 match kind {
243 CacheFileKind::Temporary => {
244 if is_older_than(effective, now, STALE_TEMP_AGE) {
245 let _ = std::fs::remove_file(&path);
246 }
247 None
248 }
249 CacheFileKind::Entry => {
250 if path != keep && is_older_than(effective, now, MAX_ENTRY_AGE) {
251 let _ = std::fs::remove_file(&path);
252 return None;
253 }
254 Some((path, effective))
255 }
256 }
257}
258
259fn touch_entry(path: &Path) {
260 if let Ok(file) = OpenOptions::new().write(true).open(path) {
261 let _ = file.set_modified(SystemTime::now());
262 }
263}