#![cfg(feature = "typesense")]
use serde_json::{Map, Value};
use crate::config::percent_encode;
use crate::engine::{Engine, EngineFuture};
use crate::typesense_query::{
check_import, check_status, ndjson_payload, offset_limit, page_offset, parse_search_response,
search_params,
};
use crate::{SearchBuilder, SearchDocument, SearchResult};
pub struct TypesenseEngine {
host: String,
api_key: Option<String>,
client: reqwest::Client,
}
impl TypesenseEngine {
pub fn new(host: String, api_key: Option<String>) -> Self {
Self {
host: host.trim_end_matches('/').to_string(),
api_key,
client: reqwest::Client::new(),
}
}
async fn raw(
&self,
method: reqwest::Method,
path: &str,
query: Option<&[(String, String)]>,
body: Option<String>,
content_type: Option<&str>,
) -> crate::Result<(reqwest::StatusCode, String)> {
let mut request = self.client.request(method.clone(), format!("{}{}", self.host, path));
if let Some(api_key) = &self.api_key {
request = request.header("X-TYPESENSE-API-KEY", api_key);
}
if let Some(query) = query {
request = request.query(query);
}
if let Some(body) = body {
request = request.body(body);
if let Some(content_type) = content_type {
request = request.header(reqwest::header::CONTENT_TYPE, content_type);
}
}
let response = request.send().await?;
let status = response.status();
let body = response.text().await.unwrap_or_default();
Ok((status, body))
}
async fn delete_ok(&self, path: &str) -> crate::Result<()> {
let (status, text) = self.raw(reqwest::Method::DELETE, path, None, None, None).await?;
if status == reqwest::StatusCode::NOT_FOUND {
return Ok(());
}
check_status("DELETE", path, &status, &text)
}
async fn create_collection(&self, index: &str) -> crate::Result<()> {
let path = format!("/collections/{}", percent_encode(index));
let body = serde_json::json!({
"name": index,
"fields": [
{"name": "id", "type": "string"},
{"name": "__soft_deleted", "type": "bool", "optional": true}
]
});
let (status, text) = self
.raw(reqwest::Method::PUT, &path, None, Some(body.to_string()), Some("application/json"))
.await?;
if status == reqwest::StatusCode::CONFLICT {
return Ok(()); }
check_status("PUT", &path, &status, &text)
}
async fn import_docs(&self, index: &str, docs: &[&SearchDocument]) -> crate::Result<()> {
let payload = ndjson_payload(docs)?;
let path = format!("/collections/{}/documents/import?action=upsert", percent_encode(index));
let (status, text) = self
.raw(reqwest::Method::POST, &path, None, Some(payload.clone()), Some("application/x-ndjson"))
.await?;
if status == reqwest::StatusCode::NOT_FOUND {
self.create_collection(index).await?;
let (status, text) = self
.raw(reqwest::Method::POST, &path, None, Some(payload), Some("application/x-ndjson"))
.await?;
return check_import(&status, &path, &text);
}
check_import(&status, &path, &text)
}
async fn search_page(&self, builder: &SearchBuilder, offset: usize, limit: usize) -> crate::Result<SearchResult> {
if builder.where_ins.iter().any(|(_, v)| v.is_empty()) {
return Ok(SearchResult::default());
}
let index = builder.index.as_deref().unwrap_or("default");
crate::validate_index_name(index)?;
let params = search_params(builder, offset, limit);
let path = format!("/collections/{}/documents/search", percent_encode(index));
let (status, text) = self.raw(reqwest::Method::GET, &path, Some(¶ms), None, None).await?;
check_status("GET", &path, &status, &text)?;
Ok(parse_search_response(&serde_json::from_str::<Value>(&text)?))
}
}
impl Engine for TypesenseEngine {
fn update<'a>(&'a self, docs: &'a [SearchDocument]) -> EngineFuture<'a, ()> {
self.update_bulk(docs)
}
fn delete<'a>(&'a self, ids: &'a [String]) -> EngineFuture<'a, ()> {
self.delete_in("default", ids)
}
fn delete_in<'a>(&'a self, index: &'a str, ids: &'a [String]) -> EngineFuture<'a, ()> {
Box::pin(async move {
crate::validate_index_name(index)?;
for id in ids {
self.delete_ok(&format!(
"/collections/{}/documents/{}",
percent_encode(index),
percent_encode(id)
))
.await?;
}
Ok(())
})
}
fn search<'a>(&'a self, builder: &'a SearchBuilder) -> EngineFuture<'a, SearchResult> {
let (offset, limit) = offset_limit(builder);
let want_none = builder.take == Some(0);
Box::pin(async move {
let result = self.search_page(builder, offset, limit.max(1)).await?;
Ok(if want_none { result.without_hits() } else { result })
})
}
fn paginate<'a>(
&'a self,
builder: &'a SearchBuilder,
page: usize,
per_page: usize,
) -> EngineFuture<'a, SearchResult> {
let (offset, per_page) = page_offset(page, per_page);
Box::pin(async move { self.search_page(builder, offset, per_page).await })
}
fn create_index<'a>(
&'a self,
index: &'a str,
_settings: serde_json::Value,
) -> EngineFuture<'a, ()> {
Box::pin(async move {
crate::validate_index_name(index)?;
self.create_collection(index).await
})
}
fn delete_index<'a>(&'a self, index: &'a str) -> EngineFuture<'a, ()> {
Box::pin(async move {
crate::validate_index_name(index)?;
self.delete_ok(&format!("/collections/{}", percent_encode(index))).await
})
}
fn update_bulk<'a>(&'a self, docs: &'a [SearchDocument]) -> EngineFuture<'a, ()> {
Box::pin(async move {
let mut groups: std::collections::HashMap<&str, Vec<&SearchDocument>> = Default::default();
for doc in docs {
groups.entry(doc.index.as_deref().unwrap_or("default")).or_default().push(doc);
}
for (index, docs) in groups {
crate::validate_index_name(index)?;
self.import_docs(index, &docs).await?;
}
Ok(())
})
}
fn delete_bulk<'a>(&'a self, index: &'a str, ids: &'a [String]) -> EngineFuture<'a, ()> {
self.delete_in(index, ids)
}
fn soft_delete_in<'a>(&'a self, index: &'a str, ids: &'a [String]) -> EngineFuture<'a, ()> {
Box::pin(async move {
crate::validate_index_name(index)?;
for id in ids {
let builder = SearchBuilder::new("").within(index).where_field("id", id.clone());
let result = self.search(&builder).await?;
let Some(hit) = result.hits.first() else {
continue;
};
let mut fields: Map<String, Value> = match &hit.source {
Value::Object(map) => map.clone(),
_ => Map::new(),
};
fields.insert("__soft_deleted".into(), Value::Bool(true));
let doc = SearchDocument {
id: id.clone(),
index: None,
fields,
};
self.import_docs(index, &[&doc]).await?;
}
Ok(())
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn flush_is_a_noop_and_makes_no_request() {
let engine = TypesenseEngine::new("http://127.0.0.1:1".to_string(), None);
engine.flush("books").await.unwrap();
}
#[tokio::test]
async fn index_less_soft_delete_is_refused_not_silently_skipped() {
let engine = TypesenseEngine::new("http://127.0.0.1:1".to_string(), None);
let err = engine
.soft_delete(&["b1".to_string()])
.await
.expect_err("index-less soft_delete 必须报错,而不是静默 no-op");
assert!(matches!(err, crate::ScoutError::Unsupported(_)), "got {err:?}");
}
#[tokio::test]
async fn take_zero_keeps_total_and_drops_hits() {
let r = SearchResult {
hits: vec![],
total: 7,
..SearchResult::default()
};
let trimmed = r.without_hits();
assert!(trimmed.hits.is_empty());
assert_eq!(trimmed.total, 7);
}
#[tokio::test]
async fn empty_where_in_short_circuits_search_and_paginate() {
let engine = TypesenseEngine::new("http://127.0.0.1:1".to_string(), None);
let builder = SearchBuilder::new("")
.within("books")
.where_in("tag", Vec::<&str>::new());
let result = engine.search(&builder).await.unwrap();
assert!(result.hits.is_empty());
assert_eq!(result.total, 0);
let paged = engine.paginate(&builder, 2, 10).await.unwrap();
assert!(paged.hits.is_empty());
assert_eq!(paged.total, 0);
}
}