Skip to main content

vibe_ticket/storage/
lock.rs

1use anyhow::{Context, Result, bail};
2use serde::{Deserialize, Serialize};
3/// File locking mechanism for concurrent access protection
4///
5/// This module provides a simple file-based locking mechanism to prevent
6/// concurrent modifications to ticket files.
7use std::fs::{self, File, OpenOptions};
8use std::io::{Read, Write as IoWrite};
9use std::path::{Path, PathBuf};
10use std::time::{Duration, SystemTime, UNIX_EPOCH};
11use uuid::Uuid;
12
13/// Maximum time a lock can be held before it's considered stale
14const LOCK_TIMEOUT: Duration = Duration::from_secs(30);
15
16/// Maximum number of retry attempts for acquiring a lock
17const MAX_RETRY_ATTEMPTS: u32 = 10;
18
19/// Delay between retry attempts
20const RETRY_DELAY: Duration = Duration::from_millis(100);
21
22/// Information stored in a lock file
23#[derive(Debug, Serialize, Deserialize)]
24pub struct LockInfo {
25    /// Unique identifier for the lock holder
26    pub(crate) holder_id: String,
27    /// Process ID of the lock holder
28    pub(crate) pid: u32,
29    /// Timestamp when the lock was acquired
30    pub(crate) acquired_at: u64,
31    /// Optional description of the operation
32    pub(crate) operation: Option<String>,
33}
34
35/// A file lock that automatically releases on drop
36pub struct FileLock {
37    path: PathBuf,
38    holder_id: String,
39}
40
41impl FileLock {
42    /// Attempts to acquire a lock for the given path
43    ///
44    /// # Arguments
45    /// * `path` - The file path to lock
46    /// * `operation` - Optional description of the operation being performed
47    ///
48    /// # Returns
49    /// A `FileLock` that will automatically release when dropped
50    #[allow(clippy::needless_pass_by_value)]
51    pub fn acquire(path: &Path, operation: Option<String>) -> Result<Self> {
52        let lock_path = Self::lock_path(path);
53        let holder_id = Uuid::new_v4().to_string();
54
55        // Try to acquire the lock with retries
56        for attempt in 0..MAX_RETRY_ATTEMPTS {
57            match Self::try_acquire_once(&lock_path, &holder_id, operation.as_ref()) {
58                Ok(()) => {
59                    return Ok(Self {
60                        path: lock_path,
61                        holder_id,
62                    });
63                },
64                Err(e) => {
65                    if attempt == MAX_RETRY_ATTEMPTS - 1 {
66                        return Err(e).context("Failed to acquire lock after maximum retries");
67                    }
68
69                    // Check if the existing lock is stale
70                    if Self::is_lock_stale(&lock_path)? {
71                        // Try to remove stale lock
72                        let _ = fs::remove_file(&lock_path);
73                        continue;
74                    }
75
76                    // Wait before retrying
77                    std::thread::sleep(RETRY_DELAY);
78                },
79            }
80        }
81
82        bail!("Failed to acquire lock: maximum retries exceeded")
83    }
84
85    /// Attempts to acquire a lock once without retrying
86    fn try_acquire_once(
87        lock_path: &Path,
88        holder_id: &str,
89        operation: Option<&String>,
90    ) -> Result<()> {
91        // Try to create the lock file exclusively
92        let mut file = OpenOptions::new()
93            .write(true)
94            .create_new(true)
95            .open(lock_path)
96            .context("Lock file already exists")?;
97
98        let lock_info = LockInfo {
99            holder_id: holder_id.to_string(),
100            pid: std::process::id(),
101            acquired_at: SystemTime::now()
102                .duration_since(UNIX_EPOCH)
103                .unwrap()
104                .as_secs(),
105            operation: operation.cloned(),
106        };
107
108        let json = serde_json::to_string_pretty(&lock_info)?;
109        file.write_all(json.as_bytes())?;
110        file.sync_all()?;
111
112        Ok(())
113    }
114
115    /// Checks if a lock file is stale (older than `LOCK_TIMEOUT`)
116    fn is_lock_stale(lock_path: &Path) -> Result<bool> {
117        if !lock_path.exists() {
118            return Ok(false);
119        }
120
121        let mut file = File::open(lock_path)?;
122        let mut contents = String::new();
123        file.read_to_string(&mut contents)?;
124
125        let lock_info: LockInfo = serde_json::from_str(&contents)?;
126
127        let now = SystemTime::now()
128            .duration_since(UNIX_EPOCH)
129            .unwrap()
130            .as_secs();
131
132        let age = now.saturating_sub(lock_info.acquired_at);
133        Ok(age > LOCK_TIMEOUT.as_secs())
134    }
135
136    /// Gets the lock file path for a given file
137    fn lock_path(path: &Path) -> PathBuf {
138        let mut lock_path = path.to_path_buf();
139        let filename = format!("{}.lock", path.file_name().unwrap().to_str().unwrap());
140        lock_path.set_file_name(filename);
141        lock_path
142    }
143
144    /// Releases the lock explicitly
145    pub fn release(self) {
146        // Drop will handle the release
147        drop(self);
148    }
149}
150
151impl Drop for FileLock {
152    fn drop(&mut self) {
153        // Only remove the lock file if we are the holder
154        if let Ok(mut file) = File::open(&self.path) {
155            let mut contents = String::new();
156            if file.read_to_string(&mut contents).is_ok() {
157                if let Ok(lock_info) = serde_json::from_str::<LockInfo>(&contents) {
158                    #[allow(clippy::excessive_nesting)]
159                    if lock_info.holder_id == self.holder_id {
160                        let _ = fs::remove_file(&self.path);
161                    }
162                }
163            }
164        }
165    }
166}
167
168/// A guard that holds a lock and automatically releases it when dropped
169pub struct LockGuard<'a> {
170    _lock: FileLock,
171    _phantom: std::marker::PhantomData<&'a ()>,
172}
173
174impl LockGuard<'_> {
175    /// Creates a new lock guard
176    #[must_use]
177    pub const fn new(lock: FileLock) -> Self {
178        LockGuard {
179            _lock: lock,
180            _phantom: std::marker::PhantomData,
181        }
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188    use tempfile::TempDir;
189
190    #[test]
191    fn test_acquire_and_release_lock() {
192        let temp_dir = TempDir::new().unwrap();
193        let file_path = temp_dir.path().join("test.yaml");
194
195        // Acquire lock
196        let lock = FileLock::acquire(&file_path, Some("test operation".to_string())).unwrap();
197
198        // Try to acquire again - should fail
199        assert!(FileLock::acquire(&file_path, None).is_err());
200
201        // Release lock
202        drop(lock);
203
204        // Should be able to acquire again
205        let _lock2 = FileLock::acquire(&file_path, None).unwrap();
206    }
207
208    #[test]
209    fn test_stale_lock_removal() {
210        let temp_dir = TempDir::new().unwrap();
211        let file_path = temp_dir.path().join("test.yaml");
212        let lock_path = FileLock::lock_path(&file_path);
213
214        // Create a stale lock manually
215        let stale_info = LockInfo {
216            holder_id: "stale-holder".to_string(),
217            pid: 99999,
218            acquired_at: 0, // Very old timestamp
219            operation: None,
220        };
221
222        fs::write(&lock_path, serde_json::to_string(&stale_info).unwrap()).unwrap();
223
224        // Should be able to acquire lock despite stale lock file
225        let _lock = FileLock::acquire(&file_path, None).unwrap();
226    }
227}