Skip to main content

crate_plugin_kit/
lock.rs

1//! Exclusive file lock held during install / uninstall.
2//!
3//! Two terminals running `plugin add` at once would corrupt `.plugins.json`, or let
4//! two `cargo build` runs write into the same wrapper directory. A cross-process
5//! lock keeps them out of each other's way.
6//!
7//! # Implementation
8//!
9//! The lock file is created with `create_new(true)` — atomic on mainstream file
10//! systems, so whoever creates it first holds the lock. The pid and a timestamp are
11//! written into it to make diagnosis easier.
12//!
13//! No OS-level file lock (`flock` / `LockFileEx`): that would need extra
14//! per-platform code, and this crate already has a simpler criterion — does the lock
15//! file exist, and is it stale? The price is that a `kill -9` leaves a stale lock
16//! file behind, hence the stale takeover.
17
18use std::io::Write;
19use std::path::{Path, PathBuf};
20use std::time::{Duration, Instant, SystemTime};
21
22use crate::error::{KitError, KitResult};
23
24/// How old a lock file has to be before it counts as stale. A lock older than this
25/// is taken over by a later arrival.
26///
27/// The value has to be longer than any reasonable install takes (`cargo build` can
28/// take minutes), and shorter than it takes the user to forget about it.
29pub const STALE_AFTER: Duration = Duration::from_secs(30 * 60);
30
31/// Poll interval.
32const POLL_INTERVAL: Duration = Duration::from_millis(120);
33
34/// Holds an exclusive lock. Released on `Drop`.
35#[derive(Debug)]
36pub struct FileLock {
37    path: PathBuf,
38}
39
40impl FileLock {
41    /// Acquires the lock, waiting at most `timeout`.
42    ///
43    /// # Errors
44    ///
45    /// - [`KitError::LockTimeout`]: another holder still has it when the timeout expires.
46    /// - [`KitError::LockIo`]: an IO error, or the lock file's parent directory could
47    ///   not be created.
48    pub fn acquire(path: &Path, timeout: Duration) -> KitResult<Self> {
49        Self::acquire_with_stale_after(path, timeout, STALE_AFTER)
50    }
51
52    /// Like [`Self::acquire`], but with a caller-supplied staleness threshold.
53    ///
54    /// The hook exists for testability: setting the threshold to 0 exercises the
55    /// takeover path without touching file timestamps (which needs platform APIs).
56    pub(crate) fn acquire_with_stale_after(
57        path: &Path,
58        timeout: Duration,
59        stale_after: Duration,
60    ) -> KitResult<Self> {
61        if let Some(parent) = path.parent() {
62            std::fs::create_dir_all(parent).map_err(|source| KitError::LockIo {
63                path: path.to_path_buf(),
64                source,
65            })?;
66        }
67
68        let deadline = Instant::now() + timeout;
69
70        loop {
71            match Self::try_create(path) {
72                Ok(lock) => return Ok(lock),
73                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
74                    // Someone else holds it. First check whether it is stale.
75                    if Self::take_over_if_stale(path, stale_after)? {
76                        continue;
77                    }
78                    if Instant::now() >= deadline {
79                        return Err(KitError::LockTimeout {
80                            path: path.to_path_buf(),
81                            secs: timeout.as_secs(),
82                        });
83                    }
84                    std::thread::sleep(POLL_INTERVAL);
85                }
86                Err(source) => {
87                    return Err(KitError::LockIo {
88                        path: path.to_path_buf(),
89                        source,
90                    })
91                }
92            }
93        }
94    }
95
96    fn try_create(path: &Path) -> std::io::Result<Self> {
97        let mut f = std::fs::OpenOptions::new()
98            .write(true)
99            .create_new(true)
100            .open(path)?;
101
102        // Some diagnostic content. Failure does not matter — the lock is already held.
103        let _ = writeln!(f, "pid={} at={:?}", std::process::id(), SystemTime::now());
104
105        Ok(Self {
106            path: path.to_path_buf(),
107        })
108    }
109
110    /// Deletes the lock file if it is too old, returning `true` to mean "it is gone,
111    /// retry now".
112    fn take_over_if_stale(path: &Path, stale_after: Duration) -> KitResult<bool> {
113        let Ok(meta) = std::fs::metadata(path) else {
114            // Already gone (someone just released it): let the caller retry.
115            return Ok(true);
116        };
117        let Ok(modified) = meta.modified() else {
118            return Ok(false);
119        };
120        let Ok(age) = SystemTime::now().duration_since(modified) else {
121            // The timestamp is in the future — the clock is broken, so do not take over.
122            return Ok(false);
123        };
124
125        if age < stale_after {
126            return Ok(false);
127        }
128
129        match std::fs::remove_file(path) {
130            Ok(()) => Ok(true),
131            // Someone else removed it at the same moment — even better; let the
132            // caller retry.
133            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true),
134            Err(source) => Err(KitError::LockIo {
135                path: path.to_path_buf(),
136                source,
137            }),
138        }
139    }
140}
141
142impl Drop for FileLock {
143    fn drop(&mut self) {
144        let _ = std::fs::remove_file(&self.path);
145    }
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    fn lock_path(dir: &tempfile::TempDir) -> PathBuf {
153        dir.path().join(".lock")
154    }
155
156    #[test]
157    fn acquires_and_creates_parent_directories() {
158        let dir = tempfile::tempdir().unwrap();
159        // The parent does not exist yet — acquire must create it
160        let path = dir.path().join("nested").join("deeper").join(".lock");
161
162        let lock = FileLock::acquire(&path, Duration::from_millis(50)).expect("should acquire");
163        assert!(path.is_file(), "the lock file should have been created");
164        drop(lock);
165    }
166
167    #[test]
168    fn releases_on_drop() {
169        let dir = tempfile::tempdir().unwrap();
170        let path = lock_path(&dir);
171
172        {
173            let _lock = FileLock::acquire(&path, Duration::from_millis(50)).unwrap();
174            assert!(path.is_file());
175        }
176
177        assert!(!path.exists(), "the lock file should be deleted on drop");
178    }
179
180    /// The second holder has to wait, and reports `LockTimeout` when it runs out of
181    /// time — it must not silently proceed.
182    #[test]
183    fn a_second_holder_times_out() {
184        let dir = tempfile::tempdir().unwrap();
185        let path = lock_path(&dir);
186
187        let _first = FileLock::acquire(&path, Duration::from_millis(50)).unwrap();
188
189        let err = FileLock::acquire(&path, Duration::from_millis(120));
190        assert!(
191            matches!(err, Err(KitError::LockTimeout { .. })),
192            "expected LockTimeout, got {err:?}"
193        );
194    }
195
196    /// Once the lock is released, a later arrival should get it immediately.
197    #[test]
198    fn a_later_holder_succeeds_after_release() {
199        let dir = tempfile::tempdir().unwrap();
200        let path = lock_path(&dir);
201
202        let first = FileLock::acquire(&path, Duration::from_millis(50)).unwrap();
203        drop(first);
204
205        let _second = FileLock::acquire(&path, Duration::from_millis(200)).expect("should acquire");
206    }
207
208    /// A stale lock (left behind by `kill -9`) has to be taken over, otherwise the
209    /// user stays blocked forever.
210    ///
211    /// With the staleness threshold set to 0, any existing lock counts as stale —
212    /// which keeps the test portable, since changing file timestamps needs platform
213    /// APIs.
214    #[test]
215    fn takes_over_a_stale_lock() {
216        let dir = tempfile::tempdir().unwrap();
217        let path = lock_path(&dir);
218
219        std::fs::write(&path, "pid=1 at=<stale>").unwrap();
220
221        let _lock =
222            FileLock::acquire_with_stale_after(&path, Duration::from_millis(500), Duration::ZERO)
223                .expect("a stale lock should be taken over");
224    }
225
226    /// A fresh lock must not be stolen.
227    #[test]
228    fn does_not_steal_a_fresh_lock() {
229        let dir = tempfile::tempdir().unwrap();
230        let path = lock_path(&dir);
231
232        std::fs::write(&path, "pid=1 at=<fresh>").unwrap();
233
234        // Threshold left at the default: a lock just written is nowhere near stale
235        let err =
236            FileLock::acquire_with_stale_after(&path, Duration::from_millis(120), STALE_AFTER);
237        assert!(
238            matches!(err, Err(KitError::LockTimeout { .. })),
239            "a fresh lock must not be stolen"
240        );
241    }
242
243    /// The lock file carries the pid, which makes it easy to see who holds it.
244    #[test]
245    fn writes_diagnostic_content() {
246        let dir = tempfile::tempdir().unwrap();
247        let path = lock_path(&dir);
248
249        let _lock = FileLock::acquire(&path, Duration::from_millis(50)).unwrap();
250
251        let text = std::fs::read_to_string(&path).unwrap();
252        assert!(text.contains("pid="), "lock file content: {text:?}");
253        assert!(text.contains(&std::process::id().to_string()));
254    }
255}