1use std::{
2 io::{BufRead, BufReader},
3 path::Path,
4 pin::pin,
5 sync::{
6 Arc,
7 atomic::{AtomicUsize, Ordering},
8 },
9};
10
11use anyhow::Context;
12use collections::HashSet;
13use fs::Fs;
14use futures::{SinkExt, StreamExt, select_biased};
15use gpui::{App, AsyncApp, Entity, Task};
16use language::{Buffer, BufferSnapshot};
17use postage::oneshot;
18use smol::channel::{Receiver, Sender, bounded, unbounded};
19
20use util::{ResultExt, maybe};
21use worktree::{Entry, ProjectEntryId, Snapshot, Worktree};
22
23use crate::{
24 ProjectItem, ProjectPath,
25 buffer_store::BufferStore,
26 search::{SearchQuery, SearchResult},
27};
28
29pub(crate) struct Search {
30 pub(crate) fs: Arc<dyn Fs>,
31 pub(crate) buffer_store: Entity<BufferStore>,
32 pub(crate) worktrees: Vec<Entity<Worktree>>,
33 pub(crate) limit: usize,
34}
35
36/// Represents results of project search and allows one to either obtain match positions OR
37/// just the handles to buffers that may match the search.
38#[must_use]
39pub(crate) struct SearchResultsHandle {
40 results: Receiver<SearchResult>,
41 matching_buffers: Receiver<Entity<Buffer>>,
42 trigger_search: Box<dyn FnOnce(&mut App) -> Task<()> + Send + Sync>,
43}
44
45impl SearchResultsHandle {
46 pub(crate) fn results(self, cx: &mut App) -> Receiver<SearchResult> {
47 (self.trigger_search)(cx).detach();
48 self.results
49 }
50 pub(crate) fn matching_buffers(self, cx: &mut App) -> Receiver<Entity<Buffer>> {
51 (self.trigger_search)(cx).detach();
52 self.matching_buffers
53 }
54}
55
56impl Search {
57 pub(crate) const MAX_SEARCH_RESULT_FILES: usize = 5_000;
58 pub(crate) const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
59 /// Prepares a project search run. The result has to be used to specify whether you're interested in matching buffers
60 /// or full search results.
61 pub(crate) fn into_results(mut self, query: SearchQuery, cx: &mut App) -> SearchResultsHandle {
62 let mut open_buffers = HashSet::default();
63 let mut unnamed_buffers = Vec::new();
64 const MAX_CONCURRENT_BUFFER_OPENS: usize = 64;
65 let buffers = self.buffer_store.read(cx);
66 for handle in buffers.buffers() {
67 let buffer = handle.read(cx);
68 if !buffers.is_searchable(&buffer.remote_id()) {
69 continue;
70 } else if let Some(entry_id) = buffer.entry_id(cx) {
71 open_buffers.insert(entry_id);
72 } else {
73 self.limit -= self.limit.saturating_sub(1);
74 unnamed_buffers.push(handle)
75 };
76 }
77 let executor = cx.background_executor().clone();
78 let (tx, rx) = unbounded();
79 let (grab_buffer_snapshot_tx, grab_buffer_snapshot_rx) = unbounded();
80 let matching_buffers = grab_buffer_snapshot_rx.clone();
81 let trigger_search = Box::new(|cx: &mut App| {
82 cx.spawn(async move |cx| {
83 for buffer in unnamed_buffers {
84 _ = grab_buffer_snapshot_tx.send(buffer).await;
85 }
86
87 let (find_all_matches_tx, find_all_matches_rx) =
88 bounded(MAX_CONCURRENT_BUFFER_OPENS);
89
90 let (get_buffer_for_full_scan_tx, get_buffer_for_full_scan_rx) = unbounded();
91 let matches_count = AtomicUsize::new(0);
92 let matched_buffer_count = AtomicUsize::new(0);
93 let (input_paths_tx, input_paths_rx) = unbounded();
94 let (sorted_search_results_tx, sorted_search_results_rx) = unbounded();
95 let worker_pool = executor.scoped(|scope| {
96 let (confirm_contents_will_match_tx, confirm_contents_will_match_rx) =
97 bounded(64);
98
99 let num_cpus = executor.num_cpus();
100
101 assert!(num_cpus > 0);
102 for _ in 0..executor.num_cpus() - 1 {
103 let worker = Worker {
104 query: &query,
105 open_buffers: &open_buffers,
106 matched_buffer_count: &matched_buffer_count,
107 matches_count: &matches_count,
108 fs: &*self.fs,
109 input_paths_rx: input_paths_rx.clone(),
110 confirm_contents_will_match_rx: confirm_contents_will_match_rx.clone(),
111 confirm_contents_will_match_tx: confirm_contents_will_match_tx.clone(),
112 get_buffer_for_full_scan_tx: get_buffer_for_full_scan_tx.clone(),
113 find_all_matches_rx: find_all_matches_rx.clone(),
114 publish_matches: tx.clone(),
115 };
116 scope.spawn(worker.run());
117 }
118 drop(tx);
119
120 scope.spawn(Self::maintain_sorted_search_results(
121 sorted_search_results_rx,
122 get_buffer_for_full_scan_tx,
123 self.limit,
124 ))
125 });
126 let provide_search_paths = cx.spawn(Self::provide_search_paths(
127 std::mem::take(&mut self.worktrees),
128 query.include_ignored(),
129 input_paths_tx,
130 sorted_search_results_tx,
131 ));
132 let open_buffers = self.open_buffers(
133 get_buffer_for_full_scan_rx,
134 grab_buffer_snapshot_tx,
135 cx.clone(),
136 );
137 let buffer_snapshots = self.grab_buffer_snapshots(
138 grab_buffer_snapshot_rx,
139 find_all_matches_tx,
140 cx.clone(),
141 );
142 futures::future::join4(
143 worker_pool,
144 buffer_snapshots,
145 open_buffers,
146 provide_search_paths,
147 )
148 .await;
149 })
150 });
151 SearchResultsHandle {
152 results: rx,
153 matching_buffers,
154 trigger_search,
155 }
156 }
157
158 fn provide_search_paths(
159 worktrees: Vec<Entity<Worktree>>,
160 include_ignored: bool,
161 tx: Sender<InputPath>,
162 results: Sender<oneshot::Receiver<ProjectPath>>,
163 ) -> impl AsyncFnOnce(&mut AsyncApp) {
164 async move |cx| {
165 _ = maybe!(async move {
166 for worktree in worktrees {
167 let (mut snapshot, worktree_settings) = worktree
168 .read_with(cx, |this, _| {
169 Some((this.snapshot(), this.as_local()?.settings()))
170 })?
171 .context("The worktree is not local")?;
172 if include_ignored {
173 // Pre-fetch all of the ignored directories as they're going to be searched.
174 let mut entries_to_refresh = vec![];
175 for entry in snapshot.entries(include_ignored, 0) {
176 if entry.is_ignored && entry.kind.is_unloaded() {
177 if !worktree_settings.is_path_excluded(&entry.path) {
178 entries_to_refresh.push(entry.path.clone());
179 }
180 }
181 }
182 let barrier = worktree.update(cx, |this, _| {
183 let local = this.as_local_mut()?;
184 let barrier = entries_to_refresh
185 .into_iter()
186 .map(|path| local.add_path_prefix_to_scan(path).into_future())
187 .collect::<Vec<_>>();
188 Some(barrier)
189 })?;
190 if let Some(barriers) = barrier {
191 futures::future::join_all(barriers).await;
192 }
193 snapshot = worktree.read_with(cx, |this, _| this.snapshot())?;
194 }
195 cx.background_executor()
196 .scoped(|scope| {
197 scope.spawn(async {
198 for entry in snapshot.files(include_ignored, 0) {
199 let (should_scan_tx, should_scan_rx) = oneshot::channel();
200 let Ok(_) = tx
201 .send(InputPath {
202 entry: entry.clone(),
203 snapshot: snapshot.clone(),
204 should_scan_tx,
205 })
206 .await
207 else {
208 return;
209 };
210 if results.send(should_scan_rx).await.is_err() {
211 return;
212 };
213 }
214 })
215 })
216 .await;
217 }
218 anyhow::Ok(())
219 })
220 .await;
221 }
222 }
223
224 async fn maintain_sorted_search_results(
225 rx: Receiver<oneshot::Receiver<ProjectPath>>,
226 paths_for_full_scan: Sender<ProjectPath>,
227 limit: usize,
228 ) {
229 let mut rx = pin!(rx);
230 let mut matched = 0;
231 while let Some(mut next_path_result) = rx.next().await {
232 let Some(successful_path) = next_path_result.next().await else {
233 // This math did not produce a match, hence skip it.
234 continue;
235 };
236 if paths_for_full_scan.send(successful_path).await.is_err() {
237 return;
238 };
239 matched += 1;
240 if matched >= limit {
241 break;
242 }
243 }
244 }
245
246 /// Background workers cannot open buffers by themselves, hence main thread will do it on their behalf.
247 async fn open_buffers(
248 &self,
249 rx: Receiver<ProjectPath>,
250 find_all_matches_tx: Sender<Entity<Buffer>>,
251 mut cx: AsyncApp,
252 ) {
253 _ = maybe!(async move {
254 while let Ok(requested_path) = rx.recv().await {
255 let Some(buffer) = self
256 .buffer_store
257 .update(&mut cx, |this, cx| this.open_buffer(requested_path, cx))?
258 .await
259 .log_err()
260 else {
261 continue;
262 };
263 find_all_matches_tx.send(buffer).await?;
264 }
265 Result::<_, anyhow::Error>::Ok(())
266 })
267 .await;
268 }
269
270 async fn grab_buffer_snapshots(
271 &self,
272 rx: Receiver<Entity<Buffer>>,
273 find_all_matches_tx: Sender<(Entity<Buffer>, BufferSnapshot)>,
274 mut cx: AsyncApp,
275 ) {
276 _ = maybe!(async move {
277 while let Ok(buffer) = rx.recv().await {
278 let snapshot = buffer.read_with(&mut cx, |this, _| this.snapshot())?;
279 find_all_matches_tx.send((buffer, snapshot)).await?;
280 }
281 Result::<_, anyhow::Error>::Ok(())
282 })
283 .await;
284 }
285}
286
287struct Worker<'search> {
288 query: &'search SearchQuery,
289 matched_buffer_count: &'search AtomicUsize,
290 matches_count: &'search AtomicUsize,
291 open_buffers: &'search HashSet<ProjectEntryId>,
292 fs: &'search dyn Fs,
293 /// Start off with all paths in project and filter them based on:
294 /// - Include filters
295 /// - Exclude filters
296 /// - Only open buffers
297 /// - Scan ignored files
298 /// Put another way: filter out files that can't match (without looking at file contents)
299 input_paths_rx: Receiver<InputPath>,
300
301 /// After that, if the buffer is not yet loaded, we'll figure out if it contains at least one match
302 /// based on disk contents of a buffer. This step is not performed for buffers we already have in memory.
303 confirm_contents_will_match_tx: Sender<MatchingEntry>,
304 confirm_contents_will_match_rx: Receiver<MatchingEntry>,
305 /// Of those that contain at least one match (or are already in memory), look for rest of matches (and figure out their ranges).
306 /// But wait - first, we need to go back to the main thread to open a buffer (& create an entity for it).
307 get_buffer_for_full_scan_tx: Sender<ProjectPath>,
308 /// Ok, we're back in background: run full scan & find all matches in a given buffer snapshot.
309 find_all_matches_rx: Receiver<(Entity<Buffer>, BufferSnapshot)>,
310 /// Cool, we have results; let's share them with the world.
311 publish_matches: Sender<SearchResult>,
312}
313
314impl Worker<'_> {
315 async fn run(mut self) {
316 let mut find_all_matches = pin!(self.find_all_matches_rx.fuse());
317 let mut find_first_match = pin!(self.confirm_contents_will_match_rx.fuse());
318 let mut scan_path = pin!(self.input_paths_rx.fuse());
319
320 loop {
321 let handler = RequestHandler {
322 query: self.query,
323 open_entries: &self.open_buffers,
324 fs: self.fs,
325 matched_buffer_count: self.matched_buffer_count,
326 matches_count: self.matches_count,
327 confirm_contents_will_match_tx: &self.confirm_contents_will_match_tx,
328 get_buffer_for_full_scan_tx: &self.get_buffer_for_full_scan_tx,
329 publish_matches: &self.publish_matches,
330 };
331 // Whenever we notice that some step of a pipeline is closed, we don't want to close subsequent
332 // steps straight away. Another worker might be about to produce a value that will
333 // be pushed there, thus we'll replace current worker's pipe with a dummy one.
334 // That way, we'll only ever close a next-stage channel when ALL workers do so.
335 select_biased! {
336 find_all_matches = find_all_matches.next() => {
337 if self.publish_matches.is_closed() {
338 break;
339 }
340 let Some(matches) = find_all_matches else {
341 self.publish_matches = bounded(1).0;
342 continue;
343 };
344 let result = handler.handle_find_all_matches(matches).await;
345 if let Some(_should_bail) = result {
346
347 self.publish_matches = bounded(1).0;
348 continue;
349 }
350 },
351 find_first_match = find_first_match.next() => {
352 if let Some(buffer_with_at_least_one_match) = find_first_match {
353 handler.handle_find_first_match(buffer_with_at_least_one_match).await;
354 } else {
355 self.get_buffer_for_full_scan_tx = bounded(1).0;
356 }
357
358 },
359 scan_path = scan_path.next() => {
360 if let Some(path_to_scan) = scan_path {
361 handler.handle_scan_path(path_to_scan).await;
362 } else {
363 // If we're the last worker to notice that this is not producing values, close the upstream.
364 self.confirm_contents_will_match_tx = bounded(1).0;
365 }
366
367 }
368 complete => {
369 break
370 },
371
372 }
373 }
374 }
375}
376
377struct RequestHandler<'worker> {
378 query: &'worker SearchQuery,
379 fs: &'worker dyn Fs,
380 open_entries: &'worker HashSet<ProjectEntryId>,
381 matched_buffer_count: &'worker AtomicUsize,
382 matches_count: &'worker AtomicUsize,
383
384 confirm_contents_will_match_tx: &'worker Sender<MatchingEntry>,
385 get_buffer_for_full_scan_tx: &'worker Sender<ProjectPath>,
386 publish_matches: &'worker Sender<SearchResult>,
387}
388
389struct LimitReached;
390
391impl RequestHandler<'_> {
392 async fn handle_find_all_matches(
393 &self,
394 (buffer, snapshot): (Entity<Buffer>, BufferSnapshot),
395 ) -> Option<LimitReached> {
396 let ranges = self
397 .query
398 .search(&snapshot, None)
399 .await
400 .iter()
401 .map(|range| snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end))
402 .collect::<Vec<_>>();
403
404 let matched_ranges = ranges.len();
405 if self.matched_buffer_count.fetch_add(1, Ordering::Release)
406 > Search::MAX_SEARCH_RESULT_FILES
407 || self
408 .matches_count
409 .fetch_add(matched_ranges, Ordering::Release)
410 > Search::MAX_SEARCH_RESULT_RANGES
411 {
412 _ = self.publish_matches.send(SearchResult::LimitReached).await;
413 Some(LimitReached)
414 } else {
415 _ = self
416 .publish_matches
417 .send(SearchResult::Buffer { buffer, ranges })
418 .await;
419 None
420 }
421 }
422 async fn handle_find_first_match(&self, mut entry: MatchingEntry) {
423 _=maybe!(async move {
424 let abs_path = entry.worktree_root.join(entry.path.path.as_std_path());
425 let Some(file) = self.fs.open_sync(&abs_path).await.log_err() else {
426 return anyhow::Ok(());
427 };
428
429 let mut file = BufReader::new(file);
430 let file_start = file.fill_buf()?;
431
432 if let Err(Some(starting_position)) =
433 std::str::from_utf8(file_start).map_err(|e| e.error_len())
434 {
435 // Before attempting to match the file content, throw away files that have invalid UTF-8 sequences early on;
436 // That way we can still match files in a streaming fashion without having look at "obviously binary" files.
437 log::debug!(
438 "Invalid UTF-8 sequence in file {abs_path:?} at byte position {starting_position}"
439 );
440 return Ok(());
441 }
442
443 if self.query.detect(file).unwrap_or(false) {
444 // Yes, we should scan the whole file.
445 entry.should_scan_tx.send(entry.path).await?;
446 }
447 Ok(())
448 }).await;
449 }
450
451 async fn handle_scan_path(&self, req: InputPath) {
452 _ = maybe!(async move {
453 let InputPath {
454 entry,
455
456 snapshot,
457 should_scan_tx,
458 } = req;
459
460 if entry.is_fifo || !entry.is_file() {
461 return Ok(());
462 }
463
464 if self.query.filters_path() {
465 let matched_path = if self.query.match_full_paths() {
466 let mut full_path = snapshot.root_name().as_std_path().to_owned();
467 full_path.push(entry.path.as_std_path());
468 self.query.match_path(&full_path)
469 } else {
470 self.query.match_path(entry.path.as_std_path())
471 };
472 if !matched_path {
473 return Ok(());
474 }
475 }
476
477 if self.open_entries.contains(&entry.id) {
478 // The buffer is already in memory and that's the version we want to scan;
479 // hence skip the dilly-dally and look for all matches straight away.
480 self.get_buffer_for_full_scan_tx
481 .send(ProjectPath {
482 worktree_id: snapshot.id(),
483 path: entry.path.clone(),
484 })
485 .await?;
486 } else {
487 self.confirm_contents_will_match_tx
488 .send(MatchingEntry {
489 should_scan_tx: should_scan_tx,
490 worktree_root: snapshot.abs_path().clone(),
491 path: ProjectPath {
492 worktree_id: snapshot.id(),
493 path: entry.path.clone(),
494 },
495 })
496 .await?;
497 }
498
499 anyhow::Ok(())
500 })
501 .await;
502 }
503}
504
505struct InputPath {
506 entry: Entry,
507 snapshot: Snapshot,
508 should_scan_tx: oneshot::Sender<ProjectPath>,
509}
510
511struct MatchingEntry {
512 worktree_root: Arc<Path>,
513 path: ProjectPath,
514 should_scan_tx: oneshot::Sender<ProjectPath>,
515}