zlayer_registry/
cache_config.rs1use 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#[cfg(feature = "persistent")]
21const DEFAULT_CACHE_DB: &str = "blobs.sqlite";
22
23#[derive(Debug, Clone)]
25pub enum CacheType {
26 Memory,
28
29 #[cfg(feature = "persistent")]
31 Persistent {
32 path: PathBuf,
34 },
35
36 #[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 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 #[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 #[must_use]
179 pub fn memory() -> Self {
180 CacheType::Memory
181 }
182
183 #[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 #[cfg(feature = "persistent")]
196 pub fn persistent_at(path: impl Into<PathBuf>) -> Self {
197 CacheType::Persistent { path: path.into() }
198 }
199
200 #[cfg(feature = "s3")]
202 #[must_use]
203 pub fn s3(config: S3CacheConfig) -> Self {
204 CacheType::S3(config)
205 }
206
207 #[must_use]
209 pub fn is_memory(&self) -> bool {
210 matches!(self, CacheType::Memory)
211 }
212
213 #[cfg(feature = "persistent")]
215 #[must_use]
216 pub fn is_persistent(&self) -> bool {
217 matches!(self, CacheType::Persistent { .. })
218 }
219
220 #[cfg(feature = "s3")]
222 #[must_use]
223 pub fn is_s3(&self) -> bool {
224 matches!(self, CacheType::S3(_))
225 }
226}
227
228#[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#[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#[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 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 struct EnvGuard;
310
311 impl EnvGuard {
312 fn new() -> Self {
313 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 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 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}