#![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, id_filter, ndjson_payload, offset_limit, page_offset,
parse_search_response, search_params,
};
use crate::{SearchBuilder, SearchDocument, SearchResult};
const SOFT_DELETE_CHUNK: usize = 250;
fn client() -> reqwest::Client {
reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.connect_timeout(std::time::Duration::from_secs(10))
.redirect(crate::config::same_origin_redirect_policy())
.build()
.unwrap_or_else(|_| reqwest::Client::new())
}
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: client(),
}
}
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)> {
crate::validate_host(&self.host)?;
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, query: Option<&[(String, String)]>) -> crate::Result<()> {
let (status, text) = self.raw(reqwest::Method::DELETE, path, query, 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> {
let index = builder.index.as_deref().unwrap_or("default");
crate::validate_index_name(index)?;
if builder.where_ins.iter().any(|(_, v)| v.is_empty()) {
return Ok(SearchResult::default());
}
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)?;
if ids.is_empty() {
return Ok(());
}
let path = format!("/collections/{}/documents", percent_encode(index));
let query = vec![("filter_by".to_string(), id_filter(ids))];
self.delete_ok(&path, Some(&query)).await
})
}
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)), None).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 in groups.keys() {
crate::validate_index_name(index)?;
}
for (index, docs) in groups {
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)?;
let mut docs: Vec<SearchDocument> = Vec::new();
for chunk in ids.chunks(SOFT_DELETE_CHUNK) {
let builder = SearchBuilder::new("")
.within(index)
.take(SOFT_DELETE_CHUNK)
.where_in("id", chunk.iter().map(String::as_str).collect::<Vec<_>>());
let result = self.search(&builder).await?;
for hit in result.hits {
let mut fields: Map<String, Value> = match &hit.source {
Value::Object(map) => map.clone(),
_ => Map::new(),
};
fields.insert("__soft_deleted".into(), Value::Bool(true));
docs.push(SearchDocument {
id: hit.id,
index: None,
fields,
});
}
}
if docs.is_empty() {
return Ok(()); }
let refs: Vec<&SearchDocument> = docs.iter().collect();
self.import_docs(index, &refs).await
})
}
}
#[cfg(test)]
#[path = "typesense_engine_tests.rs"]
mod tests;