1use std::collections::HashSet;
4use std::sync::LazyLock;
5
6use async_trait::async_trait;
7use futures::future::join_all;
8use regex::Regex;
9
10use super::{SearchStrategy, StorageSearchResult};
11use crate::error::Result;
12use crate::storage::Storage;
13
14const READ_BATCH_SIZE: usize = 8;
16
17static NON_WORD: LazyLock<Option<Regex>> = LazyLock::new(|| Regex::new(r"[^\p{L}\p{N}_]+").ok());
18
19pub(crate) static STOP_WORDS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
21 [
22 "a", "an", "the", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "do", "does", "did",
23 "will", "would", "could", "should", "may", "might", "shall", "can", "need", "dare", "ought", "used", "to",
24 "of", "in", "for", "on", "with", "at", "by", "from", "as", "into", "through", "during", "before", "after",
25 "above", "below", "between", "out", "off", "over", "under", "again", "further", "then", "once", "and", "but",
26 "or", "nor", "not", "so", "yet", "both", "either", "neither", "each", "every", "all", "any", "few", "more",
27 "most", "other", "some", "such", "no", "only", "own", "same", "than", "too", "very", "just", "because",
28 "about", "up", "its", "it", "he", "she", "they", "we", "you", "i", "me", "him", "her", "us", "them", "my",
29 "your", "his", "our", "their", "this", "that", "these", "those", "what", "which", "who", "whom", "when",
30 "where", "why", "how", "if", "while", "although", "though", "unless", "until", "since",
31 ]
32 .into_iter()
33 .collect()
34});
35
36pub(crate) fn tokenize(text: &str) -> HashSet<String> {
39 let lower = text.to_lowercase();
40 match NON_WORD.as_ref() {
41 Some(non_word) => non_word
42 .split(&lower)
43 .filter(|token| !token.is_empty())
44 .map(str::to_owned)
45 .collect(),
46 None => lower
47 .split(|c: char| !(c.is_alphanumeric() || c == '_'))
48 .filter(|token| !token.is_empty())
49 .map(str::to_owned)
50 .collect(),
51 }
52}
53
54pub(crate) fn token_overlap_score(query_tokens: &HashSet<String>, content: &str) -> usize {
56 tokenize(content)
57 .iter()
58 .filter(|token| query_tokens.contains(*token))
59 .count()
60}
61
62fn strip_extension(key: &str) -> &str {
65 let Some(dot) = key.rfind('.') else {
66 return key;
67 };
68 let follows_segment_char = key[..dot].chars().next_back().is_some_and(|c| c != '/');
69 if key[dot..].contains('/') || !follows_segment_char {
70 return key;
71 }
72 &key[..dot]
73}
74
75#[derive(Debug, Clone, Copy, Default)]
98#[non_exhaustive]
99pub struct KeywordSearchStrategy;
100
101impl KeywordSearchStrategy {
102 #[must_use]
104 pub fn new() -> Self {
105 Self
106 }
107}
108
109#[async_trait]
110impl SearchStrategy for KeywordSearchStrategy {
111 async fn search(&self, storage: &dyn Storage, query: &str) -> Result<Vec<StorageSearchResult>> {
112 let query_tokens: HashSet<String> = tokenize(query)
113 .into_iter()
114 .filter(|token| !STOP_WORDS.contains(token.as_str()))
115 .collect();
116 if query_tokens.is_empty() {
117 return Ok(Vec::new());
118 }
119
120 let keys = storage.list("").await?;
121 let mut scored = Vec::new();
122 for batch in keys.chunks(READ_BATCH_SIZE) {
123 let reads = join_all(batch.iter().map(|key| read_or_skip(storage, key))).await;
124 for (key, bytes) in batch.iter().zip(reads) {
125 let Some(bytes) = bytes else {
126 continue;
127 };
128 let text = format!("{} {}", strip_extension(key), String::from_utf8_lossy(&bytes));
129 let score = token_overlap_score(&query_tokens, &text);
130 if score > 0 {
131 scored.push(StorageSearchResult::new(key.clone(), score as f64).with_data(bytes));
132 }
133 }
134 }
135 scored.sort_by(|a, b| b.score.total_cmp(&a.score));
136 Ok(scored)
137 }
138}
139
140async fn read_or_skip(storage: &dyn Storage, key: &str) -> Option<Vec<u8>> {
142 match storage.read(key).await {
143 Ok(bytes) => bytes,
144 Err(error) => {
145 tracing::debug!("key=<{key}>, error=<{error}> | skipped unreadable entry");
146 None
147 }
148 }
149}
150
151#[cfg(test)]
152mod tests {
153 use std::sync::Arc;
154 use std::sync::atomic::{AtomicUsize, Ordering};
155
156 use super::*;
157 use crate::error::StorageError;
158 use crate::storage::InMemoryStorage;
159
160 async fn storage_with(entries: &[(&str, &str)]) -> InMemoryStorage {
161 let storage = InMemoryStorage::new();
162 for (key, content) in entries {
163 storage.write(key, content.as_bytes()).await.unwrap();
164 }
165 storage
166 }
167
168 async fn keys(storage: &dyn Storage, query: &str) -> Vec<String> {
169 let results = KeywordSearchStrategy.search(storage, query).await.unwrap();
170 results.into_iter().map(|result| result.key).collect()
171 }
172
173 #[tokio::test]
174 async fn returns_matching_entries_scored_by_token_overlap() {
175 let storage = storage_with(&[
176 ("notes/dark-mode.md", "enable dark mode in settings"),
177 ("notes/deploy.md", "deploy to production"),
178 ])
179 .await;
180 let results = KeywordSearchStrategy::new()
181 .search(&storage, "dark mode")
182 .await
183 .unwrap();
184 assert_eq!(results.len(), 1);
185 assert_eq!(results[0].key, "notes/dark-mode.md");
186 assert!(results[0].score > 0.0);
187 }
188
189 #[tokio::test]
190 async fn returns_the_stored_bytes_with_each_result() {
191 let storage = storage_with(&[("notes/dark-mode.md", "enable dark mode in settings")]).await;
192 let results = KeywordSearchStrategy::new()
193 .search(&storage, "dark mode")
194 .await
195 .unwrap();
196 assert_eq!(
197 results,
198 [StorageSearchResult::new("notes/dark-mode.md", 2.0).with_data(b"enable dark mode in settings".to_vec())]
199 );
200 }
201
202 #[tokio::test]
203 async fn skips_entries_whose_read_throws() {
204 let storage = Instrumented::new(storage_with(&[("good.md", "dark mode"), ("locked.md", "dark mode")]).await);
205 assert_eq!(keys(&storage, "dark mode").await, ["good.md"]);
206 }
207
208 #[tokio::test]
209 async fn returns_empty_array_for_empty_query() {
210 let storage = storage_with(&[("key", "content")]).await;
211 assert!(keys(&storage, "").await.is_empty());
212 }
213
214 #[tokio::test]
215 async fn returns_empty_array_for_whitespace_only_query() {
216 let storage = storage_with(&[("key", "content")]).await;
217 assert!(keys(&storage, " ").await.is_empty());
218 }
219
220 #[tokio::test]
221 async fn matches_case_insensitively() {
222 let storage = storage_with(&[("note.md", "Dark Mode Toggle")]).await;
223 assert_eq!(keys(&storage, "dark mode").await.len(), 1);
224 }
225
226 #[tokio::test]
227 async fn includes_the_key_in_the_scoring_text() {
228 let storage = storage_with(&[("dark-mode.md", "some unrelated body")]).await;
229 assert_eq!(keys(&storage, "dark mode").await, ["dark-mode.md"]);
230 }
231
232 #[tokio::test]
233 async fn ranks_results_by_score_descending() {
234 let storage = storage_with(&[("a.md", "dark"), ("b.md", "dark mode toggle feature")]).await;
235 let results = KeywordSearchStrategy::new()
236 .search(&storage, "dark mode")
237 .await
238 .unwrap();
239 assert_eq!(results.len(), 2);
240 assert!(results[0].score >= results[1].score);
241 assert_eq!(results[0].key, "b.md");
242 }
243
244 #[tokio::test]
245 async fn returns_empty_array_when_no_content_matches() {
246 let storage = storage_with(&[("note.md", "completely unrelated content")]).await;
247 assert!(keys(&storage, "kubernetes deployment").await.is_empty());
248 }
249
250 #[tokio::test]
251 async fn ignores_stop_words_in_the_query() {
252 let storage = storage_with(&[
253 ("deploy.md", "the deploy process runs nightly"),
254 ("weather.md", "what is the weather like"),
255 ])
256 .await;
257 assert_eq!(keys(&storage, "what is the deploy process").await, ["deploy.md"]);
258 }
259
260 #[tokio::test]
261 async fn returns_empty_array_for_a_query_made_only_of_stop_words() {
262 let storage = storage_with(&[("note.md", "what is the plan")]).await;
263 assert!(keys(&storage, "what is the").await.is_empty());
264 }
265
266 #[tokio::test]
267 async fn does_not_score_the_file_extension_of_the_key() {
268 let storage = storage_with(&[("release-notes.md", "ship on fridays")]).await;
269 assert!(keys(&storage, "update AGENTS.md").await.is_empty());
270 assert_eq!(keys(&storage, "release").await, ["release-notes.md"]);
271 }
272
273 #[tokio::test]
274 async fn reads_entries_in_concurrent_batches_of_at_most_8() {
275 let inner = InMemoryStorage::new();
276 for index in 0..20 {
277 inner.write(&format!("note-{index}.md"), b"dark mode").await.unwrap();
278 }
279 let storage = Instrumented::new(inner);
280 let results = KeywordSearchStrategy::new()
281 .search(&storage, "dark mode")
282 .await
283 .unwrap();
284 assert_eq!(results.len(), 20);
285 assert_eq!(storage.max_in_flight.load(Ordering::SeqCst), 8);
286 }
287
288 #[test]
289 fn tokenizes_unicode_letters_numbers_and_underscores() {
290 let tokens = tokenize("Hello, world_1! café ΣΑΣ x²");
291 let mut tokens: Vec<_> = tokens.into_iter().collect();
292 tokens.sort();
293 assert_eq!(tokens, ["café", "hello", "world_1", "x²", "σας"]);
294 }
295
296 #[test]
297 fn strips_only_a_final_extension_that_follows_a_segment_character() {
298 assert_eq!(strip_extension("notes/a.md"), "notes/a");
299 assert_eq!(strip_extension("a.b.c"), "a.b");
300 assert_eq!(strip_extension("a."), "a");
301 assert_eq!(strip_extension(".env"), ".env");
302 assert_eq!(strip_extension("notes/.hidden"), "notes/.hidden");
303 assert_eq!(strip_extension("dir.x/file"), "dir.x/file");
304 assert_eq!(strip_extension("plain"), "plain");
305 }
306
307 #[test]
308 fn scores_distinct_overlapping_tokens() {
309 let query = tokenize("dark mode");
310 assert_eq!(token_overlap_score(&query, "dark dark mode light"), 2);
311 assert_eq!(token_overlap_score(&query, "light"), 0);
312 }
313
314 struct Instrumented {
316 inner: InMemoryStorage,
317 in_flight: Arc<AtomicUsize>,
318 max_in_flight: Arc<AtomicUsize>,
319 }
320
321 impl Instrumented {
322 fn new(inner: InMemoryStorage) -> Self {
323 Self {
324 inner,
325 in_flight: Arc::default(),
326 max_in_flight: Arc::default(),
327 }
328 }
329 }
330
331 #[async_trait]
332 impl Storage for Instrumented {
333 async fn write(&self, key: &str, data: &[u8]) -> Result<()> {
334 Storage::write(&self.inner, key, data).await
335 }
336
337 async fn read(&self, key: &str) -> Result<Option<Vec<u8>>> {
338 if key == "locked.md" {
339 return Err(StorageError::new("Failed to read 'locked.md' from local storage").into());
340 }
341 let now = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1;
342 self.max_in_flight.fetch_max(now, Ordering::SeqCst);
343 tokio::task::yield_now().await;
344 self.in_flight.fetch_sub(1, Ordering::SeqCst);
345 Storage::read(&self.inner, key).await
346 }
347
348 async fn delete(&self, key: &str) -> Result<()> {
349 Storage::delete(&self.inner, key).await
350 }
351
352 async fn list(&self, prefix: &str) -> Result<Vec<String>> {
353 Storage::list(&self.inner, prefix).await
354 }
355 }
356}