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
//! What `legit-hasher info` reports: the formats, the definitions, the limits and the machine.

use std::collections::BTreeMap;

use legit_hashes::{Algorithm, DECODE_MAX_ALLOC, DECODE_MAX_DIMENSION, DECODE_MAX_INPUT};
use serde::Serialize;

use crate::definition::{Definition, Input, MAX_SHINGLE};
use crate::inspect::DECODED_FORMATS;
use crate::outcome::{RUNNER, Runner};
use crate::{FORMAT, MAX_DEFINITIONS, MAX_OPTIONS_BYTES, Settings};

/// Bytes a decoded pixel can cost a worker at its peak: four of RGBA, one of luma and eight of
/// `pdq-v1`'s two `f32` planes, all held at once, and one more for what the decoder holds.
pub const PEAK_BYTES_PER_PIXEL: u64 = 14;

/// The report `legit-hasher info` prints, as JSON.
#[derive(Debug, Clone, Serialize)]
pub struct Info {
    /// The request and result format version this runner speaks: [`FORMAT`].
    pub format: u32,
    /// The program, hash library and decoder, as every result names them.
    pub runner: Runner,
    /// Every definition the runner offers.
    pub definitions: Vec<DefinitionInfo>,
    /// The image formats decoded; any other is `decode_failed`.
    pub image_formats: &'static [&'static str],
    /// The limits a request is held to.
    pub limits: Limits,
    /// The machine the runner is on.
    pub cpu: Cpu,
    /// How `pdq-v1` computes here: `native-f32` on x86-64 and aarch64, whose `f32` arithmetic is
    /// IEEE-754 single precision, or `software-f32`, the same operations computed exactly in
    /// integers, elsewhere. Both give the same bits.
    pub pdq_arithmetic: &'static str,
    /// How `run` and `serve` set up the memory allocator in this environment.
    pub malloc: Malloc,
    /// The task kind `legit-hasher serve` serves, when this build has the `serve` feature.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub serve: Option<ServeInfo>,
}

/// The environment variable that keeps glibc's own allocator settings when set to `default`.
pub const MALLOC_VARIABLE: &str = "LEGIT_HASHER_MALLOC";

/// How `run` and `serve` set up the memory allocator, which changes their speed and the memory
/// they keep, never a result.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Malloc {
    /// On 64-bit Linux with glibc, the program sets glibc's allocator at its start to keep freed
    /// blocks of up to 32 MiB for reuse, and to keep up to 128 MiB of free memory before returning
    /// it.
    Tuned,
    /// On 64-bit Linux with glibc, `GLIBC_TUNABLES` is set, so glibc's settings are the
    /// environment's.
    Tunables,
    /// On 64-bit Linux with glibc, `LEGIT_HASHER_MALLOC=default` keeps glibc's own settings.
    Default,
    /// Not 64-bit glibc: the system's allocator, as it is. On 32-bit glibc the largest mapping
    /// threshold glibc takes is far below 32 MiB, so it is left as it is there too.
    System,
}

impl Malloc {
    /// What `run` and `serve` do in this process's environment.
    #[must_use]
    pub fn detect() -> Self {
        if !cfg!(all(
            target_os = "linux",
            target_env = "gnu",
            target_pointer_width = "64"
        )) {
            Self::System
        } else if std::env::var_os("GLIBC_TUNABLES").is_some() {
            Self::Tunables
        } else if std::env::var_os(MALLOC_VARIABLE).is_some_and(|value| value == "default") {
            Self::Default
        } else {
            Self::Tuned
        }
    }
}

/// What `legit-hasher serve` serves: the task kind, its streams and the fields of its tasks and
/// results.
#[derive(Debug, Clone, Serialize)]
pub struct ServeInfo {
    /// The task kind, `hash`, which names the streams below.
    pub kind: &'static str,
    /// The contract version of the task and result envelopes, `1`.
    pub contract: &'static str,
    /// The bulk task stream.
    pub stream: String,
    /// The consumer group both lanes are read with.
    pub group: String,
    /// The result stream of a task that names no `reply_to`.
    pub results: String,
    /// The fast lane's task stream.
    pub fast_stream: String,
    /// The payload fields of a hashing task.
    pub task_fields: &'static [&'static str],
    /// The payload fields of a distance task.
    pub distance_fields: &'static [&'static str],
    /// The sources the fast lane takes.
    pub fast_sources: &'static [&'static str],
    /// The fields a result adds to the envelope's.
    pub result_fields: &'static [&'static str],
    /// The `model_name` a task may give besides none.
    pub model_name: &'static str,
    /// The `User-Agent` URL fetches send, when `--user-agent` sets one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_agent: Option<String>,
}

/// One definition as `info` lists it.
#[derive(Debug, Clone, Serialize)]
pub struct DefinitionInfo {
    /// The stable id.
    pub id: &'static str,
    /// What it reads: `luma`, `rgba` or `text`.
    pub input: Input,
    /// The width of a bit hash, in bits.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bits: Option<u32>,
    /// The number of 32-bit values in a signature.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub values: Option<u32>,
    /// What else the result carries beside the value, such as `quality`.
    pub returns: Vec<&'static str>,
    /// The parameters a request may give it.
    pub parameters: &'static [&'static str],
}

/// The limits, in bytes and pixels.
#[derive(Debug, Clone, Serialize)]
pub struct Limits {
    /// The longest image file read, from `path` or `base64`.
    pub max_file_bytes: u64,
    /// The widest or tallest image decoded.
    pub max_side: u32,
    /// The most the decoder may allocate for one image's pixels.
    pub max_decoder_bytes: u64,
    /// The most the decoder may allocate for an image's metadata: with `--max-pixels`,
    /// [`MAX_METADATA_BYTES`](crate::MAX_METADATA_BYTES) while its size is read; without, the
    /// decoder's own limit.
    pub max_metadata_bytes: u64,
    /// The most pixels an image may have, set with `--max-pixels`; `None` leaves the limits above.
    pub max_pixels: Option<u64>,
    /// The longest text hashed, in bytes, set with `--max-text-bytes`; `None` leaves the line
    /// limit.
    pub max_text_bytes: Option<u64>,
    /// The most entries a request's `definitions` holds.
    pub max_definitions: usize,
    /// The most bytes a request's `options` takes as JSON.
    pub max_options_bytes: usize,
    /// The widest character shingle.
    pub max_shingle: u32,
    /// The longest request line read, set with `--max-line-bytes`.
    pub max_line_bytes: u64,
    /// The most image bytes a request can carry inline, as base64 within the line limit.
    pub max_inline_bytes: u64,
    /// The most memory one worker can need for one request at these limits: the file, plus the
    /// metadata the decoder may allocate, plus [`PEAK_BYTES_PER_PIXEL`] for each pixel the limits
    /// allow, plus the line.
    pub worker_peak_bytes: u64,
}

/// The CPU, as the standard library detects it at run time.
#[derive(Debug, Clone, Serialize)]
pub struct Cpu {
    /// The architecture the runner was built for, such as `x86_64` or `aarch64`.
    pub arch: &'static str,
    /// The model name the operating system reports, where it does.
    pub model: Option<String>,
    /// The logical cores available to this process, which `--jobs` defaults to.
    pub logical_cores: usize,
    /// The instruction sets that matter here, each detected at run time: on x86-64 `sse2`,
    /// `sse4.2`, `popcnt`, `fma`, `avx2`, `avx512f` and `avx512vpopcntdq`; on aarch64 `neon`.
    pub features: BTreeMap<&'static str, bool>,
}

impl Info {
    /// Detect the machine and report it with the limits `settings` and `max_line_bytes` set.
    #[must_use]
    pub fn detect(settings: Settings, max_line_bytes: usize) -> Self {
        let max_line_bytes = max_line_bytes as u64;
        let side = u64::from(DECODE_MAX_DIMENSION);
        // The decoder's allocation limit at one byte a pixel bounds the area, as do the sides...
        let pixels = (side * side)
            .min(DECODE_MAX_ALLOC)
            .min(settings.max_pixels.unwrap_or(u64::MAX));
        let metadata = if settings.max_pixels.is_some() {
            crate::MAX_METADATA_BYTES
        } else {
            DECODE_MAX_ALLOC
        };
        Self {
            format: FORMAT,
            runner: RUNNER,
            definitions: Definition::ALL.iter().map(|&definition| describe(definition)).collect(),
            image_formats: &DECODED_FORMATS,
            limits: Limits {
                max_file_bytes: DECODE_MAX_INPUT as u64,
                max_side: DECODE_MAX_DIMENSION,
                max_decoder_bytes: DECODE_MAX_ALLOC,
                max_metadata_bytes: metadata,
                max_pixels: settings.max_pixels,
                max_text_bytes: settings.max_text_bytes,
                max_definitions: MAX_DEFINITIONS,
                max_options_bytes: MAX_OPTIONS_BYTES,
                max_shingle: MAX_SHINGLE,
                max_line_bytes,
                max_inline_bytes: (max_line_bytes / 4 * 3).min(DECODE_MAX_INPUT as u64),
                worker_peak_bytes: DECODE_MAX_INPUT as u64 + metadata + PEAK_BYTES_PER_PIXEL * pixels + max_line_bytes,
            },
            cpu: Cpu {
                arch: std::env::consts::ARCH,
                model: cpu_model(),
                logical_cores: std::thread::available_parallelism().map_or(1, usize::from),
                features: features(),
            },
            pdq_arithmetic: if cfg!(any(target_arch = "x86_64", target_arch = "aarch64")) {
                "native-f32"
            } else {
                "software-f32"
            },
            malloc: Malloc::detect(),
            serve: serve_info(),
        }
    }
}

#[cfg(feature = "serve")]
fn serve_info() -> Option<ServeInfo> {
    serve_kind().into()
}

#[cfg(feature = "serve")]
fn serve_kind() -> ServeInfo {
    use crate::serve::{self, KIND};
    ServeInfo {
        kind: KIND,
        contract: legit_streams::VERSION,
        stream: serve::task_stream(KIND),
        group: serve::group(KIND),
        results: serve::result_stream(KIND),
        fast_stream: serve::fast_stream(KIND),
        task_fields: &serve::TASK_FIELDS,
        distance_fields: &serve::DISTANCE_FIELDS,
        fast_sources: &serve::FAST_SOURCES,
        result_fields: &serve::RESULT_FIELDS,
        model_name: serve::MODEL_NAME,
        user_agent: None,
    }
}

#[cfg(not(feature = "serve"))]
const fn serve_info() -> Option<ServeInfo> {
    None
}

fn describe(definition: Definition) -> DefinitionInfo {
    let (bits, values) = match definition {
        Definition::Bit(algorithm) => (Some(algorithm.bits()), None),
        Definition::Signature(algorithm) => (None, Some(algorithm.value_count())),
    };
    let returns = match definition {
        Definition::Bit(Algorithm::PdqV1) => vec!["value", "quality", "chunk_keys"],
        Definition::Bit(_) => vec!["value", "chunk_keys"],
        Definition::Signature(_) => vec!["value", "empty", "band_keys"],
    };
    DefinitionInfo {
        id: definition.id(),
        input: definition.input(),
        bits,
        values,
        returns,
        parameters: definition.parameters(),
    }
}

/// The CPU's model name from `/proc/cpuinfo`, on Linux.
fn cpu_model() -> Option<String> {
    let cpuinfo = std::fs::read_to_string("/proc/cpuinfo").ok()?;
    cpuinfo.lines().find_map(|line| {
        let (name, value) = line.split_once(':')?;
        matches!(name.trim(), "model name" | "Model" | "cpu model").then(|| value.trim().to_owned())
    })
}

#[cfg(target_arch = "x86_64")]
fn features() -> BTreeMap<&'static str, bool> {
    BTreeMap::from([
        ("sse2", std::arch::is_x86_feature_detected!("sse2")),
        ("sse4.2", std::arch::is_x86_feature_detected!("sse4.2")),
        ("popcnt", std::arch::is_x86_feature_detected!("popcnt")),
        ("fma", std::arch::is_x86_feature_detected!("fma")),
        ("avx2", std::arch::is_x86_feature_detected!("avx2")),
        ("avx512f", std::arch::is_x86_feature_detected!("avx512f")),
        (
            "avx512vpopcntdq",
            std::arch::is_x86_feature_detected!("avx512vpopcntdq"),
        ),
    ])
}

#[cfg(target_arch = "aarch64")]
fn features() -> BTreeMap<&'static str, bool> {
    BTreeMap::from([("neon", std::arch::is_aarch64_feature_detected!("neon"))])
}

#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
fn features() -> BTreeMap<&'static str, bool> {
    BTreeMap::new()
}