cache.rs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. use std::fs::File;
  2. use std::io::{self, Write};
  3. use std::path::{Path, PathBuf};
  4. use std::sync::atomic::{AtomicU64, Ordering};
  5. use anyhow::{Context, Result};
  6. use crate::Converter;
  7. /// Identifies one conversion result.
  8. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  9. pub struct CacheKey(blake3::Hash);
  10. impl CacheKey {
  11. pub fn new(converter: &dyn Converter, input: &[u8]) -> Self {
  12. let mut h = blake3::Hasher::new();
  13. h.update(converter.id().as_bytes());
  14. h.update(&[0]);
  15. h.update(&converter.version().to_le_bytes());
  16. h.update(input);
  17. CacheKey(h.finalize())
  18. }
  19. pub fn to_hex(&self) -> String {
  20. self.0.to_hex().to_string()
  21. }
  22. }
  23. /// Content-addressed store under the user's cache directory.
  24. #[derive(Debug, Clone)]
  25. pub struct Cache {
  26. root: PathBuf,
  27. }
  28. impl Cache {
  29. /// Opens (creating) a cache at `root`. Refuses locations inside the repo.
  30. pub fn open(root: impl Into<PathBuf>) -> Result<Self> {
  31. let root = root.into();
  32. victory_core::ensure_outside_repo(&root)?;
  33. std::fs::create_dir_all(&root).with_context(|| format!("creating {}", root.display()))?;
  34. Ok(Cache { root })
  35. }
  36. pub fn path_for(&self, key: &CacheKey) -> PathBuf {
  37. let hex = key.to_hex();
  38. self.root.join(&hex[..2]).join(&hex[2..])
  39. }
  40. /// Returns the cached output for `input`, converting it first if needed.
  41. pub fn get_or_convert(&self, converter: &dyn Converter, input: &[u8]) -> Result<PathBuf> {
  42. let key = CacheKey::new(converter, input);
  43. let path = self.path_for(&key);
  44. if path.is_file() {
  45. tracing::trace!(converter = converter.id(), key = %key.to_hex(), "cache hit");
  46. return Ok(path);
  47. }
  48. let output = converter
  49. .convert(input)
  50. .with_context(|| format!("converter {} v{}", converter.id(), converter.version()))?;
  51. let dir = path.parent().expect("hashed path has a parent");
  52. std::fs::create_dir_all(dir)?;
  53. // Write-then-rename so readers never see partial output.
  54. let (tmp, mut file) = tempfile_in(dir)?;
  55. let written = file.write_all(&output);
  56. drop(file);
  57. let published = written.and_then(|()| std::fs::rename(&tmp, &path));
  58. if published.is_err() {
  59. let _ = std::fs::remove_file(&tmp);
  60. }
  61. published?;
  62. Ok(path)
  63. }
  64. }
  65. fn tempfile_in(dir: &Path) -> io::Result<(PathBuf, File)> {
  66. static COUNTER: AtomicU64 = AtomicU64::new(0);
  67. create_tempfile_in(dir, &COUNTER)
  68. }
  69. fn create_tempfile_in(dir: &Path, counter: &AtomicU64) -> io::Result<(PathBuf, File)> {
  70. // An interrupted writer can leave a file behind, and process IDs are
  71. // reused. Keep it intact and try a new name rather than failing a miss.
  72. for _ in 0..128 {
  73. let n = counter.fetch_add(1, Ordering::Relaxed);
  74. let path = dir.join(format!(".tmp-{}-{n}", std::process::id()));
  75. match std::fs::OpenOptions::new()
  76. .write(true)
  77. .create_new(true)
  78. .open(&path)
  79. {
  80. Ok(file) => return Ok((path, file)),
  81. Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
  82. Err(e) => return Err(e),
  83. }
  84. }
  85. Err(io::Error::new(
  86. io::ErrorKind::AlreadyExists,
  87. "could not create a unique cache staging file after 128 attempts",
  88. ))
  89. }
  90. #[cfg(test)]
  91. mod tests {
  92. use super::*;
  93. use std::sync::atomic::{AtomicUsize, Ordering};
  94. struct Upper {
  95. version: u32,
  96. runs: AtomicUsize,
  97. }
  98. impl Converter for Upper {
  99. fn id(&self) -> &'static str {
  100. "test.upper"
  101. }
  102. fn version(&self) -> u32 {
  103. self.version
  104. }
  105. fn convert(&self, input: &[u8]) -> Result<Vec<u8>> {
  106. self.runs.fetch_add(1, Ordering::Relaxed);
  107. Ok(input.to_ascii_uppercase())
  108. }
  109. }
  110. #[test]
  111. fn converts_once_then_hits() {
  112. let tmp = tempfile::tempdir().unwrap();
  113. let cache = Cache::open(tmp.path().join("cache")).unwrap();
  114. let conv = Upper {
  115. version: 1,
  116. runs: AtomicUsize::new(0),
  117. };
  118. let a = cache.get_or_convert(&conv, b"abc").unwrap();
  119. let b = cache.get_or_convert(&conv, b"abc").unwrap();
  120. assert_eq!(a, b);
  121. assert_eq!(std::fs::read(&a).unwrap(), b"ABC");
  122. assert_eq!(conv.runs.load(Ordering::Relaxed), 1);
  123. }
  124. #[test]
  125. fn failed_publication_removes_the_staging_file() {
  126. let tmp = tempfile::tempdir().unwrap();
  127. let cache = Cache::open(tmp.path().join("cache")).unwrap();
  128. let conv = Upper {
  129. version: 1,
  130. runs: AtomicUsize::new(0),
  131. };
  132. let path = cache.path_for(&CacheKey::new(&conv, b"abc"));
  133. std::fs::create_dir_all(&path).unwrap();
  134. assert!(cache.get_or_convert(&conv, b"abc").is_err());
  135. assert!(path.is_dir());
  136. assert_eq!(
  137. std::fs::read_dir(path.parent().unwrap()).unwrap().count(),
  138. 1
  139. );
  140. }
  141. #[test]
  142. fn staging_retries_collisions_without_changing_existing_files() {
  143. let dir = tempfile::tempdir().unwrap();
  144. let counter = AtomicU64::new(0);
  145. for n in 0..2 {
  146. std::fs::write(
  147. dir.path().join(format!(".tmp-{}-{n}", std::process::id())),
  148. b"stale",
  149. )
  150. .unwrap();
  151. }
  152. let (path, mut file) = create_tempfile_in(dir.path(), &counter).unwrap();
  153. file.write_all(b"fresh").unwrap();
  154. drop(file);
  155. assert_eq!(
  156. path.file_name().unwrap(),
  157. format!(".tmp-{}-2", std::process::id()).as_str()
  158. );
  159. assert_eq!(std::fs::read(&path).unwrap(), b"fresh");
  160. for n in 0..2 {
  161. assert_eq!(
  162. std::fs::read(dir.path().join(format!(".tmp-{}-{n}", std::process::id()))).unwrap(),
  163. b"stale"
  164. );
  165. }
  166. assert_eq!(counter.load(Ordering::Relaxed), 3);
  167. }
  168. #[test]
  169. fn staging_collision_retries_are_bounded() {
  170. let dir = tempfile::tempdir().unwrap();
  171. let counter = AtomicU64::new(0);
  172. for n in 0..128 {
  173. std::fs::write(
  174. dir.path().join(format!(".tmp-{}-{n}", std::process::id())),
  175. b"stale",
  176. )
  177. .unwrap();
  178. }
  179. let error = create_tempfile_in(dir.path(), &counter).unwrap_err();
  180. assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
  181. assert_eq!(counter.load(Ordering::Relaxed), 128);
  182. assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 128);
  183. }
  184. #[test]
  185. fn staging_does_not_retry_other_io_errors() {
  186. let dir = tempfile::tempdir().unwrap();
  187. let counter = AtomicU64::new(0);
  188. let missing = dir.path().join("missing");
  189. let error = create_tempfile_in(&missing, &counter).unwrap_err();
  190. assert_eq!(error.kind(), io::ErrorKind::NotFound);
  191. assert_eq!(counter.load(Ordering::Relaxed), 1);
  192. assert!(!missing.exists());
  193. }
  194. #[test]
  195. fn version_bump_invalidates() {
  196. let v1 = Upper {
  197. version: 1,
  198. runs: AtomicUsize::new(0),
  199. };
  200. let v2 = Upper {
  201. version: 2,
  202. runs: AtomicUsize::new(0),
  203. };
  204. assert_ne!(CacheKey::new(&v1, b"x"), CacheKey::new(&v2, b"x"));
  205. }
  206. #[test]
  207. fn refuses_cache_inside_repo() {
  208. let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("cache");
  209. assert!(Cache::open(inside).is_err());
  210. }
  211. }