Skip to main content

zlayer_registry/
cache_config.rs

1//! Unified cache configuration system
2//!
3//! This module provides a unified way to configure and instantiate cache backends
4//! from environment variables or programmatic configuration.
5
6use crate::cache::{BlobCache, BlobCacheBackend};
7use crate::error::CacheError;
8use std::sync::Arc;
9
10#[cfg(feature = "persistent")]
11use std::path::PathBuf;
12
13#[cfg(feature = "persistent")]
14use crate::persistent_cache::PersistentBlobCache;
15
16#[cfg(feature = "s3")]
17use crate::s3_cache::{S3BlobCache, S3CacheConfig};
18
19/// Default cache database filename
20#[cfg(feature = "persistent")]
21const DEFAULT_CACHE_DB: &str = "blobs.sqlite";
22
23/// Cache type configuration
24#[derive(Debug, Clone)]
25pub enum CacheType {
26    /// In-memory cache (non-persistent, cleared on restart)
27    Memory,
28
29    /// Persistent disk-based cache using `SQLite`
30    #[cfg(feature = "persistent")]
31    Persistent {
32        /// Path to the cache database file
33        path: PathBuf,
34    },
35
36    /// S3-compatible storage backend
37    #[cfg(feature = "s3")]
38    S3(S3CacheConfig),
39}
40
41#[allow(clippy::derivable_impls)]
42impl Default for CacheType {
43    fn default() -> Self {
44        #[cfg(feature = "persistent")]
45        {
46            CacheType::Persistent {
47                path: zlayer_paths::ZLayerDirs::system_default()
48                    .cache()
49                    .join(DEFAULT_CACHE_DB),
50            }
51        }
52        #[cfg(not(feature = "persistent"))]
53        {
54            CacheType::Memory
55        }
56    }
57}
58
59impl CacheType {
60    /// Create cache configuration from environment variables
61    ///
62    /// # Environment Variables
63    ///
64    /// - `ZLAYER_CACHE_TYPE`: Cache type - "memory", "persistent", or "s3" (default: "persistent")
65    /// - `ZLAYER_CACHE_DIR`: Path for persistent cache directory (default: platform-specific, see `zlayer_paths`)
66    /// - `ZLAYER_S3_BUCKET`: S3 bucket name (required for s3 type)
67    /// - `ZLAYER_S3_REGION`: AWS region (optional)
68    /// - `ZLAYER_S3_ENDPOINT`: Custom S3 endpoint for S3-compatible services
69    /// - `ZLAYER_S3_PREFIX`: Key prefix for blobs (default: "zlayer/blobs/")
70    /// - `ZLAYER_S3_PATH_STYLE`: Set to "true" to use path-style URLs
71    ///
72    /// # Errors
73    ///
74    /// Returns `CacheError` if:
75    /// - `ZLAYER_CACHE_TYPE` is "s3" but `ZLAYER_S3_BUCKET` is not set
76    /// - `ZLAYER_CACHE_TYPE` is an unknown value
77    pub fn from_env() -> Result<Self, CacheError> {
78        let cache_type = std::env::var("ZLAYER_CACHE_TYPE")
79            .unwrap_or_else(|_| "persistent".to_string())
80            .to_lowercase();
81
82        match cache_type.as_str() {
83            "memory" => Ok(CacheType::Memory),
84
85            "persistent" => {
86                #[cfg(feature = "persistent")]
87                {
88                    let default_cache_dir = zlayer_paths::ZLayerDirs::system_default()
89                        .cache()
90                        .to_string_lossy()
91                        .into_owned();
92                    let cache_dir = std::env::var("ZLAYER_CACHE_DIR").unwrap_or(default_cache_dir);
93                    let path = PathBuf::from(cache_dir).join(DEFAULT_CACHE_DB);
94                    Ok(CacheType::Persistent { path })
95                }
96                #[cfg(not(feature = "persistent"))]
97                {
98                    Err(CacheError::Database(
99                        "persistent cache requires the 'persistent' feature".to_string(),
100                    ))
101                }
102            }
103
104            "s3" => {
105                #[cfg(feature = "s3")]
106                {
107                    let bucket = std::env::var("ZLAYER_S3_BUCKET").map_err(|_| {
108                        CacheError::Database(
109                            "ZLAYER_S3_BUCKET environment variable is required for S3 cache"
110                                .to_string(),
111                        )
112                    })?;
113
114                    let mut config = S3CacheConfig::new(bucket);
115
116                    if let Ok(region) = std::env::var("ZLAYER_S3_REGION") {
117                        config = config.with_region(region);
118                    }
119
120                    if let Ok(endpoint) = std::env::var("ZLAYER_S3_ENDPOINT") {
121                        config = config.with_endpoint(endpoint);
122                    }
123
124                    if let Ok(prefix) = std::env::var("ZLAYER_S3_PREFIX") {
125                        config = config.with_prefix(prefix);
126                    }
127
128                    if let Ok(path_style) = std::env::var("ZLAYER_S3_PATH_STYLE") {
129                        if path_style.to_lowercase() == "true" || path_style == "1" {
130                            config = config.with_path_style();
131                        }
132                    }
133
134                    Ok(CacheType::S3(config))
135                }
136                #[cfg(not(feature = "s3"))]
137                {
138                    Err(CacheError::Database(
139                        "S3 cache requires the 's3' feature".to_string(),
140                    ))
141                }
142            }
143
144            unknown => Err(CacheError::Database(format!(
145                "unknown cache type '{unknown}', expected 'memory', 'persistent', or 's3'"
146            ))),
147        }
148    }
149
150    /// Build a cache backend from this configuration
151    ///
152    /// # Errors
153    ///
154    /// Returns `CacheError` if the cache backend fails to initialize
155    #[allow(clippy::unused_async)]
156    pub async fn build(&self) -> Result<Arc<Box<dyn BlobCacheBackend>>, CacheError> {
157        match self {
158            CacheType::Memory => {
159                let cache = BlobCache::new()?;
160                Ok(Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>))
161            }
162
163            #[cfg(feature = "persistent")]
164            CacheType::Persistent { path } => {
165                let cache = PersistentBlobCache::open(path).await?;
166                Ok(Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>))
167            }
168
169            #[cfg(feature = "s3")]
170            CacheType::S3(config) => {
171                let cache = S3BlobCache::new(config.clone()).await?;
172                Ok(Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>))
173            }
174        }
175    }
176
177    /// Create a memory cache configuration
178    #[must_use]
179    pub fn memory() -> Self {
180        CacheType::Memory
181    }
182
183    /// Create a persistent cache configuration with default path
184    #[cfg(feature = "persistent")]
185    #[must_use]
186    pub fn persistent() -> Self {
187        CacheType::Persistent {
188            path: zlayer_paths::ZLayerDirs::system_default()
189                .cache()
190                .join(DEFAULT_CACHE_DB),
191        }
192    }
193
194    /// Create a persistent cache configuration with custom path
195    #[cfg(feature = "persistent")]
196    pub fn persistent_at(path: impl Into<PathBuf>) -> Self {
197        CacheType::Persistent { path: path.into() }
198    }
199
200    /// Create an S3 cache configuration
201    #[cfg(feature = "s3")]
202    #[must_use]
203    pub fn s3(config: S3CacheConfig) -> Self {
204        CacheType::S3(config)
205    }
206
207    /// Check if this is a memory cache
208    #[must_use]
209    pub fn is_memory(&self) -> bool {
210        matches!(self, CacheType::Memory)
211    }
212
213    /// Check if this is a persistent cache
214    #[cfg(feature = "persistent")]
215    #[must_use]
216    pub fn is_persistent(&self) -> bool {
217        matches!(self, CacheType::Persistent { .. })
218    }
219
220    /// Check if this is an S3 cache
221    #[cfg(feature = "s3")]
222    #[must_use]
223    pub fn is_s3(&self) -> bool {
224        matches!(self, CacheType::S3(_))
225    }
226}
227
228/// Build an S3 blob-cache backend from the environment to use as the SHARED
229/// write-through tier behind a fast local cache (see
230/// [`crate::ImagePuller::with_s3_cache`]). Returns `Ok(None)` when no S3 bucket
231/// is configured (`ZLAYER_S3_BUCKET` unset) — distinct from `CacheType::from_env`,
232/// which only yields S3 when `ZLAYER_CACHE_TYPE=s3` and makes it the *primary*
233/// cache. Honors the same `ZLAYER_S3_*` variables as `from_env`.
234///
235/// # Errors
236///
237/// Returns `CacheError` if a bucket is configured but the backend fails to init.
238#[cfg(feature = "s3")]
239pub async fn s3_cache_from_env() -> Result<Option<Arc<Box<dyn BlobCacheBackend>>>, CacheError> {
240    let Ok(bucket) = std::env::var("ZLAYER_S3_BUCKET") else {
241        return Ok(None);
242    };
243    if bucket.trim().is_empty() {
244        return Ok(None);
245    }
246    let mut config = S3CacheConfig::new(bucket);
247    if let Ok(region) = std::env::var("ZLAYER_S3_REGION") {
248        config = config.with_region(region);
249    }
250    if let Ok(endpoint) = std::env::var("ZLAYER_S3_ENDPOINT") {
251        config = config.with_endpoint(endpoint);
252    }
253    if let Ok(prefix) = std::env::var("ZLAYER_S3_PREFIX") {
254        config = config.with_prefix(prefix);
255    }
256    if let Ok(path_style) = std::env::var("ZLAYER_S3_PATH_STYLE") {
257        if path_style.to_lowercase() == "true" || path_style == "1" {
258            config = config.with_path_style();
259        }
260    }
261    let cache = S3BlobCache::new(config).await?;
262    Ok(Some(Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>)))
263}
264
265/// No-op when the `s3` feature is disabled: there is no S3 tier to build.
266///
267/// # Errors
268///
269/// Never errors in this build; the signature mirrors the `s3`-enabled variant
270/// so callers need no `cfg` gating.
271#[cfg(not(feature = "s3"))]
272#[allow(clippy::unused_async)]
273pub async fn s3_cache_from_env() -> Result<Option<Arc<Box<dyn BlobCacheBackend>>>, CacheError> {
274    Ok(None)
275}
276
277/// The last-resort default registry host for bare/unqualified image names,
278/// from `ZLAYER_DEFAULT_REGISTRY` (e.g. `docker.io`, `registry.example.com`).
279///
280/// Returns `None` when unset/empty — in which case a bare name found nowhere in
281/// the resolution chain is an error, NOT a silent docker.io pull. `ZLayer` never
282/// invents a default; the operator opts in explicitly.
283#[must_use]
284pub fn default_registry_from_env() -> Option<String> {
285    std::env::var("ZLAYER_DEFAULT_REGISTRY")
286        .ok()
287        .map(|s| s.trim().to_string())
288        .filter(|s| !s.is_empty())
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294    use serial_test::serial;
295    use std::env;
296    #[cfg(feature = "persistent")]
297    use zlayer_paths::ZLayerDirs;
298
299    /// Environment variable names used by cache configuration
300    const ENV_CACHE_TYPE: &str = "ZLAYER_CACHE_TYPE";
301    const ENV_CACHE_DIR: &str = "ZLAYER_CACHE_DIR";
302    const ENV_S3_BUCKET: &str = "ZLAYER_S3_BUCKET";
303    const ENV_S3_REGION: &str = "ZLAYER_S3_REGION";
304    const ENV_S3_ENDPOINT: &str = "ZLAYER_S3_ENDPOINT";
305    const ENV_S3_PREFIX: &str = "ZLAYER_S3_PREFIX";
306    const ENV_S3_PATH_STYLE: &str = "ZLAYER_S3_PATH_STYLE";
307
308    /// Guard that clears environment variables on drop to ensure test isolation.
309    struct EnvGuard;
310
311    impl EnvGuard {
312        fn new() -> Self {
313            // Clear any existing env vars at test start
314            Self::clear_all();
315            Self
316        }
317
318        fn clear_all() {
319            env::remove_var(ENV_CACHE_TYPE);
320            env::remove_var(ENV_CACHE_DIR);
321            env::remove_var(ENV_S3_BUCKET);
322            env::remove_var(ENV_S3_REGION);
323            env::remove_var(ENV_S3_ENDPOINT);
324            env::remove_var(ENV_S3_PREFIX);
325            env::remove_var(ENV_S3_PATH_STYLE);
326        }
327    }
328
329    impl Drop for EnvGuard {
330        fn drop(&mut self) {
331            Self::clear_all();
332        }
333    }
334
335    #[test]
336    fn test_default_cache_type() {
337        let cache = CacheType::default();
338
339        #[cfg(feature = "persistent")]
340        assert!(cache.is_persistent());
341
342        #[cfg(not(feature = "persistent"))]
343        assert!(cache.is_memory());
344    }
345
346    #[test]
347    fn test_memory_cache() {
348        let cache = CacheType::memory();
349        assert!(cache.is_memory());
350    }
351
352    #[cfg(feature = "persistent")]
353    #[test]
354    fn test_persistent_cache() {
355        let cache = CacheType::persistent();
356        assert!(cache.is_persistent());
357
358        let custom = CacheType::persistent_at("/tmp/test.sqlite");
359        if let CacheType::Persistent { path } = custom {
360            assert_eq!(path, PathBuf::from("/tmp/test.sqlite"));
361        } else {
362            panic!("expected Persistent variant");
363        }
364    }
365
366    #[cfg(feature = "s3")]
367    #[test]
368    fn test_s3_cache() {
369        let config = S3CacheConfig::new("test-bucket");
370        let cache = CacheType::s3(config);
371        assert!(cache.is_s3());
372    }
373
374    #[test]
375    #[serial]
376    fn test_from_env_memory() {
377        let _guard = EnvGuard::new();
378
379        env::set_var(ENV_CACHE_TYPE, "memory");
380
381        let cache = CacheType::from_env().unwrap();
382        assert!(cache.is_memory());
383    }
384
385    #[test]
386    #[serial]
387    fn test_from_env_unknown_type() {
388        let _guard = EnvGuard::new();
389
390        env::set_var(ENV_CACHE_TYPE, "invalid");
391
392        let result = CacheType::from_env();
393        assert!(result.is_err());
394    }
395
396    #[cfg(feature = "s3")]
397    #[test]
398    #[serial]
399    fn test_from_env_s3_missing_bucket() {
400        let _guard = EnvGuard::new();
401
402        env::set_var(ENV_CACHE_TYPE, "s3");
403
404        let result = CacheType::from_env();
405        assert!(result.is_err());
406    }
407
408    #[cfg(feature = "s3")]
409    #[test]
410    #[serial]
411    fn test_from_env_s3_with_all_options() {
412        let _guard = EnvGuard::new();
413
414        env::set_var(ENV_CACHE_TYPE, "s3");
415        env::set_var(ENV_S3_BUCKET, "my-bucket");
416        env::set_var(ENV_S3_REGION, "us-west-2");
417        env::set_var(ENV_S3_ENDPOINT, "https://s3.example.com");
418        env::set_var(ENV_S3_PREFIX, "custom/prefix/");
419        env::set_var(ENV_S3_PATH_STYLE, "true");
420
421        let cache = CacheType::from_env().unwrap();
422        if let CacheType::S3(config) = cache {
423            assert_eq!(config.bucket, "my-bucket");
424            assert_eq!(config.region, Some("us-west-2".to_string()));
425            assert_eq!(config.endpoint, Some("https://s3.example.com".to_string()));
426            assert_eq!(config.prefix, "custom/prefix/");
427            assert!(config.path_style);
428        } else {
429            panic!("expected S3 variant");
430        }
431    }
432
433    #[tokio::test]
434    async fn test_build_memory_cache() {
435        let cache_type = CacheType::memory();
436        let cache = cache_type.build().await.unwrap();
437
438        // Test basic operations
439        let test_data = b"test data for cache";
440        let digest = crate::cache::compute_digest(test_data);
441
442        cache.put(&digest, test_data).await.unwrap();
443        let retrieved = cache.get(&digest).await.unwrap();
444        assert_eq!(retrieved, Some(test_data.to_vec()));
445    }
446
447    #[cfg(feature = "persistent")]
448    #[tokio::test]
449    async fn test_build_persistent_cache() {
450        let temp_dir = ZLayerDirs::system_default()
451            .scratch_dir("test-build-persistent-cache-")
452            .unwrap();
453        let cache_path = temp_dir.path().join("test.sqlite");
454
455        let cache_type = CacheType::persistent_at(&cache_path);
456        let cache = cache_type.build().await.unwrap();
457
458        // Test basic operations
459        let test_data = b"persistent test data";
460        let digest = crate::cache::compute_digest(test_data);
461
462        cache.put(&digest, test_data).await.unwrap();
463        let retrieved = cache.get(&digest).await.unwrap();
464        assert_eq!(retrieved, Some(test_data.to_vec()));
465    }
466}