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

XFEToolBox

【WPF】XFE工具箱

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

namespace XFEToolBox.Test;

public static class FileSearchIndexPerformanceTests
{
    [Test]
    public static void FileIndexBulkPruningPreservesSurvivorsAndCanBeCancelled()
    {
        var index = new FileSearchIndex();
        var entries = Entries(12_000).ToArray();
        index.AddOrUpdate(entries);
        index.RemovePaths(entries.Take(8000).Select(entry => entry.FullPath));
        Ensure(index.Count == 4000 && index.GetEntriesSnapshot().Count == 4000, "批量清理后的存活数错误。");
        Ensure(index.Search("document_0000042").TotalMatches == 0 && index.Search("document_0011001").TotalMatches == 1,
            "批量清理后倒排 ID 或存活条目错误。");
        using var cancellation = new CancellationTokenSource();
        cancellation.Cancel();
        try
        {
            index.RemovePaths(entries.Skip(8000).Select(entry => entry.FullPath), cancellation.Token);
            throw new InvalidOperationException("批量清理没有响应取消。");
        }
        catch (OperationCanceledException) { }
        Ensure(index.Count == 4000, "已取消的清理仍删除了条目。");
        index.RemovePaths(entries.Skip(8000).Select(entry => entry.FullPath));
        Ensure(index.Count == 0 && index.Search("*").TotalMatches == 0, "全部清理后索引没有清空。");
        index.AddOrUpdate([new(@"C:\new\fresh.txt", false)]);
        Ensure(index.Search("fresh").TotalMatches == 1, "批量清空后索引无法复用。");
    }

    [Test]
    public static void FileIndexNeverHoldsItsGateWhileEnumeratingSlowInput()
    {
        var index = new FileSearchIndex();
        using var waitingForInput = new ManualResetEventSlim();
        using var releaseInput = new ManualResetEventSlim();
        IEnumerable<FileSearchEntry> SlowEntries()
        {
            for (var number = 0; number < 512; number++)
            {
                if (number == 256)
                {
                    waitingForInput.Set();
                    releaseInput.Wait();
                }
                yield return new($@"C:\slow\report{number:D4}.txt", false);
            }
        }
        var writer = Task.Factory.StartNew(() => index.AddOrUpdate(SlowEntries()),
            CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        Task? reader = null;
        try
        {
            Ensure(waitingForInput.Wait(TimeSpan.FromSeconds(5)), "慢速输入没有开始等待。");
            reader = Task.Factory.StartNew(() =>
            {
                Ensure(index.Count == 256, "第一批索引应已发布,进度读取不能等待文件系统。");
                Ensure(index.ContainsPath(@"C:\slow\report0000.txt"), "等待后续文件时,已有索引不可读取。");
                Ensure(index.Search("report0000").TotalMatches == 1, "等待后续文件时搜索被阻塞。");
                Ensure(index.GetEntriesSnapshot().Count == 256, "等待后续文件时快照被阻塞。");
            }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
            Ensure(reader.Wait(TimeSpan.FromSeconds(1)), "索引把输入枚举的等待传递给了读取线程。");
        }
        finally
        {
            releaseInput.Set();
            writer.GetAwaiter().GetResult();
            reader?.GetAwaiter().GetResult();
        }
        Ensure(index.Count == 512, "后续批次没有完整写入。");
    }

    [Test]
    public static void FileIndexReusesGramStorageAndUnchangedEntryObjects()
    {
        const int count = 100_000;
        var index = new FileSearchIndex();
        var allocatedBefore = GC.GetAllocatedBytesForCurrentThread();
        index.AddOrUpdate(Entries(count));
        var allocated = GC.GetAllocatedBytesForCurrentThread() - allocatedBefore;
        Ensure(allocated < count * 1500L, $"索引分配过多临时对象:每项 {allocated / count:N0} 字节。");
        var existing = index.Search("document_0049001").Items.Single().Entry;
        var updated = new FileSearchEntry(existing.FullPath, existing.IsDirectory);
        index.AddOrUpdate([updated]);
        Ensure(ReferenceEquals(existing, index.Search("document_0049001").Items.Single().Entry),
            "内容相同的重扫不应替换已有不可变条目。");
        Console.WriteLine($"索引临时分配:{count:N0} 项,{allocated / 1_000_000d:N1} MB。");
    }

    [Test]
    public static void FileIndexHandlesAMillionNamesWithConcurrentReadsAndCancellation()
    {
        const int count = 1_000_000;
        var index = new FileSearchIndex();
        var buildWatch = Stopwatch.StartNew();
        var writer = Task.Factory.StartNew(() => index.AddOrUpdate(Entries(count)),
            CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        var timings = new List<double>();
        while (!writer.Wait(20))
        {
            using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(250));
            var watch = Stopwatch.StartNew();
            try { index.Search("document_0000042", cancellationToken: cancellation.Token); }
            catch (OperationCanceledException) { }
            timings.Add(watch.Elapsed.TotalMilliseconds);
            Ensure(index.Count is >= 0 and <= count, "并发进度读取返回了无效计数。");
        }
        writer.GetAwaiter().GetResult();
        Ensure(index.Count == count, "百万条目写入不完整。");
        Ensure(index.Search("Project123").TotalMatches == 1000, "百万条目目录查询不完整。");
        Ensure(index.Search("中文").TotalMatches == 10_000, "百万条目中文查询不完整。");
        using var broadCancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(1));
        try
        {
            index.Search("*", cancellationToken: broadCancellation.Token);
            throw new InvalidOperationException("百万条目通配符搜索没有及时响应取消。");
        }
        catch (OperationCanceledException) { }
        Ensure(timings.Count > 0 && timings.Max() < 1000,
            $"构建中查询超过取消响应预算:{timings.DefaultIfEmpty().Max():N0} ms。");
        Console.WriteLine($"百万文件索引:构建 {buildWatch.Elapsed.TotalMilliseconds:N0} ms,并发查询最大 {timings.Max():N1} ms。");
        index.Clear();
        Ensure(index.Count == 0 && index.GetEntriesSnapshot().Count == 0 && index.Search("document").TotalMatches == 0,
            "清空后残留旧索引。");
        index.AddOrUpdate([new(@"C:\new\fresh.txt", false)]);
        Ensure(index.Count == 1 && index.Search("fresh").TotalMatches == 1, "清空后索引无法复用。");
    }

    private static IEnumerable<FileSearchEntry> Entries(int count)
    {
        for (var number = 0; number < count; number++)
            yield return new($@"C:\Workspace\Projects\Project{number % 1000:D3}\{(number % 100 == 0 ? "中文配置" : "document")}_{number:D7}.{(number % 4 == 0 ? "cs" : "json")}", false);
    }

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