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
//! The definitions the runner offers, and the parameters each takes.

use legit_hashes::{Algorithm, Error as HashError, SignatureAlgorithm};
use serde::Serialize;

/// A `legit-hashes` definition the runner computes: a bit hash or a set signature.
///
/// The runner offers exactly the definitions in [`Definition::ALL`]; a definition the library
/// adds later is refused as `unsupported_definition` until the runner lists it here.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Definition {
    /// A bit hash, compared by Hamming distance: an image hash or `simhash-v1`.
    Bit(Algorithm),
    /// A MinHash signature of a set of text features, compared by matching values.
    Signature(SignatureAlgorithm),
}

/// What a definition reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Input {
    /// 8-bit luma, converted from the decoded colour with the v1 formula.
    Luma,
    /// 8-bit RGBA, the decoded colour.
    Rgba,
    /// UTF-8 text, split into words or character shingles.
    Text,
}

impl Definition {
    /// Every definition the runner offers, images first, in the order `info` lists them.
    pub const ALL: [Self; 8] = [
        Self::Bit(Algorithm::AverageV1),
        Self::Bit(Algorithm::DifferenceV1),
        Self::Bit(Algorithm::PerceptualV1),
        Self::Bit(Algorithm::PdqV1),
        Self::Bit(Algorithm::BlockhashV1),
        Self::Bit(Algorithm::SimHashV1),
        Self::Signature(SignatureAlgorithm::MinHashV1),
        Self::Signature(SignatureAlgorithm::MinHashLegacyV1),
    ];

    /// Find the definition with the stable id `id`, such as `pdq-v1`, among those the runner
    /// offers. The match is exact.
    #[must_use]
    pub fn from_id(id: &str) -> Option<Self> {
        let definition = match Algorithm::from_id(id) {
            Ok(algorithm) => Self::Bit(algorithm),
            Err(HashError::NotABitHash(algorithm)) => Self::Signature(algorithm),
            Err(_) => return None,
        };
        Self::ALL.contains(&definition).then_some(definition)
    }

    /// The stable id, such as `pdq-v1`, which also starts every stored form.
    #[must_use]
    pub const fn id(self) -> &'static str {
        match self {
            Self::Bit(algorithm) => algorithm.id(),
            Self::Signature(algorithm) => algorithm.id(),
        }
    }

    /// What the definition reads: luma, RGBA or text.
    #[must_use]
    pub fn input(self) -> Input {
        match self {
            Self::Bit(Algorithm::PdqV1 | Algorithm::BlockhashV1) => Input::Rgba,
            Self::Bit(algorithm) if algorithm.is_image() => Input::Luma,
            Self::Bit(_) | Self::Signature(_) => Input::Text,
        }
    }

    /// Whether the definition hashes images, rather than text.
    #[must_use]
    pub fn is_image(self) -> bool {
        self.input() != Input::Text
    }

    /// The parameters a request may give the definition, by name.
    #[must_use]
    pub fn parameters(self) -> &'static [&'static str] {
        match (self, self.input()) {
            (Self::Signature(_), _) => &["shingle", "tokens", "band_keys"],
            (Self::Bit(_), Input::Text) => &["shingle", "tokens", "chunk_keys"],
            (Self::Bit(_), _) => &["chunk_keys"],
        }
    }
}

/// The widest character shingle a text definition takes, `64`.
pub const MAX_SHINGLE: u32 = 64;

/// How a text definition splits its text into features.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tokens {
    /// The frozen `words_v1` tokeniser: ASCII-lower-cased words split on ASCII whitespace and
    /// punctuation, each occurrence a feature.
    Words,
    /// The frozen `shingles_v1` tokeniser: every window of this many characters, 1 to
    /// [`MAX_SHINGLE`].
    Shingles(u32),
}

/// One definition of a request, with its parameters checked: what the runner computes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Plan {
    /// The definition to compute.
    pub definition: Definition,
    /// How a text definition splits its text. Always `Some` for a text definition and `None` for
    /// an image one.
    pub tokens: Option<Tokens>,
    /// How many chunk keys to return beside a bit hash.
    pub chunk_keys: Option<u32>,
    /// How many band keys to return beside a signature.
    pub band_keys: Option<u32>,
}

/// A definition-level failure: the reason one entry of `definitions` gives no hash.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DefinitionFailure {
    /// The stable code.
    pub code: crate::DefinitionError,
    /// What was wrong, for a person.
    pub message: String,
}

impl DefinitionFailure {
    pub(crate) fn new(code: crate::DefinitionError, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }

    fn parameter(message: impl Into<String>) -> Self {
        Self::new(crate::DefinitionError::InvalidParameter, message)
    }
}

impl Plan {
    /// Check one entry of a request's `definitions`: its `id` and every parameter beside it.
    ///
    /// # Errors
    ///
    /// Returns `unsupported_definition` for an id the runner doesn't offer, and
    /// `invalid_parameter` for a parameter the definition doesn't take, a value of the wrong type
    /// or out of range (a `shingle` is 1 to [`MAX_SHINGLE`]), or a text definition without exactly
    /// one of `shingle` and `tokens`.
    pub fn from_entry(id: &str, entry: &serde_json::Map<String, serde_json::Value>) -> Result<Self, DefinitionFailure> {
        let Some(definition) = Definition::from_id(id) else {
            return Err(DefinitionFailure::new(
                crate::DefinitionError::UnsupportedDefinition,
                format!("`{id}` isn't a definition this runner offers; `info` lists them"),
            ));
        };
        let allowed = definition.parameters();
        if let Some(unknown) = entry
            .keys()
            .find(|key| *key != "id" && !allowed.contains(&key.as_str()))
        {
            return Err(DefinitionFailure::parameter(format!(
                "`{id}` takes no parameter `{unknown}`; it takes {}",
                list(allowed)
            )));
        }
        let mut plan = Self {
            definition,
            tokens: None,
            chunk_keys: count(entry, "chunk_keys")?,
            band_keys: count(entry, "band_keys")?,
        };
        if let (Definition::Bit(algorithm), Some(keys)) = (definition, plan.chunk_keys) {
            let bits = algorithm.bits();
            if keys < bits.div_ceil(64) || keys > bits {
                return Err(DefinitionFailure::parameter(format!(
                    "`chunk_keys` of a {bits}-bit hash is from {} to {bits}, not `{keys}`",
                    bits.div_ceil(64)
                )));
            }
        }
        if let (Definition::Signature(algorithm), Some(bands)) = (definition, plan.band_keys) {
            let values = algorithm.value_count();
            if values % bands != 0 {
                return Err(DefinitionFailure::parameter(format!(
                    "`band_keys` must divide the `{values}` values evenly, so `{bands}` won't do; use 1, 2, 4, 8, 16, 32, 64 or 128"
                )));
            }
        }
        if definition.input() == Input::Text {
            plan.tokens = Some(tokens(id, entry)?);
        }
        Ok(plan)
    }
}

/// A positive count parameter, or `None` when it's absent.
fn count(entry: &serde_json::Map<String, serde_json::Value>, name: &str) -> Result<Option<u32>, DefinitionFailure> {
    let Some(value) = entry.get(name) else {
        return Ok(None);
    };
    match value.as_u64().and_then(|count| u32::try_from(count).ok()) {
        Some(count) if count > 0 => Ok(Some(count)),
        _ => Err(DefinitionFailure::parameter(format!(
            "`{name}` must be a positive integer, not `{value}`"
        ))),
    }
}

/// The tokeniser of a text definition: exactly one of `shingle` and `tokens`.
fn tokens(id: &str, entry: &serde_json::Map<String, serde_json::Value>) -> Result<Tokens, DefinitionFailure> {
    match (entry.get("shingle"), entry.get("tokens")) {
        (Some(_), None) => match count(entry, "shingle")?.unwrap_or(1) {
            width @ 1..=MAX_SHINGLE => Ok(Tokens::Shingles(width)),
            width => Err(DefinitionFailure::parameter(format!(
                "`shingle` is 1 to {MAX_SHINGLE} characters, not `{width}`"
            ))),
        },
        (None, Some(serde_json::Value::String(tokens))) if tokens == "words" => Ok(Tokens::Words),
        (None, Some(other)) => Err(DefinitionFailure::parameter(format!(
            "`tokens` can only be `\"words\"`, not `{other}`; for character shingles give `shingle`"
        ))),
        (Some(_), Some(_)) => Err(DefinitionFailure::parameter(format!(
            "`{id}` takes `shingle` or `tokens`, not both"
        ))),
        (None, None) => Err(DefinitionFailure::parameter(format!(
            "`{id}` needs `shingle` (characters per shingle, such as 5) or `tokens: \"words\"`"
        ))),
    }
}

/// `a`, `a` or `b`, `a`, `b` or `c`, each in backticks.
fn list(names: &[&str]) -> String {
    let quoted: Vec<String> = names.iter().map(|name| format!("`{name}`")).collect();
    match quoted.split_last() {
        Some((last, [])) => last.clone(),
        Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
        None => String::new(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn entry(json: &str) -> serde_json::Map<String, serde_json::Value> {
        serde_json::from_str(json).expect("the test entry is a JSON object")
    }

    #[test]
    fn every_offered_definition_is_found_by_its_id() {
        for definition in Definition::ALL {
            assert_eq!(Definition::from_id(definition.id()), Some(definition));
        }
        assert_eq!(Definition::from_id("pdq-v2"), None);
        assert_eq!(Definition::from_id("PDQ-V1"), None);
    }

    #[test]
    fn parameters_are_checked_against_the_definition() {
        let plan = Plan::from_entry("pdq-v1", &entry(r#"{"id":"pdq-v1","chunk_keys":16}"#)).expect("valid");
        assert_eq!(plan.chunk_keys, Some(16));
        let plan = Plan::from_entry("minhash-v1", &entry(r#"{"shingle":5,"band_keys":32}"#)).expect("valid");
        assert_eq!((plan.tokens, plan.band_keys), (Some(Tokens::Shingles(5)), Some(32)));
        let plan = Plan::from_entry("simhash-v1", &entry(r#"{"tokens":"words"}"#)).expect("valid");
        assert_eq!(plan.tokens, Some(Tokens::Words));

        for (id, json) in [
            ("pdq-v1", r#"{"chunk_keys":3}"#),
            ("pdq-v1", r#"{"chunk_keys":257}"#),
            ("perceptual-v1", r#"{"chunk_keys":0}"#),
            ("perceptual-v1", r#"{"chunk_keys":"4"}"#),
            ("perceptual-v1", r#"{"shingle":4}"#),
            ("pdq-v1", r#"{"band_keys":4}"#),
            ("minhash-v1", r#"{"shingle":5,"band_keys":7}"#),
            ("minhash-v1", r#"{"shingle":5,"chunk_keys":4}"#),
            ("minhash-v1", r#"{"shingle":0}"#),
            ("minhash-v1", r#"{"shingle":65}"#),
            ("simhash-v1", r#"{"shingle":4294967295}"#),
            ("minhash-v1", r#"{}"#),
            ("minhash-v1", r#"{"shingle":5,"tokens":"words"}"#),
            ("simhash-v1", r#"{"tokens":"sentences"}"#),
            ("simhash-v1", r#"{"tokens":"words","shingles":3}"#),
        ] {
            let failure = Plan::from_entry(id, &entry(json)).expect_err(json);
            assert_eq!(failure.code, crate::DefinitionError::InvalidParameter, "{id} {json}");
        }
        for width in [1, MAX_SHINGLE] {
            let plan = Plan::from_entry("minhash-v1", &entry(&format!(r#"{{"shingle":{width}}}"#))).expect("in range");
            assert_eq!(plan.tokens, Some(Tokens::Shingles(width)));
        }
        let failure = Plan::from_entry("pdq-v9", &entry("{}")).expect_err("unknown");
        assert_eq!(failure.code, crate::DefinitionError::UnsupportedDefinition);
    }
}