Skip to content
Open
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
241 changes: 228 additions & 13 deletions crates/victory-pipeline/src/cache.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::io::Write;
use std::fs::File;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

use anyhow::{Context, Result};

Expand Down Expand Up @@ -58,27 +60,48 @@ impl Cache {
let dir = path.parent().expect("hashed path has a parent");
std::fs::create_dir_all(dir)?;
// Write-then-rename so readers never see partial output.
let tmp = tempfile_in(dir);
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp)?;
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));
if published.is_err() {
if let Err(err) = written {
let _ = std::fs::remove_file(&tmp);
return Err(err.into());
}
if let Err(err) = std::fs::rename(&tmp, &path) {
let _ = std::fs::remove_file(&tmp);
if !path.is_file() {
return Err(err.into());
}
}
published?;
Ok(path)
}
}

fn tempfile_in(dir: &Path) -> PathBuf {
use std::sync::atomic::{AtomicU64, Ordering};
fn tempfile_in(dir: &Path) -> io::Result<(PathBuf, File)> {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
dir.join(format!(".tmp-{}-{n}", std::process::id()))
create_tempfile_in(dir, &COUNTER)
}

fn create_tempfile_in(dir: &Path, counter: &AtomicU64) -> io::Result<(PathBuf, File)> {
// An interrupted writer can leave a file behind, and process IDs are
// reused. Keep it intact and try a new name rather than failing a miss.
for _ in 0..128 {
let n = counter.fetch_add(1, Ordering::Relaxed);
let path = dir.join(format!(".tmp-{}-{n}", std::process::id()));
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
{
Ok(file) => return Ok((path, file)),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e),
}
}
Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"could not create a unique cache staging file after 128 attempts",
))
}

#[cfg(test)]
Expand Down Expand Up @@ -138,6 +161,198 @@ mod tests {
);
}

#[test]
fn staging_retries_collisions_without_changing_existing_files() {
let dir = tempfile::tempdir().unwrap();
let counter = AtomicU64::new(0);
for n in 0..2 {
std::fs::write(
dir.path().join(format!(".tmp-{}-{n}", std::process::id())),
b"stale",
)
.unwrap();
}

let (path, mut file) = create_tempfile_in(dir.path(), &counter).unwrap();
file.write_all(b"fresh").unwrap();
drop(file);
assert_eq!(
path.file_name().unwrap(),
format!(".tmp-{}-2", std::process::id()).as_str()
);
assert_eq!(std::fs::read(&path).unwrap(), b"fresh");
for n in 0..2 {
assert_eq!(
std::fs::read(dir.path().join(format!(".tmp-{}-{n}", std::process::id()))).unwrap(),
b"stale"
);
}
assert_eq!(counter.load(Ordering::Relaxed), 3);
}

#[test]
fn staging_collision_retries_are_bounded() {
let dir = tempfile::tempdir().unwrap();
let counter = AtomicU64::new(0);
for n in 0..128 {
std::fs::write(
dir.path().join(format!(".tmp-{}-{n}", std::process::id())),
b"stale",
)
.unwrap();
}

let error = create_tempfile_in(dir.path(), &counter).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
assert_eq!(counter.load(Ordering::Relaxed), 128);
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 128);
}

#[test]
fn staging_does_not_retry_other_io_errors() {
let dir = tempfile::tempdir().unwrap();
let counter = AtomicU64::new(0);
let missing = dir.path().join("missing");

let error = create_tempfile_in(&missing, &counter).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::NotFound);
assert_eq!(counter.load(Ordering::Relaxed), 1);
assert!(!missing.exists());
}

#[cfg(windows)]
#[test]
fn accepts_entry_published_concurrently_while_open() {
use std::os::windows::fs::OpenOptionsExt;

struct RacingUpper {
cache: Cache,
held: std::sync::Mutex<Option<std::fs::File>>,
}

impl Converter for RacingUpper {
fn id(&self) -> &'static str {
"test.upper"
}
fn version(&self) -> u32 {
1
}
fn convert(&self, input: &[u8]) -> Result<Vec<u8>> {
let output = input.to_ascii_uppercase();
let key = CacheKey::new(self, input);
let path = self.cache.path_for(&key);
std::fs::create_dir_all(path.parent().unwrap())?;
std::fs::write(&path, &output)?;
// FILE_SHARE_READ permits readers but prevents replacement while held.
*self.held.lock().unwrap() = Some(
std::fs::OpenOptions::new()
.read(true)
.share_mode(1)
.open(&path)?,
);
let (probe, mut file) = tempfile_in(path.parent().unwrap())?;
file.write_all(&output)?;
drop(file);
assert!(
std::fs::rename(&probe, &path).is_err(),
"the open reader must prevent replacing the published entry"
);
std::fs::remove_file(probe)?;
Ok(output)
}
}

let tmp = tempfile::tempdir().unwrap();
let cache = Cache::open(tmp.path().join("cache")).unwrap();
let conv = RacingUpper {
cache: cache.clone(),
held: std::sync::Mutex::new(None),
};
let path = cache.get_or_convert(&conv, b"abc").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"ABC");
assert_eq!(
std::fs::read_dir(path.parent().unwrap()).unwrap().count(),
1
);
}

#[cfg(windows)]
#[test]
fn stale_staging_and_open_reader_can_coexist() {
use std::os::windows::fs::OpenOptionsExt;

const CHILD: &str = "VICTORY_CACHE_COMPOSITION_CHILD";
if std::env::var_os(CHILD).is_none() {
// A fresh test process isolates the staging counter without
// changing production code or racing the other cache tests.
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"cache::tests::stale_staging_and_open_reader_can_coexist",
"--nocapture",
])
.env(CHILD, "1")
.output()
.unwrap();
assert!(
output.status.success(),
"isolated cache test failed:\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
return;
}

struct RacingUpper {
cache: Cache,
held: std::sync::Mutex<Option<std::fs::File>>,
}

impl Converter for RacingUpper {
fn id(&self) -> &'static str {
"test.cache-composition"
}
fn version(&self) -> u32 {
1
}
fn convert(&self, input: &[u8]) -> Result<Vec<u8>> {
let output = input.to_ascii_uppercase();
let path = self.cache.path_for(&CacheKey::new(self, input));
let dir = path.parent().unwrap();
std::fs::create_dir_all(dir)?;
// The isolated process has not requested a staging name.
std::fs::write(dir.join(format!(".tmp-{}-0", std::process::id())), b"stale")?;
std::fs::write(&path, &output)?;
*self.held.lock().unwrap() = Some(
std::fs::OpenOptions::new()
.read(true)
.share_mode(1) // FILE_SHARE_READ, not FILE_SHARE_DELETE
.open(&path)?,
);
let probe = dir.join("replacement-probe");
std::fs::write(&probe, b"probe")?;
assert!(std::fs::rename(&probe, &path).is_err());
std::fs::remove_file(probe)?;
Ok(output)
}
}

let tmp = tempfile::tempdir().unwrap();
let cache = Cache::open(tmp.path().join("cache")).unwrap();
let conv = RacingUpper {
cache: cache.clone(),
held: std::sync::Mutex::new(None),
};
let path = cache.get_or_convert(&conv, b"abc").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"ABC");
let dir = path.parent().unwrap();
assert_eq!(
std::fs::read(dir.join(format!(".tmp-{}-0", std::process::id()))).unwrap(),
b"stale"
);
assert_eq!(std::fs::read_dir(dir).unwrap().count(), 2);
}

#[test]
fn version_bump_invalidates() {
let v1 = Upper {
Expand Down