use std::path::{Path, PathBuf};
#[derive(Debug, Clone)]
pub(crate) struct AtomicWriteReport {
pub tee_snapshot: crate::edit_safety::tee::TeeSnapshot,
}
fn authority_refused(
refusal: crate::live_index::index_lifecycle::authority::AuthorityRefusal,
) -> std::io::Error {
std::io::Error::other(format!("source mutation authority refused: {refusal:?}"))
}
pub(crate) fn atomic_write_file(
repo_root: &Path,
project_state_dir: Option<&crate::domain::ProjectStateDir>,
path: &Path,
content: &[u8],
) -> std::io::Result<AtomicWriteReport> {
atomic_write_file_expected(repo_root, project_state_dir, path, content, None)
}
pub(crate) fn atomic_write_file_expected(
repo_root: &Path,
project_state_dir: Option<&crate::domain::ProjectStateDir>,
path: &Path,
content: &[u8],
expected_publication: Option<crate::lifecycle_identity::PublicationIdentity>,
) -> std::io::Result<AtomicWriteReport> {
let tee_snapshot = match project_state_dir {
Some(state_dir) => crate::edit_safety::tee::Tee::for_repo(repo_root, state_dir)
.snapshot(path)
.unwrap_or_else(|err| crate::edit_safety::tee::TeeSnapshot::Warning {
original_path: path.to_path_buf(),
message: format!("unexpected tee snapshot error: {err}"),
}),
None => crate::edit_safety::tee::TeeSnapshot::Warning {
original_path: path.to_path_buf(),
message: "project state unavailable; tee snapshot disabled".to_string(),
},
};
match path.strip_prefix(repo_root) {
Ok(relative) => {
match path.parent() {
None => {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"path has no parent directory",
));
}
Some(parent) if !parent.exists() => {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
"target parent directory does not exist",
));
}
Some(_) => {}
}
let authority =
crate::live_index::index_lifecycle::activation::project_source_authority(repo_root);
let mut write = {
let mut attempts = 0u32;
loop {
let acquisition = match expected_publication {
Some(expected) => authority.acquire_write_expected(expected),
None => authority.acquire_write(),
};
match acquisition {
Ok(write) => break write,
Err(
refusal @ crate::live_index::index_lifecycle::authority::AuthorityRefusal::PhaseNotCurrent { .. },
) => {
attempts += 1;
if attempts >= 80 {
return Err(authority_refused(refusal));
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
Err(refusal) => return Err(authority_refused(refusal)),
}
}
};
let receipt = write.write(relative, content).map_err(authority_refused)?;
write.finish_committed(receipt).map_err(authority_refused)?;
}
Err(_) => {
if expected_publication.is_some() {
return Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"expected-publication writes cannot leave their source root",
));
}
use std::io::Write;
let parent = path.parent().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"path has no parent directory",
)
})?;
let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
tmp.write_all(content)?;
tmp.flush()?;
tmp.as_file().sync_all()?;
tmp.persist(path).map_err(|e| e.error)?;
}
}
Ok(AtomicWriteReport { tee_snapshot })
}
pub(crate) enum GuardedWriteOutcome {
Written(AtomicWriteReport),
Rejected,
}
#[cfg(all(test, feature = "server"))]
pub(crate) use write_interleave::install as install_write_interleave_hook;
static PATH_WRITE_LOCKS: std::sync::OnceLock<
std::sync::Mutex<std::collections::HashMap<PathBuf, std::sync::Arc<std::sync::Mutex<()>>>>,
> = std::sync::OnceLock::new();
pub(crate) fn lock_for_path(key: &Path) -> std::sync::Arc<std::sync::Mutex<()>> {
let map =
PATH_WRITE_LOCKS.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
let mut guard = map.lock().expect("path write-lock map poisoned");
std::sync::Arc::clone(
guard
.entry(key.to_path_buf())
.or_insert_with(|| std::sync::Arc::new(std::sync::Mutex::new(()))),
)
}
pub(crate) fn guarded_atomic_write_file(
repo_root: &Path,
project_state_dir: Option<&crate::domain::ProjectStateDir>,
path: &Path,
base: &[u8],
new_content: &[u8],
if_match: Option<&str>,
) -> std::io::Result<GuardedWriteOutcome> {
guarded_atomic_write_file_expected(
repo_root,
project_state_dir,
path,
base,
new_content,
if_match,
None,
)
}
pub(crate) fn guarded_atomic_write_file_expected(
repo_root: &Path,
project_state_dir: Option<&crate::domain::ProjectStateDir>,
path: &Path,
base: &[u8],
new_content: &[u8],
if_match: Option<&str>,
expected_publication: Option<crate::lifecycle_identity::PublicationIdentity>,
) -> std::io::Result<GuardedWriteOutcome> {
let pinned = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
let lock = lock_for_path(&pinned);
let _write_lock = lock.lock().expect("per-path write lock poisoned");
#[cfg(test)]
write_interleave::fire();
if if_match.is_some() {
match std::fs::read(&pinned) {
Ok(on_disk) => {
if on_disk.as_slice() != base {
return Ok(GuardedWriteOutcome::Rejected);
}
}
Err(err) => return Err(err),
}
}
atomic_write_file_expected(
repo_root,
project_state_dir,
path,
new_content,
expected_publication,
)
.map(GuardedWriteOutcome::Written)
}
pub(crate) fn format_tee_snapshot_suffix(report: &AtomicWriteReport) -> String {
report
.tee_snapshot
.response_hint()
.map(|hint| format!("\n{hint}"))
.unwrap_or_default()
}
#[cfg(test)]
mod write_interleave {
use std::cell::RefCell;
type Hook = Box<dyn Fn()>;
thread_local! {
static HOOK: RefCell<Option<Hook>> = const { RefCell::new(None) };
}
#[cfg(feature = "server")]
pub(crate) struct InterleaveGuard;
#[cfg(feature = "server")]
impl Drop for InterleaveGuard {
fn drop(&mut self) {
HOOK.with(|h| *h.borrow_mut() = None);
}
}
#[cfg(feature = "server")]
pub(crate) fn install(hook: impl Fn() + 'static) -> InterleaveGuard {
HOOK.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
InterleaveGuard
}
pub(crate) fn fire() {
let hook = HOOK.with(|h| h.borrow_mut().take());
if let Some(hook) = hook {
hook();
}
}
}