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

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Diagnostics;
using System.Text;
using Microsoft.Data.Sqlite;
using SQLitePCL;

namespace XFEToolBox.Client.Core.Search;

public sealed record FileContentIndexStatus(bool IsIndexing, int IndexedCount, int SkippedCount, string? Error = null);

/// <summary>
/// Optional, local-only text index. Nothing is opened or read until EnsureIndexAsync is called.
/// Plain text/code files up to MaximumFileBytes are supported; binary, cloud placeholders,
/// Office/PDF documents, and other unsupported formats are counted as skipped.
/// </summary>
public sealed class FileContentSearchService : IAsyncDisposable
{
    public const long DefaultMaximumFileBytes = 8 * 1024 * 1024;

    private static readonly HashSet<string> TextExtensions = new(StringComparer.OrdinalIgnoreCase)
    {
        ".txt", ".text", ".md", ".markdown", ".rst", ".log", ".csv", ".tsv", ".json", ".jsonl",
        ".xml", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf", ".config", ".properties",
        ".cs", ".csx", ".vb", ".fs", ".fsx", ".xaml", ".razor", ".cshtml", ".resx",
        ".csproj", ".vbproj", ".fsproj", ".props", ".targets", ".sln", ".slnx", ".nuspec",
        ".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hxx", ".java", ".kt", ".kts", ".swift",
        ".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".vue", ".svelte", ".html", ".htm",
        ".css", ".scss", ".sass", ".less", ".svg", ".py", ".pyi", ".rb", ".php", ".go", ".rs",
        ".sql", ".sh", ".bash", ".zsh", ".ps1", ".psm1", ".psd1", ".bat", ".cmd", ".lua",
        ".r", ".dart", ".ex", ".exs", ".erl", ".hrl", ".clj", ".cljs", ".groovy", ".gradle",
        ".dockerfile", ".gitignore", ".gitattributes", ".editorconfig", ".env", ".lock"
    };
    private static readonly HashSet<string> TextFileNames = new(StringComparer.OrdinalIgnoreCase)
    {
        "Dockerfile", "Makefile", "CMakeLists.txt", "LICENSE", "NOTICE", "README", ".gitignore",
        ".gitattributes", ".editorconfig", ".env", ".npmrc", ".yarnrc", ".bashrc", ".zshrc"
    };

    private readonly object sync = new();
    private readonly string databasePath;
    private readonly CancellationTokenSource lifetime = new();
    private readonly SemaphoreSlim searchGate = new(2, 2);
    private CancellationTokenSource? indexingCancellation;
    private Task? indexingTask;
    private IReadOnlyList<FileSearchEntry>? pendingEntries;
    private bool isReconciling;
    private int reconciliationGeneration;
    private FileContentIndexStatus status = new(false, 0, 0);
    private bool databaseReady;
    private bool disposed;
    private long lastNotificationTicks;

    public FileContentSearchService(string cacheDirectory, long maximumFileBytes = DefaultMaximumFileBytes)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(cacheDirectory);
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maximumFileBytes);
        if (maximumFileBytes > int.MaxValue - 1)
            throw new ArgumentOutOfRangeException(nameof(maximumFileBytes));
        databasePath = Path.Combine(Path.GetFullPath(cacheDirectory), "file-content-v1.sqlite");
        MaximumFileBytes = maximumFileBytes;
    }

    public long MaximumFileBytes { get; }
    public FileContentIndexStatus Status => Volatile.Read(ref status);
    /// <summary>Raised on a worker thread, at most four times per second plus state transitions.</summary>
    public event EventHandler? Changed;

    public Task EnsureIndexAsync(IReadOnlyList<FileSearchEntry> entries, CancellationToken cancellationToken = default)
    {
        ArgumentNullException.ThrowIfNull(entries);
        lock (sync)
        {
            ObjectDisposedException.ThrowIf(disposed, this);
            if (isReconciling && indexingTask is not null)
            {
                pendingEntries = entries;
                return indexingTask.WaitAsync(cancellationToken);
            }
            indexingCancellation?.Dispose();
            indexingCancellation = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token, cancellationToken);
            var token = indexingCancellation.Token;
            pendingEntries = null;
            isReconciling = true;
            var generation = ++reconciliationGeneration;
            // Microsoft.Data.Sqlite's async methods perform synchronous I/O; keep it off the UI thread.
            indexingTask = Task.Run(() => ReconcilePending(entries, generation, token), CancellationToken.None);
            return indexingTask;
        }
    }

    public async Task StopAsync()
    {
        Task? pending;
        lock (sync)
        {
            indexingCancellation?.Cancel();
            pendingEntries = null;
            pending = indexingTask;
        }
        if (pending is not null)
        {
            try { await pending.ConfigureAwait(false); }
            catch (OperationCanceledException) { }
        }
    }

    public async Task<FileSearchResults> SearchAsync(string query, int offset = 0, int limit = 100,
        CancellationToken cancellationToken = default, Func<FileSearchEntry, bool>? entryFilter = null)
    {
        ObjectDisposedException.ThrowIf(disposed, this);
        ArgumentOutOfRangeException.ThrowIfNegative(offset);
        if (limit is < 1 or > 1000)
            throw new ArgumentOutOfRangeException(nameof(limit));
        using var linked = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token, cancellationToken);
        await searchGate.WaitAsync(linked.Token).ConfigureAwait(false);
        try
        {
            return await Task.Run(() => SearchCore(query, offset, limit, linked.Token, entryFilter), linked.Token).ConfigureAwait(false);
        }
        catch (SqliteException) when (linked.IsCancellationRequested)
        {
            throw new OperationCanceledException(linked.Token);
        }
        finally { searchGate.Release(); }
    }

    private void ReconcilePending(IReadOnlyList<FileSearchEntry> entries, int generation, CancellationToken token)
    {
        try
        {
            while (true)
            {
                Reconcile(entries, token);
                lock (sync)
                {
                    token.ThrowIfCancellationRequested();
                    if (pendingEntries is null)
                    {
                        isReconciling = false;
                        return;
                    }
                    entries = pendingEntries;
                    pendingEntries = null;
                }
            }
        }
        finally
        {
            lock (sync)
            {
                if (generation == reconciliationGeneration)
                {
                    pendingEntries = null;
                    isReconciling = false;
                }
            }
        }
    }

    private void Reconcile(IReadOnlyList<FileSearchEntry> entries, CancellationToken token)
    {
        SetStatus(Status with { IsIndexing = true, Error = null }, true);
        var indexed = 0;
        var skipped = 0;
        try
        {
            token.ThrowIfCancellationRequested();
            Directory.CreateDirectory(Path.GetDirectoryName(databasePath)!);
            using var connection = OpenConnection(false);
            // SqliteCommand.Cancel is a no-op. Native interrupt cooperates with long FTS operations.
            // Dispose the registration before its connection, preventing an interrupt/close race.
            using var interrupt = token.Register(static handle => raw.sqlite3_interrupt((sqlite3)handle!), connection.Handle);
            InitializeDatabase(connection);
            Volatile.Write(ref databaseReady, true);
            var existing = ReadMetadata(connection, token);
            var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            using var upsert = connection.CreateCommand();
            upsert.CommandText = """
                INSERT INTO files(path, length, mtime, body, was_skipped) VALUES($path, $length, $mtime, $body, $skipped)
                ON CONFLICT(path) DO UPDATE SET length=excluded.length, mtime=excluded.mtime,
                    body=excluded.body, was_skipped=excluded.was_skipped;
                """;
            upsert.Parameters.Add("$path", SqliteType.Text);
            upsert.Parameters.Add("$length", SqliteType.Integer);
            upsert.Parameters.Add("$mtime", SqliteType.Integer);
            upsert.Parameters.Add("$body", SqliteType.Text);
            upsert.Parameters.Add("$skipped", SqliteType.Integer);
            SqliteTransaction? transaction = null;
            var pendingWrites = 0;
            try
            {
                foreach (var entry in entries)
                {
                    token.ThrowIfCancellationRequested();
                    if (entry.IsDirectory)
                        continue;
                    if (!IsSupported(entry.FullPath))
                    {
                        skipped++;
                        continue;
                    }
                    if (!seen.Add(entry.FullPath))
                        continue;
                    FileInfo info;
                    try
                    {
                        info = new FileInfo(entry.FullPath);
                        if (!info.Exists)
                        {
                            // The name snapshot may be older than a deletion. Do not retain stale text.
                            seen.Remove(entry.FullPath);
                            skipped++;
                            continue;
                        }
                        if (existing.TryGetValue(entry.FullPath, out var cached) &&
                            cached.Length == info.Length && cached.ModifiedTicks == info.LastWriteTimeUtc.Ticks)
                        {
                            if (cached.Skipped) skipped++; else indexed++;
                            SetStatus(new(true, indexed, skipped));
                            continue;
                        }
                    }
                    catch (Exception error) when (error is IOException or UnauthorizedAccessException or ArgumentException)
                    {
                        seen.Remove(entry.FullPath);
                        skipped++;
                        continue;
                    }

                    string? body = null;
                    try
                    {
                        if (info.Length <= MaximumFileBytes &&
                            (info.Attributes & (FileAttributes.Offline | FileAttributes.ReparsePoint)) == 0)
                            body = ReadText(info, token);
                    }
                    catch (Exception error) when (error is IOException or UnauthorizedAccessException or DecoderFallbackException)
                    {
                        // Unreadable and non-text files remain metadata-only so unchanged files are not reread.
                    }
                    transaction ??= connection.BeginTransaction();
                    // SQLite NOCASE folds ASCII only, unlike Windows path identity. Remove the exact
                    // old spelling before a Unicode case-only rename can insert a second cached row.
                    if (existing.TryGetValue(entry.FullPath, out var oldMetadata) &&
                        !StringComparer.Ordinal.Equals(oldMetadata.Path, entry.FullPath))
                    {
                        using var removeOldSpelling = connection.CreateCommand();
                        removeOldSpelling.Transaction = transaction;
                        removeOldSpelling.CommandText = "DELETE FROM files WHERE path=$path";
                        removeOldSpelling.Parameters.AddWithValue("$path", oldMetadata.Path);
                        removeOldSpelling.ExecuteNonQuery();
                    }
                    upsert.Transaction = transaction;
                    upsert.Parameters["$path"].Value = entry.FullPath;
                    upsert.Parameters["$length"].Value = info.Length;
                    upsert.Parameters["$mtime"].Value = info.LastWriteTimeUtc.Ticks;
                    upsert.Parameters["$body"].Value = (object?)body ?? DBNull.Value;
                    upsert.Parameters["$skipped"].Value = body is null ? 1 : 0;
                    upsert.ExecuteNonQuery();
                    if (body is null) skipped++; else indexed++;
                    if (++pendingWrites >= 32)
                    {
                        transaction.Commit();
                        transaction.Dispose();
                        transaction = null;
                        upsert.Transaction = null;
                        pendingWrites = 0;
                    }
                    SetStatus(new(true, indexed, skipped));
                }
                transaction?.Commit();
            }
            finally { transaction?.Dispose(); }

            token.ThrowIfCancellationRequested();
            using (var remove = connection.CreateCommand())
            using (var deleteTransaction = connection.BeginTransaction())
            {
                remove.Transaction = deleteTransaction;
                remove.CommandText = "DELETE FROM files WHERE path=$path";
                remove.Parameters.Add("$path", SqliteType.Text);
                foreach (var path in existing.Keys)
                {
                    token.ThrowIfCancellationRequested();
                    if (seen.Contains(path)) continue;
                    remove.Parameters["$path"].Value = path;
                    remove.ExecuteNonQuery();
                }
                deleteTransaction.Commit();
            }
            SetStatus(new(false, indexed, skipped), true);
        }
        catch (OperationCanceledException)
        {
            SetStatus(Status with { IsIndexing = false }, true);
            throw;
        }
        catch (SqliteException) when (token.IsCancellationRequested)
        {
            SetStatus(Status with { IsIndexing = false }, true);
            throw new OperationCanceledException(token);
        }
        catch (Exception error) when (error is SqliteException or IOException or UnauthorizedAccessException)
        {
            SetStatus(new(false, indexed, skipped, error.Message), true);
        }
    }

    private FileSearchResults SearchCore(string text, int offset, int limit, CancellationToken token,
        Func<FileSearchEntry, bool>? entryFilter)
    {
        var stopwatch = Stopwatch.StartNew();
        var query = FileSearchQuery.Parse(text);
        if (query.IsEmpty || !query.HasTextTerms || query.Error is not null || !Volatile.Read(ref databaseReady))
            return new(Array.Empty<FileSearchMatch>(), 0, stopwatch.Elapsed);
        using var connection = OpenConnection(true);
        using var interrupt = token.Register(static handle => raw.sqlite3_interrupt((sqlite3)handle!), connection.Handle);
        using var command = connection.CreateCommand();
        // Literal fragments are necessary conditions, not a substitute for the shared wildcard matcher.
        var literals = query.RequiredLiterals.Where(value => value.EnumerateRunes().Take(3).Count() >= 3 &&
            !value.Any(char.IsControl)).Distinct(StringComparer.OrdinalIgnoreCase).Take(8).ToArray();
        if (literals.Length > 0)
        {
            command.CommandText = """
                SELECT files.path, files.body FROM files_fts JOIN files ON files.id=files_fts.rowid
                WHERE files_fts MATCH $match AND files.was_skipped=0 ORDER BY files.id;
                """;
            command.Parameters.AddWithValue("$match", string.Join(" AND ", literals.Select(value =>
                "\"" + value.Replace("\"", "\"\"") + "\"")));
        }
        else
        {
            // One/two-character and all-wildcard searches read the local cache, never original files.
            command.CommandText = "SELECT path, body FROM files WHERE was_skipped=0 ORDER BY id";
        }
        var matches = new List<FileSearchMatch>(limit);
        var total = 0;
        using var reader = command.ExecuteReader();
        while (reader.Read())
        {
            token.ThrowIfCancellationRequested();
            var entry = new FileSearchEntry(reader.GetString(0), false);
            if (entryFilter?.Invoke(entry) == false || !query.MatchesMetadata(entry)) continue;
            var body = reader.GetString(1);
            if (!query.MatchesContent(entry, body)) continue;
            if (total >= offset && matches.Count < limit)
                matches.Add(new(entry, 500, true, CreateSnippet(body, query.RequiredLiterals)));
            total++;
        }
        return new(matches.AsReadOnly(), total, stopwatch.Elapsed);
    }

    private SqliteConnection OpenConnection(bool readOnly)
    {
        var builder = new SqliteConnectionStringBuilder
        {
            DataSource = databasePath,
            Mode = readOnly ? SqliteOpenMode.ReadOnly : SqliteOpenMode.ReadWriteCreate,
            Cache = SqliteCacheMode.Private,
            Pooling = false,
            DefaultTimeout = 3
        };
        var connection = new SqliteConnection(builder.ToString());
        connection.Open();
        return connection;
    }

    private static void InitializeDatabase(SqliteConnection connection)
    {
        using var command = connection.CreateCommand();
        command.CommandText = """
            PRAGMA journal_mode=WAL;
            PRAGMA synchronous=NORMAL;
            PRAGMA cache_size=-8192;
            CREATE TABLE IF NOT EXISTS files (
                id INTEGER PRIMARY KEY, path TEXT NOT NULL COLLATE NOCASE UNIQUE,
                length INTEGER NOT NULL, mtime INTEGER NOT NULL, body TEXT, was_skipped INTEGER NOT NULL
            );
            CREATE VIRTUAL TABLE IF NOT EXISTS files_fts USING fts5(
                body, content='files', content_rowid='id', tokenize='trigram'
            );
            CREATE TRIGGER IF NOT EXISTS files_ai AFTER INSERT ON files WHEN new.was_skipped=0 BEGIN
                INSERT INTO files_fts(rowid, body) VALUES(new.id, new.body);
            END;
            CREATE TRIGGER IF NOT EXISTS files_ad AFTER DELETE ON files WHEN old.was_skipped=0 BEGIN
                INSERT INTO files_fts(files_fts, rowid, body) VALUES('delete', old.id, old.body);
            END;
            DROP TRIGGER IF EXISTS files_au_delete;
            DROP TRIGGER IF EXISTS files_au_insert;
            CREATE TRIGGER IF NOT EXISTS files_au AFTER UPDATE ON files BEGIN
                INSERT INTO files_fts(files_fts, rowid, body)
                    SELECT 'delete', old.id, old.body WHERE old.was_skipped=0;
                INSERT INTO files_fts(rowid, body)
                    SELECT new.id, new.body WHERE new.was_skipped=0;
            END;
            """;
        command.ExecuteNonQuery();
    }

    private static Dictionary<string, CachedMetadata> ReadMetadata(SqliteConnection connection, CancellationToken token)
    {
        using var command = connection.CreateCommand();
        command.CommandText = "SELECT path, length, mtime, was_skipped FROM files";
        using var reader = command.ExecuteReader();
        var result = new Dictionary<string, CachedMetadata>(StringComparer.OrdinalIgnoreCase);
        while (reader.Read())
        {
            token.ThrowIfCancellationRequested();
            var path = reader.GetString(0);
            result[path] = new(path, reader.GetInt64(1), reader.GetInt64(2), reader.GetInt32(3) != 0);
        }
        return result;
    }

    public static bool IsSupported(string path) =>
        TextExtensions.Contains(Path.GetExtension(path)) || TextFileNames.Contains(Path.GetFileName(path));

    private string? ReadText(FileInfo info, CancellationToken token)
    {
        using var stream = new FileStream(info.FullName, FileMode.Open, FileAccess.Read,
            FileShare.ReadWrite | FileShare.Delete, 64 * 1024, FileOptions.SequentialScan);
        var length = stream.Length;
        if (length > MaximumFileBytes) return null;
        var bytes = new byte[(int)length];
        var read = 0;
        while (read < bytes.Length)
        {
            token.ThrowIfCancellationRequested();
            var count = stream.Read(bytes, read, Math.Min(64 * 1024, bytes.Length - read));
            if (count == 0) break;
            read += count;
        }
        if (stream.ReadByte() != -1) return null;
        var span = bytes.AsSpan(0, read);
        string text;
        if (span.StartsWith(new byte[] { 0xff, 0xfe, 0, 0 }))
            text = new UTF32Encoding(false, false, true).GetString(span[4..]);
        else if (span.StartsWith(new byte[] { 0, 0, 0xfe, 0xff }))
            text = new UTF32Encoding(true, false, true).GetString(span[4..]);
        else if (span.StartsWith(new byte[] { 0xff, 0xfe }))
            text = new UnicodeEncoding(false, false, true).GetString(span[2..]);
        else if (span.StartsWith(new byte[] { 0xfe, 0xff }))
            text = new UnicodeEncoding(true, false, true).GetString(span[2..]);
        else
        {
            if (span.StartsWith(new byte[] { 0xef, 0xbb, 0xbf })) span = span[3..];
            text = new UTF8Encoding(false, true).GetString(span);
        }
        var controls = 0;
        foreach (var character in text)
        {
            if (character == '\0') return null;
            if (char.IsControl(character) && character is not ('\r' or '\n' or '\t' or '\f')) controls++;
        }
        return controls > Math.Max(2, text.Length / 100) ? null : text;
    }

    private static string CreateSnippet(string text, IReadOnlyList<string> literals)
    {
        var first = -1;
        foreach (var literal in literals)
        {
            var index = text.IndexOf(literal, StringComparison.OrdinalIgnoreCase);
            if (index >= 0 && (first < 0 || index < first)) first = index;
        }
        var start = Math.Max(0, first - 45);
        var length = Math.Min(180, text.Length - start);
        return (start > 0 ? "…" : "") + text.Substring(start, length).Replace('\r', ' ').Replace('\n', ' ').Replace('\t', ' ')
            + (start + length < text.Length ? "…" : "");
    }

    private void SetStatus(FileContentIndexStatus value, bool force = false)
    {
        Volatile.Write(ref status, value);
        var ticks = Stopwatch.GetTimestamp();
        if (!force && Stopwatch.GetElapsedTime(Volatile.Read(ref lastNotificationTicks), ticks) < TimeSpan.FromMilliseconds(250))
            return;
        Volatile.Write(ref lastNotificationTicks, ticks);
        Changed?.Invoke(this, EventArgs.Empty);
    }

    public async ValueTask DisposeAsync()
    {
        lock (sync)
        {
            if (disposed) return;
            disposed = true;
            lifetime.Cancel();
        }
        await StopAsync().ConfigureAwait(false);
        indexingCancellation?.Dispose();
        lifetime.Dispose();
        // Queries dispose their own connections. Do not dispose their semaphore while a finally may release it.
    }

    private readonly record struct CachedMetadata(string Path, long Length, long ModifiedTicks, bool Skipped);
}