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
//! `legit-hamming serve`: the command-line front of [`legit_hamming::serve`].

use std::process::ExitCode;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use legit_hamming::serve::{self, BACKLOG_TIMEOUT, ENVELOPE_ROOM, ServeConfig, Server, StatsFile, StatsState};
use legit_hamming::service::{Catalog, Service};
use legit_streams::{RedisStreams, Streams};

use crate::{Arguments, Usage};

/// The environment variable `--redis` defaults to, so a password needn't be on the command line.
const REDIS_URL_VARIABLE: &str = "LEGIT_HAMMING_REDIS_URL";

/// How often the main loop looks for a signal or a stopped worker.
const POLL: Duration = Duration::from_millis(100);

/// Run `legit-hamming serve` with its parsed arguments.
pub(crate) fn serve(arguments: &Arguments) -> Result<ExitCode, Usage> {
    let settings = &arguments.serve;
    // Checked before anything else, so a stats file that could never be written stops the start...
    let stats_file = settings
        .stats_file
        .as_ref()
        .map(|path| StatsFile::new(path).map_err(|error| Usage(format!("`--stats-file {}`: {error}", path.display()))))
        .transpose()?;
    let url = settings
        .redis
        .clone()
        .or_else(|| std::env::var(REDIS_URL_VARIABLE).ok())
        .ok_or_else(|| Usage(format!("`serve` needs `--redis URL`, or `{REDIS_URL_VARIABLE}` set")))?;
    let kind = settings.kind.clone().unwrap_or_else(|| serve::KIND.to_owned());
    if !legit_streams::is_valid_kind(&kind) {
        return Err(Usage("`--kind` is 1 to 16 of `a-z`, `0-9`, `_` and `-`".to_owned()));
    }
    // A result must fit a stream entry with the envelope's fields, or it would fail after the work...
    let entry = legit_streams::Limits::default().max_entry_bytes;
    if arguments.limits.max_result_bytes > entry - ENVELOPE_ROOM {
        return Err(Usage(format!(
            "`--max-result-bytes` is at most {} on a stream, whose entries hold at most {entry} bytes",
            entry - ENVELOPE_ROOM
        )));
    }
    if arguments.load.state_dir.is_some() && settings.jobs > 1 {
        return Err(Usage(
            "with `--state-dir`, `--jobs` is 1: changes apply one at a time, in the order the worker takes them"
                .to_owned(),
        ));
    }
    let mut load = arguments.load.clone();
    load.write_changes = true;
    let catalog = Arc::new(Catalog::new(arguments.specs.clone(), load).map_err(Usage)?);
    let prefix = settings
        .consumer
        .clone()
        .unwrap_or_else(|| format!("legit-hamming-{}", host_name()));
    if prefix.len() > serve::CONSUMER_MAX - 32 {
        return Err(Usage(format!(
            "`--consumer` is at most {} bytes: it names the worker in every result",
            serve::CONSUMER_MAX - 32
        )));
    }
    let mut config = ServeConfig::for_kind(&kind, &prefix, std::process::id());
    config.worker.concurrency = settings.jobs;
    config.worker.shutdown_grace = settings.shutdown_grace;
    config.reload = settings.reload;
    config.fast = match (settings.no_fast, config.fast) {
        (false, Some(mut fast)) => {
            fast.concurrency = settings.fast_jobs;
            Some(fast)
        }
        _ => None,
    };

    let _ = tracing::subscriber::set_global_default(serve::subscriber(tracing::Level::INFO, std::io::stderr));

    let stop = Arc::new(AtomicBool::new(false));
    for signal in [signal_hook::consts::SIGTERM, signal_hook::consts::SIGINT] {
        // A second signal while stopping ends the process at once...
        signal_hook::flag::register_conditional_shutdown(signal, 1, Arc::clone(&stop))
            .and_then(|_| signal_hook::flag::register(signal, Arc::clone(&stop)))
            .map_err(|error| Usage(format!("couldn't handle signals: {error}")))?;
    }

    let streams = RedisStreams::open(&url)
        .map(|streams| streams.with_key_prefix(settings.key_prefix.clone()))
        .map_err(|error| Usage(format!("couldn't open `--redis`: {error}")))?;
    // The stats file reads the backlog on a connection of its own, never one of the workers'...
    let mut stats_file = stats_file.map(|file| {
        let backlog: Arc<dyn Streams> = Arc::new(streams.clone().timeout(BACKLOG_TIMEOUT));
        file.with_backlog(backlog, config.worker.stream.clone(), config.worker.group.clone())
    });
    let streams: Arc<dyn Streams> = Arc::new(streams);
    let consumer = config.worker.consumer.clone();
    let limits = arguments.limits;
    let load = catalog.config();
    tracing::info!(
        kind = %kind,
        consumer = %consumer,
        sets = %catalog.sets().iter().map(|(set, dir)| format!("{set}={}", dir.display())).collect::<Vec<_>>().join(" "),
        jobs = config.worker.concurrency,
        fast_jobs = config.fast.as_ref().map_or(0, |fast| fast.concurrency),
        threads = load.threads,
        table_memory = ?load.table_memory,
        reload_s = config.reload.as_secs_f64(),
        max_values_fast = limits.max_values_fast,
        max_values = limits.max_values,
        max_options_bytes = limits.max_options_bytes,
        max_radius_64 = limits.max_radius_64,
        max_radius_256 = limits.max_radius_256,
        max_matches = limits.max_matches,
        fast_query_time_ms = limits.query_time_fast_ms,
        query_time_ms = limits.query_time_ms,
        max_result_bytes = limits.max_result_bytes,
        state_dir = %load.state_dir.as_ref().map(|dir| dir.display().to_string()).unwrap_or_default(),
        max_change_records = limits.max_change_records,
        max_remove_ids = limits.max_remove_ids,
        max_log_bytes = limits.max_log_bytes,
        repeat_window_s = load.repeat_window.as_secs_f64(),
        stats_sample = load.sample,
        "Starting"
    );
    // The first load before the workers join their group, so a worker never takes a task it can
    // only answer `not_ready` while another worker of the group could answer it...
    let first = {
        let catalog = Arc::clone(&catalog);
        std::thread::Builder::new()
            .name("hamming-first-load".to_owned())
            .spawn(move || catalog.load_changed(&mut serve::log_event))
            .map_err(|error| Usage(format!("couldn't start a thread: {error}")))?
    };
    while !first.is_finished() {
        if stop.load(Ordering::SeqCst) {
            tracing::info!("Stopping on a signal before the first load ended");
            return Ok(ExitCode::SUCCESS);
        }
        std::thread::sleep(POLL);
    }
    if let Err(panic) = first.join() {
        tracing::error!(reason = %serve::panic_message(panic.as_ref()), "The first snapshot load panicked; stopping");
        return Ok(ExitCode::from(2));
    }
    let service = Arc::new(Service::new(Arc::clone(&catalog), limits, load.threads));
    let server = match Server::start(config, service, streams, None) {
        Ok(server) => server,
        Err(error) => {
            tracing::error!(error = %error, "The search worker couldn't start");
            return Ok(ExitCode::from(2));
        }
    };
    let meter = server.meter();
    // A failed write is logged by the file itself, and never stops the worker...
    let mut write_stats = |state| {
        if let Some(file) = stats_file.as_mut() {
            let _ = file.write(meter.sample(), state);
        }
    };
    write_stats(StatsState::Running);
    let mut last = Instant::now();
    while !stop.load(Ordering::SeqCst) && !server.is_finished() {
        if last.elapsed() >= settings.heartbeat {
            last = Instant::now();
            heartbeat(&server, &consumer, "running");
            write_stats(StatsState::Running);
        }
        std::thread::sleep(POLL);
    }
    let asked = stop.load(Ordering::SeqCst);
    if asked {
        tracing::info!("Stopping on a signal; a running task has the shutdown grace to finish");
    }
    server.stop();
    heartbeat(&server, &consumer, "stopping");
    let joined = server.join();
    write_stats(StatsState::Stopped);
    match joined {
        Ok(_) if asked => Ok(ExitCode::SUCCESS),
        Ok(_) => Ok(ExitCode::from(2)),
        Err(error) => {
            tracing::error!(error = %error, "The search worker stopped with an error");
            Ok(ExitCode::from(2))
        }
    }
}

/// One heartbeat line on standard error.
fn heartbeat(server: &Server, consumer: &str, state: &str) {
    let beat = server.heartbeat();
    tracing::info!(
        state,
        consumer,
        uptime_s = beat.uptime_s,
        in_flight = beat.in_flight,
        search = beat.tasks.search,
        stats = beat.tasks.stats,
        append = beat.tasks.append,
        replace = beat.tasks.replace,
        remove = beat.tasks.remove,
        other = beat.tasks.other,
        errors = %serde_json::to_string(&beat.errors).unwrap_or_default(),
        queries = beat.queries,
        candidates = beat.candidates,
        cut_limit = beat.cut_limit,
        cut_time = beat.cut_time,
        cut_size = beat.cut_size,
        fast_count = beat.fast.count,
        fast_p50_ms = beat.fast.p50_ms,
        fast_p99_ms = beat.fast.p99_ms,
        bulk_count = beat.bulk.count,
        bulk_p50_ms = beat.bulk.p50_ms,
        bulk_p99_ms = beat.bulk.p99_ms,
        "Heartbeat"
    );
}

/// The machine's name for the default consumer name, keeping only the characters a consumer name
/// takes without quoting.
fn host_name() -> String {
    let name = std::fs::read_to_string("/proc/sys/kernel/hostname")
        .ok()
        .or_else(|| std::env::var("HOSTNAME").ok())
        .or_else(|| std::env::var("COMPUTERNAME").ok())
        .unwrap_or_default();
    let name: String = name
        .trim()
        .chars()
        .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
        .take(64)
        .collect();
    if name.is_empty() { "host".to_owned() } else { name }
}