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 result of one request, as one JSON line.

use serde::Serialize;

use crate::FORMAT;
use crate::request::Id;

/// A request-level error code: the request as a whole gave no hashes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RequestError {
    /// The line isn't a request: not JSON, not an object, no usable `id`, a field of the wrong
    /// type, a field the format doesn't define, invalid base64, or a line over the length limit.
    InvalidRequest,
    /// `options` is missing or wrong: no `format`, another format version, no `definitions`, an
    /// entry that isn't an object with an `id`, or an unknown `orientation`.
    InvalidOptions,
    /// The request names no source, or more than one of `path`, `text` and `base64`.
    NoSource,
    /// The file at `path` couldn't be read: it's missing, unreadable, or not a file.
    ReadFailed,
    /// The source is over a limit `info` states: its byte length, a side, the decoder's memory
    /// or `--max-pixels`.
    TooLarge,
    /// The bytes aren't a PNG or JPEG image the decoder can read: another format, damaged data or
    /// no image at all.
    DecodeFailed,
    /// The runner failed while handling the request, such as a panic. Report it as a bug.
    Internal,
    /// An `image_url` source couldn't be fetched: the host didn't answer, answered with an error
    /// status, took too long, or redirected too often. Only `serve` fetches URLs.
    DownloadFailed,
    /// The server refused an `image_url`'s credential, with `401` or `403`: a presigned URL that
    /// has expired, or one that was never valid. A fresh URL may succeed.
    UrlExpired,
    /// The worker's allowlist refuses an `image_url`: its host isn't listed, it resolves to an
    /// address the worker doesn't reach, or it's plain `http` where only `https` is allowed.
    HostNotAllowed,
}

impl RequestError {
    /// The code as results carry it, such as `decode_failed`.
    ///
    /// ```
    /// assert_eq!(legit_hasher::RequestError::NoSource.as_str(), "no_source");
    /// ```
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::InvalidRequest => "invalid_request",
            Self::InvalidOptions => "invalid_options",
            Self::NoSource => "no_source",
            Self::ReadFailed => "read_failed",
            Self::TooLarge => "too_large",
            Self::DecodeFailed => "decode_failed",
            Self::Internal => "internal",
            Self::DownloadFailed => "download_failed",
            Self::UrlExpired => "url_expired",
            Self::HostNotAllowed => "host_not_allowed",
        }
    }
}

/// A definition-level error code: one entry of `definitions` gave no hash, and the others stand.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DefinitionError {
    /// The `id` isn't a definition this runner offers.
    UnsupportedDefinition,
    /// An image definition asked of text, or a text definition asked of an image.
    WrongSource,
    /// A parameter the definition doesn't take, a value of the wrong type or out of range, or a
    /// text definition without exactly one of `shingle` and `tokens`.
    InvalidParameter,
}

/// Whether a request was handled.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Status {
    /// The source was read and each definition gave a hash or its own error.
    Success,
    /// The request gave no hashes; `error_type` says why.
    Error,
}

/// What was hashed: the length and SHA-1 of an image source's bytes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SourceFacts {
    /// The byte length of the source.
    pub bytes: u64,
    /// The SHA-1 of the source, 40 lower-case hex digits. An identity check, not a security
    /// measure.
    pub sha1: String,
}

/// How the bytes became pixels.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DecodeFacts {
    /// The container format: `jpeg` or `png`.
    pub format: &'static str,
    /// How many frames the file holds; only the first is hashed.
    pub frames: u32,
    /// The EXIF orientation tag, or `None` when the file carries none.
    pub orientation_tag: Option<u16>,
    /// Whether the pixels were turned by the tag before hashing.
    pub orientation_applied: bool,
    /// Whether the file ends before its end marker, or `None` when its structure can't be followed.
    pub truncated: Option<bool>,
}

/// The program, hash library and decoder that made a result.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Runner {
    /// The program: `legit-hasher`.
    pub name: &'static str,
    /// The runner's version.
    pub version: &'static str,
    /// The exact `legit-hashes` release it was built with, such as `0.2.1`. Definitions never
    /// change within one, or ever.
    pub hashes: &'static str,
    /// The decoder and its exact release, such as `image 0.25.10`. A decoder release can change
    /// the pixels of a JPEG, and so its hashes.
    pub decoder: &'static str,
}

/// The runner that made every result of this build. The two releases are the ones `Cargo.lock`
/// pins, and a test fails when they differ from it.
pub const RUNNER: Runner = Runner {
    name: "legit-hasher",
    version: env!("CARGO_PKG_VERSION"),
    hashes: "0.2.1",
    decoder: "image 0.25.10",
};

/// Time spent on the request, in microseconds, reported with `--timings`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Timings {
    /// Reading the file, or decoding the base64.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub read_us: Option<u64>,
    /// Decoding the image and converting it to what each definition reads, orientation included.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decode_us: Option<u64>,
    /// The whole request, parsing included.
    pub total_us: u64,
}

/// One entry of a result's `hashes`, in the order of the request's `definitions`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct HashOutcome {
    /// The definition id as the request gave it.
    pub id: String,
    /// A text definition's shingle size.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shingle: Option<u32>,
    /// A text definition's tokeniser when it isn't shingles: `words`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tokens: Option<&'static str>,
    /// The stored string form `legit-hashes` defines, `<id>:<hex>`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,
    /// `pdq-v1`'s quality score, 0 to 100.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quality: Option<u8>,
    /// Whether a signature is empty: its text had no features.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub empty: Option<bool>,
    /// The chunk keys of a bit hash, as signed 64-bit integers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub chunk_keys: Option<Vec<i64>>,
    /// The band keys of a signature, as signed 64-bit integers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub band_keys: Option<Vec<i64>>,
    /// Why the entry gave no hash.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_type: Option<DefinitionError>,
    /// What was wrong, for a person.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Time spent on this hash and its keys, in microseconds, with `--timings`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_us: Option<u64>,
}

impl HashOutcome {
    pub(crate) fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            shingle: None,
            tokens: None,
            value: None,
            quality: None,
            empty: None,
            chunk_keys: None,
            band_keys: None,
            error_type: None,
            error: None,
            time_us: None,
        }
    }

    pub(crate) fn failed(id: impl Into<String>, code: DefinitionError, message: impl Into<String>) -> Self {
        Self {
            error_type: Some(code),
            error: Some(message.into()),
            ..Self::new(id)
        }
    }
}

/// The result of one request: one JSON line, with fields in a fixed order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Outcome {
    /// The format version of the line: [`FORMAT`].
    pub format: u32,
    /// The request's `id`, or `None` (`null`) when the line had no usable one.
    pub id: Option<Id>,
    /// The line of the input the request came from, counting from 1, in batch mode.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line: Option<u64>,
    /// Whether the request was handled.
    pub status: Status,
    /// Why the request gave no hashes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_type: Option<RequestError>,
    /// What was wrong, for a person.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// The format read from the first bytes when the source wasn't decoded, such as `gif`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detected_format: Option<&'static str>,
    /// The width of the pixels hashed, after orientation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub width: Option<u32>,
    /// The height of the pixels hashed, after orientation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub height: Option<u32>,
    /// What was hashed, for an image source whose bytes were read.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<SourceFacts>,
    /// How the bytes became pixels, when they were decoded.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decode: Option<DecodeFacts>,
    /// The program, library and decoder that made the result.
    pub runner: Runner,
    /// One entry per requested definition, on success.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hashes: Option<Vec<HashOutcome>>,
    /// Time spent, with `--timings`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timings: Option<Timings>,
}

impl Outcome {
    /// A successful result for `id`, with no hashes yet.
    pub(crate) const fn success(id: Option<Id>) -> Self {
        Self {
            format: FORMAT,
            id,
            line: None,
            status: Status::Success,
            error_type: None,
            error: None,
            detected_format: None,
            width: None,
            height: None,
            source: None,
            decode: None,
            runner: RUNNER,
            hashes: Some(Vec::new()),
            timings: None,
        }
    }

    /// A request-level error for `id`.
    #[must_use]
    pub fn error(id: Option<Id>, code: RequestError, message: impl Into<String>) -> Self {
        Self {
            status: Status::Error,
            error_type: Some(code),
            error: Some(message.into()),
            hashes: None,
            ..Self::success(id)
        }
    }

    /// Whether the request failed: a request-level error, or an error on any definition.
    #[must_use]
    pub fn is_failure(&self) -> bool {
        self.status == Status::Error || self.hashes.iter().flatten().any(|hash| hash.error_type.is_some())
    }

    /// The result as one line of JSON, without the newline.
    #[must_use]
    pub fn to_json(&self) -> String {
        // Every field is a string, number, boolean, null or a list of those, and every map key is
        // a string, so serializing can't fail...
        serde_json::to_string(self).unwrap_or_else(|error| {
            serde_json::json!({
                "format": FORMAT,
                "id": null,
                "status": "error",
                "error_type": "internal",
                "error": error.to_string(),
            })
            .to_string()
        })
    }
}