agpm_cli/cache/
lock.rs

1//! File locking utilities for cache operations.
2//!
3//! This module provides thread-safe and process-safe file locking for cache directories
4//! to prevent corruption during concurrent cache operations. The locks are automatically
5//! released when the lock object is dropped.
6
7use anyhow::{Context, Result};
8use fs4::fs_std::FileExt;
9use std::fs::{File, OpenOptions};
10use std::path::Path;
11
12/// A file lock for cache operations
13pub struct CacheLock {
14    _file: File,
15}
16
17impl CacheLock {
18    /// Acquires an exclusive lock for a specific source in the cache directory.
19    ///
20    /// This async method creates and acquires an exclusive file lock for the specified
21    /// source name. The file locking operation uses `spawn_blocking` internally to avoid
22    /// blocking the tokio runtime, while still providing blocking file lock semantics.
23    ///
24    /// # Lock File Management
25    ///
26    /// The method performs several setup operations:
27    /// 1. **Locks directory creation**: Creates `.locks/` directory if needed
28    /// 2. **Lock file creation**: Creates `{source_name}.lock` file
29    /// 3. **Exclusive locking**: Acquires exclusive access via OS file locking
30    /// 4. **Handle retention**: Keeps file handle open to maintain lock
31    ///
32    /// # Async and Blocking Behavior
33    ///
34    /// If another process already holds a lock for the same source:
35    /// - **Async-friendly**: Uses `spawn_blocking` to avoid blocking the tokio runtime
36    /// - **Blocking wait**: The spawned task blocks until other lock is released
37    /// - **Fair queuing**: Locks are typically acquired in FIFO order
38    /// - **No timeout**: Task will wait indefinitely (use with caution)
39    /// - **Interruptible**: Can be interrupted by process signals
40    ///
41    /// # Lock File Location
42    ///
43    /// Lock files are created in a dedicated subdirectory:
44    /// ```text
45    /// {cache_dir}/.locks/{source_name}.lock
46    /// ```
47    ///
48    /// Examples:
49    /// - `~/.agpm/cache/.locks/community.lock`
50    /// - `~/.agpm/cache/.locks/work-tools.lock`
51    /// - `~/.agpm/cache/.locks/my-project.lock`
52    ///
53    /// # Parameters
54    ///
55    /// * `cache_dir` - Root cache directory path
56    /// * `source_name` - Unique identifier for the source being locked
57    ///
58    /// # Returns
59    ///
60    /// Returns a `CacheLock` instance that holds the exclusive lock. The lock
61    /// remains active until the returned instance is dropped.
62    ///
63    /// # Errors
64    ///
65    /// The method can fail for several reasons:
66    ///
67    /// ## Directory Creation Errors
68    /// - Permission denied creating `.locks/` directory
69    /// - Disk space exhausted
70    /// - Path length exceeds system limits
71    ///
72    /// ## File Operation Errors
73    /// - Permission denied creating/opening lock file
74    /// - File system full
75    /// - Invalid characters in source name
76    ///
77    /// ## Locking Errors
78    /// - File locking not supported by file system
79    /// - Lock file corrupted or in invalid state
80    /// - System resource limits exceeded
81    ///
82    /// # Platform Considerations
83    ///
84    /// - **Windows**: Uses Win32 `LockFile` API via [`fs4`]
85    /// - **Unix**: Uses POSIX `fcntl()` locking via [`fs4`]
86    /// - **NFS/Network**: Behavior depends on file system support
87    /// - **Docker**: Works within containers with proper volume mounts
88    ///
89    /// # Examples
90    ///
91    /// Simple lock acquisition:
92    ///
93    /// ```rust,no_run
94    /// use agpm_cli::cache::lock::CacheLock;
95    /// use std::path::PathBuf;
96    ///
97    /// # async fn example() -> anyhow::Result<()> {
98    /// let cache_dir = PathBuf::from("/home/user/.agpm/cache");
99    ///
100    /// // This will block if another process has the lock
101    /// let lock = CacheLock::acquire(&cache_dir, "my-source").await?;
102    ///
103    /// // Perform cache operations safely...
104    /// println!("Lock acquired successfully!");
105    ///
106    /// // Lock is released when 'lock' variable is dropped
107    /// drop(lock);
108    /// # Ok(())
109    /// # }
110    /// ```
111    pub async fn acquire(cache_dir: &Path, source_name: &str) -> Result<Self> {
112        use tokio::fs;
113        use tokio::task::spawn_blocking;
114
115        // Create locks directory if it doesn't exist
116        let locks_dir = cache_dir.join(".locks");
117        fs::create_dir_all(&locks_dir).await.with_context(|| {
118            format!("Failed to create locks directory: {}", locks_dir.display())
119        })?;
120
121        // Create lock file path
122        let lock_path = locks_dir.join(format!("{source_name}.lock"));
123
124        // Open/create lock file
125        let file = spawn_blocking(move || -> Result<File> {
126            let file = OpenOptions::new()
127                .create(true)
128                .write(true)
129                .truncate(false)
130                .open(&lock_path)
131                .with_context(|| format!("Failed to open lock file: {}", lock_path.display()))?;
132
133            // Acquire exclusive lock
134            file.lock_exclusive()
135                .with_context(|| format!("Failed to acquire lock: {}", lock_path.display()))?;
136
137            Ok(file)
138        })
139        .await
140        .with_context(|| "Failed to spawn blocking task for lock acquisition")??;
141
142        Ok(Self {
143            _file: file,
144        })
145    }
146}
147
148/// Cleans up stale lock files in the cache directory.
149///
150/// This function removes lock files that are older than the specified TTL.
151/// It's useful for cleaning up after crashes or processes that didn't
152/// properly release their locks.
153///
154/// # Parameters
155///
156/// * `cache_dir` - The cache directory containing the .locks subdirectory
157/// * `ttl_seconds` - Time-to-live in seconds for lock files
158///
159/// # Returns
160///
161/// Returns the number of lock files that were removed.
162///
163/// # Errors
164///
165/// Returns an error if unable to read the locks directory or access lock file metadata
166pub async fn cleanup_stale_locks(cache_dir: &Path, ttl_seconds: u64) -> Result<usize> {
167    use std::time::{Duration, SystemTime};
168    use tokio::fs;
169
170    let locks_dir = cache_dir.join(".locks");
171    if !locks_dir.exists() {
172        return Ok(0);
173    }
174
175    let mut removed_count = 0;
176    let now = SystemTime::now();
177    let ttl_duration = Duration::from_secs(ttl_seconds);
178
179    let mut entries = fs::read_dir(&locks_dir).await.context("Failed to read locks directory")?;
180
181    while let Some(entry) = entries.next_entry().await? {
182        let path = entry.path();
183
184        // Only process .lock files
185        if path.extension().and_then(|s| s.to_str()) != Some("lock") {
186            continue;
187        }
188
189        // Check file age
190        let Ok(metadata) = fs::metadata(&path).await else {
191            continue; // Skip if we can't read metadata
192        };
193
194        let Ok(modified) = metadata.modified() else {
195            continue; // Skip if we can't get modification time
196        };
197
198        // Remove if older than TTL
199        if let Ok(age) = now.duration_since(modified)
200            && age > ttl_duration
201        {
202            // Try to remove the file (it might be locked by another process)
203            if fs::remove_file(&path).await.is_ok() {
204                removed_count += 1;
205            }
206        }
207    }
208
209    Ok(removed_count)
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215    use tempfile::TempDir;
216
217    #[tokio::test]
218    async fn test_cache_lock_acquire_and_release() {
219        let temp_dir = TempDir::new().unwrap();
220        let cache_dir = temp_dir.path();
221
222        // Acquire lock
223        let lock = CacheLock::acquire(cache_dir, "test_source").await.unwrap();
224
225        // Verify lock file was created
226        let lock_path = cache_dir.join(".locks").join("test_source.lock");
227        assert!(lock_path.exists());
228
229        // Drop the lock
230        drop(lock);
231
232        // Lock file should still exist (we don't delete it)
233        assert!(lock_path.exists());
234    }
235
236    #[tokio::test]
237    async fn test_cache_lock_creates_locks_directory() {
238        let temp_dir = TempDir::new().unwrap();
239        let cache_dir = temp_dir.path();
240
241        // Locks directory shouldn't exist initially
242        let locks_dir = cache_dir.join(".locks");
243        assert!(!locks_dir.exists());
244
245        // Acquire lock - should create directory
246        let lock = CacheLock::acquire(cache_dir, "test").await.unwrap();
247
248        // Verify locks directory was created
249        assert!(locks_dir.exists());
250        assert!(locks_dir.is_dir());
251
252        // Explicitly drop the lock to release the file handle before TempDir cleanup
253        drop(lock);
254    }
255
256    #[tokio::test]
257    async fn test_cache_lock_exclusive_blocking() {
258        use std::sync::Arc;
259        use std::time::{Duration, Instant};
260        use tokio::sync::Barrier;
261
262        let temp_dir = TempDir::new().unwrap();
263        let cache_dir = Arc::new(temp_dir.path().to_path_buf());
264        let barrier = Arc::new(Barrier::new(2));
265
266        let cache_dir1 = cache_dir.clone();
267        let barrier1 = barrier.clone();
268
269        // Task 1: Acquire lock and hold it
270        let handle1 = tokio::spawn(async move {
271            let _lock = CacheLock::acquire(&cache_dir1, "exclusive_test").await.unwrap();
272            barrier1.wait().await; // Signal that lock is acquired
273            tokio::time::sleep(Duration::from_millis(100)).await; // Hold lock
274            // Lock released on drop
275        });
276
277        let cache_dir2 = cache_dir.clone();
278
279        // Task 2: Try to acquire same lock (should block)
280        let handle2 = tokio::spawn(async move {
281            barrier.wait().await; // Wait for first task to acquire lock
282            let start = Instant::now();
283            let _lock = CacheLock::acquire(&cache_dir2, "exclusive_test").await.unwrap();
284            let elapsed = start.elapsed();
285
286            // Should have blocked for at least 50ms (less than 100ms due to timing)
287            assert!(elapsed >= Duration::from_millis(50));
288        });
289
290        handle1.await.unwrap();
291        handle2.await.unwrap();
292    }
293
294    #[tokio::test]
295    async fn test_cache_lock_different_sources_dont_block() {
296        use std::sync::Arc;
297        use std::time::{Duration, Instant};
298        use tokio::sync::Barrier;
299
300        let temp_dir = TempDir::new().unwrap();
301        let cache_dir = Arc::new(temp_dir.path().to_path_buf());
302        let barrier = Arc::new(Barrier::new(2));
303
304        let cache_dir1 = cache_dir.clone();
305        let barrier1 = barrier.clone();
306
307        // Task 1: Lock source1
308        let handle1 = tokio::spawn(async move {
309            let _lock = CacheLock::acquire(&cache_dir1, "source1").await.unwrap();
310            barrier1.wait().await;
311            tokio::time::sleep(Duration::from_millis(100)).await;
312        });
313
314        let cache_dir2 = cache_dir.clone();
315
316        // Task 2: Lock source2 (different source, shouldn't block)
317        let handle2 = tokio::spawn(async move {
318            barrier.wait().await;
319            let start = Instant::now();
320            let _lock = CacheLock::acquire(&cache_dir2, "source2").await.unwrap();
321            let elapsed = start.elapsed();
322
323            // Should not block (complete quickly)
324            // Increased timeout for slower systems while still ensuring no blocking
325            assert!(
326                elapsed < Duration::from_millis(200),
327                "Lock acquisition took {:?}, expected < 200ms for non-blocking operation",
328                elapsed
329            );
330        });
331
332        handle1.await.unwrap();
333        handle2.await.unwrap();
334    }
335
336    #[tokio::test]
337    async fn test_cache_lock_path_with_special_characters() {
338        let temp_dir = TempDir::new().unwrap();
339        let cache_dir = temp_dir.path();
340
341        // Test with various special characters in source name
342        let special_names = vec![
343            "source-with-dash",
344            "source_with_underscore",
345            "source.with.dots",
346            "source@special",
347        ];
348
349        for name in special_names {
350            let lock = CacheLock::acquire(cache_dir, name).await.unwrap();
351            let expected_path = cache_dir.join(".locks").join(format!("{name}.lock"));
352            assert!(expected_path.exists());
353            drop(lock);
354        }
355    }
356}