using System.Runtime.ExceptionServices; using XFEToolBox.Client.Core.Search; namespace XFEToolBox.Test; public static class QuietFileSearchTests { [Test] public static void LatestSearchCancellationDoesNotThrowFirstChanceExceptions() { var index = new FileSearchIndex(); index.AddOrUpdate(Enumerable.Range(0, 10_000).Select(number => new FileSearchEntry($@"C:\quiet\item{number:D5}.txt", false))); var exceptions = 0; var testThread = Environment.CurrentManagedThreadId; void FirstChance(object? sender, FirstChanceExceptionEventArgs args) { if (Environment.CurrentManagedThreadId == testThread && args.Exception is OperationCanceledException) exceptions++; } AppDomain.CurrentDomain.FirstChanceException += FirstChance; try { using var alreadyCanceled = new CancellationTokenSource(); alreadyCanceled.Cancel(); Ensure(index.TrySearch("*", cancellationToken: alreadyCanceled.Token) is null, "Canceled latest queries must return quietly."); using var duringMatching = new CancellationTokenSource(); var visited = 0; var result = index.TrySearch("*", cancellationToken: duringMatching.Token, filter: entry => { if (++visited == 512) duringMatching.Cancel(); return true; }); Ensure(result is null && visited >= 512, "Cancellation during matching was not observed."); Ensure(exceptions == 0, "Normal query replacement still throws first-chance cancellation exceptions."); Ensure(index.Search("*").TotalMatches == 10_000, "Canceled pooled snapshots damaged later results."); } finally { AppDomain.CurrentDomain.FirstChanceException -= FirstChance; } } [Test] public static void AccessFiltersRunBeforeCountingAndOutsideTheIndexLock() { var index = new FileSearchIndex(); index.AddOrUpdate([new(@"C:\visible\report.txt", false), new(@"C:\private\report.txt", false)]); var filtered = index.Search("report", limit: 1, filter: entry => entry.FullPath.Contains("visible")); Ensure(filtered.TotalMatches == 1 && filtered.Items.Single().Entry.FullPath.Contains("visible"), "The service filter leaked hidden matches or applied after paging."); using var filtering = new ManualResetEventSlim(); using var release = new ManualResetEventSlim(); var query = Task.Run(() => index.Search("report", filter: entry => { filtering.Set(); release.Wait(TimeSpan.FromSeconds(5)); return true; })); try { Ensure(filtering.Wait(TimeSpan.FromSeconds(5)), "Access filter did not start."); var writer = Task.Run(() => index.AddOrUpdate([new(@"C:\visible\new.txt", false)])); Ensure(writer.Wait(TimeSpan.FromSeconds(1)), "A filesystem access check held the search index read lock."); } finally { release.Set(); query.GetAwaiter().GetResult(); } } private static void Ensure(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); } }