zlayer_registry/cache.rs
1//! Local blob cache for OCI images
2//!
3//! Simplified cache implementation using `std::collections::HashMap`.
4//!
5//! ## Cache-key construction rule
6//!
7//! All cache keys for OCI manifest data MUST be constructed via the
8//! helpers in [`crate::client`]:
9//!
10//! - [`crate::client::manifest_cache_key`] for the manifest body.
11//! - [`crate::client::manifest_digest_cache_key`] for the digest sidecar.
12//!
13//! Do NOT write `format!("manifest...")` anywhere outside `crate::client`.
14//! A previous drift between two `format!` strings (writer using
15//! `"manifest:digest-{image}"`, reader using `"manifest-digest:{image}"`)
16//! silently broke image-recreate detection — exactly the bug class these
17//! helpers exist to prevent.
18
19use crate::error::{CacheError, Result};
20use async_trait::async_trait;
21use sha2::{Digest, Sha256};
22use std::path::{Path, PathBuf};
23use std::sync::Arc;
24use std::sync::RwLock;
25
26/// Trait for blob cache backends
27///
28/// This trait abstracts the storage backend for blob caching,
29/// allowing different implementations (in-memory, disk, S3, etc.)
30#[async_trait]
31pub trait BlobCacheBackend: Send + Sync {
32 /// Get a blob by digest
33 async fn get(&self, digest: &str) -> Result<Option<Vec<u8>>, CacheError>;
34
35 /// Put a blob into the cache
36 async fn put(&self, digest: &str, data: &[u8]) -> Result<(), CacheError>;
37
38 /// Check if a blob exists in the cache
39 async fn contains(&self, digest: &str) -> Result<bool, CacheError>;
40
41 /// Remove a cached entry by key.
42 ///
43 /// The default implementation returns an "unsupported" error so backends
44 /// that cannot efficiently delete individual entries (e.g. immutable
45 /// object stores) can still satisfy the trait. Callers should treat a
46 /// delete failure as non-fatal and continue — the cache will eventually
47 /// be revalidated or evicted by other means.
48 ///
49 /// # Errors
50 ///
51 /// Returns `CacheError::Database` when the backend does not support
52 /// point deletion, or when the underlying store reports a failure.
53 async fn delete(&self, _digest: &str) -> Result<(), CacheError> {
54 Err(CacheError::Database(
55 "delete not supported for this cache backend".to_string(),
56 ))
57 }
58
59 /// Return every cached key whose name starts with `prefix`.
60 ///
61 /// Used by image-management operations (`zlayer image ls`, `rm`, `prune`)
62 /// to walk the manifest keyspace without loading every blob. The default
63 /// implementation returns `CacheError::Database`, so backends that cannot
64 /// efficiently enumerate keys (e.g. S3) simply don't support the feature.
65 ///
66 /// Ordering is not defined; callers must not depend on it.
67 ///
68 /// # Errors
69 ///
70 /// Returns `CacheError::Database` when the backend doesn't support
71 /// enumeration, or when the underlying store fails.
72 async fn keys_with_prefix(&self, _prefix: &str) -> Result<Vec<String>, CacheError> {
73 Err(CacheError::Database(
74 "keys_with_prefix not supported for this cache backend".to_string(),
75 ))
76 }
77
78 /// Size in bytes of a cached blob, without loading the blob body.
79 ///
80 /// The default reads the whole blob via [`BlobCacheBackend::get`] and
81 /// reports its length; file- or metadata-backed backends should override
82 /// this to avoid materializing large blobs just to measure them.
83 ///
84 /// # Errors
85 ///
86 /// Returns `CacheError` if the underlying lookup fails.
87 async fn get_size(&self, digest: &str) -> Result<Option<u64>, CacheError> {
88 Ok(self.get(digest).await?.map(|v| v.len() as u64))
89 }
90
91 /// Filesystem path of a cached blob's bytes, when the backend stores the
92 /// blob as a file on disk. Returns `None` for in-memory / inline / remote
93 /// backends — callers must then fall back to [`BlobCacheBackend::get`].
94 ///
95 /// This lets the streaming pull path consume a large layer straight from
96 /// disk without ever holding it in a `Vec<u8>`.
97 ///
98 /// # Errors
99 ///
100 /// Returns `CacheError` if the lookup fails.
101 async fn get_path(&self, _digest: &str) -> Result<Option<PathBuf>, CacheError> {
102 Ok(None)
103 }
104
105 /// Ingest an already-on-disk file as a cached blob without buffering it in
106 /// memory. The default reads `src` into memory and calls
107 /// [`BlobCacheBackend::put`]; file-backed backends should override this to
108 /// hardlink/move the file and avoid the read.
109 ///
110 /// # Errors
111 ///
112 /// Returns `CacheError` if the file cannot be read or the store write fails.
113 async fn put_path(&self, digest: &str, src: &Path) -> Result<(), CacheError> {
114 let data = tokio::fs::read(src).await?;
115 self.put(digest, &data).await
116 }
117
118 /// Reclaim free space the backend is holding but no longer using (e.g.
119 /// `SQLite` freelist pages left behind by deletes/evictions, which keep the
120 /// on-disk file large even after the rows are gone).
121 ///
122 /// Best-effort and potentially expensive (a full rewrite on some backends),
123 /// so call it only from explicit prune / maintenance paths — never on the
124 /// hot read/write path. The default is a no-op for backends with nothing to
125 /// compact (in-memory caches, remote object stores).
126 ///
127 /// # Errors
128 ///
129 /// Returns `CacheError` if the underlying store reports a failure.
130 async fn compact(&self) -> Result<(), CacheError> {
131 Ok(())
132 }
133}
134
135/// Local blob cache for OCI images (in-memory)
136pub struct BlobCache {
137 blobs: Arc<RwLock<std::collections::HashMap<String, Vec<u8>>>>,
138 max_size_bytes: u64,
139}
140
141impl BlobCache {
142 /// Largest blob [`BlobCacheBackend::put_path`] will read into RAM for the
143 /// in-memory cache; bigger blobs are skipped to avoid buffering a layer.
144 const MAX_INMEM_INGEST: u64 = 64 * 1024 * 1024;
145
146 /// Create a new in-memory cache
147 ///
148 /// # Errors
149 ///
150 /// Returns `CacheError` if the cache cannot be initialized.
151 pub fn new() -> Result<Self, CacheError> {
152 Ok(Self {
153 blobs: Arc::new(RwLock::new(std::collections::HashMap::new())),
154 max_size_bytes: 10 * 1024 * 1024 * 1024, // 10GB default
155 })
156 }
157
158 /// Open or create a cache at the given path (creates in-memory for now)
159 ///
160 /// # Errors
161 ///
162 /// Returns `CacheError` if the cache cannot be initialized.
163 pub fn open<P: AsRef<Path>>(_path: P) -> Result<Self, CacheError> {
164 Self::new()
165 }
166
167 /// Set maximum cache size in bytes
168 #[must_use]
169 pub fn with_max_size(mut self, max_size_bytes: u64) -> Self {
170 self.max_size_bytes = max_size_bytes;
171 self
172 }
173
174 /// Get a blob by digest
175 ///
176 /// # Errors
177 ///
178 /// Returns `CacheError` if the digest is invalid or the lock is poisoned.
179 pub fn get(&self, digest: &str) -> Result<Option<Vec<u8>>, CacheError> {
180 validate_digest(digest)?;
181 let blobs = self
182 .blobs
183 .read()
184 .map_err(|e| CacheError::Database(format!("failed to acquire read lock: {e}")))?;
185 Ok(blobs.get(digest).cloned())
186 }
187
188 /// Put a blob into the cache
189 ///
190 /// # Errors
191 ///
192 /// Returns `CacheError` if the digest is invalid, mismatched, or the lock is poisoned.
193 pub fn put(&self, digest: &str, data: &[u8]) -> Result<(), CacheError> {
194 validate_digest(digest)?;
195
196 // Verify digest matches data (skip for manifest cache keys)
197 if !digest.starts_with("manifest:") {
198 let actual_digest = compute_digest(data);
199 if actual_digest != digest {
200 return Err(CacheError::Corrupted(format!(
201 "digest mismatch: expected {digest}, got {actual_digest}"
202 )));
203 }
204 }
205
206 {
207 let mut blobs = self
208 .blobs
209 .write()
210 .map_err(|e| CacheError::Database(format!("failed to acquire write lock: {e}")))?;
211 blobs.insert(digest.to_string(), data.to_vec());
212 } // Write lock released here
213
214 // Now safe to call evict_if_needed() with no locks held
215 self.evict_if_needed()?;
216
217 Ok(())
218 }
219
220 /// Check if a blob exists in the cache
221 ///
222 /// # Errors
223 ///
224 /// Returns `CacheError` if the digest is invalid or the lock is poisoned.
225 pub fn contains(&self, digest: &str) -> Result<bool, CacheError> {
226 validate_digest(digest)?;
227 let blobs = self
228 .blobs
229 .read()
230 .map_err(|e| CacheError::Database(format!("failed to acquire read lock: {e}")))?;
231 Ok(blobs.contains_key(digest))
232 }
233
234 /// Delete a blob from the cache
235 ///
236 /// # Errors
237 ///
238 /// Returns `CacheError` if the digest is invalid or the lock is poisoned.
239 pub fn delete(&self, digest: &str) -> Result<(), CacheError> {
240 validate_digest(digest)?;
241 let mut blobs = self
242 .blobs
243 .write()
244 .map_err(|e| CacheError::Database(format!("failed to acquire write lock: {e}")))?;
245 blobs.remove(digest);
246 Ok(())
247 }
248
249 /// Get current cache size in bytes
250 ///
251 /// # Errors
252 ///
253 /// Returns `CacheError` if the lock is poisoned.
254 pub fn size(&self) -> Result<u64, CacheError> {
255 let blobs = self
256 .blobs
257 .read()
258 .map_err(|e| CacheError::Database(format!("failed to acquire read lock: {e}")))?;
259 let size = blobs.values().map(|v| v.len() as u64).sum();
260 Ok(size)
261 }
262
263 /// Clear all blobs from the cache
264 ///
265 /// # Errors
266 ///
267 /// Returns `CacheError` if the lock is poisoned.
268 pub fn clear(&self) -> Result<(), CacheError> {
269 let mut blobs = self
270 .blobs
271 .write()
272 .map_err(|e| CacheError::Database(format!("failed to acquire write lock: {e}")))?;
273 blobs.clear();
274 Ok(())
275 }
276
277 /// Evict blobs if cache is over size limit
278 fn evict_if_needed(&self) -> Result<(), CacheError> {
279 let current_size = self.size()?;
280 if current_size <= self.max_size_bytes {
281 return Ok(());
282 }
283
284 // Simple eviction: clear if significantly over
285 if current_size > self.max_size_bytes * 2 {
286 self.clear()?;
287 }
288
289 Ok(())
290 }
291}
292
293impl Default for BlobCache {
294 fn default() -> Self {
295 Self::new().unwrap()
296 }
297}
298
299#[async_trait]
300impl BlobCacheBackend for BlobCache {
301 async fn get(&self, digest: &str) -> Result<Option<Vec<u8>>, CacheError> {
302 // Delegate to the synchronous method
303 BlobCache::get(self, digest)
304 }
305
306 async fn put(&self, digest: &str, data: &[u8]) -> Result<(), CacheError> {
307 // Delegate to the synchronous method
308 BlobCache::put(self, digest, data)
309 }
310
311 async fn contains(&self, digest: &str) -> Result<bool, CacheError> {
312 // Delegate to the synchronous method
313 BlobCache::contains(self, digest)
314 }
315
316 async fn delete(&self, digest: &str) -> Result<(), CacheError> {
317 // Delegate to the synchronous method
318 BlobCache::delete(self, digest)
319 }
320
321 async fn keys_with_prefix(&self, prefix: &str) -> Result<Vec<String>, CacheError> {
322 let blobs = self
323 .blobs
324 .read()
325 .map_err(|e| CacheError::Database(format!("failed to acquire read lock: {e}")))?;
326 Ok(blobs
327 .keys()
328 .filter(|k| k.starts_with(prefix))
329 .cloned()
330 .collect())
331 }
332
333 /// Ingest a file into the in-memory cache, but ONLY when it is small.
334 ///
335 /// An in-memory cache holding a value means holding its bytes in RAM — the
336 /// exact thing the streaming pull path avoids for large layers. So a blob
337 /// larger than [`Self::MAX_INMEM_INGEST`] is skipped (the on-disk file the
338 /// caller already has remains the source of truth); small blobs are read in
339 /// and cached as usual. The file-backed [`crate::PersistentBlobCache`]
340 /// overrides this with a zero-copy hardlink and has no such cap.
341 async fn put_path(&self, digest: &str, src: &Path) -> Result<(), CacheError> {
342 let size = tokio::fs::metadata(src).await?.len();
343 if size > Self::MAX_INMEM_INGEST {
344 return Ok(());
345 }
346 let data = tokio::fs::read(src).await?;
347 BlobCache::put(self, digest, &data)
348 }
349}
350
351/// Validate that a digest string is properly formatted
352///
353/// Accepts two formats:
354/// - `sha256:<64 hex chars>` - Standard blob digest
355/// - `manifest:<image reference>` - Manifest cache key
356pub(crate) fn validate_digest(digest: &str) -> Result<(), CacheError> {
357 // Allow manifest cache keys
358 if digest.starts_with("manifest:") {
359 return Ok(());
360 }
361
362 // Standard sha256 digest validation
363 if !digest.starts_with("sha256:") {
364 return Err(CacheError::InvalidDigest(
365 "digest must start with sha256: or manifest:".to_string(),
366 ));
367 }
368
369 let hex_part = &digest[7..];
370 if hex_part.len() != 64 {
371 return Err(CacheError::InvalidDigest(
372 "sha256 digest must be 64 hex characters".to_string(),
373 ));
374 }
375
376 if !hex_part.chars().all(|c| c.is_ascii_hexdigit()) {
377 return Err(CacheError::InvalidDigest(
378 "digest must contain only hex characters".to_string(),
379 ));
380 }
381
382 Ok(())
383}
384
385/// Compute SHA-256 digest of data
386#[must_use]
387pub fn compute_digest(data: &[u8]) -> String {
388 let mut hasher = Sha256::new();
389 hasher.update(data);
390 let result = hasher.finalize();
391 format!("sha256:{}", hex::encode(result))
392}
393
394#[cfg(test)]
395mod tests {
396 use super::*;
397
398 #[test]
399 fn test_compute_digest() {
400 let data = b"hello world";
401 let digest = compute_digest(data);
402 assert!(digest.starts_with("sha256:"));
403 assert_eq!(digest.len(), 7 + 64);
404 }
405
406 #[test]
407 fn test_validate_digest() {
408 assert!(validate_digest(
409 "sha256:1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
410 )
411 .is_ok());
412 assert!(validate_digest("md5:123456").is_err());
413 assert!(validate_digest("sha256:123").is_err());
414 }
415
416 #[test]
417 fn test_cache_put_get() {
418 let cache = BlobCache::new().unwrap();
419
420 let data = b"test data";
421 let digest = compute_digest(data);
422
423 // Put and get
424 cache.put(&digest, data).unwrap();
425 let retrieved = cache.get(&digest).unwrap();
426 assert_eq!(retrieved, Some(data.to_vec()));
427
428 // Contains
429 assert!(cache.contains(&digest).unwrap());
430
431 // Delete
432 cache.delete(&digest).unwrap();
433 assert!(!cache.contains(&digest).unwrap());
434 }
435
436 #[tokio::test]
437 async fn blob_cache_keys_with_prefix_filters_correctly() {
438 let cache = BlobCache::new().unwrap();
439 cache.put("manifest:foo", b"body1").unwrap();
440 cache.put("manifest:bar", b"body2").unwrap();
441 // Real sha256 digest of b"body3" so put() validation succeeds.
442 let body3 = b"body3";
443 let body3_digest = compute_digest(body3);
444 cache.put(&body3_digest, body3).unwrap();
445
446 let mut keys = <BlobCache as BlobCacheBackend>::keys_with_prefix(&cache, "manifest:")
447 .await
448 .unwrap();
449 keys.sort();
450 assert_eq!(
451 keys,
452 vec!["manifest:bar".to_string(), "manifest:foo".to_string()]
453 );
454 }
455}