1use std::{io, path::Path};
4
5#[derive(Debug)]
7pub struct DurableReplaceError {
8 renamed: bool,
9 source: io::Error,
10}
11
12impl DurableReplaceError {
13 pub fn renamed(&self) -> bool {
16 self.renamed
17 }
18
19 fn new(source: io::Error, renamed: bool) -> Self {
20 Self { renamed, source }
21 }
22}
23
24impl std::fmt::Display for DurableReplaceError {
25 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26 self.source.fmt(f)
27 }
28}
29
30impl std::error::Error for DurableReplaceError {
31 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
32 Some(&self.source)
33 }
34}
35
36impl From<DurableReplaceError> for io::Error {
37 fn from(error: DurableReplaceError) -> Self {
38 error.source
39 }
40}
41
42pub fn durable_replace(from: &Path, to: &Path) -> Result<(), DurableReplaceError> {
47 durable_replace_impl(from, to, || Ok(()))
48}
49
50#[cfg(feature = "test-support")]
54pub fn durable_replace_with_rename_hook(
55 from: &Path,
56 to: &Path,
57 after_rename: impl FnOnce() -> io::Result<()>,
58) -> Result<(), DurableReplaceError> {
59 durable_replace_impl(from, to, after_rename)
60}
61
62fn durable_replace_impl(
63 from: &Path,
64 to: &Path,
65 after_rename: impl FnOnce() -> io::Result<()>,
66) -> Result<(), DurableReplaceError> {
67 #[cfg(unix)]
68 {
69 std::fs::rename(from, to).map_err(|error| DurableReplaceError::new(error, false))?;
70 after_rename().map_err(|error| DurableReplaceError::new(error, true))?;
71 let parent = to.parent().ok_or_else(|| {
72 DurableReplaceError::new(
73 io::Error::new(io::ErrorKind::InvalidInput, "destination has no parent"),
74 true,
75 )
76 })?;
77 std::fs::File::open(parent)
78 .and_then(|directory| directory.sync_all())
79 .map_err(|error| DurableReplaceError::new(error, true))
80 }
81 #[cfg(windows)]
82 {
83 windows_replace_with_operation(
84 from,
85 to,
86 || windows_move(from, to).and_then(|()| after_rename()),
87 windows_path_identity,
88 )
89 }
90 #[cfg(not(any(unix, windows)))]
91 {
92 let _ = (from, to, after_rename);
93 Err(DurableReplaceError::new(
94 io::Error::new(
95 io::ErrorKind::Unsupported,
96 "durable replacement unsupported",
97 ),
98 false,
99 ))
100 }
101}
102
103#[cfg(windows)]
104#[derive(Clone, Copy, PartialEq, Eq)]
105struct FileIdentity {
106 volume: u32,
107 index: u64,
108}
109
110#[cfg(windows)]
111fn windows_open_identity(path: &Path) -> io::Result<std::fs::File> {
112 use std::os::windows::fs::OpenOptionsExt;
113 use windows_sys::Win32::Storage::FileSystem::{
114 FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
115 };
116 std::fs::OpenOptions::new()
117 .access_mode(0)
118 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
119 .open(path)
120}
121
122#[cfg(windows)]
123#[allow(unsafe_code)]
124fn windows_file_identity(file: &std::fs::File) -> io::Result<FileIdentity> {
125 use std::os::windows::io::AsRawHandle;
126 use windows_sys::Win32::Storage::FileSystem::{
127 GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
128 };
129 let mut information: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
131 if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) } == 0 {
134 return Err(io::Error::last_os_error());
135 }
136 Ok(FileIdentity {
137 volume: information.dwVolumeSerialNumber,
138 index: (u64::from(information.nFileIndexHigh) << 32) | u64::from(information.nFileIndexLow),
139 })
140}
141
142#[cfg(windows)]
143fn windows_path_identity(path: &Path) -> io::Result<Option<FileIdentity>> {
144 match windows_open_identity(path) {
145 Ok(file) => windows_file_identity(&file).map(Some),
146 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
147 Err(error) => Err(error),
148 }
149}
150
151#[cfg(windows)]
152fn windows_replace_with_operation(
153 from: &Path,
154 to: &Path,
155 operation: impl FnOnce() -> io::Result<()>,
156 inspect: impl Fn(&Path) -> io::Result<Option<FileIdentity>>,
157) -> Result<(), DurableReplaceError> {
158 let source =
159 windows_open_identity(from).map_err(|error| DurableReplaceError::new(error, false))?;
160 let identity =
161 windows_file_identity(&source).map_err(|error| DurableReplaceError::new(error, false))?;
162 let result = operation().map_err(|error| {
163 let renamed = match (inspect(from), inspect(to)) {
164 (Ok(None), Ok(Some(destination))) if destination == identity => true,
165 (Ok(Some(original)), Ok(_)) if original == identity => false,
166 _ => true,
171 };
172 DurableReplaceError::new(error, renamed)
173 });
174 drop(source);
177 result
178}
179
180#[cfg(windows)]
181#[allow(unsafe_code)]
182fn windows_move(from: &Path, to: &Path) -> io::Result<()> {
183 use std::os::windows::ffi::OsStrExt;
184 use windows_sys::Win32::Storage::FileSystem::{
185 MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,
186 };
187 fn wide(path: &Path) -> io::Result<Vec<u16>> {
188 let mut result: Vec<_> = path.as_os_str().encode_wide().collect();
189 if result.contains(&0) {
190 return Err(io::Error::new(io::ErrorKind::InvalidInput, "NUL in path"));
191 }
192 result.push(0);
193 Ok(result)
194 }
195 let from = wide(from)?;
196 let to = wide(to)?;
197 if unsafe {
202 MoveFileExW(
203 from.as_ptr(),
204 to.as_ptr(),
205 MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
206 )
207 } == 0
208 {
209 return Err(io::Error::last_os_error());
210 }
211 Ok(())
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217 use std::{fs, io::Write};
218 fn root() -> cortexkit_test_support::ScratchDir {
219 cortexkit_test_support::ScratchDir::new("subc-durable-replace")
220 }
221 #[test]
222 fn durable_replace_replaces_existing_file() {
223 let root = root();
224 let from = root.join("stage");
225 let to = root.join("store");
226 fs::write(&to, b"previous").unwrap();
227 let mut file = fs::File::create(&from).unwrap();
228 file.write_all(b"next").unwrap();
229 file.sync_all().unwrap();
230 drop(file);
231 durable_replace(&from, &to).unwrap();
232 assert_eq!(fs::read(&to).unwrap(), b"next");
233 assert!(!from.exists());
234 }
235 #[test]
236 fn durable_replace_missing_source_is_error() {
237 let root = root();
238 let to = root.join("store");
239 fs::write(&to, b"previous").unwrap();
240 assert!(!durable_replace(&root.join("absent"), &to)
241 .unwrap_err()
242 .renamed());
243 assert_eq!(fs::read(&to).unwrap(), b"previous");
244 }
245
246 fn replacement_files(root: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
247 let from = root.join("stage");
248 let to = root.join("store");
249 let mut file = fs::File::create(&from).unwrap();
250 file.write_all(b"next").unwrap();
251 file.sync_all().unwrap();
252 drop(file);
253 fs::write(&to, b"previous").unwrap();
254 (from, to)
255 }
256
257 #[cfg(unix)]
258 #[test]
259 fn durable_replace_sync_error_after_rename_retains_publication_witness() {
260 let root = root();
261 let (from, to) = replacement_files(&root);
262 let error = durable_replace_impl(&from, &to, || {
263 Err(io::Error::other("injected directory sync failure"))
264 })
265 .unwrap_err();
266 assert!(error.renamed(), "{error}");
267 assert_eq!(error.to_string(), "injected directory sync failure");
268 assert_eq!(fs::read(to).unwrap(), b"next");
269 assert!(!from.exists());
270 }
271
272 #[cfg(windows)]
273 #[test]
274 fn durable_replace_windows_error_after_real_move_reports_renamed() {
275 let root = root();
276 let (from, to) = replacement_files(&root);
277 let error = durable_replace_impl(&from, &to, || {
278 Err(io::Error::other("injected write-through failure"))
279 })
280 .unwrap_err();
281 assert!(error.renamed(), "{error}");
282 assert_eq!(error.to_string(), "injected write-through failure");
283 assert_eq!(fs::read(to).unwrap(), b"next");
284 assert!(!from.exists());
285 }
286
287 #[cfg(windows)]
288 #[test]
289 fn durable_replace_windows_error_without_move_reports_not_renamed() {
290 let root = root();
291 let (from, to) = replacement_files(&root);
292 let error = windows_replace_with_operation(
293 &from,
294 &to,
295 || Err(io::Error::other("injected pre-move failure")),
296 windows_path_identity,
297 )
298 .unwrap_err();
299 assert!(!error.renamed(), "{error}");
300 assert_eq!(fs::read(to).unwrap(), b"previous");
301 assert_eq!(fs::read(from).unwrap(), b"next");
302 }
303
304 #[cfg(windows)]
305 #[test]
306 fn durable_replace_windows_inspection_failure_advances_conservatively() {
307 let root = root();
308 let (from, to) = replacement_files(&root);
309 let error = windows_replace_with_operation(
310 &from,
311 &to,
312 || Err(io::Error::other("injected move failure")),
313 |path| {
314 if path == from {
315 windows_path_identity(path)
316 } else {
317 Err(io::Error::other("injected destination inspection failure"))
318 }
319 },
320 )
321 .unwrap_err();
322 assert!(
323 error.renamed(),
324 "uncertainty must retain the witness: {error}"
325 );
326 assert_eq!(error.to_string(), "injected move failure");
327 assert_eq!(fs::read(to).unwrap(), b"previous");
328 assert_eq!(fs::read(from).unwrap(), b"next");
329 }
330}