use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
pub(crate) fn data_path(datadir: &Path, port: u16) -> PathBuf {
datadir.join(format!("{port}.json"))
}
pub(crate) fn temp_path(datadir: &Path, port: u16) -> PathBuf {
datadir.join(format!("{port}.json.tmp"))
}
pub(crate) fn cursors_path(datadir: &Path, port: u16) -> PathBuf {
datadir.join(format!("{port}.cursors"))
}
pub(crate) fn cursors_temp_path(datadir: &Path, port: u16) -> PathBuf {
datadir.join(format!("{port}.cursors.tmp"))
}
pub(crate) fn requests_path(datadir: &Path, port: u16) -> PathBuf {
datadir.join(format!("{port}.requests.jsonl"))
}
pub(crate) fn requests_temp_path(datadir: &Path, port: u16) -> PathBuf {
datadir.join(format!("{port}.requests.jsonl.tmp"))
}
pub(crate) async fn write_replacing(
datadir: &Path,
port: u16,
bytes: Vec<u8>,
persist: tokio::sync::OwnedMutexGuard<()>,
) -> io::Result<()> {
replace_file(
data_path(datadir, port),
temp_path(datadir, port),
bytes,
persist,
)
.await
}
pub(crate) async fn write_cursors_replacing(
datadir: &Path,
port: u16,
bytes: Vec<u8>,
persist: tokio::sync::OwnedMutexGuard<()>,
) -> io::Result<()> {
replace_file(
cursors_path(datadir, port),
cursors_temp_path(datadir, port),
bytes,
persist,
)
.await
}
async fn replace_file(
target: PathBuf,
temp: PathBuf,
bytes: Vec<u8>,
persist: tokio::sync::OwnedMutexGuard<()>,
) -> io::Result<()> {
tokio::task::spawn_blocking(move || {
let _persist = persist;
let written = write_and_sync(&temp, &bytes).and_then(|()| std::fs::rename(&temp, &target));
if written.is_err() {
match std::fs::remove_file(&temp) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => {
tracing::warn!(error = %e, ?temp, "could not remove a failed write's temp file")
}
}
}
written
})
.await
.map_err(io::Error::other)?
}
fn write_and_sync(path: &Path, bytes: &[u8]) -> io::Result<()> {
let mut file = std::fs::File::create(path)?;
file.write_all(bytes)?;
file.sync_data()
}
pub fn sweep_interrupted_writes(datadir: &Path) -> io::Result<Vec<PathBuf>> {
let mut removed = Vec::new();
for entry in std::fs::read_dir(datadir)? {
let path = entry?.path();
let is_ours = path
.file_name()
.and_then(|name| name.to_str())
.and_then(|name| {
name.strip_suffix(".json.tmp")
.or_else(|| name.strip_suffix(".cursors.tmp"))
.or_else(|| name.strip_suffix(".requests.jsonl.tmp"))
})
.is_some_and(|stem| {
stem.parse::<u16>()
.is_ok_and(|port| port.to_string() == stem)
});
if !is_ours {
continue;
}
match std::fs::remove_file(&path) {
Ok(()) => removed.push(path),
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
}
Ok(removed)
}
#[cfg(test)]
mod tests {
use super::*;
fn lock() -> tokio::sync::OwnedMutexGuard<()> {
std::sync::Arc::new(tokio::sync::Mutex::new(()))
.try_lock_owned()
.expect("uncontended")
}
#[tokio::test]
async fn a_write_replaces_the_file_and_leaves_no_temp_file() {
let dir = tempfile::tempdir().expect("tempdir");
std::fs::write(data_path(dir.path(), 4545), "old").expect("seed");
write_replacing(dir.path(), 4545, b"new".to_vec(), lock())
.await
.expect("write");
assert_eq!(
std::fs::read_to_string(data_path(dir.path(), 4545)).expect("read"),
"new"
);
assert!(!temp_path(dir.path(), 4545).exists());
}
#[tokio::test]
async fn a_failed_write_leaves_the_previous_file_intact() {
let dir = tempfile::tempdir().expect("tempdir");
std::fs::write(data_path(dir.path(), 4545), "old").expect("seed");
std::fs::create_dir(temp_path(dir.path(), 4545)).expect("block the temp path");
write_replacing(dir.path(), 4545, b"new".to_vec(), lock())
.await
.expect_err("the temp file cannot be created");
assert_eq!(
std::fs::read_to_string(data_path(dir.path(), 4545)).expect("read"),
"old"
);
}
#[tokio::test]
async fn a_failed_rename_removes_the_temp_file() {
let dir = tempfile::tempdir().expect("tempdir");
std::fs::create_dir(data_path(dir.path(), 4545)).expect("block the target");
std::fs::write(data_path(dir.path(), 4545).join("x"), "").expect("fill it");
write_replacing(dir.path(), 4545, b"new".to_vec(), lock())
.await
.expect_err("rename onto a non-empty directory fails");
assert!(!temp_path(dir.path(), 4545).exists());
}
#[test]
fn the_sweep_removes_only_port_named_temp_files() {
let dir = tempfile::tempdir().expect("tempdir");
for name in [
"4545.json.tmp",
"65535.json.tmp",
"4546.cursors.tmp",
"4547.requests.jsonl.tmp",
"4545.json",
"4546.cursors",
"4547.requests.jsonl",
"notes.requests.jsonl.tmp",
"notes.json.tmp",
"notes.cursors.tmp",
"65536.json.tmp",
"+80.json.tmp",
"04545.json.tmp",
"4545.tmp",
] {
std::fs::write(dir.path().join(name), "x").expect("seed");
}
let mut removed = sweep_interrupted_writes(dir.path()).expect("sweep");
removed.sort();
assert_eq!(
removed,
vec![
dir.path().join("4545.json.tmp"),
dir.path().join("4546.cursors.tmp"),
dir.path().join("4547.requests.jsonl.tmp"),
dir.path().join("65535.json.tmp")
]
);
for kept in [
"4545.json",
"4546.cursors",
"4547.requests.jsonl",
"notes.requests.jsonl.tmp",
"notes.json.tmp",
"notes.cursors.tmp",
"65536.json.tmp",
"+80.json.tmp",
"04545.json.tmp",
"4545.tmp",
] {
assert!(dir.path().join(kept).exists(), "{kept} must be kept");
}
}
}