use std::fs::File;
use std::io::{self, BufRead, BufReader, BufWriter, Read, Write};
use std::path::PathBuf;
use std::process::ExitCode;
use std::sync::Arc;
use std::time::{Duration, Instant};
use legit_hamming::service::{
self, Catalog, Event, Lane, Limits, LoadConfig, Service, SetSpec, TableMemory, verify_snapshot,
};
use legit_hamming::{Cpu, snapshot};
#[cfg(feature = "serve")]
mod serve_command;
const HELP: &str = "\
legit-hamming: exact Hamming radius search over snapshots of 64-bit and 256-bit hashes
Usage:
legit-hamming query [options] search: one options object a line in, one result a line out
legit-hamming stats [options] load, measure the neighbour table, print each set's stats
legit-hamming verify DIR check a snapshot: manifest, sizes, checksums, ids rising
legit-hamming info print the CPU's paths, formats and versions as JSON
legit-hamming serve [options] answer search and stats tasks from Redis Streams
(in a build with the `serve` feature)
legit-hamming help print this help
legit-hamming --version print the version
Indexes (query, stats, serve):
--index NAME=DIR serve the index NAME from DIR, which holds snapshot directories
and a one-line file CURRENT naming the one to serve; repeatable
--subset INDEX.NAME=DIR serve the subset NAME of INDEX from DIR, the same way; repeatable
--threads N threads a bulk search, a table build and a neighbour count run on
(default: the available cores)
--state-dir DIR each index's change log, in DIR/INDEX/: `serve` writes it and takes
append, replace and remove tasks, one process an index; `query`
and `stats` read it as it is on disk, without the lock
--table-memory BYTES build the multi-index tables when they take at most BYTES, with
a k, m or g suffix for KiB, MiB or GiB; 0 scans every query;
`auto` builds them when they fit in the memory available less a
quarter, at least 512 MiB (default: auto)
Limits (query, stats, serve), each checked before a search starts, but the search budgets:
--max-values-fast N values a quick request may hold (default: 1)
--max-values N values a bulk task may hold (default: 5000)
--max-options-bytes N the longest options read (default: 1048576)
--max-radius-64 N the largest radius at 64 bits (default: 16)
--max-radius-256 N the largest radius at 256 bits (default: 96)
--max-matches N matches kept a query, the nearest (default: 10000)
--fast-query-time S a quick search's budget: it stops collecting candidates after S
seconds, and the reply follows as soon as what was collected is
merged and written (default: 2)
--query-time S the same for a bulk task, all its values together (default: 30)
--max-result-bytes N the largest result object (default: 33554432)
--max-change-records N records an append or replace task may hold (default: 1000)
--max-remove-ids N ids a remove task may hold (default: 10000)
--max-log-bytes N an index's change log; past it, changes are refused with
log_full, and a log longer than it and one largest task isn't
read: raise it to read one (default: 268435456)
Query:
--input FILE read from FILE rather than standard input
--lane fast|bulk answer as the quick path or the bulk stream would (default: bulk)
Stats:
--sample N records sampled for the neighbour table (default: 2000)
--max-distance D the farthest distance counted (default: 16 at 64 bits, 96 at 256)
--seed S the seed the sample is drawn with (default: 0)
Serve:
--redis URL the Redis server, such as redis://127.0.0.1:6379; without it,
LEGIT_HAMMING_REDIS_URL, which keeps a password off the command line
--key-prefix PREFIX a prefix every key on the server carries (default: none)
--kind KIND the task kind, which names the streams (default: hamming)
--consumer NAME this worker's name in the group (default: legit-hamming-HOST);
the process id is added
--jobs N bulk tasks run at once, each across --threads (default: 1)
--fast-jobs N quick requests run at once, one thread each (default: 2)
--no-fast serve the bulk lane only
--reload-seconds S the wait between the end of one check of each CURRENT, its
loads included, and the next (default: 30)
--stats-sample N records sampled for each snapshot's neighbour table (default: 2000)
--stats-max-distance-64 D the farthest distance it counts at 64 bits (default: 16)
--stats-max-distance-256 D the same at 256 bits (default: 96)
--shutdown-grace S seconds a stop waits for a running task (default: 30)
--heartbeat S seconds between heartbeat lines (default: 30)
--stats-file PATH write a JSON document of counts and timings to PATH at start, at
each heartbeat and at stop, whole each time (via PATH.tmp, then
renamed; mode 0644); numbers only, never a name, path or value.
Its directory must exist
--repeat-window S seconds a change task is still recognised as a repeat once a
snapshot covers it and its entries are dropped (default: 3600)
With --state-dir, --jobs must be 1: changes apply one at a time, in the order taken.
Log lines and heartbeats are JSON on standard error. SIGTERM or SIGINT stops it
cleanly; a second one stops it at once.
Exit status: query exits 0 when every request succeeded, 1 when any was answered with
an error (each a line, `not_ready` for a set that didn't load), 2 when it couldn't
run, such as an input it couldn't open.
stats exits 1 when an index or subset has no snapshot loaded. verify exits 0 for a
sound snapshot and 1 otherwise. serve exits 0 after a clean stop on a signal, and 2
when it couldn't run.
The request and result formats are in the crate's README.
";
struct Usage(String);
#[derive(Debug)]
struct Arguments {
specs: Vec<SetSpec>,
input: Option<PathBuf>,
lane: Lane,
load: LoadConfig,
limits: Limits,
threads: Option<usize>,
sample: Option<usize>,
max_distance: Option<u32>,
seed: Option<u64>,
positional: Vec<String>,
help: bool,
#[cfg_attr(not(feature = "serve"), allow(dead_code, reason = "read by `serve` only"))]
serve: ServeArguments,
}
#[derive(Debug)]
#[cfg_attr(not(feature = "serve"), allow(dead_code, reason = "read by `serve` only"))]
struct ServeArguments {
redis: Option<String>,
key_prefix: String,
kind: Option<String>,
consumer: Option<String>,
jobs: usize,
fast_jobs: usize,
no_fast: bool,
reload: Duration,
shutdown_grace: Duration,
heartbeat: Duration,
stats_file: Option<PathBuf>,
}
const SET_FLAGS: [&str; 17] = [
"--index",
"--subset",
"--threads",
"--state-dir",
"--max-change-records",
"--max-remove-ids",
"--max-log-bytes",
"--table-memory",
"--max-values-fast",
"--max-values",
"--max-options-bytes",
"--max-radius-64",
"--max-radius-256",
"--max-matches",
"--fast-query-time",
"--query-time",
"--max-result-bytes",
];
#[cfg(feature = "serve")]
const SERVE_FLAGS: [&str; 15] = [
"--stats-file",
"--redis",
"--repeat-window",
"--key-prefix",
"--kind",
"--consumer",
"--jobs",
"--fast-jobs",
"--no-fast",
"--reload-seconds",
"--stats-sample",
"--stats-max-distance-64",
"--stats-max-distance-256",
"--shutdown-grace",
"--heartbeat",
];
fn main() -> ExitCode {
let mut arguments = std::env::args().skip(1);
let command = arguments.next();
let rest: Vec<String> = arguments.collect();
let flags = |extra: &[&'static str]| -> Vec<&'static str> { SET_FLAGS.iter().chain(extra).copied().collect() };
let run = |allowed: &[&str], positional: bool, command: &dyn Fn(&Arguments) -> Result<ExitCode, Usage>| {
parse(&rest, allowed, positional).and_then(|arguments| {
if arguments.help {
Ok(help())
} else {
command(&arguments)
}
})
};
let result = match command.as_deref() {
Some("query") => run(&flags(&["--input", "--lane"]), false, &query),
Some("stats") => run(&flags(&["--sample", "--max-distance", "--seed"]), false, &stats),
Some("verify") => run(&[], true, &verify),
Some("info") => run(&[], false, &|_| info()),
#[cfg(feature = "serve")]
Some("serve") => run(&flags(&SERVE_FLAGS), false, &serve_command::serve),
#[cfg(not(feature = "serve"))]
Some("serve") if rest.iter().any(|argument| is_help(argument)) => Ok(help()),
#[cfg(not(feature = "serve"))]
Some("serve") => Err(Usage(
"this build has no `serve`; build it with `--features serve`".to_owned(),
)),
Some("help" | "--help" | "-h") | None => Ok(help()),
Some("--version" | "-V") => {
println!("legit-hamming {}", env!("CARGO_PKG_VERSION"));
Ok(ExitCode::SUCCESS)
}
Some(other) => Err(Usage(format!("there's no command `{}`", service::shorten(other, 64)))),
};
result.unwrap_or_else(|Usage(message)| {
eprintln!("legit-hamming: {message}; see `legit-hamming help`");
ExitCode::from(2)
})
}
fn help() -> ExitCode {
print!("{HELP}");
ExitCode::SUCCESS
}
fn is_help(argument: &str) -> bool {
matches!(argument, "--help" | "-h")
}
fn parse(rest: &[String], allowed: &[&str], positional: bool) -> Result<Arguments, Usage> {
let mut arguments = Arguments {
specs: Vec::new(),
input: None,
lane: Lane::Bulk,
load: LoadConfig::default(),
limits: Limits::default(),
threads: None,
sample: None,
max_distance: None,
seed: None,
positional: Vec::new(),
help: false,
serve: ServeArguments {
redis: None,
key_prefix: String::new(),
kind: None,
consumer: None,
jobs: 1,
fast_jobs: 2,
no_fast: false,
reload: Duration::from_secs(30),
shutdown_grace: Duration::from_secs(30),
heartbeat: Duration::from_secs(30),
stats_file: None,
},
};
let mut iter = rest.iter();
while let Some(argument) = iter.next() {
if is_help(argument) {
arguments.help = true;
return Ok(arguments);
}
if positional && !argument.starts_with("--") {
arguments.positional.push(argument.clone());
continue;
}
let (flag, inline) = match argument.split_once('=') {
Some((flag, value)) if flag.starts_with("--") => (flag, Some(value.to_owned())),
_ => (argument.as_str(), None),
};
if !allowed.contains(&flag) {
return Err(Usage(format!("`{}` isn't an option here", service::shorten(flag, 64))));
}
let mut value = || {
inline
.clone()
.or_else(|| iter.next().cloned())
.ok_or_else(|| Usage(format!("`{flag}` needs a value")))
};
let limits = &mut arguments.limits;
let serve = &mut arguments.serve;
match flag {
"--index" => arguments.specs.push(SetSpec::parse_index(&value()?).map_err(Usage)?),
"--subset" => arguments.specs.push(SetSpec::parse_subset(&value()?).map_err(Usage)?),
"--threads" => arguments.threads = Some(number(flag, &value()?, 1)?),
"--table-memory" => arguments.load.table_memory = table_memory(&value()?)?,
"--state-dir" => arguments.load.state_dir = Some(PathBuf::from(value()?)),
"--max-change-records" => limits.max_change_records = number(flag, &value()?, 1)?,
"--max-remove-ids" => limits.max_remove_ids = number(flag, &value()?, 1)?,
"--max-log-bytes" => limits.max_log_bytes = number(flag, &value()?, 1)?,
"--repeat-window" => {
arguments.load.repeat_window = Duration::from_millis(millis(flag, &value()?)?);
}
"--max-values-fast" => limits.max_values_fast = number(flag, &value()?, 1)?,
"--max-values" => limits.max_values = number(flag, &value()?, 1)?,
"--max-options-bytes" => limits.max_options_bytes = number(flag, &value()?, 1)?,
"--max-radius-64" => limits.max_radius_64 = number(flag, &value()?, 0)?,
"--max-radius-256" => limits.max_radius_256 = number(flag, &value()?, 0)?,
"--max-matches" => limits.max_matches = number(flag, &value()?, 1)?,
"--fast-query-time" => limits.query_time_fast_ms = millis(flag, &value()?)?,
"--query-time" => limits.query_time_ms = millis(flag, &value()?)?,
"--max-result-bytes" => limits.max_result_bytes = number(flag, &value()?, 1)?,
"--input" => arguments.input = Some(PathBuf::from(value()?)),
"--lane" => {
arguments.lane = match value()?.as_str() {
"fast" => Lane::Fast,
"bulk" => Lane::Bulk,
_ => return Err(Usage("`--lane` is `fast` or `bulk`".to_owned())),
};
}
"--sample" => arguments.sample = Some(number(flag, &value()?, 1)?),
"--max-distance" => arguments.max_distance = Some(number(flag, &value()?, 0)?),
"--seed" => arguments.seed = Some(number(flag, &value()?, 0)?),
"--stats-sample" => arguments.load.sample = number(flag, &value()?, 0)?,
"--stats-max-distance-64" => arguments.load.max_distance_64 = number(flag, &value()?, 0)?,
"--stats-max-distance-256" => arguments.load.max_distance_256 = number(flag, &value()?, 0)?,
"--redis" => serve.redis = Some(value()?),
"--key-prefix" => serve.key_prefix = value()?,
"--kind" => serve.kind = Some(value()?),
"--consumer" => serve.consumer = Some(value()?),
"--jobs" => serve.jobs = number(flag, &value()?, 1)?,
"--fast-jobs" => serve.fast_jobs = number(flag, &value()?, 1)?,
"--no-fast" => serve.no_fast = true,
"--reload-seconds" => serve.reload = Duration::from_millis(millis(flag, &value()?)?),
"--shutdown-grace" => serve.shutdown_grace = Duration::from_millis(millis(flag, &value()?)?),
"--stats-file" => serve.stats_file = Some(PathBuf::from(value()?)),
_ => serve.heartbeat = Duration::from_millis(millis(flag, &value()?)?),
}
}
if let Some(threads) = arguments.threads {
arguments.load.threads = threads;
}
if let Some(seed) = arguments.seed {
arguments.load.seed = seed;
}
if let Some(sample) = arguments.sample {
arguments.load.sample = sample;
}
if let Some(distance) = arguments.max_distance {
arguments.load.max_distance_64 = distance;
arguments.load.max_distance_256 = distance;
}
arguments
.limits
.validate()
.map_err(|message| Usage(format!("the limits don't fit together: {message}")))?;
arguments.load.max_log_read_bytes = arguments.limits.log_read_bound();
Ok(arguments)
}
fn number<T: std::str::FromStr + PartialOrd + From<u8>>(flag: &str, text: &str, least: u8) -> Result<T, Usage> {
match text.parse::<T>() {
Ok(value) if value >= T::from(least) => Ok(value),
_ => Err(Usage(format!(
"`{flag}` takes a whole number of at least {least}, not `{}`",
service::shorten(text, 32)
))),
}
}
fn millis(flag: &str, text: &str) -> Result<u64, Usage> {
match text.parse::<f64>() {
Ok(seconds) if seconds.is_finite() && (0.001..=86_400.0).contains(&seconds) =>
{
#[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "checked above")]
Ok((seconds * 1000.0).round() as u64)
}
_ => Err(Usage(format!(
"`{flag}` takes seconds from 0.001 to 86400, not `{}`",
service::shorten(text, 32)
))),
}
}
fn table_memory(text: &str) -> Result<TableMemory, Usage> {
if text == "auto" {
return Ok(TableMemory::Auto);
}
let (digits, shift) = match text.char_indices().last() {
Some((at, 'k' | 'K')) => (&text[..at], 10),
Some((at, 'm' | 'M')) => (&text[..at], 20),
Some((at, 'g' | 'G')) => (&text[..at], 30),
_ => (text, 0),
};
digits
.parse::<u64>()
.ok()
.and_then(|bytes| bytes.checked_mul(1 << shift))
.map(TableMemory::Bytes)
.ok_or_else(|| {
Usage(format!(
"`--table-memory` is `auto` or bytes with an optional k, m or g, not `{}`",
service::shorten(text, 32)
))
})
}
fn load(arguments: &Arguments, neighbours: bool) -> Result<Arc<Catalog>, Usage> {
let mut config = arguments.load.clone();
config.neighbours = neighbours;
let catalog = Catalog::new(arguments.specs.clone(), config).map_err(Usage)?;
catalog.refresh(&mut |event| match event {
Event::Refused { set, reason } => eprintln!("legit-hamming: `{set}`: {reason}"),
Event::Failed {
set, snapshot, reason, ..
} => {
eprintln!("legit-hamming: `{set}`: snapshot `{snapshot}` failed to load: {reason}");
}
Event::LogRefused { set, reason } => eprintln!("legit-hamming: `{set}`: its change log is refused: {reason}"),
_ => {}
});
Ok(Arc::new(catalog))
}
fn service(arguments: &Arguments, catalog: Arc<Catalog>) -> Service {
Service::new(catalog, arguments.limits, arguments.load.threads)
}
fn query(arguments: &Arguments) -> Result<ExitCode, Usage> {
let reader: Box<dyn BufRead> = match &arguments.input {
Some(path) if path.as_os_str() != "-" => Box::new(BufReader::with_capacity(
1 << 16,
File::open(path).map_err(|error| Usage(format!("couldn't open `{}`: {error}", path.display())))?,
)),
_ => Box::new(BufReader::with_capacity(1 << 16, io::stdin())),
};
let catalog = load(arguments, false)?;
for (set, why) in catalog.unready() {
eprintln!("legit-hamming: `{set}` can't be searched: {why}");
}
let service = service(arguments, catalog);
let mut out = BufWriter::new(io::stdout().lock());
let mut failed = false;
let result = each_line(reader, arguments.limits.max_options_bytes, |line| {
let json = match line {
Ok(options) => service.search(options, arguments.lane).map(|answer| answer.json),
Err(error) => Err(error),
}
.unwrap_or_else(|error| {
failed = true;
error.to_json()
});
writeln!(out, "{json}")
})
.and_then(|()| out.flush());
match result {
Err(error) if error.kind() != io::ErrorKind::BrokenPipe => {
eprintln!("legit-hamming: {error}");
Ok(ExitCode::from(2))
}
_ if failed => Ok(ExitCode::from(1)),
_ => Ok(ExitCode::SUCCESS),
}
}
fn each_line(
mut reader: impl BufRead,
most: usize,
mut each: impl FnMut(Result<&str, service::ServiceError>) -> io::Result<()>,
) -> io::Result<()> {
let mut line = Vec::new();
loop {
line.clear();
let read = Read::by_ref(&mut reader)
.take(u64::try_from(most).unwrap_or(u64::MAX).saturating_add(2))
.read_until(b'\n', &mut line)?;
if read == 0 {
return Ok(());
}
let ended = line.last() == Some(&b'\n');
if ended {
line.pop();
if line.last() == Some(&b'\r') {
line.pop();
}
}
if line.len() > most {
if !ended {
reader.skip_until(b'\n')?;
}
each(Err(service::ServiceError::new(
service::ErrorType::InvalidOptions,
format!("the line is more than {most} bytes of `options`"),
)))?;
continue;
}
if line.iter().all(u8::is_ascii_whitespace) {
continue;
}
match std::str::from_utf8(&line) {
Ok(text) => each(Ok(text))?,
Err(_) => each(Err(service::ServiceError::new(
service::ErrorType::InvalidOptions,
"the line isn't UTF-8",
)))?,
}
}
}
fn stats(arguments: &Arguments) -> Result<ExitCode, Usage> {
let catalog = load(arguments, true)?;
let ready = catalog.unready().is_empty();
let service = service(arguments, catalog);
let mut out = io::stdout().lock();
for line in service.all_stats() {
if writeln!(out, "{line}").is_err() {
return Ok(ExitCode::from(2));
}
}
Ok(if ready { ExitCode::SUCCESS } else { ExitCode::from(1) })
}
fn verify(arguments: &Arguments) -> Result<ExitCode, Usage> {
let [dir] = arguments.positional.as_slice() else {
return Err(Usage("`verify` takes one snapshot directory".to_owned()));
};
let started = Instant::now();
let (sound, object) = match verify_snapshot(dir.as_ref()) {
Ok(verified) => (
true,
serde_json::json!({"snapshot": dir, "sound": true, "seconds": started.elapsed().as_secs_f64(), "holds": verified}),
),
Err(error) => (
false,
serde_json::json!({"snapshot": dir, "sound": false, "error": error}),
),
};
println!("{object}");
Ok(if sound { ExitCode::SUCCESS } else { ExitCode::from(1) })
}
fn info() -> Result<ExitCode, Usage> {
let cpu = Cpu::detect();
let object = serde_json::json!({
"program": "legit-hamming",
"version": env!("CARGO_PKG_VERSION"),
"format": service::FORMAT,
"snapshot": {"format": snapshot::FORMAT, "version": snapshot::VERSION},
"serve": cfg!(feature = "serve"),
"cpu": {
"arch": cpu.arch,
"features": cpu.features,
"paths": cpu.paths.iter().map(|isa| isa.name()).collect::<Vec<_>>(),
"path_64": cpu.best64.name(),
"path_256": cpu.best256.name(),
"threads": cpu.threads,
},
"memory": {"available": service::available_memory()},
"limits": Limits::default(),
});
let json = serde_json::to_string_pretty(&object).map_err(|error| Usage(error.to_string()))?;
if writeln!(io::stdout().lock(), "{json}").is_err() {
return Ok(ExitCode::from(2));
}
Ok(ExitCode::SUCCESS)
}