migratrom 0.2.0

Declarative, self-verifying database migrations (core engine).
Documentation
//! Migration checksum API: canonical encoding, digesting, parsing, and verification.
//!
//! The runner records these strings in the history table and later verifies
//! them to detect edits to an already-applied migration body.

mod canonical;
mod hash;

pub use canonical::canonical_encode;
pub use hash::HashAlgorithm;

use crate::error::{MigratromError, Result};
use crate::types::Operation;

/// A parsed checksum string split into algorithm name and hex digest.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParsedChecksum {
    /// Registered hash algorithm name before the `/` separator.
    pub algo: String,
    /// Hex-encoded digest after the `/` separator.
    pub hex: String,
}

/// Compute the checksum of an operation list using the default algorithm.
pub fn checksum(operations: &[Operation]) -> String {
    checksum_with(operations, HashAlgorithm::DEFAULT)
}

/// Compute the checksum using a specific algorithm.
pub fn checksum_with(operations: &[Operation], algorithm: HashAlgorithm) -> String {
    let digest = algorithm.hash(&canonical_encode(operations));
    format!("{}/{}", algorithm.name(), hex::encode(digest))
}

/// Split a stored checksum on its first `/`, validating the hex digest.
pub fn parse_checksum(stored: &str) -> Result<ParsedChecksum> {
    let Some(slash) = stored.find('/') else {
        return Err(MigratromError::Config(format!(
            "malformed checksum (missing '/'): {stored}"
        )));
    };
    let algo = &stored[..slash];
    let hex = &stored[slash + 1..];
    let valid_hex = !hex.is_empty()
        && hex.len().is_multiple_of(2)
        && hex.bytes().all(|b| b.is_ascii_hexdigit());
    if algo.is_empty() || !valid_hex {
        return Err(MigratromError::Config(format!(
            "malformed checksum: {stored}"
        )));
    }
    Ok(ParsedChecksum {
        algo: algo.to_string(),
        hex: hex.to_string(),
    })
}

/// Verify a stored checksum against the current operation body.
///
/// Returns [`MigratromError::ChecksumMismatch`] when the recomputed digest
/// differs (case-insensitive), or [`MigratromError::Config`] when the stored
/// algorithm is unknown.
pub fn verify_checksum(stored: &str, operations: &[Operation], migration_id: i64) -> Result<()> {
    let parsed = parse_checksum(stored)?;
    let Some(algorithm) = HashAlgorithm::from_name(&parsed.algo) else {
        return Err(MigratromError::Config(format!(
            "unknown checksum algorithm: {}",
            parsed.algo
        )));
    };
    let actual = checksum_with(operations, algorithm);
    let actual_parsed = parse_checksum(&actual)?;
    if parsed.hex.eq_ignore_ascii_case(&actual_parsed.hex) {
        Ok(())
    } else {
        Err(MigratromError::ChecksumMismatch {
            id: migration_id,
            expected: stored.to_string(),
            actual,
        })
    }
}