zlayer-registry 0.14.0

OCI container registry client with blob caching
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! Local blob cache for OCI images
//!
//! Simplified cache implementation using `std::collections::HashMap`.
//!
//! ## Cache-key construction rule
//!
//! All cache keys for OCI manifest data MUST be constructed via the
//! helpers in [`crate::client`]:
//!
//! - [`crate::client::manifest_cache_key`] for the manifest body.
//! - [`crate::client::manifest_digest_cache_key`] for the digest sidecar.
//!
//! Do NOT write `format!("manifest...")` anywhere outside `crate::client`.
//! A previous drift between two `format!` strings (writer using
//! `"manifest:digest-{image}"`, reader using `"manifest-digest:{image}"`)
//! silently broke image-recreate detection — exactly the bug class these
//! helpers exist to prevent.

use crate::error::{CacheError, Result};
use async_trait::async_trait;
use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};
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(),
        ))
    }

    /// Size in bytes of a cached blob, without loading the blob body.
    ///
    /// The default reads the whole blob via [`BlobCacheBackend::get`] and
    /// reports its length; file- or metadata-backed backends should override
    /// this to avoid materializing large blobs just to measure them.
    ///
    /// # Errors
    ///
    /// Returns `CacheError` if the underlying lookup fails.
    async fn get_size(&self, digest: &str) -> Result<Option<u64>, CacheError> {
        Ok(self.get(digest).await?.map(|v| v.len() as u64))
    }

    /// Filesystem path of a cached blob's bytes, when the backend stores the
    /// blob as a file on disk. Returns `None` for in-memory / inline / remote
    /// backends — callers must then fall back to [`BlobCacheBackend::get`].
    ///
    /// This lets the streaming pull path consume a large layer straight from
    /// disk without ever holding it in a `Vec<u8>`.
    ///
    /// # Errors
    ///
    /// Returns `CacheError` if the lookup fails.
    async fn get_path(&self, _digest: &str) -> Result<Option<PathBuf>, CacheError> {
        Ok(None)
    }

    /// Ingest an already-on-disk file as a cached blob without buffering it in
    /// memory. The default reads `src` into memory and calls
    /// [`BlobCacheBackend::put`]; file-backed backends should override this to
    /// hardlink/move the file and avoid the read.
    ///
    /// # Errors
    ///
    /// Returns `CacheError` if the file cannot be read or the store write fails.
    async fn put_path(&self, digest: &str, src: &Path) -> Result<(), CacheError> {
        let data = tokio::fs::read(src).await?;
        self.put(digest, &data).await
    }

    /// Reclaim free space the backend is holding but no longer using (e.g.
    /// `SQLite` freelist pages left behind by deletes/evictions, which keep the
    /// on-disk file large even after the rows are gone).
    ///
    /// Best-effort and potentially expensive (a full rewrite on some backends),
    /// so call it only from explicit prune / maintenance paths — never on the
    /// hot read/write path. The default is a no-op for backends with nothing to
    /// compact (in-memory caches, remote object stores).
    ///
    /// # Errors
    ///
    /// Returns `CacheError` if the underlying store reports a failure.
    async fn compact(&self) -> Result<(), CacheError> {
        Ok(())
    }
}

/// 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 {
    /// Largest blob [`BlobCacheBackend::put_path`] will read into RAM for the
    /// in-memory cache; bigger blobs are skipped to avoid buffering a layer.
    const MAX_INMEM_INGEST: u64 = 64 * 1024 * 1024;

    /// 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())
    }

    /// Ingest a file into the in-memory cache, but ONLY when it is small.
    ///
    /// An in-memory cache holding a value means holding its bytes in RAM — the
    /// exact thing the streaming pull path avoids for large layers. So a blob
    /// larger than [`Self::MAX_INMEM_INGEST`] is skipped (the on-disk file the
    /// caller already has remains the source of truth); small blobs are read in
    /// and cached as usual. The file-backed [`crate::PersistentBlobCache`]
    /// overrides this with a zero-copy hardlink and has no such cap.
    async fn put_path(&self, digest: &str, src: &Path) -> Result<(), CacheError> {
        let size = tokio::fs::metadata(src).await?.len();
        if size > Self::MAX_INMEM_INGEST {
            return Ok(());
        }
        let data = tokio::fs::read(src).await?;
        BlobCache::put(self, digest, &data)
    }
}

/// 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()]
        );
    }
}