use larust_core::AppError;
use serde::de::DeserializeOwned;
use serde::Serialize;
use tokio::sync::OnceCell;
static CLIENT: OnceCell<reqwest::Client> = OnceCell::const_new();
async fn client() -> &'static reqwest::Client {
CLIENT
.get_or_init(|| async { reqwest::Client::new() })
.await
}
fn base_url() -> String {
std::env::var("MEILISEARCH_URL").unwrap_or_else(|_| "http://127.0.0.1:7700".to_string())
}
fn auth_key() -> Option<String> {
std::env::var("MEILISEARCH_KEY").ok()
}
fn authorized(mut request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
if let Some(key) = auth_key() {
request = request.bearer_auth(key);
}
request
}
pub async fn index<T: Serialize>(index_name: &str, document: &T) -> Result<(), AppError> {
let url = format!("{}/indexes/{index_name}/documents", base_url());
let body = serde_json::json!([document]);
let response = authorized(client().await.post(&url).json(&body))
.send()
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
ensure_success(response, "indexing a document").await
}
pub async fn remove(index_name: &str, id: impl std::fmt::Display) -> Result<(), AppError> {
let url = format!("{}/indexes/{index_name}/documents/{id}", base_url());
let response = authorized(client().await.delete(&url))
.send()
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
ensure_success(response, "removing a document").await
}
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct SearchResults<T> {
pub hits: Vec<T>,
#[serde(rename = "estimatedTotalHits")]
pub estimated_total_hits: Option<u64>,
}
pub async fn search<T: DeserializeOwned>(
index_name: &str,
query: &str,
) -> Result<SearchResults<T>, AppError> {
let url = format!("{}/indexes/{index_name}/search", base_url());
let body = serde_json::json!({ "q": query });
let response = authorized(client().await.post(&url).json(&body))
.send()
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
if response.status() == reqwest::StatusCode::NOT_FOUND {
return Ok(SearchResults {
hits: Vec::new(),
estimated_total_hits: Some(0),
});
}
let response = ensure_status(response, "searching").await?;
response
.json()
.await
.map_err(|source| AppError::Internal(Box::new(source)))
}
async fn ensure_success(response: reqwest::Response, action: &str) -> Result<(), AppError> {
ensure_status(response, action).await.map(|_| ())
}
async fn ensure_status(
response: reqwest::Response,
action: &str,
) -> Result<reqwest::Response, AppError> {
if response.status().is_success() {
return Ok(response);
}
let status = response.status();
let body = response.text().await.unwrap_or_default();
Err(AppError::Internal(Box::new(std::io::Error::other(
format!("Meilisearch request failed while {action} ({status}): {body}"),
))))
}
#[cfg(test)]
mod tests {
use super::*;
use axum::extract::Path;
use axum::response::IntoResponse;
use axum::routing::{delete, post};
use axum::{Json, Router};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
#[derive(Debug, Clone, Default)]
struct Hits {
index: Arc<AtomicUsize>,
remove: Arc<AtomicUsize>,
search: Arc<AtomicUsize>,
}
async fn start_mock_meilisearch() -> (String, Hits) {
let hits = Hits::default();
let index_hits = hits.index.clone();
let search_hits = hits.search.clone();
let app = Router::new()
.route(
"/indexes/:index/documents",
post(move |Json(_body): Json<serde_json::Value>| {
let index_hits = index_hits.clone();
async move {
index_hits.fetch_add(1, Ordering::SeqCst);
Json(serde_json::json!({"taskUid": 1, "status": "enqueued"}))
}
}),
)
.route(
"/indexes/:index/documents/:id",
delete({
let remove_hits = hits.remove.clone();
move |Path((_index, _id)): Path<(String, String)>| {
let remove_hits = remove_hits.clone();
async move {
remove_hits.fetch_add(1, Ordering::SeqCst);
Json(serde_json::json!({"taskUid": 2, "status": "enqueued"}))
}
}
}),
)
.route(
"/indexes/:index/search",
post(
move |Path(index): Path<String>, Json(_body): Json<serde_json::Value>| {
let search_hits = search_hits.clone();
async move {
search_hits.fetch_add(1, Ordering::SeqCst);
if index == "empty-index" {
return axum::http::StatusCode::NOT_FOUND.into_response();
}
Json(serde_json::json!({
"hits": [{"id": 1, "title": "a matching post"}],
"estimatedTotalHits": 1,
}))
.into_response()
}
},
),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
(format!("http://{addr}"), hits)
}
#[derive(Debug, serde::Deserialize)]
struct Post {
#[allow(dead_code)]
id: i64,
title: String,
}
#[tokio::test]
async fn scout_crate_behaves_correctly_across_every_scenario() {
let (base_url, hits) = start_mock_meilisearch().await;
unsafe {
std::env::set_var("MEILISEARCH_URL", &base_url);
}
index("posts", &serde_json::json!({"id": 1, "title": "hello"}))
.await
.unwrap();
assert_eq!(hits.index.load(Ordering::SeqCst), 1);
remove("posts", 1).await.unwrap();
assert_eq!(hits.remove.load(Ordering::SeqCst), 1);
let results: SearchResults<Post> = search("posts", "hello").await.unwrap();
assert_eq!(hits.search.load(Ordering::SeqCst), 1);
assert_eq!(results.hits.len(), 1);
assert_eq!(results.hits[0].title, "a matching post");
assert_eq!(results.estimated_total_hits, Some(1));
let empty: SearchResults<Post> = search("empty-index", "anything").await.unwrap();
assert!(empty.hits.is_empty());
assert_eq!(empty.estimated_total_hits, Some(0));
}
}