checkpointkit 0.1.1

Crash-resume checkpoint persistence with atomic writes and progress tracking
Documentation
//! Input/Output operations for saving and loading checkpoints.

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;

/// Guard that cleans up a temp file unless explicitly committed.
///
/// `Drop` attempts [`std::fs::remove_file`]; failures cannot be reported because `Drop` has no
/// `Result` channel - callers rely on atomic `rename` for durability, not on temp deletion.
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() {
            if fs::remove_file(&self.path).is_err() {
                // Best-effort cleanup; `Drop` cannot report I/O failures to the caller.
            }
        }
    }
}

static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

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);
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos()
        .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> {
    // The caller already rejects literal `..` components. This function defends
    // against pre-existing symlinks that would cause reads/writes to escape the
    // requested parent directory.
    let Some(parent) = path.parent() else { return Ok(()) };
    if parent.as_os_str().is_empty() {
        return Ok(());
    }

    let canonical_parent = match fs::canonicalize(parent) {
        Ok(p) => p,
        // Parent does not exist yet (load on missing checkpoint) or is inaccessible.
        // Let the later I/O operation surface that error.
        Err(_) => 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)
}

/// Saves serializable state to `path` using unique temp file + rename for atomic replacement.
///
/// This operation is safe for concurrent use - multiple threads/processes can
/// save to the same path simultaneously without data corruption.
///
/// On error, any temporary files are automatically cleaned up.
///
/// # Examples
///
/// ```rust
/// use checkpointkit::save;
///
/// let path = tempfile::tempdir().unwrap().path().join("state.json");
/// save(&path, &42).unwrap();
/// ```
///
/// # Errors
///
/// Returns an error when the parent directory cannot be created, when the state
/// cannot be serialized to JSON, when the disk is full, or when the checkpoint
/// file cannot be written and atomically renamed into place.
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)
}

/// Atomically writes raw bytes to `path` using a unique temp file + rename.
///
/// This is the durability primitive underneath [`save`] (which is simply
/// `serialize` + `atomic_write`), exposed for callers that serialize their own
/// payload — e.g. a checkpoint format that is not plain compact JSON, or a
/// caller that layers additional locking/backup on top. Guarantees are
/// identical to [`save`]: `..` and symlink path-traversal guards, `O_NOFOLLOW`
/// temp creation, fsync of both the file and its parent directory, atomic
/// rename into place, and automatic temp-file cleanup on any error.
///
/// Safe for concurrent use: the temp file name is process/thread/counter
/// unique, so multiple writers to the same `path` never corrupt each other.
///
/// # Errors
///
/// Returns an error when `path` contains a `..` component or resolves through a
/// symlink escaping its parent, when the parent directory cannot be created,
/// when the disk is full, or when the temp file cannot be written and
/// atomically renamed into place.
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(())
}

/// Loads serializable state from `path`, returning `Ok(None)` when no checkpoint exists.
///
/// # Examples
///
/// ```rust
/// use checkpointkit::{save, load};
///
/// let path = tempfile::tempdir().unwrap().path().join("state.json");
/// save(&path, &42).unwrap();
/// let value: i32 = load(&path).unwrap().unwrap();
/// assert_eq!(value, 42);
/// ```
///
/// # Errors
///
/// Returns an error when an existing checkpoint cannot be read or when the
/// checkpoint contents are not valid JSON for `T`.
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) => {
            if file.metadata().is_ok_and(|m| m.len() == 0) {
                return Ok(None);
            }
            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"
        );
    }
}