1use crate::background_indexer::{BackgroundIndexer, IndexerState};
17use crate::cache::CacheManager;
18use crate::errors::ReflexError;
19use crate::indexer::Indexer;
20use crate::models::{IndexConfig, LOCK_WAIT_FOREVER};
21use crate::query::UpdatePlan;
22use anyhow::Result;
23use std::collections::HashMap;
24use std::path::{Path, PathBuf};
25use std::sync::{Arc, Mutex, OnceLock};
26use std::time::SystemTime;
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct UpdateOptions {
31 pub spawn_symbol_pass: bool,
35 pub self_heal_version: bool,
39 pub progress: bool,
42}
43
44impl UpdateOptions {
45 pub fn cli() -> Self {
47 Self {
48 spawn_symbol_pass: true,
49 self_heal_version: true,
50 progress: true,
51 }
52 }
53
54 pub fn server() -> Self {
56 Self {
57 spawn_symbol_pass: true,
58 self_heal_version: false,
59 progress: false,
60 }
61 }
62
63 pub fn library() -> Self {
65 Self {
66 spawn_symbol_pass: false,
67 self_heal_version: false,
68 progress: false,
69 }
70 }
71}
72
73#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum Updated {
76 Nothing,
78 Paths(usize),
80 Index { changed: usize },
82 Built,
84 Skipped(String),
87}
88
89impl Updated {
90 pub fn wrote(&self) -> bool {
92 matches!(self, Self::Paths(_) | Self::Index { .. } | Self::Built)
93 }
94}
95
96fn root_mutex(root: &Path) -> Arc<Mutex<()>> {
99 static MUTEXES: OnceLock<Mutex<HashMap<PathBuf, Arc<Mutex<()>>>>> = OnceLock::new();
100 let key = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
101 let mut map = MUTEXES
102 .get_or_init(|| Mutex::new(HashMap::new()))
103 .lock()
104 .unwrap_or_else(|e| e.into_inner());
105 Arc::clone(map.entry(key).or_default())
106}
107
108type Attempt = (UpdatePlan, Vec<(PathBuf, Option<(u64, SystemTime)>)>);
112
113fn failed_attempts() -> &'static Mutex<HashMap<PathBuf, Attempt>> {
114 static FAILED: OnceLock<Mutex<HashMap<PathBuf, Attempt>>> = OnceLock::new();
115 FAILED.get_or_init(|| Mutex::new(HashMap::new()))
116}
117
118fn stat_of(root: &Path, plan: &UpdatePlan) -> Attempt {
119 let paths: &[PathBuf] = match plan {
120 UpdatePlan::Paths(p) | UpdatePlan::Full(p) => p,
121 _ => &[],
122 };
123 let stats = paths
124 .iter()
125 .map(|p| {
126 let md = std::fs::symlink_metadata(root.join(p)).ok();
127 (
128 p.clone(),
129 md.and_then(|m| Some((m.len(), m.modified().ok()?))),
130 )
131 })
132 .collect();
133 (plan.clone(), stats)
134}
135
136pub fn update_if_stale(cache: &CacheManager, opts: &UpdateOptions) -> Result<Updated> {
139 let root = cache.workspace_root();
140 let mutex = root_mutex(&root);
141 let _one_at_a_time = mutex.lock().unwrap_or_else(|e| e.into_inner());
142
143 if !cache.exists() {
144 build(cache, &root, opts)?;
145 return Ok(Updated::Built);
146 }
147
148 let planned = match crate::query::plan_update(cache) {
151 Ok(planned) => planned,
152 Err(e) => return Ok(Updated::Skipped(format!("freshness check failed: {e}"))),
153 };
154 let plan = planned.plan.clone();
155 let key = root.canonicalize().unwrap_or_else(|_| root.clone());
156 match &plan {
157 UpdatePlan::Fresh => {
158 if let Ok(mut failed) = failed_attempts().lock() {
159 failed.remove(&key);
160 }
161 return Ok(Updated::Nothing);
162 }
163 UpdatePlan::Unknown(reason) => return Ok(Updated::Skipped(reason.clone())),
164 UpdatePlan::Foreign(reason) if !opts.self_heal_version => {
165 return Ok(Updated::Skipped(reason.clone()));
166 }
167 _ => {}
168 }
169
170 let attempt = stat_of(&root, &plan);
171 if let Ok(failed) = failed_attempts().lock()
172 && failed.get(&key) == Some(&attempt)
173 {
174 return Ok(Updated::Skipped(
175 "an automatic update of these files did not make the index fresh; \
176 run `rfx index` to rebuild it"
177 .to_string(),
178 ));
179 }
180
181 let result = match &plan {
182 UpdatePlan::Foreign(_) => {
183 crate::query::invalidate_caches(&root);
184 match cache.clear() {
185 Ok(()) => build(cache, &root, opts).map(|()| Updated::Built),
186 Err(e) => Err(e),
187 }
188 }
189 UpdatePlan::Paths(paths) => config(cache).and_then(|config| {
190 with_symbol_pass_retry(cache, || {
191 Indexer::new(CacheManager::new(&root), config.clone()).update_paths(&root, paths)
192 })
193 .map(|_| Updated::Paths(paths.len()))
194 }),
195 UpdatePlan::Full(_) => config(cache).and_then(|config| {
196 if opts.progress {
197 eprintln!("Updating the index …");
198 }
199 with_symbol_pass_retry(cache, || {
200 Indexer::new(CacheManager::new(&root), config.clone()).index(&root, false)
201 })
202 .map(|stats| Updated::Index {
203 changed: stats.new_files + stats.modified_files + stats.deleted_files,
204 })
205 }),
206 UpdatePlan::Fresh | UpdatePlan::Unknown(_) => unreachable!("returned above"),
207 };
208
209 let updated = match result {
210 Ok(updated) => updated,
211 Err(e) => return Ok(Updated::Skipped(describe(&e))),
212 };
213
214 if crate::query::settle_update(cache, &planned) {
217 if let Ok(mut failed) = failed_attempts().lock() {
218 failed.remove(&key);
219 }
220 restart_symbol_pass(cache, &root, opts, &updated);
221 return Ok(updated);
222 }
223 match crate::query::update_plan(cache) {
224 Ok(UpdatePlan::Fresh) => {
225 if let Ok(mut failed) = failed_attempts().lock() {
226 failed.remove(&key);
227 }
228 }
229 Ok(after) if after == plan => {
230 if let Ok(mut failed) = failed_attempts().lock() {
231 failed.insert(key, attempt);
232 }
233 }
234 _ => {}
235 }
236
237 restart_symbol_pass(cache, &root, opts, &updated);
238 Ok(updated)
239}
240
241fn config(cache: &CacheManager) -> Result<IndexConfig> {
243 let mut config = cache.effective_index_config(&[])?;
244 config.lock_wait_secs = LOCK_WAIT_FOREVER;
245 Ok(config)
246}
247
248fn build(cache: &CacheManager, root: &Path, opts: &UpdateOptions) -> Result<()> {
249 let config = config(cache)?;
250 if opts.progress {
251 eprintln!("Building the index for {} …", root.display());
252 }
253 with_symbol_pass_retry(cache, || {
254 Indexer::new(CacheManager::new(root), config.clone()).index(root, false)
255 })?;
256 restart_symbol_pass(cache, root, opts, &Updated::Built);
257 Ok(())
258}
259
260fn with_symbol_pass_retry<T>(cache: &CacheManager, mut f: impl FnMut() -> Result<T>) -> Result<T> {
263 let processed = || {
264 BackgroundIndexer::get_status(cache.path())
265 .ok()
266 .flatten()
267 .map(|s| s.processed_files)
268 };
269 let mut last = processed();
270 loop {
271 match f() {
272 Err(e)
273 if matches!(
274 e.downcast_ref::<ReflexError>(),
275 Some(ReflexError::SymbolIndexingInProgress { .. })
276 ) =>
277 {
278 let now = processed();
279 if now > last {
280 last = now;
281 continue;
282 }
283 return Err(e);
284 }
285 other => return other,
286 }
287 }
288}
289
290fn restart_symbol_pass(cache: &CacheManager, root: &Path, opts: &UpdateOptions, updated: &Updated) {
293 if !opts.spawn_symbol_pass || !updated.wrote() || BackgroundIndexer::is_running(cache.path()) {
294 return;
295 }
296 let cancelled = BackgroundIndexer::get_status(cache.path())
297 .ok()
298 .flatten()
299 .is_some_and(|s| s.state == IndexerState::Cancelled);
300 if (matches!(updated, Updated::Built | Updated::Index { .. }) || cancelled)
301 && let Err(e) = BackgroundIndexer::spawn_detached(root)
302 {
303 log::warn!("Could not start the symbol pass: {e}");
304 }
305}
306
307fn describe(e: &anyhow::Error) -> String {
309 format!("automatic index update failed: {e}")
310}