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
//! One task of the kind `hash`, read from its fields, run, and answered with the runner's result
//! object.

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

use legit_streams::{Context, Failure, INVALID_TASK, Reply, Task, UNSUPPORTED_MODEL};
use serde_json::Value;

use super::{Counters, FAST_SOURCES, Fetcher, MODEL_NAME};
use crate::distance::{compare_pair, invalid_pair};
use crate::hasher::text_too_large;
use crate::request::{Id, Options, Request, Source, inline_bytes};
use crate::{DistanceError, MAX_OPTIONS_BYTES, Outcome, RequestError, Settings, Status, hash};

/// What every task of a server shares.
#[derive(Debug)]
pub(crate) struct Shared {
    pub(crate) settings: Settings,
    pub(crate) fetcher: Fetcher,
    pub(crate) counters: Arc<Counters>,
}

/// Which lane a handler serves.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Lane {
    /// `{kind}_tasks`: every source, and distances.
    Bulk,
    /// `{kind}_tasks:fast`: text and distances, which a caller waits for.
    Fast,
}

/// The handler a worker runs each task with.
#[derive(Debug)]
pub(crate) struct Handler {
    shared: Arc<Shared>,
    lane: Lane,
}

impl Handler {
    pub(crate) const fn new(shared: Arc<Shared>, lane: Lane) -> Self {
        Self { shared, lane }
    }
}

impl legit_streams::Handler for Handler {
    fn handle(&self, task: &Task, context: &Context) -> Result<Reply, Failure> {
        let counters = &self.shared.counters;
        // The start, before anything else; dropped by a panic, it sends the finish as a failure...
        #[cfg(unix)]
        let event = counters
            .socket
            .as_deref()
            .map(|socket| socket.begin(self.lane == Lane::Fast, super::socket::task_kind(task)));
        if self.lane == Lane::Bulk {
            counters.in_flight.fetch_add(1, Ordering::Relaxed);
        }
        let answer = self.answer(task, context);
        // The time the result's `processing_ms` reports, to the nanosecond...
        let elapsed = context.elapsed();
        if let Err(failure) = &answer
            && !failure.is_abandon()
        {
            // The entry id and the code only: never the task's text, which was refused...
            tracing::debug!(
                entry = %context.entry_id(),
                error_type = failure.error_type().unwrap_or_default(),
                "A task was answered with an error"
            );
        }
        let (done, failed, times) = match self.lane {
            Lane::Bulk => {
                counters.in_flight.fetch_sub(1, Ordering::Relaxed);
                (&counters.done, &counters.failed, &counters.bulk_times)
            }
            Lane::Fast => (&counters.fast_done, &counters.fast_failed, &counters.fast_times),
        };
        // Every task counted as answered is timed, failures included...
        times.record(elapsed);
        let is_failure = matches!(&answer, Ok(Answer { failed: true, .. }) | Err(_));
        done.fetch_add(1, Ordering::Relaxed);
        if is_failure {
            failed.fetch_add(1, Ordering::Relaxed);
        }
        // Four numbers, as the stats file counts the task, and only when the events file asks...
        if let Some(events) = &counters.events {
            events.record(self.lane == Lane::Fast, is_failure, elapsed);
        }
        // ...and the finish once the reply is ready, counted as the stats file counts it.
        #[cfg(unix)]
        if let Some(event) = event {
            event.finish(!is_failure, elapsed);
        }
        answer.map(|answer| answer.reply)
    }
}

/// A successful reply, and whether its result object holds a failed definition.
struct Answer {
    reply: Reply,
    failed: bool,
}

/// A field's value, or `None` when it's missing or empty: the contract reads an empty value as
/// absent.
fn present<'a>(task: &'a Task, name: &str) -> Option<&'a str> {
    task.get(name).filter(|value| !value.is_empty())
}

impl Handler {
    fn answer(&self, task: &Task, context: &Context) -> Result<Answer, Failure> {
        // The unit tests' way to make a handler panic; no build but theirs has it.
        #[cfg(test)]
        assert!(task.get("panic_in_test").is_none(), "a handler panics, as a test asked");
        let model = task.model_name();
        if !model.is_empty() && model != MODEL_NAME {
            return Err(Failure::new(
                UNSUPPORTED_MODEL,
                format!(
                    "this worker is `{MODEL_NAME}`; it serves no model `{model}`, and an empty `model_name` is fine"
                ),
            )
            .field("supported_models", format!("[\"{MODEL_NAME}\"]")));
        }
        let id = Id::Text(present(task, "id").unwrap_or(task.task_id()).to_owned());
        // `text_data` is a source even when empty: an empty text is hashed, as on the command line...
        let sources: Vec<&str> = [
            task.get("text_data").map(|_| "text_data"),
            present(task, "image_data").map(|_| "image_data"),
            present(task, "image_url").map(|_| "image_url"),
        ]
        .into_iter()
        .flatten()
        .collect();
        let pair = (present(task, "a"), present(task, "b"));
        if pair != (None, None) {
            if !sources.is_empty() {
                return Err(request_failure(
                    &Outcome::error(
                        Some(id),
                        RequestError::InvalidRequest,
                        "the task gives a source and a pair `a` and `b`; a task hashes one source or compares one pair",
                    ),
                    Some(INVALID_TASK),
                ));
            }
            return distance(id, pair);
        }
        let name = match sources.as_slice() {
            [name] => *name,
            [] => {
                let outcome = Outcome::error(
                    Some(id),
                    RequestError::NoSource,
                    "the task needs one source: `text_data`, `image_data` or `image_url`, or a pair `a` and `b`",
                );
                return Err(request_failure(&outcome, Some(INVALID_TASK)));
            }
            _ => {
                let outcome = Outcome::error(
                    Some(id),
                    RequestError::NoSource,
                    format!(
                        "the task gives more than one source (`{}`); give exactly one",
                        sources.join("`, `")
                    ),
                );
                return Err(request_failure(&outcome, None));
            }
        };
        if self.lane == Lane::Fast && !FAST_SOURCES.contains(&name) {
            let outcome = Outcome::error(
                Some(id),
                RequestError::NoSource,
                format!("the fast lane takes `text_data` and pairs; send `{name}` to the bulk task stream"),
            );
            return Err(request_failure(&outcome, Some(INVALID_TASK)));
        }
        if name == "text_data"
            && let Some(message) = text_too_large(task.get(name).map_or(0, str::len), self.shared.settings)
        {
            // Refused before the text is copied, parsed or tokenised...
            return Err(request_failure(
                &Outcome::error(Some(id), RequestError::TooLarge, message),
                None,
            ));
        }
        // Measured before it's parsed...
        let options = match present(task, "options") {
            None => Err("the request has no `options`".to_owned()),
            Some(options) if options.len() > MAX_OPTIONS_BYTES => Err(format!(
                "`options` is `{}` bytes of JSON; it may be at most `{MAX_OPTIONS_BYTES}`",
                options.len()
            )),
            Some(options) => match serde_json::from_str::<Value>(options) {
                Err(error) => Err(format!("`options` isn't JSON: {error}")),
                Ok(options) => Options::from_json(&options),
            },
        };
        let options = match options {
            Ok(options) => {
                // Asked for, whether or not the fetch, the decode or the definition then fails...
                self.shared.counters.definitions.ask(&options);
                options
            }
            Err(message) => {
                return Err(request_failure(
                    &Outcome::error(Some(id), RequestError::InvalidOptions, message),
                    None,
                ));
            }
        };
        if name == "image_url" {
            // A stopping worker releases a task whose fetch hasn't begun, rather than begin it...
            context.checkpoint()?;
        }
        // ...but once a fetch has begun, the task runs to its answer within the shutdown grace:
        // the hash takes milliseconds, and a source already downloaded isn't thrown away. What
        // still runs when the grace ends, the worker releases.
        let (source, read_us) = match self.source(task, name, context) {
            Ok(source) => source,
            Err((code, message)) => return Err(request_failure(&Outcome::error(Some(id), code, message), None)),
        };
        let request = Request { id, source, options };
        let mut outcome = hash(&request, self.shared.settings);
        self.shared.counters.definitions.count(&outcome);
        if let (Some(read_us), Some(timings)) = (read_us, outcome.timings.as_mut()) {
            timings.read_us = Some(read_us);
            timings.total_us = timings.total_us.saturating_add(read_us);
        }
        if outcome.status == Status::Error {
            return Err(request_failure(&outcome, None));
        }
        Ok(Answer {
            failed: outcome.is_failure(),
            reply: Reply::new().field("result", outcome.to_json()),
        })
    }

    /// The task's source, and for a URL how long the fetch took, in microseconds.
    fn source(
        &self,
        task: &Task,
        name: &str,
        context: &Context,
    ) -> Result<(Source, Option<u64>), (RequestError, String)> {
        let value = task.get(name).unwrap_or_default();
        match name {
            "text_data" => Ok((Source::Text(value.to_owned()), None)),
            "image_data" => inline_bytes("image_data", value).map(|bytes| (Source::Bytes(bytes), None)),
            _ => {
                let counters = &self.shared.counters;
                match self.shared.fetcher.fetch(value) {
                    Ok(fetched) => {
                        counters.fetched.fetch_add(1, Ordering::Relaxed);
                        counters
                            .fetched_bytes
                            .fetch_add(fetched.bytes.len() as u64, Ordering::Relaxed);
                        let read_us = u64::try_from(fetched.elapsed.as_micros()).unwrap_or(u64::MAX);
                        Ok((Source::Bytes(fetched.bytes), Some(read_us)))
                    }
                    Err(error) => {
                        // The entry id, the code and the URL's host: never its path, query or user...
                        tracing::warn!(
                            entry = %context.entry_id(),
                            error_type = error.code.as_str(),
                            host = %super::url_host(value),
                            "An image_url couldn't be fetched"
                        );
                        Err((error.code, error.message))
                    }
                }
            }
        }
    }
}

/// The error answer for a request that failed as a whole: the contract's `error_type` is the
/// runner's code, or `contract_code` where the contract names its own, and `result` holds the
/// whole result object, so what was learned of the source reaches the caller.
fn request_failure(outcome: &Outcome, contract_code: Option<&str>) -> Failure {
    let code = contract_code
        .or_else(|| outcome.error_type.map(RequestError::as_str))
        .unwrap_or(RequestError::Internal.as_str());
    Failure::new(code, outcome.error.clone().unwrap_or_default()).field("result", outcome.to_json())
}

/// Compare a pair, as `legit-hasher distance` compares one line.
fn distance(id: Id, pair: (Option<&str>, Option<&str>)) -> Result<Answer, Failure> {
    let comparison = match pair {
        (Some(a), Some(b)) => compare_pair(id, a, b),
        _ => invalid_pair(id, "a distance task needs `a` and `b`, each a stored hash or signature"),
    };
    let json = serde_json::to_string(&comparison).unwrap_or_default();
    match comparison.error_type {
        Some(code) => {
            let contract_code = match code {
                DistanceError::InvalidRequest => INVALID_TASK,
                code => code.as_str(),
            };
            Err(Failure::new(contract_code, comparison.error.unwrap_or_default()).field("result", json))
        }
        None => Ok(Answer {
            reply: Reply::new().field("result", json),
            failed: false,
        }),
    }
}