1use super::grep_file::{GrepSearchInput, GrepSearchResult};
9use crate::cache::{CacheKey, DEFAULT_CACHE_TTL, EvictionPolicy, UnifiedCache, estimate_json_size};
10use std::sync::Arc;
11
12#[derive(Debug, Clone, Hash, PartialEq, Eq)]
14struct SearchCacheKey {
15 pattern: String,
16 path: String,
17 case_sensitive: bool,
18 max_results: usize,
19 glob_pattern: Option<String>,
20 type_pattern: Option<String>,
21 max_result_bytes: Option<usize>,
22 respect_ignore_files: bool,
23 search_hidden: bool,
24 search_binary: bool,
25 literal: bool,
26}
27
28impl CacheKey for SearchCacheKey {
29 fn to_cache_key(&self) -> String {
30 format!(
35 "grep\u{1f}{}\u{1f}{}\u{1f}{}\u{1f}{}\u{1f}{:?}\u{1f}{:?}\u{1f}{:?}\u{1f}{}\u{1f}{}\u{1f}{}\u{1f}{}",
36 self.pattern,
37 self.path,
38 self.case_sensitive,
39 self.max_results,
40 self.glob_pattern,
41 self.type_pattern,
42 self.max_result_bytes,
43 self.respect_ignore_files,
44 self.search_hidden,
45 self.search_binary,
46 self.literal,
47 )
48 }
49}
50
51impl From<&GrepSearchInput> for SearchCacheKey {
52 fn from(input: &GrepSearchInput) -> Self {
53 Self {
54 pattern: input.pattern.clone(),
55 path: input.path.clone(),
56 case_sensitive: input.case_sensitive.unwrap_or(false),
57 max_results: input.max_results.unwrap_or(5), glob_pattern: input.glob_pattern.clone(),
59 type_pattern: input.type_pattern.clone(),
60 max_result_bytes: input.max_result_bytes,
61 respect_ignore_files: input.respect_ignore_files.unwrap_or(true),
62 search_hidden: input.search_hidden.unwrap_or(false),
63 search_binary: input.search_binary.unwrap_or(false),
64 literal: input.literal.unwrap_or(false),
65 }
66 }
67}
68
69pub struct GrepSearchCache {
71 cache: UnifiedCache<SearchCacheKey, GrepSearchResult>,
72}
73
74impl GrepSearchCache {
75 pub fn new(capacity: usize) -> Self {
77 Self {
78 cache: UnifiedCache::new(capacity, DEFAULT_CACHE_TTL, EvictionPolicy::Lru),
79 }
80 }
81
82 pub fn get(&self, input: &GrepSearchInput) -> Option<Arc<GrepSearchResult>> {
84 let key = SearchCacheKey::from(input);
85 self.cache.get(&key)
86 }
87
88 pub fn put(&self, input: &GrepSearchInput, result: GrepSearchResult) {
90 let key = SearchCacheKey::from(input);
91 let size_bytes = size_of::<GrepSearchResult>() as u64
92 + result.query.len() as u64
93 + result.matches.iter().map(estimate_json_size).sum::<u64>();
94 self.cache.insert(key, result, size_bytes);
95 }
96
97 pub fn should_cache(result: &GrepSearchResult) -> bool {
111 result
112 .matches
113 .iter()
114 .any(|entry| entry.get("type").and_then(serde_json::Value::as_str) == Some("match"))
115 }
116
117 pub fn clear(&self) {
119 self.cache.clear();
120 }
121
122 pub fn stats(&self) -> (usize, usize) {
124 let stats = self.cache.stats();
125 (stats.current_size, stats.max_size)
126 }
127}
128
129impl Default for GrepSearchCache {
130 fn default() -> Self {
131 Self::new(100) }
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 fn make_test_input(pattern: &str, path: &str) -> GrepSearchInput {
140 GrepSearchInput {
141 pattern: pattern.to_string(),
142 path: path.to_string(),
143 case_sensitive: Some(true),
144 literal: None,
145 glob_pattern: Some("*.rs".to_string()),
146 context_lines: None,
147 include_hidden: None,
148 max_results: Some(5), respect_ignore_files: None,
150 max_file_size: None,
151 search_hidden: None,
152 search_binary: None,
153 files_with_matches: None,
154 type_pattern: None,
155 invert_match: None,
156 word_boundaries: None,
157 line_number: None,
158 column: None,
159 only_matching: None,
160 trim: None,
161 max_result_bytes: None,
162 timeout: None,
163 extra_ignore_globs: None,
164 }
165 }
166
167 #[test]
168 fn test_cache_key_equality() {
169 let input1 = make_test_input("test", "/path");
170 let input2 = make_test_input("test", "/path");
171
172 let key1 = SearchCacheKey::from(&input1);
173 let key2 = SearchCacheKey::from(&input2);
174 assert_eq!(key1, key2);
175 }
176
177 #[test]
178 fn test_cache_operations() {
179 let cache = GrepSearchCache::new(10);
180
181 let input = make_test_input("test", "/path");
182
183 let result = GrepSearchResult {
184 query: "test".to_string(),
185 matches: vec![serde_json::json!({"file": "test.rs", "line": 1})],
186 truncated: false,
187 total_matches: None,
188 };
189
190 assert!(cache.get(&input).is_none());
192
193 cache.put(&input, result.clone());
195
196 let cached = cache.get(&input).unwrap();
198 assert_eq!(cached.query, result.query);
199 assert_eq!(cached.matches.len(), result.matches.len());
200 assert_eq!(cached.truncated, result.truncated);
201 }
202
203 #[test]
204 fn empty_results_are_not_cached_so_stale_negatives_cannot_mask_new_matches() {
205 let cache = GrepSearchCache::new(10);
206 let input = make_test_input("never-matches", "/path");
207 let result = GrepSearchResult {
208 query: "never-matches".to_string(),
209 matches: vec![],
210 truncated: false,
211 total_matches: None,
212 };
213
214 assert!(!GrepSearchCache::should_cache(&result));
218
219 let no_hit_events = GrepSearchResult {
224 matches: vec![
225 serde_json::json!({"type": "begin", "data": {"path": {"text": "/ws/a.rs"}}}),
226 serde_json::json!({"type": "end", "data": {"path": {"text": "/ws/a.rs"}}}),
227 ],
228 ..result.clone()
229 };
230 assert!(!GrepSearchCache::should_cache(&no_hit_events));
231
232 let with_matches = GrepSearchResult {
235 matches: vec![serde_json::json!({
236 "type": "match",
237 "data": {"path": {"text": "/ws/a.rs"}, "lines": {"text": "needle\n"}, "line_number": 1}
238 })],
239 ..result.clone()
240 };
241 assert!(GrepSearchCache::should_cache(&with_matches));
242
243 cache.put(&input, with_matches);
244 let cached = cache.get(&input).expect("result with a real match must be served from cache");
245 assert_eq!(cached.matches.len(), 1);
246 }
247}