1use crate::file_identity;
2use std::{
3 fs::{File, OpenOptions, TryLockError},
4 path::{Path, PathBuf},
5 time::Duration,
6};
7use workyard_core::{Control, Problem};
8
9const RETRY_INTERVAL: Duration = Duration::from_millis(20);
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum LockMode {
14 Shared,
16 Exclusive,
18}
19
20impl LockMode {
21 fn try_lock(self, file: &File) -> Result<(), TryLockError> {
22 match self {
23 Self::Shared => file.try_lock_shared(),
24 Self::Exclusive => file.try_lock(),
25 }
26 }
27}
28
29pub struct Lock {
31 file: File,
32 path: PathBuf,
33}
34
35impl Lock {
36 pub fn acquire(path: &Path, shared: bool) -> Result<Self, Problem> {
38 let mode = if shared {
39 LockMode::Shared
40 } else {
41 LockMode::Exclusive
42 };
43 Self::acquire_mode(path, mode)
44 }
45
46 pub fn acquire_mode(path: &Path, mode: LockMode) -> Result<Self, Problem> {
48 let file = OpenOptions::new()
49 .create(true)
50 .truncate(false)
51 .read(true)
52 .write(true)
53 .open(path)
54 .map_err(|e| Problem::io(format!("Open lock {path:?}"), e))?;
55
56 mode.try_lock(&file).map_err(|error| match error {
57 TryLockError::WouldBlock => Problem::new(
58 workyard_core::ProblemCode::ResourceBusy,
59 format!("Resource is busy: {path:?}"),
60 )
61 .remedy(
62 "Wait for the active Workyard operation to finish, then retry. Do not delete lockfiles.",
63 ),
64 TryLockError::Error(error) => Problem::io(format!("Lock {path:?}"), error),
65 })?;
66
67 let lock = Self {
68 file,
69 path: path.into(),
70 };
71
72 lock.verify()?;
73
74 Ok(lock)
75 }
76
77 pub fn read_existing(path: &Path) -> Result<Self, Problem> {
79 let file =
80 File::open(path).map_err(|e| Problem::io(format!("Open existing gate {path:?}"), e))?;
81
82 file.try_lock_shared().map_err(|error| match error {
83 TryLockError::WouldBlock => Problem::new(
84 workyard_core::ProblemCode::ResourceBusy,
85 format!("Resource is busy: {path:?}"),
86 ),
87 TryLockError::Error(e) => Problem::io("Read-lock existing gate", e),
88 })?;
89
90 let lock = Self {
91 file,
92 path: path.into(),
93 };
94
95 lock.verify()?;
96
97 Ok(lock)
98 }
99
100 pub fn wait_existing(path: &Path, mode: LockMode) -> Result<Self, Problem> {
103 smol::block_on(Self::wait_existing_with_control(
104 path,
105 mode,
106 &Control::default(),
107 ))
108 }
109
110 pub async fn wait_existing_with_control(
112 path: &Path,
113 mode: LockMode,
114 control: &Control,
115 ) -> Result<Self, Problem> {
116 let file = OpenOptions::new()
117 .read(true)
118 .write(mode == LockMode::Exclusive)
119 .open(path)
120 .map_err(|error| Problem::io(format!("Open workspace gate {path:?}"), error))?;
121
122 loop {
123 control.check()?;
124 match mode.try_lock(&file) {
125 Ok(()) => break,
126 Err(TryLockError::WouldBlock) => {}
127 Err(TryLockError::Error(error)) => {
128 return Err(Problem::io(format!("Lock workspace gate {path:?}"), error));
129 }
130 }
131 smol::Timer::after(RETRY_INTERVAL).await;
132 }
133
134 let guard = Self {
135 file,
136 path: path.into(),
137 };
138 guard.verify()?;
139 Ok(guard)
140 }
141
142 pub async fn wait(path: &Path, control: &Control) -> Result<Self, Problem> {
144 loop {
145 control.check()?;
146
147 match Self::acquire_mode(path, LockMode::Exclusive) {
148 Ok(lock) => return Ok(lock),
149 Err(error) if error.code == workyard_core::ProblemCode::ResourceBusy => {}
150 Err(error) => return Err(error),
151 }
152
153 smol::Timer::after(RETRY_INTERVAL).await;
154 }
155 }
156
157 pub fn verify(&self) -> Result<(), Problem> {
159 let named = File::open(&self.path).map_err(|e| Problem::io("Open named lock", e))?;
160
161 let same = file_identity(&self.file)? == file_identity(&named)?;
162 if !same {
163 return Err(Problem::new(
164 workyard_core::ProblemCode::StaleIdentity,
165 format!("Lock was replaced: {:?}", self.path),
166 )
167 .remedy(
168 "Stop conflicting processes and inspect the state directory before retrying.",
169 ));
170 }
171
172 Ok(())
173 }
174}
175
176impl Drop for Lock {
177 fn drop(&mut self) {
178 let _ = self.file.unlock();
182 }
183}
184
185#[cfg(all(test, unix))]
186mod tests {
187 #[test]
188 fn dropping_guard_releases_lock_even_with_a_duplicate_descriptor() {
189 let directory = tempfile::tempdir().unwrap();
190 let path = directory.path().join("resource.lock");
191
192 let guard = super::Lock::acquire(&path, false).unwrap();
193
194 let inherited = guard.file.try_clone().unwrap();
196 drop(guard);
197
198 let next = super::Lock::acquire(&path, false).unwrap();
199 drop(inherited);
200 next.verify().unwrap();
201 }
202}