Skip to main content

rust_scout/
collection_engine.rs

1use std::collections::HashMap;
2use std::sync::Mutex;
3
4use crate::engine::{Engine, EngineFuture};
5use crate::{SearchBuilder, SearchDocument, SearchHit, SearchResult};
6
7pub struct CollectionEngine {
8    docs: Mutex<HashMap<String, HashMap<String, SearchDocument>>>,
9}
10
11impl Default for CollectionEngine {
12    fn default() -> Self {
13        Self::new()
14    }
15}
16
17impl CollectionEngine {
18    pub fn new() -> Self {
19        Self {
20            docs: Mutex::new(HashMap::new()),
21        }
22    }
23
24    fn index_for<'a>(&self, builder: &'a SearchBuilder) -> &'a str {
25        builder.index.as_deref().unwrap_or("default")
26    }
27
28    fn selected(&self, index: &str, builder: &SearchBuilder) -> (Vec<SearchHit>, usize) {
29        // 软删除过滤在这里做;matches() 保持纯匹配语义。
30        //
31        // 先对文档**引用**排序、取完窗口再物化:命中上万条时,先给每条命中深拷贝
32        // 一份 fields 只为扔掉落选的那些是纯浪费。引用借自 guard,所以整段必须在
33        // 锁作用域内完成 —— 出不了这个函数的边界。
34        let guard = self.docs.lock().expect("collection engine poisoned");
35        let Some(map) = guard.get(index) else {
36            return (Vec::new(), 0);
37        };
38        let mut docs: Vec<&SearchDocument> = map
39            .values()
40            .filter(|doc| match builder.trashed {
41                crate::TrashedFilter::Exclude => !soft_deleted(doc),
42                crate::TrashedFilter::OnlyTrashed => soft_deleted(doc),
43                crate::TrashedFilter::WithTrashed => true,
44            })
45            .filter(|doc| builder.matches(doc))
46            .collect();
47        let cmp = |a: &&SearchDocument, b: &&SearchDocument| {
48            builder.sort_cmp((Some(&a.fields), a.id.as_str()), (Some(&b.fields), b.id.as_str()))
49        };
50        // total 是过滤后的总数,与窗口无关
51        let total = docs.len();
52        let offset = builder.skip.unwrap_or(0);
53        let take = builder.take.unwrap_or(total);
54        // 只要窗口内的前 offset+take 条:select_nth_unstable_by 分区一次就把窗口外
55        // 的元素甩到后面(无序),truncate 直接丢掉,省掉对整份命中集的排序 ——
56        // 排序正是 100k 条时 400ms 里的大头。
57        //
58        // sort_cmp 是**全序**(并列时用 id 兜底),所以「top-K 再排序」与
59        // 「全排序再截断」逐条相同,total 不受影响。
60        let k = offset.saturating_add(take).min(total);
61        if k < total {
62            docs.select_nth_unstable_by(k, cmp);
63            docs.truncate(k);
64        }
65        docs.sort_by(cmp);
66        let hits = docs
67            .into_iter()
68            .skip(offset)
69            .take(take)
70            .map(SearchHit::from)
71            .collect();
72        (hits, total)
73    }
74}
75
76fn soft_deleted(doc: &SearchDocument) -> bool {
77    doc.fields
78        .get("__soft_deleted")
79        .and_then(|v| v.as_bool())
80        .unwrap_or(false)
81}
82
83impl Engine for CollectionEngine {
84    fn update<'a>(&'a self, docs: &'a [SearchDocument]) -> EngineFuture<'a, ()> {
85        Box::pin(async move {
86            // 写入的索引名来自 doc.index(None ≡ "default"),与五个网络驱动
87            // 同契约:先整批校验再落库,避免「写进去几条才报错」的半截状态。
88            for doc in docs {
89                crate::validate_index_name(doc.index.as_deref().unwrap_or("default"))?;
90            }
91            let mut guard = self.docs.lock().expect("collection engine poisoned");
92            for doc in docs {
93                let index = doc.index.clone().unwrap_or_else(|| "default".to_string());
94                guard
95                    .entry(index)
96                    .or_default()
97                    .insert(doc.id.clone(), doc.clone());
98            }
99            Ok(())
100        })
101    }
102
103    fn delete<'a>(&'a self, ids: &'a [String]) -> EngineFuture<'a, ()> {
104        Box::pin(async move {
105            let mut guard = self.docs.lock().expect("collection engine poisoned");
106            for ids_set in guard.values_mut() {
107                for id in ids {
108                    ids_set.remove(id);
109                }
110            }
111            Ok(())
112        })
113    }
114
115    fn delete_in<'a>(&'a self, index: &'a str, ids: &'a [String]) -> EngineFuture<'a, ()> {
116        Box::pin(async move {
117            // 与其余驱动、与本文件的 soft_delete_in 同序:保留名照样拒绝,别让
118            // 「进程内驱动没有多索引展开风险」变成两套契约(delete_in("_all") 必须
119            // 在八个驱动上给同一个答案)。
120            crate::validate_index_name(index)?;
121            let mut guard = self.docs.lock().expect("collection engine poisoned");
122            if let Some(ids_set) = guard.get_mut(index) {
123                for id in ids {
124                    ids_set.remove(id);
125                }
126            }
127            Ok(())
128        })
129    }
130
131    fn soft_delete<'a>(&'a self, ids: &'a [String]) -> EngineFuture<'a, ()> {
132        Box::pin(async move {
133            // 与 delete() 一致的跨索引语义:标记所有索引中匹配 id 的文档。
134            let mut guard = self.docs.lock().expect("collection engine poisoned");
135            for ids_set in guard.values_mut() {
136                for id in ids {
137                    if let Some(doc) = ids_set.get_mut(id) {
138                        doc.set("__soft_deleted", true);
139                    }
140                }
141            }
142            Ok(())
143        })
144    }
145
146    fn soft_delete_in<'a>(&'a self, index: &'a str, ids: &'a [String]) -> EngineFuture<'a, ()> {
147        Box::pin(async move {
148            crate::validate_index_name(index)?;
149            let mut guard = self.docs.lock().expect("collection engine poisoned");
150            if let Some(ids_set) = guard.get_mut(index) {
151                for id in ids {
152                    if let Some(doc) = ids_set.get_mut(id) {
153                        doc.set("__soft_deleted", true);
154                    }
155                }
156            }
157            Ok(())
158        })
159    }
160
161    fn reindex<'a>(&'a self, from: &'a str, to: &'a str) -> EngineFuture<'a, ()> {
162        Box::pin(async move {
163            // 两端都要校验(与 ES/Algolia 的 reindex 同序):`_all` 在这里 Ok
164            // 而在网络上 Err 就是同一输入两个答案。
165            crate::validate_index_name(from)?;
166            crate::validate_index_name(to)?;
167            let mut guard = self.docs.lock().expect("collection engine poisoned");
168            // from 不存在时 to 得到空索引(与 create_index 语义一致)。
169            let source = guard.get(from).cloned().unwrap_or_default();
170            guard.insert(to.to_string(), source);
171            Ok(())
172        })
173    }
174
175    fn search<'a>(&'a self, builder: &'a SearchBuilder) -> EngineFuture<'a, SearchResult> {
176        Box::pin(async move {
177            // 校验是这个 future 里第一个可能失败的东西(与 ES `search_hits` 同序):
178            // 别让「保留名」在进程内驱动上返回 Ok(空结果) 而在网络上 Err。
179            crate::validate_index_name(self.index_for(builder))?;
180            let (hits, total) = self.selected(self.index_for(builder), builder);
181            Ok(SearchResult {
182                hits,
183                total,
184                ..SearchResult::default()
185            })
186        })
187    }
188
189    fn paginate<'a>(
190        &'a self,
191        builder: &'a SearchBuilder,
192        page: usize,
193        per_page: usize,
194    ) -> EngineFuture<'a, SearchResult> {
195        let page = page.max(1);
196        let per_page = per_page.max(1);
197        Box::pin(async move {
198            // paginate 与 search 走同一个 builder.index,必须同行为
199            crate::validate_index_name(self.index_for(builder))?;
200            let mut base = builder.clone();
201            base.skip = Some((page - 1).saturating_mul(per_page));
202            base.take = Some(per_page);
203            let (hits, total) = self.selected(self.index_for(builder), &base);
204            Ok(SearchResult {
205                hits,
206                total,
207                ..SearchResult::default()
208            })
209        })
210    }
211
212    fn create_index<'a>(
213        &'a self,
214        index: &'a str,
215        _settings: serde_json::Value,
216    ) -> EngineFuture<'a, ()> {
217        Box::pin(async move {
218            // 与 delete_index 同一道校验:ES 的 create_index 就拒保留名,
219            // 内存驱动不该在这里破例,否则 `_all` 在哪能建、哪不能建就说不清了。
220            crate::validate_index_name(index)?;
221            self.docs
222                .lock()
223                .expect("collection engine poisoned")
224                .entry(index.to_string())
225                .or_default();
226            Ok(())
227        })
228    }
229
230    fn delete_index<'a>(&'a self, index: &'a str) -> EngineFuture<'a, ()> {
231        Box::pin(async move {
232            // delete_in / soft_delete_in 既然拒保留名,同一职责的 delete_index 不能例外
233            // (DatabaseEngine::delete_index 也走同一道校验)。
234            crate::validate_index_name(index)?;
235            self.docs
236                .lock()
237                .expect("collection engine poisoned")
238                .remove(index);
239            Ok(())
240        })
241    }
242}
243
244impl From<&SearchDocument> for SearchHit {
245    fn from(doc: &SearchDocument) -> Self {
246        Self {
247            id: doc.id.clone(),
248            score: None,
249            source: serde_json::to_value(&doc.fields).unwrap_or_default(),
250            highlight: None,
251        }
252    }
253}
254
255#[cfg(test)]
256#[path = "collection_engine_tests.rs"]
257mod tests;