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

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Buffers;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO.Compression;
using System.IO.Enumeration;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Channels;

namespace XFEToolBox.Client.Core.Search;

/// <summary>Maintains a searchable local filename index without putting disk enumeration on the UI thread.</summary>
public sealed class FileIndexService : IAsyncDisposable
{
    private const int CacheMagic = 0x58464958;
    private const int CacheVersion = 1;
    private const int BatchSize = 256;
    private const int MaximumCacheEntries = 10_000_000;
    private const int MaximumPathBytes = 131_072;
    private const long MaximumCacheFileBytes = 2L * 1024 * 1024 * 1024;
    private const long MaximumDecodedCacheBytes = 512L * 1024 * 1024;
    private const int MaximumQueuedChanges = 100_000;
    private static readonly StringComparer PathComparer = OperatingSystem.IsWindows()
        ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;

    private readonly FileIndexOptions options;
    private readonly string[] roots;
    private readonly string[] scanRoots;
    private readonly HashSet<string> rootSet;
    private readonly string cacheDirectory;
    private readonly string cacheDirectoryPrefix;
    private readonly string cachePath;
    private readonly string rootsFingerprint;
    private readonly CancellationTokenSource lifetime = new();
    private readonly object lifecycleGate = new();
    private readonly object statusGate = new();
    private readonly object journalGate = new();
    private readonly ConcurrentQueue<FileChange> pendingChanges = new();
    private readonly List<FileChange> scanJournal = [];
    private readonly List<FileSystemWatcher> watchers = [];
    // This is a coalesced wakeup, not a counter of filesystem events. The actual
    // events remain in pendingChanges; redundant wakeups must not throw exceptions.
    private readonly Channel<byte> changeSignal = Channel.CreateBounded<byte>(new BoundedChannelOptions(1)
    {
        SingleReader = true,
        SingleWriter = false,
        FullMode = BoundedChannelFullMode.DropWrite,
        AllowSynchronousContinuations = false
    });
    private readonly SemaphoreSlim changeApplyGate = new(1, 1);
    private readonly SemaphoreSlim saveGate = new(1, 1);
    private readonly Timer notificationTimer;
    private FileIndexStatus status = new(false, 0, 0, null, null, null);
    private Task? initializationTask;
    private Task? reconciliationTask;
    private Task? changePumpTask;
    private Task? maintenanceTask;
    private bool scanRunning;
    private int queuedChanges;
    private int reconciliationNeeded;
    private int notificationsPending;
    private int cacheDirty;
    private int disposed;
    private bool hasCompleteSnapshot;
    private bool lastScanInterrupted;

    public FileIndexService(FileIndexOptions options)
    {
        ArgumentNullException.ThrowIfNull(options);
        this.options = options;
        cacheDirectory = NormalizePath(options.CacheDirectory);
        cacheDirectoryPrefix = Path.EndsInDirectorySeparator(cacheDirectory) ? cacheDirectory : cacheDirectory + Path.DirectorySeparatorChar;
        cachePath = Path.Combine(cacheDirectory, "files.v1.gz");
        roots = options.Roots.Select(NormalizePath).Distinct(PathComparer)
            .Where(root => !IsWithin(root, cacheDirectory)).ToArray();
        // Scheduling priority does not alter the logical scope/fingerprint of saved caches.
        scanRoots = FileIndexOptions.GetPriorityDirectories().Where(path => !string.IsNullOrEmpty(path))
            .Select(NormalizePath).Where(path => roots.Any(root => IsWithin(path, root)) &&
                !IsWithin(path, cacheDirectory) && Directory.Exists(path))
            .Concat(roots).Distinct(PathComparer).ToArray();
        rootSet = new HashSet<string>(scanRoots, PathComparer);
        rootsFingerprint = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(
            string.Join('\n', roots.Select(root => OperatingSystem.IsWindows() ? root.ToUpperInvariant() : root)
                .OrderBy(root => root, StringComparer.Ordinal)))));
        notificationTimer = new Timer(NotifySubscribers, null, TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(500));
    }

    public FileSearchIndex Index { get; } = new();
    public FileIndexStatus Status => Volatile.Read(ref status);
    /// <remarks>Raised on a worker thread, at most twice per second.</remarks>
    public event EventHandler? Changed;

    /// <summary>Loads any compatible cache, then starts the first scan in the background.</summary>
    public Task StartAsync(CancellationToken cancellationToken = default)
    {
        ThrowIfDisposed();
        cancellationToken.ThrowIfCancellationRequested();
        lock (lifecycleGate)
        {
            initializationTask ??= Task.Run(() => InitializeAsync(lifetime.Token), lifetime.Token);
            return initializationTask.WaitAsync(cancellationToken);
        }
    }

    public async Task RebuildAsync(CancellationToken cancellationToken = default)
    {
        await StartAsync(cancellationToken).ConfigureAwait(false);
        await RequestReconciliation().WaitAsync(cancellationToken).ConfigureAwait(false);
    }

    private async Task InitializeAsync(CancellationToken cancellationToken)
    {
        await LoadCacheAsync(cancellationToken).ConfigureAwait(false);
        cancellationToken.ThrowIfCancellationRequested();
        StartWatchers();
        changePumpTask = Task.Run(() => ProcessChangesAsync(lifetime.Token), lifetime.Token);
        maintenanceTask = Task.Run(() => MaintainAsync(lifetime.Token), lifetime.Token);
        // A valid snapshot already contains searchable names. Do not immediately
        // launch another whole-drive crawl on every app launch. Watch new events now;
        // verify offline mutations later, without delaying the foreground search.
        if (hasCompleteSnapshot)
            SetStatus(current => current with { UsingCachedSnapshot = true, VerificationPending = true });
        else
            _ = RequestReconciliation();
    }

    private Task RequestReconciliation()
    {
        lock (lifecycleGate)
        {
            if (lifetime.IsCancellationRequested)
                return Task.CompletedTask;
            if (reconciliationTask is { IsCompleted: false })
                return reconciliationTask;
            reconciliationTask = Task.Run(() => ReconcileAsync(lifetime.Token), lifetime.Token);
            return reconciliationTask;
        }
    }

    private async Task ReconcileAsync(CancellationToken cancellationToken)
    {
        lock (journalGate)
        {
            scanJournal.Clear();
            scanRunning = true;
        }
        SetStatus(current => current with { IsScanning = true, IsReconciling = hasCompleteSnapshot,
            VerificationPending = false, SkippedDirectories = 0, Error = null });
        lastScanInterrupted = false;
        // A first scan has nothing to prune. Avoid retaining a second dictionary containing
        // every discovered path; only cached paths not yet seen need reconciliation tracking.
        var stalePaths = new HashSet<string>(Index.GetEntriesSnapshot().Select(entry => entry.FullPath), PathComparer);
        try
        {
            await ScanRootsAsync((entries, requiresVerification) =>
                {
                    // Only the single batch consumer touches this set. Preheated
                    // MFT names must be verified just like names restored from cache.
                    TrackVerificationBatch(stalePaths, entries, requiresVerification);
                    Index.AddOrUpdate(entries);
                    MarkIndexChanged(completedMutation: false);
                }, cancellationToken).ConfigureAwait(false);

            Index.RemovePaths(stalePaths, cancellationToken);

            FileChange[] journal;
            lock (journalGate)
            {
                scanRunning = false;
                journal = scanJournal.ToArray();
                scanJournal.Clear();
            }
            await changeApplyGate.WaitAsync(cancellationToken).ConfigureAwait(false);
            try
            {
                foreach (var change in journal)
                    ApplyChange(change, cancellationToken);
            }
            finally
            {
                changeApplyGate.Release();
            }

            SetStatus(current => current with { IsScanning = false, IsReconciling = false, IsNativeWarmup = false,
                UsingCachedSnapshot = false, CurrentRoot = null,
                IndexedCount = Index.Count, LastUpdatedUtc = DateTimeOffset.UtcNow });
            hasCompleteSnapshot = true;
            Interlocked.Exchange(ref cacheDirty, 1);
            await SaveCacheAsync(cancellationToken).ConfigureAwait(false);
        }
        catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
        {
            lastScanInterrupted = true;
            SetStatus(current => current with { IsScanning = false, IsReconciling = false, IsNativeWarmup = false,
                CurrentRoot = null, IndexedCount = Index.Count });
        }
        catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException)
        {
            lastScanInterrupted = true;
            SetStatus(current => current with { IsScanning = false, IsReconciling = false, IsNativeWarmup = false,
                CurrentRoot = null, Error = exception.Message });
        }
        finally
        {
            lock (journalGate)
            {
                scanRunning = false;
                scanJournal.Clear();
            }
        }
    }

    private async Task ScanRootsAsync(Action<IReadOnlyList<FileSearchEntry>, bool> accept, CancellationToken cancellationToken)
    {
        using var scanning = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
        var token = scanning.Token;
        var workerCount = Math.Clamp(options.MaxParallelism, 1, 4);
        // Disk producers never take the search index lock. Limit in-flight name batches
        // to a few thousand entries rather than letting disk IO outrun index construction.
        var batches = Channel.CreateBounded<IndexBatch>(new BoundedChannelOptions(workerCount * 4)
        {
            SingleReader = true, SingleWriter = false, FullMode = BoundedChannelFullMode.Wait,
            AllowSynchronousContinuations = false
        });
        var consumer = FileIndexWorker.Run(() =>
        {
            try
            {
                while (FileIndexWorker.Wait(batches.Reader.WaitToReadAsync(token)))
                    while (batches.Reader.TryRead(out var batch))
                    {
                        token.ThrowIfCancellationRequested();
                        accept(batch.Entries, batch.RequiresVerification);
                    }
            }
            catch
            {
                scanning.Cancel();
                throw;
            }
        }, "File index builder", token);

        void Submit(IReadOnlyList<FileSearchEntry> entries, bool requiresVerification = false) =>
            FileIndexWorker.Wait(batches.Writer.WriteAsync(new(entries as FileSearchEntry[] ?? entries.ToArray(), requiresVerification), token));

        // Directory discovery is self-feeding. It must not block on a bounded directory
        // queue (all producers could wait for capacity); only the independently consumed
        // file-batch pipeline above applies backpressure.
        var pending = Channel.CreateUnbounded<DirectoryWork>(new UnboundedChannelOptions
            { SingleReader = false, SingleWriter = false, AllowSynchronousContinuations = false });
        var outstanding = 0;

        void ScanWorker()
        {
            var batch = new List<FileSearchEntry>(BatchSize);
            var lastPublish = Stopwatch.GetTimestamp();
            string? currentRoot = null;
            void Publish()
            {
                if (batch.Count == 0)
                    return;
                Submit(batch);
                batch.Clear();
                lastPublish = Stopwatch.GetTimestamp();
            }
            try
            {
                while (FileIndexWorker.Wait(pending.Reader.WaitToReadAsync(token)))
                while (pending.Reader.TryRead(out var work))
                {
                    token.ThrowIfCancellationRequested();
                    if (!PathComparer.Equals(currentRoot, work.Root))
                    {
                        currentRoot = work.Root;
                        SetStatus(current => current with { CurrentRoot = work.Root });
                    }
                    try
                    {
                        var normalizedDirectory = FileSearchEntry.NormalizePath(work.Path);
                        EnumerateDirectory(work.Path, entry =>
                        {
                            batch.Add(FileSearchEntry.FromDirectory(entry.FullPath, entry.IsDirectory, work.Path, normalizedDirectory));
                            if (entry.IsDirectory && !entry.IsReparsePoint && !rootSet.Contains(entry.FullPath))
                            {
                                Interlocked.Increment(ref outstanding);
                                pending.Writer.TryWrite(new(entry.FullPath, work.Root));
                            }
                            if (batch.Count >= BatchSize || Stopwatch.GetElapsedTime(lastPublish).TotalMilliseconds >= 100)
                                Publish();
                        }, token);
                    }
                    finally
                    {
                        if (Interlocked.Decrement(ref outstanding) == 0)
                            pending.Writer.TryComplete();
                    }
                }
                Publish();
            }
            catch (Exception exception)
            {
                // If one worker fails, release readers waiting for more work as well.
                pending.Writer.TryComplete(exception);
                throw;
            }
        }

        Task[] workers = [];
        try
        {
            // Seed and native reads also run on a dedicated low-IO-priority thread.
            await FileIndexWorker.Run(() =>
            {
                if (options.EnableNtfsWarmup && !hasCompleteSnapshot)
                {
                    foreach (var root in roots)
                    {
                        token.ThrowIfCancellationRequested();
                        if (!NtfsVolumeScanner.TryNormalizeVolumeRoot(root, out _)) continue;
                        SetStatus(current => current with { IsNativeWarmup = true, CurrentRoot = root });
                        // MFT primary names become searchable early. A normal scan still
                        // follows to cover hard-link aliases and establish a complete snapshot.
                        NtfsVolumeScanner.TryScan(root, entries => Submit(entries.Where(entry =>
                            !IsCachePath(entry.FullPath)).ToArray(), requiresVerification: true), token);
                    }
                    SetStatus(current => current with { IsNativeWarmup = false });
                }
                foreach (var root in scanRoots)
                {
                    token.ThrowIfCancellationRequested();
                    if (!TryGetRoot(root, out var entry, out var canTraverse)) continue;
                    Submit([entry]);
                    if (canTraverse)
                    {
                        outstanding++;
                        pending.Writer.TryWrite(new(root, root));
                    }
                }
                if (outstanding == 0) pending.Writer.TryComplete();
            }, "File index disk initialization", token, backgroundIo: true).ConfigureAwait(false);

            workers = Enumerable.Range(0, workerCount).Select(number =>
                FileIndexWorker.Run(ScanWorker, $"File index disk {number + 1}", token, backgroundIo: true)).ToArray();
            await Task.WhenAll(workers).ConfigureAwait(false);
            batches.Writer.TryComplete();
            await consumer.ConfigureAwait(false);
        }
        finally
        {
            scanning.Cancel();
            pending.Writer.TryComplete();
            batches.Writer.TryComplete();
            try { await Task.WhenAll(workers.Append(consumer)).ConfigureAwait(false); }
            catch (OperationCanceledException) when (token.IsCancellationRequested) { }
        }
    }

    internal static void TrackVerificationBatch(HashSet<string> stalePaths,
        IReadOnlyList<FileSearchEntry> entries, bool requiresVerification)
    {
        if (!requiresVerification && stalePaths.Count == 0) return;
        foreach (var entry in entries)
            if (requiresVerification) stalePaths.Add(entry.FullPath);
            else stalePaths.Remove(entry.FullPath);
    }

    private bool TryGetRoot(string root, out FileSearchEntry entry, out bool canTraverse)
    {
        entry = null!;
        canTraverse = false;
        if (IsCachePath(root))
            return false;
        try
        {
            var attributes = File.GetAttributes(root);
            if ((attributes & FileAttributes.Directory) == 0)
                return false;
            entry = new(root, true);
            canTraverse = (attributes & FileAttributes.ReparsePoint) == 0;
            return true;
        }
        catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or System.Security.SecurityException)
        {
            RecordSkippedDirectory();
            return false;
        }
    }

    private void EnumerateDirectory(string directory, Action<ScanEntry> accept, CancellationToken cancellationToken)
    {
        try
        {
            var enumeration = new FileSystemEnumerable<ScanEntry>(directory,
                (ref FileSystemEntry entry) => new ScanEntry(entry.ToFullPath(), entry.IsDirectory,
                    (entry.Attributes & FileAttributes.ReparsePoint) != 0),
                new EnumerationOptions { RecurseSubdirectories = false, IgnoreInaccessible = false,
                    AttributesToSkip = 0, ReturnSpecialDirectories = false, BufferSize = 64 * 1024 });
            foreach (var entry in enumeration)
            {
                cancellationToken.ThrowIfCancellationRequested();
                if (!IsCachePath(entry.FullPath))
                    accept(entry);
            }
        }
        catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or System.Security.SecurityException)
        {
            RecordSkippedDirectory();
        }
    }

    private void ScanTree(string root, Action<IReadOnlyList<FileSearchEntry>> accept,
        CancellationToken cancellationToken)
    {
        if (!TryGetRoot(root, out var rootEntry, out var canTraverse))
            return;
        var pending = new Stack<string>();
        var batch = new List<FileSearchEntry>(BatchSize);
        batch.Add(rootEntry);
        if (canTraverse)
            pending.Push(root);
        while (pending.TryPop(out var directory))
        {
            cancellationToken.ThrowIfCancellationRequested();
            var normalizedDirectory = FileSearchEntry.NormalizePath(directory);
            EnumerateDirectory(directory, entry =>
            {
                batch.Add(FileSearchEntry.FromDirectory(entry.FullPath, entry.IsDirectory, directory, normalizedDirectory));
                if (entry.IsDirectory && !entry.IsReparsePoint)
                    pending.Push(entry.FullPath);
                if (batch.Count >= BatchSize)
                {
                    accept(batch);
                    batch.Clear();
                }
            }, cancellationToken);
        }
        if (batch.Count > 0)
            accept(batch);
    }

    private void StartWatchers()
    {
        foreach (var root in roots.Where(root => !roots.Any(other =>
                     !PathComparer.Equals(root, other) && IsWithin(root, other))))
        {
            try
            {
                var watcher = new FileSystemWatcher(root)
                {
                    IncludeSubdirectories = true,
                    NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite | NotifyFilters.Size,
                    InternalBufferSize = 64 * 1024
                };
                watcher.Created += (_, args) => QueueChange(new FileChange(args.FullPath, null, false));
                watcher.Deleted += (_, args) => QueueChange(new FileChange(args.FullPath, null, true));
                watcher.Renamed += (_, args) => QueueChange(new FileChange(args.FullPath, args.OldFullPath, false));
                watcher.Changed += (_, args) => QueueChange(new FileChange(args.FullPath, null, false, ContentChanged: true));
                watcher.Error += (_, _) => { Interlocked.Exchange(ref reconciliationNeeded, 1); SignalChanges(); };
                watcher.EnableRaisingEvents = true;
                watchers.Add(watcher);
            }
            catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException)
            {
                // Periodic reconciliation still discovers changes if Windows cannot watch a root.
                RecordSkippedDirectory();
            }
        }
    }

    private void QueueChange(FileChange change)
    {
        if (lifetime.IsCancellationRequested)
            return;
        if (IsCachePath(change.Path))
        {
            if (change.OldPath is null || IsCachePath(change.OldPath))
                return;
            change = new FileChange(change.OldPath, null, true);
        }
        lock (journalGate)
        {
            if (scanRunning)
            {
                if (scanJournal.Count < MaximumQueuedChanges)
                    scanJournal.Add(change);
                else
                    Interlocked.Exchange(ref reconciliationNeeded, 1);
            }
        }
        if (Interlocked.Increment(ref queuedChanges) <= MaximumQueuedChanges)
            pendingChanges.Enqueue(change);
        else
        {
            Interlocked.Decrement(ref queuedChanges);
            Interlocked.Exchange(ref reconciliationNeeded, 1);
        }
        SignalChanges();
    }

    private void SignalChanges() => changeSignal.Writer.TryWrite(0);

    private async Task ProcessChangesAsync(CancellationToken cancellationToken)
    {
        try
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                await changeSignal.Reader.ReadAsync(cancellationToken).ConfigureAwait(false);
                await Task.Delay(options.WatchDebounce, cancellationToken).ConfigureAwait(false);
                await changeApplyGate.WaitAsync(cancellationToken).ConfigureAwait(false);
                try
                {
                    while (pendingChanges.TryDequeue(out var change))
                    {
                        Interlocked.Decrement(ref queuedChanges);
                        ApplyChange(change, cancellationToken);
                    }
                }
                finally { changeApplyGate.Release(); }
                if (Volatile.Read(ref reconciliationNeeded) != 0)
                {
                    // If a scan was already running, reconcile again after it ends: events may have overflowed its journal.
                    await RequestReconciliation().ConfigureAwait(false);
                    if (Interlocked.Exchange(ref reconciliationNeeded, 0) != 0)
                        await RequestReconciliation().ConfigureAwait(false);
                }
            }
        }
        catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { }
    }

    private void ApplyChange(FileChange change, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();
        if (change.ContentChanged)
        {
            // Filename identity is unchanged, but opt-in content search needs a new reconciliation signal.
            SetStatus(current => current with { LastUpdatedUtc = DateTimeOffset.UtcNow });
            return;
        }
        if (change.OldPath is not null)
            Index.RemovePath(change.OldPath, true);
        if (change.Deleted)
            Index.RemovePath(change.Path, true);
        else
        {
            try
            {
                var attributes = File.GetAttributes(change.Path);
                if ((attributes & FileAttributes.Directory) != 0)
                {
                    if ((attributes & FileAttributes.ReparsePoint) == 0)
                        ScanTree(change.Path, entries => Index.AddOrUpdate(entries), cancellationToken);
                    else
                        Index.AddOrUpdate([new FileSearchEntry(change.Path, true)]);
                }
                else
                    Index.AddOrUpdate([new FileSearchEntry(change.Path, false)]);
            }
            catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or System.Security.SecurityException)
            {
                Index.RemovePath(change.Path, true);
            }
        }
        MarkIndexChanged();
    }

    private async Task MaintainAsync(CancellationToken cancellationToken)
    {
        var lastReconciliation = DateTimeOffset.UtcNow;
        var interval = options.ReconciliationInterval < TimeSpan.FromSeconds(1)
            ? TimeSpan.FromSeconds(1) : options.ReconciliationInterval;
        var cachedVerificationDue = DateTimeOffset.UtcNow +
            (options.CachedVerificationDelay < TimeSpan.Zero ? TimeSpan.Zero : options.CachedVerificationDelay);
        try
        {
            using var timer = new PeriodicTimer(TimeSpan.FromSeconds(30));
            while (await timer.WaitForNextTickAsync(cancellationToken).ConfigureAwait(false))
            {
                if ((Status.VerificationPending && DateTimeOffset.UtcNow >= cachedVerificationDue) ||
                    DateTimeOffset.UtcNow - lastReconciliation >= interval)
                {
                    await RequestReconciliation().ConfigureAwait(false);
                    lastReconciliation = DateTimeOffset.UtcNow;
                }
                else if (Volatile.Read(ref cacheDirty) != 0 && !Status.IsScanning)
                    await SaveCacheAsync(cancellationToken).ConfigureAwait(false);
            }
        }
        catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { }
    }

    private async Task LoadCacheAsync(CancellationToken cancellationToken)
    {
        if (!File.Exists(cachePath))
            return;
        var acceptedCacheBatch = false;
        var completeCache = false;
        try
        {
            if (new FileInfo(cachePath).Length > MaximumCacheFileBytes)
                return;
            await using var file = new FileStream(cachePath, FileMode.Open, FileAccess.Read, FileShare.Read,
                64 * 1024, FileOptions.SequentialScan);
            using var compressed = new GZipStream(file, CompressionMode.Decompress);
            using var reader = new BinaryReader(compressed, Encoding.UTF8, leaveOpen: true);
            if (reader.ReadInt32() != CacheMagic || reader.ReadInt32() != CacheVersion ||
                ReadString(reader, 128) != rootsFingerprint)
                return;
            var count = reader.ReadInt32();
            if (count < 0 || count > MaximumCacheEntries)
                return;
            // Publish small batches while decoding rather than staging millions of full
            // objects before any cached result can be searched. This also bounds memory.
            var entries = new List<FileSearchEntry>(BatchSize);
            long decodedBytes = 0;
            for (var index = 0; index < count; index++)
            {
                cancellationToken.ThrowIfCancellationRequested();
                var path = ReadString(reader, MaximumPathBytes);
                decodedBytes += (long)path.Length * sizeof(char) + sizeof(int) + sizeof(byte);
                if (decodedBytes > MaximumDecodedCacheBytes)
                    return;
                var entryKind = reader.ReadByte();
                if (entryKind > 1 || path.Contains('\0') || !Path.IsPathFullyQualified(path) || IsCachePath(path) ||
                    !roots.Any(root => IsWithin(path, root)))
                    continue;
                entries.Add(new FileSearchEntry(path, entryKind == 1));
                if (entries.Count >= BatchSize)
                {
                    acceptedCacheBatch = true;
                    Index.AddOrUpdate(entries);
                    entries.Clear();
                    SetStatus(current => current with { IndexedCount = Index.Count });
                }
            }
            if (compressed.ReadByte() != -1)
                return;
            if (entries.Count > 0)
            {
                cancellationToken.ThrowIfCancellationRequested();
                acceptedCacheBatch = true;
                Index.AddOrUpdate(entries);
            }
            completeCache = true;
            hasCompleteSnapshot = true;
            SetStatus(current => current with { IndexedCount = Index.Count,
                LastUpdatedUtc = new DateTimeOffset(File.GetLastWriteTimeUtc(cachePath), TimeSpan.Zero) });
        }
        catch (Exception exception) when (exception is IOException or InvalidDataException or UnauthorizedAccessException or ArgumentException)
        {
            // A partial write, obsolete format, or corrupt cache is replaced after the next successful scan.
        }
        finally
        {
            if (acceptedCacheBatch && !completeCache)
            {
                // Do not keep a valid-looking prefix from an untrusted/truncated snapshot.
                Index.Clear();
                SetStatus(current => current with { IndexedCount = 0 });
            }
        }
    }

    private async Task SaveCacheAsync(CancellationToken cancellationToken)
    {
        await saveGate.WaitAsync(cancellationToken).ConfigureAwait(false);
        string? temporaryPath = null;
        try
        {
            cancellationToken.ThrowIfCancellationRequested();
            Directory.CreateDirectory(cacheDirectory);
            temporaryPath = Path.Combine(cacheDirectory, $"files.{Guid.NewGuid():N}.tmp");
            Interlocked.Exchange(ref cacheDirty, 0);
            var entries = Index.GetEntriesSnapshot();
            await using (var file = new FileStream(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None,
                             64 * 1024, FileOptions.SequentialScan))
            {
                using (var compressed = new GZipStream(file, CompressionLevel.Fastest, leaveOpen: true))
                using (var writer = new BinaryWriter(compressed, Encoding.UTF8, leaveOpen: true))
                {
                    writer.Write(CacheMagic);
                    writer.Write(CacheVersion);
                    WriteString(writer, rootsFingerprint);
                    writer.Write(entries.Count);
                    foreach (var entry in entries)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        WriteString(writer, entry.FullPath);
                        writer.Write((byte)(entry.IsDirectory ? 1 : 0));
                    }
                }
                await file.FlushAsync(cancellationToken).ConfigureAwait(false);
            }
            File.Move(temporaryPath, cachePath, overwrite: true);
            temporaryPath = null;
        }
        catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
        {
            Interlocked.Exchange(ref cacheDirty, 1);
            SetStatus(current => current with { Error = exception.Message });
        }
        finally
        {
            if (temporaryPath is not null)
            {
                try { File.Delete(temporaryPath); }
                catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) { }
            }
            saveGate.Release();
        }
    }

    private static string ReadString(BinaryReader reader, int maximumBytes)
    {
        var length = reader.ReadInt32();
        if (length < 0 || length > maximumBytes)
            throw new InvalidDataException("Invalid file index string length.");
        byte[]? rented = null;
        Span<byte> bytes = length <= 1024 ? stackalloc byte[length]
            : (rented = ArrayPool<byte>.Shared.Rent(length)).AsSpan(0, length);
        try
        {
            reader.BaseStream.ReadExactly(bytes);
            return Encoding.UTF8.GetString(bytes);
        }
        finally
        {
            if (rented is not null)
                ArrayPool<byte>.Shared.Return(rented);
        }
    }

    private static void WriteString(BinaryWriter writer, string value)
    {
        var length = Encoding.UTF8.GetByteCount(value);
        byte[]? rented = null;
        Span<byte> bytes = length <= 1024 ? stackalloc byte[length]
            : (rented = ArrayPool<byte>.Shared.Rent(length)).AsSpan(0, length);
        try
        {
            Encoding.UTF8.GetBytes(value.AsSpan(), bytes);
            writer.Write(length);
            writer.Write(bytes);
        }
        finally
        {
            if (rented is not null)
                ArrayPool<byte>.Shared.Return(rented);
        }
    }

    private void MarkIndexChanged(bool completedMutation = true)
    {
        Interlocked.Exchange(ref cacheDirty, 1);
        SetStatus(current => current with { IndexedCount = Index.Count,
            LastUpdatedUtc = completedMutation ? DateTimeOffset.UtcNow : current.LastUpdatedUtc });
    }

    private void RecordSkippedDirectory() => SetStatus(current => current with { SkippedDirectories = current.SkippedDirectories + 1 });

    private void SetStatus(Func<FileIndexStatus, FileIndexStatus> update)
    {
        lock (statusGate)
            Volatile.Write(ref status, update(status));
        Interlocked.Exchange(ref notificationsPending, 1);
    }

    private void NotifySubscribers(object? state)
    {
        if (Interlocked.Exchange(ref notificationsPending, 0) == 0 || Volatile.Read(ref disposed) != 0)
            return;
        var handlers = Changed;
        if (handlers is null)
            return;
        foreach (EventHandler handler in handlers.GetInvocationList())
        {
            try { handler(this, EventArgs.Empty); }
            catch { /* UI subscribers cannot terminate background index maintenance. */ }
        }
    }

    private static string NormalizePath(string path) => Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));

    private bool IsCachePath(string path) => PathComparer.Equals(path, cacheDirectory) ||
        path.StartsWith(cacheDirectoryPrefix, OperatingSystem.IsWindows()
            ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);

    private static bool IsWithin(string path, string parent) => PathComparer.Equals(path, parent) ||
        path.StartsWith(Path.EndsInDirectorySeparator(parent) ? parent : parent + Path.DirectorySeparatorChar,
            OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);

    private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(Volatile.Read(ref disposed) != 0, this);

    /// <summary>Immediately requests cancellation without waiting for filesystem work to finish.</summary>
    public void RequestStop()
    {
        if (!lifetime.IsCancellationRequested)
            lifetime.Cancel();
    }

    public async ValueTask DisposeAsync()
    {
        if (Interlocked.Exchange(ref disposed, 1) != 0)
            return;
        var interruptedScan = Status.IsScanning;
        RequestStop();
        await notificationTimer.DisposeAsync().ConfigureAwait(false);
        var initialization = initializationTask;
        if (initialization is not null)
        {
            try { await initialization.ConfigureAwait(false); }
            catch (OperationCanceledException) { }
        }
        foreach (var watcher in watchers)
            watcher.Dispose();
        Task?[] tasks;
        lock (lifecycleGate)
            tasks = [initializationTask, reconciliationTask, changePumpTask, maintenanceTask];
        foreach (var task in tasks)
        {
            if (task is null)
                continue;
            try { await task.ConfigureAwait(false); }
            catch (OperationCanceledException) { }
        }
        // Only a complete scan is persisted. A canceled first scan will be rebuilt at the next launch.
        if (!interruptedScan && !lastScanInterrupted && hasCompleteSnapshot && Volatile.Read(ref cacheDirty) != 0)
            await SaveCacheAsync(CancellationToken.None).ConfigureAwait(false);
        lifetime.Dispose();
        // The pump has already stopped. Completing now also makes late watcher
        // callbacks a harmless failed TryWrite rather than a disposed-resource exception.
        changeSignal.Writer.TryComplete();
        changeApplyGate.Dispose();
        saveGate.Dispose();
    }

    private sealed record FileChange(string Path, string? OldPath, bool Deleted, bool ContentChanged = false);
    private readonly record struct ScanEntry(string FullPath, bool IsDirectory, bool IsReparsePoint);
    private readonly record struct DirectoryWork(string Path, string Root);
    private readonly record struct IndexBatch(FileSearchEntry[] Entries, bool RequiresVerification);
}