use std::sync::Mutex;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use crate::engine::{Engine, EngineFuture};
use crate::xunsearch_query::*;
use crate::{SearchBuilder, SearchDocument, SearchHit, SearchResult};
pub struct XunSearchEngine {
project: std::result::Result<String, String>,
index_addr: String,
search_addr: String,
scheme: Mutex<FieldScheme>,
has_ini: bool,
}
impl XunSearchEngine {
pub fn new(host: &str, project: &str, ini_path: Option<&str>) -> Self {
let ini = ini_path
.and_then(|p| std::fs::read_to_string(p).ok())
.and_then(|text| FieldScheme::from_ini(&text));
let (index_addr, search_addr) = Self::split_addrs(host);
let has_ini = ini.is_some();
let project = crate::validate_index_name(project)
.map(|()| project.to_string())
.map_err(|_| project.to_string());
Self {
project,
index_addr,
search_addr,
scheme: Mutex::new(ini.unwrap_or_else(FieldScheme::default)),
has_ini,
}
}
fn project_name(&self) -> crate::Result<&str> {
self.project
.as_ref()
.map(String::as_str)
.map_err(|raw| crate::ScoutError::InvalidIndexName(raw.clone()))
}
fn split_addrs(host: &str) -> (String, String) {
match host.rsplit_once(':') {
Some((h, p)) if !h.is_empty() && p.parse::<u16>().is_ok() => {
let p = p.parse::<u16>().unwrap();
match p.checked_add(1) {
Some(search) => (format!("{h}:{p}"), format!("{h}:{search}")),
None => (format!("{h}:8383"), format!("{h}:8384")),
}
}
Some((h, _)) if !h.is_empty() => (format!("{h}:8383"), format!("{h}:8384")),
_ => (format!("{host}:8383"), format!("{host}:8384")),
}
}
async fn connect(&self, search: bool) -> crate::Result<TcpStream> {
let addr = if search { &self.search_addr } else { &self.index_addr };
with_timeout(TcpStream::connect(addr)).await
}
async fn open(&self, search: bool, db: Option<&str>) -> crate::Result<TcpStream> {
let project = self.project_name()?; if let Some(db) = db {
crate::validate_index_name(db)?; }
let mut stream = self.connect(search).await?;
with_timeout(stream.write_all(&pack_cmd(CMD_USE, 0, 0, project.as_bytes(), &[]))).await?;
expect_ok(&mut stream, OK_PROJECT, "CMD_USE").await?;
if let Some(db) = db {
with_timeout(stream.write_all(&pack_cmd(CMD_INDEX_SET_DB, 0, 0, db.as_bytes(), &[]))).await?;
expect_ok(&mut stream, OK_DB_CHANGED, "CMD_INDEX_SET_DB").await?;
}
Ok(stream)
}
fn build_silent(&self, builder: &SearchBuilder) -> crate::Result<Vec<u8>> {
if builder.orders.len() > 1 {
return Err(crate::ScoutError::Unsupported("xunsearch: multiple order_by not supported (SET_SORT 单字段)".to_string()));
}
let scheme = self.scheme.lock().expect("xunsearch scheme poisoned");
let mut out = Vec::new();
out.extend_from_slice(&pack_cmd(CMD_QUERY_INIT, 0, 0, &[], &[]));
out.extend_from_slice(&pack_cmd(CMD_QUERY_PARSE, 0, 0, builder.query.as_bytes(), &[]));
if let Some(order) = builder.orders.first() {
let vno = field_vno(&scheme, &order.field, "order")?;
let flag = if order.desc { 0 } else { SORT_ASCENDING };
out.extend_from_slice(&pack_cmd(CMD_SEARCH_SET_SORT, SORT_TYPE_VALUE | flag, vno, &[], &[]));
}
for vno in scheme.numeric_vnos() {
out.extend_from_slice(&pack_cmd(CMD_SEARCH_SET_NUMERIC, 0, vno, &[], &[]));
}
for w in &builder.wheres {
let vno = field_vno(&scheme, &w.field, "where")?;
let value = value_bytes(&w.value);
if value.len() > 255 {
return Err(crate::ScoutError::XunSearch(format!("xunsearch: where_field `{}` value exceeds 255 bytes (QUERY_RANGE buf1 上限)", w.field)));
}
out.extend_from_slice(&pack_cmd(CMD_QUERY_RANGE, 0, vno, &value, &value));
}
Ok(out)
}
async fn do_search(&self, builder: &SearchBuilder) -> crate::Result<SearchResult> {
let index = builder.index.as_deref().unwrap_or("default");
crate::validate_index_name(index)?;
if builder.trashed == crate::TrashedFilter::OnlyTrashed {
return Err(crate::ScoutError::Unsupported("xunsearch: only_trashed requires soft_delete, which this engine does not implement".to_string()));
}
if builder.where_ins.iter().any(|(_, v)| v.is_empty()) {
return Ok(SearchResult::default());
}
let unsupported = !builder.where_ins.is_empty()
|| builder.where_not_ins.iter().any(|(_, v)| !v.is_empty());
if unsupported {
return Err(crate::ScoutError::Unsupported("xunsearch: where_in/where_not_in not supported; use where_field (QUERY_RANGE)".to_string()));
}
let mut stream = self.open(true, Some(index)).await?;
let mut buf = self.build_silent(builder)?;
let limit = builder.take.unwrap_or(10);
let accepted = limit.min(MAX_HITS);
let offset_limit = [builder.skip.unwrap_or(0) as u32, limit as u32].map(u32::to_le_bytes).concat();
buf.extend_from_slice(&pack_cmd(CMD_SEARCH_GET_RESULT, 0, 0, builder.query.as_bytes(), &offset_limit));
with_timeout(stream.write_all(&buf)).await?;
self.read_result(&mut stream, accepted).await
}
async fn read_result(&self, stream: &mut TcpStream, limit: usize) -> crate::Result<SearchResult> {
let id_vno = self.scheme.lock().expect("xunsearch scheme poisoned").id_vno();
let (cmd, arg, buf, _) = read_packet(stream).await?;
if cmd == CMD_ERR {
return Err(server_err(arg, &buf));
}
if cmd != CMD_OK || arg != OK_RESULT_BEGIN {
return Err(crate::ScoutError::XunSearch(format!("SEARCH_GET_RESULT: unexpected response cmd={cmd} arg={arg}")));
}
let total = buf
.get(..4)
.map(|b| u32::from_le_bytes(b.try_into().unwrap()))
.unwrap_or(0) as usize;
let body = async {
let mut hits: Vec<SearchHit> = Vec::new();
loop {
let (cmd, arg, buf, _) = read_packet(stream).await?;
match cmd {
CMD_OK if arg == OK_RESULT_END => break,
CMD_SEARCH_RESULT_DOC => {
if hits.len() >= limit {
return Err(crate::ScoutError::XunSearch(format!(
"SEARCH_GET_RESULT: peer sent more than the accepted {limit} documents"
)));
}
let weight = buf
.get(16..20)
.map(|b| f32::from_le_bytes(b.try_into().unwrap()))
.unwrap_or(0.0);
hits.push(SearchHit {
id: String::new(),
score: Some(f64::from(weight)),
source: serde_json::Value::Object(Default::default()),
highlight: None,
});
}
CMD_SEARCH_RESULT_FIELD => {
let vno = arg as u8;
let value = String::from_utf8_lossy(&buf).to_string();
let hit = hits.last_mut().ok_or_else(|| {
crate::ScoutError::XunSearch("result field before any doc".to_string())
})?;
if vno == id_vno {
hit.id = value;
} else {
let name = {
let scheme = self.scheme.lock().expect("xunsearch scheme poisoned");
scheme
.name_for_vno(vno)
.map(str::to_string)
.or_else(|| (vno == MIXED_VNO).then(|| "body".to_string()))
};
let name = name.ok_or_else(|| {
crate::ScoutError::XunSearch(format!(
"search result: field vno {vno} not in the local field scheme (writer used a different scheme)"
))
})?;
hit.source
.as_object_mut()
.unwrap()
.insert(name, serde_json::Value::String(value));
}
}
CMD_SEARCH_RESULT_FACETS | CMD_SEARCH_RESULT_MATCHED => {}
CMD_ERR => return Err(server_err(arg, &buf)),
other => {
return Err(crate::ScoutError::XunSearch(format!("search result: unexpected cmd {other}")))
}
}
}
Ok(hits)
};
let hits = match tokio::time::timeout(RESULT_DEADLINE, body).await {
Ok(Ok(hits)) => hits,
Ok(Err(e)) => return Err(e),
Err(_) => {
return Err(crate::ScoutError::XunSearch(format!(
"SEARCH_GET_RESULT: result stream exceeded the {}s deadline",
RESULT_DEADLINE.as_secs()
)))
}
};
Ok(SearchResult { hits, total, ..SearchResult::default() })
}
async fn send_removes(&self, stream: &mut TcpStream, ids: &[String]) -> crate::Result<()> {
let id_vno = self.scheme.lock().expect("xunsearch scheme poisoned").id_vno();
let mut buf = Vec::new();
for id in ids {
buf.extend_from_slice(&pack_cmd(CMD_INDEX_REMOVE, 0, id_vno, id.to_lowercase().as_bytes(), &[]));
}
with_timeout(stream.write_all(&buf)).await?;
for _ in ids {
expect_ok(stream, OK_RQST_FINISHED, "CMD_INDEX_REMOVE").await?;
}
Ok(())
}
}
fn field_vno(scheme: &FieldScheme, field: &str, what: &str) -> crate::Result<u8> {
scheme.field(field).map(|f| f.vno).ok_or_else(|| {
crate::ScoutError::Unsupported(format!("xunsearch: {what} field `{field}` not in field scheme (缺省方案下需先 update 该字段,或提供项目 ini)"))
})
}
const IO_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
const RESULT_DEADLINE: std::time::Duration = std::time::Duration::from_secs(20);
const MAX_HITS: usize = 100_000;
async fn with_timeout<T>(fut: impl std::future::Future<Output = std::io::Result<T>>) -> crate::Result<T> {
tokio::time::timeout(IO_TIMEOUT, fut).await
.map_err(|_| crate::ScoutError::XunSearch("xunsearch I/O timed out".to_string()))?
.map_err(crate::ScoutError::XunSearchIo)
}
const MAX_PACKET: usize = 16 * 1024 * 1024;
async fn read_packet(stream: &mut TcpStream) -> crate::Result<(u8, u16, Vec<u8>, Vec<u8>)> {
let mut header = [0u8; 8];
with_timeout(stream.read_exact(&mut header)).await?;
let blen1 = header[3] as usize;
let blen = u32::from_le_bytes(header[4..8].try_into().unwrap()) as usize;
if blen > MAX_PACKET {
return Err(crate::ScoutError::XunSearch(format!("xunsearch packet too large: {blen} bytes")));
}
let mut buf = vec![0u8; blen];
with_timeout(stream.read_exact(&mut buf)).await?;
let mut buf1 = vec![0u8; blen1];
with_timeout(stream.read_exact(&mut buf1)).await?;
Ok((header[0], (u16::from(header[1]) << 8) | u16::from(header[2]), buf, buf1))
}
fn server_err(code: u16, buf: &[u8]) -> crate::ScoutError {
crate::ScoutError::XunSearch(format!("server error {code}: {}", String::from_utf8_lossy(buf).trim()))
}
async fn expect_ok(stream: &mut TcpStream, ok_code: u16, what: &str) -> crate::Result<()> {
let (cmd, arg, buf, _) = read_packet(stream).await?;
match cmd {
CMD_ERR => Err(server_err(arg, &buf)),
CMD_OK if arg == ok_code => Ok(()),
CMD_OK => Err(crate::ScoutError::XunSearch(format!("{what}: unexpected OK code {arg}, want {ok_code}"))),
other => Err(crate::ScoutError::XunSearch(format!("{what}: unexpected cmd {other}"))),
}
}
impl Engine for XunSearchEngine {
fn update<'a>(&'a self, docs: &'a [SearchDocument]) -> EngineFuture<'a, ()> {
Box::pin(async move {
if docs.is_empty() {
return Ok(());
}
let mut groups: Vec<(&str, Vec<&SearchDocument>)> = Vec::new();
for doc in docs {
let index = doc.index.as_deref().unwrap_or("default");
match groups.iter_mut().find(|(k, _)| *k == index) {
Some((_, g)) => g.push(doc),
None => groups.push((index, vec![doc])),
}
}
for (index, _) in &groups {
crate::validate_index_name(index)?; }
let mut stream = self.open(false, None).await?;
for (index, group) in groups {
with_timeout(stream.write_all(&pack_cmd(CMD_INDEX_SET_DB, 0, 0, index.as_bytes(), &[]))).await?;
expect_ok(&mut stream, OK_DB_CHANGED, "CMD_INDEX_SET_DB").await?;
let mut buf = Vec::new();
{
let mut scheme = self.scheme.lock().expect("xunsearch scheme poisoned");
for doc in group {
buf.extend_from_slice(&doc_commands(&mut scheme, doc, true)?);
}
}
buf.extend_from_slice(&pack_cmd(CMD_INDEX_SUBMIT, 0, 0, &[], &[]));
with_timeout(stream.write_all(&buf)).await?;
expect_ok(&mut stream, OK_RQST_FINISHED, "CMD_INDEX_SUBMIT").await?;
}
Ok(())
})
}
fn update_bulk<'a>(&'a self, docs: &'a [SearchDocument]) -> EngineFuture<'a, ()> {
Box::pin(async move { self.update(docs).await })
}
fn delete<'a>(&'a self, ids: &'a [String]) -> EngineFuture<'a, ()> {
Box::pin(async move {
if ids.is_empty() {
return Ok(());
}
let mut stream = self.open(false, Some("default")).await?;
self.send_removes(&mut stream, ids).await
})
}
fn delete_bulk<'a>(&'a self, index: &'a str, ids: &'a [String]) -> EngineFuture<'a, ()> {
self.delete_in(index, ids)
}
fn delete_in<'a>(&'a self, index: &'a str, ids: &'a [String]) -> EngineFuture<'a, ()> {
Box::pin(async move {
crate::validate_index_name(index)?;
if ids.is_empty() {
return Ok(());
}
let mut stream = self.open(false, Some(index)).await?;
self.send_removes(&mut stream, ids).await
})
}
fn search<'a>(&'a self, builder: &'a SearchBuilder) -> EngineFuture<'a, SearchResult> {
Box::pin(async move { self.do_search(builder).await })
}
fn paginate<'a>(
&'a self,
builder: &'a SearchBuilder,
page: usize,
per_page: usize,
) -> EngineFuture<'a, SearchResult> {
let page = page.max(1);
let per_page = per_page.max(1);
Box::pin(async move {
let mut base = builder.clone();
base.skip = Some((page - 1).saturating_mul(per_page));
base.take = Some(per_page);
self.do_search(&base).await
})
}
fn flush<'a>(&'a self, index: &'a str) -> EngineFuture<'a, ()> {
Box::pin(async move {
let mut stream = self.open(false, Some(index)).await?;
with_timeout(stream.write_all(&pack_cmd(CMD_INDEX_COMMIT, 0, 0, &[], &[]))).await?;
match read_packet(&mut stream).await? {
(CMD_OK, OK_DB_COMMITED, _, _) => Ok(()),
(CMD_ERR, 504 | 406, _, _) => Ok(()),
(CMD_ERR, code, buf, _) => Err(server_err(code, &buf)),
(cmd, arg, _, _) => Err(crate::ScoutError::XunSearch(format!("CMD_INDEX_COMMIT: unexpected cmd={cmd} arg={arg}"))),
}
})
}
fn create_index<'a>(&'a self, index: &'a str, _settings: serde_json::Value) -> EngineFuture<'a, ()> {
Box::pin(async move {
crate::validate_index_name(index)?;
if self.has_ini {
Ok(())
} else {
Err(crate::ScoutError::Unsupported("xunsearch: create_index requires a field scheme ini passed to XunSearchEngine::new".to_string()))
}
})
}
fn delete_index<'a>(&'a self, index: &'a str) -> EngineFuture<'a, ()> {
Box::pin(async move {
let mut stream = self.open(false, Some(index)).await?;
with_timeout(stream.write_all(&pack_cmd(CMD_INDEX_CLEAN_DB, 0, 0, &[], &[]))).await?;
expect_ok(&mut stream, OK_DB_CLEAN, "CMD_INDEX_CLEAN_DB").await
})
}
}
#[cfg(test)]
#[path = "xunsearch_engine_tests.rs"]
mod tests;