Skip to main content

stackless_core/
lockfile.rs

1//! Cross-process file locks keyed by path (ARCHITECTURE.md §2/§3).
2//!
3//! The OS releases a lock when its file handle closes or its process exits.
4//! Lock files remain in place: unlinking a held lock would allow another
5//! process to lock a different inode at the same path.
6
7use std::fs::{File, TryLockError};
8use std::hash::{Hash, Hasher};
9use std::path::{Path, PathBuf};
10use std::time::{Duration, Instant};
11
12use crate::state::Store;
13
14const DEFAULT_POLL: Duration = Duration::from_millis(100);
15
16/// A held lock; released when dropped.
17#[derive(Debug)]
18pub struct FileLock {
19    _file: File,
20}
21
22impl Drop for FileLock {
23    fn drop(&mut self) {
24        // A concurrent fork can briefly inherit this open file description.
25        // Unlock explicitly so that child cannot delay a normal release.
26        let _ = self._file.unlock();
27    }
28}
29
30impl FileLock {
31    /// Try once; returns [`LockError::Held`] if a live holder has the lock.
32    pub fn try_acquire(path: &Path) -> Result<Self, LockError> {
33        if let Some(parent) = path.parent() {
34            std::fs::create_dir_all(parent).map_err(|err| LockError::CreateParent {
35                path: path.to_path_buf(),
36                detail: err.to_string(),
37            })?;
38        }
39        let file = std::fs::OpenOptions::new()
40            .read(true)
41            .write(true)
42            .create(true)
43            .truncate(false)
44            .open(path)
45            .map_err(|source| LockError::Io {
46                path: path.to_path_buf(),
47                source,
48            })?;
49        match file.try_lock() {
50            Ok(()) => Ok(Self { _file: file }),
51            Err(TryLockError::WouldBlock) => Err(LockError::Held {
52                path: path.to_path_buf(),
53            }),
54            Err(TryLockError::Error(source)) => Err(LockError::Io {
55                path: path.to_path_buf(),
56                source,
57            }),
58        }
59    }
60
61    /// Wait for contention only. Filesystem errors return immediately.
62    pub fn acquire_with_wait(path: &Path, budget: Duration) -> Result<Self, LockError> {
63        let start = Instant::now();
64        loop {
65            match Self::try_acquire(path) {
66                Ok(lock) => return Ok(lock),
67                Err(LockError::Held { .. }) if start.elapsed() < budget => {
68                    std::thread::sleep(DEFAULT_POLL);
69                }
70                Err(err) => return Err(err),
71            }
72        }
73    }
74
75    /// Wait for an existing command lock without creating one for an unused runtime.
76    pub fn acquire_existing(path: &Path, budget: Duration) -> Result<Option<Self>, LockError> {
77        match std::fs::symlink_metadata(path) {
78            Ok(meta) if meta.is_file() => Self::acquire_with_wait(path, budget).map(Some),
79            Ok(_) => Err(LockError::Io {
80                path: path.into(),
81                source: std::io::Error::other("lock is not an ordinary file"),
82            }),
83            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
84            Err(source) => Err(LockError::Io {
85                path: path.into(),
86                source,
87            }),
88        }
89    }
90
91    /// Filesystem-safe digest of a path for lock file names.
92    pub fn path_key(path: &Path) -> String {
93        let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
94        let mut hasher = std::collections::hash_map::DefaultHasher::new();
95        canonical.hash(&mut hasher);
96        format!("{:016x}", hasher.finish())
97    }
98
99    /// `{state_dir}/locks/stripe/{digest}.lock` for a definition dir.
100    pub fn stripe_lock_path(definition_dir: &Path) -> PathBuf {
101        Store::state_dir()
102            .join("locks/stripe")
103            .join(format!("{}.lock", Self::path_key(definition_dir)))
104    }
105
106    /// `{state_dir}/locks/git-cache/{cache_key}.lock`.
107    pub fn git_cache_lock_path(cache_key: &str) -> PathBuf {
108        Store::state_dir()
109            .join("locks/git-cache")
110            .join(format!("{cache_key}.lock"))
111    }
112}
113
114#[derive(Debug, thiserror::Error)]
115pub enum LockError {
116    #[error("lock {path} is held by a live process")]
117    Held { path: PathBuf },
118    #[error("could not create lock parent for {path}: {detail}")]
119    CreateParent { path: PathBuf, detail: String },
120    #[error("cannot lock {path}: {source}")]
121    Io {
122        path: PathBuf,
123        source: std::io::Error,
124    },
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130    use std::sync::{Arc, Barrier};
131    use std::thread;
132
133    #[test]
134    fn second_holder_blocks_until_release() {
135        let dir = tempfile::tempdir().unwrap();
136        let path = dir.path().join("test.lock");
137
138        let lock = FileLock::try_acquire(&path).unwrap();
139        assert!(matches!(
140            FileLock::try_acquire(&path),
141            Err(LockError::Held { .. })
142        ));
143        drop(lock);
144        assert!(FileLock::try_acquire(&path).is_ok());
145    }
146
147    #[test]
148    fn concurrent_waiters_serialize() {
149        let dir = Arc::new(tempfile::tempdir().unwrap());
150        let n = 4;
151        let start = Arc::new(Barrier::new(n));
152        let mut handles = Vec::new();
153        for _ in 0..n {
154            let dir = Arc::clone(&dir);
155            let start = Arc::clone(&start);
156            handles.push(thread::spawn(move || {
157                start.wait();
158                let _lock = FileLock::acquire_with_wait(
159                    &dir.path().join("queue.lock"),
160                    Duration::from_secs(5),
161                )
162                .unwrap();
163            }));
164        }
165        for handle in handles {
166            handle.join().unwrap();
167        }
168    }
169    #[test]
170    fn lock_crash_helper() {
171        let Some(path) = std::env::var_os("STACKLESS_TEST_LOCK_FILE") else {
172            return;
173        };
174        let path = PathBuf::from(path);
175        let _lock = FileLock::try_acquire(&path).unwrap();
176        std::fs::write(path.with_extension("ready"), "locked").unwrap();
177        std::thread::sleep(Duration::from_secs(30));
178    }
179
180    #[test]
181    fn process_crash_releases_os_lock_without_unlinking() {
182        let dir = tempfile::tempdir().unwrap();
183        let path = dir.path().join("crash.lock");
184        let mut holder = std::process::Command::new(std::env::current_exe().unwrap())
185            .args(["--exact", "lockfile::tests::lock_crash_helper"])
186            .env("STACKLESS_TEST_LOCK_FILE", &path)
187            .stdout(std::process::Stdio::null())
188            .stderr(std::process::Stdio::null())
189            .spawn()
190            .unwrap();
191        let deadline = Instant::now() + Duration::from_secs(5);
192        while !path.with_extension("ready").exists() && Instant::now() < deadline {
193            std::thread::sleep(Duration::from_millis(10));
194        }
195        let ready = path.with_extension("ready").exists();
196        let excluded = matches!(FileLock::try_acquire(&path), Err(LockError::Held { .. }));
197        holder.kill().unwrap();
198        holder.wait().unwrap();
199        assert!(ready);
200        assert!(excluded);
201        assert!(path.exists());
202        assert!(FileLock::try_acquire(&path).is_ok());
203    }
204}