use crate::error::CheckpointError;
use serde::{de::DeserializeOwned, Serialize};
use std::fs::{self, File, OpenOptions};
use std::io::{BufReader, BufWriter, Write};
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
#[cfg(unix)]
use libc::O_NOFOLLOW;
struct TempFileGuard {
path: PathBuf,
committed: bool,
}
impl TempFileGuard {
fn new(path: PathBuf) -> Self {
Self {
path,
committed: false,
}
}
fn commit(mut self) -> PathBuf {
self.committed = true;
std::mem::take(&mut self.path)
}
}
impl Drop for TempFileGuard {
fn drop(&mut self) {
if !self.committed && !self.path.as_os_str().is_empty() && fs::remove_file(&self.path).is_err() {
}
}
}
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
fn epoch_nanos(now: std::time::SystemTime) -> u128 {
now.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_else(|before_epoch| before_epoch.duration())
.as_nanos()
}
fn generate_unique_suffix() -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
std::process::id().hash(&mut hasher);
std::thread::current().id().hash(&mut hasher);
TEMP_COUNTER
.fetch_add(1, Ordering::SeqCst)
.hash(&mut hasher);
epoch_nanos(std::time::SystemTime::now()).hash(&mut hasher);
hasher.finish()
}
fn temporary_path(path: &Path) -> PathBuf {
let unique = generate_unique_suffix();
let mut temp_name = path
.file_name()
.map_or_else(|| "checkpoint".into(), std::ffi::OsStr::to_os_string);
temp_name.push(format!(".tmp.{unique:016x}"));
path.with_file_name(temp_name)
}
fn resolve_and_guard_path(path: &Path) -> Result<(), CheckpointError> {
let Some(parent) = path.parent() else { return Ok(()) };
if parent.as_os_str().is_empty() {
return Ok(());
}
let Ok(canonical_parent) = fs::canonicalize(parent) else {
return Ok(());
};
if let Ok(meta) = fs::symlink_metadata(path) {
if meta.file_type().is_symlink() {
let target = fs::read_link(path)
.map_err(|source| CheckpointError::from_io_error(path.to_path_buf(), source))?;
let target = if target.is_relative() {
parent.join(target)
} else {
target
};
let resolved = fs::canonicalize(&target)
.map_err(|_| CheckpointError::PathTraversal(path.to_path_buf()))?;
let Some(resolved_parent) = resolved.parent() else {
return Err(CheckpointError::PathTraversal(path.to_path_buf()));
};
if resolved_parent != canonical_parent {
return Err(CheckpointError::PathTraversal(path.to_path_buf()));
}
}
}
Ok(())
}
fn create_file_no_follow(path: &Path) -> Result<File, std::io::Error> {
let mut opts = OpenOptions::new();
opts.create(true).write(true).truncate(true);
#[cfg(unix)]
opts.custom_flags(O_NOFOLLOW);
opts.open(path)
}
fn open_file_no_follow(path: &Path) -> Result<File, std::io::Error> {
let mut opts = OpenOptions::new();
opts.read(true);
#[cfg(unix)]
opts.custom_flags(O_NOFOLLOW);
opts.open(path)
}
pub fn save(path: impl AsRef<Path>, state: &impl Serialize) -> Result<(), CheckpointError> {
let bytes = serde_json::to_vec(state).map_err(CheckpointError::Serialize)?;
atomic_write(path, &bytes)
}
pub fn atomic_write(path: impl AsRef<Path>, bytes: &[u8]) -> Result<(), CheckpointError> {
let path = path.as_ref();
if path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(CheckpointError::PathTraversal(path.to_path_buf()));
}
if let Some(parent) = path.parent() {
if !parent.as_os_str().is_empty() {
fs::create_dir_all(parent)
.map_err(|source| CheckpointError::from_io_error(parent.to_path_buf(), source))?;
}
}
resolve_and_guard_path(path)?;
let temp_path = temporary_path(path);
let guard = TempFileGuard::new(temp_path.clone());
let file = create_file_no_follow(&temp_path)
.map_err(|source| CheckpointError::from_io_error(temp_path.clone(), source))?;
let mut writer = BufWriter::new(file);
writer
.write_all(bytes)
.map_err(|source| CheckpointError::from_io_error(temp_path.clone(), source))?;
let file = writer
.into_inner()
.map_err(|e| CheckpointError::from_io_error(temp_path.clone(), e.into_error()))?;
file.sync_all()
.map_err(|source| CheckpointError::from_io_error(temp_path.clone(), source))?;
drop(file);
fs::rename(&temp_path, path)
.map_err(|source| CheckpointError::from_io_error(path.to_path_buf(), source))?;
sync_parent_dir(path)?;
let _committed_path = guard.commit();
Ok(())
}
fn sync_parent_dir(path: &Path) -> Result<(), CheckpointError> {
if let Some(parent) = path.parent() {
if parent.as_os_str().is_empty() {
return Ok(());
}
#[cfg(not(windows))]
{
let dir_file = File::open(parent)
.map_err(|source| CheckpointError::from_io_error(parent.to_path_buf(), source))?;
dir_file
.sync_all()
.map_err(|source| CheckpointError::from_io_error(parent.to_path_buf(), source))?;
}
}
Ok(())
}
pub fn load<T: DeserializeOwned>(path: impl AsRef<Path>) -> Result<Option<T>, CheckpointError> {
let path = path.as_ref();
if path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(CheckpointError::PathTraversal(path.to_path_buf()));
}
resolve_and_guard_path(path)?;
match open_file_no_follow(path) {
Ok(file) => {
match file.metadata() {
Ok(meta) if meta.len() == 0 => {
return Err(CheckpointError::CorruptCheckpoint(path.to_path_buf()));
}
Ok(_) => {}
Err(source) => {
return Err(CheckpointError::from_io_error(path.to_path_buf(), source));
}
}
let reader = BufReader::new(file);
Ok(Some(serde_json::from_reader::<_, T>(reader)?))
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(source) => Err(CheckpointError::from_io_error(path.to_path_buf(), source)),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generate_unique_suffix_produces_different_values() {
let v1 = generate_unique_suffix();
let v2 = generate_unique_suffix();
let v3 = generate_unique_suffix();
assert_ne!(v1, v2, "unique suffixes should be different");
assert_ne!(v2, v3, "unique suffixes should be different");
}
#[test]
fn temporary_path_includes_unique_suffix() {
let path = Path::new("/tmp/checkpoint.json");
let temp1 = temporary_path(path);
let temp2 = temporary_path(path);
assert_ne!(temp1, temp2, "temporary paths should be unique");
assert!(
temp1.to_string_lossy().contains(".tmp."),
"temp path should contain .tmp. suffix"
);
}
#[test]
fn epoch_nanos_preserves_pre_1970_clock_entropy_instead_of_zero() {
use std::time::{Duration, UNIX_EPOCH};
let before_epoch = UNIX_EPOCH - Duration::from_secs(5);
assert_eq!(
epoch_nanos(before_epoch),
5_000_000_000,
"pre-1970 clock must contribute its absolute offset, not 0"
);
assert_eq!(epoch_nanos(UNIX_EPOCH), 0);
assert_eq!(
epoch_nanos(UNIX_EPOCH + Duration::from_nanos(1_234)),
1_234,
"a normal clock contributes its forward distance from the epoch"
);
let after_epoch = UNIX_EPOCH + Duration::from_secs(5);
assert_ne!(
epoch_nanos(before_epoch),
0,
"the pre-1970 fallback must not degenerate to the old 0"
);
assert_eq!(epoch_nanos(before_epoch), epoch_nanos(after_epoch));
}
#[test]
fn load_rejects_empty_checkpoint_file_instead_of_restarting() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("state.json");
std::fs::write(&path, b"").expect("write empty checkpoint");
let result: Result<Option<u64>, _> = load(&path);
assert!(
matches!(&result, Err(CheckpointError::CorruptCheckpoint(p)) if p == &path),
"empty checkpoint must fail closed as CorruptCheckpoint, got {result:?}"
);
}
#[test]
fn load_reports_absent_checkpoint_as_none_not_error() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("missing.json");
let result: Result<Option<u64>, _> = load(&path);
assert!(
matches!(result, Ok(None)),
"an absent checkpoint must be Ok(None), got {result:?}"
);
}
#[test]
fn load_reads_back_a_real_checkpoint() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("state.json");
save(&path, &4_242_u64).expect("save");
let value: u64 = load(&path).expect("load ok").expect("some value");
assert_eq!(value, 4_242, "checkpoint must round-trip to the exact value");
}
}