using System.Reflection; using System.Runtime.ExceptionServices; using XFEToolBox.Client.Core.Search; namespace XFEToolBox.Test; public sealed class FileIndexServiceTests { [Test] public static void FileIndexWarmupNamesMustBeVerifiedBeforeTheyBecomeASnapshot() { var first = new FileSearchEntry(@"C:\scope\verified.txt", false); var vanished = new FileSearchEntry(@"C:\scope\vanished-during-mft-read.txt", false); var stale = new HashSet(StringComparer.OrdinalIgnoreCase); FileIndexService.TrackVerificationBatch(stale, [first, vanished], requiresVerification: true); Ensure(stale.Count == 2, "MFT preview entries must remain pending until a directory scan verifies them."); FileIndexService.TrackVerificationBatch(stale, [first], requiresVerification: false); Ensure(stale.SetEquals([vanished.FullPath]), "An unverified MFT path would be persisted as a complete snapshot."); var index = new FileSearchIndex(); index.AddOrUpdate([first, vanished]); index.RemovePaths(stale); Ensure(index.ContainsPath(first.FullPath) && !index.ContainsPath(vanished.FullPath), "Completed verification retained a stale native preview path."); } [Test] public static void FileIndexRestoresCacheWithoutStartingAnImmediateFullScan() => Run(async () => { using var temporary = new TemporarySearchTree(); var oldPath = Path.Combine(temporary.Root, "cached-before-exit.txt"); var newPath = Path.Combine(temporary.Root, "created-while-closed.txt"); File.WriteAllText(oldPath, "cached"); await using (var first = new FileIndexService(temporary.Options)) await first.RebuildAsync(); File.Delete(oldPath); File.WriteAllText(newPath, "offline change"); await using var restored = new FileIndexService(temporary.Options); await restored.StartAsync(); Ensure(restored.Status is { IsScanning: false, UsingCachedSnapshot: true, VerificationPending: true }, "A valid cache must be reused without immediately starting a full scan."); Ensure(restored.Index.ContainsPath(oldPath), "Restoring the cache did not make its saved entries searchable."); await Task.Delay(150); Ensure(!restored.Status.IsScanning && !restored.Index.ContainsPath(newPath), "Cache startup unexpectedly enumerated the whole scope instead of deferring verification."); await restored.RebuildAsync(); Ensure(restored.Index.ContainsPath(newPath) && !restored.Index.ContainsPath(oldPath) && restored.Status is { IsScanning: false, VerificationPending: false, UsingCachedSnapshot: false }, "Explicit verification must discover offline changes and clear the cached/pending status."); }); [Test] public static async Task FileIndexWorkersAreDedicatedAndHonorCancellation() { var caller = Environment.CurrentManagedThreadId; var worker = caller; await FileIndexWorker.Run(() => { worker = Environment.CurrentManagedThreadId; Ensure(!Thread.CurrentThread.IsThreadPoolThread, "Disk/index workers must not occupy the shared search thread pool."); Ensure(Thread.CurrentThread.Priority == ThreadPriority.BelowNormal, "Index worker CPU priority must be below foreground/search threads."); }, "Index worker regression", CancellationToken.None); Ensure(worker != caller, "Index work unexpectedly ran inline on its caller."); using var canceled = new CancellationTokenSource(); canceled.Cancel(); var ran = false; try { await FileIndexWorker.Run(() => ran = true, "Cancelled index worker regression", canceled.Token); throw new InvalidOperationException("A canceled worker start must not run its action."); } catch (OperationCanceledException) { } Ensure(!ran, "Canceled background work still ran."); } [Test] public static void FileIndexCoalescesConcurrentSignalsWithoutThrowing() => Run(async () => { // No filesystem scanning is needed to reproduce a burst of watcher wakeups. var service = new FileIndexService(new FileIndexOptions { Roots = [], CacheDirectory = Path.Combine(Path.GetTempPath(), "xfetoolbox-unused-signal-test") }); var signal = typeof(FileIndexService).GetMethod("SignalChanges", BindingFlags.NonPublic | BindingFlags.Instance)! .CreateDelegate(service); using var invokingSignal = new ThreadLocal(); void Notify() { invokingSignal.Value = true; try { signal(); } finally { invokingSignal.Value = false; } } var exceptions = 0; void OnFirstChance(object? sender, FirstChanceExceptionEventArgs args) { if (invokingSignal.Value && args.Exception is SemaphoreFullException or ObjectDisposedException) Interlocked.Increment(ref exceptions); } AppDomain.CurrentDomain.FirstChanceException += OnFirstChance; try { Parallel.For(0, 10_000, _ => Notify()); Ensure(Volatile.Read(ref exceptions) == 0, $"Normal coalesced notifications threw {exceptions} first-chance exceptions."); var flood = Task.Run(() => Parallel.For(0, 10_000, _ => Notify())); await service.DisposeAsync(); await flood; Notify(); // A late watcher callback after shutdown is also harmless. Ensure(Volatile.Read(ref exceptions) == 0, "Notifications racing shutdown must not throw."); } finally { AppDomain.CurrentDomain.FirstChanceException -= OnFirstChance; await service.DisposeAsync(); } }); [Test] public static void FileIndexWatchersDrainBurstsAndWakeAgainAfterIdle() => Run(async () => { using var temporary = new TemporarySearchTree(); await using var service = new FileIndexService(temporary.Options); await service.RebuildAsync(); var paths = Enumerable.Range(0, 64).Select(index => Path.Combine(temporary.Root, $"burst-{index:D3}.txt")).ToArray(); Parallel.ForEach(paths, path => File.WriteAllText(path, "tracked")); await WaitUntilAsync(() => paths.All(service.Index.ContainsPath), "Coalescing notifications lost files in a burst."); await Task.Delay(temporary.Options.WatchDebounce * 3); var later = Path.Combine(temporary.Root, "after-idle.txt"); File.WriteAllText(later, "wake again"); await WaitUntilAsync(() => service.Index.ContainsPath(later), "The idle change pump missed a later notification."); Parallel.ForEach(paths, File.Delete); await WaitUntilAsync(() => paths.All(path => !service.Index.ContainsPath(path)), "Coalescing notifications lost burst deletions."); }); [Test] public static void FileIndexPersistsAndRecoversFromCorruptCache() => Run(async () => { using var temporary = new TemporarySearchTree(); var file = Path.Combine(temporary.Root, "隐藏也可搜索.txt"); File.WriteAllText(file, "sample"); File.SetAttributes(file, FileAttributes.Hidden); Directory.CreateDirectory(Path.Combine(temporary.Root, "node_modules")); var nested = Path.Combine(temporary.Root, "node_modules", "dependency.js"); File.WriteAllText(nested, "export default 1;"); await using (var service = new FileIndexService(temporary.Options)) { await service.StartAsync(); await service.RebuildAsync(); Ensure(Contains(service, file) && Contains(service, nested), "Hidden and dependency files must remain discoverable."); Ensure(!service.Index.GetEntriesSnapshot().Any(entry => entry.FullPath.StartsWith(temporary.Cache, StringComparison.OrdinalIgnoreCase)), "The index must exclude its own cache."); Ensure(!service.Status.IsScanning && service.Status.LastUpdatedUtc is not null, "A successful scan must publish its completion."); } var cachePath = Path.Combine(temporary.Cache, "files.v1.gz"); Ensure(File.Exists(cachePath) && new FileInfo(cachePath).Length > 0, "A completed scan must persist a compressed snapshot."); await using (var restarted = new FileIndexService(temporary.Options)) { await restarted.StartAsync(); await restarted.RebuildAsync(); Ensure(Contains(restarted, file) && Contains(restarted, nested), "Restarting must preserve searchable files."); } File.WriteAllBytes(cachePath, [0x1F, 0x8B, 0x08, 0xFF, 0, 1, 2]); await using (var recovered = new FileIndexService(temporary.Options)) { await recovered.StartAsync(); await recovered.RebuildAsync(); Ensure(Contains(recovered, file) && Contains(recovered, nested), "A corrupt snapshot must recover through a new scan."); } }); [Test] public static void FileIndexWatchersTrackMovesAndDeletedSubtrees() => Run(async () => { using var temporary = new TemporarySearchTree(); await using var service = new FileIndexService(temporary.Options); await service.RebuildAsync(); var folder = Path.Combine(temporary.Root, "created"); Directory.CreateDirectory(folder); var original = Path.Combine(folder, "inside.txt"); File.WriteAllText(original, "tracked"); await WaitUntilAsync(() => Contains(service, original), "The watcher did not add a newly created descendant."); var beforeContentEdit = DateTimeOffset.UtcNow; File.AppendAllText(original, " updated text"); await WaitUntilAsync(() => service.Status.LastUpdatedUtc >= beforeContentEdit, "Editing an existing file must signal optional content-index reconciliation."); var renamed = Path.Combine(temporary.Root, "renamed"); Directory.Move(folder, renamed); var movedFile = Path.Combine(renamed, "inside.txt"); await WaitUntilAsync(() => Contains(service, movedFile) && !Contains(service, original), "Renaming a directory must move all indexed descendants."); Directory.Delete(renamed, recursive: true); await WaitUntilAsync(() => !service.Index.GetEntriesSnapshot().Any(entry => entry.FullPath.StartsWith(renamed, StringComparison.OrdinalIgnoreCase)), "Deleting a directory must remove indexed descendants."); }); [Test] public static void FileIndexRejectsSnapshotsForDifferentRoots() => Run(async () => { using var temporary = new TemporarySearchTree(); var first = Directory.CreateDirectory(Path.Combine(temporary.Root, "first")).FullName; var second = Directory.CreateDirectory(Path.Combine(temporary.Root, "second")).FullName; var firstFile = Path.Combine(first, "only-first.txt"); var secondFile = Path.Combine(second, "only-second.txt"); File.WriteAllText(firstFile, "first"); File.WriteAllText(secondFile, "second"); await using (var service = new FileIndexService(temporary.Options with { Roots = [first] })) await service.RebuildAsync(); await using (var service = new FileIndexService(temporary.Options with { Roots = [second] })) { await service.RebuildAsync(); Ensure(Contains(service, secondFile) && !Contains(service, firstFile), "A snapshot for another root selection must not leak old results into the active scope."); } }); [Test] public static void FileIndexSupportsCancellationAndIdempotentDisposal() => Run(async () => { using var temporary = new TemporarySearchTree(); var service = new FileIndexService(temporary.Options); using var canceled = new CancellationTokenSource(); canceled.Cancel(); var cancellationObserved = false; try { await service.StartAsync(canceled.Token); } catch (OperationCanceledException) { cancellationObserved = true; } Ensure(cancellationObserved, "An already canceled start request must honor cancellation."); await service.StartAsync(); service.RequestStop(); await service.DisposeAsync(); await service.DisposeAsync(); var disposalObserved = false; try { await service.StartAsync(); } catch (ObjectDisposedException) { disposalObserved = true; } Ensure(disposalObserved, "A disposed index must not restart watchers or scanning."); }); private static bool Contains(FileIndexService service, string path) => service.Index.GetEntriesSnapshot() .Any(entry => string.Equals(entry.FullPath, path, StringComparison.OrdinalIgnoreCase)); private static async Task WaitUntilAsync(Func condition, string message) { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); while (!condition()) { if (timeout.IsCancellationRequested) throw new InvalidOperationException(message); await Task.Delay(50); } } private static void Run(Func test) => test().GetAwaiter().GetResult(); private static void Ensure(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); } private sealed class TemporarySearchTree : IDisposable { public string Root { get; } = Path.Combine(Path.GetTempPath(), "xfetoolbox-file-index-tests-" + Guid.NewGuid().ToString("N")); public string Cache => Path.Combine(Root, ".index-cache"); public FileIndexOptions Options => new() { Roots = [Root], CacheDirectory = Cache, MaxParallelism = 2, WatchDebounce = TimeSpan.FromMilliseconds(50) }; public TemporarySearchTree() => Directory.CreateDirectory(Root); public void Dispose() { var resolvedRoot = Path.GetFullPath(Root); var expectedParent = Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.GetTempPath())) + Path.DirectorySeparatorChar; if (!resolvedRoot.StartsWith(expectedParent, StringComparison.OrdinalIgnoreCase) || !Path.GetFileName(resolvedRoot).StartsWith("xfetoolbox-file-index-tests-", StringComparison.Ordinal)) throw new InvalidOperationException("Unexpected test cleanup path."); if (Directory.Exists(resolvedRoot)) { foreach (var file in Directory.EnumerateFiles(resolvedRoot, "*", SearchOption.AllDirectories)) File.SetAttributes(file, FileAttributes.Normal); Directory.Delete(resolvedRoot, recursive: true); } } } }