checkpointkit 0.1.1

Crash-resume checkpoint persistence with atomic writes and progress tracking
Documentation
//! Progress tracking utilities persisted through checkpoints.

use crate::error::CheckpointError;
use crate::io::{load, save};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

/// Progress tracker persisted through a checkpoint file.
///
/// # Examples
///
/// ```rust
/// use checkpointkit::ProgressTracker;
/// use std::time::Duration;
/// use tempfile::tempdir;
///
/// let dir = tempdir().unwrap();
/// let path = dir.path().join("progress.json");
/// let mut tracker = ProgressTracker::new(10, &path, Duration::ZERO).unwrap();
/// tracker.increment(3).unwrap();
/// assert_eq!(tracker.resume().unwrap(), 3);
/// ```
#[derive(Debug)]
pub struct ProgressTracker {
    total: u64,
    current: u64,
    path: PathBuf,
    interval: Duration,
    last_save: Instant,
    dirty: bool,
}

impl ProgressTracker {
    /// Creates a progress tracker, resuming previously saved progress when present.
    ///
    /// # Errors
    ///
    /// Returns an error when the checkpoint file cannot be read or when the
    /// saved progress payload is invalid.
    pub fn new(
        total: u64,
        path: impl AsRef<Path>,
        interval: Duration,
    ) -> Result<Self, CheckpointError> {
        let path = path.as_ref().to_path_buf();
        let current = load::<ProgressState>(&path)?.map_or(0, |state| state.progress.min(total));
        Ok(Self {
            total,
            current,
            path,
            interval,
            last_save: Instant::now(),
            dirty: false,
        })
    }

    pub fn increment(&mut self, n: u64) -> Result<u64, CheckpointError> {
        let previous = self.current;
        self.current = self.current.saturating_add(n).min(self.total);
        if self.current != previous {
            self.dirty = true;
        }
        if self.dirty
            && (self.interval.is_zero()
                || self.last_save.elapsed() >= self.interval
                || self.current == self.total)
        {
            self.persist()?;
        }
        Ok(self.current)
    }

    /// Returns the last saved progress value from disk.
    ///
    /// # Note
    ///
    /// This method performs a blocking read and JSON deserialization on every
    /// call. Callers that invoke it in hot loops should cache the returned value.
    ///
    /// # Errors
    ///
    /// Returns an error when the checkpoint file cannot be read or when the
    /// saved progress payload is invalid.
    pub fn resume(&self) -> Result<u64, CheckpointError> {
        Ok(load::<ProgressState>(&self.path)?.map_or(0, |state| state.progress.min(self.total)))
    }

    /// Returns the in-memory current progress value.
    #[must_use]
    pub const fn current(&self) -> u64 {
        self.current
    }

    /// Returns the configured total progress value.
    #[must_use]
    pub const fn total(&self) -> u64 {
        self.total
    }

    /// Flushes any unsaved progress to disk.
    ///
    /// # Errors
    ///
    /// Returns an error when the checkpoint cannot be written atomically.
    pub fn flush(&mut self) -> Result<(), CheckpointError> {
        self.dirty = true;
        self.persist()
    }

    fn persist(&mut self) -> Result<(), CheckpointError> {
        if !self.dirty {
            return Ok(());
        }
        save(
            &self.path,
            &ProgressState {
                total: self.total,
                progress: self.current,
            },
        )?;
        self.last_save = Instant::now();
        self.dirty = false;
        Ok(())
    }
}

impl Drop for ProgressTracker {
    fn drop(&mut self) {
        if self.dirty && self.persist().is_err() {
            // `Drop` cannot return `Result`; callers that require durability must call
            // [`ProgressTracker::flush`] before dropping the tracker.
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
struct ProgressState {
    total: u64,
    progress: u64,
}