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
//! What one request may cost, checked before any work starts.

use std::time::Duration;

use serde::Serialize;

/// Which lane a request came on: the two differ in how many values a request may hold, how long
/// a search may take and how many threads it runs on.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Lane {
    /// The quick path, for a lookup a caller waits for: few values, a short time budget, one
    /// thread a request.
    Fast,
    /// The bulk path, for batches: many values, a long time budget, one batch search across the
    /// service's threads.
    Bulk,
}

impl Lane {
    /// The lane's name in logs and results: `fast` or `bulk`.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Fast => "fast",
            Self::Bulk => "bulk",
        }
    }
}

/// The bounds on a request, each reported by the `stats` task, so a client can read them from the
/// service. The counts, sizes and radii are checked before the search starts; the time budgets
/// bound how long a search collects candidates; the result bound fixes, before the search, how
/// many matches a query keeps. None of them bounds the process's memory: the crate's README,
/// "Limits", says what each holds a request to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct Limits {
    /// The most query values a request on the quick path may hold. 1 by default.
    pub max_values_fast: usize,
    /// The most query values a bulk task may hold. 5,000 by default.
    pub max_values: usize,
    /// The longest `options` read, in bytes of JSON, before it is parsed. 1 MiB by default.
    pub max_options_bytes: usize,
    /// The largest radius served at 64 bits. 16 by default.
    pub max_radius_64: u32,
    /// The largest radius served at 256 bits. 96 by default.
    pub max_radius_256: u32,
    /// The most matches kept for one query, the nearest by distance; more are cut, `cut_by:
    /// "size"`. 10,000 by default.
    pub max_matches: usize,
    /// The search budget of a quick request, in milliseconds: the search stops collecting
    /// candidates after it, `cut_by: "time"`, and the reply follows as soon as what was collected
    /// is merged and written. 2,000 by default.
    pub query_time_fast_ms: u64,
    /// The search budget of a bulk task, all its values together, in milliseconds, as
    /// [`query_time_fast_ms`](Self::query_time_fast_ms) is. 30,000 by default.
    pub query_time_ms: u64,
    /// The most bytes of JSON a result object may take. A request whose matches could take more
    /// keeps fewer per query, chosen before the search, and says so with `cut_by: "size"`, so a
    /// reply is never too large for the stream after the work is done. 32 MiB by default, half
    /// of a stream entry's default bound.
    pub max_result_bytes: usize,
    /// The most records an `append` or `replace` task may hold. 1,000 by default.
    pub max_change_records: usize,
    /// The most ids a `remove` task may hold. 10,000 by default.
    pub max_remove_ids: usize,
    /// The bound on an index's change log, in bytes: a change that would take the log past it is
    /// refused with `log_full`, never dropped. 256 MiB by default, about 3.5 million changes at
    /// 256 bits and 5 million at 64.
    pub max_log_bytes: u64,
}

impl Limits {
    /// The defaults above.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            max_values_fast: 1,
            max_values: 5_000,
            max_options_bytes: 1 << 20,
            max_radius_64: 16,
            max_radius_256: 96,
            max_matches: 10_000,
            query_time_fast_ms: 2_000,
            query_time_ms: 30_000,
            max_result_bytes: 32 << 20,
            max_change_records: 1_000,
            max_remove_ids: 10_000,
            max_log_bytes: 256 << 20,
        }
    }

    /// The most values a request on `lane` may hold.
    #[must_use]
    pub const fn max_values(&self, lane: Lane) -> usize {
        match lane {
            Lane::Fast => self.max_values_fast,
            Lane::Bulk => self.max_values,
        }
    }

    /// The search budget on `lane`: how long a search collects candidates.
    #[must_use]
    pub const fn query_time(&self, lane: Lane) -> Duration {
        Duration::from_millis(match lane {
            Lane::Fast => self.query_time_fast_ms,
            Lane::Bulk => self.query_time_ms,
        })
    }

    /// The largest radius served at `width` bits, or `None` for a width that isn't served.
    #[must_use]
    pub const fn max_radius(&self, width: u32) -> Option<u32> {
        match width {
            64 => Some(self.max_radius_64),
            256 => Some(self.max_radius_256),
            _ => None,
        }
    }

    /// The most bytes of change log read when an index opens or swaps: the log's bound,
    /// [`max_log_bytes`](Self::max_log_bytes), and one largest change task. A longer log was written
    /// under a larger bound, and is refused unread until the bound is raised again.
    #[must_use]
    pub fn log_read_bound(&self) -> u64 {
        let task = super::log::task_bytes(256, self.max_change_records.max(self.max_remove_ids)).unwrap_or(u64::MAX);
        self.max_log_bytes.saturating_add(task)
    }

    /// Check the limits make sense together: each at least 1, radii within their widths, a
    /// result budget that holds at least one match for every query of the largest request, and a
    /// log bound that holds the largest change task.
    ///
    /// # Errors
    ///
    /// A message naming the limit at fault.
    pub fn validate(&self) -> Result<(), String> {
        if self.max_values_fast == 0 || self.max_values == 0 {
            return Err("a request must be allowed at least one value".to_owned());
        }
        if self.max_matches == 0 {
            return Err("a query must be allowed at least one match".to_owned());
        }
        if self.max_radius_64 > 64 || self.max_radius_256 > 256 {
            return Err("a radius bound can't be wider than its width".to_owned());
        }
        if self.query_time_fast_ms == 0 || self.query_time_ms == 0 {
            return Err("a time budget must be above 0".to_owned());
        }
        if self.max_options_bytes == 0 {
            return Err("`options` must be allowed at least one byte".to_owned());
        }
        if self.max_change_records == 0 || self.max_remove_ids == 0 {
            return Err("a change task must be allowed at least one record".to_owned());
        }
        let records = self.max_change_records.max(self.max_remove_ids);
        let task = super::log::task_bytes(256, records).ok_or_else(|| {
            format!("a change task of {records} records takes more bytes of log than can be counted: lower the change bounds")
        })?;
        if task > self.max_log_bytes {
            return Err(format!(
                "the largest change task takes up to {task} bytes of log, more than the log's bound of {}",
                self.max_log_bytes
            ));
        }
        let largest = self.max_values_fast.max(self.max_values);
        let least = super::answer::result_bytes(256, true, largest, 1);
        if least > self.max_result_bytes {
            return Err(format!(
                "a result of {largest} queries with one 256-bit match each takes up to {least} bytes, \
                 more than the result budget of {}",
                self.max_result_bytes
            ));
        }
        Ok(())
    }
}

impl Default for Limits {
    fn default() -> Self {
        Self::new()
    }
}