link_cli/store_lock/
pid_lock.rs1use std::fs;
12use std::io::Write;
13use std::path::{Path, PathBuf};
14use std::time::{Duration, SystemTime};
15
16use super::owner::{Liveness, LockOwner};
17use crate::diagnostics;
18use crate::storage::lock::unique_token;
19
20const UNOWNED_GRACE: Duration = Duration::from_secs(10);
24const OWNER_FILE: &str = "owner";
25const ERROR_ACCESS_DENIED: i32 = 5;
26const ERROR_SHARING_VIOLATION: i32 = 32;
27const ERROR_LOCK_VIOLATION: i32 = 33;
28
29pub fn lock_dir_path(store: &Path) -> PathBuf {
31 sibling(store, ".lock.d")
32}
33
34#[derive(Debug)]
36pub struct PidLock {
37 dir: PathBuf,
38 token: String,
39 trace: bool,
40}
41
42pub enum Attempt {
44 Acquired(PidLock),
45 Held(Option<LockOwner>),
47}
48
49pub fn read_owner(dir: &Path) -> Option<LockOwner> {
51 LockOwner::parse(&fs::read_to_string(dir.join(OWNER_FILE)).ok()?)
52}
53
54pub fn stale_reason(dir: &Path, owner: Option<&LockOwner>) -> Option<String> {
56 match owner {
57 Some(owner) => match owner.liveness() {
58 Liveness::Gone(reason) => Some(reason),
59 Liveness::Alive | Liveness::Unknown(_) => None,
60 },
61 None => {
62 let age = fs::metadata(dir)
63 .and_then(|metadata| metadata.modified())
64 .ok()
65 .and_then(|modified| SystemTime::now().duration_since(modified).ok())?;
66 (age >= UNOWNED_GRACE)
67 .then(|| format!("no owner record for {} s", UNOWNED_GRACE.as_secs()))
68 }
69 }
70}
71
72pub fn try_acquire(dir: &Path, trace: bool) -> std::io::Result<Attempt> {
74 if let Some(parent) = dir.parent().filter(|parent| !parent.as_os_str().is_empty()) {
75 fs::create_dir_all(parent)?;
76 }
77 let token = unique_token();
78 let owner = LockOwner::current(&token);
79 let mut last_error = None;
80 for _ in 0..4 {
81 let staging = sibling(dir, &format!(".{}.{}.tmp", owner.pid, unique_token()));
82 fs::create_dir(&staging)?;
83 let published = write_owner(&staging, &owner).and_then(|()| fs::rename(&staging, dir));
84 let error = match published {
85 Ok(()) => {
86 return Ok(Attempt::Acquired(PidLock {
87 dir: dir.to_path_buf(),
88 token,
89 trace,
90 }))
91 }
92 Err(error) => error,
93 };
94 let _ = retry_cleanup(|| fs::remove_dir_all(&staging), trace);
95 if fs::symlink_metadata(dir).is_err() {
96 last_error = Some(error);
98 continue;
99 }
100 let holder = read_owner(dir);
101 match stale_reason(dir, holder.as_ref()) {
102 Some(reason) => {
103 if trace {
104 diagnostics::stderr!("[TRACE] Breaking stale lock {}: {reason}", dir.display());
105 }
106 break_stale(dir, holder.as_ref(), trace);
107 }
108 None => return Ok(Attempt::Held(holder)),
109 }
110 }
111 match last_error {
112 Some(error) => Err(error),
113 None => Ok(Attempt::Held(read_owner(dir))),
114 }
115}
116
117fn break_stale(dir: &Path, expected: Option<&LockOwner>, trace: bool) {
122 let tombstone = sibling(
123 dir,
124 &format!(".{}.{}.stale", std::process::id(), unique_token()),
125 );
126 if fs::rename(dir, &tombstone).is_err() {
127 return;
128 }
129 let moved = read_owner(&tombstone);
130 if moved.as_ref().map(|owner| &owner.token) == expected.map(|owner| &owner.token) {
131 let _ = retry_cleanup(|| fs::remove_dir_all(&tombstone), trace);
132 } else if fs::rename(&tombstone, dir).is_err() {
133 }
136}
137
138fn write_owner(dir: &Path, owner: &LockOwner) -> std::io::Result<()> {
139 let mut file = fs::File::create(dir.join(OWNER_FILE))?;
140 file.write_all(owner.to_record().as_bytes())?;
141 file.sync_all()
142}
143
144impl PidLock {
145 pub fn path(&self) -> &Path {
146 &self.dir
147 }
148}
149
150impl Drop for PidLock {
151 fn drop(&mut self) {
152 if read_owner(&self.dir).is_some_and(|owner| owner.token == self.token) {
154 let tombstone = sibling(&self.dir, &format!(".{}.released", self.token));
155 if retry_cleanup(|| fs::rename(&self.dir, &tombstone), self.trace).is_ok() {
156 let _ = retry_cleanup(|| fs::remove_dir_all(&tombstone), self.trace);
157 }
158 }
159 }
160}
161
162fn retry_cleanup(
163 mut cleanup: impl FnMut() -> std::io::Result<()>,
164 trace: bool,
165) -> std::io::Result<()> {
166 let mut delay_ms = 5;
167 loop {
168 let error = match cleanup() {
169 Ok(()) => return Ok(()),
170 Err(error) => error,
171 };
172 if trace {
173 diagnostics::stderr!("[TRACE] PID-lock cleanup: {error}");
174 }
175 if !cfg!(windows)
178 || delay_ms > 40
179 || !matches!(
180 error.raw_os_error(),
181 Some(ERROR_ACCESS_DENIED | ERROR_SHARING_VIOLATION | ERROR_LOCK_VIOLATION)
182 )
183 {
184 return Err(error);
185 }
186 std::thread::sleep(Duration::from_millis(delay_ms));
187 delay_ms *= 2;
188 }
189}
190
191fn sibling(path: &Path, suffix: &str) -> PathBuf {
192 let mut name = path.as_os_str().to_owned();
193 name.push(suffix);
194 PathBuf::from(name)
195}
196
197#[cfg(test)]
198mod tests {
199 use super::retry_cleanup;
200 use std::io::Error;
201
202 #[test]
203 fn pid_cleanup_retries_windows_sharing_errors_only() {
204 let mut attempts = 0;
205 let result = retry_cleanup(
206 || {
207 attempts += 1;
208 if attempts == 1 {
209 return Err(Error::from_raw_os_error(32));
210 }
211 Ok(())
212 },
213 false,
214 );
215 assert_eq!(result.is_ok(), cfg!(windows));
216 assert_eq!(attempts, if cfg!(windows) { 2 } else { 1 });
217
218 attempts = 0;
219 let error = retry_cleanup(
220 || {
221 attempts += 1;
222 Err(Error::from_raw_os_error(2))
223 },
224 false,
225 )
226 .unwrap_err();
227 assert_eq!(error.raw_os_error(), Some(2));
228 assert_eq!(attempts, 1);
229 }
230}