Skip to main content

grit_lib/
lockfile.rs

1//! Exclusive lock files with optional Git-style acquisition backoff.
2//!
3//! Grit uses lock files (`.lock` siblings, `index.lock`, `packed-refs.lock`, …) the same way
4//! Git does: create exclusively, write staged content, then rename over the target path.
5//! [`LockFile::acquire`] retries with jittered exponential backoff when configured, matching
6//! `core.filesRefLockTimeout`, `core.packedRefsTimeout`, and `reftable.lockTimeout`.
7//!
8//! ```rust
9//! use grit_lib::config::ConfigSet;
10//! use grit_lib::lockfile::LockWait;
11//! let wait = LockWait::files_ref_lock(Some(&ConfigSet::new()));
12//! assert!(matches!(wait, LockWait::Immediately | LockWait::Backoff { .. } | LockWait::Indefinitely));
13//! ```
14
15use std::fs::{self, File, OpenOptions};
16use std::io::{self, Write};
17use std::path::{Path, PathBuf};
18use std::sync::Arc;
19use std::time::{Duration, Instant};
20
21use thiserror::Error;
22
23use crate::config::ConfigSet;
24use crate::environment::Environment;
25
26/// Whether to wait for an existing lock, and for how long.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum LockWait {
29    /// Fail immediately when the lock file already exists.
30    Immediately,
31    /// Retry with jittered exponential backoff until `budget` elapses.
32    Backoff {
33        /// Total time budget for acquisition attempts.
34        budget: Duration,
35    },
36    /// Retry until the lock is acquired (Git `core.filesRefLockTimeout = -1`).
37    Indefinitely,
38}
39
40impl LockWait {
41    /// `core.filesRefLockTimeout` (milliseconds), default 100 ms when unset.
42    #[must_use]
43    pub fn files_ref_lock(config: Option<&ConfigSet>) -> Self {
44        Self::from_files_ref_lock_timeout_ms(Self::parse_files_ref_lock_timeout_ms(config))
45    }
46
47    /// Parse `core.filesRefLockTimeout` the way Git does (milliseconds).
48    #[must_use]
49    pub fn parse_files_ref_lock_timeout_ms(config: Option<&ConfigSet>) -> i64 {
50        config
51            .and_then(|cfg| cfg.value("core.filesreflocktimeout"))
52            .and_then(|v| v.trim().parse::<i64>().ok())
53            .unwrap_or(100)
54    }
55
56    #[must_use]
57    fn from_files_ref_lock_timeout_ms(timeout_ms: i64) -> Self {
58        match timeout_ms {
59            0 => Self::Immediately,
60            ms if ms < 0 => Self::Indefinitely,
61            ms => Self::Backoff {
62                budget: Duration::from_millis(ms as u64),
63            },
64        }
65    }
66
67    /// `core.packedRefsTimeout` (milliseconds), default 1000 ms when unset.
68    #[must_use]
69    pub fn packed_refs(config: Option<&ConfigSet>) -> Self {
70        Self::from_milliseconds_config(config, "core.packedrefstimeout", 1_000)
71    }
72
73    /// `reftable.lockTimeout` (milliseconds), default 1000 ms when unset.
74    #[must_use]
75    pub fn reftable_tables_list(config: Option<&ConfigSet>) -> Self {
76        Self::from_milliseconds_config(config, "reftable.locktimeout", 1_000)
77    }
78
79    /// Load repository config from `git_dir` and return [`Self::files_ref_lock`].
80    #[must_use]
81    pub fn files_ref_lock_for_git_dir(git_dir: &Path) -> Self {
82        let config = ConfigSet::load(
83            &Environment::empty(),
84            Some(git_dir),
85            &crate::config::LoadConfigOptions::standard(&Environment::empty(), Some(git_dir)),
86        )
87        .ok();
88        Self::files_ref_lock(config.as_ref())
89    }
90
91    /// Load repository config from `git_dir` and return [`Self::packed_refs`].
92    #[must_use]
93    pub fn packed_refs_for_git_dir(git_dir: &Path) -> Self {
94        let config = ConfigSet::load(
95            &Environment::empty(),
96            Some(git_dir),
97            &crate::config::LoadConfigOptions::standard(&Environment::empty(), Some(git_dir)),
98        )
99        .ok();
100        Self::packed_refs(config.as_ref())
101    }
102
103    fn from_milliseconds_config(config: Option<&ConfigSet>, key: &str, default_ms: u64) -> Self {
104        let ms = config
105            .and_then(|cfg| cfg.value(key))
106            .and_then(|v| v.trim().parse::<i64>().ok())
107            .map(|v| v.max(0) as u64)
108            .unwrap_or(default_ms);
109        if ms == 0 {
110            Self::Immediately
111        } else {
112            Self::Backoff {
113                budget: Duration::from_millis(ms),
114            }
115        }
116    }
117
118    /// Remaining wait budget after `elapsed` time since the outer wait started.
119    #[must_use]
120    pub fn remaining_after(self, elapsed: Duration) -> Self {
121        match self {
122            Self::Immediately => Self::Immediately,
123            Self::Indefinitely => Self::Indefinitely,
124            Self::Backoff { budget } => {
125                if elapsed >= budget {
126                    Self::Immediately
127                } else {
128                    Self::Backoff {
129                        budget: budget - elapsed,
130                    }
131                }
132            }
133        }
134    }
135
136    /// Remaining wait budget given `start` and `now`.
137    #[must_use]
138    pub fn remaining_from(self, start: Instant, now: Instant) -> Self {
139        self.remaining_after(now.saturating_duration_since(start))
140    }
141}
142
143/// Failure to create or commit a lock file.
144#[derive(Debug, Error)]
145#[non_exhaustive]
146pub enum LockError {
147    /// Another process holds the lock (or the lock path already exists).
148    #[error("lock held at {path}")]
149    Held {
150        /// Path to the lock file that could not be created exclusively.
151        path: PathBuf,
152    },
153
154    /// Underlying I/O failure while creating, writing, syncing, or renaming.
155    #[error("lock I/O at {path}")]
156    Io {
157        /// Lock file path associated with the failure.
158        path: PathBuf,
159        /// Underlying OS error.
160        #[source]
161        source: io::Error,
162    },
163}
164
165/// Injectable clock and sleep for deterministic lock backoff tests.
166pub trait LockClock: Send + Sync {
167    /// Current instant (used for backoff deadlines).
168    fn now(&self) -> Instant;
169    /// Pause until the next acquisition attempt.
170    fn sleep(&self, duration: Duration);
171}
172
173/// Injectable jitter so concurrent processes do not sleep in lockstep.
174pub trait LockJitter: Send + Sync {
175    /// Fraction in `[0.0, 1.0)` scaled into backoff delays.
176    fn fraction(&self, lock_path: &Path, attempt: u32) -> f64;
177}
178
179/// OS random bytes for cross-process jitter (Git-style lock backoff).
180#[derive(Debug, Default, Clone, Copy)]
181pub struct SystemLockJitter;
182
183impl LockJitter for SystemLockJitter {
184    fn fraction(&self, _lock_path: &Path, _attempt: u32) -> f64 {
185        let mut buf = [0u8; 8];
186        if getrandom::getrandom(&mut buf).is_ok() {
187            let n = u64::from_le_bytes(buf);
188            (n % 10_000) as f64 / 10_000.0
189        } else {
190            0.5
191        }
192    }
193}
194
195/// Wall-clock backoff using [`std::thread::sleep`].
196#[derive(Debug, Default, Clone, Copy)]
197pub struct SystemLockClock;
198
199impl LockClock for SystemLockClock {
200    fn now(&self) -> Instant {
201        Instant::now()
202    }
203
204    fn sleep(&self, duration: Duration) {
205        if !duration.is_zero() {
206            std::thread::sleep(duration);
207        }
208    }
209}
210
211/// Exclusive lock file created by this process.
212///
213/// Drop without [`Self::commit`] or [`Self::commit_to`] removes the lock file when this
214/// handle created it. Foreign lock files are never removed.
215pub struct LockFile {
216    lock_path: PathBuf,
217    commit_path: Option<PathBuf>,
218    file: Option<File>,
219    committed: bool,
220    wrote_holder_pid: bool,
221}
222
223impl LockFile {
224    /// Create `target` exclusively (`O_CREAT|O_EXCL`), optionally waiting per `wait`.
225    ///
226    /// `target` is the lock file path (for example `refs/heads/main.lock`), not the file being
227    /// updated. Persist staged bytes with [`Self::commit_to`] (or [`Self::commit`] after
228    /// [`Self::with_commit_target`]).
229    ///
230    /// # Errors
231    ///
232    /// Returns [`LockError::Held`] when the lock exists and the wait budget is exhausted, or
233    /// [`LockError::Io`] for other failures.
234    pub fn acquire(target: &Path, wait: LockWait) -> Result<Self, LockError> {
235        Self::acquire_with_clock(
236            target,
237            wait,
238            Arc::new(SystemLockClock),
239            Arc::new(SystemLockJitter),
240        )
241    }
242
243    /// Like [`Self::acquire`], with injectable clock and jitter for unit tests.
244    pub fn acquire_with_clock(
245        target: &Path,
246        wait: LockWait,
247        clock: Arc<dyn LockClock>,
248        jitter: Arc<dyn LockJitter>,
249    ) -> Result<Self, LockError> {
250        let to_lock_error = |source: io::Error| {
251            if crate::atomic_replace::is_lock_acquire_contention(&source, target) {
252                LockError::Held {
253                    path: target.to_path_buf(),
254                }
255            } else {
256                LockError::Io {
257                    path: target.to_path_buf(),
258                    source,
259                }
260            }
261        };
262        let open = || OpenOptions::new().write(true).create_new(true).open(target);
263        // The parent usually exists, so it is only created once an open fails. Creating it
264        // then still reports a parent blocked by a file as the directory error.
265        let mut parent_ready = false;
266        retry_while_held(
267            target,
268            || wait,
269            clock.as_ref(),
270            jitter.as_ref(),
271            || match open() {
272                Err(_) if !parent_ready => {
273                    parent_ready = true;
274                    if let Some(parent) = target.parent() {
275                        fs::create_dir_all(parent).map_err(|source| LockError::Io {
276                            path: target.to_path_buf(),
277                            source,
278                        })?;
279                    }
280                    open().map_err(to_lock_error)
281                }
282                other => other.map_err(to_lock_error),
283            },
284            |err| matches!(err, LockError::Held { .. }),
285        )
286        .map(|file| Self {
287            lock_path: target.to_path_buf(),
288            commit_path: None,
289            file: Some(file),
290            committed: false,
291            wrote_holder_pid: false,
292        })
293    }
294
295    /// Set the destination path used by [`Self::commit`].
296    #[must_use]
297    pub fn with_commit_target(mut self, path: &Path) -> Self {
298        self.commit_path = Some(path.to_path_buf());
299        self
300    }
301
302    /// Path to the lock file held by this handle.
303    #[must_use]
304    pub fn lock_path(&self) -> &Path {
305        &self.lock_path
306    }
307
308    /// Borrow the open lock file for writing.
309    ///
310    /// # Errors
311    ///
312    /// Returns [`LockError::Io`] when the handle was already taken (for example after
313    /// the open file handle was moved out for index integration).
314    pub fn as_file(&self) -> Result<&File, LockError> {
315        self.file.as_ref().ok_or_else(|| LockError::Io {
316            path: self.lock_path.clone(),
317            source: io::Error::new(io::ErrorKind::NotConnected, "lock file handle missing"),
318        })
319    }
320
321    /// Borrow the open lock file mutably for writing.
322    ///
323    /// # Errors
324    ///
325    /// Returns [`LockError::Io`] when the handle was already taken.
326    pub fn as_file_mut(&mut self) -> Result<&mut File, LockError> {
327        self.file.as_mut().ok_or_else(|| LockError::Io {
328            path: self.lock_path.clone(),
329            source: io::Error::new(io::ErrorKind::NotConnected, "lock file handle missing"),
330        })
331    }
332
333    /// Yield the lock path and open file without removing the lock on drop.
334    pub(crate) fn into_open_file(mut self) -> Result<(PathBuf, File), LockError> {
335        self.committed = true;
336        let file = self.file.take().ok_or_else(|| LockError::Io {
337            path: self.lock_path.clone(),
338            source: io::Error::new(io::ErrorKind::NotConnected, "lock file handle missing"),
339        })?;
340        Ok((self.lock_path.clone(), file))
341    }
342
343    /// Fsync the lock file, rename it over `commit_path` from [`Self::with_commit_target`], and
344    /// disarm drop cleanup.
345    ///
346    /// # Errors
347    ///
348    /// Returns [`LockError::Io`] when no commit target was configured or rename fails.
349    pub fn commit(self) -> Result<(), LockError> {
350        let dest = self.commit_path.clone().ok_or_else(|| LockError::Io {
351            path: self.lock_path.clone(),
352            source: io::Error::new(
353                io::ErrorKind::InvalidInput,
354                "lock commit target not configured",
355            ),
356        })?;
357        self.commit_to(&dest)
358    }
359
360    /// Fsync the lock file and atomically rename it over `other_path`.
361    ///
362    /// # Errors
363    ///
364    /// Returns [`LockError::Io`] on sync or rename failure.
365    pub fn commit_to(mut self, other_path: &Path) -> Result<(), LockError> {
366        let file = self.file.take().ok_or_else(|| LockError::Io {
367            path: self.lock_path.clone(),
368            source: io::Error::new(io::ErrorKind::NotConnected, "lock file handle missing"),
369        })?;
370        file.sync_all().map_err(|source| LockError::Io {
371            path: self.lock_path.clone(),
372            source,
373        })?;
374        drop(file);
375        crate::atomic_replace::replace_file(&self.lock_path, other_path).map_err(|source| {
376            LockError::Io {
377                path: self.lock_path.clone(),
378                source,
379            }
380        })?;
381        self.remove_holder_pid_sidecar();
382        self.committed = true;
383        Ok(())
384    }
385
386    /// Record this process as the holder of [`Self::lock_path`] in a Git-compatible pid sidecar.
387    ///
388    /// # Errors
389    ///
390    /// Returns [`LockError::Io`] when the sidecar cannot be written.
391    pub fn write_holder_pid(&mut self) -> Result<(), LockError> {
392        write_lock_pid_file(&pid_path_for_lock(&self.lock_path)).map_err(|source| {
393            LockError::Io {
394                path: self.lock_path.clone(),
395                source,
396            }
397        })?;
398        self.wrote_holder_pid = true;
399        Ok(())
400    }
401
402    /// Release the lock without committing (same as drop).
403    pub fn rollback(mut self) {
404        if self.committed {
405            return;
406        }
407        drop(self.file.take());
408        let _ = fs::remove_file(&self.lock_path);
409        self.remove_holder_pid_sidecar();
410        self.committed = true;
411    }
412
413    fn remove_holder_pid_sidecar(&self) {
414        if self.wrote_holder_pid {
415            let _ = fs::remove_file(pid_path_for_lock(&self.lock_path));
416        }
417    }
418
419    /// Close this handle but leave the lock file on disk (mutex-only locks).
420    pub fn detach(mut self) {
421        self.committed = true;
422    }
423}
424
425impl Write for LockFile {
426    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
427        match self.file.as_mut() {
428            Some(file) => file.write(buf),
429            None => Err(io::Error::new(
430                io::ErrorKind::NotConnected,
431                "lock file handle missing",
432            )),
433        }
434    }
435
436    fn flush(&mut self) -> io::Result<()> {
437        match self.file.as_mut() {
438            Some(file) => file.flush(),
439            None => Err(io::Error::new(
440                io::ErrorKind::NotConnected,
441                "lock file handle missing",
442            )),
443        }
444    }
445}
446
447impl Drop for LockFile {
448    fn drop(&mut self) {
449        if self.committed {
450            return;
451        }
452        drop(self.file.take());
453        let _ = fs::remove_file(&self.lock_path);
454        self.remove_holder_pid_sidecar();
455    }
456}
457
458/// Run `attempt` until it succeeds, fails with an error `is_held` does not accept, or the wait
459/// budget is spent, sleeping the jittered backoff between attempts.
460///
461/// The deadline starts before the first attempt, so time spent inside `attempt` (which may
462/// itself wait on a lock) counts against the budget. `wait` is resolved only after the first
463/// held failure, so callers that read it from config pay nothing when the lock is free.
464/// `key` names the lock for [`LockJitter::fraction`].
465///
466/// # Errors
467///
468/// Returns the last error from `attempt`: immediately when `is_held` rejects it, otherwise
469/// once the budget is exhausted.
470pub(crate) fn retry_while_held<T, E>(
471    key: &Path,
472    wait: impl FnOnce() -> LockWait,
473    clock: &dyn LockClock,
474    jitter: &dyn LockJitter,
475    mut attempt: impl FnMut() -> Result<T, E>,
476    is_held: impl Fn(&E) -> bool,
477) -> Result<T, E> {
478    let start = clock.now();
479    let mut err = match attempt() {
480        Err(err) if is_held(&err) => err,
481        other => return other,
482    };
483    let deadline = match wait() {
484        LockWait::Immediately => return Err(err),
485        LockWait::Backoff { budget } => Some(start + budget),
486        LockWait::Indefinitely => None,
487    };
488    let mut tries: u32 = 0;
489    loop {
490        if deadline.is_some_and(|deadline| clock.now() >= deadline) {
491            return Err(err);
492        }
493        let delay = backoff_delay(key, tries, jitter);
494        tries = tries.saturating_add(1);
495        clock.sleep(match deadline {
496            Some(deadline) => delay.min(deadline.saturating_duration_since(clock.now())),
497            None => delay,
498        });
499        match attempt() {
500            Err(held) if is_held(&held) => err = held,
501            other => return other,
502        }
503    }
504}
505
506pub(crate) fn backoff_delay(lock_path: &Path, attempt: u32, jitter: &dyn LockJitter) -> Duration {
507    const INITIAL_MS: u64 = 1;
508    const CAP_MS: u64 = 50;
509    let shift = attempt.min(16);
510    let base_ms = (INITIAL_MS.saturating_mul(1_u64 << shift)).min(CAP_MS);
511    let span_ms = base_ms / 2 + 1;
512    let jitter_ms = (jitter.fraction(lock_path, attempt) * span_ms as f64) as u64;
513    Duration::from_millis(base_ms.saturating_add(jitter_ms))
514}
515
516/// Process recorded as the owner of a lock file.
517///
518/// With `core.lockfilePid` enabled, the lock owner writes `pid <n>` to a sidecar named after
519/// the lock (`index.lock` → `index~pid.lock`). Git and grit share this layout.
520#[derive(Debug, Clone, Copy, PartialEq, Eq)]
521pub struct LockHolder {
522    /// Process id read from the sidecar.
523    pub pid: u64,
524    /// Whether a process with [`Self::pid`] exists right now.
525    ///
526    /// `false` means the lock is stale. `true` is only a hint: the id may have been reused by
527    /// an unrelated process.
528    pub running: bool,
529}
530
531impl LockHolder {
532    /// Read the holder recorded for `lock_path` and probe whether it is still running.
533    ///
534    /// `lock_path` is the lock file itself (for example `.git/index.lock`).
535    ///
536    /// Returns `None` when no pid sidecar exists or it does not contain a process id.
537    #[must_use]
538    pub fn read(lock_path: &Path) -> Option<Self> {
539        let pid = read_lock_pid(&pid_path_for_lock(lock_path))?;
540        Some(Self {
541            pid,
542            running: is_process_running(pid),
543        })
544    }
545
546    /// Remove `lock_path` and its pid sidecar when [`Self::read`] reports a dead holder.
547    ///
548    /// Returns `true` when both files were removed (or were already absent after the lock).
549    /// Returns `false` when there is no sidecar, the holder is still running, or the sidecar
550    /// looks left over from an earlier holder (lock file newer than the sidecar).
551    ///
552    /// # Errors
553    ///
554    /// Returns [`io::Error`] when metadata or removal fails for reasons other than
555    /// [`io::ErrorKind::NotFound`].
556    pub fn remove_if_stale(lock_path: &Path) -> io::Result<bool> {
557        let Some(holder) = Self::read(lock_path) else {
558            return Ok(false);
559        };
560        if holder.running {
561            return Ok(false);
562        }
563        let pid_path = pid_path_for_lock(lock_path);
564        if lock_path.is_file() && pid_path.is_file() {
565            let lock_mtime = fs::metadata(lock_path)?.modified()?;
566            let pid_mtime = fs::metadata(&pid_path)?.modified()?;
567            if lock_mtime > pid_mtime {
568                return Ok(false);
569            }
570        }
571        for path in [lock_path, &pid_path] {
572            match fs::remove_file(path) {
573                Ok(()) => {}
574                Err(e) if e.kind() == io::ErrorKind::NotFound => {}
575                Err(e) => return Err(e),
576            }
577        }
578        Ok(true)
579    }
580}
581
582/// Whether grit writes pid sidecars for locks it creates.
583///
584/// Honors an explicit `core.lockfilePid=false`. When unset, grit defaults to `true` so crash
585/// recovery can detect stale index locks without requiring Git's opt-in.
586///
587/// When `config` is `None`, values are loaded from `git_dir` when provided.
588#[must_use]
589pub fn grit_lockfile_pid_enabled(config: Option<&ConfigSet>, git_dir: Option<&Path>) -> bool {
590    fn from_config(cfg: &ConfigSet) -> bool {
591        cfg.bool_with_default("core.lockfilepid", true)
592    }
593    if let Some(cfg) = config {
594        return from_config(cfg);
595    }
596    if let Some(dir) = git_dir {
597        if let Ok(cfg) = ConfigSet::load(
598            &Environment::empty(),
599            Some(dir),
600            &crate::config::LoadConfigOptions::standard(&Environment::empty(), Some(dir)),
601        ) {
602            return from_config(&cfg);
603        }
604    }
605    true
606}
607
608/// Path of the pid sidecar for `lock_path` (`name.lock` → `name~pid.lock`).
609pub fn pid_path_for_lock(lock_path: &Path) -> PathBuf {
610    let file_name = lock_path
611        .file_name()
612        .map(|s| s.to_string_lossy().into_owned())
613        .unwrap_or_else(|| "index.lock".to_owned());
614    let base = file_name.strip_suffix(".lock").unwrap_or(&file_name);
615    lock_path.with_file_name(format!("{base}~pid.lock"))
616}
617
618pub(crate) fn write_lock_pid_file(pid_path: &Path) -> io::Result<()> {
619    let mut file = OpenOptions::new()
620        .write(true)
621        .create(true)
622        .truncate(true)
623        .open(pid_path)?;
624    writeln!(file, "pid {}", std::process::id())?;
625    Ok(())
626}
627
628fn read_lock_pid(pid_path: &Path) -> Option<u64> {
629    let raw = fs::read_to_string(pid_path).ok()?;
630    let trimmed = raw.trim();
631    trimmed
632        .strip_prefix("pid ")
633        .unwrap_or(trimmed)
634        .trim()
635        .parse::<u64>()
636        .ok()
637}
638
639/// Whether a process with `pid` exists on this machine.
640pub(crate) fn is_process_running(pid: u64) -> bool {
641    if pid == 0 || pid > i32::MAX as u64 {
642        return false;
643    }
644    #[cfg(windows)]
645    {
646        use windows_sys::Win32::Foundation::CloseHandle;
647        use windows_sys::Win32::System::Threading::{
648            OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
649        };
650        // SAFETY: `OpenProcess` is called with a numeric pid and a read-only access mask.
651        unsafe {
652            let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid as u32);
653            if handle.is_null() {
654                return false;
655            }
656            CloseHandle(handle);
657            true
658        }
659    }
660    #[cfg(all(unix, target_os = "linux"))]
661    {
662        Path::new(&format!("/proc/{pid}")).exists()
663    }
664    #[cfg(all(unix, not(target_os = "linux")))]
665    {
666        use rustix::io::Errno;
667        use rustix::process::{test_kill_process, Pid};
668        let Some(pid) = Pid::from_raw(pid as i32) else {
669            return false;
670        };
671        match test_kill_process(pid) {
672            Ok(()) => true,
673            Err(Errno::SRCH) => false,
674            Err(Errno::PERM) => true,
675            Err(_) => false,
676        }
677    }
678}
679
680#[cfg(test)]
681mod tests {
682    use super::*;
683    use std::sync::Mutex;
684
685    struct FakeLockClock {
686        now: Mutex<Instant>,
687        sleeps: Mutex<Vec<Duration>>,
688    }
689
690    impl FakeLockClock {
691        fn new(start: Instant) -> Arc<Self> {
692            Arc::new(Self {
693                now: Mutex::new(start),
694                sleeps: Mutex::new(Vec::new()),
695            })
696        }
697
698        fn sleeps(&self) -> Vec<Duration> {
699            self.sleeps.lock().unwrap().clone()
700        }
701    }
702
703    impl LockClock for FakeLockClock {
704        fn now(&self) -> Instant {
705            *self.now.lock().unwrap()
706        }
707
708        fn sleep(&self, duration: Duration) {
709            self.sleeps.lock().unwrap().push(duration);
710            *self.now.lock().unwrap() += duration;
711        }
712    }
713
714    #[test]
715    fn drop_without_commit_removes_own_lock() {
716        let dir = tempfile::tempdir().unwrap();
717        let lock = dir.path().join("resource.lock");
718        {
719            let _lock = LockFile::acquire(&lock, LockWait::Immediately).unwrap();
720            assert!(lock.is_file());
721        }
722        assert!(!lock.exists());
723    }
724
725    #[test]
726    fn commit_to_replaces_target() {
727        let dir = tempfile::tempdir().unwrap();
728        let target = dir.path().join("resource");
729        let lock_path = dir.path().join("resource.lock");
730        let mut lock = LockFile::acquire(&lock_path, LockWait::Immediately).unwrap();
731        lock.write_all(b"payload\n").unwrap();
732        lock.commit_to(&target).unwrap();
733        assert!(!lock_path.exists());
734        assert_eq!(fs::read_to_string(&target).unwrap(), "payload\n");
735    }
736
737    struct FixedJitter(f64);
738
739    impl LockJitter for FixedJitter {
740        fn fraction(&self, _lock_path: &Path, _attempt: u32) -> f64 {
741            self.0
742        }
743    }
744
745    #[test]
746    fn held_when_budget_exhausted() {
747        let dir = tempfile::tempdir().unwrap();
748        let lock_path = dir.path().join("x.lock");
749        fs::write(&lock_path, b"foreign").unwrap();
750        let start = Instant::now();
751        let clock = FakeLockClock::new(start);
752        let err = match LockFile::acquire_with_clock(
753            &lock_path,
754            LockWait::Backoff {
755                budget: Duration::from_millis(10),
756            },
757            clock.clone(),
758            Arc::new(FixedJitter(0.5)),
759        ) {
760            Err(e) => e,
761            Ok(_) => panic!("expected lock held error"),
762        };
763        assert!(matches!(err, LockError::Held { .. }));
764        assert!(lock_path.is_file());
765        assert_eq!(fs::read_to_string(&lock_path).unwrap(), "foreign");
766        assert!(!clock.sleeps().is_empty());
767    }
768
769    #[test]
770    fn pid_sidecar_path_replaces_lock_suffix() {
771        assert_eq!(
772            pid_path_for_lock(Path::new("/r/.git/index.lock")),
773            Path::new("/r/.git/index~pid.lock")
774        );
775        assert_eq!(
776            pid_path_for_lock(Path::new("/r/.git/refs/heads/main.lock")),
777            Path::new("/r/.git/refs/heads/main~pid.lock")
778        );
779        assert_eq!(
780            pid_path_for_lock(Path::new("/r/odd")),
781            Path::new("/r/odd~pid.lock")
782        );
783    }
784
785    #[test]
786    fn remove_if_stale_skips_when_lock_is_newer_than_sidecar() {
787        use std::thread;
788        use std::time::Duration;
789
790        let dir = tempfile::tempdir().unwrap();
791        let lock_path = dir.path().join("index.lock");
792        fs::write(&lock_path, b"").unwrap();
793        let pid_path = pid_path_for_lock(&lock_path);
794        fs::write(&pid_path, "pid 999999999\n").unwrap();
795        thread::sleep(Duration::from_millis(20));
796        fs::write(&lock_path, b"replaced").unwrap();
797
798        assert!(!LockHolder::remove_if_stale(&lock_path).unwrap());
799        assert!(lock_path.is_file());
800        assert!(pid_path.is_file());
801    }
802
803    #[test]
804    fn held_converts_to_typed_error_with_holder() {
805        let dir = tempfile::tempdir().unwrap();
806        let lock_path = dir.path().join("index.lock");
807        fs::write(&lock_path, b"").unwrap();
808        fs::write(
809            dir.path().join("index~pid.lock"),
810            format!("pid {}\n", std::process::id()),
811        )
812        .unwrap();
813        let err = LockFile::acquire(&lock_path, LockWait::Immediately)
814            .err()
815            .expect("held");
816        match crate::error::Error::from(err) {
817            crate::error::Error::LockHeld(crate::error::LockHeldError { path, holder }) => {
818                assert_eq!(path, lock_path);
819                assert_eq!(
820                    holder,
821                    Some(LockHolder {
822                        pid: u64::from(std::process::id()),
823                        running: true,
824                    })
825                );
826            }
827            other => panic!("expected LockHeld, got {other:?}"),
828        }
829    }
830
831    #[test]
832    fn io_failure_converts_to_io_error() {
833        let err = LockError::Io {
834            path: PathBuf::from("x.lock"),
835            source: io::Error::from(io::ErrorKind::PermissionDenied),
836        };
837        assert!(matches!(
838            crate::error::Error::from(err),
839            crate::error::Error::Io(e) if e.kind() == io::ErrorKind::PermissionDenied
840        ));
841    }
842
843    #[test]
844    fn rollback_removes_own_lock() {
845        let dir = tempfile::tempdir().unwrap();
846        let lock = dir.path().join("resource.lock");
847        let lock_file = LockFile::acquire(&lock, LockWait::Immediately).unwrap();
848        assert!(lock.is_file());
849        lock_file.rollback();
850        assert!(!lock.exists());
851    }
852
853    #[test]
854    fn files_ref_lock_timeout_uses_milliseconds() {
855        let mut cfg = ConfigSet::new();
856        cfg.add_command_override("core.filesreflocktimeout", "100")
857            .expect("set timeout");
858        assert_eq!(LockWait::parse_files_ref_lock_timeout_ms(Some(&cfg)), 100);
859        match LockWait::files_ref_lock(Some(&cfg)) {
860            LockWait::Backoff { budget } => {
861                assert_eq!(budget, Duration::from_millis(100));
862            }
863            other => panic!("expected backoff, got {other:?}"),
864        }
865    }
866
867    #[test]
868    fn files_ref_lock_timeout_negative_retries_indefinitely() {
869        let mut cfg = ConfigSet::new();
870        cfg.add_command_override("core.filesreflocktimeout", "-1")
871            .expect("set timeout");
872        assert!(matches!(
873            LockWait::files_ref_lock(Some(&cfg)),
874            LockWait::Indefinitely
875        ));
876    }
877
878    #[test]
879    fn indefinite_wait_succeeds_when_lock_cleared() {
880        let dir = tempfile::tempdir().unwrap();
881        let lock_path = dir.path().join("x.lock");
882        fs::write(&lock_path, b"foreign").unwrap();
883        let clock = FakeLockClock::new(Instant::now());
884        let lock_path_thread = lock_path.clone();
885        std::thread::spawn(move || {
886            std::thread::sleep(Duration::from_millis(5));
887            let _ = fs::remove_file(&lock_path_thread);
888        });
889        let _guard = LockFile::acquire_with_clock(
890            &lock_path,
891            LockWait::Indefinitely,
892            clock,
893            Arc::new(FixedJitter(0.0)),
894        )
895        .expect("indefinite wait should eventually acquire");
896    }
897
898    #[test]
899    fn retry_while_held_resolves_wait_lazily_and_counts_attempt_time() {
900        let key = Path::new("refs");
901        let jitter = FixedJitter(0.0);
902        let clock = FakeLockClock::new(Instant::now());
903
904        let ok: Result<u32, u32> = retry_while_held(
905            key,
906            || panic!("wait resolved without contention"),
907            clock.as_ref(),
908            &jitter,
909            || Ok(7),
910            |_| true,
911        );
912        assert_eq!(ok, Ok(7));
913
914        let mut calls = 0;
915        let other = retry_while_held(
916            key,
917            || LockWait::Indefinitely,
918            clock.as_ref(),
919            &jitter,
920            || {
921                calls += 1;
922                Err::<(), _>("io")
923            },
924            |e| *e == "held",
925        );
926        assert_eq!((other, calls), (Err("io"), 1));
927        assert!(clock.sleeps().is_empty());
928
929        // The first attempt itself takes the whole budget, so nothing is retried.
930        let mut calls = 0;
931        let slow = retry_while_held(
932            key,
933            || LockWait::Backoff {
934                budget: Duration::from_millis(10),
935            },
936            clock.as_ref(),
937            &jitter,
938            || {
939                calls += 1;
940                clock.sleep(Duration::from_millis(10));
941                Err::<(), _>(calls)
942            },
943            |_| true,
944        );
945        assert_eq!(slow, Err(1));
946
947        let mut calls = 0;
948        let later = retry_while_held(
949            key,
950            || LockWait::Backoff {
951                budget: Duration::from_secs(1),
952            },
953            clock.as_ref(),
954            &jitter,
955            || {
956                calls += 1;
957                if calls < 4 {
958                    Err(calls)
959                } else {
960                    Ok(calls)
961                }
962            },
963            |_| true,
964        );
965        assert_eq!(later, Ok(4));
966    }
967}