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
15fn 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 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
43fn 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#[derive(Clone, Default)]
73pub struct SharedFilePicker(pub(crate) Arc<SharedPickerInner>);
74
75pub struct SharedPickerInner {
76 picker: parking_lot::RwLock<Option<FilePicker>>,
77 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#[derive(Clone)]
93pub(crate) struct WeakFilePicker(Weak<SharedPickerInner>);
94
95impl WeakFilePicker {
96 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 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 pub(crate) fn weaken(&self) -> WeakFilePicker {
134 WeakFilePicker(Arc::downgrade(&self.0))
135 }
136
137 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 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 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 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 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 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 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 pub fn unwatch(&self, id: WatchId) -> bool {
263 self.0.watchers.unsubscribe(id)
264 }
265
266 pub fn is_watch_active(&self, id: WatchId) -> bool {
268 self.0.watchers.contains(id)
269 }
270
271 pub fn shutdown_watches(&self) {
273 self.0.watchers.shutdown();
274 }
275
276 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 #[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 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#[allow(private_bounds)]
369pub struct SharedDb<T: LmdbStore> {
370 inner: Arc<RwLock<Option<T>>>,
371 enabled: bool,
372}
373
374impl<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 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 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 spawn_lmdb_gc(self.inner.clone());
430 Ok(())
431 }
432
433 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(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
457pub type SharedFrecency = SharedDb<FrecencyTracker>;
459
460pub type SharedQueryTracker = SharedDb<QueryTracker>;