zlayer-registry 0.11.2

OCI container registry client with blob caching
Documentation
//! Local blob cache for OCI images
//!
//! Simplified cache implementation using `std::collections::HashMap`.

use crate::error::{CacheError, Result};
use async_trait::async_trait;
use sha2::{Digest, Sha256};
use std::path::Path;
use std::sync::Arc;
use std::sync::RwLock;

/// Trait for blob cache backends
///
/// This trait abstracts the storage backend for blob caching,
/// allowing different implementations (in-memory, disk, S3, etc.)
#[async_trait]
pub trait BlobCacheBackend: Send + Sync {
    /// Get a blob by digest
    async fn get(&self, digest: &str) -> Result<Option<Vec<u8>>, CacheError>;

    /// Put a blob into the cache
    async fn put(&self, digest: &str, data: &[u8]) -> Result<(), CacheError>;

    /// Check if a blob exists in the cache
    async fn contains(&self, digest: &str) -> Result<bool, CacheError>;

    /// Remove a cached entry by key.
    ///
    /// The default implementation returns an "unsupported" error so backends
    /// that cannot efficiently delete individual entries (e.g. immutable
    /// object stores) can still satisfy the trait. Callers should treat a
    /// delete failure as non-fatal and continue — the cache will eventually
    /// be revalidated or evicted by other means.
    ///
    /// # Errors
    ///
    /// Returns `CacheError::Database` when the backend does not support
    /// point deletion, or when the underlying store reports a failure.
    async fn delete(&self, _digest: &str) -> Result<(), CacheError> {
        Err(CacheError::Database(
            "delete not supported for this cache backend".to_string(),
        ))
    }

    /// Return every cached key whose name starts with `prefix`.
    ///
    /// Used by image-management operations (`zlayer image ls`, `rm`, `prune`)
    /// to walk the manifest keyspace without loading every blob. The default
    /// implementation returns `CacheError::Database`, so backends that cannot
    /// efficiently enumerate keys (e.g. S3) simply don't support the feature.
    ///
    /// Ordering is not defined; callers must not depend on it.
    ///
    /// # Errors
    ///
    /// Returns `CacheError::Database` when the backend doesn't support
    /// enumeration, or when the underlying store fails.
    async fn keys_with_prefix(&self, _prefix: &str) -> Result<Vec<String>, CacheError> {
        Err(CacheError::Database(
            "keys_with_prefix not supported for this cache backend".to_string(),
        ))
    }
}

/// Local blob cache for OCI images (in-memory)
pub struct BlobCache {
    blobs: Arc<RwLock<std::collections::HashMap<String, Vec<u8>>>>,
    max_size_bytes: u64,
}

impl BlobCache {
    /// Create a new in-memory cache
    ///
    /// # Errors
    ///
    /// Returns `CacheError` if the cache cannot be initialized.
    pub fn new() -> Result<Self, CacheError> {
        Ok(Self {
            blobs: Arc::new(RwLock::new(std::collections::HashMap::new())),
            max_size_bytes: 10 * 1024 * 1024 * 1024, // 10GB default
        })
    }

    /// Open or create a cache at the given path (creates in-memory for now)
    ///
    /// # Errors
    ///
    /// Returns `CacheError` if the cache cannot be initialized.
    pub fn open<P: AsRef<Path>>(_path: P) -> Result<Self, CacheError> {
        Self::new()
    }

    /// Set maximum cache size in bytes
    #[must_use]
    pub fn with_max_size(mut self, max_size_bytes: u64) -> Self {
        self.max_size_bytes = max_size_bytes;
        self
    }

    /// Get a blob by digest
    ///
    /// # Errors
    ///
    /// Returns `CacheError` if the digest is invalid or the lock is poisoned.
    pub fn get(&self, digest: &str) -> Result<Option<Vec<u8>>, CacheError> {
        validate_digest(digest)?;
        let blobs = self
            .blobs
            .read()
            .map_err(|e| CacheError::Database(format!("failed to acquire read lock: {e}")))?;
        Ok(blobs.get(digest).cloned())
    }

    /// Put a blob into the cache
    ///
    /// # Errors
    ///
    /// Returns `CacheError` if the digest is invalid, mismatched, or the lock is poisoned.
    pub fn put(&self, digest: &str, data: &[u8]) -> Result<(), CacheError> {
        validate_digest(digest)?;

        // Verify digest matches data (skip for manifest cache keys)
        if !digest.starts_with("manifest:") {
            let actual_digest = compute_digest(data);
            if actual_digest != digest {
                return Err(CacheError::Corrupted(format!(
                    "digest mismatch: expected {digest}, got {actual_digest}"
                )));
            }
        }

        {
            let mut blobs = self
                .blobs
                .write()
                .map_err(|e| CacheError::Database(format!("failed to acquire write lock: {e}")))?;
            blobs.insert(digest.to_string(), data.to_vec());
        } // Write lock released here

        // Now safe to call evict_if_needed() with no locks held
        self.evict_if_needed()?;

        Ok(())
    }

    /// Check if a blob exists in the cache
    ///
    /// # Errors
    ///
    /// Returns `CacheError` if the digest is invalid or the lock is poisoned.
    pub fn contains(&self, digest: &str) -> Result<bool, CacheError> {
        validate_digest(digest)?;
        let blobs = self
            .blobs
            .read()
            .map_err(|e| CacheError::Database(format!("failed to acquire read lock: {e}")))?;
        Ok(blobs.contains_key(digest))
    }

    /// Delete a blob from the cache
    ///
    /// # Errors
    ///
    /// Returns `CacheError` if the digest is invalid or the lock is poisoned.
    pub fn delete(&self, digest: &str) -> Result<(), CacheError> {
        validate_digest(digest)?;
        let mut blobs = self
            .blobs
            .write()
            .map_err(|e| CacheError::Database(format!("failed to acquire write lock: {e}")))?;
        blobs.remove(digest);
        Ok(())
    }

    /// Get current cache size in bytes
    ///
    /// # Errors
    ///
    /// Returns `CacheError` if the lock is poisoned.
    pub fn size(&self) -> Result<u64, CacheError> {
        let blobs = self
            .blobs
            .read()
            .map_err(|e| CacheError::Database(format!("failed to acquire read lock: {e}")))?;
        let size = blobs.values().map(|v| v.len() as u64).sum();
        Ok(size)
    }

    /// Clear all blobs from the cache
    ///
    /// # Errors
    ///
    /// Returns `CacheError` if the lock is poisoned.
    pub fn clear(&self) -> Result<(), CacheError> {
        let mut blobs = self
            .blobs
            .write()
            .map_err(|e| CacheError::Database(format!("failed to acquire write lock: {e}")))?;
        blobs.clear();
        Ok(())
    }

    /// Evict blobs if cache is over size limit
    fn evict_if_needed(&self) -> Result<(), CacheError> {
        let current_size = self.size()?;
        if current_size <= self.max_size_bytes {
            return Ok(());
        }

        // Simple eviction: clear if significantly over
        if current_size > self.max_size_bytes * 2 {
            self.clear()?;
        }

        Ok(())
    }
}

impl Default for BlobCache {
    fn default() -> Self {
        Self::new().unwrap()
    }
}

#[async_trait]
impl BlobCacheBackend for BlobCache {
    async fn get(&self, digest: &str) -> Result<Option<Vec<u8>>, CacheError> {
        // Delegate to the synchronous method
        BlobCache::get(self, digest)
    }

    async fn put(&self, digest: &str, data: &[u8]) -> Result<(), CacheError> {
        // Delegate to the synchronous method
        BlobCache::put(self, digest, data)
    }

    async fn contains(&self, digest: &str) -> Result<bool, CacheError> {
        // Delegate to the synchronous method
        BlobCache::contains(self, digest)
    }

    async fn delete(&self, digest: &str) -> Result<(), CacheError> {
        // Delegate to the synchronous method
        BlobCache::delete(self, digest)
    }

    async fn keys_with_prefix(&self, prefix: &str) -> Result<Vec<String>, CacheError> {
        let blobs = self
            .blobs
            .read()
            .map_err(|e| CacheError::Database(format!("failed to acquire read lock: {e}")))?;
        Ok(blobs
            .keys()
            .filter(|k| k.starts_with(prefix))
            .cloned()
            .collect())
    }
}

/// Validate that a digest string is properly formatted
///
/// Accepts two formats:
/// - `sha256:<64 hex chars>` - Standard blob digest
/// - `manifest:<image reference>` - Manifest cache key
pub(crate) fn validate_digest(digest: &str) -> Result<(), CacheError> {
    // Allow manifest cache keys
    if digest.starts_with("manifest:") {
        return Ok(());
    }

    // Standard sha256 digest validation
    if !digest.starts_with("sha256:") {
        return Err(CacheError::InvalidDigest(
            "digest must start with sha256: or manifest:".to_string(),
        ));
    }

    let hex_part = &digest[7..];
    if hex_part.len() != 64 {
        return Err(CacheError::InvalidDigest(
            "sha256 digest must be 64 hex characters".to_string(),
        ));
    }

    if !hex_part.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(CacheError::InvalidDigest(
            "digest must contain only hex characters".to_string(),
        ));
    }

    Ok(())
}

/// Compute SHA-256 digest of data
#[must_use]
pub fn compute_digest(data: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(data);
    let result = hasher.finalize();
    format!("sha256:{}", hex::encode(result))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_compute_digest() {
        let data = b"hello world";
        let digest = compute_digest(data);
        assert!(digest.starts_with("sha256:"));
        assert_eq!(digest.len(), 7 + 64);
    }

    #[test]
    fn test_validate_digest() {
        assert!(validate_digest(
            "sha256:1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
        )
        .is_ok());
        assert!(validate_digest("md5:123456").is_err());
        assert!(validate_digest("sha256:123").is_err());
    }

    #[test]
    fn test_cache_put_get() {
        let cache = BlobCache::new().unwrap();

        let data = b"test data";
        let digest = compute_digest(data);

        // Put and get
        cache.put(&digest, data).unwrap();
        let retrieved = cache.get(&digest).unwrap();
        assert_eq!(retrieved, Some(data.to_vec()));

        // Contains
        assert!(cache.contains(&digest).unwrap());

        // Delete
        cache.delete(&digest).unwrap();
        assert!(!cache.contains(&digest).unwrap());
    }

    #[tokio::test]
    async fn blob_cache_keys_with_prefix_filters_correctly() {
        let cache = BlobCache::new().unwrap();
        cache.put("manifest:foo", b"body1").unwrap();
        cache.put("manifest:bar", b"body2").unwrap();
        // Real sha256 digest of b"body3" so put() validation succeeds.
        let body3 = b"body3";
        let body3_digest = compute_digest(body3);
        cache.put(&body3_digest, body3).unwrap();

        let mut keys = <BlobCache as BlobCacheBackend>::keys_with_prefix(&cache, "manifest:")
            .await
            .unwrap();
        keys.sort();
        assert_eq!(
            keys,
            vec!["manifest:bar".to_string(), "manifest:foo".to_string()]
        );
    }
}