zlayer-registry 0.12.8

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
462
463
464
465
466
//! Unified cache configuration system
//!
//! This module provides a unified way to configure and instantiate cache backends
//! from environment variables or programmatic configuration.

use crate::cache::{BlobCache, BlobCacheBackend};
use crate::error::CacheError;
use std::sync::Arc;

#[cfg(feature = "persistent")]
use std::path::PathBuf;

#[cfg(feature = "persistent")]
use crate::persistent_cache::PersistentBlobCache;

#[cfg(feature = "s3")]
use crate::s3_cache::{S3BlobCache, S3CacheConfig};

/// Default cache database filename
#[cfg(feature = "persistent")]
const DEFAULT_CACHE_DB: &str = "blobs.sqlite";

/// Cache type configuration
#[derive(Debug, Clone)]
pub enum CacheType {
    /// In-memory cache (non-persistent, cleared on restart)
    Memory,

    /// Persistent disk-based cache using `SQLite`
    #[cfg(feature = "persistent")]
    Persistent {
        /// Path to the cache database file
        path: PathBuf,
    },

    /// S3-compatible storage backend
    #[cfg(feature = "s3")]
    S3(S3CacheConfig),
}

#[allow(clippy::derivable_impls)]
impl Default for CacheType {
    fn default() -> Self {
        #[cfg(feature = "persistent")]
        {
            CacheType::Persistent {
                path: zlayer_paths::ZLayerDirs::system_default()
                    .cache()
                    .join(DEFAULT_CACHE_DB),
            }
        }
        #[cfg(not(feature = "persistent"))]
        {
            CacheType::Memory
        }
    }
}

impl CacheType {
    /// Create cache configuration from environment variables
    ///
    /// # Environment Variables
    ///
    /// - `ZLAYER_CACHE_TYPE`: Cache type - "memory", "persistent", or "s3" (default: "persistent")
    /// - `ZLAYER_CACHE_DIR`: Path for persistent cache directory (default: platform-specific, see `zlayer_paths`)
    /// - `ZLAYER_S3_BUCKET`: S3 bucket name (required for s3 type)
    /// - `ZLAYER_S3_REGION`: AWS region (optional)
    /// - `ZLAYER_S3_ENDPOINT`: Custom S3 endpoint for S3-compatible services
    /// - `ZLAYER_S3_PREFIX`: Key prefix for blobs (default: "zlayer/blobs/")
    /// - `ZLAYER_S3_PATH_STYLE`: Set to "true" to use path-style URLs
    ///
    /// # Errors
    ///
    /// Returns `CacheError` if:
    /// - `ZLAYER_CACHE_TYPE` is "s3" but `ZLAYER_S3_BUCKET` is not set
    /// - `ZLAYER_CACHE_TYPE` is an unknown value
    pub fn from_env() -> Result<Self, CacheError> {
        let cache_type = std::env::var("ZLAYER_CACHE_TYPE")
            .unwrap_or_else(|_| "persistent".to_string())
            .to_lowercase();

        match cache_type.as_str() {
            "memory" => Ok(CacheType::Memory),

            "persistent" => {
                #[cfg(feature = "persistent")]
                {
                    let default_cache_dir = zlayer_paths::ZLayerDirs::system_default()
                        .cache()
                        .to_string_lossy()
                        .into_owned();
                    let cache_dir = std::env::var("ZLAYER_CACHE_DIR").unwrap_or(default_cache_dir);
                    let path = PathBuf::from(cache_dir).join(DEFAULT_CACHE_DB);
                    Ok(CacheType::Persistent { path })
                }
                #[cfg(not(feature = "persistent"))]
                {
                    Err(CacheError::Database(
                        "persistent cache requires the 'persistent' feature".to_string(),
                    ))
                }
            }

            "s3" => {
                #[cfg(feature = "s3")]
                {
                    let bucket = std::env::var("ZLAYER_S3_BUCKET").map_err(|_| {
                        CacheError::Database(
                            "ZLAYER_S3_BUCKET environment variable is required for S3 cache"
                                .to_string(),
                        )
                    })?;

                    let mut config = S3CacheConfig::new(bucket);

                    if let Ok(region) = std::env::var("ZLAYER_S3_REGION") {
                        config = config.with_region(region);
                    }

                    if let Ok(endpoint) = std::env::var("ZLAYER_S3_ENDPOINT") {
                        config = config.with_endpoint(endpoint);
                    }

                    if let Ok(prefix) = std::env::var("ZLAYER_S3_PREFIX") {
                        config = config.with_prefix(prefix);
                    }

                    if let Ok(path_style) = std::env::var("ZLAYER_S3_PATH_STYLE") {
                        if path_style.to_lowercase() == "true" || path_style == "1" {
                            config = config.with_path_style();
                        }
                    }

                    Ok(CacheType::S3(config))
                }
                #[cfg(not(feature = "s3"))]
                {
                    Err(CacheError::Database(
                        "S3 cache requires the 's3' feature".to_string(),
                    ))
                }
            }

            unknown => Err(CacheError::Database(format!(
                "unknown cache type '{unknown}', expected 'memory', 'persistent', or 's3'"
            ))),
        }
    }

    /// Build a cache backend from this configuration
    ///
    /// # Errors
    ///
    /// Returns `CacheError` if the cache backend fails to initialize
    #[allow(clippy::unused_async)]
    pub async fn build(&self) -> Result<Arc<Box<dyn BlobCacheBackend>>, CacheError> {
        match self {
            CacheType::Memory => {
                let cache = BlobCache::new()?;
                Ok(Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>))
            }

            #[cfg(feature = "persistent")]
            CacheType::Persistent { path } => {
                let cache = PersistentBlobCache::open(path).await?;
                Ok(Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>))
            }

            #[cfg(feature = "s3")]
            CacheType::S3(config) => {
                let cache = S3BlobCache::new(config.clone()).await?;
                Ok(Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>))
            }
        }
    }

    /// Create a memory cache configuration
    #[must_use]
    pub fn memory() -> Self {
        CacheType::Memory
    }

    /// Create a persistent cache configuration with default path
    #[cfg(feature = "persistent")]
    #[must_use]
    pub fn persistent() -> Self {
        CacheType::Persistent {
            path: zlayer_paths::ZLayerDirs::system_default()
                .cache()
                .join(DEFAULT_CACHE_DB),
        }
    }

    /// Create a persistent cache configuration with custom path
    #[cfg(feature = "persistent")]
    pub fn persistent_at(path: impl Into<PathBuf>) -> Self {
        CacheType::Persistent { path: path.into() }
    }

    /// Create an S3 cache configuration
    #[cfg(feature = "s3")]
    #[must_use]
    pub fn s3(config: S3CacheConfig) -> Self {
        CacheType::S3(config)
    }

    /// Check if this is a memory cache
    #[must_use]
    pub fn is_memory(&self) -> bool {
        matches!(self, CacheType::Memory)
    }

    /// Check if this is a persistent cache
    #[cfg(feature = "persistent")]
    #[must_use]
    pub fn is_persistent(&self) -> bool {
        matches!(self, CacheType::Persistent { .. })
    }

    /// Check if this is an S3 cache
    #[cfg(feature = "s3")]
    #[must_use]
    pub fn is_s3(&self) -> bool {
        matches!(self, CacheType::S3(_))
    }
}

/// Build an S3 blob-cache backend from the environment to use as the SHARED
/// write-through tier behind a fast local cache (see
/// [`crate::ImagePuller::with_s3_cache`]). Returns `Ok(None)` when no S3 bucket
/// is configured (`ZLAYER_S3_BUCKET` unset) — distinct from `CacheType::from_env`,
/// which only yields S3 when `ZLAYER_CACHE_TYPE=s3` and makes it the *primary*
/// cache. Honors the same `ZLAYER_S3_*` variables as `from_env`.
///
/// # Errors
///
/// Returns `CacheError` if a bucket is configured but the backend fails to init.
#[cfg(feature = "s3")]
pub async fn s3_cache_from_env() -> Result<Option<Arc<Box<dyn BlobCacheBackend>>>, CacheError> {
    let Ok(bucket) = std::env::var("ZLAYER_S3_BUCKET") else {
        return Ok(None);
    };
    if bucket.trim().is_empty() {
        return Ok(None);
    }
    let mut config = S3CacheConfig::new(bucket);
    if let Ok(region) = std::env::var("ZLAYER_S3_REGION") {
        config = config.with_region(region);
    }
    if let Ok(endpoint) = std::env::var("ZLAYER_S3_ENDPOINT") {
        config = config.with_endpoint(endpoint);
    }
    if let Ok(prefix) = std::env::var("ZLAYER_S3_PREFIX") {
        config = config.with_prefix(prefix);
    }
    if let Ok(path_style) = std::env::var("ZLAYER_S3_PATH_STYLE") {
        if path_style.to_lowercase() == "true" || path_style == "1" {
            config = config.with_path_style();
        }
    }
    let cache = S3BlobCache::new(config).await?;
    Ok(Some(Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>)))
}

/// No-op when the `s3` feature is disabled: there is no S3 tier to build.
///
/// # Errors
///
/// Never errors in this build; the signature mirrors the `s3`-enabled variant
/// so callers need no `cfg` gating.
#[cfg(not(feature = "s3"))]
#[allow(clippy::unused_async)]
pub async fn s3_cache_from_env() -> Result<Option<Arc<Box<dyn BlobCacheBackend>>>, CacheError> {
    Ok(None)
}

/// The last-resort default registry host for bare/unqualified image names,
/// from `ZLAYER_DEFAULT_REGISTRY` (e.g. `docker.io`, `registry.example.com`).
///
/// Returns `None` when unset/empty — in which case a bare name found nowhere in
/// the resolution chain is an error, NOT a silent docker.io pull. `ZLayer` never
/// invents a default; the operator opts in explicitly.
#[must_use]
pub fn default_registry_from_env() -> Option<String> {
    std::env::var("ZLAYER_DEFAULT_REGISTRY")
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

#[cfg(test)]
mod tests {
    use super::*;
    use serial_test::serial;
    use std::env;
    #[cfg(feature = "persistent")]
    use zlayer_paths::ZLayerDirs;

    /// Environment variable names used by cache configuration
    const ENV_CACHE_TYPE: &str = "ZLAYER_CACHE_TYPE";
    const ENV_CACHE_DIR: &str = "ZLAYER_CACHE_DIR";
    const ENV_S3_BUCKET: &str = "ZLAYER_S3_BUCKET";
    const ENV_S3_REGION: &str = "ZLAYER_S3_REGION";
    const ENV_S3_ENDPOINT: &str = "ZLAYER_S3_ENDPOINT";
    const ENV_S3_PREFIX: &str = "ZLAYER_S3_PREFIX";
    const ENV_S3_PATH_STYLE: &str = "ZLAYER_S3_PATH_STYLE";

    /// Guard that clears environment variables on drop to ensure test isolation.
    struct EnvGuard;

    impl EnvGuard {
        fn new() -> Self {
            // Clear any existing env vars at test start
            Self::clear_all();
            Self
        }

        fn clear_all() {
            env::remove_var(ENV_CACHE_TYPE);
            env::remove_var(ENV_CACHE_DIR);
            env::remove_var(ENV_S3_BUCKET);
            env::remove_var(ENV_S3_REGION);
            env::remove_var(ENV_S3_ENDPOINT);
            env::remove_var(ENV_S3_PREFIX);
            env::remove_var(ENV_S3_PATH_STYLE);
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            Self::clear_all();
        }
    }

    #[test]
    fn test_default_cache_type() {
        let cache = CacheType::default();

        #[cfg(feature = "persistent")]
        assert!(cache.is_persistent());

        #[cfg(not(feature = "persistent"))]
        assert!(cache.is_memory());
    }

    #[test]
    fn test_memory_cache() {
        let cache = CacheType::memory();
        assert!(cache.is_memory());
    }

    #[cfg(feature = "persistent")]
    #[test]
    fn test_persistent_cache() {
        let cache = CacheType::persistent();
        assert!(cache.is_persistent());

        let custom = CacheType::persistent_at("/tmp/test.sqlite");
        if let CacheType::Persistent { path } = custom {
            assert_eq!(path, PathBuf::from("/tmp/test.sqlite"));
        } else {
            panic!("expected Persistent variant");
        }
    }

    #[cfg(feature = "s3")]
    #[test]
    fn test_s3_cache() {
        let config = S3CacheConfig::new("test-bucket");
        let cache = CacheType::s3(config);
        assert!(cache.is_s3());
    }

    #[test]
    #[serial]
    fn test_from_env_memory() {
        let _guard = EnvGuard::new();

        env::set_var(ENV_CACHE_TYPE, "memory");

        let cache = CacheType::from_env().unwrap();
        assert!(cache.is_memory());
    }

    #[test]
    #[serial]
    fn test_from_env_unknown_type() {
        let _guard = EnvGuard::new();

        env::set_var(ENV_CACHE_TYPE, "invalid");

        let result = CacheType::from_env();
        assert!(result.is_err());
    }

    #[cfg(feature = "s3")]
    #[test]
    #[serial]
    fn test_from_env_s3_missing_bucket() {
        let _guard = EnvGuard::new();

        env::set_var(ENV_CACHE_TYPE, "s3");

        let result = CacheType::from_env();
        assert!(result.is_err());
    }

    #[cfg(feature = "s3")]
    #[test]
    #[serial]
    fn test_from_env_s3_with_all_options() {
        let _guard = EnvGuard::new();

        env::set_var(ENV_CACHE_TYPE, "s3");
        env::set_var(ENV_S3_BUCKET, "my-bucket");
        env::set_var(ENV_S3_REGION, "us-west-2");
        env::set_var(ENV_S3_ENDPOINT, "https://s3.example.com");
        env::set_var(ENV_S3_PREFIX, "custom/prefix/");
        env::set_var(ENV_S3_PATH_STYLE, "true");

        let cache = CacheType::from_env().unwrap();
        if let CacheType::S3(config) = cache {
            assert_eq!(config.bucket, "my-bucket");
            assert_eq!(config.region, Some("us-west-2".to_string()));
            assert_eq!(config.endpoint, Some("https://s3.example.com".to_string()));
            assert_eq!(config.prefix, "custom/prefix/");
            assert!(config.path_style);
        } else {
            panic!("expected S3 variant");
        }
    }

    #[tokio::test]
    async fn test_build_memory_cache() {
        let cache_type = CacheType::memory();
        let cache = cache_type.build().await.unwrap();

        // Test basic operations
        let test_data = b"test data for cache";
        let digest = crate::cache::compute_digest(test_data);

        cache.put(&digest, test_data).await.unwrap();
        let retrieved = cache.get(&digest).await.unwrap();
        assert_eq!(retrieved, Some(test_data.to_vec()));
    }

    #[cfg(feature = "persistent")]
    #[tokio::test]
    async fn test_build_persistent_cache() {
        let temp_dir = ZLayerDirs::system_default()
            .scratch_dir("test-build-persistent-cache-")
            .unwrap();
        let cache_path = temp_dir.path().join("test.sqlite");

        let cache_type = CacheType::persistent_at(&cache_path);
        let cache = cache_type.build().await.unwrap();

        // Test basic operations
        let test_data = b"persistent test data";
        let digest = crate::cache::compute_digest(test_data);

        cache.put(&digest, test_data).await.unwrap();
        let retrieved = cache.get(&digest).await.unwrap();
        assert_eq!(retrieved, Some(test_data.to_vec()));
    }
}