XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Security.Principal;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using XFEToolBox.Client.Core.Search.Service;
using XFEToolBox.Client.Utilities;
using XFEToolBox.Client.Views.Windows;

internal static class Program
{
    [STAThread]
    private static int Main(string[] args)
    {
        var options = Options.Parse(args);
        if (options is null)
        {
            Console.WriteLine("Usage: Indexing.WpfLiveValidation --seconds 30 --output <report.json>");
            return 2;
        }
        var report = new Report { RequestedSeconds = options.Seconds };
        FileSearchRuntime? runtime = null;
        string? cache = null;
        try
        {
            report.Elevated = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
            if (report.Elevated)
                return Finish("skipped", "ordinary_permission_required", 3);
            var realClient = new IndexingServiceClient();
            var status = realClient.GetStatusAsync().GetAwaiter().GetResult();
            if (status is null) return Finish("skipped", "trusted_service_unavailable", 3);
            var candidates = status.IndexedRoots.Where(IndexingServiceProtocol.IsLocalPath).ToArray();
            if (candidates.Length == 0) return Finish("skipped", "service_has_no_covered_ntfs_scope", 3);
            var systemRoot = Path.GetPathRoot(Environment.SystemDirectory);
            var scope = candidates.FirstOrDefault(root => string.Equals(root, systemRoot, StringComparison.OrdinalIgnoreCase)) ?? candidates[0];
            if (!Directory.Exists(scope)) return Finish("skipped", "covered_scope_unavailable", 3);
            report.ScopeVolumeCount = 1;

            // A private scope file selects exactly one already-covered native volume. No default
            // drive enumeration, content indexing, or changes to the user's real settings/cache.
            cache = Path.Combine(Path.GetTempPath(), "xfetoolbox-wpf-live-" + Guid.NewGuid().ToString("N"));
            var guard = new ServiceOnlyClient(realClient, status, scope);
            runtime = new FileSearchRuntime(cache, guard);
            // SetScope performs the explicit, covered scope transition before initialization.
            // If the drive vanishes it fails closed, whereas ReadScope could fall back to null.
            runtime.SetScopeAsync(scope).GetAwaiter().GetResult();
            var localFiles = typeof(FileSearchRuntime).GetField("files", BindingFlags.NonPublic | BindingFlags.Instance)!;
            if (guard.StopReason is not null || localFiles.GetValue(runtime) is not null)
                return Finish("skipped", guard.StopReason ?? "service_only_backend_not_available", 3);

            var application = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
            foreach (var source in new[]
            {
                "/XFEToolBox.WpfCore;component/Resources/Style/ToolThemeResources.xaml",
                "/XFEToolBox;component/Resources/Style/MainStyle.xaml",
                "/XFEToolBox;component/Resources/Style/AdminManagementStyle.xaml"
            }) application.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri(source, UriKind.Relative) });
            application.Startup += async (_, _) =>
            {
                try { await MeasureAsync(application, runtime, guard, report, localFiles); }
                catch (Exception exception) { report.Outcome = "failed"; report.Reason = exception.GetType().Name; }
                finally { application.Shutdown(); }
            };
            application.Run();
            return Finish(report.Outcome, report.Reason, report.Outcome == "completed" ? 0 : 4);
        }
        catch (Exception exception) { return Finish("failed", exception.GetType().Name, 1); }
        finally
        {
            runtime?.DisposeAsync().AsTask().GetAwaiter().GetResult();
            if (cache is not null)
            {
                // Only the private known settings file can exist in service-only mode.
                var settings = Path.Combine(cache, "settings.json");
                if (File.Exists(settings)) File.Delete(settings);
                if (Directory.Exists(cache) && !Directory.EnumerateFileSystemEntries(cache).Any()) Directory.Delete(cache);
            }
        }

        int Finish(string outcome, string? reason, int code)
        {
            report.Outcome = outcome;
            report.Reason = reason;
            var json = JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true });
            var output = Path.GetFullPath(options.Output);
            Directory.CreateDirectory(Path.GetDirectoryName(output)!);
            File.WriteAllText(output, json);
            Console.WriteLine(json); // Aggregates only: never print query matches, paths, user names, or error messages.
            return code;
        }
    }

    private static async Task MeasureAsync(Application application, FileSearchRuntime runtime, ServiceOnlyClient service,
        Report report, FieldInfo localFiles)
    {
        var constructor = typeof(CommandPaletteWindow).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic,
            null, [typeof(FileSearchRuntime)], null)!;
        var window = (CommandPaletteWindow)constructor.Invoke([runtime]);
        window.Topmost = false;
        window.ShowActivated = false;
        window.ShowInTaskbar = false;
        window.WindowStartupLocation = WindowStartupLocation.Manual;
        window.Left = -30000;
        window.Top = -30000;
        var input = (TextBox)window.FindName("SearchBox");
        var statusText = (TextBlock)window.FindName("StatusText");
        var results = (ListBox)window.FindName("ResultList");
        var isSearching = typeof(CommandPaletteWindow).GetField("isSearching", BindingFlags.NonPublic | BindingFlags.Instance)!;
        var ui = new List<TimedValue>();
        var palette = new List<TimedValue>();
        var displayedElapsed = new List<TimedValue>();
        var firstChanceCancellation = 0;
        var firstChanceSemaphoreFull = 0;
        var measuring = 0;
        EventHandler<FirstChanceExceptionEventArgs> firstChance = (_, eventArgs) =>
        {
            if (Volatile.Read(ref measuring) == 0) return;
            if (eventArgs.Exception is OperationCanceledException) Interlocked.Increment(ref firstChanceCancellation);
            if (eventArgs.Exception is SemaphoreFullException) Interlocked.Increment(ref firstChanceSemaphoreFull);
        };
        var heartbeat = new DispatcherTimer(DispatcherPriority.Input, application.Dispatcher) { Interval = TimeSpan.FromMilliseconds(10) };
        var lastHeartbeat = Stopwatch.GetTimestamp();
        heartbeat.Tick += (_, _) =>
        {
            var now = Stopwatch.GetTimestamp();
            ui.Add(new(Stopwatch.GetElapsedTime(lastHeartbeat, now).TotalMilliseconds, service.Latest.IsIndexing));
            lastHeartbeat = now;
        };
        try
        {
            // Show(), unlike ShowPalette(), neither activates nor repositions/focuses the window.
            // Warm up the real WPF visual tree and raster once before counting heartbeat stalls.
            window.Show();
            window.UpdateLayout();
            var bitmap = new RenderTargetBitmap((int)Math.Ceiling(window.ActualWidth), (int)Math.Ceiling(window.ActualHeight),
                96, 96, PixelFormats.Pbgra32);
            bitmap.Render(window);
            await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
            var queries = new[] { "*.dll", "readme", "*.txt", "config", "*.exe", "*", "xfetoolbox-unmatched-benchmark-needle" };
            var cycle = 0;
            var clock = Stopwatch.StartNew();
            service.BeginMeasurement();
            AppDomain.CurrentDomain.FirstChanceException += firstChance;
            Volatile.Write(ref measuring, 1);
            lastHeartbeat = Stopwatch.GetTimestamp();
            heartbeat.Start();
            while (clock.Elapsed.TotalSeconds < report.RequestedSeconds && service.StopReason is null)
            {
                if (localFiles.GetValue(runtime) is not null)
                {
                    report.Reason = "unexpected_local_backend";
                    break;
                }
                var indexingAtStart = service.Latest.IsIndexing;
                var started = Stopwatch.GetTimestamp();
                input.Text = queries[cycle++ % queries.Length]; // Real TextChanged/debounce/cancellation route.
                while ((bool)isSearching.GetValue(window)! && clock.Elapsed.TotalSeconds < report.RequestedSeconds && service.StopReason is null)
                    await Task.Delay(10);
                if ((bool)isSearching.GetValue(window)!) { report.UnfinishedPaletteQueries++; break; }
                window.UpdateLayout();
                var wasIndexing = indexingAtStart || service.Latest.IsIndexing;
                palette.Add(new(Stopwatch.GetElapsedTime(started).TotalMilliseconds, wasIndexing));
                var match = Regex.Match(statusText.Text, @"·\s*(\d+)\s*ms$", RegexOptions.CultureInvariant);
                if (match.Success) displayedElapsed.Add(new(double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture), wasIndexing));
                report.MaximumVisibleResults = Math.Max(report.MaximumVisibleResults, results.Items.Count);
                var realized = 0;
                for (var index = 0; index < results.Items.Count; index++)
                    if (results.ItemContainerGenerator.ContainerFromIndex(index) is not null) realized++;
                report.MaximumRealizedRows = Math.Max(report.MaximumRealizedRows, realized);
                await Task.Delay(150);
            }
            report.MeasuredSeconds = Math.Round(clock.Elapsed.TotalSeconds, 3);
            report.ServiceVolumes = service.Latest.Volumes;
            report.ReadyServiceVolumesAtEnd = service.Latest.ReadyVolumes;
            report.ServiceIndexingAtEnd = service.Latest.IsIndexing;
            report.Outcome = service.StopReason is null && report.Reason is null ? "completed" : "not_measurable";
            report.Reason ??= service.StopReason;
        }
        finally
        {
            heartbeat.Stop();
            Volatile.Write(ref measuring, 0);
            AppDomain.CurrentDomain.FirstChanceException -= firstChance;
            service.EndMeasurement();
            window.Hide(); // Cancels any final request through the real palette lifecycle.
            window.Close();
            report.UiHeartbeatIntervalMs = Stats.From(ui);
            report.PaletteCompletionWallMs = Stats.From(palette);
            report.DisplayedRuntimeElapsedMs = Stats.From(displayedElapsed);
            report.ServiceRequestWallMs = Stats.From(service.RequestTimes);
            report.ServiceEngineElapsedMs = Stats.From(service.EngineTimes);
            report.IndexingUiHeartbeatIntervalMs = Stats.From(ui.Where(item => item.Indexing));
            report.IndexingPaletteCompletionWallMs = Stats.From(palette.Where(item => item.Indexing));
            report.IndexingServiceRequestWallMs = Stats.From(service.RequestTimes.Where(item => item.Indexing));
            report.IndexingServiceEngineElapsedMs = Stats.From(service.EngineTimes.Where(item => item.Indexing));
            report.IndexingObserved = report.IndexingUiHeartbeatIntervalMs.Count > 0;
            report.ServiceQueryFailures = service.QueryFailures;
            report.CancelledServiceQueries = service.CancelledQueries;
            report.TransientStatusFailures = service.TransientStatusFailures;
            report.MaximumConsecutiveStatusFailures = service.MaximumConsecutiveStatusFailures;
            report.FirstChanceCancellationExceptions = firstChanceCancellation;
            report.FirstChanceSemaphoreFullExceptions = firstChanceSemaphoreFull;
        }
    }

    private sealed record Options(int Seconds, string Output)
    {
        internal static Options? Parse(string[] args)
        {
            var seconds = 30;
            string? output = null;
            for (var index = 0; index < args.Length; index++)
            {
                var option = args[index];
                if (index + 1 >= args.Length) return null;
                var argument = args[++index];
                if (option == "--seconds" && int.TryParse(argument, out var value)) seconds = value;
                else if (option == "--output") output = argument;
                else return null;
            }
            return seconds is >= 2 and <= 3600 && !string.IsNullOrWhiteSpace(output) ? new(seconds, output) : null;
        }
    }

    private sealed record TimedValue(double Milliseconds, bool Indexing);
    private sealed record Stats(int Count, double P50, double P95, double Max)
    {
        internal static Stats From(IEnumerable<TimedValue> source)
        {
            var values = source.Select(item => item.Milliseconds).Order().ToArray();
            double Value(double percentile) => values.Length == 0 ? 0 : Math.Round(values[Math.Clamp((int)Math.Ceiling(values.Length * percentile) - 1, 0, values.Length - 1)], 3);
            return new(values.Length, Value(.5), Value(.95), Value(1));
        }
    }

    private sealed class Report
    {
        public string Outcome { get; set; } = "not_measurable";
        public string? Reason { get; set; }
        public int RequestedSeconds { get; set; }
        public double MeasuredSeconds { get; set; }
        public bool Elevated { get; set; }
        public int ScopeVolumeCount { get; set; }
        public bool LocalCrawlerAllowed { get; } = false;
        public int ServiceVolumes { get; set; }
        public int ReadyServiceVolumesAtEnd { get; set; }
        public bool ServiceIndexingAtEnd { get; set; }
        public bool IndexingObserved { get; set; }
        public int UiHeartbeatTargetMs { get; } = 10;
        public int InputDebounceMs { get; } = 120;
        public Stats? UiHeartbeatIntervalMs { get; set; }
        public Stats? PaletteCompletionWallMs { get; set; }
        public Stats? DisplayedRuntimeElapsedMs { get; set; }
        public Stats? ServiceRequestWallMs { get; set; }
        public Stats? ServiceEngineElapsedMs { get; set; }
        public Stats? IndexingUiHeartbeatIntervalMs { get; set; }
        public Stats? IndexingPaletteCompletionWallMs { get; set; }
        public Stats? IndexingServiceRequestWallMs { get; set; }
        public Stats? IndexingServiceEngineElapsedMs { get; set; }
        public int MaximumVisibleResults { get; set; }
        public int MaximumRealizedRows { get; set; }
        public int UnfinishedPaletteQueries { get; set; }
        public int ServiceQueryFailures { get; set; }
        public int CancelledServiceQueries { get; set; }
        public int TransientStatusFailures { get; set; }
        public int MaximumConsecutiveStatusFailures { get; set; }
        public int FirstChanceCancellationExceptions { get; set; }
        public int FirstChanceSemaphoreFullExceptions { get; set; }
    }

    /// <summary>
    /// Benchmark-only adapter around the real client. A service outage must not accidentally
    /// trigger a new crawler in FileSearchRuntime. Coverage is never expanded beyond the last
    /// verified snapshot: loss of that coverage ends this benchmark instead of invoking fallback.
    /// </summary>
    private sealed class ServiceOnlyClient(IndexingServiceClient inner, IndexingServiceStatus initial, string scope) : IIndexingServiceClient
    {
        private IndexingServiceStatus latest = initial;
        private string? stopReason;
        private int measuring;
        private int failures;
        private int cancellations;
        private int transientStatusFailures;
        private int consecutiveStatusFailures;
        private int maximumConsecutiveStatusFailures;
        private long firstStatusFailure;
        internal IndexingServiceStatus Latest => Volatile.Read(ref latest);
        internal string? StopReason => Volatile.Read(ref stopReason);
        internal ConcurrentQueue<TimedValue> RequestTimes { get; } = new();
        internal ConcurrentQueue<TimedValue> EngineTimes { get; } = new();
        internal int QueryFailures => Volatile.Read(ref failures);
        internal int CancelledQueries => Volatile.Read(ref cancellations);
        internal int TransientStatusFailures => Volatile.Read(ref transientStatusFailures);
        internal int MaximumConsecutiveStatusFailures => Volatile.Read(ref maximumConsecutiveStatusFailures);
        internal void BeginMeasurement() => Volatile.Write(ref measuring, 1);
        internal void EndMeasurement() => Volatile.Write(ref measuring, 0);

        public async Task<IndexingServiceStatus?> GetStatusAsync(CancellationToken cancellationToken = default)
        {
            if (StopReason is not null || cancellationToken.IsCancellationRequested) return Latest;
            var probeStarted = Stopwatch.GetTimestamp();
            var status = await inner.GetStatusAsync(cancellationToken).ConfigureAwait(false);
            if (cancellationToken.IsCancellationRequested) return Latest;
            if (status is null)
            {
                Interlocked.Increment(ref transientStatusFailures);
                var consecutive = Interlocked.Increment(ref consecutiveStatusFailures);
                Interlocked.CompareExchange(ref firstStatusFailure, probeStarted, 0);
                int previousMaximum;
                do
                {
                    previousMaximum = Volatile.Read(ref maximumConsecutiveStatusFailures);
                    if (previousMaximum >= consecutive) break;
                }
                while (Interlocked.CompareExchange(ref maximumConsecutiveStatusFailures, consecutive, previousMaximum) != previousMaximum);
                // A busy cold-indexing service can miss a one-second status probe even while
                // real queries succeed. Preserve verified coverage through two such misses;
                // never enable a crawler, and stop on the third or >5 s of continuous failure.
                if (consecutive >= 3 || Stopwatch.GetElapsedTime(Volatile.Read(ref firstStatusFailure)) > TimeSpan.FromSeconds(5))
                    Interlocked.CompareExchange(ref stopReason, "service_unavailable_or_status_timeout", null);
            }
            else if (!CoversScope(status)) Interlocked.CompareExchange(ref stopReason, "native_scope_coverage_lost", null);
            else
            {
                Volatile.Write(ref latest, status);
                Interlocked.Exchange(ref consecutiveStatusFailures, 0);
                Interlocked.Exchange(ref firstStatusFailure, 0);
            }
            return Latest; // Preserve verified coverage solely to disable fallback during shutdown.
        }

        public async Task<IndexingServiceSearchResponse?> SearchAsync(string query, string? requestedScope, int limit,
            CancellationToken cancellationToken = default)
        {
            if (StopReason is not null) return new([], false, TimeSpan.Zero, Latest, "benchmark_service_unavailable");
            var indexing = Latest.IsIndexing;
            var start = Stopwatch.GetTimestamp();
            var response = await inner.SearchAsync(query, requestedScope, limit, cancellationToken).ConfigureAwait(false);
            if (cancellationToken.IsCancellationRequested)
            {
                if (Volatile.Read(ref measuring) != 0) Interlocked.Increment(ref cancellations);
                return null;
            }
            if (response is null)
            {
                if (Volatile.Read(ref measuring) != 0) Interlocked.Increment(ref failures);
                return new([], false, Stopwatch.GetElapsedTime(start), Latest, "benchmark_service_query_unavailable");
            }
            if (!CoversScope(response.Status)) Interlocked.CompareExchange(ref stopReason, "native_scope_coverage_lost", null);
            else Volatile.Write(ref latest, response.Status);
            if (Volatile.Read(ref measuring) != 0)
            {
                RequestTimes.Enqueue(new(Stopwatch.GetElapsedTime(start).TotalMilliseconds, indexing || response.Status.IsIndexing));
                EngineTimes.Enqueue(new(response.Elapsed.TotalMilliseconds, indexing || response.Status.IsIndexing));
                if (response.Error is not null) Interlocked.Increment(ref failures);
            }
            return response;
        }

        private bool CoversScope(IndexingServiceStatus status) => status.IndexedRoots.Any(root =>
        {
            var normalized = Path.TrimEndingDirectorySeparator(root);
            return Path.TrimEndingDirectorySeparator(scope).Equals(normalized, StringComparison.OrdinalIgnoreCase) ||
                scope.StartsWith(Path.EndsInDirectorySeparator(normalized) ? normalized : normalized + Path.DirectorySeparatorChar,
                    StringComparison.OrdinalIgnoreCase);
        });
    }
}