docuparse 0.0.1

Document extraction and parsing — PDF text, rendering, and OCR
Documentation
use std::{fs, io::Read, path::Path};

use crate::{
    error::ValidationError,
    utils::{MAX_PDF_SIZE, MB, MIN_PDF_SIZE, PDF_MAGIC},
};

fn validate_exists(path: &Path) -> Result<(), ValidationError> {
    if !path.exists() {
        return Err(ValidationError::NotFound {
            path: path.display().to_string(),
        });
    }

    if !path.is_file() {
        return Err(ValidationError::NotAFile {
            path: path.display().to_string(),
        });
    }

    Ok(())
}

fn validate_size(path: &Path) -> Result<(), ValidationError> {
    let size = fs::metadata(path).map_err(ValidationError::Io)?.len();

    match size {
        s if s < MIN_PDF_SIZE => Err(ValidationError::TooSmall {
            size: s,
            min: MIN_PDF_SIZE,
        }),
        s if s > MAX_PDF_SIZE => Err(ValidationError::FileTooLarge {
            size_mb: s,
            max_mb: MAX_PDF_SIZE / MB,
        }),
        _ => Ok(()),
    }
}

fn validate_magic_bytes(path: &Path) -> Result<(), ValidationError> {
    let mut file = fs::File::open(path).map_err(ValidationError::Io)?;

    let mut header = [0u8; PDF_MAGIC.len()];

    file.read_exact(&mut header)
        .map_err(|_| ValidationError::InvalidMagicBytes)?;

    if header != *PDF_MAGIC {
        return Err(ValidationError::InvalidMagicBytes);
    }

    Ok(())
}

pub fn validate_pdf(path: &Path) -> Result<(), ValidationError> {
    validate_exists(path)?;
    validate_size(path)?;
    validate_magic_bytes(path)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::{fs, io::Write};

    use rstest::{fixture, rstest};
    use tempfile::{NamedTempFile, TempDir};

    use super::*;

    // ── fixtures ────────────────────────────────────────────────────────────────

    /// A valid, minimal PDF file on disk.
    #[fixture]
    fn valid_pdf() -> NamedTempFile {
        let mut f = NamedTempFile::new().expect("tempfile");
        // Write magic bytes followed by enough padding to satisfy MIN_PDF_SIZE.
        f.write_all(PDF_MAGIC).expect("write magic");
        let padding = vec![0u8; (MIN_PDF_SIZE as usize).saturating_sub(PDF_MAGIC.len())];
        f.write_all(&padding).expect("write padding");
        f
    }

    /// A temp file whose content is deliberately *not* a PDF (wrong magic),
    /// but is large enough to pass the size check.
    #[fixture]
    fn non_pdf_file() -> NamedTempFile {
        let mut f = NamedTempFile::new().expect("tempfile");

        // Body must be >= MIN_PDF_SIZE so validate_size doesn't short-circuit
        // before validate_magic_bytes gets a chance to run.
        let size = MIN_PDF_SIZE as usize;
        let mut content = vec![0u8; size];

        // Stomp the first bytes with something that is explicitly not PDF_MAGIC.
        let fake_magic = b"NOT_PDF!";
        content[..fake_magic.len()].copy_from_slice(fake_magic);
        f.write_all(&content).expect("write");

        f
    }

    /// A temp file that is too small (below MIN_PDF_SIZE), but has correct magic.
    #[fixture]
    fn too_small_pdf() -> NamedTempFile {
        let mut f = NamedTempFile::new().expect("tempfile");
        // Write only the magic bytes — guaranteed to be < MIN_PDF_SIZE.
        f.write_all(PDF_MAGIC).expect("write magic");
        f
    }

    /// A temp file that exceeds MAX_PDF_SIZE.
    #[fixture]
    fn too_large_pdf() -> NamedTempFile {
        let mut f = NamedTempFile::new().expect("tempfile");
        f.write_all(PDF_MAGIC).expect("write magic");
        let overflow = vec![0u8; (MAX_PDF_SIZE as usize) + 1];
        f.write_all(&overflow).expect("write overflow");
        f
    }

    /// A TempDir used to derive paths that simply do not exist.
    #[fixture]
    fn temp_dir() -> TempDir {
        tempfile::tempdir().expect("tempdir")
    }

    // ── validate_exists ─────────────────────────────────────────────────────────

    #[rstest]
    fn test_exists_ok(valid_pdf: NamedTempFile) {
        assert!(validate_exists(valid_pdf.path()).is_ok());
    }

    #[rstest]
    fn test_exists_missing_path(temp_dir: TempDir) {
        let ghost = temp_dir.path().join("does_not_exist.pdf");
        let err = validate_exists(&ghost).unwrap_err();
        assert!(
            matches!(err, ValidationError::NotFound { .. }),
            "expected NotFound, got {err:?}"
        );
    }

    #[rstest]
    fn test_exists_is_directory(temp_dir: TempDir) {
        // A directory is not a file.
        let err = validate_exists(temp_dir.path()).unwrap_err();
        assert!(
            matches!(err, ValidationError::NotAFile { .. }),
            "expected NotAFile, got {err:?}"
        );
    }

    // ── validate_size ───────────────────────────────────────────────────────────

    #[rstest]
    fn test_size_ok(valid_pdf: NamedTempFile) {
        assert!(validate_size(valid_pdf.path()).is_ok());
    }

    #[rstest]
    fn test_size_too_small(too_small_pdf: NamedTempFile) {
        let err = validate_size(too_small_pdf.path()).unwrap_err();
        assert!(
            matches!(err, ValidationError::TooSmall { .. }),
            "expected TooSmall, got {err:?}"
        );
    }

    #[rstest]
    fn test_size_too_large(too_large_pdf: NamedTempFile) {
        let err = validate_size(too_large_pdf.path()).unwrap_err();
        assert!(
            matches!(
                err,
                ValidationError::FileTooLarge { size_mb, max_mb }
                if size_mb > max_mb
            ),
            "expected FileTooLarge, got {err:?}"
        );
    }

    // ── validate_magic_bytes ────────────────────────────────────────────────────

    #[rstest]
    fn test_magic_bytes_ok(valid_pdf: NamedTempFile) {
        assert!(validate_magic_bytes(valid_pdf.path()).is_ok());
    }

    #[rstest]
    fn test_magic_bytes_wrong(non_pdf_file: NamedTempFile) {
        let err = validate_magic_bytes(non_pdf_file.path()).unwrap_err();
        assert!(
            matches!(err, ValidationError::InvalidMagicBytes),
            "expected InvalidMagicBytes, got {err:?}"
        );
    }

    #[rstest]
    fn test_magic_bytes_empty_file(temp_dir: TempDir) {
        // read_exact on a 0-byte file must surface InvalidMagicBytes, not an Io variant.
        let empty = temp_dir.path().join("empty.pdf");
        fs::write(&empty, b"").expect("write empty");
        let err = validate_magic_bytes(&empty).unwrap_err();
        assert!(
            matches!(err, ValidationError::InvalidMagicBytes),
            "expected InvalidMagicBytes on empty file, got {err:?}"
        );
    }

    // ── validate_pdf (integration of all three guards) ──────────────────────────

    #[rstest]
    fn test_validate_pdf_happy_path(valid_pdf: NamedTempFile) {
        assert!(validate_pdf(valid_pdf.path()).is_ok());
    }

    #[rstest]
    fn test_validate_pdf_missing(temp_dir: TempDir) {
        let ghost = temp_dir.path().join("ghost.pdf");
        assert!(matches!(
            validate_pdf(&ghost).unwrap_err(),
            ValidationError::NotFound { .. }
        ));
    }

    #[rstest]
    fn test_validate_pdf_too_small(too_small_pdf: NamedTempFile) {
        assert!(matches!(
            validate_pdf(too_small_pdf.path()).unwrap_err(),
            ValidationError::TooSmall { .. }
        ));
    }

    #[rstest]
    fn test_validate_pdf_too_large(too_large_pdf: NamedTempFile) {
        assert!(matches!(
            validate_pdf(too_large_pdf.path()).unwrap_err(),
            ValidationError::FileTooLarge { .. }
        ));
    }

    #[rstest]
    fn test_validate_pdf_wrong_magic(non_pdf_file: NamedTempFile) {
        assert!(matches!(
            validate_pdf(non_pdf_file.path()).unwrap_err(),
            ValidationError::InvalidMagicBytes
        ));
    }

    // ── parametric: boundary values around MIN_PDF_SIZE ─────────────────────────

    #[rstest]
    #[case(MIN_PDF_SIZE - 1, true)] // one byte below → TooSmall
    #[case(MIN_PDF_SIZE, false)] // exact minimum  → Ok
    #[case(MIN_PDF_SIZE + 1, false)] // one byte above → Ok
    fn test_size_boundary(#[case] size: u64, #[case] expect_err: bool, temp_dir: TempDir) {
        let path = temp_dir.path().join("boundary.pdf");
        // Prepend magic so magic-byte validation doesn't interfere.
        let mut content = PDF_MAGIC.to_vec();
        let body_len = (size as usize).saturating_sub(PDF_MAGIC.len());
        content.extend(vec![0u8; body_len]);
        // Truncate or pad to hit the exact target size.
        content.truncate(size as usize);
        fs::write(&path, &content).expect("write boundary file");

        let result = validate_size(&path);
        assert_eq!(
            result.is_err(),
            expect_err,
            "size={size}, expect_err={expect_err}"
        );
    }
}