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

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Diagnostics;
using XFEToolBox.Client.Core.Search;

namespace XFEToolBox.Indexing.Service.Engine;

/// <summary>
/// Independent read-only metadata service. One bounded native iterator feeds CPU-count name-index
/// shards; queries never perform disk enumeration and run on the caller's impersonated thread.
/// </summary>
public sealed class NtfsIndexEngine : IAsyncDisposable
{
    private const uint NameChangeReasons = 0x00000100 | 0x00000200 | 0x00001000 | 0x00002000 | 0x00010000 | 0x00100000;
    private readonly string dataDirectory;
    private readonly int parallelism;
    private readonly Func<NtfsVolume[]> volumeProvider;
    private readonly Func<NtfsVolume, INtfsMetadataSource> sourceFactory;
    private readonly NtfsAuditLog audit;
    private readonly CancellationTokenSource stop = new();
    private readonly SemaphoreSlim wake = new(0, 1);
    private readonly object lifecycleGate = new();
    private Task? worker;
    private VolumeState[] volumes = [];
    private EngineStatus status = new(false, 0, 0, 0, null);
    private int rebuildRequested;
    public event EventHandler? Changed;

    public NtfsIndexEngine(string dataDirectory, int maxParallelism = 0)
        : this(dataDirectory, maxParallelism, NtfsNativeVolume.GetVolumes, volume => new NtfsNativeVolume(volume)) { }

    internal NtfsIndexEngine(string dataDirectory, int maxParallelism, Func<NtfsVolume[]> volumeProvider,
        Func<NtfsVolume, INtfsMetadataSource> sourceFactory)
    {
        this.dataDirectory = Path.GetFullPath(dataDirectory);
        parallelism = maxParallelism > 0 ? maxParallelism : Math.Max(1, Environment.ProcessorCount);
        this.volumeProvider = volumeProvider;
        this.sourceFactory = sourceFactory;
        audit = new(this.dataDirectory);
    }

    public Task StartAsync(CancellationToken cancellationToken = default)
    {
        cancellationToken.ThrowIfCancellationRequested();
        lock (lifecycleGate)
        {
            ObjectDisposedException.ThrowIf(stop.IsCancellationRequested, this);
            worker ??= Task.Factory.StartNew(Run, stop.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }
        return Task.CompletedTask;
    }

    public EngineStatus GetStatus()
    {
        var snapshot = Volatile.Read(ref status);
        var liveVolumes = Volatile.Read(ref volumes);
        var snapshots = snapshot.VolumeStatuses.Select(volume =>
        {
            var live = liveVolumes.FirstOrDefault(state => state.Volume.Root == volume.Root);
            return live is null ? volume : volume with
            {
                IndexedFiles = Volatile.Read(ref live.Shards).Sum(shard => shard.Count)
            };
        }).ToArray();
        return snapshot with { IndexedFiles = snapshots.Sum(volume => volume.IndexedFiles), VolumeStatuses = snapshots };
    }

    public Task RebuildAsync(CancellationToken cancellationToken = default)
    {
        cancellationToken.ThrowIfCancellationRequested();
        Interlocked.Exchange(ref rebuildRequested, 1);
        // Count is checked under the same lifecycle gate as every release: no SemaphoreFullException.
        lock (lifecycleGate)
            if (!stop.IsCancellationRequested && wake.CurrentCount == 0)
                wake.Release();
        return Task.CompletedTask;
    }

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

    public FileSearchResults? TrySearch(string query, int offset, int limit, CancellationToken cancellationToken = default,
        Func<FileSearchEntry, bool>? filter = null)
    {
        var elapsed = Stopwatch.StartNew();
        if (cancellationToken.IsCancellationRequested) return null;
        offset = Math.Max(0, offset);
        limit = Math.Clamp(limit, 1, 10001);
        var window = checked(Math.Min(offset, 100_000) + limit);
        var results = new List<FileSearchMatch>();
        var total = 0;
        foreach (var volume in Volatile.Read(ref volumes))
        foreach (var shard in Volatile.Read(ref volume.Shards))
        {
            if (cancellationToken.IsCancellationRequested) return null;
            // Deliberately synchronous: host ACL predicates run inside NamedPipe.RunAsClient.
            var matches = shard.TrySearch(query, 0, window, cancellationToken, filter);
            if (matches is null) return null;
            total += matches.TotalMatches;
            results.AddRange(matches.Items);
        }
        var selected = results.OrderBy(match => match.Score)
            .ThenBy(match => match.Entry.FullPath, StringComparer.OrdinalIgnoreCase).Skip(offset).Take(limit).ToArray();
        return new(selected, total, elapsed.Elapsed);
    }

    private void Run()
    {
        Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
        var token = stop.Token;
        try
        {
            Directory.CreateDirectory(dataDirectory);
            Audit(null, "service-start");
            Volatile.Write(ref volumes, volumeProvider().Select(volume => new VolumeState(volume)).ToArray());
            PublishStatus();
            // Only one volume builds at once: the global CPU budget is not multiplied by disk count.
            foreach (var volume in volumes)
            {
                token.ThrowIfCancellationRequested();
                RunVolume(volume, () => InitializeVolume(volume, force: false, token), token);
            }
            var lastVolumeDiscovery = Stopwatch.GetTimestamp();
            while (!token.IsCancellationRequested)
            {
                var rebuild = Interlocked.Exchange(ref rebuildRequested, 0) != 0;
                foreach (var volume in volumes)
                {
                    token.ThrowIfCancellationRequested();
                    if (rebuild)
                        RunVolume(volume, () => InitializeVolume(volume, force: true, token), token);
                    else if (volume.Native is not null && volume.Catalog is not null && volume.Error is null)
                        RunVolume(volume, () => RefreshVolume(volume, token), token);
                }
                if (Stopwatch.GetElapsedTime(lastVolumeDiscovery) > TimeSpan.FromMinutes(1))
                {
                    RefreshMountedVolumes(token);
                    lastVolumeDiscovery = Stopwatch.GetTimestamp();
                }
                wake.Wait(TimeSpan.FromSeconds(1), token);
            }
        }
        catch (OperationCanceledException) when (token.IsCancellationRequested) { }
        catch (Exception exception)
        {
            Volatile.Write(ref status, GetStatus() with { IsIndexing = false, Error = exception.Message });
            Audit(null, "service-error");
        }
        finally
        {
            Audit(null, "service-stop");
            foreach (var volume in volumes)
            {
                // A previous atomic checkpoint plus journal replay is sufficient after cancellation.
                // Do not perform a multi-million-node disk save while the service is stopping.
                volume.Native?.Dispose();
            }
        }
    }

    private void RefreshMountedVolumes(CancellationToken token)
    {
        var current = volumeProvider();
        var existing = volumes.ToDictionary(state => state.Volume.VolumeId, StringComparer.OrdinalIgnoreCase);
        var active = current.Select(volume => existing.TryGetValue(volume.VolumeId, out var state)
                && state.Volume == volume ? state : new VolumeState(volume)).ToArray();
        foreach (var removed in volumes.Except(active))
            removed.Native?.Dispose();
        Volatile.Write(ref volumes, active);
        PublishStatus();
        foreach (var volume in active)
        {
            token.ThrowIfCancellationRequested();
            if (volume.Native is null || volume.Error is not null)
                RunVolume(volume, () => InitializeVolume(volume, force: false, token), token);
        }
    }

    private void RunVolume(VolumeState volume, Action action, CancellationToken token)
    {
        try { action(); }
        catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
        catch (Exception exception) when (exception is IOException or InvalidDataException or UnauthorizedAccessException)
        {
            // A damaged metadata/cache stream on one volume must not stop every other volume's
            // journal listener. Retry this volume after mount discovery's bounded one-minute delay.
            volume.Error = exception.Message;
            volume.Phase = "普通扫描回退";
            Audit(volume, "volume-error");
            PublishStatus();
        }
    }

    private void InitializeVolume(VolumeState state, bool force, CancellationToken token)
    {
        var initializationStarted = Stopwatch.GetTimestamp();
        state.Native?.Dispose();
        state.Native = sourceFactory(state.Volume);
        state.Error = null;
        state.Phase = "恢复检查点";
        PublishStatus();
        if (!state.Native.IsOpen || !state.Native.TryGetJournal(out var journal, out state.Error))
        {
            state.Error ??= state.Native.OpenError;
            state.Phase = "普通扫描回退";
            Audit(state, "volume-unavailable");
            PublishStatus();
            return;
        }
        var cachePath = NtfsCatalog.GetCachePath(dataDirectory, state.Volume);
        var restoreStarted = Stopwatch.GetTimestamp();
        var catalog = force ? null : NtfsCatalog.TryLoad(cachePath, state.Volume, journal);
        var restored = catalog is not null;
        if (restored)
        {
            state.MetadataCount = catalog!.Nodes.Count;
            state.Catalog = catalog;
            Audit(state, "cache-restored", Stopwatch.GetElapsedTime(restoreStarted).TotalMilliseconds,
                cacheRestored: true);
        }
        if (catalog is null)
        {
            state.Phase = "批量读取 MFT 名称";
            PublishStatus();
            catalog = new NtfsCatalog { JournalId = journal.Id, NextUsn = journal.NextUsn };
            state.MftEnumerations++;
            var enumerationStarted = Stopwatch.GetTimestamp();
            Audit(state, "mft-start", startUsn: journal.NextUsn, nextUsn: journal.NextUsn, journalId: journal.Id,
                cacheRestored: false);
            if (!state.Native.TryEnumerate(nodes =>
                {
                    foreach (var node in nodes)
                        catalog.Nodes[node.FileId] = node;
                    state.MetadataCount = catalog.Nodes.Count;
                    PublishStatus();
                }, token, out state.Error))
            {
                state.Phase = "普通扫描回退";
                Audit(state, "volume-unavailable");
                PublishStatus();
                return;
            }
            Audit(state, "mft-enumerated", Stopwatch.GetElapsedTime(enumerationStarted).TotalMilliseconds,
                startUsn: journal.NextUsn, nextUsn: journal.NextUsn, journalId: journal.Id, cacheRestored: false);
        }
        state.Catalog = catalog;
        state.MetadataCount = catalog.Nodes.Count;
        state.Phase = "多核建立搜索分片";
        PublishStatus();
        BuildShards(state, token);
        // Replay from the journal position captured BEFORE MFT enumeration. This closes scan races.
        if (!ReplayChanges(state, token, out var rebuildRequired))
        {
            state.Phase = "等待日志恢复";
            PublishStatus();
            if (rebuildRequired && !force)
                InitializeVolume(state, force: true, token);
            return;
        }
        catalog.SaveAtomic(cachePath, state.Volume, token);
        Audit(state, "checkpoint-saved");
        state.LastCheckpoint = Stopwatch.GetTimestamp();
        state.Phase = "USN 增量监听";
        Audit(state, "volume-ready", Stopwatch.GetElapsedTime(initializationStarted).TotalMilliseconds,
            cacheRestored: restored);
        PublishStatus();
    }

    private void BuildShards(VolumeState state, CancellationToken token)
    {
        var buildStarted = Stopwatch.GetTimestamp();
        var catalog = state.Catalog!;
        var directories = catalog.ResolveDirectories(state.Volume.Root, token);
        var buckets = new List<NtfsNode>[parallelism];
        var shards = new FileSearchIndex[parallelism];
        for (var index = 0; index < parallelism; index++)
        {
            buckets[index] = [];
            shards[index] = new();
        }
        foreach (var node in catalog.Nodes.Values)
            buckets[ShardFor(node.FileId)].Add(node);
        if (state.Shards.Length == 0)
            Volatile.Write(ref state.Shards, shards); // First build becomes searchable batch by batch.
        var tasks = Enumerable.Range(0, parallelism).Select(shard => Task.Factory.StartNew(() =>
        {
            Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
            var batch = new List<FileSearchEntry>(256);
            foreach (var node in buckets[shard])
            {
                token.ThrowIfCancellationRequested();
                foreach (var entry in NtfsCatalog.GetEntries(node, state.Volume.Root, directories))
                {
                    batch.Add(entry);
                    if (batch.Count < 256)
                        continue;
                    shards[shard].AddOrUpdate(batch);
                    batch.Clear();
                }
            }
            if (batch.Count > 0)
                shards[shard].AddOrUpdate(batch);
        }, token, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray();
        Task.WhenAll(tasks).GetAwaiter().GetResult();
        state.Directories = directories;
        Volatile.Write(ref state.Shards, shards); // Rebuild replaces old live shards atomically.
        Audit(state, "shards-built", Stopwatch.GetElapsedTime(buildStarted).TotalMilliseconds);
    }

    private void RefreshVolume(VolumeState state, CancellationToken token)
    {
        if (!ReplayChanges(state, token, out var rebuildRequired))
        {
            PublishStatus();
            if (rebuildRequired)
                InitializeVolume(state, force: true, token);
            return;
        }
        if (state.Dirty && Stopwatch.GetElapsedTime(state.LastCheckpoint) > TimeSpan.FromSeconds(30))
        {
            state.Catalog!.SaveAtomic(NtfsCatalog.GetCachePath(dataDirectory, state.Volume), state.Volume, token);
            Audit(state, "checkpoint-saved");
            state.LastCheckpoint = Stopwatch.GetTimestamp();
            state.Dirty = false;
        }
        PublishStatus();
    }

    private bool ReplayChanges(VolumeState state, CancellationToken token, out bool rebuildRequired)
    {
        rebuildRequired = false;
        var native = state.Native!;
        var catalog = state.Catalog!;
        var replayStarted = Stopwatch.GetTimestamp();
        var replayStartUsn = catalog.NextUsn;
        if (!native.TryGetJournal(out var journal, out state.Error))
            return false;
        if (!journal.CanResume(catalog.JournalId, catalog.NextUsn))
        {
            state.Error = "USN 日志检查点已失效,重新读取本卷 MFT。";
            rebuildRequired = true;
            return false;
        }
        var changed = new HashSet<ulong>();
        var next = catalog.NextUsn;
        while (next < journal.NextUsn)
        {
            token.ThrowIfCancellationRequested();
            if (!native.TryReadChanges(journal, next, out var readNext, out var changes, out state.Error))
            {
                rebuildRequired = true;
                return false;
            }
            if (readNext <= next)
            {
                state.Error = "USN 日志游标没有前进,保留旧检查点等待重试。";
                return false;
            }
            foreach (var change in changes)
                if ((change.Reason & NameChangeReasons) != 0)
                    changed.Add(change.FileId);
            next = readNext;
        }
        if (changed.Count > 0)
        {
            var refreshed = new Dictionary<ulong, NtfsNode>();
            foreach (var group in changed.Order().Chunk(128))
                if (!native.TryReadNodes(group, nodes =>
                    {
                        foreach (var node in nodes)
                            refreshed[node.FileId] = node;
                    }, token, out state.Error))
                    return false;
            var affected = catalog.GetDescendants(changed, token);
            var removedPaths = affected.Where(catalog.Nodes.ContainsKey).ToDictionary(id => id,
                id => NtfsCatalog.GetEntries(catalog.Nodes[id], state.Volume.Root, state.Directories)
                    .Select(entry => entry.FullPath).ToArray());
            foreach (var id in changed)
                catalog.UpdateNode(id, refreshed.GetValueOrDefault(id));
            affected.UnionWith(catalog.GetDescendants(changed, token));
            foreach (var id in affected)
                state.Directories.Remove(id);
            catalog.ResolveDirectories(state.Volume.Root, token, state.Directories, affected);
            // A newly created directory or a rename touches only that subtree, never all volume
            // postings. Hardlinks may contribute multiple old and new names for the same FRN.
            state.Phase = "更新目录路径";
            PublishStatus();
            foreach (var group in affected.GroupBy(ShardFor))
            {
                var shard = state.Shards[group.Key];
                shard.RemovePaths(group.Where(removedPaths.ContainsKey).SelectMany(id => removedPaths[id]), token);
                shard.AddOrUpdate(group.Where(catalog.Nodes.ContainsKey).SelectMany(id =>
                    NtfsCatalog.GetEntries(catalog.Nodes[id], state.Volume.Root, state.Directories)));
            }
            state.MetadataCount = catalog.Nodes.Count;
        }
        state.Dirty |= next != catalog.NextUsn;
        // The sole writer advances only after every affected node and search shard is updated.
        catalog.NextUsn = next;
        catalog.JournalId = journal.Id;
        state.Phase = "USN 增量监听";
        // Content-only journal movement includes this log's own append. Do not create an idle
        // audit->USN->audit feedback loop; ready/checkpoint records still report the current cursor.
        if (changed.Count > 0)
            Audit(state, "usn-replayed", Stopwatch.GetElapsedTime(replayStarted).TotalMilliseconds,
                startUsn: replayStartUsn, nextUsn: next);
        return true;
    }

    private void Audit(VolumeState? state, string phase, double elapsedMs = 0, long? startUsn = null,
        long? nextUsn = null, ulong? journalId = null, bool? cacheRestored = null)
    {
        audit.Write(phase, state is null ? null : NtfsAuditLog.PublicVolumeIdentity(state.Volume),
            state?.MftEnumerations ?? volumes.Sum(volume => volume.MftEnumerations),
            state?.MetadataCount ?? volumes.Sum(volume => volume.MetadataCount),
            state is null ? volumes.Sum(volume => volume.Shards.Sum(shard => shard.Count))
                : state.Shards.Sum(shard => shard.Count),
            journalId ?? state?.Catalog?.JournalId ?? 0, startUsn ?? state?.Catalog?.NextUsn ?? 0,
            nextUsn ?? state?.Catalog?.NextUsn ?? 0, parallelism, elapsedMs, cacheRestored);
    }

    private int ShardFor(ulong id) => (int)((id ^ (id >> 32)) % (uint)parallelism);

    private void PublishStatus()
    {
        var snapshots = volumes.Select(volume => new VolumeIndexStatus(volume.Volume.Root, volume.Phase,
            volume.Shards.Sum(shard => shard.Count), volume.Catalog?.JournalId ?? 0, volume.Catalog?.NextUsn ?? 0,
            volume.Error)).ToArray();
        var errors = snapshots.Where(volume => volume.Error is not null).Select(volume => volume.Root + volume.Error).ToArray();
        Volatile.Write(ref status, new(snapshots.Any(volume => volume.Phase is "恢复检查点" or "批量读取 MFT 名称"
                    or "多核建立搜索分片" or "更新目录路径"), snapshots.Sum(volume => volume.IndexedFiles), snapshots.Length,
            snapshots.Count(volume => volume.Phase == "USN 增量监听"),
            errors.Length == 0 ? null : string.Join(";", errors))
        {
            VolumeStatuses = snapshots,
            IndexedRoots = snapshots.Where(volume => volume.Error is null && volume.Phase != "普通扫描回退")
                .Select(volume => volume.Root).ToArray(),
            UnavailableRoots = snapshots.Where(volume => volume.Error is not null || volume.Phase == "普通扫描回退")
                .Select(volume => volume.Root).ToArray()
        });
        Changed?.Invoke(this, EventArgs.Empty);
    }

    public async ValueTask DisposeAsync()
    {
        Task? running;
        lock (lifecycleGate)
        {
            if (stop.IsCancellationRequested)
                return;
            stop.Cancel();
            running = worker;
        }
        if (running is not null)
            await running.ConfigureAwait(false);
        wake.Dispose();
        stop.Dispose();
    }

    private sealed class VolumeState(NtfsVolume volume)
    {
        public NtfsVolume Volume { get; } = volume;
        public INtfsMetadataSource? Native;
        public NtfsCatalog? Catalog;
        public FileSearchIndex[] Shards = [];
        public Dictionary<ulong, string> Directories = [];
        public string Phase = "等待建立索引";
        public string? Error;
        public int MetadataCount;
        public int MftEnumerations;
        public long LastCheckpoint;
        public bool Dirty;
    }
}