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
//! One task of the kind `hamming`: its `task_name` and `options` read, answered by the service.

use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Instant;

use legit_streams::{Context, Failure, Reply, Task};

use super::{ENVELOPE_ROOM, MODEL_NAME};

/// The fields of a task its result echoes, as the contract asks.
const ECHOED: [&str; 6] = [
    "model_type",
    "model_id",
    "task_name",
    "model_name",
    "metadata",
    "embedder_key",
];
use super::metrics::{Metrics, Name};
use crate::service::{Counts, ErrorType, Lane, Service, ServiceError};

/// The handler a worker runs each task with.
#[derive(Debug)]
pub(crate) struct Handler {
    service: Arc<Service>,
    metrics: Arc<Metrics>,
    lane: Lane,
    /// The bound on a result entry of this lane's worker.
    entry_bytes: usize,
}

impl Handler {
    pub(crate) const fn new(service: Arc<Service>, metrics: Arc<Metrics>, lane: Lane, entry_bytes: usize) -> Self {
        Self {
            service,
            metrics,
            lane,
            entry_bytes,
        }
    }
}

/// The most bytes a change task's `result` takes: a conflict's error object with its 100 ids, or
/// the result object. A change is refused, before anything is applied, when the room its echoes
/// leave is less, so a change that stands is never reported as an error.
pub const CHANGE_RESULT_BYTES: usize = 4 << 10;

/// Counts a task in flight on its lane's gauge while it lives, however its handling ends.
struct InFlight<'a>(&'a std::sync::atomic::AtomicU64);

impl<'a> InFlight<'a> {
    fn new(gauge: &'a std::sync::atomic::AtomicU64) -> Self {
        gauge.fetch_add(1, Ordering::Relaxed);
        Self(gauge)
    }
}

impl Drop for InFlight<'_> {
    fn drop(&mut self) {
        self.0.fetch_sub(1, Ordering::Relaxed);
    }
}

impl legit_streams::Handler for Handler {
    fn handle(&self, task: &Task, context: &Context) -> Result<Reply, Failure> {
        let started = Instant::now();
        let in_flight = InFlight::new(match self.lane {
            Lane::Bulk => &self.metrics.in_flight,
            Lane::Fast => &self.metrics.fast_in_flight,
        });
        let name = match task.task_name() {
            "search" | "" | "default" => Name::Search,
            "stats" => Name::Stats,
            "append" => Name::Append,
            "replace" => Name::Replace,
            "remove" => Name::Remove,
            _ => Name::Other,
        };
        let mut counts = Counts::default();
        self.service.catalog().fault("handle");
        let answer = self.answer(task, name, context, &mut counts);
        drop(in_flight);
        if let Err(failure) = &answer
            && failure.is_abandon()
        {
            return answer;
        }
        let error_type = answer.as_ref().err().and_then(Failure::error_type);
        if let Some(code) = error_type {
            // The entry id and the code only: never the task's options, values or names...
            tracing::info!(
                entry = %context.entry_id(),
                lane = self.lane.name(),
                task = name.as_str(),
                error_type = code,
                "A task was answered with an error"
            );
        }
        let micros = u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX);
        self.metrics.task(name, self.lane, micros, error_type, counts);
        answer
    }
}

impl Handler {
    fn answer(&self, task: &Task, name: Name, context: &Context, counts: &mut Counts) -> Result<Reply, Failure> {
        // The room the result entry leaves once the envelope and the task's echoes are in it...
        let echoed: usize = ECHOED
            .iter()
            .filter_map(|name| task.get(name).map(|value| name.len() + value.len()))
            .sum();
        let room = self.entry_bytes.saturating_sub(ENVELOPE_ROOM).saturating_sub(echoed);
        if let Some(error) = self.refusal(task, name, room) {
            return Err(failure(&error, room));
        }
        if self.lane == Lane::Bulk {
            // A stopping worker releases the task rather than start a long search or a change...
            context.checkpoint()?;
        }
        let options = task.get("options").unwrap_or_default();
        let result = if name == Name::Stats {
            self.service.stats(options).and_then(|json| fits(json, room, "`stats`"))
        } else if name.is_change() {
            // Once applied, a change is answered whatever happens: a stop now would only make the
            // task run again, and a repeat is answered from the log...
            self.service.change(task.task_id(), task.task_name(), options)
        } else {
            self.service.search_within(options, self.lane, room).map(|answer| {
                *counts = answer.counts;
                answer.json
            })
        };
        result
            .map(|json| Reply::new().field("result", json))
            .map_err(|error| failure(&error, room))
    }

    /// Why the task is refused before the service reads its `options`, if it is: a model this
    /// worker doesn't serve, a `task_name` it doesn't know, a change on the quick path, or a change
    /// whose result the `room` its echoes leave couldn't carry.
    fn refusal(&self, task: &Task, name: Name, room: usize) -> Option<ServiceError> {
        let model = task.model_name();
        if !model.is_empty() && model != MODEL_NAME {
            return Some(ServiceError::new(
                ErrorType::UnsupportedModel,
                format!("this worker is `{MODEL_NAME}`; it serves no other model, and an empty `model_name` is fine"),
            ));
        }
        if name == Name::Other {
            return Some(ServiceError::new(
                ErrorType::InvalidTask,
                "this worker answers the `task_name`s `search` (or `default`) and `stats`, and with `--state-dir` \
                 `append`, `replace` and `remove` on the bulk stream",
            ));
        }
        if name.is_change() && self.lane == Lane::Fast {
            return Some(ServiceError::new(
                ErrorType::InvalidTask,
                "a change goes on the bulk stream; the quick path answers searches and `stats`",
            ));
        }
        if name.is_change() && room < CHANGE_RESULT_BYTES {
            // Refused before it is applied: its answer couldn't be delivered after...
            return Some(ServiceError::new(
                ErrorType::InvalidTask,
                format!(
                    "the task's echoed fields leave {room} bytes for its result; a change needs \
                     {CHANGE_RESULT_BYTES}, and nothing was applied"
                ),
            ));
        }
        None
    }
}

/// `json` when it fits `room`, or `invalid_task` saying it doesn't.
fn fits(json: String, room: usize, what: &str) -> Result<String, ServiceError> {
    if json.len() <= room {
        Ok(json)
    } else {
        Err(ServiceError::new(
            crate::service::ErrorType::InvalidTask,
            format!(
                "{what} takes {} bytes; the task's echoed fields leave {room}",
                json.len()
            ),
        ))
    }
}

/// The error result for a request the service refused: the contract's `error_type`, the message,
/// `result` holding the error object, and the code's own fields; or, when those don't fit the
/// `room` the task's echoes leave, the code and a short message alone, so the caller is told the
/// error it got and not one the transport makes of a reply too large.
fn failure(error: &ServiceError, room: usize) -> Failure {
    match error_fields(error, room) {
        Some(fields) => fields.into_iter().fold(
            Failure::new(error.error_type.as_str(), error.message.clone()),
            |failure, (name, value)| failure.field(name, value),
        ),
        None => Failure::new(
            error.error_type.as_str(),
            "the error's detail doesn't fit the room the task's echoed fields leave",
        ),
    }
}

/// The fields an error result carries beside the envelope's own: `result`, holding the error
/// object, and the code's own fields; `None` when they take more than `room`.
fn error_fields(error: &ServiceError, room: usize) -> Option<Vec<(&'static str, String)>> {
    let mut fields = vec![("result", error.to_json())];
    fields.extend(error.fields());
    let bytes: usize = fields
        .iter()
        .map(|(name, value)| value.len() + if *name == "result" { 0 } else { name.len() })
        .sum();
    (bytes <= room).then_some(fields)
}

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

    #[test]
    fn every_error_type_carries_its_object_in_result_with_its_fields() {
        for error_type in ErrorType::ALL {
            let mut error = ServiceError::new(error_type, "what was wrong");
            match error_type {
                ErrorType::RadiusTooLarge => error.max_radius = Some(16),
                ErrorType::NotReady => {
                    error.state = Some("loading");
                    error.fraction = Some(0.5);
                }
                ErrorType::Conflict => {
                    error.ids = Some(vec![1, 2]);
                    error.count = Some(2);
                }
                _ => {}
            }
            let fields = error_fields(&error, 4_096).expect("it fits");
            let (name, result) = &fields[0];
            assert_eq!(*name, "result");
            let object: serde_json::Value = serde_json::from_str(result).expect("JSON");
            assert_eq!(object["format"], 1);
            assert_eq!(object["error_type"], error_type.as_str());
            assert_eq!(object["error"], "what was wrong");
            // Each field beside `result` is in the object too...
            for (name, value) in &fields[1..] {
                let field: serde_json::Value =
                    serde_json::from_str(value).unwrap_or_else(|_| serde_json::Value::String(value.clone()));
                assert_eq!(object[*name], field, "{error_type}: `{name}`");
            }
            // ...and an error that doesn't fit the room is the code alone.
            let all: usize = fields.iter().map(|(_, value)| value.len()).sum();
            assert!(error_fields(&error, all / 2).is_none());
        }
        let error = ServiceError::new(ErrorType::UnsupportedModel, "m");
        assert_eq!(
            error.fields(),
            [("supported_models", r#"["legit-hamming"]"#.to_owned())]
        );
        assert!(error.to_json().ends_with(r#""supported_models":["legit-hamming"]}"#));
    }
}