Files
leleka/control-plane/src/immutable_directory.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 72fc3b0820 style: cargo fmt on strata-control, strata-desktop-core, leleka-runtime-client; clear Clippy lints and two red tests on main
Mechanical rustfmt (control-plane, desktop-core and the runtime client had 360 hunks of drift; the CI format steps for control-plane and
desktop-core were red), plus, found by running `cargo clippy -D warnings` and the tests on Linux:
* control-plane/tests/log_failure_sse.rs `no_panicking_log_macros_in_the_serving_crate` was red on main since the observability merge: two
  test-only `eprintln!` samples (prometheus.rs, request_log.rs) trip its source scan. They now write to stderr with `write_fmt` and
  ignore a failed write, which is what the test asks for; the output is the same.
* tool_output.rs `is_multiple_of(2)`, an unneeded `mut` in a control-plane test, a collapsible `if` in leleka-inference.rs,
  `#[allow(dead_code)]` on observer_adaptive_slots (compiled into leleka-inference-evaluation too).
* crates/deploy/src/facts.rs: `lab_holder_running` moved above `mod tests` (clippy::items_after_test_module); code moved, not changed.
Kept as its own commit so it can be redone with `cargo fmt` if other branches touch these crates first. No behaviour change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 00:30:27 +01:00

202 lines
7.7 KiB
Rust

//! Atomic publication of a new immutable directory. Existence checks alone
//! cannot protect an empty destination created immediately before rename.
use std::{io, path::Path};
pub(crate) fn publish(source: &Path, destination: &Path) -> io::Result<()> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
use std::{ffi::CString, os::unix::ffi::OsStrExt};
let source = CString::new(source.as_os_str().as_bytes())?;
let destination = CString::new(destination.as_os_str().as_bytes())?;
#[cfg(target_os = "linux")]
let result = unsafe {
// Rust's bundled musl exposes no renameat2 wrapper. Use the same
// kernel primitive through syscall, with the target's syscall ID.
libc::syscall(
libc::SYS_renameat2,
libc::AT_FDCWD,
source.as_ptr(),
libc::AT_FDCWD,
destination.as_ptr(),
libc::RENAME_NOREPLACE,
)
};
#[cfg(target_os = "macos")]
let result =
unsafe { libc::renamex_np(source.as_ptr(), destination.as_ptr(), libc::RENAME_EXCL) };
if result == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
// Windows: MoveFileExW without MOVEFILE_REPLACE_EXISTING never replaces anything (std::fs::rename may replace an
// empty directory), which is the same atomic no-replace guarantee.
#[cfg(target_os = "windows")]
{
use std::os::windows::ffi::OsStrExt;
let wide =
|path: &Path| -> Vec<u16> { path.as_os_str().encode_wide().chain(Some(0)).collect() };
let (from, to) = (wide(source), wide(destination));
// SAFETY: both buffers are NUL-terminated UTF-16 that outlive the call.
if unsafe {
windows_sys::Win32::Storage::FileSystem::MoveFileExW(from.as_ptr(), to.as_ptr(), 0)
} != 0
{
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
{
let _ = (source, destination);
Err(io::Error::new(
io::ErrorKind::Unsupported,
"atomic no-replace directory publication requires Linux or macOS",
))
}
}
#[cfg(all(test, target_os = "windows"))]
mod windows_tests {
use super::*;
#[test]
fn a_second_publication_onto_the_same_destination_is_refused() {
let root = std::env::temp_dir().join(format!("strata-publish-win-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("a")).unwrap();
std::fs::create_dir_all(root.join("b")).unwrap();
publish(&root.join("a"), &root.join("dest")).unwrap();
assert!(publish(&root.join("b"), &root.join("dest")).is_err());
assert!(root.join("b").is_dir() && root.join("dest").is_dir());
std::fs::remove_dir_all(&root).unwrap();
}
}
#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
mod tests {
use super::*;
use std::{
fs,
os::unix::fs::{MetadataExt, symlink},
path::PathBuf,
sync::{Arc, Barrier},
};
struct Temporary(PathBuf);
impl Temporary {
fn new() -> Self {
let path = std::env::temp_dir().join(format!(
"strata-publish-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir(&path).unwrap();
Self(path)
}
}
impl Drop for Temporary {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[test]
fn conflicts_preserve_even_empty_destination_and_source() {
let root = Temporary::new();
let source = root.0.join("stage");
fs::create_dir(&source).unwrap();
fs::write(source.join("payload"), b"complete bytes").unwrap();
for kind in ["empty", "nonempty", "file", "symlink", "dangling"] {
let target = root.0.join(kind);
match kind {
"empty" => fs::create_dir(&target).unwrap(),
"nonempty" => {
fs::create_dir(&target).unwrap();
fs::write(target.join("original"), b"keep").unwrap();
}
"file" => fs::write(&target, b"keep").unwrap(),
"symlink" => symlink(&source, &target).unwrap(),
_ => symlink(root.0.join("absent"), &target).unwrap(),
}
let before = fs::symlink_metadata(&target).unwrap();
assert_eq!(
publish(&source, &target).unwrap_err().kind(),
io::ErrorKind::AlreadyExists
);
assert_eq!(fs::symlink_metadata(&target).unwrap().ino(), before.ino());
assert_eq!(fs::read(source.join("payload")).unwrap(), b"complete bytes");
match kind {
"empty" => assert_eq!(fs::read_dir(&target).unwrap().count(), 0),
"nonempty" => assert_eq!(fs::read(target.join("original")).unwrap(), b"keep"),
"file" => assert_eq!(fs::read(&target).unwrap(), b"keep"),
_ => assert!(
fs::symlink_metadata(&target)
.unwrap()
.file_type()
.is_symlink()
),
}
}
#[cfg(target_os = "linux")]
let target = {
use std::os::unix::ffi::OsStringExt;
root.0
.join(std::ffi::OsString::from_vec(b"pack-\xff".to_vec()))
};
// APFS rejects invalid UTF-8 filenames independently of rename flags.
#[cfg(target_os = "macos")]
let target = root.0.join("pack-версія one");
publish(&source, &target).unwrap();
assert!(!source.exists());
assert_eq!(fs::read(target.join("payload")).unwrap(), b"complete bytes");
}
#[test]
fn concurrent_publish_has_one_complete_winner() {
let root = Temporary::new();
let target = root.0.join("version");
let barrier = Arc::new(Barrier::new(2));
let mut handles = Vec::new();
for number in 0..2u8 {
let source = root.0.join(format!("stage-{number}"));
fs::create_dir(&source).unwrap();
fs::write(source.join("payload"), vec![number; 1024]).unwrap();
fs::write(source.join("receipt"), [number]).unwrap();
let target = target.clone();
let barrier = barrier.clone();
handles.push(std::thread::spawn(move || {
barrier.wait();
(number, source.clone(), publish(&source, &target))
}));
}
let results = handles
.into_iter()
.map(|h| h.join().unwrap())
.collect::<Vec<_>>();
assert_eq!(results.iter().filter(|(_, _, r)| r.is_ok()).count(), 1);
let (winner, source, _) = results.iter().find(|(_, _, r)| r.is_ok()).unwrap();
assert!(!source.exists());
assert_eq!(
fs::read(target.join("payload")).unwrap(),
vec![*winner; 1024]
);
assert_eq!(fs::read(target.join("receipt")).unwrap(), [*winner]);
let (loser, source, error) = results.iter().find(|(_, _, r)| r.is_err()).unwrap();
assert_eq!(
error.as_ref().unwrap_err().kind(),
io::ErrorKind::AlreadyExists
);
assert_eq!(
fs::read(source.join("payload")).unwrap(),
vec![*loser; 1024]
);
assert_eq!(fs::read(source.join("receipt")).unwrap(), [*loser]);
}
}