Skip to main content

fff_search/
shared.rs

1use std::path::{Path, PathBuf};
2use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard, Weak};
3use std::time::{Duration, Instant};
4
5use crate::dbs::lmdb::{LmdbStore, spawn_lmdb_gc};
6use crate::error::Error;
7use crate::file_picker::FilePicker;
8use crate::frecency::FrecencyTracker;
9use crate::git::GitStatusCache;
10use crate::query_tracker::QueryTracker;
11use crate::scan::ScanJob;
12use crate::watch::{WatchEvent, WatchId, WatchOptions, WatchRegistry};
13use git2::Repository;
14
15/// Poll `.git/index.lock` until it disappears (git write completed), giving up
16/// after [`GIT_LOCK_MAX_WAIT`]. Used by [`SharedPicker::refresh_git_status`]
17/// to avoid reading a half-updated index when the watcher fires mid-`git add`.
18///
19/// The wait is bounded and cheap: the lock file is typically cleared within
20/// a few milliseconds of the git command exiting.
21fn wait_for_git_index_lock_release(git_root: &Path) {
22    const GIT_LOCK_POLL: Duration = Duration::from_millis(10);
23    const GIT_LOCK_MAX_WAIT: Duration = Duration::from_millis(500);
24
25    let lock = git_root.join(".git").join("index.lock");
26    // Fast path: no lock present.
27    if !lock.exists() {
28        return;
29    }
30    let deadline = Instant::now() + GIT_LOCK_MAX_WAIT;
31    while lock.exists() && Instant::now() < deadline {
32        std::thread::sleep(GIT_LOCK_POLL);
33    }
34    if lock.exists() {
35        tracing::warn!(
36            "Proceeding with git status refresh despite lingering \
37             .git/index.lock at {} — will retry once it clears",
38            lock.display()
39        );
40    }
41}
42
43/// Poll `done` every 10ms until it returns `true`, or until `timeout` elapses.
44/// Returns `true` if the condition was met, `false` on timeout.
45fn poll_until(timeout: Duration, mut done: impl FnMut() -> bool) -> bool {
46    let start = Instant::now();
47    while !done() {
48        if start.elapsed() >= timeout {
49            return false;
50        }
51        std::thread::sleep(Duration::from_millis(10));
52    }
53    true
54}
55
56/// Thread-safe shared handle to the [`FilePicker`] instance.
57/// This accumulates only asynchronous non-blocking operations against the
58/// file picker: creating, triggering various rescans and so on.
59///
60/// For blocking access use internal picker via `.read()` or `.write()`
61///
62/// ```ignore
63/// let shared_picker = SharedFilePicker::default();
64///
65/// if let Some(picker) = shared_picker.read()?.as_ref() {
66///     let files = picker.fuzzy_search(&query, options);
67///     println!("Found {} files", files.len());
68/// } else {
69///     println!("Picker not initialized");
70/// }
71/// ```
72#[derive(Clone, Default)]
73pub struct SharedFilePicker(pub(crate) Arc<SharedPickerInner>);
74
75pub struct SharedPickerInner {
76    picker: parking_lot::RwLock<Option<FilePicker>>,
77    /// Watch subscriptions live outside the picker lock so delivery and
78    /// (un)subscribing never contend with searches.
79    watchers: Arc<WatchRegistry>,
80}
81
82impl Default for SharedPickerInner {
83    fn default() -> Self {
84        Self {
85            picker: parking_lot::RwLock::new(None),
86            watchers: Arc::new(WatchRegistry::default()),
87        }
88    }
89}
90
91/// Non-owning handle to a [`SharedPicker`].
92#[derive(Clone)]
93pub(crate) struct WeakFilePicker(Weak<SharedPickerInner>);
94
95impl WeakFilePicker {
96    /// Try to promote the weak handle back to a strong [`SharedPicker`].
97    ///
98    /// Returns `None` once every strong `SharedPicker` clone has been
99    /// dropped. Callers should treat that as "the picker is being
100    /// torn down" and exit their current iteration cleanly.
101    pub(crate) fn upgrade(&self) -> Option<SharedFilePicker> {
102        self.0.upgrade().map(SharedFilePicker)
103    }
104}
105
106impl std::fmt::Debug for SharedFilePicker {
107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        f.debug_tuple("SharedPicker").field(&"..").finish()
109    }
110}
111
112impl SharedFilePicker {
113    pub fn read(&self) -> Result<parking_lot::RwLockReadGuard<'_, Option<FilePicker>>, Error> {
114        Ok(self.0.picker.read())
115    }
116
117    pub fn write(&self) -> Result<parking_lot::RwLockWriteGuard<'_, Option<FilePicker>>, Error> {
118        Ok(self.0.picker.write())
119    }
120
121    /// Signal the background scan to cancel. Non-blocking: post-scan
122    /// threads check this flag and bail out at their next cancellation point.
123    pub fn cancel(&self) {
124        if let Ok(guard) = self.read()
125            && let Some(picker) = guard.as_ref()
126        {
127            picker.cancel();
128        }
129    }
130
131    /// Produce a non-owning handle to the same inner picker.
132    /// Use it if you don't need to block internal threads from dropping while owning this ref
133    pub(crate) fn weaken(&self) -> WeakFilePicker {
134        WeakFilePicker(Arc::downgrade(&self.0))
135    }
136
137    /// Return `true` if this is an instance of the picker that requires a complicated post-scan
138    /// indexing/cache warmup job. The indexing is not crazy but it takes time.
139    pub fn need_complex_rebuild(&self) -> bool {
140        let guard = self.0.picker.read();
141        guard
142            .as_ref()
143            .is_some_and(|p| p.has_mmap_cache() || p.has_content_indexing())
144    }
145
146    /// Block until the background filesystem scan finishes.
147    /// Returns `true` if scan completed, `false` on timeout.
148    pub fn wait_for_scan(&self, timeout: Duration) -> bool {
149        let signal = {
150            let guard = self.0.picker.read();
151            match &*guard {
152                Some(picker) => Arc::clone(&picker.signals.scanning),
153                None => return true,
154            }
155        };
156
157        poll_until(timeout, || {
158            !signal.load(std::sync::atomic::Ordering::Acquire)
159        })
160    }
161
162    /// Block until the background file watcher is ready.
163    /// Returns `true` if watcher ready, `false` on timeout.
164    pub fn wait_for_watcher(&self, timeout: Duration) -> bool {
165        let watch_ready_signal = {
166            let guard = self.0.picker.read();
167            match &*guard {
168                Some(picker) => Arc::clone(&picker.signals.watcher_ready),
169                None => return true,
170            }
171        };
172
173        poll_until(timeout, || {
174            watch_ready_signal.load(std::sync::atomic::Ordering::Acquire)
175        })
176    }
177
178    /// Blocks until both the filesystem walk and post-scan indexing are done.
179    /// Returns true once scanning=false AND post_scan_indexing_active=false.
180    pub fn wait_for_indexing_complete(&self, timeout: Duration) -> bool {
181        let (scanning, post_scan_active) = {
182            let guard = self.0.picker.read();
183            match &*guard {
184                Some(picker) => (
185                    Arc::clone(&picker.signals.scanning),
186                    Arc::clone(&picker.signals.post_scan_indexing_active),
187                ),
188                None => return true,
189            }
190        };
191
192        poll_until(timeout, || {
193            !scanning.load(std::sync::atomic::Ordering::Acquire)
194                && !post_scan_active.load(std::sync::atomic::Ordering::Acquire)
195        })
196    }
197
198    /// Trigger a full filesystem rescan without blocking the caller.
199    /// Performs a safe async rescan. Guarantees only single active rescan per picker.
200    /// If many rescans requested the last one guaranteed to be finished.
201    pub fn trigger_full_rescan_async(&self, shared_frecency: &SharedFrecency) -> Result<(), Error> {
202        match ScanJob::new_rescan(self, shared_frecency)? {
203            Some(job) => {
204                job.spawn();
205            }
206            None => {
207                // we can not abort the ongoing sync, but if the events
208                if let Ok(guard) = self.read()
209                    && let Some(picker) = guard.as_ref()
210                {
211                    picker
212                        .scan_signals()
213                        .rescan_pending
214                        .store(true, std::sync::atomic::Ordering::Release);
215                    tracing::info!(
216                        "Full rescan requested while another scan is active — \
217                         deferred via rescan_pending flag"
218                    );
219                }
220            }
221        }
222        Ok(())
223    }
224
225    /// Subscribe to filesystem changes matching `pattern`.
226    ///
227    /// Patterns may be base-relative globs (./ works), exact paths inside the indexed
228    /// tree, or existing directories. An empty pattern watches the whole tree.
229    ///
230    /// Events are debounced and submitted in batches per 100-ms window at most 128 events.
231    /// Gitignored and other ignored files are never triggering watcher.
232    pub fn watch(
233        &self,
234        pattern: &str,
235        options: WatchOptions,
236        callback: impl Fn(WatchId, &[WatchEvent]) + Send + Sync + 'static,
237    ) -> Result<WatchId, Error> {
238        let (base_path, has_watcher, watcher_ready) = {
239            let guard = self.read()?;
240            let picker = guard.as_ref().ok_or(Error::FilePickerMissing)?;
241
242            (
243                picker.base_path().to_path_buf(),
244                picker.has_watcher(),
245                picker.is_watcher_ready(),
246            )
247        };
248
249        if !has_watcher {
250            return Err(Error::WatcherDisabled);
251        }
252        if !watcher_ready {
253            return Err(Error::WatcherNotReady);
254        }
255
256        self.0
257            .watchers
258            .subscribe(&base_path, pattern, options, Box::new(callback))
259    }
260
261    /// Remove a watch subscription. Returns `true` if the id was active.
262    pub fn unwatch(&self, id: WatchId) -> bool {
263        self.0.watchers.unsubscribe(id)
264    }
265
266    /// Return whether a watch subscription is active.
267    pub fn is_watch_active(&self, id: WatchId) -> bool {
268        self.0.watchers.contains(id)
269    }
270
271    /// Remove every subscription without waiting for an executing callback.
272    pub fn shutdown_watches(&self) {
273        self.0.watchers.shutdown();
274    }
275
276    /// Remove every subscription and wait for an executing callback.
277    /// When called by that callback, it does not wait on itself.
278    pub fn shutdown_watches_and_wait(&self) {
279        self.0.watchers.shutdown_and_wait();
280    }
281
282    pub(crate) fn rebase_watches(&self, base_path: &Path) {
283        self.0.watchers.rebase(base_path);
284    }
285
286    pub(crate) fn watch_registry(&self) -> &Arc<WatchRegistry> {
287        &self.0.watchers
288    }
289
290    /// Refresh git statuses for all indexed files
291    #[tracing::instrument(level = "info", skip_all)]
292    pub fn refresh_git_status(&self, shared_frecency: &SharedFrecency) -> Result<usize, Error> {
293        use tracing::debug;
294
295        let git_status = {
296            let git_root = {
297                let guard = self.read()?;
298                let Some(ref picker) = *guard else {
299                    return Err(Error::FilePickerMissing);
300                };
301                picker.git_root().map(|p| p.to_path_buf())
302            };
303
304            debug!(?git_root, "Refreshing git status for picker");
305
306            if let Some(ref root) = git_root {
307                wait_for_git_index_lock_release(root);
308            }
309
310            GitStatusCache::read_git_status(
311                git_root.as_deref(),
312                &mut crate::git::default_status_options(),
313            )
314        };
315
316        let mut guard = self.write()?;
317        let picker = guard.as_mut().ok_or(Error::FilePickerMissing)?;
318
319        let statuses_count = if let Some(git_status) = git_status {
320            let count = git_status.statuses_len();
321            picker.update_git_statuses(git_status, shared_frecency)?;
322            count
323        } else {
324            0
325        };
326
327        Ok(statuses_count)
328    }
329
330    /// Recompute and apply git status for a specific set of paths.
331    pub fn update_git_status_for_paths(
332        &self,
333        paths: &[PathBuf],
334        shared_frecency: &SharedFrecency,
335    ) -> Result<(), Error> {
336        if paths.is_empty() {
337            return Ok(());
338        }
339
340        let git_root = {
341            let guard = self.read()?;
342            let Some(ref picker) = *guard else {
343                return Err(Error::FilePickerMissing);
344            };
345            picker.git_root().map(|p| p.to_path_buf())
346        };
347        let Some(git_root) = git_root else {
348            return Ok(());
349        };
350
351        wait_for_git_index_lock_release(&git_root);
352
353        let repo = Repository::open(&git_root)?;
354        let status = GitStatusCache::git_status_for_paths(&repo, paths)?;
355
356        let mut guard = self.write()?;
357        let picker = guard.as_mut().ok_or(Error::FilePickerMissing)?;
358        picker.update_git_statuses(status, shared_frecency)
359    }
360}
361
362/// Thread-safe shared handle to an LMDB-backed store. A disabled (`noop`)
363/// instance silently ignores writes. See the [`SharedFrecency`] and
364/// [`SharedQueryTracker`] aliases.
365///
366/// `LmdbStore` is intentionally crate-private, so the store type is sealed:
367/// only `FrecencyTracker` / `QueryTracker` can ever instantiate this.
368#[allow(private_bounds)]
369pub struct SharedDb<T: LmdbStore> {
370    inner: Arc<RwLock<Option<T>>>,
371    enabled: bool,
372}
373
374// Hand-written to avoid a spurious `T: Clone` bound — `Arc` is always `Clone`.
375impl<T: LmdbStore> Clone for SharedDb<T> {
376    fn clone(&self) -> Self {
377        Self {
378            inner: self.inner.clone(),
379            enabled: self.enabled,
380        }
381    }
382}
383
384impl<T: LmdbStore> Default for SharedDb<T> {
385    fn default() -> Self {
386        Self {
387            inner: Arc::new(RwLock::new(None)),
388            enabled: true,
389        }
390    }
391}
392
393impl<T: LmdbStore> std::fmt::Debug for SharedDb<T> {
394    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
395        f.debug_tuple("SharedDb").field(&T::LABEL).finish()
396    }
397}
398
399#[allow(private_bounds)]
400impl<T: LmdbStore> SharedDb<T> {
401    /// Creates a disabled instance that silently ignores all writes.
402    pub fn noop() -> Self {
403        Self {
404            inner: Arc::new(RwLock::new(None)),
405            enabled: false,
406        }
407    }
408
409    pub fn read(&self) -> Result<RwLockReadGuard<'_, Option<T>>, Error> {
410        self.inner.read().map_err(|_| Error::AcquireFrecencyLock)
411    }
412
413    pub fn write(&self) -> Result<RwLockWriteGuard<'_, Option<T>>, Error> {
414        self.inner.write().map_err(|_| Error::AcquireFrecencyLock)
415    }
416
417    /// Initialize the store + spawn GC in the background. No-op when disabled.
418    pub fn init(&self, tracker: T) -> Result<(), Error> {
419        if !self.enabled {
420            return Ok(());
421        }
422
423        {
424            let mut guard = self.write()?;
425            *guard = Some(tracker);
426        }
427
428        // GC holds a read guard on this lock, so destroy / re-init wait won't race
429        spawn_lmdb_gc(self.inner.clone());
430        Ok(())
431    }
432
433    /// Drop the in-memory tracker and delete the on-disk database directory.
434    ///
435    /// Acquires the write lock, ensuring all readers (including any active mmap
436    /// access) are finished before the LMDB environment is closed and the files
437    /// are removed.
438    ///
439    /// Returns `Ok(Some(path))` with the deleted path, or `Ok(None)` if no tracker was initialized.
440    pub fn destroy(&self) -> Result<Option<PathBuf>, Error> {
441        let mut guard = self.write()?;
442        let Some(tracker) = guard.take() else {
443            return Ok(None);
444        };
445        let db_path = tracker.env().path().to_path_buf();
446        // Drop closes the LMDB env and unmaps the files
447        drop(tracker);
448        drop(guard);
449        std::fs::remove_dir_all(&db_path).map_err(|source| Error::RemoveDbDir {
450            path: db_path.clone(),
451            source,
452        })?;
453        Ok(Some(db_path))
454    }
455}
456
457/// Thread-safe shared handle to the [`FrecencyTracker`] instance.
458pub type SharedFrecency = SharedDb<FrecencyTracker>;
459
460/// Thread-safe shared handle to the [`QueryTracker`] instance.
461pub type SharedQueryTracker = SharedDb<QueryTracker>;