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

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using XFEToolBox.Client.Core.Search;

namespace XFEToolBox.Client.Wpf.Test;

/// <summary>Small correctness coverage plus an opt-in, bounded real-disk/real-dispatcher benchmark.</summary>
public static class ColdScanResponsivenessTests
{
    [Test]
    public static async Task ColdDirectoryScanConvergesWhileQueriesAreRunning()
    {
        using var tree = await Task.Run(() => SearchTree.Create(16, 32));
        await using var service = await Task.Run(() => new FileIndexService(tree.Options));
        using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15));
        var scan = service.RebuildAsync(timeout.Token);
        var queries = 0;
        do
        {
            _ = await Task.Run(() => service.Index.Search("*.txt", limit: 10, cancellationToken: timeout.Token));
            queries++;
            if (!scan.IsCompleted) await Task.Delay(1, timeout.Token);
        } while (!scan.IsCompleted);
        await scan;
        Ensure(queries > 0, "冷扫描期间没有执行并发查询。");
        Ensure(service.Index.Count == tree.FileCount + tree.DirectoryCount + 1,
            $"冷扫描没有收敛至完整目录树:{service.Index.Count} 项。");
        Ensure(service.Index.Search("*.txt").TotalMatches == tree.FileCount,
            "并发搜索损坏了冷扫描的文件名索引。");
        Ensure(service.Index.Search("needle-first").Items.Single().Entry.FullPath == tree.FirstFile,
            "冷扫描遗漏首目录中的文件。");
        Ensure(service.Index.Search("needle-last").Items.Single().Entry.FullPath == tree.LastFile,
            "冷扫描遗漏末目录中的文件。");
    }

    [Test]
    [Explicit]
    public static void ColdDirectoryScanKeepsDispatcherAndSearchResponsive()
    {
        Exception? failure = null;
        var thread = new Thread(() =>
        {
            var dispatcher = Dispatcher.CurrentDispatcher;
            SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(dispatcher));
            _ = dispatcher.InvokeAsync(async () =>
            {
                try { await MeasureAsync(dispatcher); }
                catch (Exception error) { failure = error; }
                finally { dispatcher.InvokeShutdown(); }
            });
            Dispatcher.Run();
        }) { IsBackground = true, Name = "Cold scan dispatcher benchmark" };
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        Ensure(thread.Join(TimeSpan.FromSeconds(45)), "冷扫描界面响应基准超时。");
        if (failure is not null) throw new InvalidOperationException("冷扫描界面响应基准失败。", failure);
    }

    private static async Task MeasureAsync(Dispatcher dispatcher)
    {
        // Never enumerate a real drive or reuse another run's fixture. Preparation is outside the measurement.
        using var tree = await Task.Run(() => SearchTree.Create(128, 64));
        await using var service = await Task.Run(() => new FileIndexService(tree.Options));
        var input = new TextBox { Margin = new Thickness(12), Text = "needle" };
        var results = new ListBox { Margin = new Thickness(12) };
        VirtualizingPanel.SetIsVirtualizing(results, true);
        VirtualizingPanel.SetVirtualizationMode(results, VirtualizationMode.Recycling);
        var panel = new DockPanel();
        DockPanel.SetDock(input, Dock.Top);
        panel.Children.Add(input);
        panel.Children.Add(results);
        var window = new Window
        {
            Content = panel, Width = 640, Height = 440, Left = -10_000, Top = -10_000,
            ShowInTaskbar = false, ShowActivated = false, WindowStartupLocation = WindowStartupLocation.Manual
        };
        window.Show();
        window.UpdateLayout();
        await dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);

        using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
        var watch = Stopwatch.StartNew();
        var previousBeat = watch.Elapsed.TotalMilliseconds;
        var maximumHeartbeat = 0d;
        var beats = 0;
        var firstSearchable = -1d;
        var maximumUiCountRead = 0d;
        var timer = new DispatcherTimer(DispatcherPriority.Input, dispatcher)
        {
            Interval = TimeSpan.FromMilliseconds(10)
        };
        timer.Tick += (_, _) =>
        {
            var now = watch.Elapsed.TotalMilliseconds;
            maximumHeartbeat = Math.Max(maximumHeartbeat, now - previousBeat);
            previousBeat = now;
            beats++;
            // This models the status counter polled by the UI; it must not wait for a writer.
            var countRead = Stopwatch.StartNew();
            var count = service.Index.Count;
            maximumUiCountRead = Math.Max(maximumUiCountRead, countRead.Elapsed.TotalMilliseconds);
            if (firstSearchable < 0 && count > 1) firstSearchable = now;
        };
        timer.Start();
        var latencies = new List<double>();
        var coldLatencies = new List<double>();
        var scan = service.RebuildAsync(timeout.Token);
        double scanMilliseconds = -1;
        try
        {
            // Continue briefly after completion to collect a stable latency distribution without larger fixtures.
            do
            {
                var scanning = !scan.IsCompleted;
                input.Text = latencies.Count % 2 == 0 ? "*.txt" : "needle";
                var query = input.Text;
                var queryWatch = Stopwatch.StartNew();
                var page = await Task.Run(() => service.Index.Search(query, limit: 20, cancellationToken: timeout.Token));
                latencies.Add(queryWatch.Elapsed.TotalMilliseconds);
                if (scanning) coldLatencies.Add(queryWatch.Elapsed.TotalMilliseconds);
                results.ItemsSource = page.Items.Select(item => item.Entry.Name).ToArray();
                if (scan.IsCompleted && scanMilliseconds < 0) scanMilliseconds = watch.Elapsed.TotalMilliseconds;
                await Task.Delay(25, timeout.Token);
            } while (!scan.IsCompleted || watch.Elapsed < TimeSpan.FromSeconds(1));
            await scan;
            Ensure(service.Index.Count == tree.FileCount + tree.DirectoryCount + 1, "显式冷扫描基准索引条目不完整。");
            Ensure(service.Index.Search("*.txt").TotalMatches == tree.FileCount, "显式冷扫描基准查询结果不完整。");
            Ensure(beats > 0 && coldLatencies.Count > 0, "显式基准没有覆盖界面调度和并发查询。");
            // These are a deadlock/stall guard, not a hardware-specific frame-rate promise.
            Ensure(maximumHeartbeat < 1000, $"冷扫描使界面单次无响应超过一秒:{maximumHeartbeat:F1} ms。");
            Ensure(latencies.Max() < 1000, $"冷扫描使搜索单次无响应超过一秒:{latencies.Max():F1} ms。");
            Ensure(maximumUiCountRead < 100, $"界面读取索引计数等待了共享锁:{maximumUiCountRead:F1} ms。");
            Console.WriteLine($"Cold directory scan: {tree.FileCount:N0} files/{tree.DirectoryCount:N0} folders; " +
                $"scan+cache <= {scanMilliseconds:F1} ms; searchable <= {firstSearchable:F1} ms; " +
                $"queries {latencies.Count}, cold {coldLatencies.Count}; query p95 {Percentile(latencies, .95):F1} ms/max {latencies.Max():F1} ms; " +
                $"UI max heartbeat {maximumHeartbeat:F1} ms/{beats} beats; count read max {maximumUiCountRead:F3} ms.");
        }
        finally
        {
            timer.Stop();
            window.Close();
            service.RequestStop();
        }
    }

    private static double Percentile(List<double> values, double fraction)
        => values.Order().ElementAt(Math.Clamp((int)Math.Ceiling(values.Count * fraction) - 1, 0, values.Count - 1));

    private static void Ensure(bool condition, string message)
    {
        if (!condition) throw new InvalidOperationException(message);
    }

    private sealed class SearchTree : IDisposable
    {
        private readonly List<string> files = [];
        private readonly List<string> directories = [];
        private readonly string root = Path.Combine(Path.GetTempPath(), "xfetoolbox-cold-scan-test-" + Guid.NewGuid().ToString("N"));
        public int FileCount => files.Count;
        public int DirectoryCount => directories.Count;
        public string FirstFile => files[0];
        public string LastFile => files[^1];
        public FileIndexOptions Options => new()
        {
            Roots = [root], CacheDirectory = Path.Combine(root, ".cache"), MaxParallelism = 2,
            ReconciliationInterval = TimeSpan.FromHours(1)
        };

        public static SearchTree Create(int folderCount, int filesPerFolder)
        {
            var tree = new SearchTree();
            try
            {
                Directory.CreateDirectory(tree.root);
                for (var folder = 0; folder < folderCount; folder++)
                {
                    var parent = Directory.CreateDirectory(Path.Combine(tree.root, $"folder-{folder:D4}")).FullName;
                    tree.directories.Add(parent);
                    for (var file = 0; file < filesPerFolder; file++)
                    {
                        var name = folder == 0 && file == 0 ? "needle-first.txt" :
                            folder == folderCount - 1 && file == filesPerFolder - 1 ? "needle-last.txt" : $"report-{folder:D4}-{file:D4}.txt";
                        var path = Path.Combine(parent, name);
                        using (File.Create(path)) { }
                        tree.files.Add(path);
                    }
                }
                return tree;
            }
            catch { tree.Dispose(); throw; }
        }

        public void Dispose()
        {
            var target = Path.GetFullPath(root);
            Ensure(Path.GetDirectoryName(target) == Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.GetTempPath())) &&
                Path.GetFileName(target).StartsWith("xfetoolbox-cold-scan-test-", StringComparison.Ordinal), "Unexpected cold scan fixture target.");
            // Delete only paths created by this fixture, then empty directories, never a recursive/glob target.
            foreach (var path in files) File.Delete(path);
            foreach (var path in directories.AsEnumerable().Reverse()) Directory.Delete(path);
            var cache = Path.Combine(target, ".cache");
            if (Directory.Exists(cache))
            {
                foreach (var path in Directory.EnumerateFiles(cache, "*", SearchOption.TopDirectoryOnly)) File.Delete(path);
                Directory.Delete(cache);
            }
            if (Directory.Exists(target)) Directory.Delete(target);
        }
    }
}