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

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Buffers;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace XFEToolBox.Client.Core.Search;

/// <summary>
/// An incremental in-memory name index. Bi/trigram postings index basenames and each distinct
/// directory path once, rather than indexing the same complete parent path for every file.
/// Queries have no filesystem IO and retain only the requested best result window.
/// </summary>
public sealed class FileSearchIndex
{
    private const int MaximumWriteBatchSize = 256;
    private readonly ReaderWriterLockSlim gate = new();
    private readonly Dictionary<string, int> paths = new(StringComparer.OrdinalIgnoreCase);
    private readonly List<EntrySlot?> entries = [];
    private readonly Dictionary<string, int> directoryIds = new(StringComparer.OrdinalIgnoreCase);
    private readonly List<DirectorySlot> directories = [];
    private readonly Dictionary<ulong, PostingList> nameGrams = [];
    private readonly Dictionary<ulong, PostingList> directoryGrams = [];
    private int removedCount;
    private int liveCount;

    // Progress is read by the UI. It must never wait for an index writer or a filesystem iterator.
    public int Count => Volatile.Read(ref liveCount);

    public void AddOrUpdate(IEnumerable<FileSearchEntry> values)
    {
        ArgumentNullException.ThrowIfNull(values);
        using var enumerator = values.GetEnumerator();
        var batch = new FileSearchEntry[MaximumWriteBatchSize];
        while (true)
        {
            var count = 0;
            // Enumerating a filesystem source can perform slow IO. Do all of it outside the gate.
            while (count < batch.Length && enumerator.MoveNext())
                batch[count++] = enumerator.Current;
            if (count == 0)
                return;
            gate.EnterWriteLock();
            try
            {
                for (var index = 0; index < count; index++)
                    AddCore(batch[index]);
                Volatile.Write(ref liveCount, paths.Count);
                CompactIfNecessary();
            }
            finally { gate.ExitWriteLock(); }
            Array.Clear(batch, 0, count);
        }
    }

    public void Clear()
    {
        gate.EnterWriteLock();
        try { ClearCore(); }
        finally { gate.ExitWriteLock(); }
    }

    private void ClearCore()
    {
        paths.Clear();
        entries.Clear();
        directoryIds.Clear();
        directories.Clear();
        nameGrams.Clear();
        directoryGrams.Clear();
        removedCount = 0;
        Volatile.Write(ref liveCount, 0);
    }

    /// <summary>Prunes a completed scan's stale paths without repeatedly rebuilding the index.</summary>
    public void RemovePaths(IEnumerable<string> values, CancellationToken cancellationToken = default)
    {
        ArgumentNullException.ThrowIfNull(values);
        using var enumerator = values.GetEnumerator();
        var batch = new string[MaximumWriteBatchSize];
        while (true)
        {
            cancellationToken.ThrowIfCancellationRequested();
            var count = 0;
            while (count < batch.Length && enumerator.MoveNext())
                batch[count++] = FileSearchEntry.NormalizePath(enumerator.Current);
            if (count == 0)
                break;
            while (!gate.TryEnterWriteLock(50))
                cancellationToken.ThrowIfCancellationRequested();
            try
            {
                cancellationToken.ThrowIfCancellationRequested();
                for (var index = 0; index < count; index++)
                    if (paths.TryGetValue(batch[index], out var id))
                        RemoveCore(id);
                Volatile.Write(ref liveCount, paths.Count);
            }
            finally { gate.ExitWriteLock(); }
            Array.Clear(batch, 0, count);
        }
        while (!gate.TryEnterWriteLock(50))
            cancellationToken.ThrowIfCancellationRequested();
        try
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (paths.Count == 0)
                ClearCore();
            else
                CompactIfNecessary();
        }
        finally { gate.ExitWriteLock(); }
    }

    public void RemovePath(string path, bool includeDescendants)
    {
        path = FileSearchEntry.NormalizePath(path);
        gate.EnterWriteLock();
        try
        {
            if (paths.TryGetValue(path, out var id))
                RemoveCore(id);
            if (includeDescendants)
            {
                var prefix = path.EndsWith('\\') ? path : path + '\\';
                for (var index = 0; index < entries.Count; index++)
                    if (entries[index]?.Entry.SearchPath.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) == true)
                        RemoveCore(index);
            }
            Volatile.Write(ref liveCount, paths.Count);
            CompactIfNecessary();
        }
        finally { gate.ExitWriteLock(); }
    }

    public IReadOnlyList<FileSearchEntry> GetEntriesSnapshot()
    {
        gate.EnterReadLock();
        try { return entries.Where(slot => slot is not null).Select(slot => slot!.Entry).ToArray(); }
        finally { gate.ExitReadLock(); }
    }

    public bool ContainsPath(string path)
    {
        path = FileSearchEntry.NormalizePath(path);
        gate.EnterReadLock();
        try { return paths.ContainsKey(path); }
        finally { gate.ExitReadLock(); }
    }

    public FileSearchResults Search(string query, int offset = 0, int limit = 100, CancellationToken cancellationToken = default,
        Func<FileSearchEntry, bool>? filter = null) =>
        TrySearch(query, offset, limit, cancellationToken, filter) ?? throw new OperationCanceledException(cancellationToken);

    /// <summary>Latest-query UI path: cancellation is a result, not an exception used for control flow.</summary>
    public FileSearchResults? TrySearch(string query, int offset = 0, int limit = 100,
        CancellationToken cancellationToken = default, Func<FileSearchEntry, bool>? filter = null)
    {
        var watch = Stopwatch.StartNew();
        if (cancellationToken.IsCancellationRequested) return null;
        var parsed = FileSearchQuery.Parse(query);
        if (parsed.IsEmpty || parsed.Error is not null)
            return new([], 0, watch.Elapsed);
        offset = Math.Max(0, offset);
        limit = Math.Max(0, limit);

        var snapshot = CaptureCandidates(parsed, cancellationToken);
        if (snapshot is null) return null;
        var (candidates, candidateCount) = snapshot.Value;
        try
        {
            // Entries are immutable. Match and rank the captured generation without holding a
            // reader lock. The scratch array is pooled: repeated broad queries must not allocate
            // another multi-megabyte LOH array and trigger foreground-wide GC pauses per keypress.
            var resultCount = 0;
            var maximumKept = (int)Math.Min((long)offset + limit, candidateCount);
            var best = new PriorityQueue<FileSearchMatch, FileSearchMatch>(WorstFirstComparer.Instance);
            for (var index = 0; index < candidateCount; index++)
            {
                if ((index & 63) == 0)
                    if (cancellationToken.IsCancellationRequested) return null;
                var entry = candidates[index];
                var score = parsed.GetScore(entry);
                if (score == int.MaxValue)
                    continue;
                // Access checks happen outside the index lock, and before counting,
                // so privileged service queries cannot leak inaccessible totals.
                if (filter is not null && !filter(entry)) continue;
                resultCount++;
                if (maximumKept == 0 || limit == 0)
                    continue;
                if (best.Count < maximumKept)
                {
                    var match = new FileSearchMatch(entry, score);
                    best.Enqueue(match, match);
                }
                else if (CompareEntryToMatch(entry, score, best.Peek()) < 0)
                {
                    var match = new FileSearchMatch(entry, score);
                    best.EnqueueDequeue(match, match);
                }
            }

            var results = best.UnorderedItems.Select(item => item.Element).ToArray();
            Array.Sort(results, CompareMatches);
            return new(results.Skip(offset).Take(limit).ToArray(), resultCount, watch.Elapsed);
        }
        finally { ArrayPool<FileSearchEntry>.Shared.Return(candidates, clearArray: true); }
    }

    private (FileSearchEntry[] Entries, int Count)? CaptureCandidates(FileSearchQuery parsed, CancellationToken cancellationToken)
    {
        FileSearchEntry[]? candidates = null;
        var transferred = false;
        try
        {
            while (!gate.TryEnterReadLock(50))
                if (cancellationToken.IsCancellationRequested) return null;
            try
            {
                if (cancellationToken.IsCancellationRequested) return null;
                var candidateIds = GetCandidates(parsed, cancellationToken);
                if (cancellationToken.IsCancellationRequested) return null;
                candidates = ArrayPool<FileSearchEntry>.Shared.Rent(Math.Max(1, candidateIds?.Count ?? paths.Count));
                var count = 0;
                if (candidateIds is null)
                {
                    for (var index = 0; index < entries.Count; index++)
                    {
                        if ((index & 1023) == 0)
                            if (cancellationToken.IsCancellationRequested) return null;
                        if (entries[index] is { } slot)
                            candidates[count++] = slot.Entry;
                    }
                }
                else
                {
                    var seen = 0;
                    foreach (var id in candidateIds)
                    {
                        if ((seen++ & 1023) == 0)
                            if (cancellationToken.IsCancellationRequested) return null;
                        if (entries[id] is { } slot)
                            candidates[count++] = slot.Entry;
                    }
                }
                transferred = true;
                return (candidates, count);
            }
            finally { gate.ExitReadLock(); }
        }
        finally
        {
            if (!transferred && candidates is not null)
                ArrayPool<FileSearchEntry>.Shared.Return(candidates, clearArray: true);
        }
    }

    private void AddCore(FileSearchEntry entry)
    {
        var key = entry.SearchPath;
        if (paths.TryGetValue(key, out var existing))
        {
            var previous = entries[existing]!;
            if (previous.Entry.IsDirectory == entry.IsDirectory && previous.Entry.FullPath.Equals(entry.FullPath, StringComparison.Ordinal))
                return;
            // Windows filesystem identity is case-insensitive; case-only renames need no new postings.
            var directory = directories[previous.DirectoryId];
            entry = entry.ShareDirectory(directory.Path, directory.SearchPath);
            previous.Entry = entry;
            return;
        }
        if (!directoryIds.GetAlternateLookup<ReadOnlySpan<char>>().TryGetValue(entry.SearchDirectorySpan, out var directoryId))
        {
            directoryId = directories.Count;
            directoryIds.Add(entry.SearchDirectoryPath, directoryId);
            directories.Add(new(entry.DirectoryPath, entry.SearchDirectoryPath));
            AddGrams(directoryGrams, entry.SearchDirectoryPath, directoryId);
        }
        else
        {
            var directory = directories[directoryId];
            entry = entry.ShareDirectory(directory.Path, directory.SearchPath);
        }
        var id = entries.Count;
        entries.Add(new(entry, directoryId));
        paths.Add(key, id);
        directories[directoryId].EntryIds.Add(id);
        AddGrams(nameGrams, entry.Name, id);
    }

    private void RemoveCore(int id)
    {
        var slot = entries[id];
        if (slot is null)
            return;
        paths.Remove(slot.Entry.SearchPath);
        directories[slot.DirectoryId].EntryIds.Remove(id);
        entries[id] = null;
        removedCount++;
    }

    private void CompactIfNecessary()
    {
        if (removedCount < 4096 || removedCount < entries.Count / 3)
            return;
        var remaining = entries.Where(slot => slot is not null).Select(slot => slot!.Entry).ToArray();
        paths.Clear();
        entries.Clear();
        directoryIds.Clear();
        directories.Clear();
        nameGrams.Clear();
        directoryGrams.Clear();
        removedCount = 0;
        foreach (var entry in remaining)
            AddCore(entry);
    }

    private HashSet<int>? GetCandidates(FileSearchQuery query, CancellationToken cancellationToken)
    {
        var union = new HashSet<int>();
        foreach (var group in query.Groups)
        {
            if (cancellationToken.IsCancellationRequested) return null;
            CandidatePlan[]? bestPlans = null;
            long bestSize = long.MaxValue;
            foreach (var term in group.Terms)
            {
                if (term.Excluded)
                    continue;
                var fragments = term.CandidateFragments;
                if (fragments.Count == 0)
                    continue;
                var plans = new List<CandidatePlan>();
                var possible = true;
                long size = 0;
                foreach (var fragment in fragments)
                {
                    if (string.IsNullOrEmpty(fragment) || !TryCreatePlan(fragment, term.Scope, out var plan))
                    {
                        possible = false;
                        break;
                    }
                    plans.Add(plan);
                    size += plan.EstimatedCount;
                }
                if (possible && size < bestSize)
                {
                    bestSize = size;
                    bestPlans = plans.ToArray();
                }
            }
            // An unbounded OR branch (for example !*.tmp) requires considering every live entry.
            if (bestPlans is null)
                return null;
            // A broad posting would allocate a near-full HashSet only to copy every entry again.
            // A linear snapshot is cheaper, and still applies the complete query when matching.
            if (bestSize > paths.Count / 2)
                return null;
            foreach (var plan in bestPlans)
            {
                if (plan.NamePosting is not null)
                {
                    var count = 0;
                    foreach (var id in plan.NamePosting)
                    {
                        if ((count++ & 1023) == 0)
                            if (cancellationToken.IsCancellationRequested) return null;
                        if (entries[id] is not null)
                            union.Add(id);
                    }
                }
                if (plan.DirectoryPosting is not null)
                    foreach (var directoryId in plan.DirectoryPosting)
                    {
                        if (cancellationToken.IsCancellationRequested) return null;
                        union.UnionWith(directories[directoryId].EntryIds);
                    }
            }
        }
        return union;
    }

    private bool TryCreatePlan(string fragment, FileSearchQuery.CandidateScope scope, out CandidatePlan plan)
    {
        var normalized = fragment.ToUpperInvariant();
        var gramLength = normalized.Length >= 3 ? 3 : normalized.Length;
        // ASCII one-character queries deliberately scan names instead of retaining another
        // full posting per character per file. Non-ASCII unigrams keep Chinese searches fast.
        if (gramLength == 1 && normalized[0] < 128)
        {
            plan = default;
            return false;
        }
        var namePosting = FindSmallestPosting(nameGrams, normalized, gramLength);
        var directoryPosting = scope == FileSearchQuery.CandidateScope.Any
            ? FindSmallestPosting(directoryGrams, normalized, gramLength) : null;
        long count = namePosting?.Count ?? 0;
        if (directoryPosting is not null)
            foreach (var directoryId in directoryPosting)
                count += directories[directoryId].EntryIds.Count;
        plan = new(namePosting, directoryPosting, count);
        return true;
    }

    private static PostingList? FindSmallestPosting(Dictionary<ulong, PostingList> source, string value, int length)
    {
        PostingList? smallest = null;
        for (var index = 0; index <= value.Length - length; index++)
        {
            if (!source.TryGetValue(GetGram(value, index, length), out var posting))
                return null;
            if (smallest is null || posting.Count < smallest.Count)
                smallest = posting;
        }
        return smallest;
    }

    private void AddGrams(Dictionary<ulong, PostingList> destination, string value, int id)
    {
        // String casing handles supplementary Unicode characters as complete code points. ASCII
        // filenames use the allocation-free char path; non-ASCII names keep the same normalization
        // as query planning, including surrogate-pair case mappings.
        if (value.AsSpan().IndexOfAnyExceptInRange('\0', '\x7f') >= 0)
            value = value.ToUpperInvariant();
        // Each posting already remembers its newest ID, so it can de-duplicate repeated grams
        // without a second hash table per filename. Roll the preceding two characters forward
        // rather than casing every character up to five times for overlapping bi/trigrams.
        uint previous = 0;
        uint preceding = 0;
        for (var index = 0; index < value.Length; index++)
        {
            var character = value[index];
            uint current = character is >= 'a' and <= 'z' ? (uint)(character - 32) : character;
            if (character >= 128)
                AppendGram(destination, (1UL << 48) | current, id);
            if (index > 0)
                AppendGram(destination, (2UL << 48) | previous | ((ulong)current << 16), id);
            if (index > 1)
                AppendGram(destination, (3UL << 48) | preceding | ((ulong)previous << 16) | ((ulong)current << 32), id);
            preceding = previous;
            previous = current;
        }
    }

    private static void AppendGram(Dictionary<ulong, PostingList> destination, ulong gram, int id)
    {
        ref var posting = ref CollectionsMarshal.GetValueRefOrAddDefault(destination, gram, out _);
        posting ??= new();
        posting.Add(id);
    }

    private static ulong GetGram(string value, int index, int length)
    {
        var key = (ulong)length << 48;
        for (var offset = 0; offset < length; offset++)
            key |= (ulong)value[index + offset] << (offset * 16);
        return key;
    }

    private static int CompareMatches(FileSearchMatch left, FileSearchMatch right)
    {
        var score = left.Score.CompareTo(right.Score);
        return score != 0 ? score : StringComparer.OrdinalIgnoreCase.Compare(left.Entry.FullPath, right.Entry.FullPath);
    }

    private static int CompareEntryToMatch(FileSearchEntry entry, int score, FileSearchMatch right)
    {
        var comparison = score.CompareTo(right.Score);
        return comparison != 0 ? comparison : StringComparer.OrdinalIgnoreCase.Compare(entry.FullPath, right.Entry.FullPath);
    }

    private sealed class EntrySlot(FileSearchEntry entry, int directoryId)
    {
        public FileSearchEntry Entry { get; set; } = entry;
        public int DirectoryId { get; } = directoryId;
    }
    private sealed class DirectorySlot(string path, string searchPath)
    {
        public string Path { get; } = path;
        public string SearchPath { get; } = searchPath;
        public HashSet<int> EntryIds { get; } = [];
    }
    private readonly record struct CandidatePlan(PostingList? NamePosting, PostingList? DirectoryPosting, long EstimatedCount);

    // Entry IDs are append-only and therefore monotonic in every posting. Delta/variable-byte
    // encoding uses one byte for the common adjacent IDs instead of four bytes per gram.
    // Tombstones are checked against entries and periodically compacted as one generation.
    private sealed class PostingList
    {
        private readonly List<byte> bytes = [];
        private int lastId;
        public int Count { get; private set; }

        public void Add(int id)
        {
            if (Count > 0 && id == lastId)
                return;
            var delta = (uint)(id - lastId);
            while (delta >= 128)
            {
                bytes.Add((byte)((delta & 127) | 128));
                delta >>= 7;
            }
            bytes.Add((byte)delta);
            lastId = id;
            Count++;
        }

        public Enumerator GetEnumerator() => new(bytes);

        public struct Enumerator(List<byte> bytes)
        {
            private int offset;
            private int id;
            public int Current { get; private set; }

            public bool MoveNext()
            {
                if (offset >= bytes.Count)
                    return false;
                uint delta = 0;
                var shift = 0;
                byte current;
                do
                {
                    current = bytes[offset++];
                    delta |= (uint)(current & 127) << shift;
                    shift += 7;
                } while ((current & 128) != 0);
                id += (int)delta;
                Current = id;
                return true;
            }
        }
    }
    private sealed class WorstFirstComparer : IComparer<FileSearchMatch>
    {
        public static WorstFirstComparer Instance { get; } = new();
        public int Compare(FileSearchMatch? x, FileSearchMatch? y) => CompareMatches(y!, x!);
    }
}