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

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Buffers.Binary;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Text;
using XFEToolBox.Client.Core.Search;
using XFEToolBox.Client.Core.Search.Service;

namespace XFEToolBox.Test;

public static class IndexingServiceProtocolTests
{
    [Test]
    public static async Task IndexingProtocolRoundTripsBoundedMetadata()
    {
        using var stream = new MemoryStream();
        var status = new IndexingServiceStatus(true, 0, 2, 1) { IndexedRoots = [@"C:\"], UnavailableRoots = [@"D:\"] };
        var result = new IndexingServiceResponse(1, status,
            new([new(new(@"C:\documents\报告.txt", false), 2)], true, TimeSpan.FromMilliseconds(12), status));
        await IndexingServiceProtocol.WriteAsync(stream, result, IndexingServiceProtocol.MaximumResponseBytes, default);
        stream.Position = 0;
        var restored = await IndexingServiceProtocol.ReadAsync<IndexingServiceResponse>(stream,
            IndexingServiceProtocol.MaximumResponseBytes, default);
        Ensure(restored.Search?.Items.Single().Entry.FullPath == @"C:\documents\报告.txt", "IPC文件名还原错误。");
        Ensure(restored.Search!.HasMore && restored.Status.IndexedRoots.Single() == @"C:\", "IPC状态或分页信息丢失。");
    }

    [Test]
    public static async Task IndexingProtocolRejectsOversizedFramesBeforeAllocating()
    {
        foreach (var size in new[] { -1, 0, IndexingServiceProtocol.MaximumRequestBytes + 1, int.MaxValue })
        {
            var prefix = new byte[4];
            BinaryPrimitives.WriteInt32LittleEndian(prefix, size);
            using var stream = new MemoryStream(prefix);
            try
            {
                await IndexingServiceProtocol.ReadAsync<IndexingServiceRequest>(stream, IndexingServiceProtocol.MaximumRequestBytes, default);
                throw new InvalidOperationException("非法帧长度被接受。");
            }
            catch (InvalidDataException) { }
        }
        using var truncated = new MemoryStream([5, 0, 0, 0, (byte)'{']);
        try
        {
            await IndexingServiceProtocol.ReadAsync<IndexingServiceRequest>(truncated, IndexingServiceProtocol.MaximumRequestBytes, default);
            throw new InvalidOperationException("截断帧被接受。");
        }
        catch (EndOfStreamException) { }
        using var destination = new MemoryStream();
        try
        {
            await IndexingServiceProtocol.WriteAsync(destination, new string('x', 20_000), 1024, default);
            throw new InvalidOperationException("过大输出帧被接受。");
        }
        catch (InvalidDataException) { }
        Ensure(destination.Length == 0, "输出大小检查前已经发布部分帧。");
    }

    [Test]
    public static void IndexingProtocolRestrictsRequestsToLocalMetadataSearch()
    {
        Ensure(IndexingServiceProtocol.IsValid(new(1, "search", "*.cs", @"C:\projects", 10000)), "合法请求被拒绝。");
        foreach (var request in new IndexingServiceRequest[]
        {
            new(2, "search"), new(1, "delete"), new(1, "rebuild"), new(1, "read"),
            new(1, "search", null!), new(1, "search", new string('a', 1025)),
            new(1, "search", "*", null, 10001), new(1, "search", "*", null, 0),
            new(1, "search", "*", @"\\server\share"), new(1, "search", "*", @"\\?\C:\"),
            new(1, "search", "*", @"C:\file:stream"), new(1, "search", "*", "C:relative"),
        }) Ensure(!IndexingServiceProtocol.IsValid(request), "危险/不受支持请求被接受。");
    }

    [Test]
    public static async Task MissingIndexingServiceDoesNotRaiseExceptionsWhilePolling()
    {
        var client = new IndexingServiceClient();
        if (await client.GetStatusAsync() is not null) return;
        var exceptions = 0;
        void Observe(object? sender, FirstChanceExceptionEventArgs args)
        {
            if ((args.Exception is OperationCanceledException or System.ComponentModel.Win32Exception
                or IOException or UnauthorizedAccessException)
                && args.Exception.StackTrace?.Contains("XFEToolBox.Client.Core.Search.Service", StringComparison.Ordinal) == true)
                Interlocked.Increment(ref exceptions);
        }
        AppDomain.CurrentDomain.FirstChanceException += Observe;
        var watch = Stopwatch.StartNew();
        try
        {
            for (var index = 0; index < 100; index++)
                Ensure(await client.GetStatusAsync() is null, "缺失服务不应产生有效结果。");
            using var cancelled = new CancellationTokenSource();
            cancelled.Cancel();
            Ensure(await client.SearchAsync("*", null, 100, cancelled.Token) is null, "取消请求没有快速返回。");
        }
        finally { AppDomain.CurrentDomain.FirstChanceException -= Observe; }
        Ensure(exceptions == 0, $"正常服务缺失/取消被用作异常控制流:{exceptions} 次。");
        Ensure(watch.Elapsed < TimeSpan.FromSeconds(3), "缺失服务轮询阻塞过久。");
    }

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