#![cfg(feature = "meilisearch")]
use std::time::Duration;
use serde_json::{Map, Value};
use crate::config::percent_encode;
use crate::engine::{Engine, EngineFuture};
use crate::{SearchBuilder, SearchDocument, SearchResult};
pub(crate) enum PageMode {
Page(usize, usize),
Offset(usize, usize),
}
const TASK_POLL_INTERVAL: Duration = Duration::from_millis(100);
const TASK_POLL_TIMEOUT: Duration = Duration::from_secs(30);
pub struct MeilisearchEngine {
host: String,
api_key: Option<String>,
client: reqwest::Client,
}
impl MeilisearchEngine {
pub fn new(host: String, api_key: Option<String>) -> Self {
Self {
host: host.trim_end_matches('/').to_string(),
api_key,
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()),
}
}
async fn raw(
&self,
method: reqwest::Method,
path: &str,
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("Authorization", format!("Bearer {}", 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)?)
}
async fn await_task(&self, response: &Value) -> crate::Result<()> {
let Some(uid) = response.get("taskUid").and_then(Value::as_u64) else {
return Ok(()); };
let deadline = std::time::Instant::now() + TASK_POLL_TIMEOUT;
loop {
let task = self
.request(reqwest::Method::GET, &format!("/tasks/{uid}"), None)
.await?;
match task.get("status").and_then(Value::as_str) {
Some("succeeded") => return Ok(()),
Some(status @ ("failed" | "canceled")) => {
let error = task.get("error").map(Value::to_string).unwrap_or_default();
return Err(crate::ScoutError::Backend(format!(
"写入任务 {uid} {status}: {error}"
)));
}
_ => {}
}
if std::time::Instant::now() >= deadline {
return Err(crate::ScoutError::Backend(format!(
"写入任务 {uid} 在 {}s 内未结束,写入结果未知",
TASK_POLL_TIMEOUT.as_secs()
)));
}
tokio::time::sleep(TASK_POLL_INTERVAL).await;
}
}
}
impl Engine for MeilisearchEngine {
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 {
if ids.is_empty() {
return Ok(());
}
crate::validate_index_name(index)?;
let ids: Vec<Value> = ids.iter().map(|id| Value::String(id.clone())).collect();
let path = format!("/indexes/{}/documents/delete-batch", percent_encode(index));
let task = self
.request(reqwest::Method::POST, &path, Some(Value::Array(ids)))
.await?;
self.await_task(&task).await?;
Ok(())
})
}
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 mode = Self::page_mode(builder);
let want_none = builder.take == Some(0);
Box::pin(async move {
let body = Self::search_body(builder, &mode)?;
let path = format!("/indexes/{}/search", 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 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 mode = Self::page_mode_of(page, per_page);
Box::pin(async move {
let body = Self::search_body(builder, &mode)?;
let path = format!("/indexes/{}/search", 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 body = serde_json::json!({"uid": index, "primaryKey": "id"});
let path = "/indexes";
let (status, text) = self
.raw(
reqwest::Method::POST,
path,
Some(body.to_string()),
Some("application/json"),
)
.await?;
if status == reqwest::StatusCode::CONFLICT {
return Ok(()); }
if !status.is_success() {
return Err(crate::ScoutError::Backend(format!(
"{} {} -> {}: {}",
reqwest::Method::POST, path, status, text
)));
}
let mut filterable: Vec<&str> = vec!["id", "__soft_deleted"];
let mut sortable: Vec<&str> = Vec::new();
for (key, list) in [("filterableAttributes", &mut filterable), ("sortableAttributes", &mut sortable)] {
if let Some(values) = settings.get(key).and_then(Value::as_array) {
for v in values {
if let Some(s) = v.as_str() {
if !list.contains(&s) {
list.push(s);
}
}
}
}
}
let settings_body = serde_json::json!({
"filterableAttributes": filterable,
"sortableAttributes": sortable,
});
let _ = self
.request(
reqwest::Method::PATCH,
&format!("/indexes/{}/settings", percent_encode(index)),
Some(settings_body),
)
.await?;
Ok(())
})
}
fn delete_index<'a>(&'a self, index: &'a str) -> EngineFuture<'a, ()> {
Box::pin(async move {
crate::validate_index_name(index)?;
let path = format!("/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_document(doc));
}
for (index, docs) in groups {
crate::validate_index_name(index)?;
let path = format!("/indexes/{}/documents?primaryKey=id", percent_encode(index));
let task = self
.request(reqwest::Method::POST, &path, Some(Value::Array(docs)))
.await?;
self.await_task(&task).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
.iter()
.filter(|(k, _)| !k.starts_with('_')) .map(|(k, v)| (k.clone(), v.clone()))
.collect(),
_ => Map::new(),
};
fields.insert("__soft_deleted".into(), Value::Bool(true));
let doc = SearchDocument {
id: id.clone(),
index: Some(index.to_string()),
fields,
};
self.update(std::slice::from_ref(&doc)).await?;
}
Ok(())
})
}
}
#[cfg(test)]
#[path = "meilisearch_engine_tests.rs"]
mod tests;