cache.rs 3.9 KB

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