1use std::fs;
2use std::io;
3use std::path::{Path, PathBuf};
4
5use log::{debug, error};
6
7pub struct FileLock {
10 lock_path: PathBuf,
11 #[cfg(unix)]
12 _file: fs::File,
13}
14
15impl FileLock {
16 pub fn acquire(path: &Path) -> io::Result<Self> {
20 let mut lock_name = path.file_name().unwrap_or_default().to_os_string();
21 lock_name.push(".purple_lock");
22 let lock_path = path.with_file_name(lock_name);
23
24 #[cfg(unix)]
25 {
26 use std::os::unix::fs::OpenOptionsExt;
27 let file = fs::OpenOptions::new()
28 .write(true)
29 .create(true)
30 .truncate(false)
31 .mode(0o600)
32 .open(&lock_path)?;
33
34 let ret =
38 unsafe { libc::flock(std::os::unix::io::AsRawFd::as_raw_fd(&file), libc::LOCK_EX) };
39 if ret != 0 {
40 return Err(io::Error::last_os_error());
41 }
42
43 Ok(FileLock {
44 lock_path,
45 _file: file,
46 })
47 }
48
49 #[cfg(not(unix))]
50 {
51 let file = fs::OpenOptions::new()
53 .write(true)
54 .create_new(true)
55 .open(&lock_path)
56 .or_else(|_| {
57 std::thread::sleep(std::time::Duration::from_millis(100));
59 fs::remove_file(&lock_path).ok();
60 fs::OpenOptions::new()
61 .write(true)
62 .create_new(true)
63 .open(&lock_path)
64 })?;
65 Ok(FileLock {
66 lock_path,
67 _file: file,
68 })
69 }
70 }
71}
72
73impl Drop for FileLock {
74 fn drop(&mut self) {
75 let _ = &self.lock_path;
83 }
84}
85
86pub fn atomic_write(path: &Path, content: &[u8]) -> io::Result<()> {
90 debug!("Atomic write: {}", path.display());
91 if let Some(parent) = path.parent() {
93 fs::create_dir_all(parent)?;
94 }
95
96 let mut tmp_name = path.file_name().unwrap_or_default().to_os_string();
97 tmp_name.push(format!(".purple_tmp.{}", std::process::id()));
98 let tmp_path = path.with_file_name(tmp_name);
99
100 #[cfg(unix)]
101 {
102 use std::io::Write;
103 use std::os::unix::fs::OpenOptionsExt;
104 let open = || {
107 fs::OpenOptions::new()
108 .write(true)
109 .create_new(true)
110 .mode(0o600)
111 .open(&tmp_path)
112 };
113 let mut file = match open() {
114 Ok(f) => f,
115 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
116 let _ = fs::remove_file(&tmp_path);
117 open().map_err(|e| {
118 io::Error::new(
119 e.kind(),
120 format!("Failed to create temp file {}: {}", tmp_path.display(), e),
121 )
122 })?
123 }
124 Err(e) => {
125 return Err(io::Error::new(
126 e.kind(),
127 format!("Failed to create temp file {}: {}", tmp_path.display(), e),
128 ));
129 }
130 };
131 if let Err(e) = file.write_all(content) {
132 drop(file);
133 let _ = fs::remove_file(&tmp_path);
134 return Err(e);
135 }
136 if let Err(e) = file.sync_all() {
137 drop(file);
138 let _ = fs::remove_file(&tmp_path);
139 return Err(e);
140 }
141 }
142
143 #[cfg(not(unix))]
144 {
145 if let Err(e) = fs::write(&tmp_path, content) {
146 let _ = fs::remove_file(&tmp_path);
147 return Err(e);
148 }
149 match fs::File::open(&tmp_path) {
151 Ok(f) => {
152 if let Err(e) = f.sync_all() {
153 let _ = fs::remove_file(&tmp_path);
154 return Err(e);
155 }
156 }
157 Err(e) => {
158 let _ = fs::remove_file(&tmp_path);
159 return Err(e);
160 }
161 }
162 }
163
164 let result = fs::rename(&tmp_path, path);
165 if let Err(ref err) = result {
166 let _ = fs::remove_file(&tmp_path);
167 error!("[purple] Atomic write failed: {}: {err}", path.display());
168 return result;
169 }
170
171 #[cfg(unix)]
178 if let Some(parent) = path.parent() {
179 if let Err(err) = fs::File::open(parent).and_then(|d| d.sync_all()) {
180 debug!(
181 "[purple] parent dir sync after rename failed (rename succeeded): {}: {err}",
182 parent.display()
183 );
184 }
185 }
186
187 result
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193
194 #[test]
195 fn file_lock_does_not_remove_lockfile_on_drop() {
196 let dir = tempfile::tempdir().expect("tempdir");
201 let target = dir.path().join("config");
202 let lockfile = dir.path().join("config.purple_lock");
203
204 {
205 let _lock = FileLock::acquire(&target).expect("acquire");
206 assert!(lockfile.exists(), "lockfile must be created on acquire");
207 }
208 assert!(
209 lockfile.exists(),
210 "lockfile must remain after drop (not unlinked)"
211 );
212 }
213
214 #[test]
215 fn atomic_write_creates_file_with_content() {
216 let dir = tempfile::tempdir().expect("tempdir");
217 let target = dir.path().join("file");
218 atomic_write(&target, b"hello\n").expect("write");
219 let content = std::fs::read_to_string(&target).expect("read");
220 assert_eq!(content, "hello\n");
221 }
222
223 #[test]
224 fn atomic_write_replaces_existing_file() {
225 let dir = tempfile::tempdir().expect("tempdir");
226 let target = dir.path().join("file");
227 std::fs::write(&target, b"old").expect("write old");
228 atomic_write(&target, b"new").expect("write new");
229 let content = std::fs::read_to_string(&target).expect("read");
230 assert_eq!(content, "new");
231 }
232
233 #[test]
234 fn atomic_write_leaves_no_temp_file() {
235 let dir = tempfile::tempdir().expect("tempdir");
236 let target = dir.path().join("file");
237 atomic_write(&target, b"content").expect("write");
238 let stem = target.file_name().unwrap().to_string_lossy().to_string();
239 let leftovers: Vec<_> = std::fs::read_dir(dir.path())
240 .unwrap()
241 .filter_map(|e| e.ok())
242 .filter(|e| {
243 let n = e.file_name().to_string_lossy().to_string();
244 n.starts_with(&format!("{}.purple_tmp.", stem))
245 })
246 .collect();
247 assert!(
248 leftovers.is_empty(),
249 "temp file leaked after successful write: {:?}",
250 leftovers.iter().map(|e| e.path()).collect::<Vec<_>>()
251 );
252 }
253}