legit-hasher 0.1.6

Every legit-hashes definition, images and text, for callers in any language: a command-line runner over JSON lines with resumable batches, and with the `serve` feature a worker that takes hashing tasks from Redis Streams
Documentation
//! `legit-hasher distance`: compare pairs of stored hashes or signatures, one JSON line each way.

use std::io::{BufRead, Write};

use legit_hashes::{Error as HashError, Hash, Signature};
use serde::Serialize;
use serde_json::{Map, Value};

use crate::request::Id;
use crate::{Error, FORMAT, Status, Summary};

/// Why a pair wasn't compared.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DistanceError {
    /// The line isn't an object with string fields `a` and `b`, an optional `id`, and no others.
    InvalidRequest,
    /// `a` or `b` isn't a stored form this runner reads.
    InvalidHash,
    /// `a` and `b` come from different definitions, or one is a bit hash and the other a
    /// signature.
    Mismatch,
}

impl DistanceError {
    /// The code as results carry it, such as `mismatch`.
    ///
    /// ```
    /// assert_eq!(legit_hasher::DistanceError::InvalidHash.as_str(), "invalid_hash");
    /// ```
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::InvalidRequest => "invalid_request",
            Self::InvalidHash => "invalid_hash",
            Self::Mismatch => "mismatch",
        }
    }
}

/// The comparison of one pair, as one JSON line.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Comparison {
    /// The format version of the line: [`FORMAT`].
    pub format: u32,
    /// The pair's `id`, when it gave one.
    pub id: Option<Id>,
    /// The input line, counting from 1, in batch mode. A task on a stream has none.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line: Option<u64>,
    /// Whether the pair was compared.
    pub status: Status,
    /// Why it wasn't.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_type: Option<DistanceError>,
    /// What was wrong, for a person.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// The definition both come from.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub definition: Option<&'static str>,
    /// For bit hashes, how many bits differ.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub distance: Option<u32>,
    /// For bit hashes, their width.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bits: Option<u32>,
    /// For signatures, how many values match.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub matching: Option<u32>,
    /// For signatures, how many values each holds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub values: Option<u32>,
    /// For signatures, the estimated Jaccard similarity: `matching / values`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub similarity: Option<f64>,
}

impl Comparison {
    fn new(id: Option<Id>, line: Option<u64>) -> Self {
        Self {
            format: FORMAT,
            id,
            line,
            status: Status::Success,
            error_type: None,
            error: None,
            definition: None,
            distance: None,
            bits: None,
            matching: None,
            values: None,
            similarity: None,
        }
    }

    fn failed(mut self, code: DistanceError, message: impl Into<String>) -> Self {
        self.status = Status::Error;
        self.error_type = Some(code);
        self.error = Some(message.into());
        self
    }
}

/// A stored form read as whichever kind it names.
enum Stored {
    Bit(Hash),
    Signature(Box<Signature>),
}

fn parse(name: &str, text: &str) -> Result<Stored, String> {
    match text.parse::<Hash>() {
        Ok(hash) => Ok(Stored::Bit(hash)),
        Err(HashError::NotABitHash(_)) => text
            .parse::<Signature>()
            .map(|signature| Stored::Signature(Box::new(signature)))
            .map_err(|error| format!("`{name}`: {error}")),
        Err(error) => Err(format!("`{name}`: {error}")),
    }
}

/// Compare the pair on one line: `{"id": ..., "a": "<stored form>", "b": "<stored form>"}`.
#[must_use]
pub fn compare(line: &[u8], number: u64) -> Comparison {
    let pair: Map<String, Value> = match serde_json::from_slice(line) {
        Ok(Value::Object(pair)) => pair,
        _ => {
            return Comparison::new(None, Some(number)).failed(
                DistanceError::InvalidRequest,
                "a pair is a JSON object with `a` and `b`",
            );
        }
    };
    let id = pair.get("id").and_then(Id::from_json);
    let comparison = Comparison::new(id, Some(number));
    if let Some(unknown) = pair.keys().find(|key| !matches!(key.as_str(), "id" | "a" | "b")) {
        return comparison.failed(
            DistanceError::InvalidRequest,
            format!("a pair has no field `{unknown}`; it takes `id`, `a` and `b`"),
        );
    }
    if pair.get("id").is_some() && comparison.id.is_none() {
        return comparison.failed(DistanceError::InvalidRequest, "`id` must be a string or an integer");
    }
    let (Some(Value::String(a)), Some(Value::String(b))) = (pair.get("a"), pair.get("b")) else {
        return comparison.failed(DistanceError::InvalidRequest, "a pair needs `a` and `b`, each a string");
    };
    compare_stored(comparison, a, b)
}

/// Compare `a` and `b`, two stored forms, as one pair with this `id` and no line: the comparison
/// a distance task on a stream gets.
#[cfg(feature = "serve")]
pub(crate) fn compare_pair(id: Id, a: &str, b: &str) -> Comparison {
    compare_stored(Comparison::new(Some(id), None), a, b)
}

/// The comparison of a distance task on a stream that doesn't give both `a` and `b`.
#[cfg(feature = "serve")]
pub(crate) fn invalid_pair(id: Id, message: &str) -> Comparison {
    Comparison::new(Some(id), None).failed(DistanceError::InvalidRequest, message)
}

/// Fill in `comparison` with the distance between the stored forms `a` and `b`.
fn compare_stored(comparison: Comparison, a: &str, b: &str) -> Comparison {
    let (a, b) = match (parse("a", a), parse("b", b)) {
        (Ok(a), Ok(b)) => (a, b),
        (Err(message), _) | (_, Err(message)) => return comparison.failed(DistanceError::InvalidHash, message),
    };
    let mut comparison = comparison;
    match (a, b) {
        (Stored::Bit(a), Stored::Bit(b)) => match a.distance(&b) {
            Ok(distance) => {
                comparison.definition = Some(a.algorithm().id());
                comparison.distance = Some(distance);
                comparison.bits = Some(a.bits());
                comparison
            }
            Err(error) => comparison.failed(DistanceError::Mismatch, error.to_string()),
        },
        (Stored::Signature(a), Stored::Signature(b)) => match a.matching(&b) {
            Ok(matching) => {
                let values = a.algorithm().value_count();
                comparison.definition = Some(a.algorithm().id());
                comparison.matching = Some(matching);
                comparison.values = Some(values);
                comparison.similarity = Some(f64::from(matching) / f64::from(values));
                comparison
            }
            Err(error) => comparison.failed(DistanceError::Mismatch, error.to_string()),
        },
        (Stored::Bit(a), Stored::Signature(b)) => comparison.failed(
            DistanceError::Mismatch,
            format!(
                "can't compare a `{}` hash with a `{}` signature",
                a.algorithm(),
                b.algorithm()
            ),
        ),
        (Stored::Signature(a), Stored::Bit(b)) => comparison.failed(
            DistanceError::Mismatch,
            format!(
                "can't compare a `{}` signature with a `{}` hash",
                a.algorithm(),
                b.algorithm()
            ),
        ),
    }
}

/// Compare every pair in `input`, writing one line each to `output`, in order. Blank lines are
/// skipped. Each line is flushed as it is written, so a caller that sends a pair and waits for its
/// reply gets it while the input stays open.
///
/// # Errors
///
/// Returns [`Error::Io`] when reading `input` or writing `output` fails.
pub fn distances(input: impl BufRead, mut output: impl Write) -> Result<Summary, Error> {
    let mut summary = Summary::default();
    for (index, line) in input.split(b'\n').enumerate() {
        let line = line.map_err(|error| Error::io("couldn't read the input", error))?;
        if line.iter().all(u8::is_ascii_whitespace) {
            continue;
        }
        let comparison = compare(&line, index as u64 + 1);
        summary.written += 1;
        summary.failed += u64::from(comparison.status == Status::Error);
        let json = serde_json::to_string(&comparison).map_err(|error| Error::Internal(error.to_string()))?;
        writeln!(output, "{json}")
            .and_then(|()| output.flush())
            .map_err(|error| Error::io("couldn't write the output", error))?;
    }
    Ok(summary)
}