use std::sync::Arc;
use std::time::Instant;
use serde::Serialize;
use super::FORMAT;
use super::catalog::{Catalog, Generation, Slot, Writer};
use super::error::{ErrorType, ServiceError};
use super::limits::{Lane, Limits};
use super::log::ChangeName;
use super::memory::{available_memory, process_rss};
use super::request::{self, Values};
use super::set::{SearchSet, Sets};
use super::time::rfc3339;
use crate::search::{Cut, Found, Options, Stop};
use crate::value::Value;
pub const BULK_TURN: usize = 256;
const HEADER_BYTES: usize = 512;
const QUERY_BYTES: usize = 96;
pub(crate) const fn result_bytes(width: u32, ids: bool, queries: usize, matches: usize) -> usize {
HEADER_BYTES
.saturating_add(queries.saturating_mul(QUERY_BYTES))
.saturating_add(queries.saturating_mul(matches).saturating_mul(match_bytes(width, ids)))
}
const fn match_bytes(width: u32, ids: bool) -> usize {
(width as usize / 4) + 30 + if ids { 26 } else { 0 }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct Counts {
pub queries: u64,
pub candidates: u64,
pub cut_limit: u64,
pub cut_time: u64,
pub cut_size: u64,
pub matches: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Answer {
pub json: String,
pub counts: Counts,
}
#[derive(Debug)]
pub struct Service {
catalog: Arc<Catalog>,
limits: Limits,
threads: usize,
now: fn() -> Instant,
}
#[derive(Serialize)]
struct SearchObject<'a> {
format: u32,
index: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
subset: Option<&'a str>,
snapshot: &'a str,
seq: u64,
exact: bool,
queries: Vec<QueryObject>,
}
#[derive(Serialize)]
struct QueryObject {
matches: Vec<MatchObject>,
complete: bool,
#[serde(skip_serializing_if = "Option::is_none")]
cut_by: Option<&'static str>,
plan: &'static str,
}
#[derive(Serialize)]
struct MatchObject {
#[serde(skip_serializing_if = "Option::is_none")]
id: Option<u64>,
value: String,
distance: u32,
}
impl Service {
#[must_use]
pub const fn new(catalog: Arc<Catalog>, limits: Limits, threads: usize) -> Self {
Self {
catalog,
limits,
threads,
now: Instant::now,
}
}
#[cfg(test)]
pub(crate) const fn with_clock(
catalog: Arc<Catalog>,
limits: Limits,
threads: usize,
now: fn() -> Instant,
) -> Self {
Self {
catalog,
limits,
threads,
now,
}
}
#[must_use]
pub const fn catalog(&self) -> &Arc<Catalog> {
&self.catalog
}
#[must_use]
pub const fn limits(&self) -> &Limits {
&self.limits
}
#[must_use]
pub const fn threads(&self) -> usize {
self.threads
}
pub fn search(&self, options: &str, lane: Lane) -> Result<Answer, ServiceError> {
self.search_within(options, lane, self.limits.max_result_bytes)
}
pub fn search_within(&self, options: &str, lane: Lane, max_bytes: usize) -> Result<Answer, ServiceError> {
let budget = self.limits.max_result_bytes.min(max_bytes);
let request = request::search(options, &self.limits, lane)?;
let slot = self.catalog.find(&request.index, request.subset.as_deref())?;
let generation = slot.ready()?;
let width = generation.set.width();
if width != request.width {
return Err(ServiceError::new(
ErrorType::WidthMismatch,
format!(
"`{}` holds {width}-bit values; the request gives `width` {}",
slot.label(),
request.width
),
));
}
let queries = request.values.len();
let fixed = result_bytes(width, false, queries, 0);
if fixed > budget {
return Err(ServiceError::new(
ErrorType::TooManyValues,
format!(
"a result of {queries} queries takes at least {fixed} bytes; {budget} are left for it beside \
what the task echoes"
),
));
}
let room = budget - fixed;
let by_size = room
/ queries
.max(1)
.saturating_mul(match_bytes(width, generation.set.has_ids()));
let options = Options {
radius: request.radius,
limit: request.limit,
max_matches: Some(self.limits.max_matches.min(by_size)),
time_budget: Some(self.limits.query_time(lane)),
threads: match lane {
Lane::Fast => 1,
Lane::Bulk => self.threads,
},
exclude_zero: request.exclude_zero,
};
let mut counts = Counts {
queries: queries as u64,
..Counts::default()
};
let queries = match (&generation.set, &request.values) {
(Sets::W64(set), Values::W64(values)) => run(set, values, &options, self.now, &mut counts),
(Sets::W256(set), Values::W256(values)) => run(set, values, &options, self.now, &mut counts),
_ => return Err(ServiceError::new(ErrorType::Internal, "the widths disagree")),
};
let object = SearchObject {
format: FORMAT,
index: &slot.index,
subset: slot.subset.as_deref(),
snapshot: &generation.snapshot,
seq: generation.set.seq(),
exact: true,
queries,
};
let json = serde_json::to_string(&object)
.map_err(|error| ServiceError::new(ErrorType::Internal, error.to_string()))?;
Ok(Answer { json, counts })
}
#[must_use]
pub fn takes_changes(&self) -> bool {
let config = self.catalog.config();
config.state_dir.is_some() && config.write_changes
}
pub fn change(&self, task_id: &str, task_name: &str, options: &str) -> Result<String, ServiceError> {
let name = match task_name {
"append" => ChangeName::Append,
"replace" => ChangeName::Replace,
"remove" => ChangeName::Remove,
_ => {
return Err(ServiceError::new(
ErrorType::InvalidTask,
"a change task is `append`, `replace` or `remove`",
));
}
};
if !super::log::is_valid_task_id(task_id) {
return Err(super::catalog::invalid_task_id());
}
if !self.takes_changes() {
return Err(ServiceError::new(
ErrorType::InvalidTask,
"this service keeps no change log: changes are taken by `serve --state-dir`",
));
}
let request = request::change(options, &self.limits, name)?;
self.catalog.change(task_id, request, &self.limits)
}
pub fn stats(&self, options: &str) -> Result<String, ServiceError> {
let request = request::stats(options, &self.limits)?;
let slot = self.catalog.find(&request.index, request.subset.as_deref())?;
serde_json::to_string(&self.stats_object(slot))
.map_err(|error| ServiceError::new(ErrorType::Internal, error.to_string()))
}
#[must_use]
pub fn all_stats(&self) -> Vec<String> {
self.catalog
.slots()
.iter()
.map(|slot| serde_json::to_string(&self.stats_object(slot)).unwrap_or_default())
.collect()
}
fn stats_object<'a>(&'a self, slot: &'a Slot) -> StatsObject<'a> {
let view = slot.view();
let state = match (&view.current, &view.loading, &view.log_refused) {
(_, _, Some(_)) => "refused",
(Some(_), _, _) => "ready",
(None, Some(_), _) => "loading",
(None, None, None) => "empty",
};
let (rss, peak) = process_rss().unzip();
StatsObject {
format: FORMAT,
index: &slot.index,
subset: slot.subset.as_deref(),
state,
refused: view.log_refused.as_ref().map(|refused| refused.message.clone()),
refused_code: view.log_refused.as_ref().map(|refused| refused.code),
seq: view.current.as_ref().map_or(0, |current| current.set.seq()),
snapshot: view.current.as_deref().map(snapshot_object),
loading: view.loading.as_ref().map(|loading| LoadingObject {
snapshot: loading.snapshot.clone(),
fraction: loading.fraction(),
bytes_read: loading.read.load(std::sync::atomic::Ordering::Relaxed),
bytes: loading.total,
}),
last_failure: view.failed.as_ref().map(|failed| FailureObject {
snapshot: failed.snapshot.clone(),
code: failed.code,
reason: failed.reason.clone(),
at: rfc3339(failed.at),
}),
changes: view.log.map(|log| {
let (values, removals, bytes) =
view.current.as_ref().map_or((0, 0, 0), |current| current.set.changes());
ChangesObject {
writer: view.writer.map(|writer| match writer {
Writer::Ok => "ok",
Writer::Broken(_) => "broken",
}),
writer_reason: match view.writer {
Some(Writer::Broken(code)) => Some(code),
_ => None,
},
remembered: view.remembered,
log: LogObject {
tasks: log.tasks,
entries: log.entries,
bytes: log.bytes,
first_seq: log.first_seq,
last_seq: log.last_seq,
base_seq: log.base_seq,
},
held: HeldObject {
values,
removals,
bytes: bytes as u64,
},
}
}),
neighbours: view.current.as_deref().map(|current| self.neighbours_object(current)),
memory: MemoryObject {
records: view
.current
.as_ref()
.map_or(0, |current| current.set.memory().records as u64),
tables: view
.current
.as_ref()
.map_or(0, |current| current.set.memory().index as u64),
process_rss: rss,
process_peak_rss: peak,
available: available_memory(),
},
limits: &self.limits,
threads: self.threads,
}
}
fn neighbours_object(&self, generation: &Generation) -> NeighboursObject {
let config = self.catalog.config();
match generation.neighbours.get() {
Some(neighbours) => NeighboursObject {
state: "measured",
sample: Some(neighbours.table.sample),
seed: Some(neighbours.table.seed),
max_distance: Some(neighbours.max_distance),
counts: Some(neighbours.table.counts.clone()),
ms: Some(neighbours.ms),
},
None => NeighboursObject {
state: if config.neighbours { "measuring" } else { "off" },
sample: None,
seed: None,
max_distance: None,
counts: None,
ms: None,
},
}
}
}
fn snapshot_object(generation: &Generation) -> SnapshotObject {
SnapshotObject {
name: generation.snapshot.clone(),
width: generation.set.width(),
ids: generation.set.has_ids(),
records: generation.set.len(),
loaded_at: rfc3339(generation.loaded_at),
covers_seq: generation.covers_seq,
tables: generation.set.has_tables(),
table_bytes: generation.table_bytes,
table_budget: generation.table_budget,
load_ms: generation.load_ms,
build_ms: generation.build_ms,
replayed: generation.replayed,
replay_ms: generation.replay_ms,
}
}
fn run<V: Value>(
set: &SearchSet<V>,
values: &[V],
options: &Options,
now: fn() -> Instant,
counts: &mut Counts,
) -> Vec<QueryObject> {
let stop = Stop::after(options.time_budget, now);
let mut entries = Vec::with_capacity(values.len());
for turn in values.chunks(BULK_TURN) {
for found in set.search_until(turn, options, &stop) {
entries.push(entry(found, counts));
}
}
entries
}
fn entry<V: Value>(found: Found<V>, counts: &mut Counts) -> QueryObject {
counts.candidates = counts.candidates.saturating_add(found.candidates);
match found.cut_by {
Some(Cut::Limit) => counts.cut_limit += 1,
Some(Cut::Time) => counts.cut_time += 1,
Some(Cut::Size) => counts.cut_size += 1,
_ => {}
}
counts.matches = counts.matches.saturating_add(found.matches.len() as u64);
QueryObject {
complete: found.is_complete(),
cut_by: found.cut_by.map(Cut::name),
plan: found.plan.map_or("scan", |plan| plan.strategy.name()),
matches: found
.matches
.into_iter()
.map(|found| MatchObject {
id: found.id,
value: found.value.to_hex(),
distance: found.distance,
})
.collect(),
}
}
#[derive(Serialize)]
struct StatsObject<'a> {
format: u32,
index: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
subset: Option<&'a str>,
state: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
refused: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
refused_code: Option<&'static str>,
seq: u64,
#[serde(skip_serializing_if = "Option::is_none")]
snapshot: Option<SnapshotObject>,
#[serde(skip_serializing_if = "Option::is_none")]
loading: Option<LoadingObject>,
#[serde(skip_serializing_if = "Option::is_none")]
last_failure: Option<FailureObject>,
#[serde(skip_serializing_if = "Option::is_none")]
changes: Option<ChangesObject>,
#[serde(skip_serializing_if = "Option::is_none")]
neighbours: Option<NeighboursObject>,
memory: MemoryObject,
limits: &'a Limits,
threads: usize,
}
#[derive(Serialize)]
struct SnapshotObject {
name: String,
width: u32,
ids: bool,
records: usize,
loaded_at: String,
covers_seq: Option<u64>,
tables: bool,
table_bytes: u64,
table_budget: Option<u64>,
load_ms: u64,
build_ms: u64,
replayed: usize,
replay_ms: u64,
}
#[derive(Serialize)]
struct ChangesObject {
log: LogObject,
held: HeldObject,
#[serde(skip_serializing_if = "Option::is_none")]
writer: Option<&'static str>,
#[serde(skip_serializing_if = "Option::is_none")]
writer_reason: Option<&'static str>,
remembered: usize,
}
#[derive(Serialize)]
struct LogObject {
tasks: usize,
entries: usize,
bytes: u64,
first_seq: Option<u64>,
last_seq: u64,
base_seq: u64,
}
#[derive(Serialize)]
struct HeldObject {
values: usize,
removals: usize,
bytes: u64,
}
#[derive(Serialize)]
struct LoadingObject {
snapshot: String,
fraction: Option<f64>,
bytes_read: u64,
bytes: u64,
}
#[derive(Serialize)]
struct FailureObject {
snapshot: String,
code: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
reason: Option<String>,
at: String,
}
#[derive(Serialize)]
struct NeighboursObject {
state: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
sample: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
seed: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
max_distance: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
counts: Option<Vec<u64>>,
#[serde(skip_serializing_if = "Option::is_none")]
ms: Option<u64>,
}
#[derive(Serialize)]
struct MemoryObject {
records: u64,
tables: u64,
process_rss: Option<u64>,
process_peak_rss: Option<u64>,
available: Option<u64>,
}
#[cfg(test)]
mod tests {
use serde_json::Value as Json;
use super::*;
use crate::Records;
use crate::search::ticking;
use crate::service::{LoadConfig, SetSpec};
use crate::snapshot;
#[test]
fn a_search_whose_deadline_passed_before_its_result_was_built_is_cut_by_time() {
let dir = std::env::temp_dir().join(format!("legit-hamming-answer-clock-{}", std::process::id()));
let records = Records::from_records((0..900u64).map(|id| (id, id % 4))).expect("ids rise");
snapshot::write(&dir.join("first"), &records, 1_000).expect("written");
std::fs::write(dir.join("CURRENT"), "first\n").expect("written");
let config = LoadConfig {
neighbours: false,
table_memory: crate::service::TableMemory::Bytes(0),
..LoadConfig::default()
};
let catalog = Arc::new(Catalog::new(vec![SetSpec::index("images", &dir)], config).expect("a catalog"));
catalog.refresh(&mut |_| {});
let options = r#"{"format":1,"index":"images","width":64,"radius":1,"values":["0000000000000000"]}"#;
let mut runs = Vec::new();
for budget in 1..30 {
let mut limits = Limits::new();
limits.query_time_fast_ms = budget;
let service = Service::with_clock(Arc::clone(&catalog), limits, 1, ticking::now);
ticking::reset();
let answer = service.search(options, Lane::Fast).expect("an answer");
let json: Json = serde_json::from_str(&answer.json).expect("JSON");
runs.push((answer.counts, json["queries"][0].clone()));
}
std::fs::remove_dir_all(&dir).ok();
let (counts, query) = runs.last().expect("runs");
assert_eq!((counts.candidates, counts.cut_time), (900, 0));
assert_eq!(query["matches"].as_array().map(Vec::len), Some(675));
let (_, query) = runs
.iter()
.find(|(counts, _)| counts.candidates == 900 && counts.cut_time == 1)
.expect("a budget that ended between the last comparison and the result");
assert_eq!(query["cut_by"], "time");
let matches = query["matches"].as_array().expect("matches");
assert_eq!(matches.len(), 225);
assert!(matches.iter().all(|found| found["distance"] == 0));
}
}