using System.Buffers.Binary;
using System.Text.Json;
namespace XFEToolBox.Client.Core.Search.Service;
/// The privileged service exposes metadata search only, never filesystem operations.
public static class IndexingServiceProtocol
{
public const string ServiceName = "XFEToolBoxIndexing";
public const string PipeName = "XFEToolBox.Indexing.v1";
public const int Version = 1;
public const int MaximumQueryLength = 1024;
public const int MaximumResults = 10_000;
public const int MaximumRequestBytes = 16 * 1024;
public const int MaximumResponseBytes = 16 * 1024 * 1024;
private static readonly JsonSerializerOptions JsonOptions = new() { MaxDepth = 16 };
public static bool IsValid(IndexingServiceRequest request) => request.Version == Version
&& request.Operation is "status" or "search"
&& request.Query is not null && request.Query.Length <= MaximumQueryLength
&& request.Limit is >= 1 and <= MaximumResults
&& (request.Scope is null || IsLocalPath(request.Scope));
public static bool IsLocalPath(string path) => path.Length is >= 3 and <= 32767
&& char.IsAsciiLetter(path[0]) && path[1] == ':' && path[2] is '\\' or '/'
&& !path.AsSpan(2).Contains(':') && !path.Contains('\0');
public static async Task WriteAsync(Stream stream, T value, int maximumBytes, CancellationToken token)
{
using var bytes = new BoundedFrameStream(maximumBytes);
await JsonSerializer.SerializeAsync(bytes, value, JsonOptions, token).ConfigureAwait(false);
if (bytes.Length == 0) throw new InvalidDataException("Empty indexing IPC frame.");
var prefix = new byte[4];
BinaryPrimitives.WriteInt32LittleEndian(prefix, checked((int)bytes.Length));
await stream.WriteAsync(prefix, token).ConfigureAwait(false);
await stream.WriteAsync(bytes.GetBuffer().AsMemory(0, (int)bytes.Length), token).ConfigureAwait(false);
await stream.FlushAsync(token).ConfigureAwait(false);
}
public static async Task ReadAsync(Stream stream, int maximumBytes, CancellationToken token)
{
var prefix = new byte[4];
await stream.ReadExactlyAsync(prefix, token).ConfigureAwait(false);
var length = BinaryPrimitives.ReadInt32LittleEndian(prefix);
if (length <= 0 || length > maximumBytes)
throw new InvalidDataException("Invalid indexing IPC frame length.");
var bytes = new byte[length];
await stream.ReadExactlyAsync(bytes, token).ConfigureAwait(false);
return JsonSerializer.Deserialize(bytes, JsonOptions)
?? throw new InvalidDataException("Empty indexing IPC message.");
}
private sealed class BoundedFrameStream(int limit) : MemoryStream(Math.Min(limit, 16384))
{
public override void Write(byte[] buffer, int offset, int count)
{
RequireCapacity(count);
base.Write(buffer, offset, count);
}
public override void Write(ReadOnlySpan buffer)
{
RequireCapacity(buffer.Length);
base.Write(buffer);
}
public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default)
{
RequireCapacity(buffer.Length);
return base.WriteAsync(buffer, cancellationToken);
}
private void RequireCapacity(int count)
{
if (count > limit - Position) throw new InvalidDataException("Indexing IPC frame exceeds its limit.");
}
}
}
public sealed record IndexingServiceRequest(int Version, string Operation, string Query = "", string? Scope = null, int Limit = 100);
/// Global filename counts and per-volume errors are deliberately not exposed to clients.
public sealed record IndexingServiceStatus(bool IsIndexing, int IndexedFiles, int Volumes, int ReadyVolumes, string? Error = null)
{
public IReadOnlyList IndexedRoots { get; init; } = [];
public IReadOnlyList UnavailableRoots { get; init; } = [];
}
public sealed record IndexingServiceSearchResponse(FileSearchMatch[] Items, bool HasMore, TimeSpan Elapsed,
IndexingServiceStatus Status, string? Error = null);
public sealed record IndexingServiceResponse(int Version, IndexingServiceStatus Status,
IndexingServiceSearchResponse? Search = null, string? Error = null);