use crate::background_indexer::{BackgroundIndexer, IndexerState};
use crate::cache::CacheManager;
use crate::errors::ReflexError;
use crate::indexer::Indexer;
use crate::models::{IndexConfig, LOCK_WAIT_FOREVER};
use crate::query::UpdatePlan;
use anyhow::Result;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::SystemTime;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UpdateOptions {
pub spawn_symbol_pass: bool,
pub self_heal_version: bool,
pub progress: bool,
}
impl UpdateOptions {
pub fn cli() -> Self {
Self {
spawn_symbol_pass: true,
self_heal_version: true,
progress: true,
}
}
pub fn server() -> Self {
Self {
spawn_symbol_pass: true,
self_heal_version: false,
progress: false,
}
}
pub fn library() -> Self {
Self {
spawn_symbol_pass: false,
self_heal_version: false,
progress: false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Updated {
Nothing,
Paths(usize),
Index { changed: usize },
Built,
Skipped(String),
}
impl Updated {
pub fn wrote(&self) -> bool {
matches!(self, Self::Paths(_) | Self::Index { .. } | Self::Built)
}
}
fn root_mutex(root: &Path) -> Arc<Mutex<()>> {
static MUTEXES: OnceLock<Mutex<HashMap<PathBuf, Arc<Mutex<()>>>>> = OnceLock::new();
let key = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let mut map = MUTEXES
.get_or_init(|| Mutex::new(HashMap::new()))
.lock()
.unwrap_or_else(|e| e.into_inner());
Arc::clone(map.entry(key).or_default())
}
type Attempt = (UpdatePlan, Vec<(PathBuf, Option<(u64, SystemTime)>)>);
fn failed_attempts() -> &'static Mutex<HashMap<PathBuf, Attempt>> {
static FAILED: OnceLock<Mutex<HashMap<PathBuf, Attempt>>> = OnceLock::new();
FAILED.get_or_init(|| Mutex::new(HashMap::new()))
}
fn stat_of(root: &Path, plan: &UpdatePlan) -> Attempt {
let paths: &[PathBuf] = match plan {
UpdatePlan::Paths(p) | UpdatePlan::Full(p) => p,
_ => &[],
};
let stats = paths
.iter()
.map(|p| {
let md = std::fs::symlink_metadata(root.join(p)).ok();
(
p.clone(),
md.and_then(|m| Some((m.len(), m.modified().ok()?))),
)
})
.collect();
(plan.clone(), stats)
}
pub fn update_if_stale(cache: &CacheManager, opts: &UpdateOptions) -> Result<Updated> {
let root = cache.workspace_root();
let mutex = root_mutex(&root);
let _one_at_a_time = mutex.lock().unwrap_or_else(|e| e.into_inner());
if !cache.exists() {
build(cache, &root, opts)?;
return Ok(Updated::Built);
}
let planned = match crate::query::plan_update(cache) {
Ok(planned) => planned,
Err(e) => return Ok(Updated::Skipped(format!("freshness check failed: {e}"))),
};
let plan = planned.plan.clone();
let key = root.canonicalize().unwrap_or_else(|_| root.clone());
match &plan {
UpdatePlan::Fresh => {
if let Ok(mut failed) = failed_attempts().lock() {
failed.remove(&key);
}
return Ok(Updated::Nothing);
}
UpdatePlan::Unknown(reason) => return Ok(Updated::Skipped(reason.clone())),
UpdatePlan::Foreign(reason) if !opts.self_heal_version => {
return Ok(Updated::Skipped(reason.clone()));
}
_ => {}
}
let attempt = stat_of(&root, &plan);
if let Ok(failed) = failed_attempts().lock()
&& failed.get(&key) == Some(&attempt)
{
return Ok(Updated::Skipped(
"an automatic update of these files did not make the index fresh; \
run `rfx index` to rebuild it"
.to_string(),
));
}
let result = match &plan {
UpdatePlan::Foreign(_) => {
crate::query::invalidate_caches(&root);
match cache.clear() {
Ok(()) => build(cache, &root, opts).map(|()| Updated::Built),
Err(e) => Err(e),
}
}
UpdatePlan::Paths(paths) => config(cache).and_then(|config| {
with_symbol_pass_retry(cache, || {
Indexer::new(CacheManager::new(&root), config.clone()).update_paths(&root, paths)
})
.map(|_| Updated::Paths(paths.len()))
}),
UpdatePlan::Full(_) => config(cache).and_then(|config| {
if opts.progress {
eprintln!("Updating the index …");
}
with_symbol_pass_retry(cache, || {
Indexer::new(CacheManager::new(&root), config.clone()).index(&root, false)
})
.map(|stats| Updated::Index {
changed: stats.new_files + stats.modified_files + stats.deleted_files,
})
}),
UpdatePlan::Fresh | UpdatePlan::Unknown(_) => unreachable!("returned above"),
};
let updated = match result {
Ok(updated) => updated,
Err(e) => return Ok(Updated::Skipped(describe(&e))),
};
if crate::query::settle_update(cache, &planned) {
if let Ok(mut failed) = failed_attempts().lock() {
failed.remove(&key);
}
restart_symbol_pass(cache, &root, opts, &updated);
return Ok(updated);
}
match crate::query::update_plan(cache) {
Ok(UpdatePlan::Fresh) => {
if let Ok(mut failed) = failed_attempts().lock() {
failed.remove(&key);
}
}
Ok(after) if after == plan => {
if let Ok(mut failed) = failed_attempts().lock() {
failed.insert(key, attempt);
}
}
_ => {}
}
restart_symbol_pass(cache, &root, opts, &updated);
Ok(updated)
}
fn config(cache: &CacheManager) -> Result<IndexConfig> {
let mut config = cache.effective_index_config(&[])?;
config.lock_wait_secs = LOCK_WAIT_FOREVER;
Ok(config)
}
fn build(cache: &CacheManager, root: &Path, opts: &UpdateOptions) -> Result<()> {
let config = config(cache)?;
if opts.progress {
eprintln!("Building the index for {} …", root.display());
}
with_symbol_pass_retry(cache, || {
Indexer::new(CacheManager::new(root), config.clone()).index(root, false)
})?;
restart_symbol_pass(cache, root, opts, &Updated::Built);
Ok(())
}
fn with_symbol_pass_retry<T>(cache: &CacheManager, mut f: impl FnMut() -> Result<T>) -> Result<T> {
let processed = || {
BackgroundIndexer::get_status(cache.path())
.ok()
.flatten()
.map(|s| s.processed_files)
};
let mut last = processed();
loop {
match f() {
Err(e)
if matches!(
e.downcast_ref::<ReflexError>(),
Some(ReflexError::SymbolIndexingInProgress { .. })
) =>
{
let now = processed();
if now > last {
last = now;
continue;
}
return Err(e);
}
other => return other,
}
}
}
fn restart_symbol_pass(cache: &CacheManager, root: &Path, opts: &UpdateOptions, updated: &Updated) {
if !opts.spawn_symbol_pass || !updated.wrote() || BackgroundIndexer::is_running(cache.path()) {
return;
}
let cancelled = BackgroundIndexer::get_status(cache.path())
.ok()
.flatten()
.is_some_and(|s| s.state == IndexerState::Cancelled);
if (matches!(updated, Updated::Built | Updated::Index { .. }) || cancelled)
&& let Err(e) = BackgroundIndexer::spawn_detached(root)
{
log::warn!("Could not start the symbol pass: {e}");
}
}
fn describe(e: &anyhow::Error) -> String {
format!("automatic index update failed: {e}")
}