use std::fs;
use std::path::Path;
pub(crate) fn sha256_hex_of(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
let out = Sha256::digest(bytes);
let mut hex = String::with_capacity(out.len() * 2);
for b in out {
use std::fmt::Write as _;
let _ = write!(hex, "{b:02x}");
}
hex
}
pub(crate) struct CasPathLock {
_file: fs::File,
}
impl CasPathLock {
pub(crate) fn acquire(source: &Path) -> std::io::Result<Self> {
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
let canonical = fs::canonicalize(source)?;
let key = sha256_hex_of(canonical.to_string_lossy().as_bytes());
let lock_path = std::env::temp_dir().join(format!("rhwp-cas-v1-{key}.lock"));
let mut options = fs::OpenOptions::new();
options.read(true).write(true).create(true);
#[cfg(unix)]
options.mode(0o600);
let file = options.open(lock_path)?;
file.lock()?;
Ok(Self { _file: file })
}
}
#[cfg(debug_assertions)]
pub(crate) fn cas_test_synchronize_before_lock() -> Result<(), String> {
let Some(directory) = std::env::var_os("RHWP_INTERNAL_TEST_CAS_BARRIER") else {
return Ok(());
};
let directory = std::path::PathBuf::from(directory);
fs::write(
directory.join(format!("arrived-{}", std::process::id())),
b"",
)
.map_err(|e| e.to_string())?;
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
loop {
let arrived = fs::read_dir(&directory)
.map_err(|e| e.to_string())?
.filter_map(Result::ok)
.filter(|entry| entry.file_name().to_string_lossy().starts_with("arrived-"))
.count();
if arrived >= 2 {
return Ok(());
}
if std::time::Instant::now() >= deadline {
return Err("CAS test barrier 에 두 프로세스가 도착하지 않았습니다".to_string());
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
#[cfg(not(debug_assertions))]
pub(crate) fn cas_test_synchronize_before_lock() -> Result<(), String> {
Ok(())
}
#[cfg(debug_assertions)]
pub(crate) fn cas_test_mark_checked_and_wait() {
let Some(directory) = std::env::var_os("RHWP_INTERNAL_TEST_CAS_BARRIER") else {
return;
};
let directory = std::path::PathBuf::from(directory);
let _ = fs::write(
directory.join(format!("checked-{}", std::process::id())),
b"",
);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1);
while std::time::Instant::now() < deadline {
let checked = fs::read_dir(&directory)
.ok()
.into_iter()
.flatten()
.filter_map(Result::ok)
.filter(|entry| entry.file_name().to_string_lossy().starts_with("checked-"))
.count();
if checked >= 2 {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
#[cfg(not(debug_assertions))]
pub(crate) fn cas_test_mark_checked_and_wait() {}