agent_hub_runtime/core/repo_lock.rs
1use anyhow::{Context, Result};
2use fs2::FileExt;
3use std::fs::{File, OpenOptions};
4use std::io::{Seek, SeekFrom, Write};
5use std::time::{Duration, Instant};
6
7use super::central_repo;
8
9/// Filename used for the central-repository write lock.
10///
11/// The lock lives in `base_dir()` (the parent of `skills_dir()`), not inside
12/// `skills_dir` itself. `skills_dir` gets renamed/recreated during clone and
13/// reclone flows, and on Windows mandatory file locking makes it impossible
14/// to rename a directory that contains a file held with an exclusive lock —
15/// see issue #99 (os error 5 / "Access is denied").
16const LOCK_FILE_NAME: &str = ".agent-hub.lock";
17
18/// How long a user-initiated ("foreground") operation waits for the central
19/// repository lock before giving up with a "busy" error. Background work holds
20/// the lock only briefly per skill, but an auto-backup `git push` can hold it
21/// for ~10–15s, so we wait comfortably longer than the longest expected
22/// background hold. Without this wait, a foreground install/update/tag/delete
23/// that happened to collide with a background update check or backup failed
24/// instantly with "skills repository is busy" (issues #196, #220, #232).
25pub const FOREGROUND_WAIT: Duration = Duration::from_secs(20);
26
27/// Poll cadence while waiting for the lock. Kept below the yield the background
28/// per-skill loops insert between releases (see `skill_auto_updater` and the
29/// tray check) so a waiting foreground op reliably wins the lock during that
30/// window instead of being starved by the background re-acquiring immediately.
31const POLL_INTERVAL: Duration = Duration::from_millis(50);
32
33pub struct RepoLock {
34 file: File,
35}
36
37impl RepoLock {
38 /// Acquire the lock, failing immediately if it is already held. Used by
39 /// background loops that prefer to skip a unit of work and retry on the
40 /// next round rather than block a user-initiated operation.
41 pub fn acquire(operation: &str) -> Result<Self> {
42 let file = open_lock_file()?;
43 file.try_lock_exclusive()
44 .with_context(|| format!("skills repository is busy: {operation}"))?;
45 Self::stamp(file, operation)
46 }
47
48 /// Acquire the lock, waiting up to `timeout` for a concurrent holder to
49 /// release it before reporting the repository as busy. Used by
50 /// user-initiated operations so transient contention with background work
51 /// (update checks, auto-backup) surfaces as a short wait, not an error.
52 pub fn acquire_blocking(operation: &str, timeout: Duration) -> Result<Self> {
53 let file = open_lock_file()?;
54 let start = Instant::now();
55 loop {
56 match file.try_lock_exclusive() {
57 Ok(()) => return Self::stamp(file, operation),
58 // Retry on any error (not just `WouldBlock`): on Windows
59 // `LockFileEx` reports contention as `ERROR_LOCK_VIOLATION`,
60 // which does not map to `ErrorKind::WouldBlock`, so gating on
61 // the kind would defeat the wait on the very platform that
62 // needs it most.
63 Err(err) => {
64 if start.elapsed() >= timeout {
65 return Err(err)
66 .with_context(|| format!("skills repository is busy: {operation}"));
67 }
68 std::thread::sleep(POLL_INTERVAL);
69 }
70 }
71 }
72 }
73
74 /// Convenience for user-initiated operations: wait up to [`FOREGROUND_WAIT`].
75 pub fn acquire_foreground(operation: &str) -> Result<Self> {
76 Self::acquire_blocking(operation, FOREGROUND_WAIT)
77 }
78
79 /// Records who holds the lock, so a "repository is busy" report can be
80 /// traced back to the operation sitting on it.
81 ///
82 /// Deliberately not fsynced. Mutual exclusion comes from `flock`, never from
83 /// this file's contents, so a stamp lost to a crash costs nothing — whereas
84 /// `File::sync_all` is `fcntl(F_FULLFSYNC)` on macOS, which flushes the
85 /// whole APFS volume's cache and bills every page of it, including other
86 /// processes' dirty pages, to whoever called it. Phase B of
87 /// `check_all_skill_updates` takes this lock once per skill (deliberately —
88 /// see the comment there), so on a library of ~75 skills that was 75
89 /// whole-volume barriers per round: one hour of it was reported by the
90 /// system as 2.1 GB of "file backed memory dirtied", 24x over the
91 /// disk-writes limit, with the truncate and write above stalled behind the
92 /// same barriers.
93 fn stamp(mut file: File, operation: &str) -> Result<Self> {
94 file.set_len(0)?;
95 file.seek(SeekFrom::Start(0))?;
96 writeln!(
97 file,
98 "pid={}\nhostname={}\noperation={}\nstart_time={}",
99 std::process::id(),
100 std::env::var("HOSTNAME")
101 .or_else(|_| std::env::var("COMPUTERNAME"))
102 .unwrap_or_else(|_| "unknown".to_string()),
103 operation,
104 chrono::Utc::now().to_rfc3339()
105 )?;
106 Ok(Self { file })
107 }
108}
109
110fn open_lock_file() -> Result<File> {
111 let base = central_repo::base_dir();
112 std::fs::create_dir_all(&base)?;
113 let lock_path = base.join(LOCK_FILE_NAME);
114 OpenOptions::new()
115 .create(true)
116 .truncate(false)
117 .read(true)
118 .write(true)
119 .open(&lock_path)
120 .with_context(|| format!("failed to open repo lock {}", lock_path.display()))
121}
122
123impl Drop for RepoLock {
124 fn drop(&mut self) {
125 let _ = FileExt::unlock(&self.file);
126 }
127}
128
129#[cfg(test)]
130mod tests;