Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 72 additions & 1 deletion d3d12/crates/leonida-pipeline/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,18 @@ impl Cache {
let (tmp, mut file) = tempfile_in(dir)?;
let written = file.write_all(&output);
drop(file);
let published = written.and_then(|()| std::fs::rename(&tmp, &path));
let published = written.and_then(|()| match std::fs::rename(&tmp, &path) {
Ok(()) => Ok(()),
// Content-addressed: another concurrent writer may have already
// published the same key while we were converting (on Windows,
// rename over an open/read-locked destination fails with
// AccessDenied).
Err(_) if path.is_file() => {
let _ = std::fs::remove_file(&tmp);
Ok(())
}
Err(e) => Err(e),
});
if published.is_err() {
let _ = std::fs::remove_file(&tmp);
}
Expand Down Expand Up @@ -233,4 +244,64 @@ mod tests {
let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("cache");
assert!(Cache::open(inside).is_err());
}

#[test]
fn concurrent_publish_while_reader_holds_destination_succeeds_and_cleans_staging() {
use std::sync::Mutex;

struct RacingPublish {
target: PathBuf,
held: Mutex<Option<File>>,
}

impl Converter for RacingPublish {
fn id(&self) -> &'static str {
"test.racing"
}
fn version(&self) -> u32 {
1
}
fn convert(&self, input: &[u8]) -> Result<Vec<u8>> {
let bytes = input.to_ascii_uppercase();
// Simulate another thread/process publishing the same
// content-addressed file and holding a reader handle without
// FILE_SHARE_DELETE before our rename runs.
std::fs::create_dir_all(self.target.parent().unwrap())?;
std::fs::write(&self.target, &bytes)?;
#[cfg(windows)]
let reader = {
use std::os::windows::fs::OpenOptionsExt;
std::fs::OpenOptions::new()
.read(true)
.share_mode(1) // FILE_SHARE_READ only
.open(&self.target)?
};
#[cfg(not(windows))]
let reader = File::open(&self.target)?;
*self.held.lock().unwrap() = Some(reader);
Ok(bytes)
}
}

let tmp = tempfile::tempdir().unwrap();
let cache = Cache::open(tmp.path().join("cache")).unwrap();
let probe = RacingPublish {
target: PathBuf::new(),
held: Mutex::new(None),
};
let target = cache.path_for(&CacheKey::new(&probe, b"race"));
let conv = RacingPublish {
target: target.clone(),
held: Mutex::new(None),
};

let got = cache.get_or_convert(&conv, b"race").unwrap();
assert_eq!(got, target);
assert_eq!(std::fs::read(&got).unwrap(), b"RACE");
// No leftover `.tmp-*` staging file in the shard directory.
assert_eq!(
std::fs::read_dir(target.parent().unwrap()).unwrap().count(),
1
);
}
}