use std::time::Duration;
use crate::config::{percent_encode, same_origin_redirect_policy};
use crate::engine::{Engine, EngineFuture};
use crate::query::{
build_body, check_bulk_delete_items, check_bulk_items, is_query_parse_error,
parse_search_response,
};
use crate::{SearchBuilder, SearchDocument, SearchResult};
pub struct ElasticsearchEngine {
host: String,
api_key: Option<String>,
client: reqwest::Client,
}
impl ElasticsearchEngine {
pub fn new(host: String, api_key: Option<String>) -> Self {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(30))
.connect_timeout(Duration::from_secs(10))
.redirect(same_origin_redirect_policy())
.build()
.unwrap_or_else(|_| reqwest::Client::new());
Self {
host: host.trim_end_matches('/').to_string(),
api_key,
client,
}
}
async fn raw_request(
&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, format!("{}{}", self.host, path));
if let Some(api_key) = &self.api_key {
request = request.header("Authorization", format!("ApiKey {}", 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<serde_json::Value>,
) -> crate::Result<serde_json::Value> {
let content_type = body.as_ref().map(|_| "application/json");
let (status, body) = self
.raw_request(
method.clone(),
path,
body.map(|b| b.to_string()),
content_type,
)
.await?;
if !status.is_success() {
return Err(crate::ScoutError::Backend(format!(
"{} {} -> {}: {}",
method, path, status, body
)));
}
Ok(serde_json::from_str(&body)?)
}
}
impl ElasticsearchEngine {
async fn search_hits(
&self,
builder: &SearchBuilder,
from: usize,
size: usize,
) -> crate::Result<SearchResult> {
let index = builder.index.as_deref().unwrap_or("default");
crate::validate_index_name(index)?;
let path = format!("/{}/_search", percent_encode(index));
let body = build_body(builder, from, size)?;
let (status, body) = self
.raw_request(
reqwest::Method::POST,
&path,
Some(body.to_string()),
Some("application/json"),
)
.await?;
if status == reqwest::StatusCode::BAD_REQUEST && is_query_parse_error(&body) {
return Ok(SearchResult::default());
}
if !status.is_success() {
return Err(crate::ScoutError::Backend(format!(
"{} {} -> {}: {}",
reqwest::Method::POST, path, status, body
)));
}
let parsed: serde_json::Value = serde_json::from_str(&body)?;
if parsed.get("timed_out").and_then(|v| v.as_bool()) == Some(true) {
return Err(crate::ScoutError::Backend(format!(
"POST {} -> 200: search timed out: {}",
path, body
)));
}
let failed_shards = parsed
.pointer("/_shards/failed")
.and_then(|v| v.as_u64())
.unwrap_or(0);
if failed_shards > 0 {
return Err(crate::ScoutError::Backend(format!(
"POST {} -> 200: {} shard(s) failed: {}",
path, failed_shards, body
)));
}
Ok(parse_search_response(&parsed))
}
}
const BULK_CHUNK_BYTES: usize = 5 * 1024 * 1024;
fn bulk_chunks(lines: Vec<String>) -> Vec<String> {
let mut chunks: Vec<String> = Vec::new();
let mut current = String::new();
for line in lines {
if !current.is_empty() && current.len() + line.len() > BULK_CHUNK_BYTES {
chunks.push(std::mem::take(&mut current));
}
current.push_str(&line);
}
if !current.is_empty() {
chunks.push(current);
}
chunks
}
impl ElasticsearchEngine {
async fn send_bulk(
&self,
index: &str,
lines: Vec<String>,
tolerate_missing_index: bool,
check: fn(&serde_json::Value) -> crate::Result<()>,
) -> crate::Result<()> {
let path = format!("/{}/_bulk", percent_encode(index));
for chunk in bulk_chunks(lines) {
let (status, body) = self
.raw_request(
reqwest::Method::POST,
&path,
Some(chunk),
Some("application/x-ndjson"),
)
.await?;
if tolerate_missing_index && status == reqwest::StatusCode::NOT_FOUND {
continue;
}
if !status.is_success() {
return Err(crate::ScoutError::Backend(format!(
"{} {} -> {}: {}",
reqwest::Method::POST, path, status, body
)));
}
check(&serde_json::from_str(&body)?)?;
}
Ok(())
}
}
impl Engine for ElasticsearchEngine {
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, ()> {
self.delete_bulk(index, ids)
}
fn search<'a>(&'a self, builder: &'a SearchBuilder) -> EngineFuture<'a, SearchResult> {
Box::pin(async move {
let from = builder.skip.unwrap_or(0);
let size = builder.take.unwrap_or(10);
self.search_hits(builder, from, size).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.search_hits(&base, base.skip.unwrap_or(0), base.take.unwrap_or(10))
.await
})
}
fn flush<'a>(&'a self, index: &'a str) -> EngineFuture<'a, ()> {
Box::pin(async move {
crate::validate_index_name(index)?;
let path = format!("/{}/_refresh", percent_encode(index));
let _ = self.request(reqwest::Method::POST, &path, None).await?;
Ok(())
})
}
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 path = format!("/{}", percent_encode(index));
let _ = self
.request(reqwest::Method::PUT, &path, Some(settings))
.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!("/{}", percent_encode(index));
let _ = self.request(reqwest::Method::DELETE, &path, None).await?;
Ok(())
})
}
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 {
let index = doc.index.as_deref().unwrap_or("default");
groups.entry(index).or_default().push(doc);
}
for index in groups.keys() {
crate::validate_index_name(index)?;
}
for (index, docs) in groups {
let mut lines = Vec::with_capacity(docs.len() * 2);
for doc in docs {
lines.push(format!(
"{{\"index\":{{\"_id\":{}}}}}\n",
serde_json::to_string(&doc.id)?
));
lines.push(format!("{}\n", serde_json::to_string(&doc.fields)?));
}
self.send_bulk(index, lines, false, check_bulk_items)
.await?;
}
Ok(())
})
}
fn delete_bulk<'a>(&'a self, index: &'a str, ids: &'a [String]) -> EngineFuture<'a, ()> {
Box::pin(async move {
crate::validate_index_name(index)?;
let mut lines = Vec::with_capacity(ids.len());
for id in ids {
lines.push(format!(
"{{\"delete\":{{\"_id\":{}}}}}\n",
serde_json::to_string(id)?
));
}
self.send_bulk(index, lines, true, check_bulk_delete_items)
.await
})
}
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 lines = Vec::with_capacity(ids.len() * 2);
for id in ids {
lines.push(format!(
"{{\"update\":{{\"_id\":{}}}}}\n",
serde_json::to_string(id)?
));
lines.push("{\"doc\":{\"__soft_deleted\":true}}\n".to_string());
}
self.send_bulk(index, lines, false, check_bulk_delete_items)
.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 body = serde_json::json!({
"source": {"index": from},
"dest": {"index": to}
});
let _ = self
.request(reqwest::Method::POST, "/_reindex", Some(body))
.await?;
Ok(())
})
}
}
#[cfg(test)]
#[path = "elasticsearch_engine_tests.rs"]
mod tests;