Files
leleka/control-plane/src/immutable_directory.rs
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

167 lines
6.3 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())
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
let _ = (source, destination);
Err(io::Error::new(
io::ErrorKind::Unsupported,
"atomic no-replace directory publication requires Linux or macOS",
))
}
}
#[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]);
}
}