#![cfg(feature = "algolia")]
use std::time::Duration;
use serde_json::{Map, Value};
use crate::config::percent_encode;
use crate::engine::{Engine, EngineFuture};
use crate::{SearchBuilder, SearchDocument, SearchHit, SearchResult, TrashedFilter};
const TASK_POLL_INTERVAL: Duration = Duration::from_millis(200);
const TASK_POLL_TIMEOUT: Duration = Duration::from_secs(30);
fn client() -> reqwest::Client {
reqwest::Client::builder()
.timeout(Duration::from_secs(30))
.connect_timeout(Duration::from_secs(10))
.redirect(crate::config::same_origin_redirect_policy())
.build()
.unwrap_or_else(|_| reqwest::Client::new())
}
pub struct AlgoliaEngine {
host: Option<String>,
app_id: String,
api_key: String,
client: reqwest::Client,
}
impl AlgoliaEngine {
pub fn new(app_id: String, api_key: String) -> Self {
let host = Self::valid_app_id(&app_id).then(|| format!("https://{app_id}.algolia.net"));
Self {
host,
app_id,
api_key,
client: client(),
}
}
fn valid_app_id(app_id: &str) -> bool {
!app_id.is_empty() && app_id.bytes().all(|b| b.is_ascii_alphanumeric())
}
fn base_url(&self) -> crate::Result<&str> {
self.host.as_deref().ok_or_else(|| {
crate::ScoutError::Unsupported(format!(
"algolia: invalid app_id `{}`: 只允许非空 ASCII 字母数字",
self.app_id
))
})
}
async fn raw(
&self,
method: reqwest::Method,
path: &str,
body: Option<String>,
content_type: Option<&str>,
) -> crate::Result<(reqwest::StatusCode, String)> {
let base = self.base_url()?;
crate::validate_host(base)?;
let mut request = self.client.request(method.clone(), format!("{}{}", base, path));
request = request.header("X-Algolia-Application-Id", &self.app_id);
request = request.header("X-Algolia-API-Key", &self.api_key);
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 request(
&self,
method: reqwest::Method,
path: &str,
body: Option<Value>,
) -> crate::Result<Value> {
let (status, body) = self
.raw(
method.clone(),
path,
body.map(|b| b.to_string()),
Some("application/json"),
)
.await?;
if !status.is_success() {
return Err(crate::ScoutError::Backend(format!(
"{} {} -> {}: {}",
method, path, status, body
)));
}
Ok(serde_json::from_str(&body)?)
}
fn filter_value(v: &Value) -> String {
match v {
Value::String(s) => format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")),
Value::Bool(b) => b.to_string(),
Value::Number(n) => n.to_string(),
other => other.to_string(),
}
}
fn build_filters(builder: &SearchBuilder) -> crate::Result<Option<String>> {
let mut parts: Vec<String> = Vec::new();
for w in &builder.wheres {
crate::validate_field_name(&w.field)?;
parts.push(format!("{}={}", w.field, Self::filter_value(&w.value)));
}
for (field, values) in &builder.where_ins {
if values.is_empty() {
continue; }
crate::validate_field_name(field)?;
let ors = values.iter().map(Self::filter_value).collect::<Vec<_>>().join(" OR ");
parts.push(format!("({}: {})", field, ors));
}
for (field, values) in &builder.where_not_ins {
if values.is_empty() {
continue; }
crate::validate_field_name(field)?;
let ors = values.iter().map(Self::filter_value).collect::<Vec<_>>().join(" OR ");
parts.push(format!("NOT ({}: {})", field, ors));
}
match builder.trashed {
TrashedFilter::Exclude => parts.push("NOT __soft_deleted:true".to_string()),
TrashedFilter::OnlyTrashed => parts.push("__soft_deleted:true".to_string()),
TrashedFilter::WithTrashed => {}
}
if parts.is_empty() {
Ok(None)
} else {
Ok(Some(parts.join(",")))
}
}
fn page_offset(page: usize, per_page: usize) -> usize {
page.max(1).saturating_sub(1).saturating_mul(per_page)
}
fn search_body(builder: &SearchBuilder, offset: usize, limit: usize) -> crate::Result<Value> {
let mut body = Map::new();
body.insert("query".into(), Value::String(builder.query.clone()));
body.insert("offset".into(), Value::from(offset));
body.insert("length".into(), Value::from(limit));
if let Some(filters) = Self::build_filters(builder)? {
body.insert("filters".into(), Value::String(filters));
}
Ok(Value::Object(body))
}
fn doc_to_record(doc: &SearchDocument) -> Value {
let mut fields = doc.fields.clone();
fields.insert("objectID".into(), Value::String(doc.id.clone()));
Value::Object(fields)
}
fn parse_search_response(raw: &Value) -> SearchResult {
let hits = raw.get("hits").and_then(Value::as_array);
let total = raw
.get("nbHits")
.and_then(Value::as_u64)
.map(|n| n as usize)
.unwrap_or_else(|| hits.map_or(0, Vec::len));
let hits = hits
.map(|arr| arr.iter().filter_map(Self::hit_from_response).collect())
.unwrap_or_default();
SearchResult {
hits,
total,
..Default::default()
}
}
fn hit_from_response(hit: &Value) -> Option<SearchHit> {
let object_id = hit.get("objectID")?;
let id = object_id
.as_str()
.map(str::to_string)
.unwrap_or_else(|| object_id.to_string());
Some(SearchHit {
id,
score: None,
source: hit.clone(),
highlight: None,
})
}
}
impl AlgoliaEngine {
fn reindex_body(to: &str) -> Value {
serde_json::json!({"operation": "copy", "destination": to})
}
async fn await_task(&self, index: &str, response: &Value) -> crate::Result<()> {
let Some(task_id) = response.get("taskID").and_then(Value::as_u64) else {
return Ok(());
};
let path = format!("/1/indexes/{}/task/{}", percent_encode(index), task_id);
let deadline = std::time::Instant::now() + TASK_POLL_TIMEOUT;
loop {
let task = self.request(reqwest::Method::GET, &path, None).await?;
if task.get("status").and_then(Value::as_str) == Some("published") {
return Ok(());
}
if std::time::Instant::now() >= deadline {
return Err(crate::ScoutError::Backend(format!(
"写入任务 {task_id} 在 {}s 内未 published,写入结果未知",
TASK_POLL_TIMEOUT.as_secs()
)));
}
tokio::time::sleep(TASK_POLL_INTERVAL).await;
}
}
async fn batch(&self, index: &str, requests: Vec<Value>) -> crate::Result<()> {
if requests.is_empty() {
return Ok(());
}
crate::validate_index_name(index)?;
let path = format!("/1/indexes/{}/batch", percent_encode(index));
let body = serde_json::json!({"requests": requests});
let task = self.request(reqwest::Method::POST, &path, Some(body)).await?;
self.await_task(index, &task).await
}
}
impl Engine for AlgoliaEngine {
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 {
let requests: Vec<Value> = ids
.iter()
.map(|id| {
serde_json::json!({"action": "deleteObject", "body": {"objectID": id}})
})
.collect();
self.batch(index, requests).await
})
}
fn search<'a>(&'a self, builder: &'a SearchBuilder) -> EngineFuture<'a, SearchResult> {
let index = builder.index.as_deref().unwrap_or("default");
if let Err(e) = crate::validate_index_name(index) {
return Box::pin(async move { Err(e) });
}
if builder.where_ins.iter().any(|(_, v)| v.is_empty()) {
return Box::pin(async move { Ok(SearchResult::default()) });
}
let offset = builder.skip.unwrap_or(0);
let limit = builder.take.unwrap_or(10);
let want_none = builder.take == Some(0);
Box::pin(async move {
let body = Self::search_body(builder, offset, limit.max(1))?;
let path = format!("/1/indexes/{}/query", percent_encode(index));
let raw = self.request(reqwest::Method::POST, &path, Some(body)).await?;
let result = Self::parse_search_response(&raw);
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 per_page = per_page.max(1);
let offset = Self::page_offset(page, per_page); if builder.where_ins.iter().any(|(_, v)| v.is_empty()) {
return Box::pin(async move { Ok(SearchResult::default()) });
}
Box::pin(async move {
let index = builder.index.as_deref().unwrap_or("default");
crate::validate_index_name(index)?;
let body = Self::search_body(builder, offset, per_page)?;
let path = format!("/1/indexes/{}/query", percent_encode(index));
let raw = self.request(reqwest::Method::POST, &path, Some(body)).await?;
Ok(Self::parse_search_response(&raw))
})
}
fn create_index<'a>(
&'a self,
index: &'a str,
_settings: serde_json::Value,
) -> EngineFuture<'a, ()> {
Box::pin(async move {
crate::validate_index_name(index)?;
let settings_path = format!("/1/indexes/{}/settings", percent_encode(index));
let (status, text) = self
.raw(
reqwest::Method::PUT,
&settings_path,
Some("{}".to_string()),
Some("application/json"),
)
.await?;
if status == reqwest::StatusCode::NOT_FOUND {
let create_path = format!("/1/indexes/{}", percent_encode(index));
let (status, text) =
self.raw(reqwest::Method::PUT, &create_path, None, None).await?;
if !status.is_success() {
return Err(crate::ScoutError::Backend(format!(
"{} {} -> {}: {}",
reqwest::Method::PUT, create_path, status, text
)));
}
let (status, text) = self
.raw(
reqwest::Method::PUT,
&settings_path,
Some("{}".to_string()),
Some("application/json"),
)
.await?;
if !status.is_success() {
return Err(crate::ScoutError::Backend(format!(
"{} {} -> {}: {}",
reqwest::Method::PUT, settings_path, status, text
)));
}
} else if !status.is_success() {
return Err(crate::ScoutError::Backend(format!(
"{} {} -> {}: {}",
reqwest::Method::PUT, settings_path, status, text
)));
}
Ok(())
})
}
fn delete_index<'a>(&'a self, index: &'a str) -> EngineFuture<'a, ()> {
Box::pin(async move {
crate::validate_index_name(index)?;
let path = format!("/1/indexes/{}", percent_encode(index));
let (status, text) = self.raw(reqwest::Method::DELETE, &path, None, None).await?;
if status == reqwest::StatusCode::NOT_FOUND {
return Ok(()); }
if !status.is_success() {
return Err(crate::ScoutError::Backend(format!(
"{} {} -> {}: {}",
reqwest::Method::DELETE, path, status, text
)));
}
Ok(())
})
}
fn update_bulk<'a>(&'a self, docs: &'a [SearchDocument]) -> EngineFuture<'a, ()> {
Box::pin(async move {
let mut groups: std::collections::HashMap<&str, Vec<Value>> = Default::default();
for doc in docs {
groups
.entry(doc.index.as_deref().unwrap_or("default"))
.or_default()
.push(Self::doc_to_record(doc));
}
for (index, records) in groups {
let requests: Vec<Value> = records
.into_iter()
.map(|body| serde_json::json!({"action": "addObject", "body": body}))
.collect();
self.batch(index, requests).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 requests: Vec<Value> = ids
.iter()
.map(|id| {
serde_json::json!({
"action": "partialUpdateObjectNoCreate",
"body": {"objectID": id, "__soft_deleted": true}
})
})
.collect();
self.batch(index, requests).await
})
}
fn reindex<'a>(&'a self, from: &'a str, to: &'a str) -> EngineFuture<'a, ()> {
Box::pin(async move {
crate::validate_index_name(from)?;
crate::validate_index_name(to)?;
let path = format!("/1/indexes/{}/operation", percent_encode(from));
let task = self.request(reqwest::Method::POST, &path, Some(Self::reindex_body(to))).await?;
self.await_task(to, &task).await
})
}
}
#[cfg(test)]
#[path = "algolia_engine_tests.rs"]
mod tests;