cache.rs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. use std::io::Write;
  2. use std::path::{Path, PathBuf};
  3. use anyhow::{Context, Result};
  4. use crate::Converter;
  5. /// Identifies one conversion result.
  6. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  7. pub struct CacheKey(blake3::Hash);
  8. impl CacheKey {
  9. pub fn new(converter: &dyn Converter, input: &[u8]) -> Self {
  10. let mut h = blake3::Hasher::new();
  11. h.update(converter.id().as_bytes());
  12. h.update(&[0]);
  13. h.update(&converter.version().to_le_bytes());
  14. h.update(input);
  15. CacheKey(h.finalize())
  16. }
  17. pub fn to_hex(&self) -> String {
  18. self.0.to_hex().to_string()
  19. }
  20. }
  21. /// Content-addressed store under the user's cache directory.
  22. #[derive(Debug, Clone)]
  23. pub struct Cache {
  24. root: PathBuf,
  25. }
  26. impl Cache {
  27. /// Opens (creating) a cache at `root`. Refuses locations inside the repo.
  28. pub fn open(root: impl Into<PathBuf>) -> Result<Self> {
  29. let root = root.into();
  30. victory_core::ensure_outside_repo(&root)?;
  31. std::fs::create_dir_all(&root).with_context(|| format!("creating {}", root.display()))?;
  32. Ok(Cache { root })
  33. }
  34. pub fn path_for(&self, key: &CacheKey) -> PathBuf {
  35. let hex = key.to_hex();
  36. self.root.join(&hex[..2]).join(&hex[2..])
  37. }
  38. /// Returns the cached output for `input`, converting it first if needed.
  39. pub fn get_or_convert(&self, converter: &dyn Converter, input: &[u8]) -> Result<PathBuf> {
  40. let key = CacheKey::new(converter, input);
  41. let path = self.path_for(&key);
  42. if path.is_file() {
  43. tracing::trace!(converter = converter.id(), key = %key.to_hex(), "cache hit");
  44. return Ok(path);
  45. }
  46. let output = converter
  47. .convert(input)
  48. .with_context(|| format!("converter {} v{}", converter.id(), converter.version()))?;
  49. let dir = path.parent().expect("hashed path has a parent");
  50. std::fs::create_dir_all(dir)?;
  51. // Write-then-rename so readers never see partial output.
  52. let tmp = tempfile_in(dir);
  53. let mut file = std::fs::OpenOptions::new()
  54. .write(true)
  55. .create_new(true)
  56. .open(&tmp)?;
  57. let written = file.write_all(&output);
  58. drop(file);
  59. let published = written.and_then(|()| std::fs::rename(&tmp, &path));
  60. if published.is_err() {
  61. let _ = std::fs::remove_file(&tmp);
  62. }
  63. published?;
  64. Ok(path)
  65. }
  66. }
  67. fn tempfile_in(dir: &Path) -> PathBuf {
  68. use std::sync::atomic::{AtomicU64, Ordering};
  69. static COUNTER: AtomicU64 = AtomicU64::new(0);
  70. let n = COUNTER.fetch_add(1, Ordering::Relaxed);
  71. dir.join(format!(".tmp-{}-{n}", std::process::id()))
  72. }
  73. #[cfg(test)]
  74. mod tests {
  75. use super::*;
  76. use std::sync::atomic::{AtomicUsize, Ordering};
  77. struct Upper {
  78. version: u32,
  79. runs: AtomicUsize,
  80. }
  81. impl Converter for Upper {
  82. fn id(&self) -> &'static str {
  83. "test.upper"
  84. }
  85. fn version(&self) -> u32 {
  86. self.version
  87. }
  88. fn convert(&self, input: &[u8]) -> Result<Vec<u8>> {
  89. self.runs.fetch_add(1, Ordering::Relaxed);
  90. Ok(input.to_ascii_uppercase())
  91. }
  92. }
  93. #[test]
  94. fn converts_once_then_hits() {
  95. let tmp = tempfile::tempdir().unwrap();
  96. let cache = Cache::open(tmp.path().join("cache")).unwrap();
  97. let conv = Upper {
  98. version: 1,
  99. runs: AtomicUsize::new(0),
  100. };
  101. let a = cache.get_or_convert(&conv, b"abc").unwrap();
  102. let b = cache.get_or_convert(&conv, b"abc").unwrap();
  103. assert_eq!(a, b);
  104. assert_eq!(std::fs::read(&a).unwrap(), b"ABC");
  105. assert_eq!(conv.runs.load(Ordering::Relaxed), 1);
  106. }
  107. #[test]
  108. fn failed_publication_removes_the_staging_file() {
  109. let tmp = tempfile::tempdir().unwrap();
  110. let cache = Cache::open(tmp.path().join("cache")).unwrap();
  111. let conv = Upper {
  112. version: 1,
  113. runs: AtomicUsize::new(0),
  114. };
  115. let path = cache.path_for(&CacheKey::new(&conv, b"abc"));
  116. std::fs::create_dir_all(&path).unwrap();
  117. assert!(cache.get_or_convert(&conv, b"abc").is_err());
  118. assert!(path.is_dir());
  119. assert_eq!(
  120. std::fs::read_dir(path.parent().unwrap()).unwrap().count(),
  121. 1
  122. );
  123. }
  124. #[test]
  125. fn version_bump_invalidates() {
  126. let v1 = Upper {
  127. version: 1,
  128. runs: AtomicUsize::new(0),
  129. };
  130. let v2 = Upper {
  131. version: 2,
  132. runs: AtomicUsize::new(0),
  133. };
  134. assert_ne!(CacheKey::new(&v1, b"x"), CacheKey::new(&v2, b"x"));
  135. }
  136. #[test]
  137. fn refuses_cache_inside_repo() {
  138. let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("cache");
  139. assert!(Cache::open(inside).is_err());
  140. }
  141. }