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
456
457
458
459
460
461
//! S3-backed blob cache for OCI images
//!
//! Provides S3 storage backend for image layers with optional local cache tier.

use crate::cache::BlobCacheBackend;
use crate::error::CacheError;
use aws_sdk_s3::primitives::ByteStream;
use aws_sdk_s3::Client;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::RwLock;

/// Result type alias for S3 cache operations
pub type Result<T> = std::result::Result<T, CacheError>;

/// Configuration for S3 blob cache
#[derive(Debug, Clone)]
pub struct S3CacheConfig {
    /// S3 bucket name
    pub bucket: String,
    /// Key prefix for blobs (e.g., "zlayer/blobs/")
    pub prefix: String,
    /// AWS region (optional, uses SDK default if not set)
    pub region: Option<String>,
    /// Custom S3 endpoint (for S3-compatible services like R2, B2, `MinIO`)
    pub endpoint: Option<String>,
    /// Use path-style URLs (required for some S3-compatible services)
    pub path_style: bool,
    /// Local cache directory for read-through caching
    pub local_cache_dir: Option<PathBuf>,
}

impl S3CacheConfig {
    /// Create a new S3 cache config for AWS S3
    pub fn new(bucket: impl Into<String>) -> Self {
        Self {
            bucket: bucket.into(),
            prefix: "zlayer/blobs/".to_string(),
            region: None,
            endpoint: None,
            path_style: false,
            local_cache_dir: None,
        }
    }

    /// Create config for Cloudflare R2
    pub fn cloudflare_r2(bucket: impl Into<String>, account_id: impl AsRef<str>) -> Self {
        Self {
            bucket: bucket.into(),
            prefix: "zlayer/blobs/".to_string(),
            region: Some("auto".to_string()),
            endpoint: Some(format!(
                "https://{}.r2.cloudflarestorage.com",
                account_id.as_ref()
            )),
            path_style: true,
            local_cache_dir: None,
        }
    }

    /// Create config for Backblaze B2
    pub fn backblaze_b2(bucket: impl Into<String>, region: impl Into<String>) -> Self {
        let region = region.into();
        Self {
            bucket: bucket.into(),
            prefix: "zlayer/blobs/".to_string(),
            region: Some(region.clone()),
            endpoint: Some(format!("https://s3.{region}.backblazeb2.com")),
            path_style: false,
            local_cache_dir: None,
        }
    }

    /// Create config for Wasabi
    pub fn wasabi(bucket: impl Into<String>, region: impl Into<String>) -> Self {
        let region = region.into();
        Self {
            bucket: bucket.into(),
            prefix: "zlayer/blobs/".to_string(),
            region: Some(region.clone()),
            endpoint: Some(format!("https://s3.{region}.wasabisys.com")),
            path_style: false,
            local_cache_dir: None,
        }
    }

    /// Set custom prefix
    #[must_use]
    pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.prefix = prefix.into();
        self
    }

    /// Set region
    #[must_use]
    pub fn with_region(mut self, region: impl Into<String>) -> Self {
        self.region = Some(region.into());
        self
    }

    /// Set custom endpoint
    #[must_use]
    pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.endpoint = Some(endpoint.into());
        self
    }

    /// Enable path-style URLs
    #[must_use]
    pub fn with_path_style(mut self) -> Self {
        self.path_style = true;
        self
    }

    /// Enable local cache read-through
    #[must_use]
    pub fn with_local_cache(mut self, dir: impl Into<PathBuf>) -> Self {
        self.local_cache_dir = Some(dir.into());
        self
    }

    /// Get the full key for a digest
    #[must_use]
    pub fn key_for_digest(&self, digest: &str) -> String {
        format!("{}{}", self.prefix, digest.replace(':', "/"))
    }
}

impl Default for S3CacheConfig {
    fn default() -> Self {
        Self::new("zlayer-cache")
    }
}

/// S3-backed blob cache with optional local read-through cache
pub struct S3BlobCache {
    /// S3 client
    client: Client,
    /// Configuration
    config: S3CacheConfig,
    /// Local in-memory cache for hot blobs
    local_cache: Option<RwLock<HashMap<String, Vec<u8>>>>,
}

impl S3BlobCache {
    /// Create a new S3 blob cache
    ///
    /// # Errors
    ///
    /// Returns an error if the AWS SDK configuration cannot be built.
    pub async fn new(config: S3CacheConfig) -> Result<Self> {
        let sdk_config = Self::build_sdk_config(&config).await?;

        let mut s3_config = aws_sdk_s3::config::Builder::from(&sdk_config);

        // Set custom endpoint if configured
        if let Some(ref endpoint) = config.endpoint {
            s3_config = s3_config.endpoint_url(endpoint);
        }

        // Set path-style if configured
        if config.path_style {
            s3_config = s3_config.force_path_style(true);
        }

        let client = Client::from_conf(s3_config.build());

        // Initialize local cache if configured
        let local_cache = if config.local_cache_dir.is_some() {
            Some(RwLock::new(HashMap::new()))
        } else {
            None
        };

        Ok(Self {
            client,
            config,
            local_cache,
        })
    }

    /// Build AWS SDK config
    async fn build_sdk_config(config: &S3CacheConfig) -> Result<aws_config::SdkConfig> {
        let mut loader = aws_config::defaults(aws_config::BehaviorVersion::latest());

        if let Some(ref region) = config.region {
            loader = loader.region(aws_config::Region::new(region.clone()));
        } else if config.endpoint.is_some() {
            // Custom / non-AWS endpoint (R2, B2, MinIO, …): pin a static region so the SDK
            // never consults the IMDS region provider (which blocks ~5s+ off-AWS).
            loader = loader.region(aws_config::Region::new("us-east-1"));
        }

        Ok(loader.load().await)
    }

    /// Get a blob by digest
    ///
    /// # Errors
    ///
    /// Returns an error if the digest is invalid or the S3 operation fails.
    pub async fn get(&self, digest: &str) -> Result<Option<Vec<u8>>> {
        crate::cache::validate_digest(digest)?;

        // Check local cache first
        if let Some(ref local) = self.local_cache {
            if let Ok(cache) = local.read() {
                if let Some(data) = cache.get(digest) {
                    tracing::debug!(digest = %digest, "S3 cache hit (local)");
                    return Ok(Some(data.clone()));
                }
            }
        }

        // Fetch from S3
        let key = self.config.key_for_digest(digest);

        let result = self
            .client
            .get_object()
            .bucket(&self.config.bucket)
            .key(&key)
            .send()
            .await;

        match result {
            Ok(output) => {
                let data = output
                    .body
                    .collect()
                    .await
                    .map_err(|e| {
                        CacheError::Io(std::io::Error::other(format!(
                            "failed to read S3 response body: {e}"
                        )))
                    })?
                    .into_bytes()
                    .to_vec();

                // Verify digest
                let actual_digest = crate::cache::compute_digest(&data);
                if actual_digest != digest {
                    return Err(CacheError::Corrupted(format!(
                        "S3 blob digest mismatch: expected {digest}, got {actual_digest}"
                    )));
                }

                // Populate local cache
                if let Some(ref local) = self.local_cache {
                    if let Ok(mut cache) = local.write() {
                        cache.insert(digest.to_string(), data.clone());
                    }
                }

                tracing::debug!(digest = %digest, "S3 cache hit (remote)");
                Ok(Some(data))
            }
            Err(e) => {
                // Check if it's a not-found error
                if let aws_sdk_s3::error::SdkError::ServiceError(ref service_err) = e {
                    if service_err.err().is_no_such_key() {
                        tracing::debug!(digest = %digest, "S3 cache miss");
                        return Ok(None);
                    }
                }
                Err(CacheError::Io(std::io::Error::other(format!(
                    "S3 get failed: {e}"
                ))))
            }
        }
    }

    /// Put a blob into the cache
    ///
    /// # Errors
    ///
    /// Returns an error if the digest is invalid, mismatches the data, or the S3 upload fails.
    pub async fn put(&self, digest: &str, data: &[u8]) -> Result<()> {
        crate::cache::validate_digest(digest)?;

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

        let key = self.config.key_for_digest(digest);

        self.client
            .put_object()
            .bucket(&self.config.bucket)
            .key(&key)
            .body(ByteStream::from(data.to_vec()))
            .content_type("application/octet-stream")
            .send()
            .await
            .map_err(|e| CacheError::Io(std::io::Error::other(format!("S3 put failed: {e}"))))?;

        // Update local cache
        if let Some(ref local) = self.local_cache {
            if let Ok(mut cache) = local.write() {
                cache.insert(digest.to_string(), data.to_vec());
            }
        }

        tracing::debug!(digest = %digest, bucket = %self.config.bucket, "stored blob in S3");
        Ok(())
    }

    /// Check if a blob exists in the cache
    ///
    /// # Errors
    ///
    /// Returns an error if the digest is invalid or the S3 operation fails.
    pub async fn contains(&self, digest: &str) -> Result<bool> {
        crate::cache::validate_digest(digest)?;

        // Check local cache first
        if let Some(ref local) = self.local_cache {
            if let Ok(cache) = local.read() {
                if cache.contains_key(digest) {
                    return Ok(true);
                }
            }
        }

        // Check S3
        let key = self.config.key_for_digest(digest);

        let result = self
            .client
            .head_object()
            .bucket(&self.config.bucket)
            .key(&key)
            .send()
            .await;

        match result {
            Ok(_) => Ok(true),
            Err(e) => {
                if let aws_sdk_s3::error::SdkError::ServiceError(ref service_err) = e {
                    if service_err.err().is_not_found() {
                        return Ok(false);
                    }
                }
                Err(CacheError::Io(std::io::Error::other(format!(
                    "S3 head failed: {e}"
                ))))
            }
        }
    }

    /// Clear local cache
    pub fn clear_local_cache(&self) {
        if let Some(ref local) = self.local_cache {
            if let Ok(mut cache) = local.write() {
                cache.clear();
            }
        }
    }
}

#[async_trait::async_trait]
impl BlobCacheBackend for S3BlobCache {
    async fn get(&self, digest: &str) -> std::result::Result<Option<Vec<u8>>, CacheError> {
        S3BlobCache::get(self, digest).await
    }

    async fn put(&self, digest: &str, data: &[u8]) -> std::result::Result<(), CacheError> {
        S3BlobCache::put(self, digest, data).await
    }

    async fn contains(&self, digest: &str) -> std::result::Result<bool, CacheError> {
        S3BlobCache::contains(self, digest).await
    }

    async fn get_size(&self, digest: &str) -> std::result::Result<Option<u64>, CacheError> {
        crate::cache::validate_digest(digest)?;
        let key = self.config.key_for_digest(digest);
        match self
            .client
            .head_object()
            .bucket(&self.config.bucket)
            .key(&key)
            .send()
            .await
        {
            Ok(out) => Ok(Some(
                u64::try_from(out.content_length().unwrap_or(0)).unwrap_or(0),
            )),
            Err(e) => {
                if let aws_sdk_s3::error::SdkError::ServiceError(ref service_err) = e {
                    if service_err.err().is_not_found() {
                        return Ok(None);
                    }
                }
                Err(CacheError::Io(std::io::Error::other(format!(
                    "S3 head failed: {e}"
                ))))
            }
        }
    }

    /// Upload directly from a file, streaming via `ByteStream::from_path` so a
    /// multi-GB layer is never buffered in memory. (Skips the per-blob digest
    /// re-hash that `put` does — the streaming pull path already verified it.)
    async fn put_path(
        &self,
        digest: &str,
        src: &std::path::Path,
    ) -> std::result::Result<(), CacheError> {
        crate::cache::validate_digest(digest)?;
        let key = self.config.key_for_digest(digest);
        let body = ByteStream::from_path(src).await.map_err(|e| {
            CacheError::Io(std::io::Error::other(format!("S3 body from path: {e}")))
        })?;
        self.client
            .put_object()
            .bucket(&self.config.bucket)
            .key(&key)
            .body(body)
            .content_type("application/octet-stream")
            .send()
            .await
            .map_err(|e| CacheError::Io(std::io::Error::other(format!("S3 put failed: {e}"))))?;
        Ok(())
    }
}

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

    #[test]
    fn test_key_for_digest() {
        let config = S3CacheConfig::new("mybucket").with_prefix("blobs/");
        let key = config.key_for_digest("sha256:abc123");
        assert_eq!(key, "blobs/sha256/abc123");
    }

    #[test]
    fn test_cloudflare_r2_config() {
        let config = S3CacheConfig::cloudflare_r2("mybucket", "abc123accountid");
        assert_eq!(
            config.endpoint,
            Some("https://abc123accountid.r2.cloudflarestorage.com".to_string())
        );
        assert!(config.path_style);
    }

    #[test]
    fn test_backblaze_b2_config() {
        let config = S3CacheConfig::backblaze_b2("mybucket", "us-west-001");
        assert_eq!(
            config.endpoint,
            Some("https://s3.us-west-001.backblazeb2.com".to_string())
        );
    }
}