TODO §41 (docs/features/atomic-write-coordination). Closes topo §2.9-26
and repository-analysis finding 1.
`atomic::write_atomic` names its temp `.{name}.{pid}.{n}.lucisv-tmp` with
a per-process counter and opens it create-new (O_EXCL), retrying a used
name up to 32 times; on unix the temp is created 0600 when a target
exists and takes the target's mode through the open handle before the
bytes are written, so a 0600 file never has a readable moment. The CLI's
`dedup` keys on the canonical path when the file exists, so a symlink
alias reaches one worker; the reported path is the first spelling. Two
processes on one target remain last-writer-wins (rename is atomic, the
formatter idempotent), stated in the module doc. The audit's probe is a
test: 0 write errors in 200 calls.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
452 lines
19 KiB
Rust
452 lines
19 KiB
Rust
//! Replacing a file's contents without ever leaving it half written.
|
|
//!
|
|
//! `fs::write` truncates the target and then writes into it, so a crash, a
|
|
//! full disk or a `^C` between the two leaves the user's source truncated —
|
|
//! and lucisv's first invariant is that it never corrupts code. Every
|
|
//! in-place write goes through [`write_atomic`] instead: a sibling temp file
|
|
//! gets the bytes, and a `rename` over the target publishes them in one step
|
|
//! that either happened or did not.
|
|
//!
|
|
//! Two threads of one process may write one target: the temp names carry a
|
|
//! per-process counter as well as the pid and are created with `O_EXCL`, so
|
|
//! each writer owns its own file and neither can see the other's bytes.
|
|
//!
|
|
//! Two *processes* writing one target are not coordinated, and deliberately
|
|
//! so. Both renames are atomic, the later one wins, and the loser's bytes are
|
|
//! discarded whole — never merged. Both processes formatted the same input
|
|
//! and `format` is idempotent, so whichever rename lands last leaves the
|
|
//! file complete and correctly formatted. A lock would buy nothing and would
|
|
//! be one more thing to leave behind after a `^C`.
|
|
//!
|
|
//! See `docs/features/small-items-3/README.md` and
|
|
//! `docs/features/atomic-write-coordination/README.md`.
|
|
|
|
use std::fs::{self, File, OpenOptions};
|
|
use std::io::{self, Write};
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::atomic::{AtomicU64, Ordering};
|
|
|
|
/// Writes `bytes` to `path`, replacing whatever was there in one step.
|
|
///
|
|
/// A temp file beside the target takes the bytes, inherits the target's
|
|
/// permissions when there is a target, and is renamed onto it — `rename` is
|
|
/// atomic within a directory on every platform lucisv ships to, so a reader
|
|
/// sees either the old file or the new one and never a truncated one. A
|
|
/// failure anywhere after the temp exists removes it before returning.
|
|
///
|
|
/// The temp is the caller's alone: [`temp_path`] hands out a name no other
|
|
/// writer in this process will be given, and the file is created with
|
|
/// `create_new`, so a name that somehow exists is an error and not a shared
|
|
/// file. Two threads writing one target therefore both succeed, and the
|
|
/// target ends up holding one thread's whole buffer.
|
|
///
|
|
/// A symlinked target is resolved first: `fs::write` writes *through* a
|
|
/// symlink, so replacing the link itself would silently redirect it at a new
|
|
/// file and leave the real one stale. The canonical path is what gets
|
|
/// replaced, which is also what makes the temp land on the target's own
|
|
/// filesystem — `rename` cannot cross one.
|
|
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
|
let target = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
|
|
let perms = target_permissions(&target);
|
|
// A rename replaces a file whatever its mode, so a read-only target would
|
|
// be silently overwritten where `fs::write` refuses it. Keep the refusal:
|
|
// a file someone made read-only is asking not to be rewritten in place.
|
|
if perms.as_ref().is_some_and(fs::Permissions::readonly) {
|
|
return Err(io::Error::new(
|
|
io::ErrorKind::PermissionDenied,
|
|
format!("{} is read-only", path.display()),
|
|
));
|
|
}
|
|
let (tmp, mut file) = create_temp(&target, perms.is_some())?;
|
|
if let Err(e) = fill_temp(&mut file, &tmp, perms, bytes) {
|
|
let _ = fs::remove_file(&tmp);
|
|
return Err(e);
|
|
}
|
|
drop(file);
|
|
if let Err(e) = fs::rename(&tmp, &target) {
|
|
let _ = fs::remove_file(&tmp);
|
|
return Err(e);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// How many temp names one write tries before giving up.
|
|
///
|
|
/// A name is only ever handed out once per process, so a collision means a
|
|
/// leftover from a *previous* process that crashed mid-write and whose pid
|
|
/// this process now has. A handful of those may sit in one directory; a
|
|
/// hundred is a directory to clean up by hand, not a race to retry through.
|
|
const TEMP_ATTEMPTS: u32 = 32;
|
|
|
|
/// Creates the temp file, exclusively, and returns it with its path.
|
|
///
|
|
/// `replacing` says there is a target whose mode the temp is about to take.
|
|
/// Then it is born 0600 on unix rather than at the umask's mode: a chmod does
|
|
/// not revoke a descriptor someone already opened, so the only way a private
|
|
/// file's replacement can never be read by anyone else is for the temp to be
|
|
/// private from the moment it exists. With no target there is no earlier mode
|
|
/// to honour and the umask decides, as `fs::write` would.
|
|
fn create_temp(target: &Path, replacing: bool) -> io::Result<(PathBuf, File)> {
|
|
let mut opts = OpenOptions::new();
|
|
opts.write(true).create_new(true);
|
|
#[cfg(unix)]
|
|
if replacing {
|
|
use std::os::unix::fs::OpenOptionsExt;
|
|
opts.mode(0o600);
|
|
}
|
|
#[cfg(not(unix))]
|
|
let _ = replacing;
|
|
for _ in 0..TEMP_ATTEMPTS {
|
|
let tmp = temp_path(target)?;
|
|
match opts.open(&tmp) {
|
|
Ok(file) => return Ok((tmp, file)),
|
|
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
|
|
Err(e) => return Err(e),
|
|
}
|
|
}
|
|
Err(io::Error::new(
|
|
io::ErrorKind::AlreadyExists,
|
|
format!("no free temp file name beside {} after {TEMP_ATTEMPTS} tries", target.display()),
|
|
))
|
|
}
|
|
|
|
/// Puts the target's mode on the temp, then the bytes in it.
|
|
///
|
|
/// The order is the point on unix: a 0600 target's replacement must not spend
|
|
/// even an instant holding the file's contents under the umask's broader
|
|
/// bits. Chmod does not close the handle opened before it, so a mode without
|
|
/// an owner-write bit still takes the write. Elsewhere `set_permissions`
|
|
/// takes a path rather than a handle and the mode goes on after the bytes,
|
|
/// which is the order this always had.
|
|
fn fill_temp(
|
|
file: &mut File,
|
|
tmp: &Path,
|
|
perms: Option<fs::Permissions>,
|
|
bytes: &[u8],
|
|
) -> io::Result<()> {
|
|
if cfg!(unix) {
|
|
copy_mode(file, perms);
|
|
file.write_all(bytes)
|
|
} else {
|
|
file.write_all(bytes)?;
|
|
if let Some(perms) = perms {
|
|
let _ = fs::set_permissions(tmp, perms);
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// Puts the target's mode on the temp through its open handle, which is what
|
|
/// lets it happen while the temp is still empty. No target means no earlier
|
|
/// mode to honour, and the umask's stands.
|
|
fn copy_mode(file: &File, perms: Option<fs::Permissions>) {
|
|
if let Some(perms) = perms {
|
|
let _ = file.set_permissions(perms);
|
|
}
|
|
}
|
|
|
|
/// The mode the temp must end up with: a file someone made executable, or
|
|
/// private, keeps its bits, because the temp was created with the process
|
|
/// umask (or 0600) and not with the target's. `None` means there is no target
|
|
/// — a new file, which takes the umask as `fs::write` would.
|
|
fn target_permissions(target: &Path) -> Option<fs::Permissions> {
|
|
fs::metadata(target).ok().map(|m| m.permissions())
|
|
}
|
|
|
|
/// Names handed out by [`temp_path`], one per call for the life of the
|
|
/// process. Wrapping after 2^64 names is not a scenario.
|
|
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
|
|
|
|
/// The temp file's path: hidden, in the target's own directory, and stamped
|
|
/// with the process id and a per-process counter — the pid keeps two lucisv
|
|
/// runs apart, the counter keeps two threads of one run apart, and together
|
|
/// they mean no two writers anywhere are ever given the same name.
|
|
fn temp_path(target: &Path) -> io::Result<PathBuf> {
|
|
let dir = target.parent().unwrap_or_else(|| Path::new("."));
|
|
let name = target
|
|
.file_name()
|
|
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name to write"))?;
|
|
let n = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
|
|
let mut tmp = std::ffi::OsString::from(".");
|
|
tmp.push(name);
|
|
tmp.push(format!(".{}.{n}.lucisv-tmp", std::process::id()));
|
|
Ok(dir.join(tmp))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
/// A directory that removes itself, the way `cache.rs`'s own tests have
|
|
/// one — no dependency, and no leftovers under `target/`.
|
|
struct TempDir {
|
|
path: PathBuf,
|
|
}
|
|
|
|
impl TempDir {
|
|
fn new(tag: &str) -> Self {
|
|
let path = std::env::temp_dir().join(format!(
|
|
"lucisv-atomic-{tag}-{}-{:?}",
|
|
std::process::id(),
|
|
std::thread::current().id()
|
|
));
|
|
let _ = fs::remove_dir_all(&path);
|
|
fs::create_dir_all(&path).expect("create temp dir");
|
|
TempDir { path }
|
|
}
|
|
|
|
fn file(&self, name: &str) -> PathBuf {
|
|
self.path.join(name)
|
|
}
|
|
|
|
/// Every name in the directory, so a test can say what is *not* there.
|
|
fn names(&self) -> Vec<String> {
|
|
let mut out: Vec<String> = fs::read_dir(&self.path)
|
|
.expect("read dir")
|
|
.filter_map(|e| e.ok())
|
|
.map(|e| e.file_name().to_string_lossy().into_owned())
|
|
.collect();
|
|
out.sort();
|
|
out
|
|
}
|
|
}
|
|
|
|
impl Drop for TempDir {
|
|
fn drop(&mut self) {
|
|
let _ = fs::remove_dir_all(&self.path);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn the_bytes_land_and_no_temp_file_is_left_behind() {
|
|
let dir = TempDir::new("plain");
|
|
let file = dir.file("a.sv");
|
|
fs::write(&file, "old\n").expect("seed");
|
|
write_atomic(&file, b"new\n").expect("write");
|
|
assert_eq!(fs::read_to_string(&file).expect("read"), "new\n");
|
|
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
|
|
}
|
|
|
|
#[test]
|
|
fn a_file_that_does_not_exist_yet_is_created() {
|
|
let dir = TempDir::new("create");
|
|
let file = dir.file("new.sv");
|
|
write_atomic(&file, b"hello\n").expect("write");
|
|
assert_eq!(fs::read_to_string(&file).expect("read"), "hello\n");
|
|
assert_eq!(dir.names(), vec!["new.sv".to_string()]);
|
|
}
|
|
|
|
#[test]
|
|
fn a_rename_that_cannot_happen_is_an_error_and_leaves_no_temp() {
|
|
// A directory standing where the file should be: the write succeeds,
|
|
// the rename cannot.
|
|
let dir = TempDir::new("dirtarget");
|
|
let target = dir.file("occupied");
|
|
fs::create_dir(&target).expect("create dir");
|
|
let err = write_atomic(&target, b"x\n").expect_err("a directory cannot be replaced");
|
|
assert!(err.to_string().len() > 1, "{err}");
|
|
assert_eq!(dir.names(), vec!["occupied".to_string()], "the temp file was cleaned up");
|
|
}
|
|
|
|
#[test]
|
|
fn writing_the_same_path_twice_leaves_one_file() {
|
|
let dir = TempDir::new("twice");
|
|
let file = dir.file("a.sv");
|
|
write_atomic(&file, b"one\n").expect("write");
|
|
write_atomic(&file, b"two\n").expect("write");
|
|
assert_eq!(fs::read_to_string(&file).expect("read"), "two\n");
|
|
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn the_targets_permissions_are_preserved() {
|
|
use std::os::unix::fs::PermissionsExt;
|
|
let dir = TempDir::new("modes");
|
|
for mode in [0o600, 0o755] {
|
|
let file = dir.file(&format!("m{mode:o}.sv"));
|
|
fs::write(&file, "old\n").expect("seed");
|
|
fs::set_permissions(&file, fs::Permissions::from_mode(mode)).expect("chmod");
|
|
write_atomic(&file, b"new\n").expect("write");
|
|
let got = fs::metadata(&file).expect("stat").permissions().mode() & 0o777;
|
|
assert_eq!(got, mode, "mode {mode:o} was not preserved");
|
|
}
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn a_read_only_target_is_refused_and_left_alone() {
|
|
use std::os::unix::fs::PermissionsExt;
|
|
let dir = TempDir::new("readonly");
|
|
let file = dir.file("ro.sv");
|
|
fs::write(&file, "old\n").expect("seed");
|
|
fs::set_permissions(&file, fs::Permissions::from_mode(0o444)).expect("chmod");
|
|
let err = write_atomic(&file, b"new\n").expect_err("a read-only file is not replaced");
|
|
assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{err}");
|
|
assert_eq!(fs::read_to_string(&file).expect("read"), "old\n");
|
|
assert_eq!(dir.names(), vec!["ro.sv".to_string()], "no temp file was made");
|
|
fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).expect("restore");
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn writing_through_a_symlink_replaces_the_target_not_the_link() {
|
|
let dir = TempDir::new("symlink");
|
|
let real = dir.file("real.sv");
|
|
let link = dir.file("link.sv");
|
|
fs::write(&real, "old\n").expect("seed");
|
|
std::os::unix::fs::symlink(&real, &link).expect("symlink");
|
|
write_atomic(&link, b"new\n").expect("write");
|
|
assert_eq!(fs::read_to_string(&real).expect("read"), "new\n", "the target got the bytes");
|
|
assert!(
|
|
fs::symlink_metadata(&link).expect("stat").file_type().is_symlink(),
|
|
"the link is still a link"
|
|
);
|
|
assert_eq!(fs::read_to_string(&link).expect("read"), "new\n", "and still points at it");
|
|
}
|
|
|
|
/// The audit's probe (`docs/repository-analysis.md` finding 1), which
|
|
/// used to produce 100 write errors in 200 calls: both threads derived
|
|
/// the same temp name from the target and the pid, so one deleted the
|
|
/// other's file under it. Now every writer owns its own temp, so every
|
|
/// call succeeds and the target holds one writer's whole buffer.
|
|
#[test]
|
|
fn two_threads_writing_one_target_never_collide() {
|
|
const MIB: usize = 1024 * 1024;
|
|
const ROUNDS: usize = 100;
|
|
let dir = TempDir::new("race");
|
|
let file = dir.file("a.sv");
|
|
fs::write(&file, "seed\n").expect("seed");
|
|
|
|
// Three parties: the two writers and this thread, which inspects the
|
|
// target between rounds. Nobody starts a round until everyone has
|
|
// finished the last one.
|
|
let start = std::sync::Arc::new(std::sync::Barrier::new(3));
|
|
let done = std::sync::Arc::new(std::sync::Barrier::new(3));
|
|
let writers: Vec<_> = (*b"ab")
|
|
.into_iter()
|
|
.map(|tag| {
|
|
let (path, start, done) = (file.clone(), start.clone(), done.clone());
|
|
std::thread::spawn(move || {
|
|
let bytes = vec![tag; MIB];
|
|
let mut errors = Vec::new();
|
|
for _ in 0..ROUNDS {
|
|
start.wait();
|
|
if let Err(e) = write_atomic(&path, &bytes) {
|
|
errors.push(e.to_string());
|
|
}
|
|
done.wait();
|
|
}
|
|
errors
|
|
})
|
|
})
|
|
.collect();
|
|
|
|
for round in 0..ROUNDS {
|
|
start.wait();
|
|
done.wait();
|
|
let got = fs::read(&file).expect("read");
|
|
assert_eq!(got.len(), MIB, "round {round}: a partial buffer landed");
|
|
let tag = got[0];
|
|
assert!(tag == b'a' || tag == b'b', "round {round}: neither writer's byte");
|
|
assert!(got.iter().all(|&b| b == tag), "round {round}: two buffers were mixed");
|
|
assert_eq!(dir.names(), vec!["a.sv".to_string()], "round {round}: a temp was left");
|
|
}
|
|
|
|
let errors: Vec<String> =
|
|
writers.into_iter().flat_map(|w| w.join().expect("writer thread")).collect();
|
|
assert!(
|
|
errors.is_empty(),
|
|
"{} write errors in {} calls: {errors:?}",
|
|
errors.len(),
|
|
2 * ROUNDS
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn every_thread_gets_its_own_temp_name() {
|
|
const PER_THREAD: usize = 200;
|
|
let dir = TempDir::new("names");
|
|
let target = dir.file("a.sv");
|
|
let threads: Vec<_> = (0..4)
|
|
.map(|_| {
|
|
let target = target.clone();
|
|
std::thread::spawn(move || {
|
|
(0..PER_THREAD)
|
|
.map(|_| temp_path(&target).expect("temp name"))
|
|
.collect::<Vec<_>>()
|
|
})
|
|
})
|
|
.collect();
|
|
let names: Vec<PathBuf> =
|
|
threads.into_iter().flat_map(|t| t.join().expect("name thread")).collect();
|
|
let unique: std::collections::HashSet<&PathBuf> = names.iter().collect();
|
|
assert_eq!(unique.len(), names.len(), "a temp name was handed out twice");
|
|
}
|
|
|
|
/// The mode goes on while the temp is still empty, so a 0600 file's
|
|
/// replacement never holds its contents under the umask's wider bits.
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn the_temp_takes_the_targets_mode_before_any_bytes() {
|
|
use std::os::unix::fs::PermissionsExt;
|
|
let dir = TempDir::new("modewindow");
|
|
let target = dir.file("secret.sv");
|
|
fs::write(&target, "old\n").expect("seed");
|
|
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod");
|
|
|
|
let perms = target_permissions(&target);
|
|
let (tmp, mut file) = create_temp(&target, perms.is_some()).expect("temp");
|
|
// Born private, before any mode is copied onto it: an fd opened by
|
|
// someone else in this instant would not see the bytes to come.
|
|
assert_eq!(
|
|
fs::metadata(&tmp).expect("stat").permissions().mode() & 0o777,
|
|
0o600,
|
|
"the temp was created readable by others"
|
|
);
|
|
copy_mode(&file, perms.clone());
|
|
let meta = fs::metadata(&tmp).expect("stat");
|
|
assert_eq!(meta.len(), 0, "the mode is set before a single byte is written");
|
|
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "the temp is not world-readable");
|
|
// And the chmod does not close the door on the handle opened before it.
|
|
fill_temp(&mut file, &tmp, perms, b"new\n").expect("fill");
|
|
assert_eq!(fs::read_to_string(&tmp).expect("read"), "new\n");
|
|
let _ = fs::remove_file(&tmp);
|
|
}
|
|
|
|
/// The same window seen from outside, through a real `write_atomic`: a
|
|
/// big enough buffer that the temp is usually observable while it is
|
|
/// being filled. It asserts about what it sees and never about seeing it,
|
|
/// so a scheduler that hides the window cannot fail the test.
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn a_temp_seen_mid_write_is_never_world_readable() {
|
|
use std::os::unix::fs::PermissionsExt;
|
|
let dir = TempDir::new("window");
|
|
let target = dir.file("secret.sv");
|
|
fs::write(&target, "old\n").expect("seed");
|
|
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod");
|
|
|
|
let path = target.clone();
|
|
let writer = std::thread::spawn(move || {
|
|
let bytes = vec![b'x'; 8 * 1024 * 1024];
|
|
write_atomic(&path, &bytes)
|
|
});
|
|
while !writer.is_finished() {
|
|
for entry in fs::read_dir(&dir.path).expect("read dir").flatten() {
|
|
if !entry.file_name().to_string_lossy().ends_with(".lucisv-tmp") {
|
|
continue;
|
|
}
|
|
let Ok(meta) = entry.metadata() else { continue };
|
|
assert_eq!(
|
|
meta.permissions().mode() & 0o777,
|
|
0o600,
|
|
"a temp for a 0600 target was readable by others"
|
|
);
|
|
}
|
|
}
|
|
writer.join().expect("writer thread").expect("write");
|
|
assert_eq!(fs::metadata(&target).expect("stat").permissions().mode() & 0o777, 0o600);
|
|
}
|
|
}
|