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 collect_hits(&self, index: &str, builder: &SearchBuilder) -> Vec<SearchHit> {
29        let guard = self.docs.lock().expect("collection engine poisoned");
30        guard
31            .get(index)
32            .map(|map| {
33                map.values()
34                    .filter(|doc| builder.matches(doc))
35                    .map(SearchHit::from)
36                    .collect()
37            })
38            .unwrap_or_default()
39    }
40
41    fn selected(&self, index: &str, builder: &SearchBuilder) -> (Vec<SearchHit>, usize) {
42        let mut hits = self.collect_hits(index, builder);
43        builder.sort_hits(&mut hits);
44        let total = hits.len();
45        let offset = builder.skip.unwrap_or(0);
46        let take = builder.take.unwrap_or(hits.len());
47        let hits = hits.into_iter().skip(offset).take(take).collect();
48        (hits, total)
49    }
50}
51
52impl Engine for CollectionEngine {
53    fn update<'a>(&'a self, docs: &'a [SearchDocument]) -> EngineFuture<'a, ()> {
54        Box::pin(async move {
55            let mut guard = self.docs.lock().expect("collection engine poisoned");
56            for doc in docs {
57                let index = doc.index.clone().unwrap_or_else(|| "default".to_string());
58                guard
59                    .entry(index)
60                    .or_default()
61                    .insert(doc.id.clone(), doc.clone());
62            }
63            Ok(())
64        })
65    }
66
67    fn delete<'a>(&'a self, ids: &'a [String]) -> EngineFuture<'a, ()> {
68        Box::pin(async move {
69            let mut guard = self.docs.lock().expect("collection engine poisoned");
70            for ids_set in guard.values_mut() {
71                for id in ids {
72                    ids_set.remove(id);
73                }
74            }
75            Ok(())
76        })
77    }
78
79    fn search<'a>(&'a self, builder: &'a SearchBuilder) -> EngineFuture<'a, SearchResult> {
80        Box::pin(async move {
81            let (hits, total) = self.selected(self.index_for(builder), builder);
82            Ok(SearchResult {
83                hits,
84                total,
85                ..SearchResult::default()
86            })
87        })
88    }
89
90    fn paginate<'a>(
91        &'a self,
92        builder: &'a SearchBuilder,
93        page: usize,
94        per_page: usize,
95    ) -> EngineFuture<'a, SearchResult> {
96        let page = page.max(1);
97        let per_page = per_page.max(1);
98        Box::pin(async move {
99            let mut base = builder.clone();
100            base.skip = Some((page - 1) * per_page);
101            base.take = Some(per_page);
102            let (hits, total) = self.selected(self.index_for(builder), &base);
103            Ok(SearchResult {
104                hits,
105                total,
106                ..SearchResult::default()
107            })
108        })
109    }
110
111    fn map_ids(&self, result: &SearchResult) -> Vec<String> {
112        result.ids()
113    }
114
115    fn flush<'a>(&'a self, _index: &'a str) -> EngineFuture<'a, ()> {
116        // no-op: mirrors ES _refresh; delete_index is the explicit removal path
117        Box::pin(async move { Ok(()) })
118    }
119
120    fn create_index<'a>(
121        &'a self,
122        index: &'a str,
123        _settings: serde_json::Value,
124    ) -> EngineFuture<'a, ()> {
125        Box::pin(async move {
126            self.docs
127                .lock()
128                .expect("collection engine poisoned")
129                .entry(index.to_string())
130                .or_default();
131            Ok(())
132        })
133    }
134
135    fn delete_index<'a>(&'a self, index: &'a str) -> EngineFuture<'a, ()> {
136        Box::pin(async move {
137            self.docs
138                .lock()
139                .expect("collection engine poisoned")
140                .remove(index);
141            Ok(())
142        })
143    }
144}
145
146impl From<&SearchDocument> for SearchHit {
147    fn from(doc: &SearchDocument) -> Self {
148        Self {
149            id: doc.id.clone(),
150            score: None,
151            source: serde_json::to_value(&doc.fields).unwrap_or_default(),
152            highlight: None,
153        }
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    fn doc(id: &str, index: Option<&str>) -> SearchDocument {
162        let mut d = SearchDocument::new(id, serde_json::json!({"title": id})).unwrap();
163        d.index = index.map(str::to_string);
164        d
165    }
166
167    #[tokio::test]
168    async fn update_respects_doc_index() {
169        let engine = CollectionEngine::new();
170        engine
171            .update(&[doc("one", Some("books")), doc("two", None)])
172            .await
173            .unwrap();
174        let result = engine
175            .search(&SearchBuilder::new("").within("books"))
176            .await
177            .unwrap();
178        let ids: Vec<&str> = result.hits.iter().map(|h| h.id.as_str()).collect();
179        assert_eq!(ids, ["one"]);
180    }
181
182    #[tokio::test]
183    async fn flush_keeps_data() {
184        let engine = CollectionEngine::new();
185        engine.update(&[doc("one", Some("books"))]).await.unwrap();
186        engine.flush("books").await.unwrap();
187        let result = engine
188            .search(&SearchBuilder::new("").within("books"))
189            .await
190            .unwrap();
191        assert_eq!(result.total, 1);
192    }
193}