using System.IO; using XFEToolBox.Client.Core.Search; using XFEToolBox.Client.Core.Search.Service; using XFEToolBox.Client.Utilities; namespace XFEToolBox.Client.Wpf.Test; public static class IndexingServiceRuntimeTests { [Test] public static async Task AvailableServiceAvoidsTheClientsWholeScopeCrawlerAndFallsBackOnRemoval() { using var tree = new TestTree(); var local = Path.Combine(tree.Scope, "local-after-uninstall.txt"); File.WriteAllText(local, "ordinary user content"); var remote = Path.Combine(tree.Scope, "remote-metadata.txt"); var service = new FakeService(tree.Scope, remote); await using var runtime = new FileSearchRuntime(tree.Cache, service); await runtime.SetScopeAsync(tree.Scope); var result = await runtime.SearchAsync("remote", false, 100); Ensure(runtime.IsUsingIndexingService && result.Items.Single().Entry.FullPath == remote, "Runtime did not prefer service metadata."); Ensure(service.LastScope == tree.Scope && !File.Exists(Path.Combine(tree.Cache, "files.v1.gz")), "The desktop still started a duplicate whole-scope crawler while the service was available."); service.Unavailable = true; for (var attempt = 1; attempt <= 2; attempt++) { var probesBeforeQuery = service.StatusCalls; result = await runtime.SearchAsync("local-after-uninstall", false, 100); Ensure(result.Error is not null && runtime.IsUsingIndexingService && LocalBackend(runtime) is null, $"Transient query/status failure {attempt} discarded verified coverage or started a duplicate crawler."); Ensure(service.StatusCalls == probesBeforeQuery + 1, "A failed query retried status in a loop instead of making one independent background probe."); } result = await runtime.SearchAsync("local-after-uninstall", false, 100); Ensure(result.Error is not null && !runtime.IsUsingIndexingService, "Three consecutive failed status probes did not confirm service removal and start ordinary fallback."); await runtime.RebuildAsync(); result = await runtime.SearchAsync("local-after-uninstall", false, 100); Ensure(!runtime.IsUsingIndexingService && result.Items.Single().Entry.FullPath == local, "Removing the service stranded normal-permission local search."); } [Test] public static async Task TransientStatusPollMissesPreserveCoverageAndSuccessfulProbeResetsTheStreak() { using var tree = new TestTree(); var remote = Path.Combine(tree.Scope, "remote-still-searchable.txt"); var service = new FakeService(tree.Scope, remote); await using var runtime = new FileSearchRuntime(tree.Cache, service); await runtime.SetScopeAsync(tree.Scope); service.StatusUnavailableOnly = true; for (var attempt = 1; attempt <= 2; attempt++) { await runtime.RefreshIndexingServiceAsync(); var page = await runtime.SearchAsync("remote-still-searchable", false, 100); Ensure(runtime.IsUsingIndexingService && LocalBackend(runtime) is null && page.Error is null && page.Items.Single().Entry.FullPath == remote, $"Status poll miss {attempt} disrupted real service queries or launched a duplicate crawler."); } service.StatusUnavailableOnly = false; await runtime.RefreshIndexingServiceAsync(); service.StatusUnavailableOnly = true; await runtime.RefreshIndexingServiceAsync(); await runtime.RefreshIndexingServiceAsync(); Ensure(runtime.IsUsingIndexingService && LocalBackend(runtime) is null && !File.Exists(Path.Combine(tree.Cache, "files.v1.gz")), "A successful status probe did not reset consecutive failures before the next two transient misses."); } [Test] public static async Task ThirdConsecutiveStatusPollFailureStartsOnlyTheSelectedScopeFallback() { using var tree = new TestTree(); var local = Path.Combine(tree.Scope, "scoped-fallback.txt"); File.WriteAllText(local, "isolated fixture"); var service = new FakeService(tree.Scope, Path.Combine(tree.Scope, "remote.txt")); await using var runtime = new FileSearchRuntime(tree.Cache, service); await runtime.SetScopeAsync(tree.Scope); service.StatusUnavailableOnly = true; for (var attempt = 1; attempt <= 3; attempt++) { await runtime.RefreshIndexingServiceAsync(); Ensure(runtime.IsUsingIndexingService == (attempt < 3) && (LocalBackend(runtime) is null) == (attempt < 3), "Status failure hysteresis did not switch backends at exactly three independent probes."); } await runtime.RebuildAsync(); var page = await runtime.SearchAsync("scoped-fallback", false, 100); Ensure(page.Error is null && page.Items.Single().Entry.FullPath == local && runtime.ScopePath == tree.Scope, "Confirmed service loss did not preserve ordinary-user search within the isolated selected scope."); } [Test] public static async Task InitiallyMissingServiceStillStartsScopedFallbackImmediately() { using var tree = new TestTree(); var local = Path.Combine(tree.Scope, "initial-fallback.txt"); File.WriteAllText(local, "isolated fixture"); var service = new FakeService(tree.Scope, "unused") { Unavailable = true }; await using var runtime = new FileSearchRuntime(tree.Cache, service); await runtime.SetScopeAsync(tree.Scope); Ensure(!runtime.IsUsingIndexingService && LocalBackend(runtime) is not null && service.StatusCalls == 1, "An initially absent service unnecessarily delayed normal-permission fallback or retried status."); await runtime.RebuildAsync(); var page = await runtime.SearchAsync("initial-fallback", false, 100); Ensure(page.Items.Single().Entry.FullPath == local, "Initial service absence left scoped search unavailable."); } [Test] public static async Task ServiceQueriesAndOrdinaryContentRemainSeparatedAndCancellationIsQuiet() { using var tree = new TestTree(); var source = Path.Combine(tree.Scope, "source.txt"); File.WriteAllText(source, "nevertransmit private file contents ordinarybodyneedle tail"); var service = new FakeService(tree.Scope, source); await using var runtime = new FileSearchRuntime(tree.Cache, service); await runtime.SetScopeAsync(tree.Scope); using var canceled = new CancellationTokenSource(); canceled.Cancel(); var page = await runtime.SearchAsync("*", false, 10, canceled.Token); Ensure(page.IsCancelled && page.Error is null, "Old queries must not surface cancellation as a search error."); Ensure(!Directory.Exists(Path.Combine(tree.Cache, "Content")), "The service enabled body indexing without consent."); await runtime.SetContentEnabledAsync(true); await runtime.RebuildAsync(); var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(12); do { page = await runtime.SearchAsync("ordinarybodyneedle", true, 100); if (page.Items.Any(match => match.ContentMatch && match.Entry.FullPath == source)) break; await Task.Delay(50); } while (DateTime.UtcNow < deadline); Ensure(page.Items.Any(match => match.ContentMatch && match.Entry.FullPath == source), "Opt-in content indexing did not use the ordinary user's local file list."); Ensure(service.Queries.All(query => !query.Contains("nevertransmit", StringComparison.Ordinal)), "Unexpected file contents were sent to the metadata service."); } [Test] public static async Task BusyServiceAndOverlongQueriesDoNotRestartTheWholeScopeCrawler() { using var tree = new TestTree(); var service = new FakeService(tree.Scope, Path.Combine(tree.Scope, "remote.txt")) { Busy = true }; await using var runtime = new FileSearchRuntime(tree.Cache, service); await runtime.SetScopeAsync(tree.Scope); var page = await runtime.SearchAsync("remote", false, 100); Ensure(page.Error?.Contains("忙", StringComparison.Ordinal) == true && runtime.IsUsingIndexingService, "A busy query was incorrectly treated as service removal."); var source = typeof(FileSearchRuntime).GetField("files", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!; Ensure(source.GetValue(runtime) is null, "A busy service started a duplicate local crawler."); var calls = service.Queries.Count; page = await runtime.SearchAsync(new string('a', IndexingServiceProtocol.MaximumQueryLength + 1), false, 100); Ensure(page.Error?.Contains("1,024", StringComparison.Ordinal) == true && service.Queries.Count == calls && source.GetValue(runtime) is null, "An overlong query was sent to RPC or restarted the crawler."); } [Test] public static async Task UncoveredScopeUsesLocalResultsWithoutCallingTheMetadataService() { using var tree = new TestTree(); var local = Path.Combine(tree.Scope, "ordinary-only.txt"); File.WriteAllText(local, "fixture"); var service = new FakeService(Path.Combine(tree.Scope, "other-volume"), "unused") { Busy = true }; await using var runtime = new FileSearchRuntime(tree.Cache, service); await runtime.SetScopeAsync(tree.Scope); await runtime.RebuildAsync(); var page = await runtime.SearchAsync("ordinary-only", false, 100); Ensure(page.Error is null && page.Items.Single().Entry.FullPath == local && service.Queries.Count == 0, "An out-of-coverage scope unnecessarily called RPC or discarded ordinary-user results."); } private sealed class FakeService(string root, string metadataPath) : IIndexingServiceClient { public bool Unavailable { get; set; } public bool StatusUnavailableOnly { get; set; } public bool Busy { get; set; } public int StatusCalls { get; private set; } public string? LastScope { get; private set; } public List Queries { get; } = []; private IndexingServiceStatus State => new(false, 0, 1, 1) { IndexedRoots = [root] }; public Task GetStatusAsync(CancellationToken cancellationToken = default) { StatusCalls++; return Task.FromResult(Unavailable || StatusUnavailableOnly ? null : State); } public Task SearchAsync(string query, string? scope, int limit, CancellationToken cancellationToken = default) { LastScope = scope; Queries.Add(query); if (Unavailable || Busy) return Task.FromResult(null); var entry = new FileSearchEntry(metadataPath, false); var items = FileSearchQuery.Parse(query).Matches(entry) ? new[] { new FileSearchMatch(entry, 200) } : []; return Task.FromResult(Unavailable ? null : new(items, false, TimeSpan.Zero, State)); } } private static void Ensure(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); } private static object? LocalBackend(FileSearchRuntime runtime) => typeof(FileSearchRuntime) .GetField("files", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.GetValue(runtime); private sealed class TestTree : IDisposable { private readonly string root = Path.Combine(Path.GetTempPath(), "xfetoolbox-service-runtime-" + Guid.NewGuid().ToString("N")); public string Scope { get; } public string Cache => Path.Combine(root, "cache"); public TestTree() => Scope = Directory.CreateDirectory(Path.Combine(root, "scope")).FullName; public void Dispose() { if (Path.GetDirectoryName(root) != Path.TrimEndingDirectorySeparator(Path.GetTempPath()) || !Path.GetFileName(root).StartsWith("xfetoolbox-service-runtime-", StringComparison.Ordinal)) throw new InvalidOperationException("Unexpected service runtime fixture."); foreach (var path in Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories)) File.Delete(path); foreach (var path in Directory.EnumerateDirectories(root, "*", SearchOption.AllDirectories).OrderByDescending(path => path.Length)) Directory.Delete(path); Directory.Delete(root); } } }