vibe_ticket/storage/
lock.rs1use anyhow::{Context, Result, bail};
2use serde::{Deserialize, Serialize};
3use 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
13const LOCK_TIMEOUT: Duration = Duration::from_secs(30);
15
16const MAX_RETRY_ATTEMPTS: u32 = 10;
18
19const RETRY_DELAY: Duration = Duration::from_millis(100);
21
22#[derive(Debug, Serialize, Deserialize)]
24pub struct LockInfo {
25 pub(crate) holder_id: String,
27 pub(crate) pid: u32,
29 pub(crate) acquired_at: u64,
31 pub(crate) operation: Option<String>,
33}
34
35pub struct FileLock {
37 path: PathBuf,
38 holder_id: String,
39}
40
41impl FileLock {
42 #[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 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 if Self::is_lock_stale(&lock_path)? {
71 let _ = fs::remove_file(&lock_path);
73 continue;
74 }
75
76 std::thread::sleep(RETRY_DELAY);
78 },
79 }
80 }
81
82 bail!("Failed to acquire lock: maximum retries exceeded")
83 }
84
85 fn try_acquire_once(
87 lock_path: &Path,
88 holder_id: &str,
89 operation: Option<&String>,
90 ) -> Result<()> {
91 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 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 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 pub fn release(self) {
146 drop(self);
148 }
149}
150
151impl Drop for FileLock {
152 fn drop(&mut self) {
153 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
168pub struct LockGuard<'a> {
170 _lock: FileLock,
171 _phantom: std::marker::PhantomData<&'a ()>,
172}
173
174impl LockGuard<'_> {
175 #[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 let lock = FileLock::acquire(&file_path, Some("test operation".to_string())).unwrap();
197
198 assert!(FileLock::acquire(&file_path, None).is_err());
200
201 drop(lock);
203
204 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 let stale_info = LockInfo {
216 holder_id: "stale-holder".to_string(),
217 pid: 99999,
218 acquired_at: 0, operation: None,
220 };
221
222 fs::write(&lock_path, serde_json::to_string(&stale_info).unwrap()).unwrap();
223
224 let _lock = FileLock::acquire(&file_path, None).unwrap();
226 }
227}