1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
// Copyright 2024 Hugo Osvaldo Barrera
//
// SPDX-License-Identifier: ISC
//
use std::{
    ffi::{OsStr, OsString},
    os::{fd::OwnedFd, unix::ffi::OsStrExt},
    path::PathBuf,
    pin::Pin,
};

use rand::{distributions::Alphanumeric, thread_rng, Rng};
use rustix::{
    fd::AsFd,
    fs::{AtFlags, Mode, OFlags},
};
use tokio::{fs::File, io::AsyncWrite};

use crate::{Error, ErrorKind, Result};

/// File implementation which writes atomically.
///
/// After writting to an `AtomicFile`, either [`AtomicFile::commit`] or [`AtomicFile::commit_new`]
/// must be called. The write operation will be done atomically: regardless of whether (and when)
/// the opreation is interrupted, the resulting file is either untouched, or has all content
/// written. The target file will never be partially written.
pub struct AtomicFile {
    tempfile: File,
    dir: OwnedFd,
    temp_name: OsString,
    final_name: OsString,
}

impl AtomicFile {
    pub fn new(path: impl Into<PathBuf>) -> Result<AtomicFile> {
        let path = path.into();
        let dirpath = path
            .parent()
            .ok_or(ErrorKind::InvalidInput.error("path requires a parent"))?;
        let final_name = path
            .file_name()
            .ok_or(ErrorKind::InvalidInput.error("path requires a filename"))?
            .to_os_string();

        let dir = if dirpath.as_os_str().is_empty() {
            rustix::fs::open(".", OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty())
        } else {
            rustix::fs::open(dirpath, OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty())
        }
        .map_err(|e| Error::new(ErrorKind::Io, e))?;

        let temp_name = {
            let mut rng = thread_rng();

            let mut buf = *b"123456.tmp";
            for c in buf.iter_mut().take(6) {
                *c = rng.sample(Alphanumeric);
            }

            OsStr::from_bytes(&buf).to_os_string()
        };

        // TODO: use O_TMPFILE instead of O_EXCL on linux
        //       (but need to fall back to the regular path due to heterogeneous support.

        let tempfile = rustix::fs::openat(
            dir.as_fd(),
            &temp_name,
            OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC,
            Mode::from(0o600),
        )
        .map(|fd| File::from(std::fs::File::from(fd)))
        .map_err(|e| Error::new(ErrorKind::Io, e))?;

        Ok(AtomicFile {
            tempfile,
            dir,
            temp_name,
            final_name,
        })
    }

    /// Commit content into the specified path, overwritting if it already exists.
    pub fn commit(self) -> Result<()> {
        rustix::fs::renameat(&self.dir, self.temp_name, &self.dir, self.final_name)
            .map_err(|e| Error::new(ErrorKind::Io, e))?;
        Ok(())
    }

    /// Commit content into the specified path, failing if it already exists.
    pub fn commit_new(self) -> Result<()> {
        rustix::fs::linkat(
            &self.dir,
            &self.temp_name,
            &self.dir,
            &self.final_name,
            AtFlags::empty(),
        )
        .map_err(|e| Error::new(ErrorKind::Io, e))?;
        rustix::fs::unlinkat(self.dir, self.temp_name, AtFlags::empty())
            .map_err(|e| Error::new(ErrorKind::Io, e))?;
        Ok(())
    }
}

impl AsyncWrite for AtomicFile {
    fn poll_write(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &[u8],
    ) -> std::task::Poll<Result<usize, std::io::Error>> {
        let inner = Pin::new(&mut Pin::get_mut(self).tempfile);
        AsyncWrite::poll_write(inner, cx, buf)
    }

    fn poll_flush(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), std::io::Error>> {
        let inner = Pin::new(&mut Pin::get_mut(self).tempfile);
        AsyncWrite::poll_flush(inner, cx)
    }

    fn poll_shutdown(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), std::io::Error>> {
        let inner = Pin::new(&mut Pin::get_mut(self).tempfile);
        AsyncWrite::poll_shutdown(inner, cx)
    }
}