Skip to main content

agent_first_data/
atomic_file.rs

1//! One atomic file installation, shared by every writer in this crate.
2//!
3//! Installing a file so that a crash can never expose a half-written one is a
4//! fixed sequence — private same-directory temporary file, write, permissions,
5//! fsync the file, atomically install it over the target, fsync the directory
6//! entry — and each step has a way to be got subtly wrong. Writing that
7//! sequence a second time somewhere else is how one copy ends up durable and
8//! the other only looks it: a `rename` that is never followed by a parent
9//! directory fsync returns success while the new directory entry may still be
10//! lost to a power cut.
11//!
12//! So the sequence lives here once, and callers bring only what is genuinely
13//! theirs: the pre-write guard (what may be overwritten is a policy question,
14//! and different writers answer it differently) and the error type. Failures
15//! name the step that failed through [`AtomicError`], whose `Display` is the
16//! tail of a caller's own message — `write: ` + `install \`p\`: …`.
17
18use std::fs::{self, File, OpenOptions};
19use std::io::Write as _;
20use std::path::{Path, PathBuf};
21
22/// Atomically replace a regular file, preserving its permissions. On Unix a
23/// new file starts owner-only (`0600`); Windows has no mode bits, so a new file
24/// takes the directory's inherited ACL. Symbolic links and special files are refused; parent
25/// directories must already exist. A directory-sync error reports an uncertain
26/// durable commit through [`AtomicError::commit_uncertain`].
27///
28/// This is the default form of [`AtomicWrite`]; use that for explicit
29/// permission bits or a write that refuses an existing target.
30///
31/// Hard links are not checked. The new file is renamed over the path, so a
32/// target with other hard links is split from them: this path gets the new
33/// bytes and every other link keeps the old file. A caller that needs a
34/// hard-linked target refused writes through
35/// [`DocumentFile`](crate::document::DocumentFile) instead, whose
36/// [`ensure_mutable`](crate::document::DocumentFile::ensure_mutable) guard (run
37/// by `save` and by a replacing `create_atomic`) refuses one on Unix.
38pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), AtomicError> {
39    AtomicWrite::new(bytes).write(path)
40}
41
42pub(crate) fn validate_unix_mode(mode: Option<u32>) -> std::io::Result<()> {
43    if let Some(mode) = mode
44        && mode & !0o777 != 0
45    {
46        return Err(std::io::Error::new(
47            std::io::ErrorKind::InvalidInput,
48            format!("unix mode {mode:o} contains bits outside 0o777"),
49        ));
50    }
51    Ok(())
52}
53
54/// How the finished temporary file becomes the target.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56enum InstallMode {
57    /// `rename` over the target. Replaces whatever is at the path — including a
58    /// symbolic link, which is replaced rather than followed.
59    Replace,
60    /// `hard_link`, which refuses to install over an existing target. The
61    /// caller distinguishes that refusal by [`AtomicError::target_exists`].
62    NewOnly,
63}
64
65/// One atomic file write and its options: [`write_atomic`] is the default form.
66///
67/// ```no_run
68/// # use agent_first_data::AtomicWrite;
69/// # use std::path::Path;
70/// # fn demo() -> Result<(), agent_first_data::document::AtomicError> {
71/// let secret = AtomicWrite::new(b"token_secret = \"...\"\n");
72/// #[cfg(unix)]
73/// let secret = secret.mode(0o600);
74/// match secret.new_only().write(Path::new("credentials.toml")) {
75///     Err(error) if error.target_exists() => { /* keep the file that is there */ }
76///     other => other?,
77/// }
78/// # Ok(()) }
79/// ```
80///
81/// By default the write replaces a regular file and keeps that file's own
82/// permissions; a new file starts owner-only on Unix. The options:
83///
84/// - [`mode`](Self::mode) sets explicit permission bits on the new file, over
85///   either default. Unix only: Windows has no mode bits, so the method does
86///   not exist there and a caller that needs one writes the `cfg(unix)` itself
87///   rather than have the request silently ignored. A new Windows file takes
88///   the directory's inherited ACL.
89/// - [`new_only`](Self::new_only) refuses an existing target of any kind. The
90///   target is never touched; the refusal is
91///   [`AtomicError::target_exists`].
92///
93/// Every form keeps the full sequence: private same-directory temporary file,
94/// write, permissions, file fsync, atomic install, directory fsync.
95#[derive(Debug, Clone)]
96pub struct AtomicWrite<'a> {
97    bytes: &'a [u8],
98    install_mode: InstallMode,
99    unix_mode: Option<u32>,
100    /// `Some` when the caller has already inspected the target under its own
101    /// policy and hands over the permissions to keep; `None` lets
102    /// [`write`](Self::write) inspect it.
103    caller_guarded: Option<Option<fs::Permissions>>,
104}
105
106impl<'a> AtomicWrite<'a> {
107    /// A write of the complete new contents with the default behavior.
108    pub fn new(bytes: &'a [u8]) -> Self {
109        Self {
110            bytes,
111            install_mode: InstallMode::Replace,
112            unix_mode: None,
113            caller_guarded: None,
114        }
115    }
116
117    /// Give the new file these permission bits (`0o600`), overriding both the
118    /// replaced file's permissions and the owner-only default. Unix only.
119    #[cfg(unix)]
120    #[must_use]
121    pub fn mode(mut self, bits: u32) -> Self {
122        self.unix_mode = Some(bits);
123        self
124    }
125
126    /// Refuse an existing target instead of replacing it. The refusal is
127    /// reported by [`AtomicError::target_exists`], including when the name is
128    /// taken between the check and the install.
129    #[must_use]
130    pub fn new_only(mut self) -> Self {
131        self.install_mode = InstallMode::NewOnly;
132        self
133    }
134
135    /// Write `self` to `path`. Every failure before the install leaves the
136    /// original untouched and removes the temporary file. A failure at the
137    /// final parent directory fsync — the one [`AtomicError::commit_uncertain`]
138    /// reports — means the new file may already be in place without confirmed
139    /// durability.
140    pub fn write(self, path: &Path) -> Result<(), AtomicError> {
141        self.write_with(path, |file, bytes| file.write_all(bytes))
142    }
143
144    /// Crate-internal: set unix bits without the `cfg(unix)` the public
145    /// [`mode`](Self::mode) carries; ignored where the platform has none.
146    pub(crate) fn with_unix_mode(mut self, unix_mode: Option<u32>) -> Self {
147        self.unix_mode = unix_mode;
148        self
149    }
150
151    /// Crate-internal: the caller already guarded the target under its own
152    /// policy (what may be overwritten differs between writers) and these are
153    /// the permissions to re-apply, normally the replaced file's own.
154    pub(crate) fn with_permissions(mut self, permissions: Option<fs::Permissions>) -> Self {
155        self.caller_guarded = Some(permissions);
156        self
157    }
158
159    fn write_with(
160        mut self,
161        path: &Path,
162        write: impl FnOnce(&mut File, &[u8]) -> std::io::Result<()>,
163    ) -> Result<(), AtomicError> {
164        validate_unix_mode(self.unix_mode)
165            .map_err(|error| AtomicError::at(AtomicStep::Guard, path, error))?;
166        if let Some(permissions) = self.caller_guarded.take() {
167            return install_with_writer(path, &self, permissions, write);
168        }
169        // A new-only write never looks at the target: whatever is there, even a
170        // symlink or directory, is "exists" and is refused by the install.
171        let permissions = if self.install_mode == InstallMode::NewOnly {
172            None
173        } else {
174            match fs::symlink_metadata(path) {
175                Ok(metadata) if metadata.file_type().is_file() => Some(metadata.permissions()),
176                Ok(_) => {
177                    return Err(AtomicError::at(
178                        AtomicStep::Guard,
179                        path,
180                        std::io::Error::new(
181                            std::io::ErrorKind::InvalidInput,
182                            "atomic target must be a regular file, not a symlink, directory, or special file",
183                        ),
184                    ));
185                }
186                Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
187                Err(error) => return Err(AtomicError::at(AtomicStep::Guard, path, error)),
188            }
189        };
190        install_with_writer(path, &self, permissions, write)
191    }
192}
193
194/// The step of an atomic installation that failed.
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum AtomicStep {
197    /// Inspecting the target without following links.
198    Guard,
199    /// The target has no parent directory to write the temporary file into.
200    NoParent,
201    /// The target's own file name is not valid UTF-8.
202    NonUtf8Name,
203    /// Creating the private temporary file.
204    Temp,
205    /// Every candidate temporary name was taken.
206    TempExhausted,
207    /// Writing the new bytes.
208    Write,
209    /// Re-applying the replaced file's permissions.
210    PreservePermissions,
211    /// Applying explicitly requested permission bits. Unix only, because the
212    /// bits themselves are: the step does not exist on a platform that has no
213    /// mode to set, and a variant no code can construct is a step a reader
214    /// would look for and never find.
215    #[cfg(unix)]
216    SetPermissions,
217    /// Flushing the temporary file to storage.
218    Sync,
219    /// Installing the temporary file over the target.
220    Install,
221    /// Recording the new directory entry.
222    SyncParent,
223}
224
225/// A failed atomic installation: which step, which path, and the OS error.
226#[derive(Debug)]
227pub struct AtomicError {
228    /// The step that failed.
229    pub step: AtomicStep,
230    /// The path that step was about — the target, its temporary file, or the
231    /// parent directory, depending on the step.
232    pub path: PathBuf,
233    /// The underlying OS error, absent only where the step had none.
234    pub source: Option<std::io::Error>,
235}
236
237impl AtomicError {
238    fn at(step: AtomicStep, path: &Path, source: std::io::Error) -> Self {
239        Self {
240            step,
241            path: path.to_path_buf(),
242            source: Some(source),
243        }
244    }
245
246    /// Whether this is a [`new_only`](AtomicWrite::new_only) write refusing an
247    /// existing target, which is a caller-visible outcome rather than an I/O
248    /// fault. The target was not touched. Never true for a replacing write.
249    pub fn target_exists(&self) -> bool {
250        self.step == AtomicStep::Install
251            && self
252                .source
253                .as_ref()
254                .is_some_and(|error| error.kind() == std::io::ErrorKind::AlreadyExists)
255    }
256
257    /// Whether the target may already carry the new bytes.
258    ///
259    /// Only the final directory fsync can fail after the installation itself
260    /// succeeded: the file is complete and in place, but its survival across a
261    /// crash is unconfirmed. Every other step fails before the install and
262    /// leaves the original untouched.
263    pub fn commit_uncertain(&self) -> bool {
264        self.step == AtomicStep::SyncParent
265    }
266}
267
268impl std::fmt::Display for AtomicError {
269    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
270        let path = self.path.display();
271        let phrase = match self.step {
272            AtomicStep::Guard => "inspect",
273            AtomicStep::NoParent => {
274                return write!(formatter, "has no parent directory for `{path}`");
275            }
276            AtomicStep::NonUtf8Name => {
277                return write!(formatter, "path is not valid UTF-8: `{path}`");
278            }
279            AtomicStep::TempExhausted => {
280                return write!(formatter, "could not allocate temporary file in `{path}`");
281            }
282            AtomicStep::Temp => "temporary file in",
283            AtomicStep::Write => "write",
284            AtomicStep::PreservePermissions => "preserve permissions",
285            #[cfg(unix)]
286            AtomicStep::SetPermissions => "set permissions on",
287            AtomicStep::Sync => "fsync",
288            AtomicStep::Install => "install",
289            AtomicStep::SyncParent => "fsync parent directory",
290        };
291        write!(formatter, "{phrase} `{path}`")?;
292        match &self.source {
293            Some(source) => write!(formatter, ": {source}"),
294            None => Ok(()),
295        }
296    }
297}
298
299/// The smallest `NAME_MAX` across the platforms this runs on.
300const MAX_NAME_BYTES: usize = 255;
301
302/// Compose a temporary file name that stays within one path component's limit.
303///
304/// The marker, pid, and attempt add about 35 bytes. A target whose own name is
305/// close to `NAME_MAX` would push the composed name past it, and the failure
306/// would surface at install time — after the caller had already done its work,
307/// on a file it opened successfully. Truncating the stem keeps the write
308/// possible; uniqueness still comes from the pid and attempt, with `create_new`
309/// retrying the rare collision.
310fn temp_file_name(file_name: &str, pid: u32, attempt: u32) -> String {
311    let suffix = format!(".afdata.{pid}.{attempt}.tmp");
312    // One byte for the leading dot that hides the temporary file.
313    let budget = MAX_NAME_BYTES.saturating_sub(suffix.len() + 1);
314    let stem = &file_name[..file_name.floor_char_boundary(budget)];
315    format!(".{stem}{suffix}")
316}
317
318/// Split a target into the directory the temporary file must share with it and
319/// the target's own name. Sharing the directory is what makes the final install
320/// a rename within one filesystem, which is the atomic operation this relies on.
321fn parent_and_name(path: &Path) -> Result<(&Path, String), AtomicError> {
322    let parent = match path.parent() {
323        Some(parent) if parent.as_os_str().is_empty() => Path::new("."),
324        Some(parent) => parent,
325        None => {
326            return Err(AtomicError {
327                step: AtomicStep::NoParent,
328                path: path.to_path_buf(),
329                source: None,
330            });
331        }
332    };
333    let file_name = path
334        .file_name()
335        .and_then(|name| name.to_str())
336        .ok_or_else(|| AtomicError {
337            step: AtomicStep::NonUtf8Name,
338            path: path.to_path_buf(),
339            source: None,
340        })?
341        .to_string();
342    Ok((parent, file_name))
343}
344
345fn allocate_private_temp(parent: &Path, file_name: &str) -> Result<(PathBuf, File), AtomicError> {
346    let pid = std::process::id();
347    for attempt in 0..32_u32 {
348        let candidate = parent.join(temp_file_name(file_name, pid, attempt));
349        let mut options = OpenOptions::new();
350        options.write(true).create_new(true);
351        #[cfg(unix)]
352        {
353            use std::os::unix::fs::OpenOptionsExt as _;
354            // Nothing may read the new contents through the temporary name
355            // before the caller's own permissions are applied below.
356            options.mode(0o600);
357        }
358        match options.open(&candidate) {
359            Ok(file) => return Ok((candidate, file)),
360            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
361            Err(error) => return Err(AtomicError::at(AtomicStep::Temp, parent, error)),
362        }
363    }
364    Err(AtomicError {
365        step: AtomicStep::TempExhausted,
366        path: parent.to_path_buf(),
367        source: None,
368    })
369}
370
371#[cfg(unix)]
372fn sync_parent(parent: &Path) -> Result<(), AtomicError> {
373    File::open(parent)
374        .and_then(|directory| directory.sync_all())
375        .map_err(|error| AtomicError::at(AtomicStep::SyncParent, parent, error))
376}
377
378#[cfg(not(unix))]
379fn sync_parent(_parent: &Path) -> Result<(), AtomicError> {
380    // Rust does not expose a portable directory handle on non-unix targets.
381    // The file itself is still synced before its atomic installation.
382    Ok(())
383}
384
385fn write_temp(
386    mut temp_file: File,
387    temp_path: &Path,
388    target: &Path,
389    request: &AtomicWrite<'_>,
390    permissions: Option<fs::Permissions>,
391    write: impl FnOnce(&mut File, &[u8]) -> std::io::Result<()>,
392) -> Result<(), AtomicError> {
393    write(&mut temp_file, request.bytes)
394        .map_err(|error| AtomicError::at(AtomicStep::Write, target, error))?;
395    if let Some(permissions) = permissions {
396        temp_file
397            .set_permissions(permissions)
398            .map_err(|error| AtomicError::at(AtomicStep::PreservePermissions, target, error))?;
399    }
400    #[cfg(unix)]
401    if let Some(unix_mode) = request.unix_mode {
402        use std::os::unix::fs::PermissionsExt as _;
403        temp_file
404            .set_permissions(fs::Permissions::from_mode(unix_mode))
405            .map_err(|error| AtomicError::at(AtomicStep::SetPermissions, target, error))?;
406    }
407    temp_file
408        .sync_all()
409        .map_err(|error| AtomicError::at(AtomicStep::Sync, temp_path, error))
410}
411
412/// Install `request` at `path` atomically, with the caller's own guard already
413/// decided: `permissions` are the replaced file's, re-applied before any
414/// explicit mode.
415///
416// The writer seam keeps disk-full, short-write, and interrupted-process
417// regressions at the primitive that owns publication, without exposing a
418// callback or partial-file API to callers.
419fn install_with_writer(
420    path: &Path,
421    request: &AtomicWrite<'_>,
422    permissions: Option<fs::Permissions>,
423    write: impl FnOnce(&mut File, &[u8]) -> std::io::Result<()>,
424) -> Result<(), AtomicError> {
425    let (parent, file_name) = parent_and_name(path)?;
426    let (temp_path, temp_file) = allocate_private_temp(parent, &file_name)?;
427    let result = (|| -> Result<(), AtomicError> {
428        write_temp(temp_file, &temp_path, path, request, permissions, write)?;
429        match request.install_mode {
430            InstallMode::Replace => {
431                fs::rename(&temp_path, path)
432                    .map_err(|error| AtomicError::at(AtomicStep::Install, path, error))?;
433            }
434            InstallMode::NewOnly => {
435                fs::hard_link(&temp_path, path)
436                    .map_err(|error| AtomicError::at(AtomicStep::Install, path, error))?;
437                // The file is installed from here on. Failing to unlink the
438                // temporary link leaves a stray file, but reporting an error
439                // would tell the caller the commit did not happen — and a retry
440                // would then refuse a target that this call in fact created.
441                let _ = fs::remove_file(&temp_path);
442            }
443        }
444        sync_parent(parent)?;
445        Ok(())
446    })();
447    if let Err(error) = &result {
448        // A parent-directory fsync failure comes after the install, where the
449        // temporary name no longer refers to anything to clean up.
450        if !error.commit_uncertain() {
451            let _ = fs::remove_file(&temp_path);
452        }
453    }
454    result
455}
456
457impl std::error::Error for AtomicError {
458    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
459        self.source.as_ref().map(|error| error as _)
460    }
461}
462
463#[cfg(test)]
464mod tests {
465    #![allow(clippy::unwrap_used, clippy::panic, clippy::expect_used)]
466    use super::*;
467
468    #[test]
469    fn temp_name_stays_within_one_path_component() {
470        let long = "x".repeat(400);
471        let name = temp_file_name(&long, 1234, 0);
472        assert!(name.len() <= MAX_NAME_BYTES, "{} bytes", name.len());
473        assert!(name.starts_with('.'));
474        assert!(name.ends_with(".tmp"));
475    }
476
477    #[test]
478    fn temp_name_truncates_on_a_character_boundary() {
479        let long = "é".repeat(300);
480        let name = temp_file_name(&long, 1234, 0);
481        assert!(name.is_char_boundary(name.len()));
482        assert!(name.len() <= MAX_NAME_BYTES);
483    }
484
485    #[test]
486    fn bare_relative_paths_use_the_current_directory() {
487        let (parent, file_name) = parent_and_name(Path::new("config.json")).unwrap();
488
489        assert_eq!(parent, Path::new("."));
490        assert_eq!(file_name, "config.json");
491    }
492
493    #[test]
494    fn replace_installs_new_bytes_and_leaves_no_temporary_file() {
495        let dir = tempfile::tempdir().unwrap();
496        let path = dir.path().join("config.json");
497        fs::write(&path, b"old").unwrap();
498
499        AtomicWrite::new(b"new").write(&path).unwrap();
500
501        assert_eq!(fs::read(&path).unwrap(), b"new");
502        let strays: Vec<_> = fs::read_dir(dir.path())
503            .unwrap()
504            .filter_map(Result::ok)
505            .filter(|entry| entry.file_name().to_string_lossy().ends_with(".tmp"))
506            .collect();
507        assert!(strays.is_empty(), "temporary files left behind");
508    }
509
510    #[test]
511    fn new_only_refuses_an_existing_target_without_touching_it() {
512        let dir = tempfile::tempdir().unwrap();
513        let path = dir.path().join("config.json");
514        fs::write(&path, b"original").unwrap();
515
516        let error = AtomicWrite::new(b"new")
517            .new_only()
518            .write(&path)
519            .unwrap_err();
520
521        assert!(error.target_exists());
522        assert_eq!(fs::read(&path).unwrap(), b"original");
523    }
524
525    #[cfg(unix)]
526    #[test]
527    fn replace_swaps_a_symlink_rather_than_following_it() {
528        use std::os::unix::fs::symlink;
529
530        let dir = tempfile::tempdir().unwrap();
531        let outside = dir.path().join("outside.txt");
532        fs::write(&outside, b"untouched").unwrap();
533        let link = dir.path().join("link.txt");
534        symlink(&outside, &link).unwrap();
535
536        AtomicWrite::new(b"new")
537            .with_permissions(None)
538            .write(&link)
539            .unwrap();
540
541        assert_eq!(fs::read(&outside).unwrap(), b"untouched");
542        assert!(
543            !fs::symlink_metadata(&link)
544                .unwrap()
545                .file_type()
546                .is_symlink()
547        );
548        assert_eq!(fs::read(&link).unwrap(), b"new");
549    }
550
551    #[cfg(unix)]
552    #[test]
553    fn explicit_unix_mode_wins_over_the_private_temporary_mode() {
554        use std::os::unix::fs::PermissionsExt as _;
555
556        let dir = tempfile::tempdir().unwrap();
557        let path = dir.path().join("readable.md");
558
559        AtomicWrite::new(b"body").mode(0o644).write(&path).unwrap();
560
561        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
562        assert_eq!(mode, 0o644);
563    }
564
565    #[test]
566    fn a_missing_parent_directory_fails_before_any_write() {
567        let dir = tempfile::tempdir().unwrap();
568        let path = dir.path().join("absent").join("config.json");
569
570        let error = AtomicWrite::new(b"new").write(&path).unwrap_err();
571
572        assert_eq!(error.step, AtomicStep::Temp);
573        assert!(!error.commit_uncertain());
574        assert!(!path.exists());
575    }
576    #[test]
577    fn failed_writes_preserve_previous_bytes_and_remove_temporary_file() {
578        let dir = tempfile::tempdir().unwrap();
579        let path = dir.path().join("state.json");
580        fs::write(&path, b"old complete value").unwrap();
581        for error in [
582            std::io::Error::from_raw_os_error(28),
583            std::io::Error::from(std::io::ErrorKind::Interrupted),
584            std::io::Error::from(std::io::ErrorKind::WriteZero),
585        ] {
586            let error = AtomicWrite::new(b"new")
587                .write_with(&path, |file, _| {
588                    file.write_all(b"partial")?;
589                    Err(error)
590                })
591                .unwrap_err();
592            assert_eq!(error.step, AtomicStep::Write);
593            assert!(!error.commit_uncertain());
594            assert_eq!(fs::read(&path).unwrap(), b"old complete value");
595            assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
596        }
597    }
598
599    #[test]
600    fn write_all_retries_short_writes_and_interruptions_before_publish() {
601        struct ShortWriter<'a> {
602            file: &'a mut File,
603            interrupted: bool,
604        }
605        impl std::io::Write for ShortWriter<'_> {
606            fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
607                if !self.interrupted {
608                    self.interrupted = true;
609                    return Err(std::io::ErrorKind::Interrupted.into());
610                }
611                self.file.write(&bytes[..bytes.len().min(2)])
612            }
613            fn flush(&mut self) -> std::io::Result<()> {
614                self.file.flush()
615            }
616        }
617        let dir = tempfile::tempdir().unwrap();
618        let path = dir.path().join("state.json");
619        let bytes = b"new complete value";
620        AtomicWrite::new(bytes)
621            .write_with(&path, |file, bytes| {
622                ShortWriter {
623                    file,
624                    interrupted: false,
625                }
626                .write_all(bytes)
627            })
628            .unwrap();
629        assert_eq!(fs::read(&path).unwrap(), bytes);
630    }
631
632    #[test]
633    fn interrupted_process_leaves_uncommitted_temporary_file_not_target() {
634        const CHILD_PATH: &str = "AFDATA_TEST_INTERRUPTED_ATOMIC_PATH";
635        if let Some(path) = std::env::var_os(CHILD_PATH) {
636            let _ = AtomicWrite::new(b"new").write_with(Path::new(&path), |file, _| {
637                file.write_all(b"partial")?;
638                file.sync_all()?;
639                std::process::exit(86);
640            });
641            panic!("child did not reach the interrupted write");
642        }
643        let dir = tempfile::tempdir().unwrap();
644        let path = dir.path().join("state.json");
645        write_atomic(&path, b"old complete value").unwrap();
646        let status = std::process::Command::new(std::env::current_exe().unwrap())
647            .args(["--exact", "atomic_file::tests::interrupted_process_leaves_uncommitted_temporary_file_not_target"])
648            .env(CHILD_PATH, &path).status().unwrap();
649        assert_eq!(status.code(), Some(86));
650        assert_eq!(fs::read(&path).unwrap(), b"old complete value");
651        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 2);
652        write_atomic(&path, b"new complete value").unwrap();
653        assert_eq!(fs::read(&path).unwrap(), b"new complete value");
654    }
655
656    #[cfg(unix)]
657    #[test]
658    fn public_write_refuses_a_symlink_target() {
659        let dir = tempfile::tempdir().unwrap();
660        let outside = dir.path().join("outside");
661        fs::write(&outside, b"untouched").unwrap();
662        let link = dir.path().join("link");
663        std::os::unix::fs::symlink(&outside, &link).unwrap();
664        let error = AtomicWrite::new(b"x").write(&link).unwrap_err();
665        assert_eq!(error.step, AtomicStep::Guard);
666        assert_eq!(fs::read(&outside).unwrap(), b"untouched");
667    }
668
669    #[cfg(unix)]
670    fn mode_of(path: &Path) -> u32 {
671        use std::os::unix::fs::PermissionsExt as _;
672        fs::metadata(path).unwrap().permissions().mode() & 0o777
673    }
674
675    #[cfg(unix)]
676    #[test]
677    fn mode_applies_to_a_new_file_and_overrides_an_existing_one() {
678        let dir = tempfile::tempdir().unwrap();
679        let fresh = dir.path().join("fresh");
680        AtomicWrite::new(b"x").mode(0o640).write(&fresh).unwrap();
681        assert_eq!(mode_of(&fresh), 0o640);
682
683        let existing = dir.path().join("existing");
684        write_atomic(&existing, b"old").unwrap();
685        AtomicWrite::new(b"new")
686            .mode(0o604)
687            .write(&existing)
688            .unwrap();
689        assert_eq!(mode_of(&existing), 0o604);
690        assert_eq!(fs::read(&existing).unwrap(), b"new");
691    }
692
693    #[cfg(unix)]
694    #[test]
695    fn default_write_keeps_existing_mode_and_starts_new_files_private() {
696        use std::os::unix::fs::PermissionsExt as _;
697        let dir = tempfile::tempdir().unwrap();
698        let existing = dir.path().join("existing");
699        fs::write(&existing, b"old").unwrap();
700        fs::set_permissions(&existing, fs::Permissions::from_mode(0o644)).unwrap();
701        write_atomic(&existing, b"new").unwrap();
702        assert_eq!(mode_of(&existing), 0o644);
703
704        let fresh = dir.path().join("fresh");
705        write_atomic(&fresh, b"x").unwrap();
706        assert_eq!(mode_of(&fresh), 0o600);
707    }
708
709    #[test]
710    fn new_only_creates_an_absent_target_and_leaves_no_temporary_file() {
711        let dir = tempfile::tempdir().unwrap();
712        let path = dir.path().join("fresh.json");
713        AtomicWrite::new(b"created")
714            .new_only()
715            .write(&path)
716            .unwrap();
717        assert_eq!(fs::read(&path).unwrap(), b"created");
718        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
719    }
720
721    #[test]
722    fn public_new_only_refuses_an_existing_target_byte_identical() {
723        let dir = tempfile::tempdir().unwrap();
724        let path = dir.path().join("keep.json");
725        fs::write(&path, b"original").unwrap();
726        let error = AtomicWrite::new(b"other")
727            .new_only()
728            .write(&path)
729            .unwrap_err();
730        assert!(error.target_exists());
731        assert!(!error.commit_uncertain());
732        assert_eq!(fs::read(&path).unwrap(), b"original");
733        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
734    }
735}