legit-hamming 0.1.1

Exact Hamming radius search over 64-bit and 256-bit hashes in memory: a scan or multi-index hashing, chosen per query, checked against one reference, and a search service over snapshots
Documentation
//! The errors a request can be answered with, as the contract names them.

use std::fmt;

use serde::Serialize;

use super::FORMAT;

/// The contract's `error_type` for a request that can't be answered: a search, `stats`, or a
/// change.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorType {
    /// The `options` aren't JSON, aren't an object of the contract's keys and types, name another
    /// `format`, or hold a value that isn't hex of the width.
    InvalidOptions,
    /// No index of that name is served.
    UnknownIndex,
    /// The index serves no subset of that name.
    UnknownSubset,
    /// The request's `width` isn't the width of the index or subset.
    WidthMismatch,
    /// More `values` than the lane takes.
    TooManyValues,
    /// A `radius` above the service's bound for the width; the error carries the bound.
    RadiusTooLarge,
    /// The index or subset is served, but no snapshot of it is loaded yet; the error carries its
    /// state, `empty` or `loading`, and how much of a load is done when that is known.
    NotReady,
    /// An `append` met an id the index holds with another value, and applied nothing; the error
    /// carries the ids, at most [`CONFLICT_IDS`] of them, and how many there were.
    Conflict,
    /// The change log has reached its bound, `--max-log-bytes`, and the change was refused, not
    /// dropped: a snapshot that covers the log's changes lets it be shortened.
    LogFull,
    /// A task this service doesn't take: a `task_name` it doesn't know, a change on the quick
    /// path, or any change when the service keeps no change log.
    InvalidTask,
    /// A `model_name` other than empty or the worker's own; the error carries the models served.
    UnsupportedModel,
    /// Something in the service failed that the request didn't cause.
    Internal,
}

/// The most conflicting ids a `conflict` error lists; [`ServiceError::count`] says how many there
/// were.
pub const CONFLICT_IDS: usize = 100;

impl ErrorType {
    /// Every error type, in the order the contract lists them.
    pub const ALL: [Self; 12] = [
        Self::InvalidOptions,
        Self::UnknownIndex,
        Self::UnknownSubset,
        Self::WidthMismatch,
        Self::TooManyValues,
        Self::RadiusTooLarge,
        Self::NotReady,
        Self::Conflict,
        Self::LogFull,
        Self::InvalidTask,
        Self::UnsupportedModel,
        Self::Internal,
    ];

    /// The code as the contract writes it, such as `not_ready`.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::InvalidOptions => "invalid_options",
            Self::UnknownIndex => "unknown_index",
            Self::UnknownSubset => "unknown_subset",
            Self::WidthMismatch => "width_mismatch",
            Self::TooManyValues => "too_many_values",
            Self::RadiusTooLarge => "radius_too_large",
            Self::NotReady => "not_ready",
            Self::Conflict => "conflict",
            Self::LogFull => "log_full",
            Self::InvalidTask => "invalid_task",
            Self::UnsupportedModel => "unsupported_model",
            Self::Internal => "internal",
        }
    }
}

impl fmt::Display for ErrorType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A request the service answers with an error: the code, a message, and the fields some codes
/// carry. [`to_json`](Self::to_json) is the error's result object, the line `query` writes and the
/// `result` field of a stream's error result.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct ServiceError {
    /// The contract's code.
    pub error_type: ErrorType,
    /// What was wrong, for a person. It quotes nothing from the request but a name, shortened to
    /// 64 characters, and never a query value.
    pub message: String,
    /// With [`ErrorType::RadiusTooLarge`]: the largest radius served at the request's width.
    pub max_radius: Option<u32>,
    /// With [`ErrorType::NotReady`]: `empty`, `loading`, or `refused` for an index whose change
    /// log can't be read.
    pub state: Option<&'static str>,
    /// With [`ErrorType::NotReady`] while loading: the fraction of the snapshot's bytes read.
    pub fraction: Option<f64>,
    /// With [`ErrorType::Conflict`]: the ids the index holds with another value, rising, at most
    /// [`CONFLICT_IDS`].
    pub ids: Option<Vec<u64>>,
    /// With [`ErrorType::Conflict`]: how many records of the task conflicted.
    pub count: Option<u64>,
}

/// The `model_name`s the service answers, besides an empty one: the program's name. An
/// [`ErrorType::UnsupportedModel`] error carries them as `supported_models`.
pub const SUPPORTED_MODELS: &[&str] = &["legit-hamming"];

#[derive(Serialize)]
struct ErrorObject<'a> {
    format: u32,
    error_type: &'static str,
    error: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_radius: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    state: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    fraction: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    ids: Option<&'a [u64]>,
    #[serde(skip_serializing_if = "Option::is_none")]
    count: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    supported_models: Option<&'static [&'static str]>,
}

impl ServiceError {
    /// An error of `error_type` with `message` and no further fields.
    #[must_use]
    pub fn new(error_type: ErrorType, message: impl Into<String>) -> Self {
        Self {
            error_type,
            message: message.into(),
            max_radius: None,
            state: None,
            fraction: None,
            ids: None,
            count: None,
        }
    }

    pub(crate) fn invalid(message: impl Into<String>) -> Self {
        Self::new(ErrorType::InvalidOptions, message)
    }

    /// The error's result object as JSON: `format`, `error_type`, `error`, and `max_radius`,
    /// `state`, `fraction`, `ids` and `count` where the code carries them, and with
    /// [`ErrorType::UnsupportedModel`], `supported_models`, the [`SUPPORTED_MODELS`].
    #[must_use]
    pub fn to_json(&self) -> String {
        serde_json::to_string(&ErrorObject {
            format: FORMAT,
            error_type: self.error_type.as_str(),
            error: &self.message,
            max_radius: self.max_radius,
            state: self.state,
            fraction: self.fraction,
            ids: self.ids.as_deref(),
            count: self.count,
            supported_models: self.supported_models(),
        })
        .unwrap_or_default()
    }

    /// The fields beyond the envelope's own that a stream's error result carries besides
    /// `result`: `max_radius`, `state`, `fraction`, `ids` and `supported_models` (JSON lists) and
    /// `count` where the code carries them, as strings.
    #[must_use]
    pub fn fields(&self) -> Vec<(&'static str, String)> {
        let mut fields = Vec::new();
        if let Some(max_radius) = self.max_radius {
            fields.push(("max_radius", max_radius.to_string()));
        }
        if let Some(state) = self.state {
            fields.push(("state", state.to_owned()));
        }
        if let Some(fraction) = self.fraction {
            fields.push(("fraction", fraction.to_string()));
        }
        if let Some(ids) = &self.ids {
            fields.push(("ids", serde_json::to_string(ids).unwrap_or_default()));
        }
        if let Some(count) = self.count {
            fields.push(("count", count.to_string()));
        }
        if let Some(models) = self.supported_models() {
            fields.push(("supported_models", serde_json::to_string(models).unwrap_or_default()));
        }
        fields
    }

    /// The models an [`ErrorType::UnsupportedModel`] error names.
    fn supported_models(&self) -> Option<&'static [&'static str]> {
        (self.error_type == ErrorType::UnsupportedModel).then_some(SUPPORTED_MODELS)
    }
}

impl fmt::Display for ServiceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.error_type, self.message)
    }
}

impl std::error::Error for ServiceError {}