diff --git a/crates/ide-core/Cargo.toml b/crates/ide-core/Cargo.toml index 29364ce7a..a3f341cf5 100644 --- a/crates/ide-core/Cargo.toml +++ b/crates/ide-core/Cargo.toml @@ -27,4 +27,4 @@ libc = "0.2" [target.'cfg(windows)'.dependencies] dirs.workspace = true tracing.workspace = true -windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] } +windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] } diff --git a/crates/ide-core/src/lib.rs b/crates/ide-core/src/lib.rs index 6649e236c..7f9981bf8 100644 --- a/crates/ide-core/src/lib.rs +++ b/crates/ide-core/src/lib.rs @@ -19,6 +19,7 @@ pub mod ipc_path; pub mod java_runtime; pub mod jsonc; pub mod memory; +pub mod network_path; pub mod output_encoding; pub mod output_rate; pub mod platform; diff --git a/crates/ide-core/src/network_path.rs b/crates/ide-core/src/network_path.rs new file mode 100644 index 000000000..873d9d507 --- /dev/null +++ b/crates/ide-core/src/network_path.rs @@ -0,0 +1,53 @@ +//! Whether a path is on a network file system, where every stat is a round trip to a server. + +use std::path::{Component, Path, Prefix}; + +/// A UNC path (`\\server\share`, `\\wsl.localhost\…`) or a drive letter mapped to a network +/// share (`Z:\`). Always `false` off Windows: there a mount point is not visible in the path. +pub fn is_network_path(path: &Path) -> bool { + match path.components().next() { + Some(Component::Prefix(prefix)) => match prefix.kind() { + Prefix::UNC(..) | Prefix::VerbatimUNC(..) => true, + Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => is_remote_drive(letter), + _ => false, + }, + _ => false, + } +} + +#[cfg(windows)] +fn is_remote_drive(letter: u8) -> bool { + use windows_sys::Win32::Storage::FileSystem::GetDriveTypeW; + /// `DRIVE_REMOTE` (WindowsProgramming). + const DRIVE_REMOTE: u32 = 4; + let root = [u16::from(letter), u16::from(b':'), u16::from(b'\\'), 0]; + // SAFETY: `root` is a NUL-terminated wide string that outlives the call. + unsafe { GetDriveTypeW(root.as_ptr()) == DRIVE_REMOTE } +} + +#[cfg(not(windows))] +fn is_remote_drive(_letter: u8) -> bool { + false +} + +#[cfg(test)] +mod tests { + use super::is_network_path; + use std::path::Path; + + #[test] + fn unc_paths_are_on_the_network() { + if cfg!(windows) { + assert!(is_network_path(Path::new(r"\\server\share\repo"))); + assert!(is_network_path(Path::new(r"\\?\UNC\server\share\repo"))); + assert!(is_network_path(Path::new(r"\\wsl.localhost\Ubuntu\home"))); + } + assert!(!is_network_path(Path::new("relative/path"))); + } + + #[test] + fn a_local_directory_is_not() { + let dir = std::env::temp_dir(); + assert!(!is_network_path(&dir), "{}", dir.display()); + } +} diff --git a/crates/ide-index/src/worker.rs b/crates/ide-index/src/worker.rs index 9e4e746d3..ea39ffe43 100644 --- a/crates/ide-index/src/worker.rs +++ b/crates/ide-index/src/worker.rs @@ -182,7 +182,9 @@ impl Shared { let snapshot_started = Instant::now(); let fast = self.try_fast_start(); let snapshot_elapsed = snapshot_started.elapsed(); - if let Err(reason) = fast { + if fast.is_err() && self.is_cancelled() { + // Closing: the stat loops stopped early, and a fallback walk would only stall the close. + } else if let Err(reason) = fast { let snapshot_guard = SystemTime::now(); let walk_started = Instant::now(); let found = self.walk_roots(None); @@ -276,13 +278,24 @@ impl Shared { } let root = filter.root(); let validation_started = Instant::now(); - for i in 0..snapshot.dirs_len() { - let rel = snapshot.dir(i); - let path = if rel.is_empty() { root.to_owned() } else { root.join(rel) }; - let Ok(meta) = std::fs::symlink_metadata(&path) else { return Err("directory changed") }; - if !meta.is_dir() || mtime_of(&meta) != snapshot.dir_mtime(i) { - return Err("directory changed"); - } + // In parallel: on a network share each stat is a round trip. + let cancelled = &self.cancelled; + let dirs_valid = INDEX_POOL.install(|| { + (0..snapshot.dirs_len()).into_par_iter().all(|i| { + if cancelled.load(Ordering::Relaxed) { + return false; + } + let rel = snapshot.dir(i); + let path = if rel.is_empty() { root.to_owned() } else { root.join(rel) }; + std::fs::symlink_metadata(&path) + .is_ok_and(|meta| meta.is_dir() && mtime_of(&meta) == snapshot.dir_mtime(i)) + }) + }); + if self.is_cancelled() { + return Err("cancelled"); + } + if !dirs_valid { + return Err("directory changed"); } let external = crate::store::external_ignore_candidates(root); let saved_external: Vec<&str> = (0..snapshot.ignore_len()) @@ -309,28 +322,56 @@ impl Shared { } let validation_elapsed = validation_started.elapsed(); let build_started = Instant::now(); - let entries: Vec)>> = INDEX_POOL.install(|| { - (0..snapshot.len()) - .into_par_iter() - .map(|i| { - let path = root.join(snapshot.rel(i)); - let meta = std::fs::symlink_metadata(&path).ok()?; - if !meta.is_file() || mtime_of(&meta) != snapshot.mtime(i) || meta.len() != snapshot.size(i) { + // Files are checked against their folder's listing, one per folder: on Windows the + // listing carries each entry's metadata, so a share costs a round trip per folder + // instead of one per file. Elsewhere `DirEntry::metadata` is the same `lstat`. + let mut by_dir: HashMap<&str, Vec> = HashMap::new(); + for i in 0..snapshot.len() { + let rel = snapshot.rel(i); + if !safe_rel(rel) { + return Err("file changed"); + } + let dir = rel.rfind('/').map_or("", |at| &rel[..at]); + by_dir.entry(dir).or_default().push(i); + } + let by_dir: Vec<(&str, Vec)> = by_dir.into_iter().collect(); + let entries: Option)>>> = INDEX_POOL.install(|| { + by_dir + .par_iter() + .map(|(dir, files)| { + if cancelled.load(Ordering::Relaxed) { return None; } - Some(snapshot.entry(i, root)) + let path = if dir.is_empty() { root.to_owned() } else { root.join(dir) }; + let listed: HashMap = std::fs::read_dir(&path) + .ok()? + .filter_map(|e| { + let e = e.ok()?; + Some((e.file_name(), e.metadata().ok()?)) + }) + .collect(); + files + .iter() + .map(|&i| { + let rel = snapshot.rel(i); + let name = rel.rfind('/').map_or(rel, |at| &rel[at + 1..]); + let meta = listed.get(std::ffi::OsStr::new(name))?; + if !meta.is_file() || mtime_of(meta) != snapshot.mtime(i) || meta.len() != snapshot.size(i) + { + return None; + } + Some(snapshot.entry(i, root)) + }) + .collect::>>() }) .collect() }); let built = build_started.elapsed(); - if entries.iter().any(Option::is_none) { - return Err("file changed"); - } - let validated = entries; - let mut entries = Vec::with_capacity(validated.len()); - for entry in validated { - entries.push(entry.expect("validated above")); + if self.is_cancelled() { + return Err("cancelled"); } + let Some(entries) = entries else { return Err("file changed") }; + let entries: Vec<(FileEntry, Vec)> = entries.into_iter().flatten().collect(); let dirs: Vec<(Box, PathBuf, u32)> = (0..snapshot.dirs_len()) .filter_map(|i| { let rel = snapshot.dir(i); @@ -1438,6 +1479,32 @@ mod metric_tests { assert_eq!(index_files(&shared, found[..1].iter(), true).symbol_extractions, 1); } + #[test] + fn warm_start_checks_files_against_their_folder_listing() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("project"); + std::fs::create_dir_all(root.join("src/deep")).unwrap(); + let root = dunce::canonicalize(root).unwrap(); + std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap(); + std::fs::write(root.join("src/lib.rs"), "pub fn a() {}\n").unwrap(); + std::fs::write(root.join("src/deep/b.rs"), "pub fn b() {}\n").unwrap(); + let cache = dir.path().join("cache"); + let open = || { + let mut index = shared(&root); + index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap()); + index + }; + open().scan(None, &[], None, SystemTime::now()).unwrap(); + let index = open(); + assert_eq!(index.try_fast_start(), Ok(())); + assert_eq!(index.data.read().file_count, 3); + // Same folder mtime, a different size: only the listing's metadata can tell. + let dir_mtime = std::fs::metadata(root.join("src/deep")).unwrap().modified().unwrap(); + std::fs::write(root.join("src/deep/b.rs"), "pub fn b() { /* longer */ }\n").unwrap(); + std::fs::File::open(root.join("src/deep")).and_then(|f| f.set_modified(dir_mtime)).ok(); + assert_eq!(open().try_fast_start(), Err("file changed")); + } + #[test] fn reopened_cache_counts_metadata_reuse() { let dir = tempfile::tempdir().unwrap(); @@ -1533,7 +1600,8 @@ mod metric_tests { index.run(true); }); assert_eq!(index.parsed.load(Ordering::Relaxed), 0); - assert_eq!(index.data.read().file_count, 1); + // The project is closing: its validation stops instead of statting the rest of a tree. + assert_eq!(index.data.read().file_count, 0); assert_eq!(count.load(Ordering::Relaxed), 0); } diff --git a/crates/ide-vcs/src/status.rs b/crates/ide-vcs/src/status.rs index e79e5839f..b71fd2d19 100644 --- a/crates/ide-vcs/src/status.rs +++ b/crates/ide-vcs/src/status.rs @@ -157,8 +157,32 @@ impl DiskSpelling { type Entries = (BTreeMap, HashSet); +/// Stat checks for a work tree on a network share: mtime and size only. +/// +/// A share's index is usually written by git on the server too, whose inode, owner and change +/// time never match what Windows reports for the same file (inode 0, creation time). Every +/// tracked file would then fail the stat check and be read in full to compare its content, +/// over the network, on each status; and the index written back would fail the same way for +/// git on the server. +const NETWORK_STAT_CONFIG: [(&str, &str); 2] = [("core.checkStat", "minimal"), ("core.trustCTime", "false")]; + +fn on_network(r: &Repo) -> bool { + ide_core::network_path::is_network_path(r.root()) +} + fn gix_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult { - let repo = r.gix()?; + let mut repo = r.gix()?; + if on_network(r) { + use gix::config::tree::{Core, Key}; + let mut config = repo.config_snapshot_mut(); + let keys: [&'static dyn Key; 2] = [&Core::CHECK_STAT, &Core::TRUST_C_TIME]; + for (key, (_, value)) in keys.into_iter().zip(NETWORK_STAT_CONFIG) { + if let Err(e) = config.set_value(key, value) { + tracing::debug!("{}: {e}", key.logical_name()); + } + } + config.commit().map_err(gx)?; + } let mut map: BTreeMap = BTreeMap::new(); let mut conflicts: HashSet = HashSet::new(); @@ -273,12 +297,22 @@ fn read_only() -> [(&'static str, &'static std::ffi::OsStr); 1] { [("GIT_OPTIONAL_LOCKS", std::ffi::OsStr::new("0"))] } +/// `-c` options for [`NETWORK_STAT_CONFIG`] when the work tree is on a network share. +fn network_args(r: &Repo) -> Vec { + if !on_network(r) { + return Vec::new(); + } + NETWORK_STAT_CONFIG.iter().flat_map(|(key, value)| ["-c".to_owned(), format!("{key}={value}")]).collect() +} + /// `git status --porcelain=v2`: what git lists, unreadable directories skipped. /// In Restricted Mode git compares content without the repository's clean/process /// filters and doesn't ask submodules for their own status (which runs their config). fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult { let overrides = crate::cli::filter_overrides(r.root(), &ide_core::CancellationToken::new())?; let mut args: Vec<&str> = overrides.iter().map(String::as_str).collect(); + let network = network_args(r); + args.extend(network.iter().map(String::as_str)); args.extend(["status", "--porcelain=v2", "-z", "--untracked-files=all"]); if !crate::execution_allowed() { args.push("--ignore-submodules=dirty"); @@ -292,6 +326,8 @@ fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult { fn cli_status_paths(r: &Repo, ignored: &IgnoredNames, paths: &[String]) -> IdeResult { let overrides = crate::cli::filter_overrides(r.root(), &ide_core::CancellationToken::new())?; let mut args: Vec<&str> = overrides.iter().map(String::as_str).collect(); + let network = network_args(r); + args.extend(network.iter().map(String::as_str)); args.extend(["--literal-pathspecs", "status", "--porcelain=v2", "-z", "--untracked-files=all"]); if !crate::execution_allowed() { args.push("--ignore-submodules=dirty"); diff --git a/crates/ide-vfs/tests/vfs.rs b/crates/ide-vfs/tests/vfs.rs index 2412d291e..d179974b8 100644 --- a/crates/ide-vfs/tests/vfs.rs +++ b/crates/ide-vfs/tests/vfs.rs @@ -314,16 +314,8 @@ fn wait_for(events: &Mutex>, pred: impl Fn(&[FsBatch]) -> bool) -> #[test] fn watcher_read_dir_reuses_its_ignore_rules() { let (_t, r) = root(); - write( - &r.join(".git/HEAD"), - "ref: refs/heads/main -", - ); - write( - &r.join(".gitignore"), - "*.log -", - ); + write(&r.join(".git/HEAD"), "ref: refs/heads/main\n"); + write(&r.join(".gitignore"), "*.log\n"); write(&r.join("sub/a.log"), "x"); write(&r.join("sub/b.txt"), "x"); let sink: SharedSink = Arc::new(|_| {}); @@ -342,11 +334,7 @@ fn watcher_read_dir_reuses_its_ignore_rules() { ); // The watcher's events keep the shared rules current. std::thread::sleep(Duration::from_millis(300)); - write( - &r.join(".gitignore"), - "*.txt -", - ); + write(&r.join(".gitignore"), "*.txt\n"); let deadline = Instant::now() + Duration::from_secs(10); loop { let now = ignored(watcher.read_dir(&r.join("sub"), &[]).unwrap());