use std::fs::File;
use std::io::Write;
use std::path::Path;
use crate::sort::chunk::RUN_EXTENSION;
use crate::sort::error::SortRunError;
use crate::tiles_error::{Result, TilesError};
pub const PHASE1_MARKER: &str = "phase1.complete";
pub const RECLAIM_MARKER: &str = "merge.reclaiming";
fn write_marker(dir: &Path, name: &str, text: &str) -> Result<()> {
let path = dir.join(name);
let io = |op: &'static str| {
let path = path.clone();
move |source| TilesError::from(SortRunError::Io { op, path, source })
};
let mut file = File::create(&path).map_err(io("create"))?;
file.write_all(text.as_bytes()).map_err(io("write"))?;
file.sync_all().map_err(io("sync"))?;
Ok(())
}
pub fn clean_up(dir: &Path) -> std::io::Result<()> {
let mut first_error = None;
for entry in std::fs::read_dir(dir)? {
let path = match entry {
Ok(entry) => entry.path(),
Err(e) => {
first_error.get_or_insert(e);
continue;
}
};
let name = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or_default();
let ours = name == PHASE1_MARKER
|| name == RECLAIM_MARKER
|| (name.starts_with("chunk_") && path.extension().is_some_and(|e| e == RUN_EXTENSION));
if ours
&& path.is_file()
&& let Err(e) = std::fs::remove_file(&path)
{
first_error.get_or_insert(e);
}
}
if let Some(e) = first_error {
return Err(e);
}
match std::fs::remove_dir(dir) {
Err(e) if e.kind() != std::io::ErrorKind::DirectoryNotEmpty => Err(e),
_ => Ok(()),
}
}
pub fn mark_phase1_complete(dir: &Path, runs: usize) -> Result<()> {
write_marker(dir, PHASE1_MARKER, &format!("runs {runs}\n"))
}
pub fn mark_reclaiming(dir: &Path) -> Result<()> {
write_marker(
dir,
RECLAIM_MARKER,
"the runs of this folder are being consumed\n",
)
}
pub fn check_resumable(dir: &Path, found: usize) -> Result<()> {
if dir.join(RECLAIM_MARKER).exists() {
return Err(TilesError::ChunksConsumed {
path: dir.to_path_buf(),
});
}
let marker = dir.join(PHASE1_MARKER);
let text = std::fs::read_to_string(&marker).map_err(|source| {
if source.kind() == std::io::ErrorKind::NotFound {
TilesError::Phase1Incomplete {
path: dir.to_path_buf(),
}
} else {
TilesError::from(SortRunError::Io {
op: "read",
path: marker.clone(),
source,
})
}
})?;
let expected: usize = text
.strip_prefix("runs ")
.and_then(|rest| rest.trim().parse().ok())
.ok_or_else(|| TilesError::Phase1Incomplete {
path: dir.to_path_buf(),
})?;
if expected != found {
return Err(TilesError::RunCountMismatch {
path: dir.to_path_buf(),
expected,
found,
});
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_folder_without_the_marker_is_not_resumable() {
let dir = tempfile::tempdir().expect("tmpdir");
assert!(matches!(
check_resumable(dir.path(), 3),
Err(TilesError::Phase1Incomplete { .. })
));
}
#[test]
fn the_count_must_match() {
let dir = tempfile::tempdir().expect("tmpdir");
mark_phase1_complete(dir.path(), 3).expect("mark");
assert!(check_resumable(dir.path(), 3).is_ok());
assert!(matches!(
check_resumable(dir.path(), 2),
Err(TilesError::RunCountMismatch {
expected: 3,
found: 2,
..
})
));
}
#[test]
fn a_reclaiming_merge_makes_the_folder_unresumable_whatever_the_count() {
let dir = tempfile::tempdir().expect("tmpdir");
mark_phase1_complete(dir.path(), 3).expect("mark");
mark_reclaiming(dir.path()).expect("mark");
assert!(matches!(
check_resumable(dir.path(), 3),
Err(TilesError::ChunksConsumed { .. })
));
}
#[test]
fn a_marker_with_junk_is_refused() {
let dir = tempfile::tempdir().expect("tmpdir");
std::fs::write(dir.path().join(PHASE1_MARKER), "garbage").expect("write");
assert!(matches!(
check_resumable(dir.path(), 1),
Err(TilesError::Phase1Incomplete { .. })
));
}
#[test]
fn clean_up_removes_the_runs_and_markers_and_keeps_foreign_files() {
let dir = tempfile::tempdir().expect("tmpdir");
let p = dir.path();
std::fs::write(p.join("chunk_000000.run"), b"run").expect("write");
std::fs::write(p.join("chunk_000001.run"), b"run").expect("write");
mark_phase1_complete(p, 2).expect("mark");
mark_reclaiming(p).expect("mark");
std::fs::write(p.join("notes.txt"), b"mine").expect("write");
std::fs::write(p.join("other.run"), b"not a chunk").expect("write");
std::fs::create_dir(p.join("sub")).expect("dir");
std::fs::write(p.join("sub/chunk_000009.run"), b"nested").expect("write");
clean_up(p).expect("clean up");
let mut left: Vec<String> = std::fs::read_dir(p)
.expect("read")
.map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
.collect();
left.sort();
assert_eq!(left, ["notes.txt", "other.run", "sub"]);
assert!(p.join("sub/chunk_000009.run").exists(), "no descent");
}
#[test]
fn clean_up_removes_a_folder_that_holds_only_the_build_files() {
let dir = tempfile::tempdir().expect("tmpdir");
let sort = dir.path().join("sort");
std::fs::create_dir(&sort).expect("dir");
std::fs::write(sort.join("chunk_000000.run"), b"run").expect("write");
mark_phase1_complete(&sort, 1).expect("mark");
clean_up(&sort).expect("clean up");
assert!(!sort.exists());
}
}