1use std::{
2 io::{BufRead, BufReader},
3 path::Path,
4 pin::pin,
5 sync::{
6 Arc,
7 atomic::{AtomicUsize, Ordering},
8 },
9};
10
11use collections::HashSet;
12use fs::Fs;
13use futures::{SinkExt, StreamExt, select_biased};
14use gpui::{App, AsyncApp, Entity, WeakEntity};
15use language::{Buffer, BufferSnapshot};
16use postage::oneshot;
17use smol::channel::{Receiver, Sender, bounded, unbounded};
18
19use util::{ResultExt, maybe};
20use worktree::{Entry, ProjectEntryId, Snapshot, WorktreeSettings};
21
22use crate::{
23 ProjectPath,
24 buffer_store::BufferStore,
25 search::{SearchQuery, SearchResult},
26};
27
28pub(crate) struct ProjectSearcher {
29 pub(crate) fs: Arc<dyn Fs>,
30 pub(crate) buffer_store: WeakEntity<BufferStore>,
31 pub(crate) snapshots: Vec<(Snapshot, WorktreeSettings)>,
32 pub(crate) open_buffers: HashSet<ProjectEntryId>,
33}
34
35const MAX_SEARCH_RESULT_FILES: usize = 5_000;
36const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
37
38impl ProjectSearcher {
39 pub(crate) fn run(self, query: SearchQuery, cx: &mut App) -> Receiver<SearchResult> {
40 let executor = cx.background_executor().clone();
41 let (tx, rx) = unbounded();
42 cx.spawn(async move |cx| {
43 const MAX_CONCURRENT_BUFFER_OPENS: usize = 64;
44 let (find_all_matches_tx, find_all_matches_rx) = bounded(MAX_CONCURRENT_BUFFER_OPENS);
45 let (get_buffer_for_full_scan_tx, get_buffer_for_full_scan_rx) =
46 bounded(MAX_CONCURRENT_BUFFER_OPENS);
47 let matches_count = AtomicUsize::new(0);
48 let matched_buffer_count = AtomicUsize::new(0);
49 let worker_pool = executor.scoped(|scope| {
50 let (input_paths_tx, input_paths_rx) = bounded(64);
51 let (confirm_contents_will_match_tx, confirm_contents_will_match_rx) = bounded(64);
52 let (sorted_search_results_tx, sorted_search_results_rx) = bounded(64);
53 for _ in 0..executor.num_cpus() {
54 let worker = Worker {
55 query: &query,
56 open_buffers: &self.open_buffers,
57 matched_buffer_count: &matched_buffer_count,
58 matches_count: &matches_count,
59 fs: &*self.fs,
60 input_paths_rx: input_paths_rx.clone(),
61 confirm_contents_will_match_rx: confirm_contents_will_match_rx.clone(),
62 confirm_contents_will_match_tx: confirm_contents_will_match_tx.clone(),
63 get_buffer_for_full_scan_tx: get_buffer_for_full_scan_tx.clone(),
64 find_all_matches_rx: find_all_matches_rx.clone(),
65 publish_matches: tx.clone(),
66 };
67 scope.spawn(worker.run());
68 }
69 scope.spawn(self.provide_search_paths(
70 &query,
71 input_paths_tx,
72 sorted_search_results_tx,
73 ));
74 scope.spawn(self.maintain_sorted_search_results(
75 sorted_search_results_rx,
76 get_buffer_for_full_scan_tx,
77 ))
78 });
79 let open_buffers =
80 self.open_buffers(get_buffer_for_full_scan_rx, find_all_matches_tx, cx);
81 futures::future::join(worker_pool, open_buffers).await;
82
83 let limit_reached = matches_count.load(Ordering::Acquire) > MAX_SEARCH_RESULT_RANGES
84 || matched_buffer_count.load(Ordering::Acquire) > MAX_SEARCH_RESULT_FILES;
85 if limit_reached {
86 _ = tx.send(SearchResult::LimitReached).await;
87 }
88 })
89 .detach();
90 rx
91 }
92
93 async fn provide_search_paths<'this>(
94 &'this self,
95 query: &SearchQuery,
96 tx: Sender<InputPath<'this>>,
97 results: Sender<oneshot::Receiver<ProjectPath>>,
98 ) {
99 for (snapshot, worktree_settings) in &self.snapshots {
100 for entry in snapshot.entries(query.include_ignored(), 0) {
101 let (should_scan_tx, should_scan_rx) = oneshot::channel();
102 let Ok(_) = tx
103 .send(InputPath {
104 entry,
105 settings: worktree_settings,
106 snapshot: snapshot,
107 should_scan_tx,
108 })
109 .await
110 else {
111 return;
112 };
113 results.send(should_scan_rx).await;
114 }
115 }
116 }
117
118 async fn maintain_sorted_search_results(
119 &self,
120 rx: Receiver<oneshot::Receiver<ProjectPath>>,
121 paths_for_full_scan: Sender<ProjectPath>,
122 ) {
123 let mut rx = pin!(rx);
124 while let Some(mut next_path_result) = rx.next().await {
125 let Some(successful_path) = next_path_result.next().await else {
126 // This math did not produce a match, hence skip it.
127 continue;
128 };
129 paths_for_full_scan.send(successful_path).await;
130 }
131 }
132
133 /// Background workers cannot open buffers by themselves, hence main thread will do it on their behalf.
134 async fn open_buffers<'a>(
135 &'a self,
136 rx: Receiver<ProjectPath>,
137 find_all_matches_tx: Sender<(Entity<Buffer>, BufferSnapshot)>,
138 cx: &mut AsyncApp,
139 ) {
140 _ = maybe!(async move {
141 while let Ok(requested_path) = rx.recv().await {
142 let Some(buffer) = self
143 .buffer_store
144 .update(cx, |this, cx| this.open_buffer(requested_path, cx))?
145 .await
146 .log_err()
147 else {
148 continue;
149 };
150 let snapshot = buffer.read_with(cx, |this, _| this.snapshot())?;
151 find_all_matches_tx.send((buffer, snapshot)).await?;
152 }
153 Result::<_, anyhow::Error>::Ok(())
154 })
155 .await;
156 }
157}
158
159struct Worker<'search> {
160 query: &'search SearchQuery,
161 matched_buffer_count: &'search AtomicUsize,
162 matches_count: &'search AtomicUsize,
163 open_buffers: &'search HashSet<ProjectEntryId>,
164 fs: &'search dyn Fs,
165 /// Start off with all paths in project and filter them based on:
166 /// - Include filters
167 /// - Exclude filters
168 /// - Only open buffers
169 /// - Scan ignored files
170 /// Put another way: filter out files that can't match (without looking at file contents)
171 input_paths_rx: Receiver<InputPath<'search>>,
172
173 /// After that, if the buffer is not yet loaded, we'll figure out if it contains at least one match
174 /// based on disk contents of a buffer. This step is not performed for buffers we already have in memory.
175 confirm_contents_will_match_tx: Sender<MatchingEntry>,
176 confirm_contents_will_match_rx: Receiver<MatchingEntry>,
177 /// Of those that contain at least one match (or are already in memory), look for rest of matches (and figure out their ranges).
178 /// But wait - first, we need to go back to the main thread to open a buffer (& create an entity for it).
179 get_buffer_for_full_scan_tx: Sender<ProjectPath>,
180 /// Ok, we're back in background: run full scan & find all matches in a given buffer snapshot.
181 find_all_matches_rx: Receiver<(Entity<Buffer>, BufferSnapshot)>,
182 /// Cool, we have results; let's share them with the world.
183 publish_matches: Sender<SearchResult>,
184}
185
186impl Worker<'_> {
187 async fn run(self) {
188 let mut find_all_matches = pin!(self.find_all_matches_rx.fuse());
189 let mut find_first_match = pin!(self.confirm_contents_will_match_rx.fuse());
190 let mut scan_path = pin!(self.input_paths_rx.fuse());
191 let handler = RequestHandler {
192 query: self.query,
193 open_entries: &self.open_buffers,
194 fs: self.fs,
195 matched_buffer_count: self.matched_buffer_count,
196 matches_count: self.matches_count,
197 confirm_contents_will_match_tx: &self.confirm_contents_will_match_tx,
198 get_buffer_for_full_scan_tx: &self.get_buffer_for_full_scan_tx,
199 publish_matches: &self.publish_matches,
200 };
201 loop {
202 select_biased! {
203 find_all_matches = find_all_matches.next() => {
204 let result = handler.handle_find_all_matches(find_all_matches).await;
205 if let Some(_should_bail) = result {
206 return;
207 }
208 },
209 find_first_match = find_first_match.next() => {
210 if let Some(buffer_with_at_least_one_match) = find_first_match {
211 handler.handle_find_first_match(buffer_with_at_least_one_match).await;
212 }
213
214 },
215 scan_path = scan_path.next() => {
216 if let Some(path_to_scan) = scan_path {
217 handler.handle_scan_path(path_to_scan).await;
218 }
219
220 }
221 complete => break,
222 }
223 }
224 }
225}
226
227struct RequestHandler<'worker> {
228 query: &'worker SearchQuery,
229 fs: &'worker dyn Fs,
230 open_entries: &'worker HashSet<ProjectEntryId>,
231 matched_buffer_count: &'worker AtomicUsize,
232 matches_count: &'worker AtomicUsize,
233
234 confirm_contents_will_match_tx: &'worker Sender<MatchingEntry>,
235 get_buffer_for_full_scan_tx: &'worker Sender<ProjectPath>,
236 publish_matches: &'worker Sender<SearchResult>,
237}
238
239struct LimitReached;
240
241impl RequestHandler<'_> {
242 async fn handle_find_all_matches(
243 &self,
244 req: Option<(Entity<Buffer>, BufferSnapshot)>,
245 ) -> Option<LimitReached> {
246 let Some((buffer, snapshot)) = req else {
247 unreachable!()
248 };
249 let ranges = self
250 .query
251 .search(&snapshot, None)
252 .await
253 .iter()
254 .map(|range| snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end))
255 .collect::<Vec<_>>();
256
257 let matched_ranges = ranges.len();
258 if self.matched_buffer_count.fetch_add(1, Ordering::Release) > MAX_SEARCH_RESULT_FILES
259 || self
260 .matches_count
261 .fetch_add(matched_ranges, Ordering::Release)
262 > MAX_SEARCH_RESULT_RANGES
263 {
264 Some(LimitReached)
265 } else {
266 self.publish_matches
267 .send(SearchResult::Buffer { buffer, ranges })
268 .await;
269 None
270 }
271 }
272 async fn handle_find_first_match(&self, mut entry: MatchingEntry) {
273 _=maybe!(async move {
274 let abs_path = entry.worktree_root.join(entry.path.path.as_std_path());
275 let Some(file) = self.fs.open_sync(&abs_path).await.log_err() else {
276 return anyhow::Ok(());
277 };
278
279 let mut file = BufReader::new(file);
280 let file_start = file.fill_buf()?;
281
282 if let Err(Some(starting_position)) =
283 std::str::from_utf8(file_start).map_err(|e| e.error_len())
284 {
285 // Before attempting to match the file content, throw away files that have invalid UTF-8 sequences early on;
286 // That way we can still match files in a streaming fashion without having look at "obviously binary" files.
287 log::debug!(
288 "Invalid UTF-8 sequence in file {abs_path:?} at byte position {starting_position}"
289 );
290 return Ok(());
291 }
292
293 if self.query.detect(file).unwrap_or(false) {
294 // Yes, we should scan the whole file.
295 entry.should_scan_tx.send(entry.path).await?;
296 }
297 Ok(())
298 }).await;
299 }
300
301 async fn handle_scan_path(&self, req: InputPath<'_>) {
302 _ = maybe!(async move {
303 let InputPath {
304 entry,
305 settings,
306 snapshot,
307 should_scan_tx,
308 } = req;
309 if entry.is_dir() && entry.is_ignored {
310 if !settings.is_path_excluded(&entry.path) {
311 // Self::scan_ignored_dir(
312 // self.fs,
313 // &snapshot,
314 // &entry.path,
315 // self.query,
316 // &filter_tx,
317 // &output_tx,
318 // )
319 // .await?;
320 }
321 return Ok(());
322 }
323
324 if entry.is_fifo || !entry.is_file() {
325 return Ok(());
326 }
327
328 if self.query.filters_path() {
329 let matched_path = if self.query.match_full_paths() {
330 let mut full_path = snapshot.root_name().as_std_path().to_owned();
331 full_path.push(entry.path.as_std_path());
332 self.query.match_path(&full_path)
333 } else {
334 self.query.match_path(entry.path.as_std_path())
335 };
336 if !matched_path {
337 return Ok(());
338 }
339 }
340
341 if self.open_entries.contains(&entry.id) {
342 // The buffer is already in memory and that's the version we want to scan;
343 // hence skip the dilly-dally and look for all matches straight away.
344 self.get_buffer_for_full_scan_tx
345 .send(ProjectPath {
346 worktree_id: snapshot.id(),
347 path: entry.path.clone(),
348 })
349 .await?;
350 } else {
351 self.confirm_contents_will_match_tx
352 .send(MatchingEntry {
353 should_scan_tx: should_scan_tx,
354 worktree_root: snapshot.abs_path().clone(),
355 path: ProjectPath {
356 worktree_id: snapshot.id(),
357 path: entry.path.clone(),
358 },
359 })
360 .await?;
361 }
362
363 anyhow::Ok(())
364 })
365 .await;
366 }
367}
368
369struct InputPath<'worker> {
370 entry: &'worker Entry,
371 settings: &'worker WorktreeSettings,
372 snapshot: &'worker Snapshot,
373 should_scan_tx: oneshot::Sender<ProjectPath>,
374}
375
376struct MatchingEntry {
377 worktree_root: Arc<Path>,
378 path: ProjectPath,
379 should_scan_tx: oneshot::Sender<ProjectPath>,
380}