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