larust_scout/lib.rs
1//! Laravel's `laravel/scout` - full-text search, narrowed to its
2//! Meilisearch driver: self-hostable (no required paid service, matching
3//! this framework's own posture elsewhere - `larust-reverb`'s own
4//! WebSocket server, `larust-db`'s embedded `redb`), with a REST API
5//! stable and simple enough to call directly over [`reqwest`] rather than
6//! needing a dedicated SDK dependency.
7//!
8//! **No `Searchable` trait / automatic model-lifecycle indexing.** Real
9//! Scout re-indexes a model automatically on save/delete via an Eloquent
10//! model observer - this framework has already rejected that shape of
11//! magic once, deliberately: `rust-laravel.md`'s own "What should remain
12//! deliberately different" section singles out "Magic lazy-loaded
13//! relationships by default" as something to reject, and silent
14//! lifecycle-hook re-indexing is the same instinct applied to writes
15//! instead of reads - a save that also does an unrelated network call the
16//! caller never asked for, with no visible line of code at the call site
17//! explaining why. [`index`]/[`remove`] are explicit calls instead, the
18//! same shape `larust_queue::dispatch`/`larust_events::dispatch` already
19//! use for "something happens as a deliberate, visible side effect of
20//! this write", not an invisible one.
21//!
22//! **Single-driver (Meilisearch only), not Scout's own pluggable driver
23//! split** (Algolia, a `database`/`collection` driver for local dev and
24//! testing). A real `database`-style LIKE-query fallback is a genuinely
25//! different, larger feature - this crate has one job, talking to a real
26//! Meilisearch instance, and does it without an abstraction layer only
27//! one implementation would ever sit behind.
28//!
29//! Re-exported through `larust_support::scout` (see `crates/
30//! larust-support/src/lib.rs`) so generated apps depend only on
31//! `larust-support`, never on this crate directly.
32//!
33//! ## Deliberately out of scope for this version
34//!
35//! - **No index configuration** (searchable/filterable/sortable attribute
36//! settings, typo tolerance, synonyms - Meilisearch's own `PATCH
37//! /indexes/{uid}/settings`). [`index`] relies entirely on Meilisearch's
38//! own sensible defaults (every field searchable); an app with real
39//! tuning needs calls `reqwest` against the settings endpoint directly
40//! for now.
41//! - **No filters, sorting, facets, or pagination parameters** on
42//! [`search`] - plain `q`-only full-text search. A real, separate
43//! follow-up once a caller actually needs them, not spec'd speculatively
44//! here.
45//! - **No task-completion polling.** Meilisearch indexes/deletes
46//! asynchronously - [`index`]/[`remove`] return once Meilisearch has
47//! *accepted* the write (its own task-enqueued response), not once
48//! indexing has actually finished. This matches Scout's own real-world
49//! behavior (also eventually consistent, especially when its own queue
50//! driver is active) - not a shortcut unique to this crate.
51
52use larust_core::AppError;
53use serde::de::DeserializeOwned;
54use serde::Serialize;
55use tokio::sync::OnceCell;
56
57/// Set once per process, the first time any Scout function runs - same
58/// lazy-singleton shape `larust-cache`'s own `redis_store::connection`
59/// already establishes for its `ConnectionManager`. `reqwest::Client`
60/// holds its own internal connection pool and is designed to be cloned
61/// freely (an `Arc`-backed handle), so every caller gets a cheap clone
62/// rather than contending on one shared handle.
63static CLIENT: OnceCell<reqwest::Client> = OnceCell::const_new();
64
65async fn client() -> &'static reqwest::Client {
66 CLIENT
67 .get_or_init(|| async { reqwest::Client::new() })
68 .await
69}
70
71/// `MEILISEARCH_URL` (default `http://127.0.0.1:7700`) and
72/// `MEILISEARCH_KEY` (optional - a local dev instance commonly runs with
73/// no master key at all; omitted from the request entirely rather than
74/// sent as an empty bearer token when unset). Same "a single plain env
75/// var, not a typed config block" reasoning `larust-cache`'s own
76/// `redis_store::connection` doc comment already gives for `REDIS_URL` -
77/// nothing here needs a driver/dialect choice the way SQL connections do.
78fn base_url() -> String {
79 std::env::var("MEILISEARCH_URL").unwrap_or_else(|_| "http://127.0.0.1:7700".to_string())
80}
81
82fn auth_key() -> Option<String> {
83 std::env::var("MEILISEARCH_KEY").ok()
84}
85
86fn authorized(mut request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
87 if let Some(key) = auth_key() {
88 request = request.bearer_auth(key);
89 }
90 request
91}
92
93/// Indexes `document` into `index_name` - Laravel's `$model->searchable()`.
94/// `document` must serialize to a JSON object carrying an `"id"` field
95/// (Meilisearch's own default primary-key convention, and the same `id`
96/// every `#[derive(Model)]` struct already has) - this crate adds no
97/// separate id parameter or primary-key configuration on top of that.
98/// Meilisearch creates `index_name` automatically on this first write if
99/// it doesn't already exist; no separate "create the index" call is
100/// needed.
101pub async fn index<T: Serialize>(index_name: &str, document: &T) -> Result<(), AppError> {
102 let url = format!("{}/indexes/{index_name}/documents", base_url());
103 // A single document still goes through Meilisearch's own bulk-add
104 // endpoint, which only ever accepts a JSON array - wrapped here so
105 // callers never need to know that.
106 let body = serde_json::json!([document]);
107 let response = authorized(client().await.post(&url).json(&body))
108 .send()
109 .await
110 .map_err(|source| AppError::Internal(Box::new(source)))?;
111 ensure_success(response, "indexing a document").await
112}
113
114/// Removes the document with id `id` from `index_name` - Laravel's
115/// `$model->unsearchable()`. Not an error to remove an id that was never
116/// indexed or has already been removed - Meilisearch itself treats that
117/// as a normal, successful no-op (it still enqueues a delete task; there
118/// is nothing to roll back).
119pub async fn remove(index_name: &str, id: impl std::fmt::Display) -> Result<(), AppError> {
120 let url = format!("{}/indexes/{index_name}/documents/{id}", base_url());
121 let response = authorized(client().await.delete(&url))
122 .send()
123 .await
124 .map_err(|source| AppError::Internal(Box::new(source)))?;
125 ensure_success(response, "removing a document").await
126}
127
128/// One page of search results - Meilisearch's own default (offset-based,
129/// not the alternate page-number mode its own API also supports, see this
130/// module's own "deliberately out of scope" note on pagination
131/// parameters). `estimated_total_hits` is `None` only for the "index
132/// doesn't exist yet" fallback [`search`] itself applies - a real
133/// Meilisearch response always includes it.
134#[derive(Debug, Clone, Default, serde::Deserialize)]
135pub struct SearchResults<T> {
136 pub hits: Vec<T>,
137 #[serde(rename = "estimatedTotalHits")]
138 pub estimated_total_hits: Option<u64>,
139}
140
141/// Searches `index_name` for `query` - Laravel's `Model::search($query)
142/// ->get()`. An index that has never had a document written to it (see
143/// [`index`]'s own doc comment - Meilisearch never auto-creates one for a
144/// search, only for a write) returns Meilisearch's own `index_not_found`
145/// error; treated here as an ordinary empty result set, not a caller-
146/// visible error, the same "nothing indexed yet looks like zero results,
147/// not a failure" tolerance an empty SQL table already gets everywhere
148/// else in this codebase.
149pub async fn search<T: DeserializeOwned>(
150 index_name: &str,
151 query: &str,
152) -> Result<SearchResults<T>, AppError> {
153 let url = format!("{}/indexes/{index_name}/search", base_url());
154 let body = serde_json::json!({ "q": query });
155 let response = authorized(client().await.post(&url).json(&body))
156 .send()
157 .await
158 .map_err(|source| AppError::Internal(Box::new(source)))?;
159
160 if response.status() == reqwest::StatusCode::NOT_FOUND {
161 return Ok(SearchResults {
162 hits: Vec::new(),
163 estimated_total_hits: Some(0),
164 });
165 }
166 let response = ensure_status(response, "searching").await?;
167 response
168 .json()
169 .await
170 .map_err(|source| AppError::Internal(Box::new(source)))
171}
172
173/// Shared status-check behind [`index`]/[`remove`] - both only care
174/// whether the request succeeded, never the response body itself
175/// (Meilisearch's own enqueued-task object).
176async fn ensure_success(response: reqwest::Response, action: &str) -> Result<(), AppError> {
177 ensure_status(response, action).await.map(|_| ())
178}
179
180/// Turns a non-2xx Meilisearch response into a real `AppError`, with the
181/// response body included (Meilisearch's own JSON error responses always
182/// carry a human-readable `message` field) rather than just the bare
183/// status code - the same "surface the real failure, don't make the
184/// caller go dig through logs" instinct this codebase's other external-
185/// service-calling crates already follow.
186async fn ensure_status(
187 response: reqwest::Response,
188 action: &str,
189) -> Result<reqwest::Response, AppError> {
190 if response.status().is_success() {
191 return Ok(response);
192 }
193 let status = response.status();
194 let body = response.text().await.unwrap_or_default();
195 Err(AppError::Internal(Box::new(std::io::Error::other(
196 format!("Meilisearch request failed while {action} ({status}): {body}"),
197 ))))
198}
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203 use axum::extract::Path;
204 use axum::response::IntoResponse;
205 use axum::routing::{delete, post};
206 use axum::{Json, Router};
207 use std::sync::atomic::{AtomicUsize, Ordering};
208 use std::sync::Arc;
209
210 #[derive(Debug, Clone, Default)]
211 struct Hits {
212 index: Arc<AtomicUsize>,
213 remove: Arc<AtomicUsize>,
214 search: Arc<AtomicUsize>,
215 }
216
217 /// A real local HTTP server standing in for Meilisearch - same
218 /// "no mocking crate, a tiny real `axum` server on an ephemeral port"
219 /// pattern `larust-socialite`'s own test suite already establishes
220 /// for the identical problem (no real external service available in
221 /// this environment to test against).
222 async fn start_mock_meilisearch() -> (String, Hits) {
223 let hits = Hits::default();
224
225 let index_hits = hits.index.clone();
226 let search_hits = hits.search.clone();
227 let app = Router::new()
228 .route(
229 "/indexes/:index/documents",
230 post(move |Json(_body): Json<serde_json::Value>| {
231 let index_hits = index_hits.clone();
232 async move {
233 index_hits.fetch_add(1, Ordering::SeqCst);
234 Json(serde_json::json!({"taskUid": 1, "status": "enqueued"}))
235 }
236 }),
237 )
238 .route(
239 "/indexes/:index/documents/:id",
240 delete({
241 let remove_hits = hits.remove.clone();
242 move |Path((_index, _id)): Path<(String, String)>| {
243 let remove_hits = remove_hits.clone();
244 async move {
245 remove_hits.fetch_add(1, Ordering::SeqCst);
246 Json(serde_json::json!({"taskUid": 2, "status": "enqueued"}))
247 }
248 }
249 }),
250 )
251 .route(
252 "/indexes/:index/search",
253 post(
254 move |Path(index): Path<String>, Json(_body): Json<serde_json::Value>| {
255 let search_hits = search_hits.clone();
256 async move {
257 search_hits.fetch_add(1, Ordering::SeqCst);
258 if index == "empty-index" {
259 return axum::http::StatusCode::NOT_FOUND.into_response();
260 }
261 Json(serde_json::json!({
262 "hits": [{"id": 1, "title": "a matching post"}],
263 "estimatedTotalHits": 1,
264 }))
265 .into_response()
266 }
267 },
268 ),
269 );
270
271 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
272 let addr = listener.local_addr().unwrap();
273 tokio::spawn(async move {
274 axum::serve(listener, app).await.unwrap();
275 });
276 (format!("http://{addr}"), hits)
277 }
278
279 #[derive(Debug, serde::Deserialize)]
280 struct Post {
281 #[allow(dead_code)]
282 id: i64,
283 title: String,
284 }
285
286 /// All scenarios share one test function, not several - `MEILISEARCH_URL`
287 /// is read via `std::env::var` on every call (not memoized), but the
288 /// mock server itself is still process-wide state worth standing up
289 /// only once, same "one shared fixture, one test" shape this
290 /// codebase's own process-wide-singleton test suites already use
291 /// elsewhere (`larust-sanctum`/`larust-permissions`/
292 /// `larust-notifications`).
293 #[tokio::test]
294 async fn scout_crate_behaves_correctly_across_every_scenario() {
295 let (base_url, hits) = start_mock_meilisearch().await;
296 // SAFETY: this test is the only thing in this process that ever
297 // sets `MEILISEARCH_URL` - no other test in this crate reads or
298 // writes it concurrently.
299 unsafe {
300 std::env::set_var("MEILISEARCH_URL", &base_url);
301 }
302
303 index("posts", &serde_json::json!({"id": 1, "title": "hello"}))
304 .await
305 .unwrap();
306 assert_eq!(hits.index.load(Ordering::SeqCst), 1);
307
308 remove("posts", 1).await.unwrap();
309 assert_eq!(hits.remove.load(Ordering::SeqCst), 1);
310
311 let results: SearchResults<Post> = search("posts", "hello").await.unwrap();
312 assert_eq!(hits.search.load(Ordering::SeqCst), 1);
313 assert_eq!(results.hits.len(), 1);
314 assert_eq!(results.hits[0].title, "a matching post");
315 assert_eq!(results.estimated_total_hits, Some(1));
316
317 // An index that doesn't exist yet reads as zero results, not an
318 // error - see `search`'s own doc comment for why.
319 let empty: SearchResults<Post> = search("empty-index", "anything").await.unwrap();
320 assert!(empty.hits.is_empty());
321 assert_eq!(empty.estimated_total_hits, Some(0));
322 }
323}