cvmfs 0.4.1

CernVM-FS client implementation in Rust
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//! # Local Cache Management for CernVM-FS
//!
//! This module provides functionality for managing the local cache of CernVM-FS objects.
//! The cache stores downloaded repository objects to improve performance and allow
//! offline access to previously accessed content.
//!
//! ## Cache Structure
//!
//! The cache follows a two-level directory structure:
//! - The main cache directory contains a `data` subdirectory
//! - Inside `data`, objects are organized into 256 subdirectories (00-ff) based on the first two
//!   hex characters of their content hash
//!
//! ## Cache Operations
//!
//! The cache supports the following operations:
//! - Initialization: Creating the directory structure
//! - Adding: Determining the path where a file should be stored
//! - Retrieval: Looking up files by their identifier
//! - Eviction: Clearing the cache and rebuilding the structure

use std::{
	collections::HashMap,
	fs::{create_dir_all, remove_dir_all},
	path::{Path, PathBuf},
	sync::Mutex,
	time::{Duration, Instant},
};

use crate::common::{CvmfsError, CvmfsResult};

const DEFAULT_TTL: Duration = Duration::from_secs(3600);
const DEFAULT_NEGATIVE_TTL: Duration = Duration::from_secs(5);
const DEFAULT_QUOTA: u64 = 4 * 1024 * 1024 * 1024; // 4 GB

/// A cache for storing repository objects locally
///
/// The `Cache` struct manages a local directory structure where CernVM-FS objects
/// are stored. It provides methods for initialization, file lookup, and cache management.
#[derive(Debug)]
pub struct Cache {
	/// The root directory where cache files are stored.
	pub cache_directory: String,
	ttl: Duration,
	negative_ttl: Duration,
	negative_entries: Mutex<HashMap<String, Instant>>,
	quota: u64,
}

impl Cache {
	/// Creates a new cache instance with the specified root directory.
	///
	/// This constructor creates a new cache that will store files in the specified
	/// directory. It validates that the path can be properly represented as a string.
	///
	/// # Arguments
	///
	/// * `cache_directory` - The path to the root cache directory.
	///
	/// # Returns
	///
	/// Returns a `CvmfsResult<Self>` containing the new cache instance, or an error
	/// if the path is invalid.
	///
	/// # Errors
	///
	/// Returns `CvmfsError::FileNotFound` if the path cannot be converted to a string.
	pub fn new(cache_directory: String) -> CvmfsResult<Self> {
		let path = Path::new(&cache_directory);
		Ok(Self {
			cache_directory: path.to_str().ok_or(CvmfsError::FileNotFound)?.into(),
			ttl: DEFAULT_TTL,
			negative_ttl: DEFAULT_NEGATIVE_TTL,
			negative_entries: Mutex::new(HashMap::new()),
			quota: DEFAULT_QUOTA,
		})
	}

	pub fn with_ttl(mut self, ttl: Duration, negative_ttl: Duration) -> Self {
		self.ttl = ttl;
		self.negative_ttl = negative_ttl;
		self
	}

	pub fn with_quota(mut self, quota_bytes: u64) -> Self {
		self.quota = quota_bytes;
		self
	}

	/// Initializes the cache directory structure.
	///
	/// This method creates the cache directory structure if it doesn't exist. It creates
	/// a `data` subdirectory with 256 subdirectories (00-ff) to store objects based on
	/// the first two hex characters of their hash.
	///
	/// # Returns
	///
	/// Returns `Ok(())` if initialization is successful, or an error if directory
	/// creation fails.
	///
	/// # Errors
	///
	/// Returns filesystem errors if directory creation fails, or path conversion errors.
	pub fn initialize(&self) -> CvmfsResult<()> {
		let base_path = self.create_directory("data")?;
		for i in 0x00..=0xff {
			let new_folder = format!("{:02x}", i);
			let new_file = Path::join::<&Path>(base_path.as_ref(), new_folder.as_ref());
			create_dir_all(new_file)?;
		}
		Ok(())
	}

	/// Creates a directory within the cache root
	///
	/// This helper method creates a directory at the specified path relative to the
	/// cache root directory, ensuring all parent directories are created as needed.
	///
	/// # Arguments
	///
	/// * `path` - The relative path to create within the cache directory
	///
	/// # Returns
	///
	/// Returns a `CvmfsResult<String>` containing the full path to the created directory,
	/// or an error if directory creation or path conversion fails.
	///
	/// # Errors
	///
	/// Returns filesystem errors if directory creation fails, or `CvmfsError::FileNotFound`
	/// if the path cannot be converted to a string.
	fn create_directory(&self, path: &str) -> CvmfsResult<String> {
		let cache_full_path = Path::new(&self.cache_directory).join(path);
		create_dir_all(cache_full_path.clone())?;
		cache_full_path
			.into_os_string()
			.into_string()
			.map_err(|_| CvmfsError::FileNotFound)
	}

	/// Gets the path where a file would be stored in the cache
	///
	/// This method determines the full path where a file with the given name would
	/// be stored in the cache, without checking if it actually exists.
	///
	/// # Arguments
	///
	/// * `file_name` - The name of the file
	///
	/// # Returns
	///
	/// Returns a `PathBuf` with the full path where the file would be stored.
	pub fn add(&self, file_name: &str) -> CvmfsResult<PathBuf> {
		if file_name.contains("..") || file_name.starts_with('/') {
			return Err(CvmfsError::IO("invalid cache filename".to_string()));
		}
		let path = Path::join(self.cache_directory.as_ref(), file_name);
		Ok(path)
	}

	/// Retrieves the path to a file if it exists in the cache
	///
	/// This method checks if a file with the given name exists in the cache and
	/// returns its path if found.
	///
	/// # Arguments
	///
	/// * `file_name` - The name of the file to look up
	///
	/// # Returns
	///
	/// Returns an `Option<PathBuf>` containing the path to the file if it exists,
	/// or `None` if the file is not in the cache.
	pub fn get(&self, file_name: &str) -> Option<PathBuf> {
		if self.is_negative_cached(file_name) {
			return None;
		}
		let path = self.add(file_name).ok()?;
		if !path.is_file() {
			return None;
		}
		let is_data_object = file_name.starts_with("data/");
		if !is_data_object && self.is_expired(&path) {
			std::fs::remove_file(&path).ok();
			return None;
		}
		Some(path)
	}

	pub fn record_negative(&self, file_name: &str) {
		if let Ok(mut entries) = self.negative_entries.lock() {
			entries.insert(file_name.to_string(), Instant::now());
		}
	}

	fn is_negative_cached(&self, file_name: &str) -> bool {
		let Ok(mut entries) = self.negative_entries.lock() else {
			return false;
		};
		let Some(inserted) = entries.get(file_name) else {
			return false;
		};
		if inserted.elapsed() < self.negative_ttl {
			return true;
		}
		entries.remove(file_name);
		false
	}

	fn is_expired(&self, path: &Path) -> bool {
		path.metadata()
			.and_then(|m| m.modified())
			.map(|modified| modified.elapsed().unwrap_or_default() > self.ttl)
			.unwrap_or(true)
	}

	/// Clears the cache and re-initializes the directory structure.
	///
	/// This method removes all cached objects by deleting and recreating the data
	/// directory structure. It's useful for clearing corrupted cache data or freeing
	/// disk space.
	///
	/// # Returns
	///
	/// Returns `Ok(())` if eviction is successful, or an error if directory removal
	/// or reinitialization fails.
	///
	/// # Errors
	///
	/// Returns filesystem errors if directory operations fail.
	pub fn evict(&self) -> CvmfsResult<()> {
		let data_path = Path::new(&self.cache_directory).join("data");
		if data_path.exists() && data_path.is_dir() {
			remove_dir_all(data_path)?;
			self.initialize()?;
		}
		if let Ok(mut entries) = self.negative_entries.lock() {
			entries.clear();
		}
		Ok(())
	}

	pub fn cache_size(&self) -> u64 {
		let data_path = Path::new(&self.cache_directory).join("data");
		Self::dir_size(&data_path)
	}

	pub fn enforce_quota(&self) -> CvmfsResult<()> {
		let current = self.cache_size();
		if current <= self.quota {
			return Ok(());
		}
		let data_path = Path::new(&self.cache_directory).join("data");
		let mut files = Self::collect_files_by_atime(&data_path);
		files.sort_by_key(|(_, atime)| *atime);
		let mut freed = 0u64;
		let target = current - self.quota;
		for (path, _) in &files {
			if freed >= target {
				break;
			}
			if let Ok(meta) = path.metadata() {
				freed += meta.len();
				std::fs::remove_file(path).ok();
			}
		}
		Ok(())
	}

	fn dir_size(path: &Path) -> u64 {
		let mut total = 0;
		if let Ok(entries) = std::fs::read_dir(path) {
			for entry in entries.flatten() {
				let p = entry.path();
				if p.is_dir() {
					total += Self::dir_size(&p);
				} else if let Ok(meta) = p.metadata() {
					total += meta.len();
				}
			}
		}
		total
	}

	fn collect_files_by_atime(path: &Path) -> Vec<(PathBuf, std::time::SystemTime)> {
		let mut files = Vec::new();
		if let Ok(entries) = std::fs::read_dir(path) {
			for entry in entries.flatten() {
				let p = entry.path();
				if p.is_dir() {
					files.extend(Self::collect_files_by_atime(&p));
				} else if let Ok(meta) = p.metadata() {
					let atime = meta
						.accessed()
						.or_else(|_| meta.modified())
						.unwrap_or(std::time::UNIX_EPOCH);
					files.push((p, atime));
				}
			}
		}
		files
	}
}

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

	fn tmp_cache_dir(name: &str) -> PathBuf {
		std::env::temp_dir().join(format!("cvmfs_cache_{}_{}", name, std::process::id()))
	}

	#[test]
	fn cache_new_valid_path() {
		let dir = tmp_cache_dir("new");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into()).unwrap();
		assert_eq!(cache.cache_directory, dir.to_str().unwrap());
		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn cache_initialize_creates_data_subdirs() {
		let dir = tmp_cache_dir("init");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into()).unwrap();
		cache.initialize().unwrap();

		let data_dir = dir.join("data");
		assert!(data_dir.is_dir());

		// Spot-check a few subdirectories
		assert!(data_dir.join("00").is_dir());
		assert!(data_dir.join("0a").is_dir());
		assert!(data_dir.join("ff").is_dir());
		assert!(data_dir.join("7f").is_dir());

		// Count: should be exactly 256
		let count = fs::read_dir(&data_dir).unwrap().count();
		assert_eq!(count, 256);

		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn cache_add_normal_filename() {
		let dir = tmp_cache_dir("add");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into()).unwrap();

		let result = cache.add("data/ab/cdef1234").unwrap();
		assert_eq!(result, dir.join("data/ab/cdef1234"));

		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn cache_add_path_traversal_rejected() {
		let dir = tmp_cache_dir("traversal");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into()).unwrap();

		let result = cache.add("../etc/passwd");
		assert!(result.is_err());

		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn cache_add_absolute_path_rejected() {
		let dir = tmp_cache_dir("absolute");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into()).unwrap();

		let result = cache.add("/etc/passwd");
		assert!(result.is_err());

		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn cache_get_missing_file_returns_none() {
		let dir = tmp_cache_dir("get_miss");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into()).unwrap();
		cache.initialize().unwrap();

		assert!(cache.get("data/ab/nonexistent").is_none());

		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn cache_get_existing_file_returns_some() {
		let dir = tmp_cache_dir("get_hit");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into()).unwrap();
		cache.initialize().unwrap();

		// Write a file into the cache
		let file_path = dir.join("data/ab/testfile");
		fs::write(&file_path, b"content").unwrap();

		let result = cache.get("data/ab/testfile");
		assert!(result.is_some());
		assert_eq!(result.unwrap(), file_path);

		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn cache_negative_entry_blocks_lookup() {
		let dir = tmp_cache_dir("neg");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into()).unwrap();
		cache.initialize().unwrap();

		cache.record_negative("data/ab/missing");
		assert!(cache.get("data/ab/missing").is_none());

		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn cache_negative_entry_expires() {
		let dir = tmp_cache_dir("neg_expire");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into())
			.unwrap()
			.with_ttl(Duration::from_secs(60), Duration::from_millis(1));
		cache.initialize().unwrap();

		cache.record_negative("data/ab/willexpire");
		std::thread::sleep(Duration::from_millis(5));

		let file_path = dir.join("data/ab/willexpire");
		fs::write(&file_path, b"data").unwrap();
		assert!(cache.get("data/ab/willexpire").is_some());

		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn cache_ttl_expired_metadata_not_returned() {
		let dir = tmp_cache_dir("ttl_exp");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into())
			.unwrap()
			.with_ttl(Duration::from_millis(1), Duration::from_secs(5));
		cache.initialize().unwrap();

		let file_path = dir.join(".cvmfspublished");
		fs::write(&file_path, b"old metadata").unwrap();
		std::thread::sleep(Duration::from_millis(5));

		assert!(cache.get(".cvmfspublished").is_none());
		assert!(!file_path.exists());

		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn cache_data_objects_never_expire() {
		let dir = tmp_cache_dir("data_no_exp");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into())
			.unwrap()
			.with_ttl(Duration::from_millis(1), Duration::from_secs(5));
		cache.initialize().unwrap();

		let file_path = dir.join("data/ab/deadbeef1234");
		fs::write(&file_path, b"content-addressed data").unwrap();
		std::thread::sleep(Duration::from_millis(5));

		assert!(cache.get("data/ab/deadbeef1234").is_some());
		assert!(file_path.exists());

		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn cache_evict_clears_negative_entries() {
		let dir = tmp_cache_dir("evict_neg");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into()).unwrap();
		cache.initialize().unwrap();

		cache.record_negative("data/ab/neg");
		cache.evict().unwrap();

		let file_path = dir.join("data/ab/neg");
		fs::write(&file_path, b"data").unwrap();
		assert!(cache.get("data/ab/neg").is_some());

		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn cache_with_quota_builder() {
		let dir = tmp_cache_dir("quota_builder");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into()).unwrap().with_quota(1024);
		assert_eq!(cache.quota, 1024);
		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn cache_with_ttl_builder() {
		let dir = tmp_cache_dir("ttl_builder");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into())
			.unwrap()
			.with_ttl(Duration::from_secs(120), Duration::from_secs(10));
		assert_eq!(cache.ttl, Duration::from_secs(120));
		assert_eq!(cache.negative_ttl, Duration::from_secs(10));
		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn cache_size_empty() {
		let dir = tmp_cache_dir("size_empty");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into()).unwrap();
		cache.initialize().unwrap();
		assert_eq!(cache.cache_size(), 0);
		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn cache_size_with_files() {
		let dir = tmp_cache_dir("size_files");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into()).unwrap();
		cache.initialize().unwrap();

		fs::write(dir.join("data/ab/file1"), vec![0u8; 100]).unwrap();
		fs::write(dir.join("data/cd/file2"), vec![0u8; 200]).unwrap();
		assert_eq!(cache.cache_size(), 300);
		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn enforce_quota_under_limit_noop() {
		let dir = tmp_cache_dir("quota_under");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into()).unwrap().with_quota(10_000);
		cache.initialize().unwrap();

		fs::write(dir.join("data/ab/file1"), vec![0u8; 100]).unwrap();
		cache.enforce_quota().unwrap();
		assert!(dir.join("data/ab/file1").exists());
		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn enforce_quota_over_limit_evicts() {
		let dir = tmp_cache_dir("quota_over");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into()).unwrap().with_quota(100);
		cache.initialize().unwrap();

		fs::write(dir.join("data/ab/file1"), vec![0u8; 200]).unwrap();
		fs::write(dir.join("data/cd/file2"), vec![0u8; 200]).unwrap();
		let size_before = cache.cache_size();
		assert!(size_before > 100);

		cache.enforce_quota().unwrap();
		let size_after = cache.cache_size();
		assert!(size_after <= 100);
		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn collect_files_by_atime_finds_files() {
		let dir = tmp_cache_dir("collect");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into()).unwrap();
		cache.initialize().unwrap();

		fs::write(dir.join("data/ab/f1"), b"a").unwrap();
		fs::write(dir.join("data/cd/f2"), b"bb").unwrap();

		let data_path = dir.join("data");
		let files = Cache::collect_files_by_atime(&data_path);
		assert_eq!(files.len(), 2);
		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn dir_size_empty_dir() {
		let dir = tmp_cache_dir("dir_size_empty");
		fs::create_dir_all(&dir).unwrap();
		assert_eq!(Cache::dir_size(&dir), 0);
		fs::remove_dir_all(&dir).ok();
	}

	#[test]
	fn dir_size_nonexistent() {
		let dir = PathBuf::from("/tmp/cvmfs_nonexistent_dir_size_test");
		assert_eq!(Cache::dir_size(&dir), 0);
	}

	#[test]
	fn cache_evict_clears_and_recreates() {
		let dir = tmp_cache_dir("evict");
		fs::create_dir_all(&dir).unwrap();
		let cache = Cache::new(dir.to_str().unwrap().into()).unwrap();
		cache.initialize().unwrap();

		// Put a file in the cache
		let file_path = dir.join("data/ab/toevict");
		fs::write(&file_path, b"data").unwrap();
		assert!(file_path.is_file());

		cache.evict().unwrap();

		// File should be gone
		assert!(!file_path.is_file());
		// data/ directory should still exist (re-initialized)
		assert!(dir.join("data").is_dir());
		// Subdirectories should be recreated
		assert!(dir.join("data/ab").is_dir());

		fs::remove_dir_all(&dir).ok();
	}
}