rust-scout 0.5.0

Scout-style full-text search engine abstraction for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
#![cfg(feature = "algolia")]

use serde_json::{Map, Value};

use crate::config::percent_encode;
use crate::engine::{Engine, EngineFuture};
use crate::{SearchBuilder, SearchDocument, SearchHit, SearchResult, TrashedFilter};

/// Algolia 引擎(标准端点 `https://{app_id}.algolia.net`)。文档主键为
/// `objectID` 保留键,软删除标记 `__soft_deleted` 布尔字段。
pub struct AlgoliaEngine {
    host: String,
    app_id: String,
    api_key: String,
    client: reqwest::Client,
}

impl AlgoliaEngine {
    pub fn new(app_id: String, api_key: String) -> Self {
        Self {
            host: format!("https://{}.algolia.net", app_id),
            app_id,
            api_key,
            client: reqwest::Client::new(),
        }
    }

    /// 发送请求,返回状态码 + body 文本;网络错误经 `?` 转 `ScoutError::Http`。
    async fn raw(
        &self,
        method: reqwest::Method,
        path: &str,
        body: Option<String>,
        content_type: Option<&str>,
    ) -> crate::Result<(reqwest::StatusCode, String)> {
        let mut request = self
            .client
            .request(method.clone(), format!("{}{}", self.host, 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))
    }

    /// JSON 请求;非 2xx 返回 `ScoutError::Backend("METHOD path -> 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)?)
    }

    /// filter 值:字符串加引号(转义 `\` 与 `"`),数字/bool 裸值。
    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(),
        }
    }

    /// 等值/IN/软删除 → Algolia filters 表达式;多条件用逗号(AND 语义)。
    /// 注意与 PHP 版的差异:IN 用括号 `(field: v1 OR v2)`,NOT IN 加 NOT 前缀,
    /// 避免 OR 吞掉逗号连接的其它条件。
    fn build_filters(builder: &SearchBuilder) -> Option<String> {
        let mut parts: Vec<String> = Vec::new();
        for w in &builder.wheres {
            parts.push(format!("{}={}", w.field, Self::filter_value(&w.value)));
        }
        for (field, values) in &builder.where_ins {
            if values.is_empty() {
                continue; // 空 IN 集合 = 不匹配任何,由 search/paginate 短路
            }
            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; // 空 NOT IN 集合 = 无过滤(Collection 语义)
            }
            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() {
            None
        } else {
            Some(parts.join(","))
        }
    }

    fn search_body(builder: &SearchBuilder, page: usize, per_page: usize) -> Value {
        let mut body = Map::new();
        body.insert("query".into(), Value::String(builder.query.clone()));
        body.insert("page".into(), Value::from(page)); // Algolia page 是 0 基
        body.insert("hitsPerPage".into(), Value::from(per_page));
        if let Some(filters) = Self::build_filters(builder) {
            body.insert("filters".into(), Value::String(filters));
        }
        // order_by 不生效:Algolia 排序需预建 replica index 并在查询时用
        // `replicas` 参数——Rust 侧未做,避免静默假装支持(注释留档)。
        Value::Object(body)
    }

    /// 文档 → Algolia record;`objectID` 保留键统一注入/覆盖为 doc.id。
    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)
    }

    /// 响应解析:id 取 `hits[i].objectID`,source 取整个 hit(含 _highlightResult
    /// 等 Algolia 元数据),total 取 `nbHits`。
    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 {
    /// batch 端点;requests 为空则跳过。
    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 _ = self.request(reqwest::Method::POST, &path, Some(body)).await?;
        Ok(())
    }
}

impl Engine for AlgoliaEngine {
    fn update<'a>(&'a self, docs: &'a [SearchDocument]) -> EngineFuture<'a, ()> {
        // 与 update_bulk 相同:batch addObject。
        self.update_bulk(docs)
    }

    fn delete<'a>(&'a self, ids: &'a [String]) -> EngineFuture<'a, ()> {
        // 无索引信息:仅作用于 default 索引(同 ElasticsearchEngine 语义)。
        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 per_page = builder.take.unwrap_or(10).max(1);
        let page = builder.skip.unwrap_or(0) / per_page;
        // 空 where_in 集合 = 不匹配任何(Collection 语义):短路空结果。
        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, page, 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 paginate<'a>(
        &'a self,
        builder: &'a SearchBuilder,
        page: usize,
        per_page: usize,
    ) -> EngineFuture<'a, SearchResult> {
        let page = page.max(1) - 1; // Algolia page 是 0 基
        let per_page = per_page.max(1);
        // 空 where_in 集合 = 不匹配任何(Collection 语义):短路空结果。
        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, page, 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))
        })
    }


    /// 刷新可见性。**不是**清空索引 —— Algolia 的写操作是同步的,没有 ES
    /// `_refresh` 的等价物,所以与 `CollectionEngine` 一致地做 no-op。
    ///
    /// 曾经这里打的是 `POST /1/indexes/{i}/clear`:README 的生命周期示例
    /// (update → flush → search)在这个驱动上会把整个索引删空并返回 `Ok(())`。
    fn flush<'a>(&'a self, index: &'a str) -> EngineFuture<'a, ()> {
        Box::pin(async move {
            crate::validate_index_name(index)?;
            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 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 {
                // Algolia 索引首次写入时自动创建:先 PUT 空索引再重设 settings。
                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, ()> {
        // 与 delete_in 相同:batch deleteObject。
        self.delete_in(index, ids)
    }

    /// 仅作用于 `index`。`partialUpdateObject` 单请求原子部分更新,无需先读原文档。
    ///
    /// 不带索引的 [`Engine::soft_delete`] 在本驱动上不可用(见 `engine.rs` 说明):
    /// 原先它硬编码 `default`,而且 `partialUpdateObject` 默认
    /// `createIfNotExists=true`——对写在其它索引里的文档,它会在 `default` 里
    /// **凭空造一条** `{objectID, __soft_deleted:true}` 幽灵记录。
    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!({
                        // NoCreate:目标不存在时不要凭空建记录。用
                        // partialUpdateObject 会在索引里留下幽灵行。
                        "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 body = serde_json::json!({
                "operation": "copy",
                "destination": {"index": to}
            });
            let path = format!("/1/indexes/{}/operation", percent_encode(from));
            let _ = self.request(reqwest::Method::POST, &path, Some(body)).await?;
            Ok(())
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::SearchBuilder;

    #[test]
    fn filters_join_with_comma_and_or_groups() {
        let builder = SearchBuilder::new("")
            .where_field("active", true)
            .where_field("price", 10)
            .where_in("tag", ["a", "b"])
            .where_not_in("tag", ["x"]);
        let filters = AlgoliaEngine::build_filters(&builder).unwrap();
        assert_eq!(
            filters,
            r#"active=true,price=10,(tag: "a" OR "b"),NOT (tag: "x"),NOT __soft_deleted:true"#
        );
    }

    #[test]
    fn filters_trashed_variants() {
        assert_eq!(
            AlgoliaEngine::build_filters(&SearchBuilder::new("")).unwrap(),
            "NOT __soft_deleted:true"
        );
        assert_eq!(
            AlgoliaEngine::build_filters(&SearchBuilder::new("").only_trashed()).unwrap(),
            "__soft_deleted:true"
        );
        assert_eq!(
            AlgoliaEngine::build_filters(&SearchBuilder::new("").with_trashed()),
            None
        );
    }

    #[test]
    fn doc_uses_object_id_key() {
        let doc =
            SearchDocument::new("a", serde_json::json!({"objectID": "wrong", "title": "x"}))
                .unwrap();
        let record = AlgoliaEngine::doc_to_record(&doc);
        assert_eq!(record["objectID"], "a"); // 覆盖保留键
        assert_eq!(record["title"], "x");
    }

    #[test]
    fn search_body_zero_based_page_and_filters() {
        let builder = SearchBuilder::new("q").where_field("cat", 1);
        let body = AlgoliaEngine::search_body(&builder, 2, 10);
        assert_eq!(body["query"], "q");
        assert_eq!(body["page"], 2); // 第 3 页 → page=2
        assert_eq!(body["hitsPerPage"], 10);
        assert_eq!(body["filters"], "cat=1,NOT __soft_deleted:true");
    }

    #[test]
    fn parse_response_uses_object_id_and_nb_hits() {
        let raw = serde_json::json!({
            "hits": [{
                "objectID": "1",
                "title": "a",
                "_highlightResult": {"title": {"value": "<em>a</em>"}}
            }],
            "nbHits": 7
        });
        let result = AlgoliaEngine::parse_search_response(&raw);
        assert_eq!(result.total, 7);
        assert_eq!(result.hits[0].id, "1");
        assert_eq!(result.hits[0].score, None);
        // Algolia 元数据原样保留在 source 中
        assert_eq!(
            result.hits[0].source["_highlightResult"]["title"]["value"],
            "<em>a</em>"
        );
    }

    #[test]
    fn parse_response_nb_hits_missing_falls_back() {
        let raw = serde_json::json!({"hits": [{"objectID": "1"}]});
        assert_eq!(AlgoliaEngine::parse_search_response(&raw).total, 1);
    }

    #[tokio::test]
    async fn flush_is_a_noop_and_makes_no_request() {
        // 指向必然连不上的 app_id:真的打网络就会失败,返回 Ok 即证明没有请求。
        // flush 的契约是「刷新可见性」,绝不能是清空索引——README 的生命周期示例
        // 在 update 与 search 之间调用它,而这里曾打 /clear 把索引清空。
        let engine = AlgoliaEngine::new("testappid".to_string(), "k".to_string());
        engine.flush("books").await.unwrap();
    }

    #[tokio::test]
    async fn index_less_soft_delete_is_refused_not_silently_skipped() {
        // 曾经它硬编码 default,且 partialUpdateObject 默认 createIfNotExists=true,
        // 会在 default 里凭空造一条幽灵记录。
        let engine = AlgoliaEngine::new("testappid".to_string(), "k".to_string());
        let err = engine
            .soft_delete(&["b1".to_string()])
            .await
            .expect_err("index-less soft_delete 必须报错,而不是静默 no-op");
        assert!(matches!(err, crate::ScoutError::Unsupported(_)), "got {err:?}");
    }
}