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