use std::sync::Arc;
use serde_json::Value;
use super::Lent;
use super::codec::Message;
use super::protocol::{
Empty, Failure, Handle, SearchDeleted, SearchDocument, SearchDropped, SearchFound, SearchGot, SearchHit,
SearchIndex, SearchKey, SearchListed, SearchMatch, SearchName, SearchOpen, SearchQuery, SearchSet, SearchSetMany,
SearchStatement, SearchStatus, SearchTotal, method,
};
use crate::engine::SharedFile;
use crate::search::{self, Document, Index, Match, Rebuild, SearchCall, Status, Unit};
use crate::{Store, unix_millis};
use super::Answered;
#[derive(Default)]
pub(crate) struct Handles {
open: super::ByHandle<Index<Value>>,
}
impl Handles {
fn index(&self, handle: u64) -> Result<Index<Value>, Failure> {
self.open.get(handle, || format!("index {handle}: no such handle"))
}
fn documents(&self, handle: u64) -> Result<Index<Value>, Failure> {
let index = self.index(handle)?;
if index.follows_table() {
return Err(Failure::invalid(format!(
"index {}: a table's index follows its table's rows, which are written to the table",
index.name()
)));
}
Ok(index)
}
}
pub(crate) fn call(
store: &Store,
handles: &Handles,
lent: Lent<'_>,
called: u16,
body: &[u8],
read_only: bool,
) -> Answered {
match called {
method::SEARCH_OPEN => open((store, lent), handles, SearchOpen::decode(body)?, read_only),
method::SEARCH_SET => set(handles, SearchSet::decode(body)?),
method::SEARCH_SET_MANY => set_many(handles, SearchSetMany::decode(body)?),
method::SEARCH_DELETE => {
let key = SearchKey::decode(body)?;
Ok(SearchDeleted { deleted: handles.documents(key.handle)?.delete(&key.id)? }.encode())
}
method::SEARCH_GET => {
let key = SearchKey::decode(body)?;
let value = handles.documents(key.handle)?.get(&key.id)?;
Ok(SearchGot { found: value.is_some(), value: value.map(|value| value.to_string()) }.encode())
}
method::SEARCH_SEARCH => searched(handles, SearchQuery::decode(body)?),
method::SEARCH_STATUS => Ok(status(&handles.index(Handle::decode(body)?.handle)?.status()?).encode()),
method::SEARCH_DROP_INDEX => {
Ok(SearchDropped { dropped: dropped(store, lent, SearchName::decode(body)?)? }.encode())
}
method::SEARCH_LIST => {
Empty::decode(body)?;
let indexes = if read_only { search::list_as_it_is(store)? } else { search::list(store)? };
Ok(SearchListed { indexes: indexes.iter().map(listed).collect() }.encode())
}
other => Err(Failure::unimplemented(format!("method {other:#06x}"))),
}
}
fn open((store, lent): (&Store, Lent<'_>), handles: &Handles, asked: SearchOpen, read_only: bool) -> Answered {
let index = match asked.database {
Some(database) => table_index(lent(database)?, &asked, read_only)?,
None if read_only => search::open_as_it_is(store, &asked.name)?,
None => documents_index(store, &asked)?,
};
let handle = handles.open.keep(index);
Ok(Handle { handle }.encode())
}
fn documents_index(store: &Store, asked: &SearchOpen) -> Result<Index<Value>, Failure> {
let mut builder = store.index::<Value>(&asked.name).typo_tolerance(asked.typo_tolerance.unwrap_or(true));
for field in &asked.fields {
builder = builder.field(&field.path, field.weight);
}
builder = builder.filters(&asked.filters).layouts(&asked.layouts);
if let Some(dimensions) = asked.dimensions {
builder = builder.vectors(usize::try_from(dimensions).unwrap_or(usize::MAX));
}
if let Some(recall) = asked.recall {
builder = builder.recall(recall);
}
if let Some(weight) = asked.vector_weight {
builder = builder.vector_weight(weight);
}
if asked.rerank {
builder = builder.rerank();
}
let builder = builder.rebuild(if asked.manual { Rebuild::Manual } else { Rebuild::Automatic });
Ok(if asked.reindex { builder.reindex()? } else { builder.open()? })
}
#[cfg(feature = "sql")]
fn table_index(shared: Arc<SharedFile>, asked: &SearchOpen, read_only: bool) -> Result<Index<Value>, Failure> {
if read_only {
return Ok(search::table_as_it_is(&shared, &asked.name)?);
}
let table = asked.table.as_deref().unwrap_or_default();
let mut builder = search::TableIndexBuilder::<Value>::in_file(shared, &asked.name, search::by_cells()).table(table);
builder = builder.typo_tolerance(asked.typo_tolerance.unwrap_or(true)).filters(&asked.filters);
builder = builder.layouts(&asked.layouts);
if !asked.keys.is_empty() {
builder = builder.key(&asked.keys[..]);
} else if let Some(key) = &asked.key {
builder = builder.key(key);
}
for field in &asked.fields {
builder = builder.field(&field.path, field.weight);
}
match (&asked.vector_column, asked.dimensions) {
(Some(column), Some(dimensions)) => {
builder = builder.vectors(column, usize::try_from(dimensions).unwrap_or(usize::MAX));
}
(None, None) => {}
_ => return Err(Failure::invalid("a table's index reads its vectors from a column of its dimensions")),
}
if let Some(recall) = asked.recall {
builder = builder.recall(recall);
}
if let Some(weight) = asked.vector_weight {
builder = builder.vector_weight(weight);
}
if asked.rerank {
builder = builder.rerank();
}
let builder = builder.rebuild(if asked.manual { Rebuild::Manual } else { Rebuild::Automatic });
Ok(if asked.reindex { builder.reindex()? } else { builder.open()? }.into_index())
}
#[cfg(not(feature = "sql"))]
fn table_index(_: Arc<SharedFile>, _: &SearchOpen, _: bool) -> Result<Index<Value>, Failure> {
Err(Failure::invalid("this server keeps no databases"))
}
fn dropped(store: &Store, lent: Lent<'_>, asked: SearchName) -> Result<bool, Failure> {
match asked.database {
#[cfg(feature = "sql")]
Some(database) => Ok(search::drop_in_file(&*lent(database)?, &asked.name)?),
#[cfg(not(feature = "sql"))]
Some(_) => {
let _ = lent;
Err(Failure::invalid("this server keeps no databases"))
}
None => Ok(store.drop_index(&asked.name)?),
}
}
fn set(handles: &Handles, asked: SearchSet) -> Answered {
let index = handles.documents(asked.handle)?;
let value = document(&asked.value)?;
let vector = floats(asked.vector.as_deref())?;
let call = index.id(&asked.id);
let call = match (&vector, asked.no_vector) {
(Some(vector), _) => call.vector(vector),
(None, true) => call.without_vector(),
(None, false) => {
index.set(&asked.id, &value)?;
return Ok(Empty {}.encode());
}
};
call.set(&value)?;
Ok(Empty {}.encode())
}
struct Read {
id: String,
value: Value,
vector: Option<Option<Vec<f32>>>,
}
impl<'v> Document<'v, Value> for &'v Read {
fn parts(self) -> (String, &'v Value, Option<Option<&'v [f32]>>) {
(self.id.clone(), &self.value, self.vector.as_ref().map(Option::as_deref))
}
}
fn set_many(handles: &Handles, asked: SearchSetMany) -> Answered {
let index = handles.documents(asked.handle)?;
let documents = asked.documents.iter().map(read).collect::<Result<Vec<Read>, Failure>>()?;
index.set_many(&documents)?;
Ok(Empty {}.encode())
}
fn read(given: &SearchDocument) -> Result<Read, Failure> {
let vector = match (floats(given.vector.as_deref())?, given.no_vector) {
(Some(vector), _) => Some(Some(vector)),
(None, true) => Some(None),
(None, false) => None,
};
Ok(Read { id: given.id.clone(), value: document(&given.value)?, vector })
}
fn searched(handles: &Handles, asked: SearchQuery) -> Answered {
let index = handles.index(asked.handle)?;
let vector = floats(asked.vector.as_deref())?;
let call = query(&index, &asked, vector.as_deref())?;
let asked_matches = asked.matches.is_some();
if index.follows_table() {
return rows_found(call, asked_matches);
}
let found = call.run()?;
let hits = found.hits.into_iter().map(|hit| SearchHit {
id: hit.id,
value: hit.value.to_string(),
score: hit.score,
row: None,
matches: asked_matches.then(|| matches(hit.matches)),
text_score: hit.text_score,
similarity: hit.similarity,
});
let total = found.total.map(total);
Ok(SearchFound { hits: hits.collect(), corrected: found.corrected, columns: None, total }.encode())
}
fn total(total: search::Total) -> SearchTotal {
SearchTotal { count: total.count, at_least: total.at_least }
}
fn unit(named: &str) -> Result<Unit, Failure> {
match named {
"utf8" => Ok(Unit::Bytes),
"utf16" => Ok(Unit::Utf16),
"chars" => Ok(Unit::Chars),
other => Err(Failure::invalid(format!("matches counted in {other:?}: utf8, utf16 or chars"))),
}
}
fn matches(found: Vec<Match>) -> Vec<SearchMatch> {
let wide = |at: usize| u64::try_from(at).unwrap_or(u64::MAX);
let each = |found: Match| SearchMatch {
field: found.field,
item: found.item.map(wide),
start: wide(found.at.start),
end: wide(found.at.end),
word: found.word,
};
found.into_iter().map(each).collect()
}
fn query<'i>(
index: &'i Index<Value>,
asked: &SearchQuery,
vector: Option<&'i [f32]>,
) -> Result<SearchCall<'i, Value>, Failure> {
let mut call = index.search(&asked.text).offset(usize::try_from(asked.offset).unwrap_or(usize::MAX));
if let Some(limit) = asked.limit {
call = call.limit(usize::try_from(limit).unwrap_or(usize::MAX));
}
if let Some(vector) = vector {
call = call.vector(vector);
}
if let Some(weight) = asked.vector_weight {
call = call.vector_weight(weight);
}
if asked.rerank {
call = call.rerank();
}
if let Some(cosine) = asked.min_similarity {
call = call.min_similarity(cosine);
}
if asked.prefix_every {
call = call.prefix_every();
} else if asked.prefix {
call = call.prefix();
}
if asked.total {
call = call.total();
}
if let Some(named) = &asked.matches {
call = call.matches_in(unit(named)?);
}
if let Some(conditions) = &asked.r#where {
let statements = asked.statements.iter().map(statement).collect::<Result<Vec<_>, _>>()?;
for condition in search::conditions(conditions, &statements)? {
call = call.filter(condition);
}
}
Ok(call)
}
#[cfg(feature = "sql")]
fn statement(asked: &SearchStatement) -> Result<search::Listing, Failure> {
let statement = super::sql::statement(asked.text.clone(), asked.values.clone())?;
Ok(search::Values::listing(statement))
}
#[cfg(not(feature = "sql"))]
fn statement(_: &SearchStatement) -> Result<search::Listing, Failure> {
Err(Failure::invalid("a where by a statement is a table index's, and this server keeps no databases"))
}
#[cfg(feature = "sql")]
fn rows_found(call: SearchCall<'_, Value>, asked_matches: bool) -> Answered {
let found = search::found_by(call, &crate::sql::cells_on)?;
let columns = found.hits.first().map(|hit| hit.value.0.clone()).unwrap_or_default();
let hits = found.hits.into_iter().map(|hit| SearchHit {
id: hit.id,
value: "null".to_owned(),
score: hit.score,
row: Some(hit.value.1.into_iter().map(super::sql::cell_of).collect()),
matches: asked_matches.then(|| matches(hit.matches)),
text_score: hit.text_score,
similarity: hit.similarity,
});
let total = found.total.map(total);
Ok(SearchFound { hits: hits.collect(), corrected: found.corrected, columns: Some(columns), total }.encode())
}
#[cfg(not(feature = "sql"))]
fn rows_found(_: SearchCall<'_, Value>, _: bool) -> Answered {
Err(Failure::internal("a table's index on a server that keeps no databases"))
}
fn document(text: &str) -> Result<Value, Failure> {
serde_json::from_str(text).map_err(|error| Failure::invalid(format!("a document that is not JSON: {error}")))
}
fn floats(bytes: Option<&[u8]>) -> Result<Option<Vec<f32>>, Failure> {
let Some(bytes) = bytes else { return Ok(None) };
let (floats, rest) = bytes.as_chunks::<4>();
if !rest.is_empty() {
return Err(Failure::invalid(format!("a vector of {} bytes, not four a dimension", bytes.len())));
}
Ok(Some(floats.iter().map(|float| f32::from_le_bytes(*float)).collect()))
}
fn status(status: &Status) -> SearchStatus {
match status {
Status::Ready { error } => {
SearchStatus { state: "ready".to_owned(), done: 0.0, error: error.clone().unwrap_or_default() }
}
Status::Rebuilding { done, error } => {
SearchStatus { state: "rebuilding".to_owned(), done: *done, error: error.clone().unwrap_or_default() }
}
Status::Failed { error } => SearchStatus { state: "failed".to_owned(), done: 0.0, error: error.clone() },
}
}
fn listed(index: &search::Listed) -> SearchIndex {
let status = status(&index.status);
SearchIndex {
name: index.name.clone(),
documents: index.documents,
vectors: index.vectors,
opened: index.opened.map(unix_millis),
state: status.state,
done: status.done,
error: status.error,
}
}
#[cfg(test)]
#[path = "search_tests.rs"]
mod tests;