using System.Diagnostics; using System.Security.Principal; using System.Text.Json; using XFEToolBox.Client.Core.Search.Service; namespace XFEToolBox.Indexing.LiveValidation; /// Read-only assertions against explicitly identified caller-created samples. internal static class FixtureVerifier { public static async Task RunAsync(string[] args) { string? folder = null, id = null, phase = null; try { if (!OperatingSystem.IsWindows()) throw new ArgumentException("windows_required"); using var identity = WindowsIdentity.GetCurrent(); if (new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) throw new ArgumentException("ordinary_permissions_required"); for (var index = 0; index < args.Length; index++) { var option = args[index]; if (++index >= args.Length) throw new ArgumentException("missing_option_value"); switch (option) { case "--verify-fixture": folder = Path.GetFullPath(args[index]); break; case "--fixture-id": id = args[index]; break; case "--fixture-phase": phase = args[index]; break; default: throw new ArgumentException("unknown_fixture_option"); } } if (folder is null || !IndexingServiceProtocol.IsLocalPath(folder)) throw new ArgumentException("local_fixture_folder_required"); if (!Guid.TryParseExact(id, "N", out var guid)) throw new ArgumentException("guid_n_fixture_id_required"); id = guid.ToString("N"); if (phase is not ("before" or "after")) throw new ArgumentException("before_or_after_phase_required"); var before = phase == "before"; var prefix = "XfeLive_" + id + "_"; var checks = new[] { new Check(prefix + "baseline.txt", before ? 1 : 0, "file:" + prefix + "baseline.txt"), new Check(prefix + "renamed.txt", before ? 0 : 1, "file:" + prefix + "renamed.txt"), new Check(prefix + "delete.txt", before ? 1 : 0, "file:" + prefix + "delete.txt"), new Check(prefix + "offline.txt", before ? 0 : 1, "file:" + prefix + "offline.txt"), new Check(Path.Combine("before-move", prefix + "child.txt"), before ? 1 : 0, "file:" + prefix + "child.txt"), new Check(Path.Combine("after-move", prefix + "child.txt"), before ? 0 : 1, "file:" + prefix + "child.txt"), new Check("before-move", before ? 1 : 0, "folder: folder:before-move", true), new Check("after-move", before ? 0 : 1, "folder: folder:after-move", true) }; using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(45)); var client = new IndexingServiceClient(); var status = await client.GetStatusAsync(timeout.Token).ConfigureAwait(false); var records = new List(); var failed = 0; var totalQueries = 0; var measurements = new List(); foreach (var group in checks.GroupBy(check => check.Query, StringComparer.Ordinal)) { var watch = Stopwatch.StartNew(); var response = status is null ? null : await client.SearchAsync(group.Key, folder, 100, timeout.Token).ConfigureAwait(false); totalQueries++; var succeeded = response is not null && response.Error is null; // Only compare exact known sample paths. Unexpected matches are counted, // never printed or serialized (including their names and snippets). var expectedPaths = group.Select(check => Path.GetFullPath(Path.Combine(folder, check.RelativePath))) .ToHashSet(StringComparer.OrdinalIgnoreCase); var unexpected = response?.Items.Count(match => !expectedPaths.Contains(Path.GetFullPath(match.Entry.FullPath))) ?? 0; foreach (var check in group) { var expectedPath = Path.GetFullPath(Path.Combine(folder, check.RelativePath)); var actual = response?.Items.Count(match => match.Entry.IsDirectory == check.IsDirectory && string.Equals(Path.GetFullPath(match.Entry.FullPath), expectedPath, StringComparison.OrdinalIgnoreCase)) ?? 0; var passed = succeeded && !response!.HasMore && unexpected == 0 && actual == check.ExpectedCount; if (!passed) failed++; records.Add(new { sample = check.RelativePath, expectedCount = check.ExpectedCount, actualCount = actual, unexpectedResultCount = unexpected, passed }); } measurements.Add(new { sampleQuery = group.Key, outcome = !succeeded ? "unavailable_or_query_error" : "ok", wallMs = watch.Elapsed.TotalMilliseconds, serverMs = response?.Elapsed.TotalMilliseconds, returnedCount = response?.Items.Length, hasMore = response?.HasMore }); } Console.WriteLine(JsonSerializer.Serialize(new { type = "fixture_verification", timestampUtc = DateTimeOffset.UtcNow, fixtureId = id, phase, passed = failed == 0, totalChecks = checks.Length, passedChecks = checks.Length - failed, failedChecks = failed, queries = totalQueries, serviceAvailable = status is not null, serviceIndexing = status?.IsIndexing, readyVolumes = status?.ReadyVolumes, volumes = status?.Volumes, checks = records, measurements })); return failed == 0 ? 0 : 1; } catch (Exception error) { // Do not print exception messages, scope paths or any returned filenames. Console.WriteLine(JsonSerializer.Serialize(new { type = "fixture_verification", timestampUtc = DateTimeOffset.UtcNow, phase = phase is "before" or "after" ? phase : null, passed = false, error = error.GetType().Name })); return 1; } } private sealed record Check(string RelativePath, int ExpectedCount, string Query, bool IsDirectory = false); }